Blob = function (list, opt) {
/*
* this function will emulate in node, browser's Blob class
* https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
*/
this.buf = local.bufferConcat(list.map(function (elem) {
if (
typeof elem === "string"
|| Object.prototype.toString.call(elem) === "[object Uint8Array]"
) {
return elem;
}
// emulate in node, browser-behavior - auto-stringify arbitrary data
return String(elem);
}));
this.type = (opt && opt.type) || "";
}...
// run shared js-env code - function
(function () {
local.testCase_FormData_default = function (opt, onError) {
/*
* this function will test FormData's default handling-behavior
*/
opt = {};
opt.blob1 = new local.Blob([
"aa", "bb", local.stringHelloEmoji, 0
]);
opt.blob2 = new local.Blob([
"aa", "bb", local.stringHelloEmoji, 0
], {
type: "text/plain; charset=utf-8"
});
...FormData = function () {
/*
* this function will create a serverLocal-compatible FormData instance
* The FormData(form) constructor must run these steps:
* 1. Let fd be a new FormData object.
* 2. If form is given, set fd's entries to the result
* of constructing the form data set for form. (not implemented)
* 3. Return fd.
* https://xhr.spec.whatwg.org/#dom-formdata
*/
this.entryList = [];
}...
parameters: that.parameters,
swaggerJson: local.swaggerJson
})[0];
// init default
local.objectSetDefault(opt, {
inForm: (
that._consumes0 === "multipart/form-data"
? new local.FormData()
: ""
),
inHeader: {},
inPath: that._path.replace((
/#.*?$/
), ""),
inQuery: "",
...function Module(id = '', parent) {
this.id = id;
this.path = path.dirname(id);
this.exports = {};
this.parent = parent;
updateChildren(parent, this, false);
this.filename = null;
this.loaded = false;
this.children = [];
}...
// init example.js
tmp = local.path.resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
);
..._testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
let require2;
require2 = function (file) {
/*
* this function will require <file> in sandbox-env
*/
let exports;
let mockDict;
let mockList;
mockList = [
[
globalThis, {
setImmediate: local.nop,
setInterval: local.nop,
setTimeout: local.nop
}
]
];
[
[
local, "child_process"
], [
local, "cluster"
], [
local, "http"
], [
local, "https"
], [
local, "net"
], [
local, "repl"
], [
local.events, "prototype"
], [
globalThis, "process"
], [
local.stream, "prototype"
], [
process, "stdin"
]
].forEach(function (elem, tmp) {
tmp = elem[0][elem[1]];
mockDict = {};
Object.keys(tmp).forEach(function (key) {
if (typeof tmp[key] === "function" && !(
/^(?:fs\.Read|fs\.read|process\.binding|process\.dlopen)/
).test(elem[1] + "." + key)) {
mockDict[key] = function () {
return;
};
}
});
mockList.push([
tmp, mockDict
]);
});
local.testMock(mockList, function (onError) {
local.tryCatchOnError(function () {
exports = require(file);
}, local.onErrorDefault);
onError();
}, local.onErrorThrow);
return exports;
};
if (
local.isBrowser
|| local.env.npm_config_mode_coverage
|| local.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
) {
onError(undefined, opt);
return;
}
// save apidoc.html
local.fsWriteFileWithMkdirpSync(
"tmp/build/apidoc.html",
local.apidocCreate(local.objectAssignDefault(opt, {
blacklistDict: local,
require: require2
})),
"wrote file apidoc - {{pathname}}"
);
onError();
}...
onError(undefined, opt);
};
local.testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
local._testCase_buildApidoc_default({
blacklistDict: {}
}, onError, opt);
};
local.testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
..._testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
globalThis.local.testCase_buildReadme_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildLib_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildTest_default(opt, local.onErrorThrow);
local.buildApp(opt, onError);
}...
testCase_buildReadme_default: local.nop,
testCase_buildLib_default: local.nop,
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default({}, local.nop);
local._testCase_buildApp_default({}, local.nop);
local._testCase_buildLib_default({}, local.nop);
local._testCase_buildReadme_default({}, local.nop);
local._testCase_buildTest_default({}, local.nop);
local._testCase_webpage_default({}, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default({}, local.nop);
onError(undefined, opt);
..._testCase_buildLib_default = function (opt, onError) {
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
return local.buildLib({}, onError);
}...
testCase_buildLib_default: local.nop,
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default({}, local.nop);
local._testCase_buildApp_default({}, local.nop);
local._testCase_buildLib_default({}, local.nop);
local._testCase_buildReadme_default({}, local.nop);
local._testCase_buildTest_default({}, local.nop);
local._testCase_webpage_default({}, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default({}, local.nop);
onError(undefined, opt);
}, onError);
..._testCase_buildReadme_default = function (opt, onError) {
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
return local.buildReadme({}, onError);
}...
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default({}, local.nop);
local._testCase_buildApp_default({}, local.nop);
local._testCase_buildLib_default({}, local.nop);
local._testCase_buildReadme_default({}, local.nop);
local._testCase_buildTest_default({}, local.nop);
local._testCase_webpage_default({}, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default({}, local.nop);
onError(undefined, opt);
}, onError);
};
..._testCase_buildTest_default = function (opt, onError) {
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
return local.buildTest({}, onError);
}...
}
]
], function (onError) {
local._testCase_buildApidoc_default({}, local.nop);
local._testCase_buildApp_default({}, local.nop);
local._testCase_buildLib_default({}, local.nop);
local._testCase_buildReadme_default({}, local.nop);
local._testCase_buildTest_default({}, local.nop);
local._testCase_webpage_default({}, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default({}, local.nop);
onError(undefined, opt);
}, onError);
};
..._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
local.domStyleValidate();
local.browserTest({
fileScreenshot: (
local.env.npm_config_dir_build
+ "/screenshot." + local.env.MODE_BUILD + ".browser.%2F.png"
),
url: (
local.serverLocalHost
+ "/?modeTest=1&timeoutDefault=" + local.timeoutDefault
+ "&modeTestCase=" + local.modeTestCase.replace((
/_?testCase_webpage_default/
), "")
)
}, onError);
}...
]
], function (onError) {
local._testCase_buildApidoc_default({}, local.nop);
local._testCase_buildApp_default({}, local.nop);
local._testCase_buildLib_default({}, local.nop);
local._testCase_buildReadme_default({}, local.nop);
local._testCase_buildTest_default({}, local.nop);
local._testCase_webpage_default({}, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default({}, local.nop);
onError(undefined, opt);
}, onError);
};
local.testCase_childProcessSpawnWithTimeout_default = function (
...ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example use:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
});
*/
let ajaxProgressUpdate;
let bufferValidateAndCoerce;
let isDone;
let local2;
let onError2;
let onEvent;
let stack;
let streamCleanup;
let timeout;
let tmp;
let xhr;
let xhrInit;
// init local2
local2 = opt.local2 || local.utility2 || {};
// init function
ajaxProgressUpdate = local2.ajaxProgressUpdate || function () {
return;
};
bufferValidateAndCoerce = local2.bufferValidateAndCoerce || function (
buf,
mode
) {
/*
* this function will validate and coerce/convert
* <buf> to Buffer/Uint8Array, or String if <mode> = "string"
*/
// coerce ArrayBuffer to Buffer
if (Object.prototype.toString.call(buf) === "[object ArrayBuffer]") {
buf = new Uint8Array(buf);
}
// convert Buffer to utf8
if (mode === "string" && typeof buf !== "string") {
buf = String(buf);
}
return buf;
};
onEvent = function (evt) {
/*
* this function will handle events
*/
if (Object.prototype.toString.call(evt) === "[object Error]") {
xhr.err = xhr.err || evt;
xhr.onEvent({
type: "error"
});
return;
}
// init statusCode
xhr.statusCode = (xhr.statusCode || xhr.status) | 0;
switch (evt.type) {
case "abort":
case "error":
case "load":
if (isDone) {
return;
}
isDone = true;
// decrement cnt
ajaxProgressUpdate.cnt = Math.max(
ajaxProgressUpdate.cnt - 1,
0
);
ajaxProgressUpdate();
// handle abort or err event
switch (!xhr.err && evt.type) {
case "abort":
case "error":
xhr.err = new Error("ajax - event " + evt.type);
break;
case "load":
if (xhr.statusCode >= 400) {
xhr.err = new Error(
"ajax - statusCode " + xhr.statusCode
);
}
break;
}
// debug statusCode / method / url
if (xhr.err) {
xhr.statusCode = xhr.statusCode || 500;
xhr.err.statusCode = xhr.statusCode;
tmp = (
(
local.isBrowser
? "browser"
: "node"
)
+ " - " + xhr.statusCode + " " + xhr.method + " " + xhr.url
+ "\n"
);
xhr.err.message = tmp + xhr.err.message;
xhr.err.stack = tmp + xhr.err.stack;
}
// update resHeaders
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
if (xhr.getAllResponseHeaders) {
xhr.getAllResponseHeaders().replace((
/(.*?):\u0020*(.*?)\r\n/g
), function (ignore, key, val) {
xhr.resHeaders[key.toLowerCase()] = val;
});
}
// debug ajaxResponse
xhr.resContentLength = (......
/* validateLineSortedReset */
local.ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example use:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
...ajaxProgressUpdate = function () {
return;
}...
) {
return;
}
// test-run
globalThis.utility2_modeTest += 1;
}
// visual notification - testRun
local.ajaxProgressUpdate();
// mock console.error
consoleError = console.error;
isCoverage = (
typeof globalThis.__coverage__ === "object" && globalThis.__coverage__
&& Object.keys(globalThis.__coverage__).length
);
console.error = function (...argList) {
...apidocCreate = function (opt) {
/*
* this function will create the apidoc from <opt>.dir
*/
let elemCreate;
let module;
let moduleMain;
let readExample;
let tmp;
let toString;
let trimStart;
elemCreate = function (module, prefix, key) {
/*
* this function will create the apidoc-elem in given <module>
*/
let elem;
if (opt.modeNoApidoc) {
return elem;
}
elem = {};
elem.moduleName = prefix.split(".");
// handle case where module is a function
if (elem.moduleName.slice(-1)[0] === key) {
elem.moduleName.pop();
}
elem.moduleName = elem.moduleName.join(".");
elem.id = encodeURIComponent("apidoc.elem." + prefix + "." + key);
elem.typeof = typeof module[key];
elem.name = (
elem.typeof + " <span class=\"apidocSignatureSpan\">"
+ elem.moduleName + ".</span>" + key
);
// handle case where module is a function
elem.name = elem.name.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimStart(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
), "").replace((
/,/g
), ", ").replace((
/\s+/g
), " ");
return elem.signature;
}).replace((
/(\u0020*?\/\*[\S\s]*?\*\/\n)/
), "<span class=\"apidocCodeCommentSpan\">$1</span>").replace((
/^function\u0020\(/
), key + " = function (");
// init example
opt.exampleList.some(function (example) {
example.replace(
new RegExp("((?:\n.*?){8}\\.)(" + key + ")(\\((?:.*?\n){8})"),
function (ignore, match1, match2, match3) {
elem.example = "..." + trimStart(
local.stringHtmlSafe(match1)
+ "<span class=\"apidocCodeKeywordSpan\">"
+ local.stringHtmlSafe(match2)
+ "</span>"
+ local.stringHtmlSafe(match3)
).trimEnd() + "\n...";
return "";
}
);
return elem.example;
});
elem.example = elem.example || "n/a";
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
let result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
+ "\n\n\n\n\n\n\n\n"
).replace((
/\r\n*/g
), "\n");
}, console.error);
return result;
};
toString = function (value) {
/*
* this function will try to return the string form of the value
*/
let result;
local.tryCatchOnError(function () {
result = "";
result = String(value);
}, console.error);
return result;
};
trimStart = function (str) {
/*......
local.cliDict._default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
...function ok(...args) {
innerOk(ok, args.length, ...args);
}...
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
...assertJsonEqual = function (aa, bb, message) {
/*
* this function will assert jsonStringifyOrdered(<aa>) === JSON.stringify(<bb>)
*/
aa = local.jsonStringifyOrdered(aa);
bb = JSON.stringify(bb);
local.assertOrThrow(aa === bb, message || [
aa, bb
]);
}...
// test http GET handling-behavior
local.ajax({
url: "assets.hello.txt"
}, opt.gotoNext);
break;
case 2:
// validate responseText
local.assertJsonEqual(data.responseText, local.stringHelloEmoji);
// test http GET 304 cache handling-behavior
local.ajax({
headers: {
"If-Modified-Since": (
new Date(Date.now() + 0xffff).toUTCString()
)
},
...assertJsonNotEqual = function (aa, bb, message) {
/*
* this function will assert jsonStringifyOrdered(<aa>) !== JSON.stringify(<bb>)
*/
aa = local.jsonStringifyOrdered(aa);
bb = JSON.stringify(bb);
local.assertOrThrow(aa !== bb, [
aa
], message || aa);
}...
"", 0, false, null, undefined
].forEach(function (bb, jj) {
if (ii === jj) {
// test assertJsonEqual's handling-behavior
local.assertJsonEqual(aa, bb);
} else {
// test assertJsonNotEqual's handling-behavior
local.assertJsonNotEqual(aa, bb);
}
});
});
onError(undefined, opt);
};
local.testCase_base64Xxx_default = function (opt, onError) {
...assertOrThrow = function (passed, msg) {
/*
* this function will throw err.<msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is a string, then leave as is
? msg
// else JSON.stringify msg
: JSON.stringify(msg, undefined, 4)
)
);
}...
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...base64FromBuffer = function (buf) {
/*
* this function will convert Uint8Array <buf> to base64 str
*/
let ii;
let mod3;
let str;
let uint24;
let uint6ToB64;
// convert utf8 to Uint8Array
if (typeof buf === "string") {
buf = new TextEncoder().encode(buf);
}
buf = buf || [];
str = "";
uint24 = 0;
uint6ToB64 = function (uint6) {
return (
uint6 < 26
? uint6 + 65
: uint6 < 52
? uint6 + 71
: uint6 < 62
? uint6 - 4
: uint6 === 62
? 43
: 47
);
};
ii = 0;
while (ii < buf.length) {
mod3 = ii % 3;
uint24 |= buf[ii] << (16 >>> mod3 & 24);
if (mod3 === 2 || buf.length - ii === 1) {
str += String.fromCharCode(
uint6ToB64(uint24 >>> 18 & 63),
uint6ToB64(uint24 >>> 12 & 63),
uint6ToB64(uint24 >>> 6 & 63),
uint6ToB64(uint24 & 63)
);
uint24 = 0;
}
ii += 1;
}
return str.replace((
/A(?=A$|$)/gm
), "");
}...
? "abcd1234"
: Number(
(1 + Math.random()) * 0x10000000000000
).toString(36).slice(1)
);
switch (schemaP.format) {
case "byte":
value = local.base64FromBuffer(value);
break;
case "date":
case "date-time":
value = new Date().toISOString();
break;
case "email":
value = value + "@example.com";
...base64ToBuffer = function (str) {
/*
* this function will convert base64 <str> to Uint8Array
* https://gist.github.com/wang-bin/7332335
*/
let buf;
let byte;
let chr;
let ii;
let jj;
let map64;
let mod4;
str = str || "";
buf = new Uint8Array(str.length); // 3/4
byte = 0;
jj = 0;
map64 = (
!(str.indexOf("-") < 0 && str.indexOf("_") < 0)
// base64url
? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
// base64
: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
);
mod4 = 0;
ii = 0;
while (ii < str.length) {
chr = map64.indexOf(str[ii]);
if (chr !== -1) {
mod4 %= 4;
if (mod4 === 0) {
byte = chr;
} else {
byte = byte * 64 + chr;
buf[jj] = 255 & (byte >> ((-2 * (mod4 + 1)) & 6));
jj += 1;
}
mod4 += 1;
}
ii += 1;
}
// optimization - create resized-view of buf
return buf.subarray(0, jj);
}...
if (!data) {
local.serverRespondDefault(req, res, 404);
return;
}
local.serverRespondHeadSet(req, res, null, {
"Content-Type": data.fileContentType
});
res.end(local.base64ToBuffer(data.fileBlob));
break;
case "userLogout":
opt.gotoNext();
break;
default:
opt.gotoNext(null, data, meta);
}
...base64ToUtf8 = function (str) {
/*
* this function will convert base64 <str> to utf8 str
*/
return local.bufferValidateAndCoerce(local.base64ToBuffer(str), "string");
}...
opt = {};
opt.base64 = local.base64FromBuffer(
local.stringCharsetAscii + local.stringHelloEmoji
);
// test null-case handling-behavior
local.assertJsonEqual(local.base64FromBuffer(), "");
local.assertJsonEqual(local.bufferToUtf8(local.base64ToBuffer()), "");
local.assertJsonEqual(local.base64ToUtf8(), "");
local.assertJsonEqual(local.base64FromBuffer(local.base64ToBuffer()), "");
local.assertJsonEqual(local.base64FromBuffer(local.base64ToUtf8()), "");
// test identity handling-behavior
local.assertJsonEqual(
local.base64FromBuffer(local.base64ToBuffer(opt.base64)),
opt.base64
);
...base64urlFromBuffer = function (str) {
/*
* this function will convert base64url <str> to Uint8Array
*/
return local.base64FromBuffer(str).replace((
/\+/g
), "-").replace((
/\//g
), "_");
}n/a
blobRead = function (blob, onError) {
/*
* this function will read from <blob>
*/
let isDone;
let reader;
if (blob && blob.constructor && blob.constructor === local.FormData) {
blob.read(onError);
return;
}
if (!local.isBrowser) {
onError(undefined, local.bufferValidateAndCoerce(blob.buf));
return;
}
reader = new FileReader();
reader.onabort = function (evt) {
if (isDone) {
return;
}
isDone = true;
switch (evt.type) {
case "abort":
case "error":
onError(new Error("blobRead - " + evt.type));
break;
case "load":
onError(
undefined,
Object.prototype.toString.call(reader.result)
=== "[object ArrayBuffer]"
// convert ArrayBuffer to Uint8Array
? new Uint8Array(reader.result)
: reader.result
);
break;
}
};
reader.onerror = reader.onabort;
reader.onload = reader.onabort;
reader.readAsArrayBuffer(blob);
}...
switch ((xhr.data && xhr.data.constructor) || true) {
// Blob
// https://developer.mozilla.org/en-US/docs/Web/API/Blob
case local2.Blob:
// FormData
// https://developer.mozilla.org/en-US/docs/Web/API/FormData
case local2.FormData:
local2.blobRead(xhr.data, function (err, data) {
if (err) {
xhr.onEvent(err);
return;
}
// send data
xhr.send(data);
});
...browserTest = function (opt, onError) {
/*
* this function will spawn google-puppeteer-process to test <opt>.url
*/
let browser;
let fileScreenshot;
let isDone;
let onParallel;
let page;
let testId;
let testName;
let timerTimeout;
// init utility2_testReport
globalThis.utility2_testReport = globalThis.utility2_testReport || {
coverage: globalThis.__coverage__,
testPlatformList: [
{
name: (
local.isBrowser
? (
"browser - "
+ location.pathname + " - " + navigator.userAgent
)
: "node - " + process.platform + " " + process.version
) + " - " + new Date().toISOString(),
testCaseList: []
}
]
};
if (opt.modeTestReportCreate) {
return;
}
local.gotoNext(opt, function (err, data) {
switch (opt.gotoState) {
// node - init
case 1:
onParallel = local.onParallel(opt.gotoNext);
onParallel.cnt += 1;
isDone = 0;
testId = Math.random().toString(16);
testName = local.env.MODE_BUILD + ".browser." + encodeURIComponent(
new local.url.URL(opt.url).pathname.replace(
"/build.."
+ local.env.CI_BRANCH
+ ".." + local.env.CI_HOST,
"/build"
)
);
fileScreenshot = (
local.env.npm_config_dir_build + "/screenshot."
+ testName
+ ".png"
);
opt.url = opt.url.replace(
"{{timeExit}}",
Date.now() + local.timeoutDefault
);
// init timerTimeout
timerTimeout = setTimeout(
opt.gotoNext,
local.timeoutDefault,
new Error(
"timeout - " + local.timeoutDefault + " ms - "
+ testName
)
);
// create puppeteer browser
local.puppeteerLaunch({
args: [
"--headless",
"--incognito",
"--no-sandbox",
"--remote-debugging-port=0"
],
dumpio: !opt.modeSilent,
executablePath: local.env.CHROME_BIN,
ignoreDefaultArgs: true
}).then(opt.gotoNextData);
break;
case 2:
browser = data;
browser.newPage().then(opt.gotoNextData);
break;
case 3:
page = data;
page.goto(opt.url).then(opt.gotoNextData);
break;
case 4:
onParallel.cnt += 1;
setTimeout(function () {
page.screenshot({
path: fileScreenshot
}).then(function () {
console.error(
"\nbrowserTest - created screenshot file "
+ fileScreenshot
+ "\n"
);
onParallel();
});
}, 100);
page.on("metrics", function (metric) {
if (isDone >= 1 || metric.title !== testId) {
return;
}
isDone = 1;
opt.gotoNext();
});
page.evaluate(function (testId) {
window.utility2_testId = testId;
if (!window.utility2_modeTest) {
console.timeStamp(window.utility2_testId);
}
}, testId);
break;
case 5:
page.ev......
local.cliDict = {};
local.cliDict["utility2.browserTest"] = function () {
/*
* <urlList> <mode>
* will browser-test in parallel, comma-separated <urlList> with given <mode>
*/
local.browserTest({
url: process.argv[3]
}, local.onErrorDefault);
};
local.cliDict["utility2.githubCrudContentDelete"] = function () {
/*
* <fileRemote|dirRemote> <commitMessage>
...bufferConcat = function (bufList) {
/*
* this function will emulate in browser, node's Buffer.concat
*/
let byteLength;
let ii;
let isString;
let jj;
let result;
isString = true;
result = [
""
];
byteLength = 0;
bufList.forEach(function (buf) {
if (buf !== 0 && !(buf && buf.length)) {
return;
}
// optimization - concat string
if (isString && typeof buf === "string") {
result[0] += buf;
return;
}
isString = null;
buf = local.bufferValidateAndCoerce(buf);
byteLength += buf.byteLength;
result.push(buf);
});
// optimization - return string
if (isString) {
return result[0];
}
result[0] = local.bufferValidateAndCoerce(result[0]);
byteLength += result[0].byteLength;
bufList = result;
result = local.bufferValidateAndCoerce(new Uint8Array(byteLength));
ii = 0;
bufList.forEach(function (buf) {
jj = 0;
while (jj < buf.byteLength) {
result[ii] = buf[jj];
ii += 1;
jj += 1;
}
});
return result;
}...
]);
// init boundary
ii = 0;
jj = local.bufferIndexOfSubBuffer(req.bodyRaw, crlf, ii);
if (jj <= 0) {
break;
}
boundary = local.bufferConcat([
crlf, req.bodyRaw.slice(ii, jj)
]);
ii = jj + 2;
while (true) {
jj = local.bufferIndexOfSubBuffer(
req.bodyRaw,
boundary,
...bufferIndexOfSubBuffer = function (buf, subBff, fromIndex) {
/*
* this function will search <buf> from <fromIndex> for position of <subBff>
*/
let ii;
let jj;
let kk;
if (!subBff.length) {
return 0;
}
ii = fromIndex || 0;
while (ii < buf.length) {
kk = ii;
jj = 0;
while (jj < subBff.length) {
if (subBff[jj] !== buf[kk]) {
break;
}
kk += 1;
jj += 1;
}
if (jj === subBff.length) {
return kk - jj;
}
ii += 1;
}
return -1;
}...
req.swgg.bodyParsed = {};
req.swgg.bodyMeta = {};
crlf = new Uint8Array([
0x0d, 0x0a
]);
// init boundary
ii = 0;
jj = local.bufferIndexOfSubBuffer(req.bodyRaw, crlf, ii);
if (jj <= 0) {
break;
}
boundary = local.bufferConcat([
crlf, req.bodyRaw.slice(ii, jj)
]);
ii = jj + 2;
...bufferRandomBytes = function (length) {
/*
* this function will return a Buffer with given <length>,
* filled with cryptographically-strong random-values
*/
return (
(
typeof window === "object"
&& window.crypto
&& typeof window.crypto.getRandomValues === "function"
)
? window.crypto.getRandomValues(new Uint8Array(length))
: require("crypto").randomBytes(length)
);
}n/a
bufferToUtf8 = function (buf) {
/*
* this function will convert Uint8Array <buf> to utf8
*/
return local.bufferValidateAndCoerce(buf, "string");
}...
let name;
// if req is already parsed, then goto next
if (!req.swgg.operation || !local.isNullOrUndefined(req.swgg.bodyParsed)) {
next();
return;
}
headerParse = function () {
local.bufferToUtf8(req.bodyRaw.slice(ii, ii + 1024)).replace((
/^content-disposition:\u0020?form-data;(.+?)\r\n(?:content-type:\u0020?(.*?)$)?/im
), function (ignore, match1, match2) {
data = {
contentType: match2,
name: ""
};
match1.replace((
...bufferValidateAndCoerce = function (buf, mode) {
/*
* this function will validate and coerce/convert
* <buf> to Buffer/Uint8Array, or String if <mode> = "string"
*/
// validate not 0
if (buf !== 0) {
buf = buf || "";
}
if (typeof buf === "string" && mode === "string") {
return buf;
}
// convert utf8 to Uint8Array
if (typeof buf === "string") {
buf = new TextEncoder().encode(buf);
// validate instanceof Uint8Array
} else if (Object.prototype.toString.call(buf) !== "[object Uint8Array]") {
throw new Error(
"bufferValidateAndCoerce - value is not instanceof "
+ "ArrayBuffer, String, or Uint8Array"
);
}
// convert Uint8Array to utf8
if (mode === "string") {
return new TextDecoder().decode(buf);
}
// coerce Uint8Array to Buffer
if (globalThis.Buffer && Buffer.isBuffer && !Buffer.isBuffer(buf)) {
Object.setPrototypeOf(buf, Buffer.prototype);
}
return buf;
}...
return buf.subarray(0, jj);
};
local.base64ToUtf8 = function (str) {
/*
* this function will convert base64 <str> to utf8 str
*/
return local.bufferValidateAndCoerce(local.base64ToBuffer(str), "string");
};
local.base64urlFromBuffer = function (str) {
/*
* this function will convert base64url <str> to Uint8Array
*/
return local.base64FromBuffer(str).replace((
...buildApp = function (opt, onError) {
/*
* this function will build app with given <opt>
*/
opt = local.objectAssignDefault(opt, {
assetsList: []
});
// build assets
local.fsRmrfSync("tmp/build/app");
local.onParallelList({
list: [
{
file: "/LICENSE",
url: "/LICENSE"
}, {
file: "/assets." + local.env.npm_package_nameLib + ".html",
url: "/index.html"
}, {
file: "/assets." + local.env.npm_package_nameLib + ".js",
url: "/assets." + local.env.npm_package_nameLib + ".js"
}, {
file: "/assets.app.js",
url: "/assets.app.js"
}, {
file: "/assets.example.html",
url: "/assets.example.html"
}, {
file: "/assets.example.js",
url: "/assets.example.js"
}, {
file: "/assets.test.js",
url: "/assets.test.js"
}, {
file: "/assets.utility2.html",
url: "/assets.utility2.html"
}, {
file: "/assets.utility2.rollup.js",
url: "/assets.utility2.rollup.js"
}, {
file: "/index.html",
url: "/index.html"
}, {
file: "/index.rollup.html",
url: "/index.rollup.html"
}, {
file: "/jsonp.utility2.stateInit",
url: (
"/jsonp.utility2.stateInit"
+ "?callback=window.utility2.stateInit"
)
}
].concat(opt.assetsList)
}, async function (opt2, onParallel) {
let xhr;
opt2 = opt2.elem;
onParallel.cnt += 1;
xhr = await local.httpFetch(local.serverLocalHost + opt2.url, {
responseType: "raw"
});
// jslint file
local.jslintAndPrint(xhr.data.toString(), opt2.file, {
conditional: true,
coverage: local.env.npm_config_mode_coverage
});
// handle err
local.assertOrThrow(
!local.jslint.jslintResult.errMsg,
local.jslint.jslintResult.errMsg
);
local.fsWriteFileWithMkdirpSync(
"tmp/build/app" + opt2.file,
xhr.data,
"wrote file - app - {{pathname}}"
);
onParallel();
}, function (err) {
// handle err
local.assertOrThrow(!err, err);
// test standalone assets.app.js
local.fsWriteFileWithMkdirpSync(
"tmp/buildApp/assets.app.js",
local.assetsDict["/assets.app.js"],
"wrote file - assets.app.js - {{pathname}}"
);
local.childProcessSpawnWithTimeout("node", [
"assets.app.js"
], {
cwd: "tmp/buildApp",
env: {
PATH: local.env.PATH,
PORT: (Math.random() * 0x10000) | 0x8000,
npm_config_timeout_exit: 5000
},
stdio: [
"ignore", "ignore", 2
]
}).on("error", onError).on("exit", function (exitCode) {
// validate exitCode
local.assertOrThrow(!exitCode, exitCode);
onError();
});
});
}...
if (local.isBrowser) {
onError(undefined, opt);
return;
}
globalThis.local.testCase_buildReadme_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildLib_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildTest_default(opt, local.onErrorThrow);
local.buildApp(opt, onError);
};
local._testCase_buildLib_default = function (opt, onError) {
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
...buildLib = function (opt, onError) {
/*
* this function will build lib with given <opt>
*/
let result;
local.objectAssignDefault(opt, {
customize: local.nop,
dataFrom: local.fs.readFileSync(
"lib." + local.env.npm_package_nameLib + ".js",
"utf8"
),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.my_app.template.js"]
)
});
// search-and-replace - customize dataTo
[
// customize top-level comment-description
(
/\n\u0020\*\n(?:[\S\s]*?\n)?\u0020\*\/\n/
),
// customize code after /* validateLineSortedReset */
(
/\n\/\*\u0020validateLineSortedReset\u0020\*\/\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize assets.utility2.rollup.js
if (
local.fs.existsSync("./assets.utility2.rollup.js")
) {
opt.dataTo = opt.dataTo.replace(
" // || globalThis.utility2_rollup_old",
" || globalThis.utility2_rollup_old"
).replace(
" // || require(\"./assets.utility2.rollup.js\")",
" || require(\"./assets.utility2.rollup.js\")"
);
}
// save lib
result = opt.dataTo;
if (!local.env.npm_config_mode_coverage) {
local.fsWriteFileWithMkdirpSync(
"lib." + local.env.npm_package_nameLib + ".js",
result,
"wrote file - lib - {{pathname}}"
);
}
opt.customize(opt);
onError();
return result;
}...
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
return local.buildLib({}, onError);
};
local._testCase_buildReadme_default = function (opt, onError) {
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
...buildReadme = function (opt, onError) {
/*
* this function will build readme with given <opt> my-app-lite template
*/
let result;
local.objectAssignDefault(opt, {
customize: local.nop,
// reset toc
dataFrom: local.fs.readFileSync(
"README.md",
"utf8"
).replace((
/\n#\u0020table\u0020of\u0020contents$[\S\s]*?\n\n\n\n/m
), "\n# table of contents\n\n\n\n"),
packageJsonRgx: (
/\n#\u0020package.json\n```json\n([\S\s]*?)\n```\n/
)
});
// render dataTo
opt.dataTo = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"]
);
// init package.json
opt.dataFrom.replace(opt.packageJsonRgx, function (match0, match1) {
// remove null from package.json
opt.packageJson = JSON.parse(match1.replace((
/\u0020{4}".*?":\u0020null,?$/gm
), ""));
opt.packageJson.description = opt.dataFrom.split("\n")[1];
local.objectAssignDefault(opt.packageJson, {
nameLib: JSON.parse(
local.fs.readFileSync("package.json", "utf8")
).nameLib
});
opt.packageJson = local.objectAssignDefault(opt.packageJson, {
nameLib: opt.packageJson.name.replace((
/\W/g
), "_"),
nameOriginal: opt.packageJson.name
});
opt.packageJson = local.objectAssignDefault(
opt.packageJson,
JSON.parse(local.templateRenderMyApp(opt.packageJsonRgx.exec(
local.assetsDict["/assets.readme.template.md"]
)[1])),
2
);
// avoid npm-installing that
delete opt.packageJson.devDependencies[opt.packageJson.name];
// reset scripts
opt.packageJson.scripts = {
"build-ci": "./npm_scripts.sh",
env: "env",
eval: "./npm_scripts.sh",
"heroku-postbuild": "./npm_scripts.sh",
postinstall: "./npm_scripts.sh",
start: "./npm_scripts.sh",
test: "./npm_scripts.sh",
utility2: "./npm_scripts.sh"
};
// save package.json
local.fsWriteFileWithMkdirpSync(
"package.json",
local.jsonStringifyOrdered(opt.packageJson, undefined, 4) + "\n",
"wrote file - package.json - {{pathname}}"
);
// re-render dataTo
opt.dataTo = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"]
);
opt.dataTo = opt.dataTo.replace(
opt.packageJsonRgx,
match0.replace(
match1,
local.jsonStringifyOrdered(opt.packageJson, undefined, 4)
)
);
});
// search-and-replace - customize dataTo
[
// customize name and description
(
/.*?\n.*?\n/
),
// customize cdn-download
(
/\n#\u0020cdn\u0020download\n[\S\s]*?\n\n\n\n/
),
// customize live-web-demo
(
/\n#\u0020live\u0020web\u0020demo\n[\S\s]*?\n\n\n\n/
),
// customize changelog
(
/\n####\u0020changelog\u0020[\S\s]*?\n\n\n\n/
),
// customize example.js - shared js\u002denv code - init-before
(
/\nglobalThis\.local\u0020=\u0020local;\n[^`]*?\n\/\/\u0020run\u0020browser\u0020js\u002denv\u0020code\u0020-\u0020init
-test\n/
),
// customize example.js - html-body
(
/\n<!--\u0020custom-html-start\u0020-->\\n\\\n[^`]*?\n<!--\u0020custom-html-end\u0020-->\\n\\\n/
),
// customize build_ci - shBuildCiAfter
(
/\nshBuildCiAfter\u0020\(\)\u0......
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
return local.buildReadme({}, onError);
};
local._testCase_buildTest_default = function (opt, onError) {
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
...buildTest = function (opt, onError) {
/*
* this function will build test with given <opt>
*/
let result;
local.objectAssignDefault(opt, {
customize: local.nop,
dataFrom: local.fs.readFileSync("test.js", "utf8"),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.test.template.js"]
)
});
// search-and-replace - customize dataTo
[
// customize shared js\u002denv code - function
(
/\n\}\(\)\);\n\n\n\n\/\/\u0020run\u0020shared\u0020js\u002denv\u0020code\u0020-\u0020function\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize require("utility2")
[
"./assets.utility2.rollup.js",
"./lib.utility2.js"
].forEach(function (file) {
if (local.fs.existsSync(file)) {
opt.dataTo = opt.dataTo.replace(
"require(\"utility2\")",
"require(\"" + file + "\")"
);
}
});
opt.customize(opt);
// save test.js
result = opt.dataTo;
local.fsWriteFileWithMkdirpSync(
"test.js",
result,
"wrote file - test - {{pathname}}"
);
onError();
return result;
}...
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
return local.buildTest({}, onError);
};
local._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
if (local.isBrowser) {
...childProcessSpawnWithTimeout = function (command, args, opt) {
/*
* this function will run like child_process.spawn,
* but with auto-timeout after timeout milliseconds
* example use:
let child = local.childProcessSpawnWithTimeout(
"/bin/sh",
["-c", "echo hello world"],
{stdio: ["ignore", 1, 2], timeout: 5000}
);
child.on("error", console.error);
child.on("exit", function (exitCode) {
console.error("exitCode " + exitCode);
});
*/
let child;
let child_process;
let timerTimeout;
child_process = require("child_process");
// spawn child
child = child_process.spawn(command, args, opt).on("exit", function () {
// cleanup timerTimeout
try {
process.kill(timerTimeout.pid);
} catch (ignore) {}
});
// init timerTimeout
timerTimeout = child_process.spawn(
// convert timeout to integer seconds with 2 second delay
"sleep "
+ Math.floor(
0.001 * (Number(opt && opt.timeout) || local.timeoutDefault)
+ 2
)
+ "; kill -9 " + child.pid + " 2>/dev/null",
{
shell: true,
stdio: "ignore"
}
);
return child;
}...
local.assertOrThrow(!err, err);
// test standalone assets.app.js
local.fsWriteFileWithMkdirpSync(
"tmp/buildApp/assets.app.js",
local.assetsDict["/assets.app.js"],
"wrote file - assets.app.js - {{pathname}}"
);
local.childProcessSpawnWithTimeout("node", [
"assets.app.js"
], {
cwd: "tmp/buildApp",
env: {
PATH: local.env.PATH,
PORT: (Math.random() * 0x10000) | 0x8000,
npm_config_timeout_exit: 5000
...childProcessSpawnWithUtility2 = function (script, onError) {
/*
* this function will run child_process.spawn, with lib.utility2.sh sourced
*/
require("child_process").spawn(
". " + (process.env.npm_config_dir_utility2 || __dirname)
+ "/lib.utility2.sh; " + script,
{
shell: true,
stdio: [
"ignore", 1, 2
]
}
).on("exit", function (exitCode) {
onError(exitCode && Object.assign(new Error(), {
exitCode
}));
});
}...
// test __dirname handling-behavior
[
process.env, {
npm_config_dir_utility2: ""
}
]
], function (onError) {
local.local.childProcessSpawnWithUtility2("undefined", function (err
) {
// handle err
local.assertOrThrow(err, err);
});
onError(undefined, opt);
}, onError);
};
...cliRun = function (opt) {
/*
* this function will run cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
strDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " &quo......
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...coalesce = function (...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== null && arg !== undefined && arg !== "") {
break;
}
ii += 1;
}
return arg;
}...
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
...corsBackendHostInject = function (url, backendHost, rgx, location) {
/*
* this function will if <location>.host is a github site,
* inject <backendHost> into <url> with given <rgx>
*/
location = (
location
|| (typeof window === "object" && window && window.location)
);
if (!(backendHost && location && (
/\bgithub.io$/
).test(location.host))) {
return url;
}
// init github-branch
location.pathname.replace((
/\/build\.\.(alpha|beta|master)\.\.travis-ci\.org\//
), function (ignore, match1) {
backendHost = backendHost.replace("-alpha.", "-" + match1 + ".");
});
return url.replace(rgx || (
/.*?($)/m
), backendHost + "$1");
}...
};
local.testCase_corsBackendHostInject_default = function (opt, onError) {
/*
* this function will corsBackendHostInject's default handling-behavior
*/
// test null-case handling-behavior
local.assertJsonEqual(local.corsBackendHostInject(), undefined);
// test override-all handling-behavior
local.assertJsonEqual(local.corsBackendHostInject(
"cc.com",
"aa-alpha.bb.com",
null,
{
host: "github.io",
...corsForwardProxyHostIfNeeded = function (xhr) {
/*
* this function will return xhr.corsForwardProxyHost, if needed
*/
return (
local.isBrowser
&& local.env.npm_package_nameLib
&& (
/^https?:\/\//
).test(xhr.url)
&& xhr.url.indexOf(xhr.location.protocol + "//" + xhr.location.host)
!== 0
&& (
/\.github\.io$/
).test(xhr.location.host)
&& xhr.corsForwardProxyHost !== "disabled"
&& (xhr.corsForwardProxyHost || "https://h1-proxy1.herokuapp.com")
);
}...
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener("progress", ajaxProgressUpdate);
}
// open url - corsForwardProxyHost
if (
local2.corsForwardProxyHostIfNeeded
&& local2.corsForwardProxyHostIfNeeded(xhr)
) {
xhr.open(xhr.method, local2.corsForwardProxyHostIfNeeded(xhr));
xhr.setRequestHeader(
"forward-proxy-headers",
JSON.stringify(xhr.headers)
);
xhr.setRequestHeader("forward-proxy-url", xhr.url);
...cryptoAesXxxCbcRawDecrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc decrypt with given <opt>
* example use:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
let cipher;
let crypto;
let data;
let ii;
let iv;
let key;
// init key
key = new Uint8Array(0.5 * opt.key.length);
ii = 0;
while (ii < key.byteLength) {
key[ii] = parseInt(opt.key.slice(2 * ii, 2 * ii + 2), 16);
ii += 2;
}
data = opt.data;
// base64
if (opt.mode === "base64") {
data = local.base64ToBuffer(data);
}
// normalize data
if (Object.prototype.toString.call(data) !== "[object Uint8Array]") {
data = new Uint8Array(data);
}
// init iv
iv = data.subarray(0, 16);
// optimization - create resized-view of data
data = data.subarray(16);
crypto = globalThis.crypto;
if (!local.isBrowser) {
setTimeout(function () {
crypto = require("crypto");
cipher = crypto.createDecipheriv(
"aes-" + (8 * key.byteLength) + "-cbc",
key,
iv
);
onError(undefined, Buffer.concat([
cipher.update(data), cipher.final()
]));
});
return;
}
crypto.subtle.importKey("raw", key, {
name: "AES-CBC"
}, false, [
"decrypt"
]).then(function (key) {
crypto.subtle.decrypt({
iv,
name: "AES-CBC"
}, key, data).then(function (data) {
onError(undefined, new Uint8Array(data));
}).catch(onError);
}).catch(onError);
}...
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
let cipher;
...cryptoAesXxxCbcRawEncrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc encrypt with given <opt>
* example use:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
let cipher;
let crypto;
let data;
let ii;
let iv;
let key;
// init key
key = new Uint8Array(0.5 * opt.key.length);
ii = 0;
while (ii < key.byteLength) {
key[ii] = parseInt(opt.key.slice(2 * ii, 2 * ii + 2), 16);
ii += 2;
}
data = opt.data;
// init iv
iv = new Uint8Array((((data.byteLength) >> 4) << 4) + 32);
crypto = globalThis.crypto;
if (!local.isBrowser) {
setTimeout(function () {
crypto = require("crypto");
// init iv
iv.set(crypto.randomBytes(16));
cipher = crypto.createCipheriv(
"aes-" + (8 * key.byteLength) + "-cbc",
key,
iv.subarray(0, 16)
);
data = cipher.update(data);
iv.set(data, 16);
iv.set(cipher.final(), 16 + data.byteLength);
if (opt.mode === "base64") {
iv = local.base64FromBuffer(iv);
iv += "\n";
}
onError(undefined, iv);
});
return;
}
// init iv
iv.set(crypto.getRandomValues(new Uint8Array(16)));
crypto.subtle.importKey("raw", key, {
name: "AES-CBC"
}, false, [
"encrypt"
]).then(function (key) {
crypto.subtle.encrypt({
iv: iv.subarray(0, 16),
name: "AES-CBC"
}, key, data).then(function (data) {
iv.set(new Uint8Array(data), 16);
// base64
if (opt.mode === "base64") {
iv = local.base64FromBuffer(iv);
iv += "\n";
}
onError(undefined, iv);
}).catch(onError);
}).catch(onError);
}...
local.cryptoAesXxxCbcRawDecrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc decrypt with given <opt>
* example use:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
...dateGetWeekOfMonth = function (date) {
/*
* this function will return sunday-based week-of-month from <date>
*/
date = new Date(date.slice(0, 10) + "T00:00:00Z");
return Math.ceil((date.getUTCDate() + new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
1
).getUTCDay()) / 7) - 1;
}n/a
dateGetWeekOfYear = function (date) {
/*
* this function will return ISO week-of-year from <date>
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*
* https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php
*/
date = new Date(date.slice(0, 10) + "T00:00:00Z");
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
date.setUTCDate(date.getUTCDate() + 4 - (date.getUTCDay() || 7));
// Calculate full weeks to nearest Thursday
return Math.ceil((((
date
// Get first day of year
- new Date(Date.UTC(date.getUTCFullYear(), 0, 1))
) / 86400000) + 1) / 7);
}n/a
dateUtcFromLocal = function (date, timezoneOffset) {
/*
* this function will convert local-<date> to utc-date
*/
if (!date) {
return "";
}
local.assertOrThrow((
/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+?)?$/
).test(date), "invalid local-date " + date);
if (!timezoneOffset) {
return new Date(date).toISOString();
}
return new Date(
new Date(date + "Z").getTime() + timezoneOffset * 60000
).toISOString();
}n/a
dateUtcToLocal = function (date, timezoneOffset) {
/*
* this function will convert utc-<date> to local-date
*/
if (!date) {
return "";
}
local.assertOrThrow((
/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+?)?Z$/
).test(date), "invalid utc-date " + date);
timezoneOffset = timezoneOffset || new Date(date).getTimezoneOffset();
return new Date(
new Date(date).getTime() - timezoneOffset * 60000
).toISOString();
}n/a
domFragmentRender = function (template, dict) {
/*
* this function will return dom-elem rendered from <template>
*/
let tmp;
tmp = document.createElement("template");
tmp.innerHTML = local.templateRender(template, dict);
return tmp.content;
}...
});
// init uiFragment
swaggerJson.uiFragment = document.createDocumentFragment();
// init resourceDict
Object.keys(swaggerJson.resourceDict).sort().forEach(function (key) {
// templateRender resource
swaggerJson.uiFragment.appendChild(
local.domFragmentRender(
local.templateUiResource,
swaggerJson.resourceDict[key]
)
);
});
Object.keys(swaggerJson.operationDict).sort(function (aa, bb) {
aa = swaggerJson.operationDict[aa];
...domQuerySelectorAllTagName = function (selector) {
/*
* this function will return all tagName that match <selector>
*/
let set;
set = new Set();
document.querySelectorAll(selector).forEach(function (elem) {
set.add(elem.tagName);
});
return Array.from(set).sort();
}n/a
domSelectOptionValue = function (elem) {
/*
* this function will return <elem>.options[<elem>.selectedIndex].value
*/
if (typeof elem === "string") {
elem = document.querySelector(elem);
}
elem = elem && elem.options[elem.selectedIndex];
return (elem && elem.value) || "";
}n/a
domStyleValidate = function () {
/*
* this function will validate <style> tags
*/
let rgx;
let tmp;
try {
document.querySelector("#undefined");
} catch (ignore) {
return;
}
rgx = (
/^0\u0020(?:(body\u0020>\u0020)?(?:\.testReportDiv\u0020.+|\.x-istanbul\u0020.+|\.button|\.colorError|\.readonly|\.textarea
|\.uiAnimateSlide|a|body|code|div|input|pre|textarea)(?:,|\u0020\{))|^[1-9]\d*?\u0020#/m
);
tmp = [];
Array.from(
document.querySelectorAll("style")
).map(function (elem, ii) {
elem.innerHTML.replace((
/\/\*[\S\s]*?\*\/|;|\}/g
), "\n").replace((
/^([^\n\u0020@].*?)[,{:].*?$/gm
), function (match0, match1) {
try {
ii = document.querySelectorAll(match1).length;
} catch (errCaught) {
console.error(errCaught);
}
if (!(ii > 1)) {
tmp.push(ii + " " + match0);
}
});
});
tmp.filter(function (elem) {
return !rgx.test(elem);
}).sort().reverse().forEach(function (elem, ii, list) {
console.error(
"domStyleValidateUnmatched " + (list.length - ii) + ". " + elem
);
});
}...
/*
* this function will test webpage's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
local.domStyleValidate();
local.browserTest({
fileScreenshot: (
local.env.npm_config_dir_build
+ "/screenshot." + local.env.MODE_BUILD + ".browser.%2F.png"
),
url: (
local.serverLocalHost
...emit = function (type, msg) {
/*
* this function will emit evt <type> with <msg>
*/
Array.from(dict[type] || []).forEach(function (listener) {
listener(msg);
});
}...
data = concat(fragments, messageLength);
} else if (this._binaryType === 'arraybuffer') {
data = toArrayBuffer(concat(fragments, messageLength));
} else {
data = fragments;
}
this.emit('message', data);
} else {
const buf = concat(fragments, messageLength);
if (!isValidUTF8(buf)) {
this._loop = false;
return error(Error, 'invalid UTF-8 sequence', true, 1007);
}
...eventEmitterCreate = function (that = {}) {
/*
* this function will create a simple, node-like event-emitter with <that>,
* with methods emit, on, once, removeListener
*/
let dict;
let emit;
let on;
let once;
let remove;
emit = function (type, msg) {
/*
* this function will emit evt <type> with <msg>
*/
Array.from(dict[type] || []).forEach(function (listener) {
listener(msg);
});
};
on = function (type, listener, opt = {}) {
/*
* this function will listen to evt <type> with <listener>
*/
let isDone;
if (typeof listener === "function") {
dict[type] = dict[type] || [];
dict[type].push(
opt.once
? function listener2(msg) {
remove(type, listener2);
if (!isDone) {
isDone = true;
listener(msg);
}
}
: listener
);
}
return that;
};
once = function (type, listener, opt = {}) {
/*
* this function will listen to evt <type> once with <listener>
*/
opt.once = true;
return on(type, listener, opt);
};
remove = function (type, listener) {
/*
* this function will stop listening to evt <type> with <listener>
*/
let ii;
let list;
list = dict[type] || [];
ii = list.length;
while (ii > 0) {
ii -= 1;
if (list[ii] === listener) {
list.splice(ii, 1);
}
}
return that;
};
dict = {};
that.emit = that.emit || emit;
that.listenerEmit = that.listenerEmit || emit;
that.on = that.on || on;
that.once = that.once || once;
that.removeListener = that.removeListener || remove;
that.removeEventListener = that.removeEventListener || remove;
that.listenerOn = that.listenerOn || on;
that.listenerOnce = that.listenerOnce || once;
that.listenerRemove = that.listenerRemove || remove;
return that;
}...
that.removeEventListener = that.removeEventListener || remove;
that.listenerOn = that.listenerOn || on;
that.listenerOnce = that.listenerOnce || once;
that.listenerRemove = that.listenerRemove || remove;
return that;
};
local.eventEmitterCreate(local);
local.gotoNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.gotoNext,
* and append current-stack to any err
*/
opt.gotoNext = local.onErrorWithStack(function (err, data, meta) {
...function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
}n/a
fsReadFileOrDefaultSync = function (pathname, type, dflt) {
/*
* this function will sync-read <pathname> with given <type> and <dflt>
*/
let fs;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
}...
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "
;")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
...fsRmrfSync = function (pathname) {
/*
* this function will sync "rm -rf" <pathname>
*/
let child_process;
// do nothing if module does not exist
try {
child_process = require("child_process");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
if (process.platform !== "win32") {
child_process.spawnSync("rm", [
"-rf", pathname
], {
stdio: [
"ignore", 1, 2
]
});
return;
}
try {
child_process.spawnSync("rd", [
"/s", "/q", pathname
], {
stdio: [
"ignore", 1, "ignore"
]
});
} catch (ignore) {}
}...
return "image/jpeg";
default:
return file;
}
}
};
const removeFolder = function (dir, onError) {
local.fsRmrfSync(dir);
onError();
};
removeFolder.sync = local.fsRmrfSync;
const removeRecursive = removeFolder;
let EventEmitter = require('events');
let URL = require('url');
// let WebSocket = require('ws');
...fsWriteFileWithMkdirpSync = function (pathname, data, msg) {
/*
* this function will sync write <data> to <pathname> with "mkdir -p"
*/
let fs;
let success;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
// try to write pathname
try {
fs.writeFileSync(pathname, data);
success = true;
} catch (ignore) {
// mkdir -p
fs.mkdirSync(require("path").dirname(pathname), {
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
}...
|| local.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
) {
onError(undefined, opt);
return;
}
// save apidoc.html
local.fsWriteFileWithMkdirpSync(
"tmp/build/apidoc.html",
local.apidocCreate(local.objectAssignDefault(opt, {
blacklistDict: local,
require: require2
})),
"wrote file apidoc - {{pathname}}"
);
...gotoNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.gotoNext,
* and append current-stack to any err
*/
opt.gotoNext = local.onErrorWithStack(function (err, data, meta) {
try {
opt.gotoState += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
console.error("gotoNext - " + JSON.stringify({
gotoState: opt.gotoState,
errorMessage: err && err.message
}));
if (err && err.stack) {
console.error(err.stack);
}
}
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertOrThrow(undefined, opt.errCaught);
}
opt.errCaught = errCaught;
opt.gotoNext(errCaught, data, meta);
}
});
opt.gotoNextData = opt.gotoNext.bind(undefined, undefined);
return opt;
}...
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertOrThrow(undefined, opt.errCaught);
}
opt.errCaught = errCaught;
opt.gotoNext(errCaught, data, meta);
}
});
opt.gotoNextData = opt.gotoNext.bind(undefined, undefined);
return opt;
};
local.onErrorDefault = function (err) {
...httpFetch = function (url, opt) {
/*
* this function will fetch <url> with given <opt>
* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
* https://developer.mozilla.org/en-US/docs/Web/API/Response
*/
let buf;
let cleanup;
let controller;
let debug;
let errStack;
let httpFetchProgressUpdate;
let isBrowser;
let isDebugged;
let isDone;
let nop;
let reject2;
let reject;
let request;
let resolve2;
let resolve;
let response;
let timeStart;
let timeout;
let timerTimeout;
// init function
cleanup = function () {
if (isDone) {
return true;
}
isDone = true;
// cleanup timerTimeout
clearTimeout(timerTimeout);
// decrement httpFetchProgressUpdate.cnt
httpFetchProgressUpdate.cnt = Math.max(
httpFetchProgressUpdate.cnt - 1,
0
);
httpFetchProgressUpdate();
};
debug = function () {
if (isDebugged) {
return;
}
isDebugged = true;
console.error("serverLog - " + JSON.stringify({
time: new Date(timeStart).toISOString(),
type: "httpFetchResponse",
method: opt.method,
url,
status: opt.status,
timeElapsed: Date.now() - timeStart,
// extra
responseContentLength: buf.byteLength
}) + "\n");
};
nop = function () {
return;
};
reject2 = function (err) {
if (cleanup()) {
return;
}
debug();
// append errStack
if (errStack) {
err.stack += "\n" + errStack;
}
Object.assign(err, opt);
reject(err);
};
resolve2 = async function (response) {
try {
if (isBrowser) {
Array.from(response.headers).forEach(function ([
key, val
]) {
opt.responseHeaders[key.toLowerCase()] = val;
});
opt.status = response.status;
opt.ok = response.ok;
buf = new Uint8Array(
await response.arrayBuffer()
);
} else {
// init responseproperties specified in
// https://fetch.spec.whatwg.org/#response-class
opt.responseHeaders = response.headers;
opt.status = response.statusCode;
opt.ok = 200 <= opt.status && opt.status <= 299;
}
switch (opt.responseType) {
case "json":
opt.data = JSON.parse(new TextDecoder().decode(buf));
break;
case "raw":
opt.data = buf;
break;
default:
opt.data = new TextDecoder().decode(buf);
}
if (opt.modeDebug) {
debug();
}
if (!opt.ok) {
reject2(new Error("httpFetch - status " + opt.status));
return;
}
} catch (err) {
reject2(err);
return;
}
cleanup();
resolve(opt);
};
// init httpFetchProgressUpdate
httpFetchProgressUpdate = globalThis.httpFetchProgressUpdate || nop;
httpFetchProgressUpdate.cnt |= 0;
httpFetchProgressUpdate.cnt += 1;
httpFetchProgressUpdate();
// init opt
opt = opt || {};
opt.abort = function (err) {
controller.abort();
request.destroy();
response.destroy();
reject2(err || new Error("httpFetch - abort"));
};
opt.method = opt.method || "GET";
opt.responseHeaders = {};
opt.status = 400;
// init var
buf = new Uint8Array(0);
controller = {
abort: nop,
destroy: nop
};
isBrowser = (
typeof globalThi......
)
}
].concat(opt.assetsList)
}, async function (opt2, onParallel) {
let xhr;
opt2 = opt2.elem;
onParallel.cnt += 1;
xhr = await local.httpFetch(local.serverLocalHost + opt2.url, {
responseType: "raw"
});
// jslint file
local.jslintAndPrint(xhr.data.toString(), opt2.file, {
conditional: true,
coverage: local.env.npm_config_mode_coverage
});
...identity = function (val) {
/*
* this function will return <val>
*/
return val;
}...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...isNullOrUndefined = function (val) {
/*
* this function will test if val is null or undefined
*/
return val === null || val === undefined;
}...
? "arraybuffer"
: ""
)
});
// init paramDict
that.parameters.forEach(function (schemaP) {
tmp = opt.paramDict[schemaP.name];
if (local.isNullOrUndefined(tmp)) {
return;
}
// serialize array
if (Array.isArray(tmp) && schemaP.in !== "body") {
switch (
schemaP.collectionFormat || schemaP["x-swgg-collectionFormat"]
) {
...function Instrumenter(options) {
this.opts = options || {
debug: false,
walkDebug: false,
coverageVariable: '__coverage__',
codeGenerationOptions: undefined,
noAutoWrap: false,
noCompact: false,
embedSource: false,
preserveComments: false,
esModules: false
};
if (this.opts.esModules && !this.opts.noAutoWrap) {
this.opts.noAutoWrap = true;
if (this.opts.debug) {
console.log('Setting noAutoWrap to true as required by esModules');
}
}
this.walker = new Walker({
ArrowFunctionExpression: [ this.arrowBlockConverter ],
ExpressionStatement: this.coverStatement,
ExportNamedDeclaration: this.coverExport,
BreakStatement: this.coverStatement,
ContinueStatement: this.coverStatement,
DebuggerStatement: this.coverStatement,
ReturnStatement: this.coverStatement,
ThrowStatement: this.coverStatement,
TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
VariableDeclaration: this.coverStatement,
IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ],
ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ],
ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
SwitchStatement: [ this.coverStatement, this.switchBranchInjector ],
SwitchCase: [ this.switchCaseInjector ],
WithStatement: [ this.withBlockConverter, this.coverStatement ],
FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
FunctionExpression: this.coverFunction,
LabeledStatement: this.coverStatement,
ConditionalExpression: this.conditionalBranchInjector,
LogicalExpression: this.logicalExpressionBranchInjector,
ObjectExpression: this.maybeAddType,
MetaProperty: this.coverMetaProperty,
}, this.extractCurrentHint, this, this.opts.walkDebug);
//unit testing purposes only
if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
this.omitTrackerSuffix = true;
}
}n/a
function require(path) {
return mod.require(path);
}n/a
istanbulCoverageMerge = function (coverage1 = {}, coverage2 = {}) {
/*
* this function will inplace-merge <coverage2> into <coverage1>
*/
let dict1;
let dict2;
Object.keys(coverage2).forEach(function (file) {
// if coverage1[file] is undefined, then override it
if (!coverage1[file]) {
coverage1[file] = coverage2[file];
return;
}
// merge coverage2 into coverage1
[
"b", "f", "s"
].forEach(function (key) {
dict1 = coverage1[file][key];
dict2 = coverage2[file][key];
switch (key) {
// increment coverage for branch lines
case "b":
Object.keys(dict2).forEach(function (key) {
dict2[key].forEach(function (cnt, ii) {
dict1[key][ii] += cnt;
});
});
break;
// increment coverage for function and statement lines
case "f":
case "s":
Object.keys(dict2).forEach(function (key) {
dict1[key] += dict2[key];
});
break;
}
});
});
return coverage1;
}...
case 6:
data = JSON.parse(data);
// merge browser-screenshot
data.testPlatformList[0].screenshot = fileScreenshot.replace((
/.*\//
), "");
// merge browser-coverage
local.istanbulCoverageMerge(globalThis.__coverage__, data.coverage);
// merge browser-test-report
local.testReportMerge(globalThis.utility2_testReport, data);
// save test-report.json
onParallel.cnt += 1;
local.fs.writeFile(
local.path.resolve(
local.env.npm_config_dir_build + "/test-report.json"
...istanbulCoverageReportCreate = function (opt) {
/*
* this function will
// 1. merge previous <dirCoverage>/coverage.json into <opt>.coverage
// 2. convert <opt>.coverage to <summaryDict>
// 3. convert <summaryDict> to <nodeRoot>
// 4. convert <nodeRoot> to text-report <dirCoverage>/coverage.txt
// 5. convert <nodeRoot> to html-report <dirCoverage>/\*
// 6. return coverage-report in html-format as single document
*/
let coverageInclude;
let dirCoverage;
let filePrefix;
let filesUnderRoot;
let htmlAll;
let nodeChildAdd;
let nodeCreate;
let nodeDict;
let nodeNormalize;
let nodeRoot;
let summaryDict;
let tmp;
let tmpChildren;
if (!(opt && opt.coverage)) {
return "";
}
// init function
nodeChildAdd = function (node, child) {
/*
* this function will add <child> to <node>
*/
node.children.push(child);
child.parent = node;
};
nodeCreate = function (pathname) {
/*
* this function will create a tree-node
*/
return {
children: [],
pathname,
metrics: {
branches: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
functions: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
lines: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
statements: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
}
},
name: pathname
};
};
nodeNormalize = function (node, level, filePrefix, parent) {
/*
* this function will recursively normalize <node> and its children
*/
let metric;
// init name
if (node.name.indexOf(filePrefix) === 0) {
node.name = node.name.slice(filePrefix.length);
}
if (node.name[0] === path.sep) {
node.name = node.name.slice(1);
}
// init relativeName
node.relativeName = (
parent
? (
parent.name !== "__root__/"
? node.name.slice(parent.name.length)
: node.name
)
: node.name.slice(filePrefix.length)
);
// init nameOrAllFiles
node.nameOrAllFiles = node.name || "All files";
// init relativeNameOrAllFiles
node.relativeNameOrAllFiles = node.relativeName || "All files";
// init href
node.href = node.relativeName.split(path.sep).join("/") + (
node.isFile
? ".html"
: "index.html"
);
// recurse
node.children.forEach(function (child) {
nodeNormalize(child, level + 1, filePrefix, node);
});
// sort children by name
node.children.sort(function (aa, bb) {
return (
aa.name > bb.name
? 1
: -1
);
});
// init metrics
if (!node.isFile) {
node.children.forEach(function (child) {
[
"lines", "statements", "branches", "functions"
].forEach(function (key) {
metric = node.metrics[key];
metric.total += child.metrics[key].total;
metric.covered += child.metrics[key].covered;
metric.skipped += child.metrics[key].skipped;...n/a
istanbulInstrumentInPackage = function (code, file) {
/*
* this function will instrument <code>
* if macro /\* istanbul instrument in package $npm_package_nameLib *\/
* exists in <code>
*/
return (
(
process.env.npm_config_mode_coverage
&& code.indexOf("/* istanbul ignore all */\n") < 0 && (
process.env.npm_config_mode_coverage === "all"
|| process.env.npm_config_mode_coverage === "node_modules"
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_package_nameLib + " */\n"
) >= 0
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_config_mode_coverage + " */\n"
) >= 0
)
)
? local.instrumentSync(code, file)
: code
);
}...
"globalThis.utility2_moduleExports"
);
// init example.js
tmp = local.path.resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
...istanbulInstrumentSync = function (code, file) {
/*
* this function will
// 1. normalize <file>
// 2. save <code> to __coverageInclude__[<file>] for future html-report
// 3. return instrumented-code
*/
// 1. normalize <file>
file = path.resolve(file);
// 2. save <code> to __coverageInclude__[<file>] for future html-report
globalThis.__coverageInclude__[file] = 1;
// 3. return instrumented-code
return new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimStart();
}n/a
jslintAndPrint = function (code = "", file = "undefined", opt = {}) {
/*
* this function will jslint/csslint <code> and print any errors to stderr
*/
let ii;
let tmp;
if (!(opt && opt.gotoState)) {
local.jslintResult = {
gotoState: 0
};
}
opt = Object.assign(local.jslintResult, opt);
opt.gotoState += 1;
switch (opt.gotoState) {
// jslint - init
case 1:
// cleanup
opt.errList = [];
opt.errMsg = "";
// preserve lineno
if (opt.iiStart) {
opt.lineOffset |= 0;
ii = 0;
while (true) {
ii = code.indexOf("\n", ii);
if (ii === 0 || ii > opt.iiStart) {
break;
}
ii += 1;
opt.lineOffset += 1;
}
code = code.slice(opt.iiStart, opt.iiEnd || code.length);
}
switch (opt.fileType0) {
// de-embed-js - '\\n\\\n...\\n\\\n'
case ".\\n\\":
// rgx - remove \\n\\
code = code.replace((
/\\n\\$|\\(.)/gm
), function (ignore, match1) {
return match1 || "";
});
break;
// de-embed-js - '\n...\n'
case ".sh":
// rgx - convert '"'"' to '
code = code.replace((
/'"'"'/g
), "'");
break;
}
// init
opt = Object.assign(opt, {
".css": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".html": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".js": (
/^\/\*jslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".json": (
/^\s*?(?:\[|\{)/
),
".md": (
/(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".sh": (
/(^#\u0020jslint\u0020utility2:true$)/m
),
code0: code,
fileType: (
/\.\w+?$|$/m
).exec(file)[0]
});
// jslint - .json
if (opt.fileType === ".js" && opt[".json"].test(code)) {
opt.fileType = ".json";
}
try {
opt.conditionalPassed = opt[opt.fileType].exec(code);
} catch (ignore) {}
opt.utility2 = (
opt.conditionalPassed && opt.conditionalPassed[1]
) || opt.autofix;
if (
opt.conditional
&& (!opt.conditionalPassed || opt.coverage)
) {
break;
}
opt.gotoState = 10;
break;
// jslint - autofix
case 11:
code = local.jslintAutofix(code, file, opt);
local.jslintResult = opt;
break;
// jslint - csslint and jslint
case 12:
// restore lineOffset
code = "\n".repeat(opt.lineOffset | 0) + code;
switch (opt.fileType) {
case ".css":
// csslint
Object.assign(opt, local.CSSLint.verify(code));
// init errList
opt.errList = opt.messages.map(function (err) {
err.column = err.col;
err.message = (
err.type + " - " + err.rule.id + " - " + err.message
+ "\n " + err.rule.desc
);
return err;
});
break;
case ".html":
case ".md":
case ".sh":
break;
default:
// jslint - .js......
return;
}
// read file
local.fs.readFile(opt.file, "utf8", opt.gotoNext);
break;
case 2:
// jslint
local.jslint.jslintAndPrint(data, opt.file);
local.assertOrThrow(
!local.jslint.jslintResult.errMsg,
local.jslint.jslintResult.errMsg.replace((
/\u001b\[\d*m/g
), "")
);
// validate
...jslintAutofixLocalFunction = function (code, file) {
/*
* this function will jslint-autofix local-function
*/
let code2;
let dictFnc;
let dictProp;
let tmp;
if (local.isBrowser) {
return code;
}
file = local.path.resolve(file).replace(process.cwd() + local.path.sep, "");
switch (file) {
case "README.md":
case "lib." + process.env.npm_package_nameLib + ".js":
case "lib." + process.env.npm_package_nameLib + ".sh":
case "lib.apidoc.js":
case "lib.github_crud.js":
case "lib.istanbul.js":
case "lib.jslint.js":
case "lib.marked.js":
case "lib.puppeteer.js":
case "npm_scripts.sh":
case "test.js":
break;
default:
return code;
}
// autofix - assets.utility2.header.js
code = code.replace((
/\n\/\/\u0020assets.utility2\.header\.js\u0020-\u0020start\n[\S\s]*?\n\/\/\u0020assets.utility2\.header\.js\u0020-\u0020end\n/
), "\n" + local.assetsDict["/assets.utility2.header.js"]);
// autofix - assets.my_app.template.js
code = local.stringMerge(
code,
local.assetsDict["/assets.my_app.template.js"].replace((
/my_app/g
), file.split(".")[1]),
file !== "README.md" && local.identity(
/\n\/\*\u0020istanbul\u0020instrument\u0020in\u0020package\u0020[\S\s]*?\n\/\*\u0020validateLineSortedReset\u0020\*\/\n/
)
);
// customize local for assets.utility2.rollup.js
if (
file === "lib." + process.env.npm_package_nameLib + ".js"
&& local.fs.existsSync("./assets.utility2.rollup.js")
) {
code = code.replace(
" // || globalThis.utility2_rollup_old",
" || globalThis.utility2_rollup_old"
).replace(
" // || require(\"./assets.utility2.rollup.js\")",
" || require(\"./assets.utility2.rollup.js\")"
);
}
// init functionAllDict and functionBaseDict
[
[
"utility2"
], [
"utility2", "apidoc", "github_crud"
]
].forEach(function (dictList, ii) {
tmp = (
ii
? "functionAllDict"
: "functionBaseDict"
);
if (local[tmp]) {
return;
}
local[tmp] = {};
dictList.forEach(function (dict) {
dict = local[dict];
Object.keys(dict).forEach(function (key) {
if (
!(
/^[A-Z_]|^testCase_/m
).test(key)
&& typeof dict[key] === "function"
) {
local[tmp][key] = local[tmp][key] || String(dict[key]);
}
});
});
Object.keys(local[tmp]).forEach(function (key) {
if (process.binding("natives")[key]) {
local[tmp][key] = undefined;
}
});
});
// autofix - local-function
dictFnc = {};
dictProp = {};
code = code.replace((
/^local\.(.*?)\u0020=\u0020(function\u0020\([\S\s]*?\n\});\n+/gm
), function (match0, key, match2, match3) {
// local-function - duplicate
if (dictFnc[key]) {
return "";
}
// local-function - normalize
dictFnc[key] = true;
match3 = local.functionAllDict[key] || "";
// make shell-safe
// https://unix.stackexchange.com/questions/57794/shell-escape-characters-for-sh-c
if (file.slice(-3) === ".sh") {
match3 = match3.replace((
/'/g
), "'\"'\"&ap...n/a
jsonCopy = function (obj) {
/*
* this function will deep-copy obj
*/
return (
obj === undefined
? undefined
: JSON.parse(JSON.stringify(obj))
);
}...
}
// try to validate paramDict
opt.err = local.swaggerValidateDataParameters({
// normalize paramDict
data: local.normalizeSwaggerParamDict({
modeNoDefault: opt.modeNoDefault,
operation: that,
paramDict: local.jsonCopy(opt.paramDict)
}).paramDict,
dataReadonlyRemove: opt.paramDict,
prefix: [
"operation", that._methodPath
],
parameters: that.parameters,
swaggerJson: local.swaggerJson
...jsonStringifyOrdered = function (obj, replacer, space) {
/*
* this function will JSON.stringify <obj>,
* with object-keys sorted and circular-references removed
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax
*/
let circularSet;
let stringify;
let tmp;
stringify = function (obj) {
/*
* this function will recursively JSON.stringify obj,
* with object-keys sorted and circular-references removed
*/
// if obj is not an object or function,
// then JSON.stringify as normal
if (!(
obj
&& typeof obj === "object"
&& typeof obj.toJSON !== "function"
)) {
return JSON.stringify(obj);
}
// ignore circular-reference
if (circularSet.has(obj)) {
return;
}
circularSet.add(obj);
// if obj is an array, then recurse items
if (Array.isArray(obj)) {
tmp = "[" + obj.map(function (obj) {
// recurse
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
if (typeof tmp === "string") {
return JSON.stringify(key) + ":" + tmp;
}
}).filter(function (obj) {
return typeof obj === "string";
}).join(",") + "}";
circularSet.delete(obj);
return tmp;
};
circularSet = new Set();
return JSON.stringify((
(typeof obj === "object" && obj)
// recurse
? JSON.parse(stringify(obj))
: obj
), replacer, space);
}...
<!-- swgg-script-extra-end -->\n\
</body>\n\
</html>\n\
');
/* jslint ignore:end */
local.assetsDict[
"/assets.swgg.swagger.schema.json"
] = local.jsonStringifyOrdered(
local.objectAssignRecurse(
JSON.parse(local.assetsDict["/assets.swgg.json-schema.json"].replace((
/"\$ref":".*?#/g
), "\"$ref\":\"http://json-schema.org/draft-04/schema#")),
JSON.parse(local.assetsDict["/assets.swgg.schema.json"].replace((
/"\$ref":".*?#/g
), "\"$ref\":\"http://json-schema.org/draft-04/schema#")),
...listGetElementRandom = function (list) {
/*
* this function will return random elem from <list>
*/
return list[Math.floor(Math.random() * list.length)];
}...
return local.jsonCopy(schemaP.default);
}
// init enum-value
if (schemaP.enum) {
value = (
opt.modeNotRandom
? schemaP.enum[0]
: local.listGetElementRandom(schemaP.enum)
);
return (
local.schemaPType(schemaP) === "array"
? [
value
]
: value
...listShuffle = function (list) {
/*
* this function will inplace shuffle <list> using fisher-yates algorithm
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
let ii;
let random;
let swap;
ii = list.length;
while (ii > 1) {
ii -= 1;
random = Math.floor(Math.random() * (ii + 1));
swap = list[ii];
list[ii] = list[random];
list[random] = swap;
}
return list;
}...
opt = {};
// init list
opt.list = "[0,1]";
// shuffle list 100 times
opt.ii = 0;
while (opt.ii < 100) {
opt.listShuffled = JSON.stringify(
local.listShuffle(JSON.parse(opt.list))
);
// validate shuffled list
local.assertJsonEqual(opt.listShuffled.length, opt.list.length);
opt.changed = opt.changed || opt.listShuffled !== opt.list;
opt.ii += 1;
}
// validate list changed at least once during shuffle
...listenerEmit = function (type, msg) {
/*
* this function will emit evt <type> with <msg>
*/
Array.from(dict[type] || []).forEach(function (listener) {
listener(msg);
});
}n/a
listenerOn = function (type, listener, opt = {}) {
/*
* this function will listen to evt <type> with <listener>
*/
let isDone;
if (typeof listener === "function") {
dict[type] = dict[type] || [];
dict[type].push(
opt.once
? function listener2(msg) {
remove(type, listener2);
if (!isDone) {
isDone = true;
listener(msg);
}
}
: listener
);
}
return that;
}n/a
listenerOnce = function (type, listener, opt = {}) {
/*
* this function will listen to evt <type> once with <listener>
*/
opt.once = true;
return on(type, listener, opt);
}n/a
listenerRemove = function (type, listener) {
/*
* this function will stop listening to evt <type> with <listener>
*/
let ii;
let list;
list = dict[type] || [];
ii = list.length;
while (ii > 0) {
ii -= 1;
if (list[ii] === listener) {
list.splice(ii, 1);
}
}
return that;
}n/a
localStorageSetItemOrClear = function (key, value) {
/*
* this function will try to set <key>/<value> pair to localStorage,
* or else call localStorage.clear()
*/
try {
localStorage.setItem(key, value);
} catch (ignore) {
localStorage.clear();
}
}...
);
local.apiKeyValue = localStorage.getItem(local.apiKeyKey) || "";
// save apiKeyValue
} else {
local.apiKeyValue = document.querySelector(
"#swggApiKeyInput1"
).value;
local.localStorageSetItemOrClear(
local.apiKeyKey,
local.apiKeyValue
);
}
// if keyup-evt is not return-key, then return
if (
(opt.type === "keyup" && opt.code !== "Enter")
...function c
(e, n, r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i=
n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function(
e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n
.highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(!
a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i(
e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p
();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults
,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked."
;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0
)+"</pre>";throw h}}n/a
function r(e, t){this.options=t||c.defaults,this.links=
e,this.rules=n.normal,this.renderer=this.options.renderer||new i,this.renderer.options=
this.options;if(!this.links)throw new Error("Tokens array requires a `links` property."
);this.options.gfm?this.options.breaks?this.rules=n.breaks:this.rules=n.gfm:this
.options.pedantic&&(this.rules=n.pedantic)}n/a
function t(t){this.tokens=[],this.tokens.links={},this.options=t||c.
defaults,this.rules=e.normal,this.options.gfm&&(this.options.tables?this.rules=e
.tables:this.rules=e.gfm)}n/a
function s
(e){this.tokens=[],this.token=null,this.options=e||c.defaults,this.options.renderer=
this.options.renderer||new i,this.renderer=this.options.renderer,this.renderer.options=
this.options}n/a
function i(e){this.options=e||{}}n/a
middlewareAssetsCached = function (req, res, next) {
/*
* this function will run middleware to serve cached-assets
*/
if (!local.assetsDict.hasOwnProperty(req.urlParsed.pathname)) {
next();
return;
}
// do not cache if headers already sent or url has '?' search indicator
if (!(res.headersSent || req.url.indexOf("?") >= 0)) {
// init serverResponseHeaderLastModified
local.serverResponseHeaderLastModified = (
local.serverResponseHeaderLastModified
// resolve to 1000 ms
|| new Date(new Date().toUTCString())
);
// respond with 304 If-Modified-Since serverResponseHeaderLastModified
if (
new Date(req.headers["if-modified-since"])
>= local.serverResponseHeaderLastModified
) {
res.statusCode = 304;
res.end();
return;
}
res.setHeader("Cache-Control", "no-cache");
res.setHeader(
"Last-Modified",
local.serverResponseHeaderLastModified.toUTCString()
);
}
res.end(local.assetsDict[req.urlParsed.pathname]);
}n/a
middlewareBodyRead = function (req, ignore, next) {
/*
* this function will run middleware to
* read and save <req> body to <req>.bodyRaw
*/
// if req is already read, then goto next
if (!req.readable) {
next();
return;
}
let bufList;
bufList = [];
req.on("data", function (buf) {
bufList.push(buf);
}).on("end", function () {
req.bodyRaw = (
local.isBrowser
? bufList[0]
: Buffer.concat(bufList)
);
next();
// on event-error, pass error to onError
}).on("error", next);
}...
/*
* this function will run test-middleware
*/
switch (req.urlParsed.pathname) {
// test http POST handling-behavior
case "/test.body":
// test req-body-read handling-behavior
local.middlewareBodyRead(req, res, function () {
// test multiple req-body-read handling-behavior
local.middlewareBodyRead(req, res, function () {
res.write(req.bodyRaw);
res.end();
});
});
break;
...middlewareError = function (err, req, res) {
/*
* this function will run middleware to handle errors
*/
// default - 404 Not Found
if (!err) {
local.serverRespondDefault(req, res, 404);
return;
}
// statusCode [400, 600)
local.serverRespondDefault(req, res, (
(err.statusCode >= 400 && err.statusCode < 600)
? err.statusCode
: 500
), err);
}...
}
globalThis.utility2_onReadyBefore.cnt += 1;
local.serverLocalReqHandler = function (req, res) {
let that;
that = {};
local.gotoNext(that, function (err) {
if (err || that.gotoState >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[that.gotoState](req, res, that.gotoNext);
});
that.gotoState = -1;
that.gotoNext();
...middlewareFileServer = function (req, res, next) {
/*
* this function will run middleware to serve files
*/
let file;
if (req.method !== "GET" || local.isBrowser) {
next();
return;
}
// resolve file
file = require("path").resolve(
// replace trailing "/" with "/index.html"
require("url").parse(req.url).pathname.slice(1).replace((
/\/$/
), "/index.html")
);
// security - disable parent-directory lookup
if (file.indexOf(process.cwd() + require("path").sep) !== 0) {
next();
return;
}
require("fs").readFile(file, function (err, data) {
// default to next
if (err) {
next();
return;
}
// respond with data
res.end(data);
});
}...
case "/test.timeout":
setTimeout(function () {
res.end();
}, 2000);
break;
// serve file
default:
local.middlewareFileServer(req, res, next);
}
});
}());
// run node js-env code - init-after
...middlewareForwardProxy = function (req, res, next) {
/*
* this function will run middleware to forward-proxy <req>
* to its destination-host
*/
let clientHeaders;
let clientReq;
let clientRes;
let clientUrl;
let isDone;
let onError;
let timeStart;
let timerTimeout;
// handle preflight-cors
if (req.method === "OPTIONS" && (
/forward-proxy-url/
).test(req.headers["access-control-request-headers"])) {
local.serverRespondHeadSet(req, res, undefined, {
"access-control-allow-headers": "*",
"access-control-allow-methods": "*",
"access-control-allow-origin": "*"
});
res.end();
return;
}
if (!req.headers["forward-proxy-url"]) {
next();
return;
}
local.serverRespondHeadSet(req, res, undefined, {
"access-control-allow-headers": "*",
"access-control-allow-methods": "*",
"access-control-allow-origin": "*"
});
// init onError
onError = function (err) {
if (isDone) {
return;
}
isDone = true;
// cleanup timerTimeout
clearTimeout(timerTimeout);
// debug middlewareForwardProxy
console.error("serverLog - " + JSON.stringify({
time: new Date(timeStart).toISOString(),
type: "middlewareForwardProxyResponse",
method: req.method,
clientUrl,
statusCode: res.statusCode | 0,
timeElapsed: Date.now() - timeStart,
// extra
headers: clientHeaders
}) + "\n");
if (!err) {
return;
}
// cleanup clientReq and clientRes
local.streamCleanup(clientReq);
local.streamCleanup(clientRes);
next(err);
};
// init timerTimeout
timerTimeout = setTimeout(
onError,
local.timeoutDefault,
new Error(
"timeout - " + local.timeoutDefault + " ms - "
+ "forward-proxy " + req.method + " " + clientUrl
)
);
// init client
clientUrl = local.urlParse(req.headers["forward-proxy-url"]).href;
try {
clientHeaders = {};
clientHeaders = JSON.parse(req.headers["forward-proxy-headers"]);
} catch (ignore) {}
clientReq = require(
clientUrl.indexOf("http:") === 0
? "http"
: "https"
).request(clientUrl, {
headers: clientHeaders
}, function (arg) {
clientRes = arg;
clientRes.on("error", onError);
res.statusCode = clientRes.statusCode;
// pipe clientRes to res
clientRes.pipe(res);
}).on("error", onError);
timeStart = Date.now();
// handle evt
req.on("error", onError);
res.on("finish", onError).on("error", onError);
// pipe req to clientReq
req.pipe(clientReq);
}n/a
middlewareInit = function (req, res, next) {
/*
* this function will run middleware to init <req> and <res>
*/
let contentType;
// debug req and res
local._debugServerReqRes4 = local._debugServerReqRes3;
local._debugServerReqRes3 = local._debugServerReqRes2;
local._debugServerReqRes2 = local._debugServerReqRes1;
local._debugServerReqRes1 = {
req,
res
};
// init timerTimeout
local.serverRespondTimeoutDefault(req, res, local.timeoutDefault);
// init req.urlParsed
req.urlParsed = local.urlParse(req.url);
// set reponse-header "content-type"
contentType = {
// application
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".pdf": "application/pdf",
".wasm": "application/wasm",
".xml": "application/xml; charset=utf-8",
// image
".bmp": "image/bmp",
".gif": "image/gif",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml; charset=utf-8",
// text
"/": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".htm": "text/html; charset=utf-8",
".html": "text/html; charset=utf-8",
".md": "text/markdown; charset=utf-8",
".txt": "text/plain; charset=utf-8"
};
contentType = contentType[(
/^\/$|\.[^.]*?$|$/m
).exec(req.urlParsed.pathname)[0]];
if (contentType) {
res.setHeader("content-type", contentType);
}
// default to next
next();
}n/a
middlewareJsonpStateInit = function (req, res, next) {
/*
* this function will run middleware to
* serve browser-state wrapped in given jsonp-callback
*/
let state;
if (!(req.stateInit || (
req.urlParsed
&& req.urlParsed.pathname === "/jsonp.utility2.stateInit"
))) {
next();
return;
}
state = {
utility2: {
assetsDict: {
"/assets.example.html":
local.assetsDict["/assets.example.html"],
"/assets.example.js": local.assetsDict["/assets.example.js"],
"/assets.test.js": local.assetsDict["/assets.test.js"],
"/index.rollup.html": local.assetsDict["/index.rollup.html"]
},
env: {
NODE_ENV: local.env.NODE_ENV,
npm_config_mode_backend: local.env.npm_config_mode_backend,
npm_package_description: local.env.npm_package_description,
npm_package_homepage: local.env.npm_package_homepage,
npm_package_name: local.env.npm_package_name,
npm_package_nameLib: local.env.npm_package_nameLib,
npm_package_version: local.env.npm_package_version
}
}
};
if (req.stateInit) {
return state;
}
res.end(
req.urlParsed.query.callback + "(" + JSON.stringify(state) + ");"
);
}...
code += local.assetsDict[tmp];
break;
case "local.stateInit":
// handle large string-replace
code = local.assetsDict["/assets.utility2.rollup.content.js"].split(
"/* utility2.rollup.js content */"
);
tmp = local.middlewareJsonpStateInit({
stateInit: true
});
// add extra physical files to assetsDict
local.fs.readdirSync(".").forEach(function (file) {
file = "/" + file;
if (
local.assetsDict[file]
...moduleDirname = function (module, pathList) {
/*
* this function will search <pathList> for <module>'s __dirname
*/
let result;
// search "."
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(module || "");
}
// search pathList
Array.from([
pathList,
require("module").globalPaths,
[
process.env.HOME + "/node_modules", "/usr/local/lib/node_modules"
]
]).flat().some(function (path) {
try {
result = require("path").resolve(path + "/" + module);
result = require("fs").statSync(result).isDirectory() && result;
return result;
} catch (ignore) {
result = "";
}
});
return result;
}...
return match0.replace((
/(.{128}(?:\b|\w+))/g
), "$1\n").trimEnd();
});
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
...nop = function () {
/*
* this function will do nothing
*/
return;
}...
// run shared js-env code - function
(function () {
let process;
let require;
// hack-jslint
local.nop(require);
globalThis.__coverageInclude__ = local.coalesce(
globalThis.__coverageInclude__,
{}
);
// mock builtins
process = local.process || {
cwd: function () {
...normalizeJwt = function (data) {
/*
* this function will normalize jwt-data with registered-headers
* https://tools.ietf.org/html/rfc7519#section-4.1
*/
let timeNow;
timeNow = Date.now() / 1000;
return local.objectAssignDefault(data, {
exp: timeNow + 5 * 60,
iat: timeNow,
jti: Math.random().toString(16).slice(2),
nbf: timeNow
});
}n/a
normalizeJwtBase64Url = function (str) {
/*
* this function will normlize <str> to base64url format
*/
return str.replace((
/\=/g
), "").replace((
/\+/g
), "-").replace((
/\//g
), "_");
}n/a
numberToRomanNumerals = function (num) {
/*
* this function will convert num to a roman-numeral
* https://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript
*/
let digits;
let ii;
let key;
let roman;
digits = String(num).split("");
key = [
"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"
];
roman = "";
ii = 3;
while (ii) {
ii -= 1;
roman = (key[Number(digits.pop()) + (ii * 10)] || "") + roman;
}
return new Array(Number(digits.join("") + 1)).join("M") + roman;
}...
"XCVIII",
"XCIX",
"C"
];
opt.ii = 0;
while (opt.ii < 10) {
local.assertJsonEqual(
local.numberToRomanNumerals(opt.ii),
opt.list[opt.ii]
);
opt.ii += 1;
}
onError(undefined, opt);
};
...objectAssignDefault = function (tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...objectAssignRecurse = function (dict, overrides, depth, env) {
/*
* this function will recursively set overrides for items in dict
*/
dict = dict || {};
env = env || (typeof process === "object" && process.env) || {};
overrides = overrides || {};
Object.keys(overrides).forEach(function (key) {
let dict2;
let overrides2;
dict2 = dict[key];
overrides2 = overrides[key];
if (overrides2 === undefined) {
return;
}
// if both dict2 and overrides2 are non-undefined and non-array objects,
// then recurse with dict2 and overrides2
if (
depth > 1
// dict2 is a non-undefined and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// overrides2 is a non-undefined and non-array object
&& typeof overrides2 === "object" && overrides2
&& !Array.isArray(overrides2)
) {
local.objectAssignRecurse(dict2, overrides2, depth - 1, env);
return;
}
// else set dict[key] with overrides[key]
dict[key] = (
dict === env
// if dict is env, then overrides falsy-value with empty-string
? overrides2 || ""
: overrides2
);
});
return dict;
}...
</body>\n\
</html>\n\
');
/* jslint ignore:end */
local.assetsDict[
"/assets.swgg.swagger.schema.json"
] = local.jsonStringifyOrdered(
local.objectAssignRecurse(
JSON.parse(local.assetsDict["/assets.swgg.json-schema.json"].replace((
/"\$ref":".*?#/g
), "\"$ref\":\"http://json-schema.org/draft-04/schema#")),
JSON.parse(local.assetsDict["/assets.swgg.schema.json"].replace((
/"\$ref":".*?#/g
), "\"$ref\":\"http://json-schema.org/draft-04/schema#")),
2
...on = function (type, listener, opt = {}) {
/*
* this function will listen to evt <type> with <listener>
*/
let isDone;
if (typeof listener === "function") {
dict[type] = dict[type] || [];
dict[type].push(
opt.once
? function listener2(msg) {
remove(type, listener2);
if (!isDone) {
isDone = true;
listener(msg);
}
}
: listener
);
}
return that;
}...
*/
let bufList;
bufList = [];
xhr.resHeaders = resStream.headers || xhr.resHeaders;
xhr.resStream = resStream;
xhr.statusCode = resStream.statusCode;
resStream.dataLength = 0;
resStream.on("data", function (buf) {
bufList.push(buf);
});
resStream.on("end", function () {
xhr.response = (
local.isBrowser
? bufList[0]
: Buffer.concat(bufList)
...onErrorDefault = function (err) {
/*
* this function will if <err> exists, then print it to stderr
*/
if (err) {
console.error(err);
}
return err;
}...
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
...onErrorThrow = function (err) {
/*
* this function will if <err> exists, then throw it
*/
if (err) {
throw err;
}
return err;
}...
};
local.testCase_onErrorThrow_err = function (opt, onError) {
/*
* this function will test onErrorThrow's err handling-behavior
*/
local.tryCatchOnError(function () {
local.onErrorThrow(local.errorDefault);
}, function (err) {
// handle err
local.assertOrThrow(err, err);
onError(undefined, opt);
});
};
...onErrorWithStack = function (onError) {
/*
* this function will wrap <onError> with wrapper preserving current-stack
*/
let onError2;
let stack;
stack = new Error().stack;
onError2 = function (err, data, meta) {
// append current-stack to err.stack
if (
err
&& typeof err.stack === "string"
&& err !== local.errorDefault
) {
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
}...
};
local.gotoNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.gotoNext,
* and append current-stack to any err
*/
opt.gotoNext = local.onErrorWithStack(function (err, data, meta) {
try {
opt.gotoState += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
...onFileModifiedRestart = function (file) {
/*
* this function will watch <file>, and if modified, then restart process
*/
if (
local.env.npm_config_mode_auto_restart
&& local.fs.existsSync(file)
&& local.fs.statSync(file).isFile()
) {
local.fs.watchFile(file, {
interval: 1000,
persistent: false
}, function (stat2, stat1) {
if (stat2.mtime > stat1.mtime) {
console.error("file modified - " + file);
setTimeout(function () {
process.exit(77);
}, 1000);
}
});
}
}...
[
__dirname + "/lib.jslint.js",
__filename,
"undefined"
].forEach(function (file) {
local.fs.exists(file, function (exists) {
if (exists) {
local.onFileModifiedRestart(file);
}
});
});
// if file is modified, then restart process
local.fs.readdirSync(".").forEach(function (file) {
local.onFileModifiedRestart(file);
});
...onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if cnt === 0 or err occurred, then call onError(err)
*/
let onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement cnt
onParallel.cnt -= 1;
// validate cnt
if (!(onParallel.cnt >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.cnt = " + onParallel.cnt
);
// ensure onError is run only once
} else if (onParallel.cnt < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure cnt <= 0
onParallel.cnt = -Math.abs(onParallel.cnt);
}
// call onError when isDone
if (onParallel.cnt <= 0) {
onError(err, data);
return;
}
onEach();
};
// init cnt
onParallel.cnt = 0;
// return callback
return onParallel;
}...
elem: opt.list[onParallel.ii],
ii: onParallel.ii,
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
...onParallelList = function (opt, onEach, onError) {
/*
* this function will
* 1. async-run onEach in parallel,
* with given <opt>.rateLimit and <opt>.retryLimit
* 2. call <onError> when onParallel.ii + 1 === <opt>.list.length
*/
let isListEnd;
let onEach2;
let onParallel;
opt.list = opt.list || [];
onEach2 = function () {
while (true) {
if (!(onParallel.ii + 1 < opt.list.length)) {
isListEnd = true;
return;
}
if (!(onParallel.cnt < opt.rateLimit + 1)) {
return;
}
onParallel.ii += 1;
onEach({
elem: opt.list[onParallel.ii],
ii: onParallel.ii,
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
// restart if opt.list has grown
if (isListEnd && (onParallel.ii + 1 < opt.list.length)) {
isListEnd = undefined;
onEach2();
}
});
onParallel.ii = -1;
opt.rateLimit = Number(opt.rateLimit) || 6;
opt.rateLimit = Math.max(opt.rateLimit, 1);
opt.retryLimit = Number(opt.retryLimit) || 2;
onParallel.cnt += 1;
onEach2();
onParallel();
}...
method: "DELETE",
sha: data.sha,
url: opt.url
}, opt.gotoNext);
return;
}
// delete tree
local.onParallelList({
list: data
}, function (opt2, onParallel) {
onParallel.cnt += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
...once = function (type, listener, opt = {}) {
/*
* this function will listen to evt <type> once with <listener>
*/
opt.once = true;
return on(type, listener, opt);
}...
/**
* Close the server.
*
* @param {Function} cb Callback
* @public
*/
close(cb) {
if (cb) this.once('close', cb);
//
// Terminate all associated clients.
//
if (this.clients) {
for (const client of this.clients) client.terminate();
}
...promisify = function (fnc) {
/*
* this function will promisify <fnc>
*/
return function (...argList) {
return new Promise(function (resolve, reject) {
fnc(...argList, function (err, ...argList) {
if (err) {
reject(err, ...argList);
return;
}
resolve(...argList);
});
});
};
}...
resultBuffer = Buffer.concat(bufs);
} finally {
return resultBuffer;
}
}
}
const openAsync = Helper.promisify(fs.open);
const writeAsync = Helper.promisify(fs.write);
const closeAsync = Helper.promisify(fs.close);
/**
* @param {*} value
* @param {string=} message
*/
...puppeteerLaunch = function () { [native code] }...
local.timeoutDefault,
new Error(
"timeout - " + local.timeoutDefault + " ms - "
+ testName
)
);
// create puppeteer browser
local.puppeteerLaunch({
args: [
"--headless",
"--incognito",
"--no-sandbox",
"--remote-debugging-port=0"
],
dumpio: !opt.modeSilent,
...removeEventListener = function (type, listener) {
/*
* this function will stop listening to evt <type> with <listener>
*/
let ii;
let list;
list = dict[type] || [];
ii = list.length;
while (ii > 0) {
ii -= 1;
if (list[ii] === listener) {
list.splice(ii, 1);
}
}
return that;
}n/a
removeListener = function (type, listener) {
/*
* this function will stop listening to evt <type> with <listener>
*/
let ii;
let list;
list = dict[type] || [];
ii = list.length;
while (ii > 0) {
ii -= 1;
if (list[ii] === listener) {
list.splice(ii, 1);
}
}
return that;
}...
* @public
*/
removeEventListener(method, listener) {
const listeners = this.listeners(method);
for (var i = 0; i < listeners.length; i++) {
if (listeners[i] === listener || listeners[i]._listener === listener) {
this.removeListener(method, listeners[i]);
}
}
}
};
exports_websockets_ws_lib_event_target = EventTarget;
...replStart = function () {
/*
* this function will start repl-debugger
*/
let that;
if (globalThis.utility2_repl1) {
return;
}
// start repl
that = require("repl").start({
useGlobal: true
});
globalThis.utility2_repl1 = that;
// save eval-function
that.evalDefault = that.eval;
// hook custom-eval-function
that.eval = function (script, context, file, onError) {
script.replace((
/^(\S+)\u0020(.*?)\n/
), function (ignore, match1, match2) {
switch (match1) {
// syntax-sugar - run shell-command
case "$":
match2 = match2.replace((
/^git\b/
), "git --no-pager");
switch (match2) {
// syntax-sugar - run git diff
case "git diff":
match2 = "git diff --color";
break;
// syntax-sugar - run git log
case "git log":
match2 = "git log -n 4";
break;
// syntax-sugar - run ll
case "ll":
match2 = "ls -Fal";
break;
}
// source lib.utility2.sh
if (
process.platform !== "win32"
&& process.env.npm_config_dir_utility2 && (match2 !== ":")
) {
match2 = (
". " + process.env.npm_config_dir_utility2
+ "/lib.utility2.sh;" + match2
);
}
// run shell-command
require("child_process").spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// print exitCode
}).on("exit", function (exitCode) {
console.error("exitCode " + exitCode);
that.evalDefault("\n", context, file, onError);
});
script = "\n";
break;
// syntax-sugar - map text with charCodeAt
case "charCode":
console.error(
match2.split("").map(function (chr) {
return (
"\\u"
+ chr.charCodeAt(0).toString(16).padStart(4, 0)
);
}).join("")
);
script = "\n";
break;
// syntax-sugar - sort chr
case "charSort":
console.error(JSON.stringify(match2.split("").sort().join("")));
script = "\n";
break;
// syntax-sugar - grep current dir
case "grep":
// run shell-command
require("child_process").spawn((
"find . -type f | grep -v -E "
/* jslint ignore:start */
+ '"\
/\\.|~\$|/(obj|release)/|(\\b|_)(\\.\\d|\
archive|artifact|\
bower_component|build|\
coverage|\
doc|\
external|\
fixture|\
git_module|\
jquery|\
log|\
min|misc|mock|\
node_module|\
raw|\rollup|\
swp|\
tmp|\
vendor)s{0,1}(\\b|_)\
" '
/* jslint ignore:end */
+ "| tr \"\\n\" \"\\000\" | xargs -0 grep -HIin -E \""
+ match2 + "\""
), {
shell: true,
stdio: [
"ignore", 1, 2
]
}).on("exit", function (exitCode) {
console.error(&qu......
local.cliDict["utility2.start"] = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
};
local.cliDict["utility2.testReportCreate"] = function () {
/*
*
* will create test-report
...requireReadme = function () {
/*
* this function will require and export example.js embedded in README.md
*/
let code;
let module;
let tmp;
// init module.exports
module = {};
if (local.isBrowser) {
module.exports = local.objectAssignDefault(
globalThis.utility2_rollup || globalThis.local,
local
);
return module.exports;
}
// start repl-debugger
local.replStart();
// debug dir
[
__dirname + "/lib.jslint.js",
__filename,
"undefined"
].forEach(function (file) {
local.fs.exists(file, function (exists) {
if (exists) {
local.onFileModifiedRestart(file);
}
});
});
// if file is modified, then restart process
local.fs.readdirSync(".").forEach(function (file) {
local.onFileModifiedRestart(file);
});
// jslint process.cwd()
if (!local.env.npm_config_mode_library) {
local.child_process.spawn("node", [
"-e", (
"require("
+ JSON.stringify(__filename)
+ ").jslint.jslintAndPrintDir("
+ JSON.stringify(process.cwd())
+ ", {autofix:true,conditional:true}, process.exit);"
)
], {
env: Object.assign({}, local.env, {
npm_config_mode_library: "1"
}),
stdio: [
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
/^#!\//
), "// ");
// init exports
local[local.env.npm_package_nameLib] = local;
module.exports = local;
return module.exports;
}
// init file $npm_package_main
globalThis.utility2_moduleExports = require(
local.path.resolve(local.env.npm_package_main)
);
globalThis.utility2_moduleExports.globalThis = globalThis;
// read code from README.md
code = local.templateRenderMyApp(
local.assetsDict["/assets.example.template.js"]
);
local.fsReadFileOrDefaultSync("README.md", "utf8", "").replace((
/\n```javascript(\n\/\*\nexample\.js\n[\S\s]*?\n)```\n/
), function (ignore, match1, index, input) {
// preserve lineno
code = input.slice(0, index).replace((
/.+/g
), "") + "\n" + match1;
return "";
});
// alias require($npm_package_name) to utility2_moduleExports;
code = code.replace(
new RegExp("require\\(." + local.env.npm_package_name + ".\\)"),
"globalThis.utility2_moduleExports"
).replace(
new RegExp("require\\(." + local.env.npm_package_nameOriginal + ".\\)"),
"globalThis.utility2_moduleExports"
);
// init example.js
tmp = local.path.resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
globalThis.utility2_moduleExpor......
\n\
\n\
\n\
// run shared js\-env code - init-before\n\
(function () {\n\
// init local\n\
local = globalThis.utility2 || require("utility2");\n\
local = local.requireReadme();\n\
globalThis.local = local;\n\
// init test\n\
local.testRunDefault(local);\n\
}());\n\
\n\
\n\
\n\
...serverLocalReqHandler = function (req, res) {
let that;
that = {};
local.gotoNext(that, function (err) {
if (err || that.gotoState >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[that.gotoState](req, res, that.gotoNext);
});
that.gotoState = -1;
that.gotoNext();
}...
if (isDone) {
return;
}
isDone = true;
data = _data;
// async send req from client to server
setTimeout(function () {
local.serverLocalReqHandler(req, res);
});
},
headers: xhr.headers,
method: xhr.method,
on: function () {
return xhr;
},
...serverLocalUrlTest = function (url) {
/*
* this function will test if <url> is local
*/
url = local.urlParse(url).pathname;
return local.isBrowser && !local.env.npm_config_mode_backend && (
/^\/test\./
).test(url);
}...
xhr.resHeaders = {};
xhr.timeStart = xhr.timeStart || Date.now();
};
// init xhr - XMLHttpRequest
xhr = (
local.isBrowser
&& !opt.httpReq
&& !(local2.serverLocalUrlTest && local2.serverLocalUrlTest(opt.url
))
&& new XMLHttpRequest()
);
// init xhr - http.request
if (!xhr) {
xhr = local.identity(local2.urlParse || require("url").parse)(opt.url);
// init xhr
xhrInit();
...serverRespondDefault = function (req, res, statusCode, err) {
/*
* this function will respond with a default message,
* or <err>.stack for given statusCode
*/
// init statusCode and contentType
local.serverRespondHeadSet(
req,
res,
statusCode,
{
"Content-Type": "text/plain; charset=utf-8"
}
);
if (err) {
// debug statusCode / method / url
err.message = (
res.statusCode + " " + req.method + " " + req.url + "\n"
+ err.message
);
// print err.stack to stderr
local.onErrorDefault(err);
// end res with err.stack
res.end(err.stack);
return;
}
// end res with default statusCode message
res.end(
statusCode + " " + local.http.STATUS_CODES[statusCode]
);
}...
opt.gotoNext(null, data, meta);
}
break;
case 3:
switch (crud.crudType[0]) {
case "fileGetOneById":
if (!data) {
local.serverRespondDefault(req, res, 404);
return;
}
local.serverRespondHeadSet(req, res, null, {
"Content-Type": data.fileContentType
});
res.end(local.base64ToBuffer(data.fileBlob));
break;
...serverRespondEcho = function (req, res) {
/*
* this function will respond with debug info
*/
res.write(
req.method + " " + req.url
+ " HTTP/" + req.httpVersion + "\r\n"
+ Object.keys(req.headers).map(function (key) {
return key + ": " + req.headers[key] + "\r\n";
}).join("") + "\r\n"
);
req.pipe(res);
}...
break;
// test http POST handling-behavior
case "/test.echo":
// test res-header handling-behavior
local.serverRespondHeadSet(req, res, null, {
"X-Res-Header-Test": "bb"
});
local.serverRespondEcho(req, res);
break;
// test 500-internal-server-error handling-behavior
case "/test.err-500":
// test multiple-callback serverRespondHeadSet handling-behavior
local.serverRespondHeadSet(req, res, null, {});
next(local.errorDefault);
// test multiple-callback-error handling-behavior
...serverRespondHeadSet = function (ignore, res, statusCode, headers) {
/*
* this function will set <res> object's <statusCode> and <headers>
*/
if (res.headersSent) {
return;
}
// init res.statusCode
if (Number(statusCode)) {
res.statusCode = Number(statusCode);
}
Object.keys(headers).forEach(function (key) {
if (headers[key]) {
res.setHeader(key, headers[key]);
}
});
return true;
}...
});
local.dbTableFile.crudSetManyById(crud.body, opt.gotoNext);
break;
case "userLoginByPassword":
case "userLogout":
// respond with 401 Unauthorized
if (!user.isAuthenticated) {
local.serverRespondHeadSet(req, res, 401, {});
req.swgg.crud.endArgList = [
req, res
];
opt.gotoState = Infinity;
opt.gotoNext();
return;
}
...serverRespondTimeoutDefault = function (req, res, timeout) {
/*
* this function will create <timeout>-handler for server-<req>
*/
let isDone;
let onError;
onError = function () {
if (isDone) {
return;
}
isDone = true;
// debug res
console.error("serverLog - " + JSON.stringify({
time: new Date(req.timeStart).toISOString(),
type: "serverResponse",
method: req.method,
url: req.url,
statusCode: res.statusCode | 0,
timeElapsed: Date.now() - req.timeStart,
// extra
reqContentLength: req.dataLength || 0,
resContentLength: res.contentLength,
reqHeaderXForwardedFor: req.headers["x-forwarded-for"] || "",
reqHeaderOrigin: req.headers.origin || "",
reqHeaderReferer: req.headers.referer || "",
reqHeaderUserAgent: req.headers["user-agent"]
}) + "\n");
// cleanup timerTimeout
clearTimeout(req.timerTimeout);
};
req.timeStart = Date.now();
req.onTimeout = req.onTimeout || function (err) {
local.serverRespondDefault(req, res, 500, err);
setTimeout(function () {
// cleanup req and res
local.streamCleanup(req);
local.streamCleanup(res);
}, 1000);
};
// init timerTimeout
timeout = timeout || local.timeoutDefault;
req.timerTimeout = setTimeout(
req.onTimeout,
timeout,
new Error(
"timeout - " + timeout + " ms - "
+ "server " + req.method + " " + req.url
)
);
res.contentLength = 0;
res.writeContentLength = res.writeContentLength || res.write;
res.write = function (buf, encoding, callback) {
buf = local.bufferValidateAndCoerce(buf, typeof buf);
res.contentLength += buf.length;
res.writeContentLength(buf, encoding, callback);
};
res.on("error", onError);
res.on("finish", onError);
}...
local._debugServerReqRes3 = local._debugServerReqRes2;
local._debugServerReqRes2 = local._debugServerReqRes1;
local._debugServerReqRes1 = {
req,
res
};
// init timerTimeout
local.serverRespondTimeoutDefault(req, res, local.timeoutDefault);
// init req.urlParsed
req.urlParsed = local.urlParse(req.url);
// set reponse-header "content-type"
contentType = {
// application
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
...setTimeoutOnError = function (onError, timeout, err, data) {
/*
* this function will after timeout has passed,
* then call <onError>(<err>, <data>)
*/
if (typeof onError === "function") {
setTimeout(function () {
onError(err, data);
}, timeout);
}
return data;
}...
element.querySelector(
"[tabIndex]"
).focus();
// validate input
local.uiEventListenerDict.onEventInputValidateAndAjax({
targetOnEvent: element
});
local.setTimeoutOnError(onError, 0, null, element);
}
);
};
local.uiEventListenerDict.onEventResourceDisplayAction = function (evt) {
/*
* this function will toggle the display of the resource
...stateInit = function (opt) {
/*
* this function will init state <opt>
*/
local.objectAssignRecurse(local, opt, 10);
}...
// run shared js-env code - init-after
(function () {
// hack-coverage - test testRunServer's multiple-call handling-behavior
local.testRunServer(local);
// hack-coverage - stateInit
local.stateInit({});
// init test-middleware
local.middlewareList.push(function (req, res, next) {
/*
* this function will run test-middleware
*/
switch (req.urlParsed.pathname) {
// test http POST handling-behavior
...function Stream(opts) {
EE.call(this, opts);
}n/a
streamCleanup = function (stream) {
/*
* this function will try to end or destroy <stream>
*/
let err;
// try to end stream
try {
stream.end();
} catch (errCaught) {
err = errCaught;
}
// if err, then try to destroy stream
if (err) {
try {
stream.destroy();
} catch (ignore) {}
}
}...
// extra
headers: clientHeaders
}) + "\n");
if (!err) {
return;
}
// cleanup clientReq and clientRes
local.streamCleanup(clientReq);
local.streamCleanup(clientRes);
next(err);
};
// init timerTimeout
timerTimeout = setTimeout(
onError,
local.timeoutDefault,
...stringHtmlSafe = function (str) {
/*
* this function will make <str> html-safe
* https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html
*/
return str.replace((
/&/gu
), "&").replace((
/"/gu
), """).replace((
/'/gu
), "'").replace((
/</gu
), "<").replace((
/>/gu
), ">").replace((
/&(amp;|apos;|gt;|lt;|quot;)/igu
), "&$1");
}...
);
// handle case where module is a function
elem.name = elem.name.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimStart(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
...stringLineCount = function (str, start, end) {
/*
* this function will count number of "\n" in <str>
* from <start> to <end>
*/
let count;
count = 0;
while (true) {
start = str.indexOf("\n", start) + 1;
if (start === 0 || start >= end) {
return count;
}
count += 1;
}
}n/a
stringMerge = function (str1, str2, rgx) {
/*
* this function will merge <str2> into <str1>,
* for sections where both match <rgx>
*/
str2.replace(rgx, function (match2) {
str1.replace(rgx, function (match1) {
str1 = str1.replace(match1, function () {
return match2;
});
return "";
});
return "";
});
return str1;
}...
/\n\u0020\*\n(?:[\S\s]*?\n)?\u0020\*\/\n/
),
// customize code after /* validateLineSortedReset */
(
/\n\/\*\u0020validateLineSortedReset\u0020\*\/\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize assets.utility2.rollup.js
if (
local.fs.existsSync("./assets.utility2.rollup.js")
) {
opt.dataTo = opt.dataTo.replace(
" // || globalThis.utility2_rollup_old",
...stringQuotedToAscii = function (str) {
/*
* this function will replace non-ascii-chr to unicode-escaped-ascii-chr
* in quoted-<str>
*/
return str.replace((
/\r/g
), "\\r").replace((
/\t/g
), "\\t").replace((
/[^\n\u0020-\u007e]/g
), function (chr) {
return "\\u" + ("0000" + chr.charCodeAt(0).toString(16)).slice(-4);
});
}...
};
local.testCase_stringQuotedToAscii_default = function (opt, onError) {
/*
* this function will test stringQuotedToAscii's default handling-behavior
*/
local.assertJsonEqual(
local.stringQuotedToAscii(local.stringHelloEmoji),
"hello \\ud83d\\ude01\n"
);
onError(undefined, opt);
};
local.testCase_stringRegexpEscape_default = function (opt, onError) {
/*
...stringRegexpEscape = function (str) {
/*
* this function will regexp-escape <str>
* https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
*/
return str.replace((
/[\-\/\\\^$*+?.()|\[\]{}]/g
), "\\$&");
}...
};
local.testCase_stringRegexpEscape_default = function (opt, onError) {
/*
* this function will test stringRegexpEscape's default handling-behavior
*/
local.assertJsonEqual(
local.stringRegexpEscape(local.stringCharsetAscii),
(
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007"
+ "\b\t\n\u000b\f\r\u000e\u000f"
+ "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017"
+ "\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"
+ " !\"#\\$%&'\\(\\)\\*\\+,\\-\\.\\/0123456789:;<=>\\?@"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\\\\\]\\^_`"
...templateRender = function (template, dict, opt, ii) {
/*
* this function will render <template> with given <dict>
*/
let argList;
let getVal;
let match;
let renderPartial;
let rgx;
let skip;
let val;
if (dict === null || dict === undefined) {
dict = {};
}
opt = opt || {};
getVal = function (key) {
argList = key.split(" ");
val = dict;
if (argList[0] === "#this/") {
return val;
}
if (argList[0] === "#ii/") {
return ii;
}
// iteratively lookup nested val in dict
argList[0].split(".").forEach(function (key) {
val = val && val[key];
});
return val;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
), "");
}
return val;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getVal(key)
? partial[0]
// handle "unless" case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getVal(key)
? ""
// recurse with partial
: local.templateRender(partial, dict, opt)
);
default:
// recurse with partial
return match0[0] + local.templateRender(match0.slice(1), dict, opt);
}
};
// render partials
rgx = (
/\{\{#(\w+)\u0020([^}]+?)\}\}/g
);
template = template || "";
match = rgx.exec(template);
while (match) {
rgx.lastIndex += 1 - match[0].length;
template = template.replace(
new RegExp(
"\\{\\{#(" + match[1] + ") (" + match[2]
+ ")\\}\\}([\\S\\s]*?)\\{\\{/" + match[1] + " " + match[2]
+ "\\}\\}"
),
renderPartial
);
match = rgx.exec(template);
}
// search for keys in template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
let markdownToHtml;
let notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
val = getVal(match0.slice(2, -2));
if (val === undefined) {
return match0;
}
argList.slice(1).forEach(function (fmt, ii, list) {
switch (fmt) {
case "*":
case "+":
case "-":
case "/":
skip = ii + 1;
val = String(
fmt === "*"
? Number(val) * Number(list[skip])
: fmt === "+"
? Number(val) + Number(list[skip])
: fmt === "-"
? Number(val) - Number(list[skip])
: Number(val) / Number(list[skip])
);
break;......
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
...templateRenderMyApp = function (template) {
/*
* this function will render my-app-lite template
*/
let githubRepo;
let packageJson;
packageJson = JSON.parse(local.fs.readFileSync("package.json", "utf8"));
local.objectAssignDefault(packageJson, {
nameLib: packageJson.name.replace((
/\W/g
), "_"),
repository: {
url: (
"https://github.com/kaizhu256/node-" + packageJson.name
)
}
}, 2);
githubRepo = packageJson.repository.url.replace((
/\.git$/
), "").split("/").slice(-2);
template = template.replace((
/kaizhu256(\.github\.io\/|%252F|\/)/g
), githubRepo[0] + ("$1"));
template = template.replace((
/node-my-app-lite/g
), githubRepo[1]);
template = template.replace((
/\bh1-my-app\b/g
), (
packageJson.nameHeroku
|| ("h1-" + packageJson.nameLib.replace((
/_/g
), "-"))
));
template = template.replace((
/my-app-lite/g
), packageJson.name);
template = template.replace((
/my_app/g
), packageJson.nameLib);
template = template.replace((
/\{\{packageJson\.(\S+)\}\}/g
), function (ignore, match1) {
return packageJson[match1];
});
return template;
}...
let result;
local.objectAssignDefault(opt, {
customize: local.nop,
dataFrom: local.fs.readFileSync(
"lib." + local.env.npm_package_nameLib + ".js",
"utf8"
),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.my_app.template.js"]
)
});
// search-and-replace - customize dataTo
[
// customize top-level comment-description
(
...testMock = function (mockList, onTestCase, onError) {
/*
* this function will mock objects in <mockList> when running <onTestCase>
*/
let onError2;
onError2 = function (err) {
// restore mock[0] from mock[2]
mockList.reverse().forEach(function (mock) {
Object.keys(mock[2]).forEach(function (key) {
mock[0][key] = mock[2][key];
});
});
onError(err);
};
// suppress console.error and console.log
if (!(mockList[0] && mockList[0][0] === console)) {
mockList.unshift([
console, {}
]);
}
local.objectAssignDefault(mockList[0][1], {
error: local.nop,
log: local.nop
});
// mock-objects
mockList.forEach(function (mock) {
mock[2] = {};
// backup mock[0] into mock[2]
Object.keys(mock[1]).forEach(function (key) {
mock[2][key] = (
(
typeof process === "object"
&& process.env === mock[0]
&& mock[0][key] === undefined
)
// handle process.env
? ""
: mock[0][key]
);
});
// override mock[0] with mock[1]
Object.keys(mock[1]).forEach(function (key) {
mock[0][key] = mock[1][key];
});
});
// try to call onError with mock-objects
local.tryCatchOnError(function () {
// run onTestCase
onTestCase(onError2);
}, onError2);
}...
};
}
});
mockList.push([
tmp, mockDict
]);
});
local.testMock(mockList, function (onError) {
local.tryCatchOnError(function () {
exports = require(file);
}, local.onErrorDefault);
onError();
}, local.onErrorThrow);
return exports;
};
...testReportCreate = function (testReport) {
/*
* this function will create test-report artifacts
*/
testReport = local.objectAssignDefault(testReport, {
testPlatformList: []
});
// print test-report summary
console.error(
"\n" + new Array(56).join("-")
+ "\n" + testReport.testPlatformList.filter(function (testPlatform) {
// if testPlatform has no tests, then filter it out
return testPlatform.testCaseList.length;
}).map(function (testPlatform) {
return (
"| test-report - " + testPlatform.name + "\n|"
+ String(
testPlatform.timeElapsed + " ms "
).padStart(16, " ")
+ String(
testPlatform.testsFailed + " failed "
).padStart(16, " ")
+ String(
testPlatform.testsPassed + " passed "
).padStart(16, " ")
+ " |\n" + new Array(56).join("-")
);
}).join("\n") + "\n"
);
// create test-report.html
local.fsWriteFileWithMkdirpSync(
"tmp/build/test-report.html",
local.testReportMerge(testReport),
"wrote file - test-report - {{pathname}}"
);
// create build.badge.svg
local.fsWriteFileWithMkdirpSync(
"tmp/build/build.badge.svg",
local.assetsDict["/assets.buildBadge.template.svg"].replace((
/0000-00-00\u002000:00:00\u0020UTC\u0020-\u0020master\u0020-\u0020aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/g
), (
new Date().toISOString().slice(0, 19).replace("T", " ")
+ " - " + local.env.CI_BRANCH + " - " + local.env.CI_COMMIT_ID
)),
"wrote file - test-report - {{pathname}}"
);
// create test-report.badge.svg
local.fsWriteFileWithMkdirpSync(
"tmp/build/test-report.badge.svg",
local.assetsDict["/assets.testReportBadge.template.svg"].replace((
// edit number of tests failed
/999/g
), testReport.testsFailed).replace((
// edit badge color
/d00/g
), (
testReport.testsFailed
? "d00"
: "0d0"
)),
"wrote file - test-report - {{pathname}}"
);
// if any test failed, then exit with non-zero exitCode
console.error(
"\n" + local.env.MODE_BUILD
+ " - " + testReport.testsFailed + " failed tests\n"
);
// print failed testCase
testReport.testPlatformList.forEach(function (testPlatform) {
testPlatform.testCaseList.forEach(function (testCase) {
if (testCase.status !== "passed") {
console.error(JSON.stringify(testCase, undefined, 4));
}
});
});
return testReport;
}...
local.cliDict["utility2.testReportCreate"] = function () {
/*
*
* will create test-report
*/
process.exit(
local.testReportCreate(
JSON.parse(local.fs.readFileSync(
local.path.resolve(
local.env.npm_config_dir_build + "/test-report.json"
),
"utf8"
))
).testsFailed !== 0
...testReportMerge = function (testReport1, testReport2) {
/*
* this function will
* 1. merge testReport2 into testReport1
* 2. return testReport1 in html-format
*/
let errorStackList;
let testCaseNumber;
let testReport;
testReport2 = testReport2 || {};
// 1. merge testReport2 into testReport1
[
testReport1, testReport2
].forEach(function (testReport, ii) {
ii += 1;
local.objectAssignDefault(testReport, {
date: new Date().toISOString(),
errorStackList: [],
testPlatformList: [],
timeElapsed: 0
}, -1);
// security - handle malformed testReport
local.assertOrThrow(
typeof testReport === "object" && testReport,
ii + " invalid testReport " + typeof testReport
);
// validate timeElapsed
local.assertOrThrow(
typeof testReport.timeElapsed === "number",
ii + " invalid testReport.timeElapsed "
+ typeof testReport.timeElapsed
);
// security - handle malformed testReport.testPlatformList
testReport.testPlatformList.forEach(function (testPlatform) {
local.objectAssignDefault(testPlatform, {
name: "undefined",
testCaseList: [],
timeElapsed: 0
}, -1);
local.assertOrThrow(
typeof testPlatform.name === "string",
ii + " invalid testPlatform.name " + typeof testPlatform.name
);
// insert $MODE_BUILD into testPlatform.name
if (local.env.MODE_BUILD) {
testPlatform.name = testPlatform.name.replace((
/^(browser|node)\b/
), local.env.MODE_BUILD + " - $1");
}
// validate timeElapsed
local.assertOrThrow(
typeof testPlatform.timeElapsed === "number",
(
ii + " invalid testPlatform.timeElapsed "
+ typeof testPlatform.timeElapsed
)
);
// security - handle malformed testPlatform.testCaseList
testPlatform.testCaseList.forEach(function (testCase) {
local.objectAssignDefault(testCase, {
errorStack: "",
name: "undefined",
timeElapsed: 0
}, -1);
local.assertOrThrow(
typeof testCase.errorStack === "string",
ii + " invalid testCase.errorStack "
+ typeof testCase.errorStack
);
local.assertOrThrow(
typeof testCase.name === "string",
ii + " invalid testCase.name " + typeof testCase.name
);
// validate timeElapsed
local.assertOrThrow(
typeof testCase.timeElapsed === "number",
(
ii + " invalid testCase.timeElapsed "
+ typeof testCase.timeElapsed
)
);
});
});
});
// merge testReport2.testPlatformList into testReport1.testPlatformList
testReport2.testPlatformList.forEach(function (testPlatform2) {
// add testPlatform2 to testReport1.testPlatformList
testReport1.testPlatformList.push(testPlatform2);
});
testReport = testReport1;
testReport.testsFailed = 0;
testReport.testsPassed = 0;
testReport.testsPending = 0;
testReport.testPlatformList.forEach(function (testPlatform) {
testPlatform.testsFailed = 0;
testPlatform.testsPassed = 0;
testPlatform.testsPending = 0;
testPlatform.testCaseList.forEach(function (testCase) {
switch (testCase......
// merge browser-screenshot
data.testPlatformList[0].screenshot = fileScreenshot.replace((
/.*\//
), "");
// merge browser-coverage
local.istanbulCoverageMerge(globalThis.__coverage__, data.coverage);
// merge browser-test-report
local.testReportMerge(globalThis.utility2_testReport, data);
// save test-report.json
onParallel.cnt += 1;
local.fs.writeFile(
local.path.resolve(
local.env.npm_config_dir_build + "/test-report.json"
),
JSON.stringify(globalThis.utility2_testReport),
...testRunBrowser = function () {
/*
* this function will run browser-tests
*/
// hide browser-tests
if (document.querySelector("#htmlTestReport1").style.maxHeight !== "0px") {
local.uiAnimateSlideUp(document.querySelector("#htmlTestReport1"));
document.querySelector(
"#buttonTestRun1"
).textContent = "run browser-tests";
return;
}
// show browser-tests
local.uiAnimateSlideDown(document.querySelector("#htmlTestReport1"));
document.querySelector(
"#buttonTestRun1"
).textContent = "hide browser-tests";
local.modeTest = 1;
local.testRunDefault(globalThis.local);
// reset output
document.querySelectorAll(".onevent-reset-output").forEach(function (elem) {
elem.textContent = "";
});
}n/a
testRunDefault = function (opt) {
/*
* this function will run tests in testPlatform.testCaseList
*/
let consoleError;
let isCoverage;
let processExit;
let testPlatform;
let testReport;
let timerInterval;
// run-server
if (!local.isBrowser) {
local.testRunServer(opt);
}
globalThis.utility2_modeTest = Number(
globalThis.utility2_modeTest
|| opt.modeTest
|| local.modeTest
|| local.env.npm_config_mode_test
);
switch (globalThis.utility2_modeTest) {
// init
case 1:
globalThis.utility2_modeTest += 1;
// reset db
globalThis.utility2_onReadyAfter(function () {
local.testRunDefault(opt);
});
return;
// test-run
default:
// test-ignore
if (
globalThis.utility2_onReadyBefore.cnt
|| !globalThis.utility2_modeTest
|| globalThis.utility2_modeTest > 2
) {
return;
}
// test-run
globalThis.utility2_modeTest += 1;
}
// visual notification - testRun
local.ajaxProgressUpdate();
// mock console.error
consoleError = console.error;
isCoverage = (
typeof globalThis.__coverage__ === "object" && globalThis.__coverage__
&& Object.keys(globalThis.__coverage__).length
);
console.error = function (...argList) {
/*
* this function will ignore serverLog-messages during test-run
*/
if (!isCoverage && !(
/^serverLog\u0020-\u0020\{/
).test(argList[0])) {
consoleError(...argList);
}
};
// mock proces.exit
if (!local.isBrowser) {
processExit = process.exit;
process.exit = local.nop;
}
// init modeTestCase
local.modeTestCase = (
local.modeTestCase
|| local.env.npm_config_mode_test_case || ""
);
// init testReport
testReport = globalThis.utility2_testReport;
// init testReport timer
local.timeElapsedStart(testReport);
// init testPlatform
testPlatform = testReport.testPlatformList[0];
// init testPlatform timer
local.timeElapsedStart(testPlatform);
// reset testPlatform.testCaseList
testPlatform.testCaseList.length = 0;
// add tests into testPlatform.testCaseList
Object.keys(opt).forEach(function (key) {
// add testCase opt[key] to testPlatform.testCaseList
if (
typeof opt[key] === "function" && (
local.modeTestCase
? local.modeTestCase.split(
/[,\s]/g
).indexOf(key) >= 0
: key.indexOf("testCase_") === 0
)
) {
testPlatform.testCaseList.push({
isBrowser: local.isBrowser,
name: key,
status: "pending",
onTestCase: opt[key]
});
}
});
local.testReportMerge(testReport);
if (local.isBrowser) {
document.querySelectorAll("#htmlTestReport1").forEach(function (elem) {
local.uiAnimateSlideDown(elem);
elem.innerHTML = local.testReportMerge(testReport);
});
}
local.emit("utility2.testRunStart", testReport);
// testRunProgressUpdate every 2000 ms until isDone
timerInterval = setInterval(function () {
// update testPlatform.timeElapsed
local.timeElapsedPoll(testPlatform);
if (local.isBrowser) {
document.querySelector(
"#htmlTestReport1"
).innerHTML = local.testReportMerge(testReport);
}
local.emit("utility2.testRunProgressUpdate", testReport);
// cleanup timerInterval
if (!testReport.testsPending) {
clearInterval(timerInterval);
}
// list pending testCase every 5000 ms
if (testPlatform.timeElapsed % 5000 < 2000) {......
// run shared js\-env code - init-before\n\
(function () {\n\
// init local\n\
local = globalThis.utility2 || require("utility2");\n\
local = local.requireReadme();\n\
globalThis.local = local;\n\
// init test\n\
local.testRunDefault(local);\n\
}());\n\
\n\
\n\
\n\
// run shared js\-env code - function\n\
(function () {\n\
return;\n\
...testRunServer = function (opt) {
/*
* this function will
* 1. create server from local.middlewareList
* 2. start server on local.env.PORT
* 3. run tests
*/
// 1. create server from local.middlewareList
local.middlewareList = local.middlewareList || [
local.middlewareInit,
local.middlewareForwardProxy,
local.middlewareAssetsCached,
local.middlewareJsonpStateInit,
local.middlewareFileServer
];
if (local.env.npm_config_mode_library || globalThis.utility2_serverHttp1) {
return;
}
globalThis.utility2_onReadyBefore.cnt += 1;
local.serverLocalReqHandler = function (req, res) {
let that;
that = {};
local.gotoNext(that, function (err) {
if (err || that.gotoState >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[that.gotoState](req, res, that.gotoNext);
});
that.gotoState = -1;
that.gotoNext();
};
globalThis.utility2_serverHttp1 = local.http.createServer(
local.serverLocalReqHandler
);
// 2. start server on local.env.PORT
console.error("http-server listening on port " + local.env.PORT);
globalThis.utility2_onReadyBefore.cnt += 1;
globalThis.utility2_serverHttp1.listen(
local.env.PORT,
globalThis.utility2_onReadyBefore
);
// 3. run tests
local.testRunDefault(opt);
globalThis.utility2_onReadyBefore();
}...
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
};
local.cliDict["utility2.testReportCreate"] = function () {
/*
*
* will create test-report
*/
...throwError = function () {
/*
* this function will throw new err
*/
throw new Error();
}...
};
local.testCase_throwError_default = function (opt, onError) {
/*
* this function will test throwError's default handling-behavior
*/
local.tryCatchOnError(function () {
local.throwError();
}, function (err) {
// handle err
local.assertOrThrow(err, err);
onError(undefined, opt);
});
};
...timeElapsedPoll = function (opt) {
/*
* this function will poll <opt>.timeElapsed
*/
opt = local.timeElapsedStart(opt);
opt.timeElapsed = Date.now() - opt.timeStart;
return opt;
}...
> bb.status.replace("passed", "z") + bb.name
? 1
: -1
);
});
// stop testReport timer
if (!testReport.testsPending) {
local.timeElapsedPoll(testReport);
}
// 2. return testReport1 in html-format
// json-copy testReport that will be modified for html templating
testReport = local.jsonCopy(testReport1);
// update timeElapsed
local.timeElapsedPoll(testReport);
testReport.testPlatformList.forEach(function (testPlatform) {
...timeElapsedStart = function (opt) {
/*
* this function will start <opt>.timeElapsed
*/
opt = opt || {};
opt.timeStart = opt.timeStart || Date.now();
return opt;
}...
local.modeTestCase = (
local.modeTestCase
|| local.env.npm_config_mode_test_case || ""
);
// init testReport
testReport = globalThis.utility2_testReport;
// init testReport timer
local.timeElapsedStart(testReport);
// init testPlatform
testPlatform = testReport.testPlatformList[0];
// init testPlatform timer
local.timeElapsedStart(testPlatform);
// reset testPlatform.testCaseList
testPlatform.testCaseList.length = 0;
// add tests into testPlatform.testCaseList
...tryCatchOnError = function (fnc, onError) {
/*
* this function will run <fnc> in tryCatch block,
* else call onError with errCaught
*/
let result;
// validate onError
local.assertOrThrow(typeof onError === "function", typeof onError);
try {
// reset errCaught
local._debugTryCatchError = null;
result = fnc();
local._debugTryCatchError = null;
return result;
} catch (errCaught) {
// debug errCaught
local._debugTryCatchError = errCaught;
return onError(errCaught);
}
}...
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
let result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
...uiAnimateSlideAccordian = function (elem, elemList, onError) {
/*
* this function will slideDown <elem>, but slideUp elements in <elemList>
*/
elemList.forEach(function (elem2) {
if (elem2 !== elem) {
local.uiAnimateSlideUp(elem2);
}
});
setTimeout(function () {
local.uiAnimateSlideDown(elem, onError);
}, 250);
}...
// show parent resource
local.uiAnimateSlideDown(element.closest(
".resource"
).querySelector(
".operationList"
));
// show the operation, but hide all other operations
local.uiAnimateSlideAccordian(
element.querySelector(
".operation > form"
),
Array.from(element.closest(
".operationList"
).querySelectorAll(
".operation > form"
...uiAnimateSlideDown = function (elem, onError) {
/*
* this function will slideDown dom-<elem>
*/
onError = onError || local.nop;
if (!(
elem
&& elem.style && elem.style.maxHeight !== "100%"
&& elem.classList && elem.classList.contains("uiAnimateSlide")
)) {
onError();
return;
}
elem.style.borderBottom = "";
elem.style.borderTop = "";
elem.style.marginBottom = "";
elem.style.marginTop = "";
elem.style.maxHeight = 1.5 * globalThis.innerHeight + "px";
elem.style.paddingBottom = "";
elem.style.paddingTop = "";
setTimeout(function () {
elem.style.maxHeight = "100%";
onError();
}, 250);
}...
".operation"
);
location.hash = "!" + element.id;
element.closest(
".resource"
).classList.remove("expanded");
// show parent resource
local.uiAnimateSlideDown(element.closest(
".resource"
).querySelector(
".operationList"
));
// show the operation, but hide all other operations
local.uiAnimateSlideAccordian(
element.querySelector(
...uiAnimateSlideUp = function (elem, onError) {
/*
* this function will slideUp dom-<elem>
*/
if (!(
elem
&& elem.style && elem.style.maxHeight !== "0px"
&& elem.classList && elem.classList.contains("uiAnimateSlide")
)) {
local.setTimeoutOnError(onError);
return;
}
elem.style.borderBottom = "0";
elem.style.borderTop = "0";
elem.style.marginBottom = "0";
elem.style.marginTop = "0";
elem.style.maxHeight = "0";
elem.style.paddingBottom = "0";
elem.style.paddingTop = "0";
local.setTimeoutOnError(onError, 250);
}...
);
// collapse all operations in the resource
if (evt.currentTarget.classList.contains("expanded")) {
evt.currentTarget.classList.remove("expanded");
Array.from(evt.currentTarget.querySelectorAll(
".operation > form"
)).forEach(function (element) {
local.uiAnimateSlideUp(element);
});
// expand all operations in the resource
} else {
evt.currentTarget.classList.add("expanded");
Array.from(evt.currentTarget.querySelectorAll(
".operation > form"
)).forEach(function (element) {
...urlJoin = function (aa, bb) {
/*
* this function will if bb is relative, url-join aa with bb
*/
// bb is absolute-url
if ((
/^\w+?:\/\//
).test(bb)) {
return bb;
}
// bb is absolute-url without protocol
if (bb.slice(0, 2) === "//") {
return aa.split("/")[0] + bb;
}
// bb is absolute-url without host
if (bb[0] === "/") {
return aa.split("/").slice(0, 3).join("/") + bb;
}
// bb is relative-url
if (aa.split("/").length < 4) {
aa += "/";
}
return aa.replace((
/[?#].*?$/
), "").replace((
/[^\/]*?$/
), "") + bb;
}...
onError(undefined, opt);
};
local.testCase_urlJoin_default = function (opt, onError) {
/*
* this function will test urlJoin's default handling-behavior
*/
local.assertJsonEqual(local.urlJoin("", ""), "/");
local.assertJsonEqual(local.urlJoin("http://aa/bb", "zz"), "http://aa/zz");
local.assertJsonEqual(
local.urlJoin("http://aa/bb/", "zz"),
"http://aa/bb/zz"
);
local.assertJsonEqual(
local.urlJoin("http://aa/bb/", "/zz"),
...urlParse = function (url) {
/*
* this function will parse <url> according to below spec, plus a query param
* https://developer.mozilla.org/en-US/docs/Web/API/URL
*/
let urlParsed;
urlParsed = {};
// try to parse url
local.tryCatchOnError(function () {
// resolve host-less url
if (local.isBrowser) {
local.serverLocalHost = (
local.serverLocalHost
|| location.protocol + "//" + location.host
);
// resolve absolute path
if (url[0] === "/") {
url = local.serverLocalHost + url;
// resolve relative path
} else if (!(
/^\w+?:\/\//
).test(url)) {
url = (
local.serverLocalHost
+ location.pathname.replace((
/\/[^\/]*?$/
), "") + "/" + url
);
}
urlParsed = new globalThis.URL(url);
urlParsed.path = (
"/" + urlParsed.href.split("/").slice(3).join("/").split("#")[0]
);
} else {
local.env.PORT = local.env.PORT || "8081";
local.serverLocalHost = (
local.serverLocalHost
|| ("http://127.0.0.1:" + local.env.PORT)
);
// resolve absolute path
if (url[0] === "/") {
url = local.serverLocalHost + url;
// resolve relative path
} else if (!(
/^\w+?:\/\//
).test(url)) {
url = local.serverLocalHost + "/" + url;
}
urlParsed = local.url.parse(url);
}
// init query
urlParsed.query = {};
local.coalesce(urlParsed.search, "").slice(1).replace((
/[^&]+/g
), function (item) {
item = item.split("=");
item[0] = decodeURIComponent(item[0]);
item[1] = decodeURIComponent(item.slice(1).join("="));
// parse repeating query-param as an array
if (urlParsed.query[item[0]]) {
if (!Array.isArray(urlParsed.query[item[0]])) {
urlParsed.query[item[0]] = [
urlParsed.query[item[0]]
];
}
urlParsed.query[item[0]].push(item[1]);
} else {
urlParsed.query[item[0]] = item[1];
}
return "";
});
urlParsed.basename = urlParsed.pathname.replace((
/^.*\//
), "");
}, local.nop);
// https://developer.mozilla.org/en/docs/Web/API/URL#Properties
return {
basename: urlParsed.basename || "",
hash: urlParsed.hash || "",
host: urlParsed.host || "",
hostname: urlParsed.hostname || "",
href: urlParsed.href || "",
path: urlParsed.path || "",
pathname: urlParsed.pathname || "",
port: urlParsed.port || "",
protocol: urlParsed.protocol || "",
query: urlParsed.query || {},
search: urlParsed.search || ""
};
}...
);
}
// init url
opt.url = "";
opt.url += (
local.identity(
that["x-swgg-schemes"] || local.swaggerJson.schemes || []
)[0] || local.urlParse("").protocol.slice(0, -1)
);
opt.url += "://";
opt.url += (
that["x-swgg-host"]
|| local.swaggerJson.host
|| local.urlParse("").host
);
...uuid4Create = function () {
/*
* this function will create a random uuid,
* with format 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
*/
// code derived from http://jsperf.com/uuid4
let id;
let ii;
id = "";
ii = 0;
while (ii < 32) {
switch (ii) {
case 8:
case 20:
id += "-";
// coerce to finite integer
id += local.identity((Math.random() * 16) | 0).toString(16);
break;
case 12:
id += "-";
id += "4";
break;
case 16:
id += "-";
id += local.identity((Math.random() * 4) | 8).toString(16);
break;
default:
// coerce to finite integer
id += local.identity((Math.random() * 16) | 0).toString(16);
}
ii += 1;
}
return id;
}...
};
local.testCase_uuid4Create_default = function (opt, onError) {
/*
* this function will test uuid4Create's default handling-behavior
*/
local.assertOrThrow(
local.regexpValidateUuid.test(local.uuid4Create()),
local.uuid4Create()
);
onError(undefined, opt);
};
local.testCase_webpage_err = function (opt, onError) {
/*
...FormData = function () {
/*
* this function will create a serverLocal-compatible FormData instance
* The FormData(form) constructor must run these steps:
* 1. Let fd be a new FormData object.
* 2. If form is given, set fd's entries to the result
* of constructing the form data set for form. (not implemented)
* 3. Return fd.
* https://xhr.spec.whatwg.org/#dom-formdata
*/
this.entryList = [];
}...
parameters: that.parameters,
swaggerJson: local.swaggerJson
})[0];
// init default
local.objectSetDefault(opt, {
inForm: (
that._consumes0 === "multipart/form-data"
? new local.FormData()
: ""
),
inHeader: {},
inPath: that._path.replace((
/#.*?$/
), ""),
inQuery: "",
...append = function (name, value, filename) {
/*
* The append(name, value, filename) method, when invoked, must run these steps:
* 1. If the filename argument is given, set value to a new File object
* whose contents are value and name is filename.
* 2. Append a new entry whose name is name, and value is value,
* to context object's list of entries.
* https://xhr.spec.whatwg.org/#dom-formdata-append
*/
if (filename) {
// bug-workaround - chromium cannot assign name to Blob instance
local.tryCatchOnError(function () {
value.name = filename;
}, local.nop);
}
this.entryList.push({
name,
value
});
}...
"\n<" + schemaP.name + ">" + "<![CDATA["
+ tmp.replace((
/\]\]>/g
), "]]>") + "]]></" + schemaP.name + ">"
);
break;
case "multipart/form-data":
opt.inForm.append(schemaP.name, tmp, tmp && tmp.name);
break;
default:
if (opt.inForm) {
opt.inForm += "&";
}
opt.inForm += (
encodeURIComponent(schemaP.name) + "="
...read = function (onError) {
/*
* this function will read from formData as a buffer, e.g.
* --Boundary\r\n
* Content-Disposition: form-data; name="key"\r\n
* \r\n
* value\r\n
* --Boundary\r\n
* Content-Disposition: form-data; name="input1"; filename="file1.png"\r\n
* Content-Type: image/jpeg\r\n
* \r\n
* <data1>\r\n
* --Boundary\r\n
* Content-Disposition: form-data; name="input2"; filename="file2.png"\r\n
* Content-Type: image/jpeg\r\n
* \r\n
* <data2>\r\n
* --Boundary--\r\n
* https://tools.ietf.org/html/rfc7578
*/
let boundary;
let result;
// handle null-case
if (!this.entryList.length) {
onError();
return;
}
// init boundary
boundary = "--" + Date.now().toString(16) + Math.random().toString(16);
// init result
result = [];
local.onParallelList({
list: this.entryList
}, function (opt2, onParallel) {
let value;
value = opt2.elem.value;
if (!(value && value.constructor === local.Blob)) {
result[opt2.ii] = [
(
boundary + "\r\nContent-Disposition: form-data; name=\""
+ opt2.elem.name + "\"\r\n\r\n"
), value, "\r\n"
];
onParallel.cnt += 1;
onParallel();
return;
}
// read from blob in parallel
onParallel.cnt += 1;
local.blobRead(value, function (err, data) {
result[opt2.ii] = !err && [
(
boundary + "\r\nContent-Disposition: form-data; name=\""
+ opt2.elem.name + "\"" + (
(value && value.name)
// read param filename
? "; filename=\"" + value.name + "\""
: ""
) + "\r\n" + (
(value && value.type)
// read param Content-Type
? "Content-Type: " + value.type + "\r\n"
: ""
) + "\r\n"
), data, "\r\n"
];
onParallel(err);
});
}, function (err) {
// add closing boundary
result.push([
boundary + "--\r\n"
]);
// concatenate result
onError(
err,
// flatten result
!err
&& local.bufferConcat(result.flat())
);
});
}...
var c,
reader = this._reader,
token = null,
startLine = reader.getLine(),
startCol = reader.getCol();
c = reader.read();
while (c) {
switch (c) {
/*
* Potential tokens:
* - COMMENT
...function Module(id = '', parent) {
this.id = id;
this.path = path.dirname(id);
this.exports = {};
this.parent = parent;
updateChildren(parent, this, false);
this.filename = null;
this.loaded = false;
this.children = [];
}...
// init example.js
tmp = local.path.resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
);
...class SourceMap {
#payload;
#mappings = [];
#sources = {};
#sourceContentByURL = {};
/**
* @constructor
* @param {SourceMapV3} payload
*/
constructor(payload) {
if (!base64Map) {
const base64Digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
base64Map = {};
for (let i = 0; i < base64Digits.length; ++i)
base64Map[base64Digits[i]] = i;
}
this.#payload = cloneSourceMapV3(payload);
this.#parseMappingPayload();
}
/**
* @return {Object} raw source map v3 payload.
*/
get payload() {
return cloneSourceMapV3(this.#payload);
}
/**
* @param {SourceMapV3} mappingPayload
*/
#parseMappingPayload = () => {
if (this.#payload.sections) {
this.#parseSections(this.#payload.sections);
} else {
this.#parseMap(this.#payload, 0, 0);
}
this.#mappings.sort(compareSourceMapEntry);
}
/**
* @param {Array.<SourceMapV3.Section>} sections
*/
#parseSections = (sections) => {
for (let i = 0; i < sections.length; ++i) {
const section = sections[i];
this.#parseMap(section.map, section.offset.line, section.offset.column);
}
}
/**
* @param {number} lineNumber in compiled resource
* @param {number} columnNumber in compiled resource
* @return {?Array}
*/
findEntry(lineNumber, columnNumber) {
let first = 0;
let count = this.#mappings.length;
while (count > 1) {
const step = count >> 1;
const middle = first + step;
const mapping = this.#mappings[middle];
if (lineNumber < mapping[0] ||
(lineNumber === mapping[0] && columnNumber < mapping[1])) {
count = step;
} else {
first = middle;
count -= step;
}
}
const entry = this.#mappings[first];
if (!first && entry && (lineNumber < entry[0] ||
(lineNumber === entry[0] && columnNumber < entry[1]))) {
return {};
} else if (!entry) {
return {};
}
return {
generatedLine: entry[0],
generatedColumn: entry[1],
originalSource: entry[2],
originalLine: entry[3],
originalColumn: entry[4]
};
}
/**
* @override
*/
#parseMap = (map, lineNumber, columnNumber) => {
let sourceIndex = 0;
let sourceLineNumber = 0;
let sourceColumnNumber = 0;
const sources = [];
const originalToCanonicalURLMap = {};
for (let i = 0; i < map.sources.length; ++i) {
const url = map.sources[i];
originalToCanonicalURLMap[url] = url;
sources.push(url);
this.#sources[url] = true;
if (map.sourcesContent && map.sourcesContent[i])
this.#sourceContentByURL[url] = map.sourcesContent[i];
}
const stringCharIterator = new StringCharIterator(map.mappings);
let sourceURL = sources[sourceIndex];
while (true) {
if (stringCharIterator.peek() === ',')
stringCharIterator.next();
else {
while (stringCharIterator.peek() === ';') {
lineNumber += 1;
columnNumber = 0;
stringCharIterator.next();
}
if (!stringCharIterator.hasNext())
break;
}
columnNumber += decodeVLQ(stringCharIterator);
if (isSeparator(stringCharIterator.peek())) {
this.#mappings.push([lineNumber, columnNumber]);
continue;
}
const sourceIndexDelta = decodeVLQ(stringCharIterator);
if (sourceIndexDelta) {
sourceIndex += sourceIndexDelta;
sourceURL = sources[sourceIndex];
}
sourceLineNumber += decodeVLQ(stringCharIterator);
sourceColumnNumber += decodeVLQ(stringCharIterator);
if (!isSeparator(stringCharIterator.peek()))
// Unused index into the names list.
decodeVLQ(stringCharIterator);
this.#mappings.push([lineNumber, columnNumber, sourceURL,
sourceLineNumber, sourceColumnNumber])...n/a
function deprecated(...args) {
if (!warned) {
warned = true;
if (code !== undefined) {
if (!codesWarned.has(code)) {
process.emitWarning(msg, 'DeprecationWarning', code, deprecated);
codesWarned.add(code);
}
} else {
process.emitWarning(msg, 'DeprecationWarning', deprecated);
}
}
if (new.target) {
return ReflectConstruct(fn, args, new.target);
}
return fn.apply(this, args);
}n/a
function(request, paths, isMain) {
const absoluteRequest = path.isAbsolute(request);
if (absoluteRequest) {
paths = [''];
} else if (!paths || paths.length === 0) {
return false;
}
const cacheKey = request + '\x00' +
(paths.length === 1 ? paths[0] : paths.join('\x00'));
const entry = Module._pathCache[cacheKey];
if (entry)
return entry;
let exts;
let trailingSlash = request.length > 0 &&
request.charCodeAt(request.length - 1) === CHAR_FORWARD_SLASH;
if (!trailingSlash) {
trailingSlash = RegExpPrototypeTest(trailingSlashRegex, request);
}
// For each path
for (let i = 0; i < paths.length; i++) {
// Don't search further if path doesn't exist
const curPath = paths[i];
if (curPath && stat(curPath) < 1) continue;
if (!absoluteRequest) {
const exportsResolved = resolveExports(curPath, request);
// Undefined means not found, false means no exports
if (exportsResolved === undefined)
break;
if (exportsResolved) {
return exportsResolved;
}
}
const basePath = path.resolve(curPath, request);
let filename;
const rc = stat(basePath);
if (!trailingSlash) {
if (rc === 0) { // File.
if (!isMain) {
if (preserveSymlinks) {
filename = path.resolve(basePath);
} else {
filename = toRealPath(basePath);
}
} else if (preserveSymlinksMain) {
// For the main module, we use the preserveSymlinksMain flag instead
// mainly for backward compatibility, as the preserveSymlinks flag
// historically has not applied to the main module. Most likely this
// was intended to keep .bin/ binaries working, as following those
// symlinks is usually required for the imports in the corresponding
// files to resolve; that said, in some use cases following symlinks
// causes bigger problems which is why the preserveSymlinksMain option
// is needed.
filename = path.resolve(basePath);
} else {
filename = toRealPath(basePath);
}
}
if (!filename) {
// Try it with each of the extensions
if (exts === undefined)
exts = ObjectKeys(Module._extensions);
filename = tryExtensions(basePath, exts, isMain);
}
}
if (!filename && rc === 1) { // Directory.
// try it with each of the extensions at "index"
if (exts === undefined)
exts = ObjectKeys(Module._extensions);
filename = tryPackage(basePath, exts, isMain, request);
}
if (filename) {
Module._pathCache[cacheKey] = filename;
return filename;
}
}
return false;
}n/a
function() {
const homeDir = isWindows ? process.env.USERPROFILE : safeGetenv('HOME');
const nodePath = isWindows ? process.env.NODE_PATH : safeGetenv('NODE_PATH');
// process.execPath is $PREFIX/bin/node except on Windows where it is
// $PREFIX\node.exe where $PREFIX is the root of the Node.js installation.
const prefixDir = isWindows ?
path.resolve(process.execPath, '..') :
path.resolve(process.execPath, '..', '..');
let paths = [path.resolve(prefixDir, 'lib', 'node')];
if (homeDir) {
paths.unshift(path.resolve(homeDir, '.node_libraries'));
paths.unshift(path.resolve(homeDir, '.node_modules'));
}
if (nodePath) {
paths = nodePath.split(path.delimiter).filter(function pathsFilterCB(path) {
return !!path;
}).concat(paths);
}
modulePaths = paths;
// Clone as a shallow copy, for introspection.
Module.globalPaths = modulePaths.slice(0);
}n/a
function(request, parent, isMain) {
let relResolveCacheIdentifier;
if (parent) {
debug('Module._load REQUEST %s parent: %s', request, parent.id);
// Fast path for (lazy loaded) modules in the same directory. The indirect
// caching is required to allow cache invalidation without changing the old
// cache key names.
relResolveCacheIdentifier = `${parent.path}\x00${request}`;
const filename = relativeResolveCache[relResolveCacheIdentifier];
if (filename !== undefined) {
const cachedModule = Module._cache[filename];
if (cachedModule !== undefined) {
updateChildren(parent, cachedModule, true);
if (!cachedModule.loaded)
return getExportsForCircularRequire(cachedModule);
return cachedModule.exports;
}
delete relativeResolveCache[relResolveCacheIdentifier];
}
}
const filename = Module._resolveFilename(request, parent, isMain);
const cachedModule = Module._cache[filename];
if (cachedModule !== undefined) {
updateChildren(parent, cachedModule, true);
if (!cachedModule.loaded)
return getExportsForCircularRequire(cachedModule);
return cachedModule.exports;
}
const mod = loadNativeModule(filename, request);
if (mod && mod.canBeRequiredByUsers) return mod.exports;
// Don't call updateChildren(), Module constructor already does.
const module = new Module(filename, parent);
if (isMain) {
process.mainModule = module;
module.id = '.';
}
Module._cache[filename] = module;
if (parent !== undefined) {
relativeResolveCache[relResolveCacheIdentifier] = filename;
}
let threw = true;
try {
// Intercept exceptions that occur during the first tick and rekey them
// on error instance rather than module instance (which will immediately be
// garbage collected).
if (enableSourceMaps) {
try {
module.load(filename);
} catch (err) {
rekeySourceMap(Module._cache[filename], err);
throw err; /* node-do-not-add-exception-line */
}
} else {
module.load(filename);
}
threw = false;
} finally {
if (threw) {
delete Module._cache[filename];
if (parent !== undefined) {
delete relativeResolveCache[relResolveCacheIdentifier];
const children = parent && parent.children;
if (ArrayIsArray(children)) {
const index = children.indexOf(module);
if (index !== -1) {
children.splice(index, 1);
}
}
}
} else if (module.exports &&
!isProxy(module.exports) &&
ObjectGetPrototypeOf(module.exports) ===
CircularRequirePrototypeWarningProxy) {
ObjectSetPrototypeOf(module.exports, PublicObjectPrototype);
}
}
return module.exports;
}n/a
function(from) {
// Guarantee that 'from' is absolute.
from = path.resolve(from);
// Return early not only to avoid unnecessary work, but to *avoid* returning
// an array of two items for a root: [ '//node_modules', '/node_modules' ]
if (from === '/')
return ['/node_modules'];
// note: this approach *only* works when the path is guaranteed
// to be absolute. Doing a fully-edge-case-correct path.split
// that works on both Windows and Posix is non-trivial.
const paths = [];
for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
const code = from.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
if (p !== nmLen)
paths.push(from.slice(0, last) + '/node_modules');
last = i;
p = 0;
} else if (p !== -1) {
if (nmChars[p] === code) {
++p;
} else {
p = -1;
}
}
}
// Append /node_modules to handle root paths.
paths.push('/node_modules');
return paths;
}n/a
function(requests) {
if (!ArrayIsArray(requests))
return;
// Preloaded modules have a dummy parent module which is deemed to exist
// in the current working directory. This seeds the search path for
// preloaded modules.
const parent = new Module('internal/preload', null);
try {
parent.paths = Module._nodeModulePaths(process.cwd());
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
for (let n = 0; n < requests.length; n++)
parent.require(requests[n]);
}n/a
function(request, parent, isMain, options) {
if (NativeModule.canBeRequiredByUsers(request)) {
return request;
}
let paths;
if (typeof options === 'object' && options !== null) {
if (ArrayIsArray(options.paths)) {
const isRelative = request.startsWith('./') ||
request.startsWith('../') ||
((isWindows && request.startsWith('.\\')) ||
request.startsWith('..\\'));
if (isRelative) {
paths = options.paths;
} else {
const fakeParent = new Module('', null);
paths = [];
for (let i = 0; i < options.paths.length; i++) {
const path = options.paths[i];
fakeParent.paths = Module._nodeModulePaths(path);
const lookupPaths = Module._resolveLookupPaths(request, fakeParent);
for (let j = 0; j < lookupPaths.length; j++) {
if (!paths.includes(lookupPaths[j]))
paths.push(lookupPaths[j]);
}
}
}
} else if (options.paths === undefined) {
paths = Module._resolveLookupPaths(request, parent);
} else {
throw new ERR_INVALID_OPT_VALUE('options.paths', options.paths);
}
} else {
paths = Module._resolveLookupPaths(request, parent);
}
if (parent && parent.filename) {
const filename = trySelf(parent.filename, request);
if (filename) {
const cacheKey = request + '\x00' +
(paths.length === 1 ? paths[0] : paths.join('\x00'));
Module._pathCache[cacheKey] = filename;
return filename;
}
}
// Look up the filename first, since that's the cache key.
const filename = Module._findPath(request, paths, isMain, false);
if (filename) return filename;
const requireStack = [];
for (let cursor = parent;
cursor;
cursor = cursor.parent) {
requireStack.push(cursor.filename || cursor.id);
}
let message = `Cannot find module '${request}'`;
if (requireStack.length > 0) {
message = message + '\nRequire stack:\n- ' + requireStack.join('\n- ');
}
// eslint-disable-next-line no-restricted-syntax
const err = new Error(message);
err.code = 'MODULE_NOT_FOUND';
err.requireStack = requireStack;
throw err;
}n/a
function(request, parent) {
if (NativeModule.canBeRequiredByUsers(request)) {
debug('looking for %j in []', request);
return null;
}
// Check for node modules paths.
if (request.charAt(0) !== '.' ||
(request.length > 1 &&
request.charAt(1) !== '.' &&
request.charAt(1) !== '/' &&
(!isWindows || request.charAt(1) !== '\\'))) {
let paths = modulePaths;
if (parent != null && parent.paths && parent.paths.length) {
paths = parent.paths.concat(paths);
}
debug('looking for %j in %j', request, paths);
return paths.length > 0 ? paths : null;
}
// In REPL, parent.filename is null.
if (!parent || !parent.id || !parent.filename) {
// Make require('./path/to/foo') work - normally the path is taken
// from realpath(__filename) but in REPL there is no filename
const mainPaths = ['.'];
debug('looking for %j in %j', request, mainPaths);
return mainPaths;
}
debug('RELATIVE: requested: %s from parent.id %s', request, parent.id);
const parentDir = [path.dirname(parent.filename)];
debug('looking for %j', parentDir);
return parentDir;
}n/a
function createRequire(filename) {
let filepath;
if (filename instanceof URL ||
(typeof filename === 'string' && !path.isAbsolute(filename))) {
try {
filepath = fileURLToPath(filename);
} catch {
throw new ERR_INVALID_ARG_VALUE('filename', filename,
createRequireError);
}
} else if (typeof filename !== 'string') {
throw new ERR_INVALID_ARG_VALUE('filename', filename, createRequireError);
} else {
filepath = filename;
}
return createRequireFromPath(filepath);
}n/a
function deprecated(...args) {
if (!warned) {
warned = true;
if (code !== undefined) {
if (!codesWarned.has(code)) {
process.emitWarning(msg, 'DeprecationWarning', code, deprecated);
codesWarned.add(code);
}
} else {
process.emitWarning(msg, 'DeprecationWarning', deprecated);
}
}
if (new.target) {
return ReflectConstruct(fn, args, new.target);
}
return fn.apply(this, args);
}n/a
function findSourceMap(uri, error) {
if (!Module) Module = require('internal/modules/cjs/loader').Module;
if (!SourceMap) {
SourceMap = require('internal/source_map/source_map').SourceMap;
}
let sourceMap = cjsSourceMapCache.get(Module._cache[uri]);
if (!uri.startsWith('file://')) uri = normalizeReferrerURL(uri);
if (sourceMap === undefined) {
sourceMap = esmSourceMapCache.get(uri);
}
if (sourceMap === undefined) {
const candidateSourceMap = cjsSourceMapCache.get(error);
if (candidateSourceMap && uri === candidateSourceMap.filename) {
sourceMap = candidateSourceMap;
}
}
if (sourceMap && sourceMap.data) {
return new SourceMap(sourceMap.data);
}
return undefined;
}n/a
function executeUserEntryPoint(main = process.argv[1]) {
const resolvedMain = resolveMainPath(main);
const useESMLoader = shouldUseESMLoader(resolvedMain);
if (useESMLoader) {
runMainESM(resolvedMain || main);
} else {
// Module._load is the monkey-patchable CJS module loader.
Module._load(main, null, true);
}
}...
process.argv.splice(1, 1, __dirname + "/lib.istanbul.js", "cover");
local.istanbul.cliDict[process.argv[2]]();
return;
}
// start
process.argv.splice(1, 1);
process.argv[1] = local.path.resolve(process.argv[1]);
local.Module.runMain();
}
// runme
if (local.env.npm_config_runme) {
require(local.path.resolve(local.env.npm_config_runme));
}
}());
}());
...function syncBuiltinESMExports() {
for (const mod of NativeModule.map.values()) {
if (mod.canBeRequiredByUsers) {
mod.syncExports();
}
}
}n/a
function(content, filename) {
let moduleURL;
let redirects;
if (manifest) {
moduleURL = pathToFileURL(filename);
redirects = manifest.getRedirector(moduleURL);
manifest.assertIntegrity(moduleURL, content);
}
maybeCacheSourceMap(filename, content, this);
const compiledWrapper = wrapSafe(filename, content, this);
let inspectorWrapper = null;
if (getOptionValue('--inspect-brk') && process._eval == null) {
if (!resolvedArgv) {
// We enter the repl if we're not given a filename argument.
if (process.argv[1]) {
try {
resolvedArgv = Module._resolveFilename(process.argv[1], null, false);
} catch {
// We only expect this codepath to be reached in the case of a
// preloaded module (it will fail earlier with the main entry)
assert(ArrayIsArray(getOptionValue('--require')));
}
} else {
resolvedArgv = 'repl';
}
}
// Set breakpoint on module start
if (resolvedArgv && !hasPausedEntry && filename === resolvedArgv) {
hasPausedEntry = true;
inspectorWrapper = internalBinding('inspector').callAndPauseOnStart;
}
}
const dirname = path.dirname(filename);
const require = makeRequireFunction(this, redirects);
let result;
const exports = this.exports;
const thisValue = exports;
const module = this;
if (requireDepth === 0) statCache = new Map();
if (inspectorWrapper) {
result = inspectorWrapper(compiledWrapper, thisValue, exports,
require, module, filename, dirname);
} else {
result = compiledWrapper.call(thisValue, exports, require, module,
filename, dirname);
}
hasLoadedAnyUserCJSModule = true;
if (requireDepth === 0) statCache = null;
return result;
}...
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
);
// init assets lib.xxx.js
local.assetsDict[
...function(filename) {
debug('load %j for module %j', filename, this.id);
assert(!this.loaded);
this.filename = filename;
this.paths = Module._nodeModulePaths(path.dirname(filename));
const extension = findLongestRegisteredExtension(filename);
// allow .mjs to be overridden
if (filename.endsWith('.mjs') && !Module._extensions['.mjs']) {
throw new ERR_REQUIRE_ESM(filename);
}
Module._extensions[extension](this, filename);
this.loaded = true;
const ESMLoader = asyncESM.ESMLoader;
const url = `${pathToFileURL(filename)}`;
const module = ESMLoader.moduleMap.get(url);
// Create module entry at load time to snapshot exports correctly
const exports = this.exports;
// Called from cjs translator
if (module !== undefined && module.module !== undefined) {
if (module.module.getStatus() >= kInstantiated)
module.module.setExport('default', exports);
} else {
// Preemptively cache
// We use a function to defer promise creation for async hooks.
ESMLoader.moduleMap.set(
url,
// Module job creation will start promises.
// We make it a function to lazily trigger those promises
// for async hooks compatibility.
() => new ModuleJob(ESMLoader, url, () =>
new ModuleWrap(url, undefined, ['default'], function() {
this.setExport('default', exports);
})
, false /* isMain */, false /* inspectBrk */)
);
}
}n/a
function(id) {
validateString(id, 'id');
if (id === '') {
throw new ERR_INVALID_ARG_VALUE('id', id,
'must be a non-empty string');
}
requireDepth++;
try {
return Module._load(id, this, /* isMain */ false);
} finally {
requireDepth--;
}
}...
}).slice(0, 256).map(readExample);
// init moduleMain
local.tryCatchOnError(function () {
console.error("apidocCreate - requiring " + opt.dir + " ...");
moduleMain = {};
moduleMain = (
opt.moduleDict[opt.env.npm_package_name]
|| opt.require(opt.dir)
|| opt.require(
opt.dir + "/"
+ (opt.packageJson.bin)[Object.keys(opt.packageJson.bin)[0]]
) || {}
);
opt.circularSet.add(moduleMain);
console.error("apidocCreate - ... required " + opt.dir);
...createServer = function () {
/*
* this function will emulate in browser, node's http.createServer function
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_http_createserver_requestlistener
*/
return {
listen: function (port, onError) {
onError(undefined, port);
}
};
}...
if (options.port == null && !options.server && !options.noServer) {
throw new TypeError(
'One of the "port", "server", or "noServer" options must be specified'
);
}
if (options.port != null) {
this._server = http.createServer((req, res) => {
const body = http.STATUS_CODES[426];
res.writeHead(426, {
'Content-Length': body.length,
'Content-Type': 'text/plain'
});
res.end(body);
...request = function (xhr, onResponse) {
/*
* this function will emulate in browser, node's http.request function
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_http_request_options_callback
*/
let bufList;
let data;
let handler;
let isDone;
let req;
let res;
xhr = {
end: function (_data) {
if (isDone) {
return;
}
isDone = true;
data = _data;
// async send req from client to server
setTimeout(function () {
local.serverLocalReqHandler(req, res);
});
},
headers: xhr.headers,
method: xhr.method,
on: function () {
return xhr;
},
timeout: xhr.timeout,
url: xhr.href
};
bufList = [];
handler = new globalThis.EventTarget();
req = {
emit: function (type, data) {
handler.dispatchEvent(new globalThis.CustomEvent("req." + type, {
detail: data
}));
},
headers: xhr.headers,
httpVersion: "1.1",
method: xhr.method,
on: function (type, onEvent) {
handler.addEventListener("req." + type, function (evt) {
onEvent(evt.detail);
});
if (req.readable && type === "end") {
req.readable = null;
req.emit("data", data);
req.emit("end");
}
return req;
},
pipe: function (writable) {
req.on("data", function (buf) {
writable.write(buf);
});
req.on("end", function () {
writable.end();
});
return writable;
},
readable: true,
url: xhr.url
};
res = {
emit: function (type, data) {
handler.dispatchEvent(new globalThis.CustomEvent("res." + type, {
detail: data
}));
},
end: function (data) {
if (res._isDone) {
return;
}
res._isDone = true;
bufList.push(data);
// notify server res is finished
res.emit("finish");
// pass res to client
onResponse(res);
res.emit("data", local.bufferConcat(bufList));
res.emit("end");
},
on: function (type, onEvent) {
handler.addEventListener("res." + type, function (evt) {
onEvent(evt.detail);
});
return res;
},
setHeader: function (key, val) {
xhr.resHeaders[key.toLowerCase()] = val;
},
statusCode: 200,
write: function (data) {
bufList.push(data);
}
};
return xhr;
}...
}
// node - request
errStack = new Error().stack;
request = require(
url.indexOf("https:") === 0
? "https"
: "http"
).request(url, opt, function (aa) {
response = aa;
let bufList;
// handle err
response.on("error", reject2);
// handle stream
if (opt.responseType === "stream") {
resolve2(response);
...apidocCreate = function (opt) {
/*
* this function will create the apidoc from <opt>.dir
*/
let elemCreate;
let module;
let moduleMain;
let readExample;
let tmp;
let toString;
let trimStart;
elemCreate = function (module, prefix, key) {
/*
* this function will create the apidoc-elem in given <module>
*/
let elem;
if (opt.modeNoApidoc) {
return elem;
}
elem = {};
elem.moduleName = prefix.split(".");
// handle case where module is a function
if (elem.moduleName.slice(-1)[0] === key) {
elem.moduleName.pop();
}
elem.moduleName = elem.moduleName.join(".");
elem.id = encodeURIComponent("apidoc.elem." + prefix + "." + key);
elem.typeof = typeof module[key];
elem.name = (
elem.typeof + " <span class=\"apidocSignatureSpan\">"
+ elem.moduleName + ".</span>" + key
);
// handle case where module is a function
elem.name = elem.name.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimStart(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
), "").replace((
/,/g
), ", ").replace((
/\s+/g
), " ");
return elem.signature;
}).replace((
/(\u0020*?\/\*[\S\s]*?\*\/\n)/
), "<span class=\"apidocCodeCommentSpan\">$1</span>").replace((
/^function\u0020\(/
), key + " = function (");
// init example
opt.exampleList.some(function (example) {
example.replace(
new RegExp("((?:\n.*?){8}\\.)(" + key + ")(\\((?:.*?\n){8})"),
function (ignore, match1, match2, match3) {
elem.example = "..." + trimStart(
local.stringHtmlSafe(match1)
+ "<span class=\"apidocCodeKeywordSpan\">"
+ local.stringHtmlSafe(match2)
+ "</span>"
+ local.stringHtmlSafe(match3)
).trimEnd() + "\n...";
return "";
}
);
return elem.example;
});
elem.example = elem.example || "n/a";
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
let result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
+ "\n\n\n\n\n\n\n\n"
).replace((
/\r\n*/g
), "\n");
}, console.error);
return result;
};
toString = function (value) {
/*
* this function will try to return the string form of the value
*/
let result;
local.tryCatchOnError(function () {
result = "";
result = String(value);
}, console.error);
return result;
};
trimStart = function (str) {
/*......
local.cliDict._default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
...apidocModuleDictAdd = function (opt, moduleDict) {
/*
* this function will add the modules in <moduleDict> to <opt>.moduleDict
*/
let isModule;
let objectKeys;
let tmp;
objectKeys = function (dict) {
/*
* this function will return a list of the dict's keys, with valid getters
*/
return Object.keys(dict).sort().filter(function (key) {
return local.tryCatchOnError(function () {
return dict[key] || true;
}, local.nop);
});
};
[
"child", "prototype", "grandchild", "prototype"
].forEach(function (elem) {
objectKeys(moduleDict).forEach(function (prefix) {
if (!(
/^\w[\w\-.]*?$/
).test(prefix)) {
return;
}
objectKeys(moduleDict[prefix]).forEach(function (key) {
if (!(
/^\w[\w\-.]*?$/
).test(key) || !moduleDict[prefix][key]) {
return;
}
tmp = (
elem === "prototype"
? {
module: moduleDict[prefix][key].prototype,
name: prefix + "." + key + ".prototype"
}
: {
module: moduleDict[prefix][key],
name: prefix + "." + key
}
);
if (
!tmp.module
|| !(
typeof tmp.module === "function"
|| typeof tmp.module === "object"
)
|| Array.isArray(tmp.module)
|| opt.moduleDict[tmp.name]
|| opt.circularSet.has(tmp.module)
) {
return;
}
isModule = Array.from([
tmp.module,
tmp.module.prototype
]).some(function (dict) {
return objectKeys(dict || {}).some(function (key) {
return typeof dict[key] === "function";
});
});
if (!isModule) {
return;
}
opt.circularSet.add(tmp.module);
opt.moduleDict[tmp.name] = tmp.module;
});
});
});
}...
opt.circularSet.add(opt.moduleDict[key]);
});
// init circularSet - prototype
opt.circularSet.forEach(function (elem) {
opt.circularSet.add(elem && elem.prototype);
});
// init moduleDict child
local.apidocModuleDictAdd(opt, opt.moduleDict);
// init moduleExtraDict
opt.moduleExtraDict[opt.env.npm_package_name] = (
opt.moduleExtraDict[opt.env.npm_package_name] || {}
);
module = opt.moduleExtraDict[opt.env.npm_package_name];
([
1, 2, 3, 4
...function ok(...args) {
innerOk(ok, args.length, ...args);
}...
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
...assertOrThrow = function (passed, msg) {
/*
* this function will throw err.<msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is a string, then leave as is
? msg
// else JSON.stringify msg
: JSON.stringify(msg, undefined, 4)
)
);
}...
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...cliRun = function (opt) {
/*
* this function will run cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
strDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " &quo......
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...coalesce = function (...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== null && arg !== undefined && arg !== "") {
break;
}
ii += 1;
}
return arg;
}...
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
...function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
}n/a
fsReadFileOrDefaultSync = function (pathname, type, dflt) {
/*
* this function will sync-read <pathname> with given <type> and <dflt>
*/
let fs;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
}...
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "
;")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
...fsRmrfSync = function (pathname) {
/*
* this function will sync "rm -rf" <pathname>
*/
let child_process;
// do nothing if module does not exist
try {
child_process = require("child_process");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
if (process.platform !== "win32") {
child_process.spawnSync("rm", [
"-rf", pathname
], {
stdio: [
"ignore", 1, 2
]
});
return;
}
try {
child_process.spawnSync("rd", [
"/s", "/q", pathname
], {
stdio: [
"ignore", 1, "ignore"
]
});
} catch (ignore) {}
}...
return "image/jpeg";
default:
return file;
}
}
};
const removeFolder = function (dir, onError) {
local.fsRmrfSync(dir);
onError();
};
removeFolder.sync = local.fsRmrfSync;
const removeRecursive = removeFolder;
let EventEmitter = require('events');
let URL = require('url');
// let WebSocket = require('ws');
...fsWriteFileWithMkdirpSync = function (pathname, data, msg) {
/*
* this function will sync write <data> to <pathname> with "mkdir -p"
*/
let fs;
let success;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
// try to write pathname
try {
fs.writeFileSync(pathname, data);
success = true;
} catch (ignore) {
// mkdir -p
fs.mkdirSync(require("path").dirname(pathname), {
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
}...
|| local.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
) {
onError(undefined, opt);
return;
}
// save apidoc.html
local.fsWriteFileWithMkdirpSync(
"tmp/build/apidoc.html",
local.apidocCreate(local.objectAssignDefault(opt, {
blacklistDict: local,
require: require2
})),
"wrote file apidoc - {{pathname}}"
);
...identity = function (val) {
/*
* this function will return <val>
*/
return val;
}...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...moduleDirname = function (module, pathList) {
/*
* this function will search <pathList> for <module>'s __dirname
*/
let result;
// search "."
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(module || "");
}
// search pathList
Array.from([
pathList,
require("module").globalPaths,
[
process.env.HOME + "/node_modules", "/usr/local/lib/node_modules"
]
]).flat().some(function (path) {
try {
result = require("path").resolve(path + "/" + module);
result = require("fs").statSync(result).isDirectory() && result;
return result;
} catch (ignore) {
result = "";
}
});
return result;
}...
return match0.replace((
/(.{128}(?:\b|\w+))/g
), "$1\n").trimEnd();
});
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
...nop = function () {
/*
* this function will do nothing
*/
return;
}...
// run shared js-env code - function
(function () {
let process;
let require;
// hack-jslint
local.nop(require);
globalThis.__coverageInclude__ = local.coalesce(
globalThis.__coverageInclude__,
{}
);
// mock builtins
process = local.process || {
cwd: function () {
...objectAssignDefault = function (tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...function Stream(opts) {
EE.call(this, opts);
}n/a
stringHtmlSafe = function (str) {
/*
* this function will make <str> html-safe
* https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html
*/
return str.replace((
/&/gu
), "&").replace((
/"/gu
), """).replace((
/'/gu
), "'").replace((
/</gu
), "<").replace((
/>/gu
), ">").replace((
/&(amp;|apos;|gt;|lt;|quot;)/igu
), "&$1");
}...
);
// handle case where module is a function
elem.name = elem.name.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimStart(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
...templateRender = function (template, dict, opt, ii) {
/*
* this function will render <template> with given <dict>
*/
let argList;
let getVal;
let match;
let renderPartial;
let rgx;
let skip;
let val;
if (dict === null || dict === undefined) {
dict = {};
}
opt = opt || {};
getVal = function (key) {
argList = key.split(" ");
val = dict;
if (argList[0] === "#this/") {
return val;
}
if (argList[0] === "#ii/") {
return ii;
}
// iteratively lookup nested val in dict
argList[0].split(".").forEach(function (key) {
val = val && val[key];
});
return val;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
), "");
}
return val;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getVal(key)
? partial[0]
// handle "unless" case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getVal(key)
? ""
// recurse with partial
: local.templateRender(partial, dict, opt)
);
default:
// recurse with partial
return match0[0] + local.templateRender(match0.slice(1), dict, opt);
}
};
// render partials
rgx = (
/\{\{#(\w+)\u0020([^}]+?)\}\}/g
);
template = template || "";
match = rgx.exec(template);
while (match) {
rgx.lastIndex += 1 - match[0].length;
template = template.replace(
new RegExp(
"\\{\\{#(" + match[1] + ") (" + match[2]
+ ")\\}\\}([\\S\\s]*?)\\{\\{/" + match[1] + " " + match[2]
+ "\\}\\}"
),
renderPartial
);
match = rgx.exec(template);
}
// search for keys in template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
let markdownToHtml;
let notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
val = getVal(match0.slice(2, -2));
if (val === undefined) {
return match0;
}
argList.slice(1).forEach(function (fmt, ii, list) {
switch (fmt) {
case "*":
case "+":
case "-":
case "/":
skip = ii + 1;
val = String(
fmt === "*"
? Number(val) * Number(list[skip])
: fmt === "+"
? Number(val) + Number(list[skip])
: fmt === "-"
? Number(val) - Number(list[skip])
: Number(val) / Number(list[skip])
);
break;......
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
...tryCatchOnError = function (fnc, onError) {
/*
* this function will run <fnc> in tryCatch block,
* else call onError with errCaught
*/
let result;
// validate onError
local.assertOrThrow(typeof onError === "function", typeof onError);
try {
// reset errCaught
local._debugTryCatchError = null;
result = fnc();
local._debugTryCatchError = null;
return result;
} catch (errCaught) {
// debug errCaught
local._debugTryCatchError = errCaught;
return onError(errCaught);
}
}...
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
let result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
..._default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
}...
local.cliDict._help();
return;
}
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
local.moduleDirname = function (module, pathList) {
/*
* this function will search <pathList> for <module>'s __dirname
*/
let result;
...utility2.browserTest = function () {
/*
* <urlList> <mode>
* will browser-test in parallel, comma-separated <urlList> with given <mode>
*/
local.browserTest({
url: process.argv[3]
}, local.onErrorDefault);
}n/a
utility2.githubCrudContentDelete = function () {
/*
* <fileRemote|dirRemote> <commitMessage>
* will delete from github <fileRemote|dirRemote>
*/
local.github_crud.githubCrudContentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (err) {
process.exit(Boolean(err));
});
}n/a
utility2.githubCrudContentGet = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
*/
local.github_crud.githubCrudContentGet({
url: process.argv[3]
}, function (err, data) {
try {
process.stdout.write(data);
} catch (ignore) {}
process.exit(Boolean(err));
});
}n/a
utility2.githubCrudContentPut = function () {
/*
* <fileRemote> <fileLocal> <commitMessage>
* will put on github <fileRemote>, <fileLocal>
*/
local.github_crud.githubCrudContentPutFile({
message: process.argv[5],
url: process.argv[3],
file: process.argv[4]
}, function (err) {
process.exit(Boolean(err));
});
}n/a
utility2.githubCrudContentTouch = function () {
/*
* <fileRemoteList> <commitMessage>
* will touch on github in parallel, comma-separated <fileRemoteList>
*/
local.github_crud.githubCrudContentTouchList({
message: process.argv[4],
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}n/a
utility2.githubCrudRepoCreate = function () {
/*
* <repoList>
* will create on github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoCreateList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}n/a
utility2.githubCrudRepoDelete = function () {
/*
* <repoList>
* will delete from github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoDeleteList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}n/a
utility2.start = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
}n/a
utility2.testReportCreate = function () {
/*
*
* will create test-report
*/
process.exit(
local.testReportCreate(
JSON.parse(local.fs.readFileSync(
local.path.resolve(
local.env.npm_config_dir_build + "/test-report.json"
),
"utf8"
))
).testsFailed !== 0
);
}n/a
ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example use:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
});
*/
let ajaxProgressUpdate;
let bufferValidateAndCoerce;
let isDone;
let local2;
let onError2;
let onEvent;
let stack;
let streamCleanup;
let timeout;
let tmp;
let xhr;
let xhrInit;
// init local2
local2 = opt.local2 || local.utility2 || {};
// init function
ajaxProgressUpdate = local2.ajaxProgressUpdate || function () {
return;
};
bufferValidateAndCoerce = local2.bufferValidateAndCoerce || function (
buf,
mode
) {
/*
* this function will validate and coerce/convert
* <buf> to Buffer/Uint8Array, or String if <mode> = "string"
*/
// coerce ArrayBuffer to Buffer
if (Object.prototype.toString.call(buf) === "[object ArrayBuffer]") {
buf = new Uint8Array(buf);
}
// convert Buffer to utf8
if (mode === "string" && typeof buf !== "string") {
buf = String(buf);
}
return buf;
};
onEvent = function (evt) {
/*
* this function will handle events
*/
if (Object.prototype.toString.call(evt) === "[object Error]") {
xhr.err = xhr.err || evt;
xhr.onEvent({
type: "error"
});
return;
}
// init statusCode
xhr.statusCode = (xhr.statusCode || xhr.status) | 0;
switch (evt.type) {
case "abort":
case "error":
case "load":
if (isDone) {
return;
}
isDone = true;
// decrement cnt
ajaxProgressUpdate.cnt = Math.max(
ajaxProgressUpdate.cnt - 1,
0
);
ajaxProgressUpdate();
// handle abort or err event
switch (!xhr.err && evt.type) {
case "abort":
case "error":
xhr.err = new Error("ajax - event " + evt.type);
break;
case "load":
if (xhr.statusCode >= 400) {
xhr.err = new Error(
"ajax - statusCode " + xhr.statusCode
);
}
break;
}
// debug statusCode / method / url
if (xhr.err) {
xhr.statusCode = xhr.statusCode || 500;
xhr.err.statusCode = xhr.statusCode;
tmp = (
(
local.isBrowser
? "browser"
: "node"
)
+ " - " + xhr.statusCode + " " + xhr.method + " " + xhr.url
+ "\n"
);
xhr.err.message = tmp + xhr.err.message;
xhr.err.stack = tmp + xhr.err.stack;
}
// update resHeaders
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
if (xhr.getAllResponseHeaders) {
xhr.getAllResponseHeaders().replace((
/(.*?):\u0020*(.*?)\r\n/g
), function (ignore, key, val) {
xhr.resHeaders[key.toLowerCase()] = val;
});
}
// debug ajaxResponse
xhr.resContentLength = (......
/* validateLineSortedReset */
local.ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example use:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
...function ok(...args) {
innerOk(ok, args.length, ...args);
}...
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
...assertOrThrow = function (passed, msg) {
/*
* this function will throw err.<msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is a string, then leave as is
? msg
// else JSON.stringify msg
: JSON.stringify(msg, undefined, 4)
)
);
}...
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...cliRun = function (opt) {
/*
* this function will run cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
strDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " &quo......
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...coalesce = function (...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== null && arg !== undefined && arg !== "") {
break;
}
ii += 1;
}
return arg;
}...
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
...function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
}n/a
fsReadFileOrDefaultSync = function (pathname, type, dflt) {
/*
* this function will sync-read <pathname> with given <type> and <dflt>
*/
let fs;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
}...
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "
;")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
...fsRmrfSync = function (pathname) {
/*
* this function will sync "rm -rf" <pathname>
*/
let child_process;
// do nothing if module does not exist
try {
child_process = require("child_process");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
if (process.platform !== "win32") {
child_process.spawnSync("rm", [
"-rf", pathname
], {
stdio: [
"ignore", 1, 2
]
});
return;
}
try {
child_process.spawnSync("rd", [
"/s", "/q", pathname
], {
stdio: [
"ignore", 1, "ignore"
]
});
} catch (ignore) {}
}...
return "image/jpeg";
default:
return file;
}
}
};
const removeFolder = function (dir, onError) {
local.fsRmrfSync(dir);
onError();
};
removeFolder.sync = local.fsRmrfSync;
const removeRecursive = removeFolder;
let EventEmitter = require('events');
let URL = require('url');
// let WebSocket = require('ws');
...fsWriteFileWithMkdirpSync = function (pathname, data, msg) {
/*
* this function will sync write <data> to <pathname> with "mkdir -p"
*/
let fs;
let success;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
// try to write pathname
try {
fs.writeFileSync(pathname, data);
success = true;
} catch (ignore) {
// mkdir -p
fs.mkdirSync(require("path").dirname(pathname), {
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
}...
|| local.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
) {
onError(undefined, opt);
return;
}
// save apidoc.html
local.fsWriteFileWithMkdirpSync(
"tmp/build/apidoc.html",
local.apidocCreate(local.objectAssignDefault(opt, {
blacklistDict: local,
require: require2
})),
"wrote file apidoc - {{pathname}}"
);
...githubCrudAjax = function (opt, onError) {
/*
* this function will make a low-level content-req to github
* https://developer.github.com/v3/repos/contents/
*/
// init opt
opt = {
content: opt.content,
headers: Object.assign({
// github oauth authentication
Authorization: "token " + (
typeof process === "object"
&& process && process.env.GITHUB_TOKEN
),
// bug-workaround
// https://developer.github.com/v3/#user-agent-required
"User-Agent": "undefined"
}, opt.headers),
httpReq: opt.httpReq,
message: opt.message,
method: opt.method || "GET",
responseJson: {},
sha: opt.sha,
url: opt.url
};
// parse https://github.com/:owner/:repo/blob/:branch/:path
opt.url = opt.url.replace((
/^https:\/\/github.com\/([^\/]+?\/[^\/]+?)\/blob\/([^\/]+?)\/(.+)/
), "https://api.github.com/repos/$1/contents/$3?branch=$2");
// parse https://github.com/:owner/:repo/tree/:branch/:path
opt.url = opt.url.replace((
/^https:\/\/github.com\/([^\/]+?\/[^\/]+?)\/tree\/([^\/]+?)\/(.+)/
), "https://api.github.com/repos/$1/contents/$3?branch=$2");
// parse https://raw.githubusercontent.com/:owner/:repo/:branch/:path
opt.url = opt.url.replace((
/^https:\/\/raw.githubusercontent.com\/([^\/]+?\/[^\/]+?)\/([^\/]+?)\/(.+)/
), "https://api.github.com/repos/$1/contents/$3?branch=$2");
// parse https://:owner.github.io/:repo/:path
opt.url = opt.url.replace((
/^https:\/\/([^.]+?)\.github\.io\/([^\/]+?)\/(.+)/
), "https://api.github.com/repos/$1/$2/contents/$3?branch=gh-pages");
// parse :owner/:repo
opt.url = opt.url.replace((
/^([^\/]+?\/[^\/]+?)$/
), "https://github.com/$1");
opt.url = opt.url.replace((
/\?branch=(.*)/
), function (match0, match1) {
opt.branch = match1;
if (opt.method === "GET") {
match0 = match0.replace("branch", "ref");
}
return match0;
});
if ((
/^https:\/\/github\.com\/[^\/]+?\/[^\/]+?$/
).test(opt.url)) {
opt.data = JSON.stringify({
name: opt.url.split("/")[4]
});
switch (opt.method) {
case "DELETE":
opt.url = (
"https://api.github.com/repos/"
+ opt.url.split("/").slice(3).join("/")
);
break;
case "POST_ORG":
opt.url = (
"https://api.github.com/orgs/"
+ opt.url.split("/")[3] + "/repos"
);
break;
case "POST_USER":
opt.url = "https://api.github.com/user/repos";
break;
}
opt.method = opt.method.split("_")[0];
} else {
if (opt.url.indexOf("https://api.github.com/repos/") !== 0) {
console.error("githubCrud - invalid url " + opt.url);
onError(new Error("invalid url " + opt.url));
return;
}
if (opt.method !== "GET") {
opt.message = (
opt.message
|| "[ci skip] " + opt.method + " file "
+ opt.url.replace((
/\?.*/
), "")
);
opt.url += "&message=" + encodeURIComponent(opt.message);
if (opt.sha) {
opt.url += "&sha=" + opt.sha;
}
opt.data = JSON.stringify({
branch: opt.branch,
content: Buffer.from(opt.content || "").toString("base64"),
message: opt.message,......
message: opt.message,
url: opt.url
};
local.gotoNext(opt, function (err, data) {
switch (opt.gotoState) {
case 1:
// get sha
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.gotoNext);
break;
case 2:
// delete file with sha
if (!err && data.sha) {
...githubCrudContentDelete = function (opt, onError) {
/*
* this function will delete github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#delete-a-file
*/
opt = {
httpReq: opt.httpReq,
message: opt.message,
url: opt.url
};
local.gotoNext(opt, function (err, data) {
switch (opt.gotoState) {
case 1:
// get sha
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.gotoNext);
break;
case 2:
// delete file with sha
if (!err && data.sha) {
local.githubCrudAjax({
httpReq: opt.httpReq,
message: opt.message,
method: "DELETE",
sha: data.sha,
url: opt.url
}, opt.gotoNext);
return;
}
// delete tree
local.onParallelList({
list: data
}, function (opt2, onParallel) {
onParallel.cnt += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
url: opt2.elem.url
}, onParallel);
}, opt.gotoNext);
break;
default:
onError(err, data);
}
});
opt.gotoState = 0;
opt.gotoNext();
}...
}
// delete tree
local.onParallelList({
list: data
}, function (opt2, onParallel) {
onParallel.cnt += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
url: opt2.elem.url
}, onParallel);
}, opt.gotoNext);
break;
default:
...githubCrudContentGet = function (opt, onError) {
/*
* this function will get github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#get-contents
*/
opt = {
httpReq: opt.httpReq,
url: opt.url
};
local.gotoNext(opt, function (err, data) {
switch (opt.gotoState) {
case 1:
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.gotoNext);
break;
case 2:
opt.gotoNext(null, Buffer.from(data.content || "", "base64"));
break;
default:
onError(err, !err && data);
}
});
opt.gotoState = 0;
opt.gotoNext();
}...
};
local.cliDict.get = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
*/
local.github_crud.githubCrudContentGet({
url: process.argv[3]
}, function (err, data) {
try {
process.stdout.write(data);
} catch (ignore) {}
process.exit(Boolean(err));
});
...githubCrudContentPut = function (opt, onError) {
/*
* this function will put <opt>.content to github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#create-a-file
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
opt = {
content: opt.content,
httpReq: opt.httpReq,
message: opt.message,
modeErrorIgnore: true,
url: opt.url
};
local.gotoNext(opt, function (err, data) {
switch (opt.gotoState) {
case 1:
// get sha
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.gotoNext);
break;
case 2:
// put file with sha
local.githubCrudAjax({
content: opt.content,
httpReq: opt.httpReq,
message: opt.message,
method: "PUT",
sha: data.sha,
url: opt.url
}, opt.gotoNext);
break;
default:
onError(err, data);
}
});
opt.gotoState = 0;
opt.gotoNext();
}...
});
return;
}
// get file
local.fs.readFile(opt.file, opt.gotoNext);
break;
case 2:
local.githubCrudContentPut({
content: data,
httpReq: opt.httpReq,
message: opt.message,
// resolve file in url
url: (
(
/\/$/
...githubCrudContentPutFile = function (opt, onError) {
/*
* this function will put opt.file to github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
opt = {
file: opt.file,
httpReq: opt.httpReq,
message: opt.message,
url: opt.url
};
local.gotoNext(opt, function (err, data) {
switch (opt.gotoState) {
case 1:
// get file from url
if ((
/^(?:http|https):\/\//
).test(opt.file)) {
local.ajax({
httpReq: opt.httpReq,
url: opt.file
}, function (err, res) {
opt.gotoNext(err, res && res.data);
});
return;
}
// get file
local.fs.readFile(opt.file, opt.gotoNext);
break;
case 2:
local.githubCrudContentPut({
content: data,
httpReq: opt.httpReq,
message: opt.message,
// resolve file in url
url: (
(
/\/$/
).test(opt.url)
? opt.url + local.path.basename(opt.file)
: opt.url
)
}, opt.gotoNext);
break;
default:
onError(err, data);
}
});
opt.gotoState = 0;
opt.gotoNext();
}...
};
local.cliDict.put = function () {
/*
* <fileRemote> <fileLocal> <commitMessage>
* will put on github <fileRemote> to <fileLocal>
*/
local.github_crud.githubCrudContentPutFile({
message: process.argv[5],
url: process.argv[3],
file: process.argv[4]
}, function (err) {
process.exit(Boolean(err));
});
};
...githubCrudContentTouch = function (opt, onError) {
/*
* this function will touch github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
opt = {
httpReq: opt.httpReq,
message: opt.message,
modeErrorIgnore: true,
url: opt.url
};
local.gotoNext(opt, function (err, data) {
switch (opt.gotoState) {
case 1:
// get sha
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.gotoNext);
break;
case 2:
// put file with sha
local.githubCrudAjax({
content: Buffer.from(data.content || "", "base64"),
httpReq: opt.httpReq,
message: opt.message,
method: "PUT",
sha: data.sha,
url: opt.url
}, opt.gotoNext);
break;
default:
onError(err, data);
}
});
opt.gotoState = 0;
opt.gotoNext();
}...
* this function will touch github-files <opt>.urlList in parallel
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
local.onParallelList({
list: opt.urlList
}, function (opt2, onParallel) {
onParallel.cnt += 1;
local.githubCrudContentTouch({
httpReq: opt.httpReq,
message: opt.message,
url: opt2.elem
}, onParallel);
}, onError);
};
...githubCrudContentTouchList = function (opt, onError) {
/*
* this function will touch github-files <opt>.urlList in parallel
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
local.onParallelList({
list: opt.urlList
}, function (opt2, onParallel) {
onParallel.cnt += 1;
local.githubCrudContentTouch({
httpReq: opt.httpReq,
message: opt.message,
url: opt2.elem
}, onParallel);
}, onError);
}...
};
local.cliDict.touch = function () {
/*
* <fileRemoteList> <commitMessage>
* will touch on github in parallel, comma-separated <fileRemoteList>
*/
local.github_crud.githubCrudContentTouchList({
message: process.argv[4],
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
...githubCrudRepoCreate = function (opt, onError) {
/*
* this function will create github-repo <opt>.url
* https://developer.github.com/v3/repos/#create
*/
local.githubCrudAjax({
httpReq: opt.httpReq,
method: "POST_ORG",
url: opt.url
}, function (err, data) {
if (!(err && err.statusCode === 404)) {
onError(err, data);
return;
}
local.githubCrudAjax({
httpReq: opt.httpReq,
method: "POST_USER",
url: opt.url
}, onError);
});
}...
* this function will create github-repos <opt>.urlList in parallel
* https://developer.github.com/v3/repos/#create
*/
local.onParallelList({
list: opt.urlList
}, function (opt2, onParallel) {
onParallel.cnt += 1;
local.githubCrudRepoCreate({
httpReq: opt.httpReq,
url: opt2.elem
}, onParallel);
}, onError);
};
local.githubCrudRepoDelete = function (opt, onError) {
...githubCrudRepoCreateList = function (opt, onError) {
/*
* this function will create github-repos <opt>.urlList in parallel
* https://developer.github.com/v3/repos/#create
*/
local.onParallelList({
list: opt.urlList
}, function (opt2, onParallel) {
onParallel.cnt += 1;
local.githubCrudRepoCreate({
httpReq: opt.httpReq,
url: opt2.elem
}, onParallel);
}, onError);
}...
};
local.cliDict.repo_create = function () {
/*
* <repoList>
* will create on github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoCreateList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
};
...githubCrudRepoDelete = function (opt, onError) {
/*
* this function will delete github-repo <opt>.url
* https://developer.github.com/v3/repos/#delete-a-repository
*/
local.githubCrudAjax({
httpReq: opt.httpReq,
method: "DELETE",
url: opt.url
}, onError);
}...
* this function will delete github-repos <opt>.urlList in parallel
* https://developer.github.com/v3/repos/#delete-a-repository
*/
local.onParallelList({
list: opt.urlList
}, function (opt2, onParallel) {
onParallel.cnt += 1;
local.githubCrudRepoDelete({
httpReq: opt.httpReq,
url: opt2.elem
}, onParallel);
}, onError);
};
}());
...githubCrudRepoDeleteList = function (opt, onError) {
/*
* this function will delete github-repos <opt>.urlList in parallel
* https://developer.github.com/v3/repos/#delete-a-repository
*/
local.onParallelList({
list: opt.urlList
}, function (opt2, onParallel) {
onParallel.cnt += 1;
local.githubCrudRepoDelete({
httpReq: opt.httpReq,
url: opt2.elem
}, onParallel);
}, onError);
}...
};
local.cliDict.repo_delete = function () {
/*
* <repoList>
* will delete from github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoDeleteList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
};
...gotoNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.gotoNext,
* and append current-stack to any err
*/
opt.gotoNext = local.onErrorWithStack(function (err, data, meta) {
try {
opt.gotoState += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
console.error("gotoNext - " + JSON.stringify({
gotoState: opt.gotoState,
errorMessage: err && err.message
}));
if (err && err.stack) {
console.error(err.stack);
}
}
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertOrThrow(undefined, opt.errCaught);
}
opt.errCaught = errCaught;
opt.gotoNext(errCaught, data, meta);
}
});
opt.gotoNextData = opt.gotoNext.bind(undefined, undefined);
return opt;
}...
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertOrThrow(undefined, opt.errCaught);
}
opt.errCaught = errCaught;
opt.gotoNext(errCaught, data, meta);
}
});
opt.gotoNextData = opt.gotoNext.bind(undefined, undefined);
return opt;
};
local.onErrorDefault = function (err) {
...identity = function (val) {
/*
* this function will return <val>
*/
return val;
}...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...nop = function () {
/*
* this function will do nothing
*/
return;
}...
// run shared js-env code - function
(function () {
let process;
let require;
// hack-jslint
local.nop(require);
globalThis.__coverageInclude__ = local.coalesce(
globalThis.__coverageInclude__,
{}
);
// mock builtins
process = local.process || {
cwd: function () {
...objectAssignDefault = function (tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...onErrorDefault = function (err) {
/*
* this function will if <err> exists, then print it to stderr
*/
if (err) {
console.error(err);
}
return err;
}...
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
...onErrorWithStack = function (onError) {
/*
* this function will wrap <onError> with wrapper preserving current-stack
*/
let onError2;
let stack;
stack = new Error().stack;
onError2 = function (err, data, meta) {
// append current-stack to err.stack
if (
err
&& typeof err.stack === "string"
&& err !== local.errorDefault
) {
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
}...
};
local.gotoNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.gotoNext,
* and append current-stack to any err
*/
opt.gotoNext = local.onErrorWithStack(function (err, data, meta) {
try {
opt.gotoState += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
...onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if cnt === 0 or err occurred, then call onError(err)
*/
let onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement cnt
onParallel.cnt -= 1;
// validate cnt
if (!(onParallel.cnt >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.cnt = " + onParallel.cnt
);
// ensure onError is run only once
} else if (onParallel.cnt < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure cnt <= 0
onParallel.cnt = -Math.abs(onParallel.cnt);
}
// call onError when isDone
if (onParallel.cnt <= 0) {
onError(err, data);
return;
}
onEach();
};
// init cnt
onParallel.cnt = 0;
// return callback
return onParallel;
}...
elem: opt.list[onParallel.ii],
ii: onParallel.ii,
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
...onParallelList = function (opt, onEach, onError) {
/*
* this function will
* 1. async-run onEach in parallel,
* with given <opt>.rateLimit and <opt>.retryLimit
* 2. call <onError> when onParallel.ii + 1 === <opt>.list.length
*/
let isListEnd;
let onEach2;
let onParallel;
opt.list = opt.list || [];
onEach2 = function () {
while (true) {
if (!(onParallel.ii + 1 < opt.list.length)) {
isListEnd = true;
return;
}
if (!(onParallel.cnt < opt.rateLimit + 1)) {
return;
}
onParallel.ii += 1;
onEach({
elem: opt.list[onParallel.ii],
ii: onParallel.ii,
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
// restart if opt.list has grown
if (isListEnd && (onParallel.ii + 1 < opt.list.length)) {
isListEnd = undefined;
onEach2();
}
});
onParallel.ii = -1;
opt.rateLimit = Number(opt.rateLimit) || 6;
opt.rateLimit = Math.max(opt.rateLimit, 1);
opt.retryLimit = Number(opt.retryLimit) || 2;
onParallel.cnt += 1;
onEach2();
onParallel();
}...
method: "DELETE",
sha: data.sha,
url: opt.url
}, opt.gotoNext);
return;
}
// delete tree
local.onParallelList({
list: data
}, function (opt2, onParallel) {
onParallel.cnt += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
...function Stream(opts) {
EE.call(this, opts);
}n/a
delete = function () {
/*
* <fileRemote|dirRemote> <commitMessage>
* will delete from github <fileRemote|dirRemote>
*/
local.github_crud.githubCrudContentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (err) {
process.exit(Boolean(err));
});
}...
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
...get = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
*/
local.github_crud.githubCrudContentGet({
url: process.argv[3]
}, function (err, data) {
try {
process.stdout.write(data);
} catch (ignore) {}
process.exit(Boolean(err));
});
}...
this._skipCruft();
break;
case Tokens.SUPPORTS_SYM:
this._supports();
this._skipCruft();
break;
case Tokens.UNKNOWN_SYM: //unknown @ rule
tokenStream.get();
if (!this.options.strict) {
//fire error event
this.fire({
type: "error",
error: null,
message: "Unknown @ rule: " + tokenStream.LT(0).value + ".",
...put = function () {
/*
* <fileRemote> <fileLocal> <commitMessage>
* will put on github <fileRemote> to <fileLocal>
*/
local.github_crud.githubCrudContentPutFile({
message: process.argv[5],
url: process.argv[3],
file: process.argv[4]
}, function (err) {
process.exit(Boolean(err));
});
}n/a
repo_create = function () {
/*
* <repoList>
* will create on github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoCreateList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}n/a
repo_delete = function () {
/*
* <repoList>
* will delete from github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoDeleteList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}n/a
touch = function () {
/*
* <fileRemoteList> <commitMessage>
* will touch on github in parallel, comma-separated <fileRemoteList>
*/
local.github_crud.githubCrudContentTouchList({
message: process.argv[4],
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}n/a
function Instrumenter(options) {
this.opts = options || {
debug: false,
walkDebug: false,
coverageVariable: '__coverage__',
codeGenerationOptions: undefined,
noAutoWrap: false,
noCompact: false,
embedSource: false,
preserveComments: false,
esModules: false
};
if (this.opts.esModules && !this.opts.noAutoWrap) {
this.opts.noAutoWrap = true;
if (this.opts.debug) {
console.log('Setting noAutoWrap to true as required by esModules');
}
}
this.walker = new Walker({
ArrowFunctionExpression: [ this.arrowBlockConverter ],
ExpressionStatement: this.coverStatement,
ExportNamedDeclaration: this.coverExport,
BreakStatement: this.coverStatement,
ContinueStatement: this.coverStatement,
DebuggerStatement: this.coverStatement,
ReturnStatement: this.coverStatement,
ThrowStatement: this.coverStatement,
TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
VariableDeclaration: this.coverStatement,
IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ],
ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ],
ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
SwitchStatement: [ this.coverStatement, this.switchBranchInjector ],
SwitchCase: [ this.switchCaseInjector ],
WithStatement: [ this.withBlockConverter, this.coverStatement ],
FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
FunctionExpression: this.coverFunction,
LabeledStatement: this.coverStatement,
ConditionalExpression: this.conditionalBranchInjector,
LogicalExpression: this.logicalExpressionBranchInjector,
ObjectExpression: this.maybeAddType,
MetaProperty: this.coverMetaProperty,
}, this.extractCurrentHint, this, this.opts.walkDebug);
//unit testing purposes only
if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
this.omitTrackerSuffix = true;
}
}n/a
function Module(id = '', parent) {
this.id = id;
this.path = path.dirname(id);
this.exports = {};
this.parent = parent;
updateChildren(parent, this, false);
this.filename = null;
this.loaded = false;
this.children = [];
}n/a
function ok(...args) {
innerOk(ok, args.length, ...args);
}...
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
...assertOrThrow = function (passed, msg) {
/*
* this function will throw err.<msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is a string, then leave as is
? msg
// else JSON.stringify msg
: JSON.stringify(msg, undefined, 4)
)
);
}...
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...cliRun = function (opt) {
/*
* this function will run cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
strDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " &quo......
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...coalesce = function (...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== null && arg !== undefined && arg !== "") {
break;
}
ii += 1;
}
return arg;
}...
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
...coverageMerge = function (coverage1 = {}, coverage2 = {}) {
/*
* this function will inplace-merge <coverage2> into <coverage1>
*/
let dict1;
let dict2;
Object.keys(coverage2).forEach(function (file) {
// if coverage1[file] is undefined, then override it
if (!coverage1[file]) {
coverage1[file] = coverage2[file];
return;
}
// merge coverage2 into coverage1
[
"b", "f", "s"
].forEach(function (key) {
dict1 = coverage1[file][key];
dict2 = coverage2[file][key];
switch (key) {
// increment coverage for branch lines
case "b":
Object.keys(dict2).forEach(function (key) {
dict2[key].forEach(function (cnt, ii) {
dict1[key][ii] += cnt;
});
});
break;
// increment coverage for function and statement lines
case "f":
case "s":
Object.keys(dict2).forEach(function (key) {
dict1[key] += dict2[key];
});
break;
}
});
});
return coverage1;
}n/a
coverageReportCreate = function (opt) {
/*
* this function will
// 1. merge previous <dirCoverage>/coverage.json into <opt>.coverage
// 2. convert <opt>.coverage to <summaryDict>
// 3. convert <summaryDict> to <nodeRoot>
// 4. convert <nodeRoot> to text-report <dirCoverage>/coverage.txt
// 5. convert <nodeRoot> to html-report <dirCoverage>/\*
// 6. return coverage-report in html-format as single document
*/
let coverageInclude;
let dirCoverage;
let filePrefix;
let filesUnderRoot;
let htmlAll;
let nodeChildAdd;
let nodeCreate;
let nodeDict;
let nodeNormalize;
let nodeRoot;
let summaryDict;
let tmp;
let tmpChildren;
if (!(opt && opt.coverage)) {
return "";
}
// init function
nodeChildAdd = function (node, child) {
/*
* this function will add <child> to <node>
*/
node.children.push(child);
child.parent = node;
};
nodeCreate = function (pathname) {
/*
* this function will create a tree-node
*/
return {
children: [],
pathname,
metrics: {
branches: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
functions: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
lines: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
statements: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
}
},
name: pathname
};
};
nodeNormalize = function (node, level, filePrefix, parent) {
/*
* this function will recursively normalize <node> and its children
*/
let metric;
// init name
if (node.name.indexOf(filePrefix) === 0) {
node.name = node.name.slice(filePrefix.length);
}
if (node.name[0] === path.sep) {
node.name = node.name.slice(1);
}
// init relativeName
node.relativeName = (
parent
? (
parent.name !== "__root__/"
? node.name.slice(parent.name.length)
: node.name
)
: node.name.slice(filePrefix.length)
);
// init nameOrAllFiles
node.nameOrAllFiles = node.name || "All files";
// init relativeNameOrAllFiles
node.relativeNameOrAllFiles = node.relativeName || "All files";
// init href
node.href = node.relativeName.split(path.sep).join("/") + (
node.isFile
? ".html"
: "index.html"
);
// recurse
node.children.forEach(function (child) {
nodeNormalize(child, level + 1, filePrefix, node);
});
// sort children by name
node.children.sort(function (aa, bb) {
return (
aa.name > bb.name
? 1
: -1
);
});
// init metrics
if (!node.isFile) {
node.children.forEach(function (child) {
[
"lines", "statements", "branches", "functions"
].forEach(function (key) {
metric = node.metrics[key];
metric.total += child.metrics[key].total;
metric.covered += child.metrics[key].covered;
metric.skipped += child.metrics[key].skipped;......
break;\n\
}\n\
};\n\
// handle evt\n\
local.on("utility2.testRunEnd", function () {\n\
document.querySelector(\n\
"#htmlCoverageReport1"\n\
).innerHTML = local.istanbul.coverageReportCreate({\n\
coverage: globalThis.__coverage__\n\
});\n\
});\n\
local.on("utility2.testRunProgressUpdate", function (testReport) {\n\
document.querySelector(\n\
"#htmlTestReport2"\n\
).innerHTML = local.testReportMerge(testReport, {});\n\
...function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
}n/a
fsReadFileOrDefaultSync = function (pathname, type, dflt) {
/*
* this function will sync-read <pathname> with given <type> and <dflt>
*/
let fs;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
}...
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "
;")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
...fsRmrfSync = function (pathname) {
/*
* this function will sync "rm -rf" <pathname>
*/
let child_process;
// do nothing if module does not exist
try {
child_process = require("child_process");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
if (process.platform !== "win32") {
child_process.spawnSync("rm", [
"-rf", pathname
], {
stdio: [
"ignore", 1, 2
]
});
return;
}
try {
child_process.spawnSync("rd", [
"/s", "/q", pathname
], {
stdio: [
"ignore", 1, "ignore"
]
});
} catch (ignore) {}
}...
return "image/jpeg";
default:
return file;
}
}
};
const removeFolder = function (dir, onError) {
local.fsRmrfSync(dir);
onError();
};
removeFolder.sync = local.fsRmrfSync;
const removeRecursive = removeFolder;
let EventEmitter = require('events');
let URL = require('url');
// let WebSocket = require('ws');
...fsWriteFileWithMkdirpSync = function (pathname, data, msg) {
/*
* this function will sync write <data> to <pathname> with "mkdir -p"
*/
let fs;
let success;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
// try to write pathname
try {
fs.writeFileSync(pathname, data);
success = true;
} catch (ignore) {
// mkdir -p
fs.mkdirSync(require("path").dirname(pathname), {
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
}...
|| local.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
) {
onError(undefined, opt);
return;
}
// save apidoc.html
local.fsWriteFileWithMkdirpSync(
"tmp/build/apidoc.html",
local.apidocCreate(local.objectAssignDefault(opt, {
blacklistDict: local,
require: require2
})),
"wrote file apidoc - {{pathname}}"
);
...identity = function (val) {
/*
* this function will return <val>
*/
return val;
}...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...instrumentInPackage = function (code, file) {
/*
* this function will instrument <code>
* if macro /\* istanbul instrument in package $npm_package_nameLib *\/
* exists in <code>
*/
return (
(
process.env.npm_config_mode_coverage
&& code.indexOf("/* istanbul ignore all */\n") < 0 && (
process.env.npm_config_mode_coverage === "all"
|| process.env.npm_config_mode_coverage === "node_modules"
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_package_nameLib + " */\n"
) >= 0
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_config_mode_coverage + " */\n"
) >= 0
)
)
? local.instrumentSync(code, file)
: code
);
}n/a
instrumentSync = function (code, file) {
/*
* this function will
// 1. normalize <file>
// 2. save <code> to __coverageInclude__[<file>] for future html-report
// 3. return instrumented-code
*/
// 1. normalize <file>
file = path.resolve(file);
// 2. save <code> to __coverageInclude__[<file>] for future html-report
globalThis.__coverageInclude__[file] = 1;
// 3. return instrumented-code
return new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimStart();
}...
try {\n\
delete globalThis.__coverage__["/inputTextarea1.js"];\n\
} catch (ignore) {}\n\
// try to cover and eval #inputTextarea1\n\
try {\n\
document.querySelector(\n\
"#outputTextarea1"\n\
).value = local.istanbul.instrumentSync(\n\
document.querySelector("#inputTextarea1").value,\n\
"/inputTextarea1.js"\n\
);\n\
eval( // jslint ignore:line\n\
document.querySelector("#outputTextarea1").value\n\
);\n\
} catch (errCaught) {\n\
...nop = function () {
/*
* this function will do nothing
*/
return;
}...
// run shared js-env code - function
(function () {
let process;
let require;
// hack-jslint
local.nop(require);
globalThis.__coverageInclude__ = local.coalesce(
globalThis.__coverageInclude__,
{}
);
// mock builtins
process = local.process || {
cwd: function () {
...objectAssignDefault = function (tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...function require(path) {
return mod.require(path);
}...
}).slice(0, 256).map(readExample);
// init moduleMain
local.tryCatchOnError(function () {
console.error("apidocCreate - requiring " + opt.dir + " ...");
moduleMain = {};
moduleMain = (
opt.moduleDict[opt.env.npm_package_name]
|| opt.require(opt.dir)
|| opt.require(
opt.dir + "/"
+ (opt.packageJson.bin)[Object.keys(opt.packageJson.bin)[0]]
) || {}
);
opt.circularSet.add(moduleMain);
console.error("apidocCreate - ... required " + opt.dir);
...function Stream(opts) {
EE.call(this, opts);
}n/a
templateRender = function (template, dict, opt, ii) {
/*
* this function will render <template> with given <dict>
*/
let argList;
let getVal;
let match;
let renderPartial;
let rgx;
let skip;
let val;
if (dict === null || dict === undefined) {
dict = {};
}
opt = opt || {};
getVal = function (key) {
argList = key.split(" ");
val = dict;
if (argList[0] === "#this/") {
return val;
}
if (argList[0] === "#ii/") {
return ii;
}
// iteratively lookup nested val in dict
argList[0].split(".").forEach(function (key) {
val = val && val[key];
});
return val;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
), "");
}
return val;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getVal(key)
? partial[0]
// handle "unless" case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getVal(key)
? ""
// recurse with partial
: local.templateRender(partial, dict, opt)
);
default:
// recurse with partial
return match0[0] + local.templateRender(match0.slice(1), dict, opt);
}
};
// render partials
rgx = (
/\{\{#(\w+)\u0020([^}]+?)\}\}/g
);
template = template || "";
match = rgx.exec(template);
while (match) {
rgx.lastIndex += 1 - match[0].length;
template = template.replace(
new RegExp(
"\\{\\{#(" + match[1] + ") (" + match[2]
+ ")\\}\\}([\\S\\s]*?)\\{\\{/" + match[1] + " " + match[2]
+ "\\}\\}"
),
renderPartial
);
match = rgx.exec(template);
}
// search for keys in template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
let markdownToHtml;
let notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
val = getVal(match0.slice(2, -2));
if (val === undefined) {
return match0;
}
argList.slice(1).forEach(function (fmt, ii, list) {
switch (fmt) {
case "*":
case "+":
case "-":
case "/":
skip = ii + 1;
val = String(
fmt === "*"
? Number(val) * Number(list[skip])
: fmt === "+"
? Number(val) + Number(list[skip])
: fmt === "-"
? Number(val) - Number(list[skip])
: Number(val) / Number(list[skip])
);
break;......
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
...function Instrumenter(options) {
this.opts = options || {
debug: false,
walkDebug: false,
coverageVariable: '__coverage__',
codeGenerationOptions: undefined,
noAutoWrap: false,
noCompact: false,
embedSource: false,
preserveComments: false,
esModules: false
};
if (this.opts.esModules && !this.opts.noAutoWrap) {
this.opts.noAutoWrap = true;
if (this.opts.debug) {
console.log('Setting noAutoWrap to true as required by esModules');
}
}
this.walker = new Walker({
ArrowFunctionExpression: [ this.arrowBlockConverter ],
ExpressionStatement: this.coverStatement,
ExportNamedDeclaration: this.coverExport,
BreakStatement: this.coverStatement,
ContinueStatement: this.coverStatement,
DebuggerStatement: this.coverStatement,
ReturnStatement: this.coverStatement,
ThrowStatement: this.coverStatement,
TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
VariableDeclaration: this.coverStatement,
IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ],
ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ],
ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
SwitchStatement: [ this.coverStatement, this.switchBranchInjector ],
SwitchCase: [ this.switchCaseInjector ],
WithStatement: [ this.withBlockConverter, this.coverStatement ],
FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
FunctionExpression: this.coverFunction,
LabeledStatement: this.coverStatement,
ConditionalExpression: this.conditionalBranchInjector,
LogicalExpression: this.logicalExpressionBranchInjector,
ObjectExpression: this.maybeAddType,
MetaProperty: this.coverMetaProperty,
}, this.extractCurrentHint, this, this.opts.walkDebug);
//unit testing purposes only
if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
this.omitTrackerSuffix = true;
}
}n/a
arrowBlockConverter = function (node) {
var retStatement;
if (node.expression) { // turn expression nodes into a block with a return statement
retStatement = astgen.returnStatement(node.body);
// ensure the generated return statement is covered
retStatement.loc = node.body.loc;
node.body = this.convertToBlock(retStatement);
node.expression = false;
}
}n/a
branchIncrementExprAst = function (varName, branchIndex, down) {
var ret = astgen.postIncrement(
astgen.subscript(
astgen.subscript(
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')),
astgen.stringLiteral(varName)
),
astgen.numericLiteral(branchIndex)
),
down
);
return ret;
}n/a
branchLocationFor = function (name, index) {
return this.coverState.branchMap[name].locations[index];
}n/a
branchName = function (type, startLine, pathLocations) {
var bName,
paths = [],
locations = [],
i,
ignoring = !!this.currentState.ignoring;
this.currentState.branch += 1;
bName = this.currentState.branch;
for (i = 0; i < pathLocations.length; i += 1) {
pathLocations[i].skip = pathLocations[i].skip || ignoring || undefined;
locations.push(pathLocations[i]);
paths.push(0);
}
this.coverState.b[bName] = paths;
this.coverState.branchMap[bName] = { line: startLine, type: type, locations: locations };
return bName;
}n/a
conditionalBranchInjector = function (node, walker) {
var bName = this.branchName('cond-expr', walker.startLineForNode(node), this.locationsForNodes([ node.consequent, node.alternate
])),
ast1 = this.branchIncrementExprAst(bName, 0),
ast2 = this.branchIncrementExprAst(bName, 1);
node.consequent.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 0));
node.alternate.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 1));
node.consequent = astgen.sequence(ast1, node.consequent);
node.alternate = astgen.sequence(ast2, node.alternate);
}n/a
convertToBlock = function (node) {
if (!node) {
return { type: 'BlockStatement', body: [] };
} else if (node.type === 'BlockStatement') {
return node;
} else {
return { type: 'BlockStatement', body: [ node ] };
}
}n/a
coverExport = function (node, walker) {
var sName, incrStatementCount;
if ( !node.declaration || !node.declaration.declarations ) { return; }
this.maybeSkipNode(node, 'next');
sName = this.statementName(node.declaration.loc);
incrStatementCount = astgen.statement(
astgen.postIncrement(
astgen.subscript(
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
astgen.stringLiteral(sName)
)
)
);
this.splice(incrStatementCount, node, walker);
}n/a
coverFunction = function (node, walker) {
var id,
body = node.body,
blockBody = body.body,
popped;
this.maybeSkipNode(node, 'next');
id = this.functionName(node, walker.startLineForNode(node), {
start: node.loc.start,
end: { line: node.body.loc.start.line, column: node.body.loc.start.column }
});
if (blockBody.length > 0 && this.isUseStrictExpression(blockBody[0])) {
popped = blockBody.shift();
}
blockBody.unshift(
astgen.statement(
astgen.postIncrement(
astgen.subscript(
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')),
astgen.stringLiteral(id)
)
)
)
);
if (popped) {
blockBody.unshift(popped);
}
}n/a
function(node) {
node.skipSelf = true;
}n/a
coverStatement = function (node, walker) {
var sName,
incrStatementCount,
parent,
grandParent;
this.maybeSkipNode(node, 'next');
if (this.isUseStrictExpression(node)) {
grandParent = walker.ancestor(2);
/* istanbul ignore else: difficult to test */
if (grandParent) {
if ((grandParent.node.type === SYNTAX.FunctionExpression.name ||
grandParent.node.type === SYNTAX.FunctionDeclaration.name) &&
walker.parent().node.body[0] === node) {
return;
}
}
}
if (node.type === SYNTAX.FunctionDeclaration.name) {
// Called for the side-effect of setting the function's statement count to 1.
this.statementName(node.loc, 1);
} else {
// We let `coverExport` handle ExportNamedDeclarations.
parent = walker.parent();
if (parent && parent.node.type === SYNTAX.ExportNamedDeclaration.name) {
return;
}
sName = this.statementName(node.loc);
incrStatementCount = astgen.statement(
astgen.postIncrement(
astgen.subscript(
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
astgen.stringLiteral(sName)
)
)
);
this.splice(incrStatementCount, node, walker);
}
}n/a
endIgnore = function () {
this.currentState.ignoring -= 1;
}n/a
extractCurrentHint = function (node) {
if (!node.range) { return; }
var i = this.currentState.lastHintPosition + 1,
hints = this.currentState.hints,
nodeStart = node.range[0],
hint;
this.currentState.currentHint = null;
// hack-coverage - allow top-level istanbul-ignore-next
if (node.type === "Program") { return; }
while (i < hints.length) {
hint = hints[i];
if (hint.end < nodeStart) {
this.currentState.currentHint = hint;
this.currentState.lastHintPosition = i;
i += 1;
} else {
break;
}
}
}n/a
filterHints = function (comments) {
var ret = [],
i,
comment,
groups;
if (!(comments && isArray(comments))) {
return ret;
}
for (i = 0; i < comments.length; i += 1) {
comment = comments[i];
/* istanbul ignore else: paranoid check */
if (comment && comment.value && comment.range && isArray(comment.range)) {
groups = String(comment.value).match(COMMENT_RE);
if (groups) {
ret.push({ type: groups[1], start: comment.range[0], end: comment.range[1] });
}
}
}
return ret;
}n/a
findLeaves = function (node, accumulator, parent, property) {
if (node.type === SYNTAX.LogicalExpression.name) {
this.findLeaves(node.left, accumulator, node, 'left');
this.findLeaves(node.right, accumulator, node, 'right');
} else {
accumulator.push({ node: node, parent: parent, property: property });
}
}n/a
fixColumnPositions = function (coverState) {
var offset = LEADER_WRAP.length,
fixer = function (loc) {
if (loc.start.line === 1) {
loc.start.column -= offset;
}
if (loc.end.line === 1) {
loc.end.column -= offset;
}
},
k,
obj,
i,
locations;
obj = coverState.statementMap;
for (k in obj) {
/* istanbul ignore else: has own property */
if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
}
obj = coverState.fnMap;
for (k in obj) {
/* istanbul ignore else: has own property */
if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
}
obj = coverState.branchMap;
for (k in obj) {
/* istanbul ignore else: has own property */
if (obj.hasOwnProperty(k)) {
locations = obj[k].locations;
for (i = 0; i < locations.length; i += 1) {
fixer(locations[i]);
}
}
}
}n/a
functionName = function (node, line, location) {
this.currentState.func += 1;
var id = this.currentState.func,
ignoring = !!this.currentState.ignoring,
name = node.id ? node.id.name : '(anonymous_' + id + ')',
clone = function (attr) {
var obj = location[attr] || /* istanbul ignore next */ {};
return { line: obj.line, column: obj.column };
};
this.coverState.fnMap[id] = {
name: name, line: line,
loc: {
start: clone('start'),
end: clone('end')
},
skip: ignoring || undefined
};
this.coverState.f[id] = 0;
return id;
}n/a
getPreamble = function (sourceCode, emitUseStrict) {
var varName = this.opts.coverageVariable || '__coverage__',
file = this.coverState.path.replace(/\\/g, '\\\\'),
tracker = this.currentState.trackerVar,
coverState,
strictLine = emitUseStrict ? '"use strict";' : '',
// return replacements using the function to ensure that the replacement is
// treated like a dumb string and not as a string with RE replacement patterns
replacer = function (s) {
return function () { return s; };
},
code;
if (!this.opts.noAutoWrap) {
this.fixColumnPositions(this.coverState);
}
if (this.opts.embedSource) {
this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/);
}
coverState = this.opts.debug ? JSON.stringify(this.coverState, undefined, 4) : JSON.stringify(this.coverState);
code = [
"%STRICT%",
"var %VAR% = (Function('return this'))();",
"if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }",
"%VAR% = %VAR%.%GLOBAL%;",
"if (!(%VAR%['%FILE%'])) {",
" %VAR%['%FILE%'] = %OBJECT%;",
"}",
"%VAR% = %VAR%['%FILE%'];"
].join("\n")
.replace(/%STRICT%/g, replacer(strictLine))
.replace(/%VAR%/g, replacer(tracker))
.replace(/%GLOBAL%/g, replacer(varName))
.replace(/%FILE%/g, replacer(file))
.replace(/%OBJECT%/g, replacer(coverState));
return code;
}n/a
ifBlockConverter = function (node) {
node.consequent = this.convertToBlock(node.consequent);
node.alternate = this.convertToBlock(node.alternate);
}n/a
ifBranchInjector = function (node, walker) {
var alreadyIgnoring = !!this.currentState.ignoring,
hint = this.currentState.currentHint,
ignoreThen = !alreadyIgnoring && hint && hint.type === 'if',
ignoreElse = !alreadyIgnoring && hint && hint.type === 'else',
line = node.loc.start.line,
col = node.loc.start.column,
makeLoc = function () { return { line: line, column: col }; },
bName = this.branchName('if', walker.startLineForNode(node), [
{ start: makeLoc(), end: makeLoc(), skip: ignoreThen || undefined },
{ start: makeLoc(), end: makeLoc(), skip: ignoreElse || undefined }
]),
thenBody = node.consequent.body,
elseBody = node.alternate.body,
child;
thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0)));
elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1)));
if (ignoreThen) { child = node.consequent; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
if (ignoreElse) { child = node.alternate; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
}n/a
instrument = function (code, filename, callback) {
if (!callback && typeof filename === 'function') {
callback = filename;
filename = null;
}
try {
callback(null, this.instrumentSync(code, filename));
} catch (ex) {
callback(ex);
}
}n/a
instrumentASTSync = function (program, filename, originalCode) {
var usingStrict = false,
codegenOptions,
generated,
preamble,
lineCount,
i;
filename = filename || String(new Date().getTime()) + '.js';
this.sourceMap = null;
this.coverState = {
path: filename,
s: {},
b: {},
f: {},
fnMap: {},
statementMap: {},
branchMap: {}
};
this.currentState = {
trackerVar: generateTrackerVar(filename, this.omitTrackerSuffix),
func: 0,
branch: 0,
variable: 0,
statement: 0,
hints: this.filterHints(program.comments),
currentHint: null,
lastHintPosition: -1,
ignoring: 0
};
if (program.body && program.body.length > 0 && this.isUseStrictExpression(program.body[0])) {
//nuke it
program.body.shift();
//and add it back at code generation time
usingStrict = true;
}
this.walker.startWalk(program);
codegenOptions = this.opts.codeGenerationOptions || { format: { compact: !this.opts.noCompact }};
codegenOptions.comment = this.opts.preserveComments;
//console.log(JSON.stringify(program, undefined, 2));
generated = ESPGEN.generate(program, codegenOptions);
preamble = this.getPreamble(originalCode || '', usingStrict);
if (generated.map && generated.code) {
lineCount = preamble.split(/\r\n|\r|\n/).length;
// offset all the generated line numbers by the number of lines in the preamble
for (i = 0; i < generated.map._mappings._array.length; i += 1) {
generated.map._mappings._array[i].generatedLine += lineCount;
}
this.sourceMap = generated.map;
generated = generated.code;
}
return preamble + '\n' + generated + '\n';
}n/a
instrumentSync = function (code, filename) {
var program;
//protect from users accidentally passing in a Buffer object instead
if (typeof code !== 'string') { throw new Error('Code must be string'); }
if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't affect syntax tree locations for things we care about
code = '//' + code;
}
if (!this.opts.noAutoWrap) {
code = LEADER_WRAP + code + TRAILER_WRAP;
}
try {
// hack-coverage - acorn opt
let opt = {
locations: true,
onComment: [],
onToken: this.opts.preserveComments,
ranges: true,
sourceType: this.opts.esModules ? 'module' : 'script'
};
program = ESP.parse(code, opt);
program.comments = opt.onComment
} catch (e) {
console.log('Failed to parse file: ' + filename);
throw e;
}
if (this.opts.preserveComments) {
program = ESPGEN.attachComments(program, program.comments, program.tokens);
}
if (!this.opts.noAutoWrap) {
program = {
type: SYNTAX.Program.name,
body: program.body[0].expression.callee.body.body,
comments: program.comments
};
}
return this.instrumentASTSync(program, filename, code);
}...
try {\n\
delete globalThis.__coverage__["/inputTextarea1.js"];\n\
} catch (ignore) {}\n\
// try to cover and eval #inputTextarea1\n\
try {\n\
document.querySelector(\n\
"#outputTextarea1"\n\
).value = local.istanbul.instrumentSync(\n\
document.querySelector("#inputTextarea1").value,\n\
"/inputTextarea1.js"\n\
);\n\
eval( // jslint ignore:line\n\
document.querySelector("#outputTextarea1").value\n\
);\n\
} catch (errCaught) {\n\
...isUseStrictExpression = function (node) {
return node && node.type === SYNTAX.ExpressionStatement.name &&
node.expression && node.expression.type === SYNTAX.Literal.name &&
node.expression.value === 'use strict';
}n/a
lastFileCoverage = function () {
return this.coverState;
}n/a
lastSourceMap = function () {
return this.sourceMap;
}n/a
locationsForNodes = function (nodes) {
var ret = [],
i;
for (i = 0; i < nodes.length; i += 1) {
ret.push(nodes[i].loc);
}
return ret;
}n/a
logicalExpressionBranchInjector = function (node, walker) {
var parent = walker.parent(),
leaves = [],
bName,
tuple,
i;
this.maybeSkipNode(node, 'next');
if (parent && parent.node.type === SYNTAX.LogicalExpression.name) {
//already covered
return;
}
this.findLeaves(node, leaves);
bName = this.branchName('binary-expr',
walker.startLineForNode(node),
this.locationsForNodes(leaves.map(function (item) { return item.node; }))
);
for (i = 0; i < leaves.length; i += 1) {
tuple = leaves[i];
tuple.parent[tuple.property] = astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node);
tuple.node.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, i));
}
}n/a
loopBlockConverter = function (node) {
node.body = this.convertToBlock(node.body);
}n/a
maybeAddSkip = function (branchLocation) {
return function (node) {
var alreadyIgnoring = !!this.currentState.ignoring,
hint = this.currentState.currentHint,
ignoreThis = !alreadyIgnoring && hint && hint.type === 'next';
if (ignoreThis) {
this.startIgnore();
node.postprocessor = this.endIgnore;
}
if (ignoreThis || alreadyIgnoring) {
branchLocation.skip = true;
}
};
}n/a
maybeAddType = function (node) {
var props = node.properties,
i,
child;
for (i = 0; i < props.length; i += 1) {
child = props[i];
if (!child.type) {
child.type = SYNTAX.Property.name;
}
}
}n/a
maybeSkipNode = function (node, type) {
var alreadyIgnoring = !!this.currentState.ignoring,
hint = this.currentState.currentHint,
ignoreThis = !alreadyIgnoring && hint && hint.type === type;
if (ignoreThis) {
this.startIgnore();
node.postprocessor = this.endIgnore;
return true;
}
return false;
}n/a
paranoidHandlerCheck = function (node) {
// if someone is using an older esprima on the browser
// convert handlers array to single handler attribute
// containing its first element
/* istanbul ignore next */
if (!node.handler && node.handlers) {
node.handler = node.handlers[0];
}
}n/a
skipInit = function (node) {
if (node.init) {
node.init.skipWalk = true;
}
}n/a
skipLeft = function (node) {
node.left.skipWalk = true;
}n/a
splice = function (statements, node, walker) {
var targetNode = walker.isLabeled() ? walker.parent().node : node;
targetNode.prepend = targetNode.prepend || [];
pushAll(targetNode.prepend, statements);
}...
Reference.prototype.replace = function replace(node) {
this.parent[this.key] = node;
};
Reference.prototype.remove = function remove() {
if (isArray(this.parent)) {
this.parent.splice(this.key, 1);
return true;
} else {
this.replace(null);
return false;
}
};
...startIgnore = function () {
this.currentState.ignoring += 1;
}n/a
statementName = function (location, initValue) {
var sName,
ignoring = !!this.currentState.ignoring;
location.skip = ignoring || undefined;
initValue = initValue || 0;
this.currentState.statement += 1;
sName = this.currentState.statement;
this.coverState.statementMap[sName] = location;
this.coverState.s[sName] = initValue;
return sName;
}n/a
switchBranchInjector = function (node, walker) {
var cases = node.cases,
bName,
i;
if (!(cases && cases.length > 0)) {
return;
}
bName = this.branchName('switch', walker.startLineForNode(node), this.locationsForNodes(cases));
for (i = 0; i < cases.length; i += 1) {
cases[i].branchLocation = this.branchLocationFor(bName, i);
cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName, i)));
}
}n/a
switchCaseInjector = function (node) {
var location = node.branchLocation;
delete node.branchLocation;
if (this.maybeSkipNode(node, 'next')) {
location.skip = true;
}
}n/a
withBlockConverter = function (node) {
node.body = this.convertToBlock(node.body);
}n/a
cover = function () {
/*
* <script>
* will run and cover <script>
*/
let tmp;
try {
tmp = JSON.parse(local.fs.readFileSync("package.json", "utf8"));
process.env.npm_package_nameLib = (
process.env.npm_package_nameLib
|| tmp.nameLib
|| tmp.name.replace((
/-/g
), "_")
);
} catch (ignore) {}
process.env.npm_config_mode_coverage = (
process.env.npm_config_mode_coverage
|| process.env.npm_package_nameLib
|| "all"
);
// add coverage hook to require
local.__istanbul_moduleExtensionsJs = (
local.__istanbul_module._extensions[".js"]
);
local.__istanbul_module._extensions[".js"] = function (module, file) {
if (typeof file === "string" && (
file.indexOf(process.env.npm_config_mode_coverage_dir) === 0 || (
file.indexOf(process.cwd() + local.path.sep) === 0
&& (
process.env.npm_config_mode_coverage === "node_modules"
|| file.indexOf(
local.path.resolve("node_modules") + local.path.sep
) !== 0
)
)
)) {
module._compile(local.instrumentInPackage(
local.fs.readFileSync(file, "utf8"),
file
), file);
return;
}
local.__istanbul_moduleExtensionsJs(module, file);
};
// init process.argv
process.argv.splice(1, 2);
process.argv[1] = local.path.resolve(process.argv[1]);
console.error("\nistanbul - covering $ " + process.argv.join(" "));
// create coverage on exit
process.on("exit", function () {
local.coverageReportCreate({
coverage: globalThis.__coverage__
});
});
// re-init cli
local.__istanbul_module.runMain();
}n/a
instrument = function () {
/*
* <script>
* will instrument <script> and print result to stdout
*/
process.argv[3] = local.path.resolve(process.argv[3]);
process.stdout.write(local.instrumentSync(
local.fs.readFileSync(process.argv[3], "utf8"),
process.argv[3]
));
}n/a
report = function () {
/*
* <coverageJson>
* will create coverage-report from file <coverageJson>
*/
process.argv[3] = local.path.resolve(process.argv[3]);
globalThis.__coverage__ = JSON.parse(
local.fs.readFileSync(process.argv[3])
);
globalThis.__coverageInclude__ = {};
Object.keys(globalThis.__coverage__).forEach(function (file) {
globalThis.__coverageInclude__[file] = 1;
});
local.coverageReportCreate({
coverage: globalThis.__coverage__
});
}n/a
test = function () {
/*
* <script>
* will run and cover <script> if env-var $npm_config_mode_coverage is set
*/
if (process.env.npm_config_mode_coverage) {
process.argv[2] = "cover";
// re-init cli
local.cliDict[process.argv[2]]();
return;
}
// restart node with __filename removed from process.argv
process.argv.splice(1, 2);
process.argv[1] = local.path.resolve(process.argv[1]);
// re-init cli
local.__istanbul_module.runMain();
}...
return {
elemList: Object.keys(module).filter(function (key) {
return local.tryCatchOnError(function () {
return (
key
&& (
/^\w[\w\-.]*?$/
).test(key)
&& key.indexOf("testCase_") !== 0
&& (
module[key] !== opt.blacklistDict[key]
|| opt.whitelistDict[key]
)
);
}, console.error);
...function attachComments(tree, providedComments, tokens) {
// At first, we should calculate extended comment ranges.
var comments = [], comment, len, i, cursor;
if (!tree.range) {
throw new Error('attachComments needs range information');
}
// tokens array is empty, we attach comments to tree as 'leadingComments'
if (!tokens.length) {
if (providedComments.length) {
for (i = 0, len = providedComments.length; i < len; i += 1) {
comment = deepCopy(providedComments[i]);
comment.extendedRange = [0, tree.range[0]];
comments.push(comment);
}
tree.leadingComments = comments;
}
return tree;
}
for (i = 0, len = providedComments.length; i < len; i += 1) {
comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
}
// This is based on John Freeman's implementation.
cursor = 0;
traverse(tree, {
enter: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (comment.extendedRange[1] > node.range[0]) {
break;
}
if (comment.extendedRange[1] === node.range[0]) {
if (!node.leadingComments) {
node.leadingComments = [];
}
node.leadingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
cursor = 0;
traverse(tree, {
leave: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (node.range[1] < comment.extendedRange[0]) {
break;
}
if (node.range[1] === comment.extendedRange[0]) {
if (!node.trailingComments) {
node.trailingComments = [];
}
node.trailingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
return tree;
}n/a
function generate(node, options) {
var defaultOptions = getDefaultOptions(), result, pair;
if (options != null) {
// Obsolete options
//
// `options.indent`
// `options.base`
//
// Instead of them, we can use `option.format.indent`.
if (typeof options.indent === 'string') {
defaultOptions.format.indent.style = options.indent;
}
if (typeof options.base === 'number') {
defaultOptions.format.indent.base = options.base;
}
options = updateDeeply(defaultOptions, options);
indent = options.format.indent.style;
if (typeof options.base === 'string') {
base = options.base;
} else {
base = stringRepeat(indent, options.format.indent.base);
}
} else {
options = defaultOptions;
indent = options.format.indent.style;
base = stringRepeat(indent, options.format.indent.base);
}
json = options.format.json;
renumber = options.format.renumber;
hexadecimal = json ? false : options.format.hexadecimal;
quotes = json ? 'double' : options.format.quotes;
escapeless = options.format.escapeless;
newline = options.format.newline;
space = options.format.space;
if (options.format.compact) {
newline = space = indent = base = '';
}
parentheses = options.format.parentheses;
semicolons = options.format.semicolons;
safeConcatenation = options.format.safeConcatenation;
directive = options.directive;
parse = json ? null : options.parse;
sourceMap = options.sourceMap;
sourceCode = options.sourceCode;
preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;
extra = options;
if (sourceMap) {
if (!exports.browser) {
// We assume environment is node.js
// And prevent from including source-map by browserify
SourceNode = require('source-map').SourceNode;
} else {
SourceNode = global.sourceMap.SourceNode;
}
}
result = generateInternal(node);
if (!sourceMap) {
pair = {code: result.toString(), map: null};
return options.sourceMapWithCode ? pair : pair.code;
}
pair = result.toStringWithSourceMap({
file: options.file,
sourceRoot: options.sourceMapRoot
});
if (options.sourceContent) {
pair.map.setSourceContent(options.sourceMap,
options.sourceContent);
}
if (options.sourceMapWithCode) {
return pair;
}
return pair.map.toString();
}n/a
function Node(parser, pos, loc) {
this.type = "";
this.start = pos;
this.end = 0;
if (parser.options.locations)
{ this.loc = new SourceLocation(parser, loc); }
if (parser.options.directSourceFile)
{ this.sourceFile = parser.options.directSourceFile; }
if (parser.options.ranges)
{ this.range = [pos, 0]; }
}n/a
function Parser(options, input, startPos) {
this.options = options = getOptions(options);
this.sourceFile = options.sourceFile;
this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
var reserved = "";
if (options.allowReserved !== true) {
for (var v = options.ecmaVersion;; v--)
{ if (reserved = reservedWords[v]) { break } }
if (options.sourceType === "module") { reserved += " await"; }
}
this.reservedWords = wordsRegexp(reserved);
var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
this.reservedWordsStrict = wordsRegexp(reservedStrict);
this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
this.input = String(input);
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
this.containsEsc = false;
// Set up token state
// The current position of the tokenizer in the input.
if (startPos) {
this.pos = startPos;
this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
} else {
this.pos = this.lineStart = 0;
this.curLine = 1;
}
// Properties of the current token:
// Its type
this.type = types.eof;
// For tokens that include more information than their type, the value
this.value = null;
// Its start and end offset
this.start = this.end = this.pos;
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = this.curPosition();
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null;
this.lastTokStart = this.lastTokEnd = this.pos;
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext();
this.exprAllowed = true;
// Figure out if it's a module code.
this.inModule = options.sourceType === "module";
this.strict = this.inModule || this.strictDirective(this.pos);
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1;
// Positions to delayed-check that yield/await does not exist in default parameters.
this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
// Labels in scope.
this.labels = [];
// Thus-far undefined exports.
this.undefinedExports = {};
// If enabled, skip leading hashbang line.
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
{ this.skipLineComment(2); }
// Scope tracking for duplicate variable names (see scope.js)
this.scopeStack = [];
this.enterScope(SCOPE_TOP);
// For RegExp validation
this.regexpState = null;
}n/a
function Position(line, col) {
this.line = line;
this.column = col;
}n/a
function SourceLocation(p, start, end) {
this.start = start;
this.end = end;
if (p.sourceFile !== null) { this.source = p.sourceFile; }
}n/a
function TokContext(token, isExpr, preserveSpace, override, generator) {
this.token = token;
this.isExpr = !!isExpr;
this.preserveSpace = !!preserveSpace;
this.override = override;
this.generator = !!generator;
}n/a
function Token(p) {
this.type = p.type;
this.value = p.value;
this.start = p.start;
this.end = p.end;
if (p.options.locations)
{ this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
if (p.options.ranges)
{ this.range = [p.start, p.end]; }
}n/a
function TokenType(label, conf) {
if ( conf === void 0 ) conf = {};
this.label = label;
this.keyword = conf.keyword;
this.beforeExpr = !!conf.beforeExpr;
this.startsExpr = !!conf.startsExpr;
this.isLoop = !!conf.isLoop;
this.isAssign = !!conf.isAssign;
this.prefix = !!conf.prefix;
this.postfix = !!conf.postfix;
this.binop = conf.binop || null;
this.updateContext = null;
}n/a
function getLineInfo(input, offset) {
for (var line = 1, cur = 0;;) {
lineBreakG.lastIndex = cur;
var match = lineBreakG.exec(input);
if (match && match.index < offset) {
++line;
cur = match.index + match[0].length;
} else {
return new Position(line, offset - cur)
}
}
}n/a
function isIdentifierChar(code, astral) {
if (code < 48) { return code === 36 }
if (code < 58) { return true }
if (code < 65) { return false }
if (code < 91) { return true }
if (code < 97) { return code === 95 }
if (code < 123) { return true }
if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
if (astral === false) { return false }
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
}n/a
function isIdentifierStart(code, astral) {
if (code < 65) { return code === 36 }
if (code < 91) { return true }
if (code < 97) { return code === 95 }
if (code < 123) { return true }
if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
if (astral === false) { return false }
return isInAstralSet(code, astralIdentifierStartCodes)
}n/a
function isNewLine(code, ecma2019String) {
return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
}n/a
function parse(input, options) {
return Parser.parse(input, options)
}...
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
};
local.fsRmrfSync = function (pathname) {
...function parseExpressionAt(input, pos, options) {
return Parser.parseExpressionAt(input, pos, options)
}...
}
// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.
function parseExpressionAt(input, pos, options) {
return Parser.parseExpressionAt(input, pos, options)
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenizer` export provides an interface to the tokenizer.
function tokenizer(input, options) {
return Parser.tokenizer(input, options)
...function tokenizer(input, options) {
return Parser.tokenizer(input, options)
}...
return Parser.parseExpressionAt(input, pos, options)
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenizer` export provides an interface to the tokenizer.
function tokenizer(input, options) {
return Parser.tokenizer(input, options)
}
exports.Node = Node;
exports.Parser = Parser;
exports.Position = Position;
exports.SourceLocation = SourceLocation;
exports.TokContext = TokContext;
...function(statements) {
for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
statements[i].directive = statements[i].expression.raw.slice(1, -1);
}
}...
if (this.inModule)
{ for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
{
var name = list[i];
this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined
"));
} }
this.adaptDirectivePrologue(node.body);
this.next();
node.sourceType = this.options.sourceType;
return this.finishNode(node, "Program")
};
var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
...function(tokType, notNext) {
if (this.type === tokType) {
if (this.options.onTrailingComma)
{ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
if (!notNext)
{ this.next(); }
return true
}
}...
pp$1.parseExportSpecifiers = function(exports) {
var nodes = [], first = true;
// export { x, y as z } [from '...']
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
if (!first) {
this.expect(types.comma);
if (this.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var node = this.startNode();
node.local = this.parseIdent(true);
node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
this.checkExport(exports, node.exported.name, node.exported.start);
nodes.push(this.finishNode(node, "ExportSpecifier"));
...function(prevType) {
var parent = this.curContext();
if (parent === types$1.f_expr || parent === types$1.f_stat)
{ return true }
if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
{ return !parent.isExpr }
// The check for `tt.name && exprAllowed` detects whether we are
// after a `yield` or `of` construct. See the `updateContext` for
// `tt.name`.
if (prevType === types._return || prevType === types.name && this.exprAllowed)
{ return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType ===
types.arrow)
{ return true }
if (prevType === types.braceL)
{ return parent === types$1.b_stat }
if (prevType === types._var || prevType === types._const || prevType === types.name)
{ return false }
return !this.exprAllowed
}...
if (out === types$1.b_stat && this.curContext().token === "function") {
out = this.context.pop();
}
this.exprAllowed = !out.isExpr;
};
types.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
this.exprAllowed = true;
};
types.dollarBraceL.updateContext = function() {
this.context.push(types$1.b_tmpl);
this.exprAllowed = true;
};
...function(startPos, startLoc, left, right, op, logical) {
var node = this.startNodeAt(startPos, startLoc);
node.left = left;
node.operator = op;
node.right = right;
return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
}...
if (prec != null && (!noIn || this.type !== types._in)) {
if (prec > minPrec) {
var logical = this.type === types.logicalOR || this.type === types.logicalAND;
var op = this.value;
this.next();
var startPos = this.start, startLoc = this.startLoc;
var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical
);
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
}
}
return left
};
pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
...function() {
return this.type === types.eof ||
this.type === types.braceR ||
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
}...
pp.canInsertSemicolon = function() {
return this.type === types.eof ||
this.type === types.braceR ||
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};
pp.insertSemicolon = function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon)
{ this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
return true
}
};
// Consume a semicolon, or, failing that, see if we are allowed to
...function(exports, name, pos) {
if (!exports) { return }
if (has(exports, name))
{ this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
exports[name] = true;
}...
this.expectContextual("from");
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
this.semicolon();
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(types._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart);
var isAsync;
if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode();
this.next();
if (isAsync) { this.next(); }
node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
} else if (this.type === types._class) {
...function(refDestructuringErrors, andThrow) {
if (!refDestructuringErrors) { return false }
var shorthandAssign = refDestructuringErrors.shorthandAssign;
var doubleProto = refDestructuringErrors.doubleProto;
if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
if (shorthandAssign >= 0)
{ this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
if (doubleProto >= 0)
{ this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
}...
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
this.toAssignable(init, false, refDestructuringErrors);
this.checkLVal(init);
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true);
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init)
};
pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
this.next();
...function(expr, bindingType, checkClashes) {
if ( bindingType === void 0 ) bindingType = BIND_NONE;
switch (expr.type) {
case "Identifier":
if (bindingType === BIND_LEXICAL && expr.name === "let")
{ this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
if (this.strict && this.reservedWordsStrictBind.test(expr.name))
{ this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
if (checkClashes) {
if (has(checkClashes, expr.name))
{ this.raiseRecoverable(expr.start, "Argument name clash"); }
checkClashes[expr.name] = true;
}
if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
break
case "MemberExpression":
if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); }
break
case "ObjectPattern":
for (var i = 0, list = expr.properties; i < list.length; i += 1)
{
var prop = list[i];
this.checkLVal(prop, bindingType, checkClashes);
}
break
case "Property":
// AssignmentProperty has type === "Property"
this.checkLVal(expr.value, bindingType, checkClashes);
break
case "ArrayPattern":
for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
var elem = list$1[i$1];
if (elem) { this.checkLVal(elem, bindingType, checkClashes); }
}
break
case "AssignmentPattern":
this.checkLVal(expr.left, bindingType, checkClashes);
break
case "RestElement":
this.checkLVal(expr.argument, bindingType, checkClashes);
break
case "ParenthesizedExpression":
this.checkLVal(expr.expression, bindingType, checkClashes);
break
default:
this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
}
}...
if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
this.toAssignable(init, false, refDestructuringErrors);
this.checkLVal(init);
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true);
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init)
};
...function(id) {
// scope.functions must be empty as Module code is always strict.
if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
this.scopeStack[0].var.indexOf(id.name) === -1) {
this.undefinedExports[id.name] = id;
}
}...
} else {
for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
// check for keywords used as local names
var spec = list[i];
this.checkUnreserved(spec.local);
// check if export is defined
this.checkLocalExport(spec.local);
}
node.source = null;
}
this.semicolon();
}
return this.finishNode(node, "ExportNamedDeclaration")
...function(node, allowDuplicates) {
var nameHash = {};
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash);
}
}...
pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
var isExpression = isArrowFunction && this.type !== types.braceL;
var oldStrict = this.strict, useStrict = false;
if (isExpression) {
node.body = this.parseMaybeAssign();
node.expression = true;
this.checkParams(node, false);
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end);
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
...function(refDestructuringErrors, isAssign) {
if (!refDestructuringErrors) { return }
if (refDestructuringErrors.trailingComma > -1)
{ this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
}...
case "ObjectPattern":
case "ArrayPattern":
case "RestElement":
break
case "ObjectExpression":
node.type = "ObjectPattern";
if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
this.toAssignable(prop, isBinding);
// Early error:
// AssignmentRestProperty[Yield, Await] :
// `...` DestructuringAssignmentTarget[Yield, Await]
...function(exports, pat) {
var type = pat.type;
if (type === "Identifier")
{ this.checkExport(exports, pat.name, pat.start); }
else if (type === "ObjectPattern")
{ for (var i = 0, list = pat.properties; i < list.length; i += 1)
{
var prop = list[i];
this.checkPatternExport(exports, prop);
} }
else if (type === "ArrayPattern")
{ for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
var elt = list$1[i$1];
if (elt) { this.checkPatternExport(exports, elt); }
} }
else if (type === "Property")
{ this.checkPatternExport(exports, pat.value); }
else if (type === "AssignmentPattern")
{ this.checkPatternExport(exports, pat.left); }
else if (type === "RestElement")
{ this.checkPatternExport(exports, pat.argument); }
else if (type === "ParenthesizedExpression")
{ this.checkPatternExport(exports, pat.expression); }
}...
if (type === "Identifier")
{ this.checkExport(exports, pat.name, pat.start); }
else if (type === "ObjectPattern")
{ for (var i = 0, list = pat.properties; i < list.length; i += 1)
{
var prop = list[i];
this.checkPatternExport(exports, prop);
} }
else if (type === "ArrayPattern")
{ for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
var elt = list$1[i$1];
if (elt) { this.checkPatternExport(exports, elt); }
} }
...function(prop, propHash, refDestructuringErrors) {
if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
{ return }
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
{ return }
var key = prop.key;
var name;
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
var kind = prop.kind;
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) {
if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; }
// Backwards-compat kludge. Can be removed in version 6.0
else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
}
propHash.proto = true;
}
return
}
name = "$" + name;
var other = propHash[name];
if (other) {
var redefinition;
if (kind === "init") {
redefinition = this.strict && other.init || other.get || other.set;
} else {
redefinition = other.init || other[kind];
}
if (redefinition)
{ this.raiseRecoverable(key.start, "Redefinition of property"); }
} else {
other = propHash[name] = {
init: false,
get: false,
set: false
};
}
other[kind] = true;
}...
while (!this.eat(types.braceR)) {
if (!first) {
this.expect(types.comma);
if (this.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var prop = this.parseProperty(isPattern, refDestructuringErrors);
if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
node.properties.push(prop);
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
};
pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
...function(ref) {
var start = ref.start;
var end = ref.end;
var name = ref.name;
if (this.inGenerator && name === "yield")
{ this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
if (this.inAsync && name === "await")
{ this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
if (this.keywords.test(name))
{ this.raise(start, ("Unexpected keyword '" + name + "'")); }
if (this.options.ecmaVersion < 6 &&
this.input.slice(start, end).indexOf("\\") !== -1) { return }
var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
if (re.test(name)) {
if (!this.inAsync && name === "await")
{ this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
}
}...
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
} else {
for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
// check for keywords used as local names
var spec = list[i];
this.checkUnreserved(spec.local);
// check if export is defined
this.checkLocalExport(spec.local);
}
node.source = null;
}
this.semicolon();
...function(exports, decls) {
if (!exports) { return }
for (var i = 0, list = decls; i < list.length; i += 1)
{
var decl = list[i];
this.checkPatternExport(exports, decl.id);
}
}...
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(null);
if (node.declaration.type === "VariableDeclaration")
{ this.checkVariableExport(exports, node.declaration.declarations); }
else
{ this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
node.specifiers = [];
node.source = null;
} else { // export { x, y as z } [from '...']
node.declaration = null;
node.specifiers = this.parseExportSpecifiers(exports);
...function() {
if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
{ this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
if (this.awaitPos)
{ this.raise(this.awaitPos, "Await expression cannot be a default value"); }
}...
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression"
;)
};
pp$1.parseFunctionParams = function(node) {
this.expect(types.parenL);
node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
};
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseClass = function(node, isStatement) {
this.next();
...function() {
return this.context[this.context.length - 1]
}...
var pp$7 = Parser.prototype;
pp$7.initialContext = function() {
return [types$1.b_stat]
};
pp$7.braceIsBlock = function(prevType) {
var parent = this.curContext();
if (parent === types$1.f_expr || parent === types$1.f_stat)
{ return true }
if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
{ return !parent.isExpr }
// The check for `tt.name && exprAllowed` detects whether we are
// after a `yield` or `of` construct. See the `updateContext` for
...function() {
if (this.options.locations) {
return new Position(this.curLine, this.pos - this.lineStart)
}
}...
this.type = types.eof;
// For tokens that include more information than their type, the value
this.value = null;
// Its start and end offset
this.start = this.end = this.pos;
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = this.curPosition();
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null;
this.lastTokStart = this.lastTokEnd = this.pos;
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
...function() {
return this.scopeStack[this.scopeStack.length - 1]
}...
};
prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
// Switch to a getter for 7.0.0.
Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION
) > 0 };
Parser.extend = function extend () {
var plugins = [], len = arguments.length;
while ( len-- ) plugins[ len ] = arguments[ len ];
...function() {
for (var i = this.scopeStack.length - 1;; i--) {
var scope = this.scopeStack[i];
if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
}
}...
this.nextToken();
return this.parseTopLevel(node)
};
prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags
& SCOPE_SUPER) > 0 };
prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
// Switch to a getter for 7.0.0.
Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION
) > 0 };
Parser.extend = function extend () {
...function() {
for (var i = this.scopeStack.length - 1;; i--) {
var scope = this.scopeStack[i];
if (scope.flags & SCOPE_VAR) { return scope }
}
}...
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode();
this.nextToken();
return this.parseTopLevel(node)
};
prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags
& SCOPE_FUNCTION) > 0 };
prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
// Switch to a getter for 7.0.0.
...function(name, bindingType, pos) {
var redeclared = false;
if (bindingType === BIND_LEXICAL) {
var scope = this.currentScope();
redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
scope.lexical.push(name);
if (this.inModule && (scope.flags & SCOPE_TOP))
{ delete this.undefinedExports[name]; }
} else if (bindingType === BIND_SIMPLE_CATCH) {
var scope$1 = this.currentScope();
scope$1.lexical.push(name);
} else if (bindingType === BIND_FUNCTION) {
var scope$2 = this.currentScope();
if (this.treatFunctionsAsVar)
{ redeclared = scope$2.lexical.indexOf(name) > -1; }
else
{ redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
scope$2.functions.push(name);
} else {
for (var i = this.scopeStack.length - 1; i >= 0; --i) {
var scope$3 = this.scopeStack[i];
if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
!this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
redeclared = true;
break
}
scope$3.var.push(name);
if (this.inModule && (scope$3.flags & SCOPE_TOP))
{ delete this.undefinedExports[name]; }
if (scope$3.flags & SCOPE_VAR) { break }
}
}
if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
}...
if (this.strict && this.reservedWordsStrictBind.test(expr.name))
{ this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in
strict mode"); }
if (checkClashes) {
if (has(checkClashes, expr.name))
{ this.raiseRecoverable(expr.start, "Argument name clash"); }
checkClashes[expr.name] = true;
}
if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName
span>(expr.name, bindingType, expr.start); }
break
case "MemberExpression":
if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); }
break
case "ObjectPattern":
...function(type) {
if (this.type === type) {
this.next();
return true
} else {
return false
}
}...
}
};
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
pp.semicolon = function() {
if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
};
pp.afterTrailingComma = function(tokType, notNext) {
if (this.type === tokType) {
if (this.options.onTrailingComma)
{ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
if (!notNext)
...function(name) {
if (!this.isContextual(name)) { return false }
this.next();
return true
}...
this.next();
return true
};
// Asserts that following token is given contextual keyword.
pp.expectContextual = function(name) {
if (!this.eatContextual(name)) { this.unexpected(); }
};
// Test whether a semicolon can be inserted at the current position.
pp.canInsertSemicolon = function() {
return this.type === types.eof ||
this.type === types.braceR ||
...function(flags) {
this.scopeStack.push(new Scope(flags));
}...
// If enabled, skip leading hashbang line.
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
{ this.skipLineComment(2); }
// Scope tracking for duplicate variable names (see scope.js)
this.scopeStack = [];
this.enterScope(SCOPE_TOP);
// For RegExp validation
this.regexpState = null;
};
var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },
allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } };
...function() {
this.scopeStack.pop();
}...
}
this.expect(types.colon);
} else {
if (!cur) { this.unexpected(); }
cur.consequent.push(this.parseStatement(null));
}
}
this.exitScope();
if (cur) { this.finishNode(cur, "SwitchCase"); }
this.next(); // Closing brace
this.labels.pop();
return this.finishNode(node, "SwitchStatement")
};
pp$1.parseThrowStatement = function(node) {
...function(type) {
this.eat(type) || this.unexpected();
}...
};
pp$1.parseDoStatement = function(node) {
this.next();
this.labels.push(loopLabel);
node.body = this.parseStatement("do");
this.labels.pop();
this.expect(types._while);
node.test = this.parseParenExpression();
if (this.options.ecmaVersion >= 6)
{ this.eat(types.semi); }
else
{ this.semicolon(); }
return this.finishNode(node, "DoWhileStatement")
};
...function(name) {
if (!this.eatContextual(name)) { this.unexpected(); }
}...
// Parses module export declaration.
pp$1.parseExport = function(node, exports) {
this.next();
// export * from '...'
if (this.eat(types.star)) {
this.expectContextual("from");
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
this.semicolon();
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(types._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart);
...function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
}...
var name = list[i];
this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined
"));
} }
this.adaptDirectivePrologue(node.body);
this.next();
node.sourceType = this.options.sourceType;
return this.finishNode(node, "Program")
};
var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
pp$1.isLet = function(context) {
if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
skipWhiteSpace.lastIndex = this.pos;
...function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
}...
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
} else {
val = exprList[0];
}
} else {
val = this.parseParenExpression();
}
...function(type, size) {
var str = this.input.slice(this.pos, this.pos + size);
this.pos += size;
return this.finishToken(type, str)
}...
return this.finishToken(types.dot)
}
};
pp$9.readToken_slash = function() { // '/'
var next = this.input.charCodeAt(this.pos + 1);
if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(types.slash, 1)
};
pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
var tokentype = code === 42 ? types.star : types.modulo;
...function(type, val) {
this.end = this.pos;
if (this.options.locations) { this.endLoc = this.curPosition(); }
var prevType = this.type;
this.type = type;
this.value = val;
this.updateContext(prevType);
}...
pp$9.nextToken = function() {
var curContext = this.curContext();
if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
this.start = this.pos;
if (this.options.locations) { this.startLoc = this.curPosition(); }
if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
if (curContext.override) { return curContext.override(this) }
else { this.readToken(this.fullCharCodeAtPos()); }
};
pp$9.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
...function() {
var code = this.input.charCodeAt(this.pos);
if (code <= 0xd7ff || code >= 0xe000) { return code }
var next = this.input.charCodeAt(this.pos + 1);
return (code << 10) + next - 0x35fdc00
}...
if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
this.start = this.pos;
if (this.options.locations) { this.startLoc = this.curPosition(); }
if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
if (curContext.override) { return curContext.override(this) }
else { this.readToken(this.fullCharCodeAtPos()); }
};
pp$9.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
{ return this.readWord() }
...function() {
this.next();
return new Token(this)
}...
// When `locations` is on, `loc` properties holding objects with
// `start` and `end` properties in `{line, column}` form (with
// line being 1-based and column 0-based) will be attached to the
// nodes.
locations: false,
// A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same
// format as tokens returned from `tokenizer().getToken()`. Note
// that you are not allowed to call the parser from the
// callback—that will corrupt its internal state.
onToken: null,
// A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start,
// end)` parameters whenever a comment is skipped. `block` is a
// boolean indicating whether this is a block (`/* */`) comment,
...function(code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot()
// Punctuation tokens.
case 40: ++this.pos; return this.finishToken(types.parenL)
case 41: ++this.pos; return this.finishToken(types.parenR)
case 59: ++this.pos; return this.finishToken(types.semi)
case 44: ++this.pos; return this.finishToken(types.comma)
case 91: ++this.pos; return this.finishToken(types.bracketL)
case 93: ++this.pos; return this.finishToken(types.bracketR)
case 123: ++this.pos; return this.finishToken(types.braceL)
case 125: ++this.pos; return this.finishToken(types.braceR)
case 58: ++this.pos; return this.finishToken(types.colon)
case 63: ++this.pos; return this.finishToken(types.question)
case 96: // '`'
if (this.options.ecmaVersion < 6) { break }
++this.pos;
return this.finishToken(types.backQuote)
case 48: // '0'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
return this.readNumber(false)
// Quotes produce strings.
case 34: case 39: // '"', "'"
return this.readString(code)
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 126: // '~'
return this.finishOp(types.prefix, 1)
}
this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
}...
pp$9.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
{ return this.readWord() }
return this.getTokenFromCode(code)
};
pp$9.fullCharCodeAtPos = function() {
var code = this.input.charCodeAt(this.pos);
if (code <= 0xd7ff || code >= 0xe000) { return code }
var next = this.input.charCodeAt(this.pos + 1);
return (code << 10) + next - 0x35fdc00
...function() {
for (var i = this.context.length - 1; i >= 1; i--) {
var context = this.context[i];
if (context.token === "function")
{ return context.generator }
}
return false
}...
this.exprAllowed = true;
};
types.name.updateContext = function(prevType) {
var allowed = false;
if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
if (this.value === "of" && !this.exprAllowed ||
this.value === "yield" && this.inGeneratorContext())
{ allowed = true; }
}
this.exprAllowed = allowed;
};
// This file contains Unicode properties extracted from the ECMAScript
// specification. The lists are extracted like so:
...function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }...
var meta = this.parseIdent(true);
if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
node.meta = meta;
var containsEsc = this.containsEsc;
node.property = this.parseIdent(true);
if (node.property.name !== "target" || containsEsc)
{ this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); }
if (!this.inNonArrowFunction())
{ this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc;
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
if (this.options.ecmaVersion > 10 && node.callee.type === "Import") {
this.raise(node.callee.start, "Cannot use new with import(...)");
...function(node) {
node.id = null;
if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
if (this.options.ecmaVersion >= 8) { node.async = false; }
}...
var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
// Parse a function declaration or literal (depending on the
// `statement & FUNC_STATEMENT`).
// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
this.initFunction(node);
if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
{ this.unexpected(); }
node.generator = this.eat(types.star);
}
if (this.options.ecmaVersion >= 8)
{ node.async = !!isAsync; }
...function() {
return [types$1.b_stat]
}...
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null;
this.lastTokStart = this.lastTokEnd = this.pos;
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext();
this.exprAllowed = true;
// Figure out if it's a module code.
this.inModule = options.sourceType === "module";
this.strict = this.inModule || this.strictDirective(this.pos);
// Used to signify the start of a potential arrow function
...function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon)
{ this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
return true
}
}...
}
};
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
pp.semicolon = function() {
if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
};
pp.afterTrailingComma = function(tokType, notNext) {
if (this.type === tokType) {
if (this.options.onTrailingComma)
{ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
if (!notNext)
...function(position, message) {
if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
throw INVALID_TEMPLATE_ESCAPE_ERROR
} else {
this.raise(position, message);
}
}...
var ch = this.input.charCodeAt(this.pos), code;
if (ch === 123) { // '{'
if (this.options.ecmaVersion < 6) { this.unexpected(); }
var codePos = ++this.pos;
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
++this.pos;
if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of
bounds"); }
} else {
code = this.readHexChar(4);
}
return code
};
function codePointToString$1(code) {
...function() {
if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
{ return false }
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length;
return !lineBreak.test(this.input.slice(this.pos, next)) &&
this.input.slice(next, next + 8) === "function" &&
(next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
}...
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
if (this.isAsyncFunction()) {
if (context) { this.unexpected(); }
this.next();
return this.parseFunctionStatement(node, true, !context)
}
var maybeName = this.value, expr = this.parseExpression();
if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
...function(prop) {
return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
(this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type
.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
!lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
}...
startLoc = this.startLoc;
}
if (!isPattern)
{ isGenerator = this.eat(types.star); }
}
var containsEsc = this.containsEsc;
this.parsePropertyName(prop);
if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
isAsync = true;
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
this.parsePropertyName(prop, refDestructuringErrors);
} else {
isAsync = false;
}
this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
...function(name) {
return this.type === types.name && this.value === name && !this.containsEsc
}...
pp.isContextual = function(name) {
return this.type === types.name && this.value === name && !this.containsEsc
};
// Consumes contextual keyword if possible.
pp.eatContextual = function(name) {
if (!this.isContextual(name)) { return false }
this.next();
return true
};
// Asserts that following token is given contextual keyword.
pp.expectContextual = function(name) {
...function(statement) {
return (
statement.type === "ExpressionStatement" &&
statement.expression.type === "Literal" &&
typeof statement.expression.value === "string" &&
// Reject parenthesized strings.
(this.input[statement.start] === "\"" || this.input[statement.start] === "'")
)
}...
nodes.push(this.finishNode(node$2, "ImportSpecifier"));
}
return nodes
};
// Set `ExpressionStatement#directive` property for directive prologues.
pp$1.adaptDirectivePrologue = function(statements) {
for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements
[i]); ++i) {
statements[i].directive = statements[i].expression.raw.slice(1, -1);
}
};
pp$1.isDirectiveCandidate = function(statement) {
return (
statement.type === "ExpressionStatement" &&
statement.expression.type === "Literal" &&
...function(context) {
if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
// For ambiguous cases, determine if a LexicalDeclaration (or only a
// Statement) is allowed here. If context is not empty then only a Statement
// is allowed. However, `let [` is an explicit negative lookahead for
// ExpressionStatement, so special-case it first.
if (nextCh === 91) { return true } // '['
if (context) { return false }
if (nextCh === 123) { return true } // '{'
if (isIdentifierStart(nextCh, true)) {
var pos = next + 1;
while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
var ident = this.input.slice(next, pos);
if (!keywordRelationalOperator.test(ident)) { return true }
}
return false
}...
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp$1.parseStatement = function(context, topLevel, exports) {
var starttype = this.type, node = this.startNode(), kind;
if (this.isLet(context)) {
starttype = types._var;
kind = "let";
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
...function(expr) {
if (expr.type === "ParenthesizedExpression")
{ return this.isSimpleAssignTarget(expr.expression) }
return expr.type === "Identifier" || expr.type === "MemberExpression"
}...
{ this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
if (this.awaitPos)
{ this.raise(this.awaitPos, "Await expression cannot be a default value"); }
};
pp.isSimpleAssignTarget = function(expr) {
if (expr.type === "ParenthesizedExpression")
{ return this.isSimpleAssignTarget(expr.expression) }
return expr.type === "Identifier" || expr.type === "MemberExpression"
};
var pp$1 = Parser.prototype;
// ### Statement parsing
...function(params) {
for (var i = 0, list = params; i < list.length; i += 1)
{
var param = list[i];
if (param.type !== "Identifier") { return false
} }
return true
}...
var oldStrict = this.strict, useStrict = false;
if (isExpression) {
node.body = this.parseMaybeAssign();
node.expression = true;
this.checkParams(node, false);
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(
node.params);
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end);
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (useStrict && nonSimple)
{ this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list
"); }
...function() {
if (this.options.onToken)
{ this.options.onToken(new Token(this)); }
this.lastTokEnd = this.end;
this.lastTokStart = this.start;
this.lastTokEndLoc = this.endLoc;
this.lastTokStartLoc = this.startLoc;
this.nextToken();
}...
};
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp.eat = function(type) {
if (this.type === type) {
this.next();
return true
} else {
return false
}
};
// Tests whether parsed token is a contextual keyword.
...function() {
var curContext = this.curContext();
if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
this.start = this.pos;
if (this.options.locations) { this.startLoc = this.curPosition(); }
if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
if (curContext.override) { return curContext.override(this) }
else { this.readToken(this.fullCharCodeAtPos()); }
}...
this.regexpState = null;
};
var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },
allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } };
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode();
this.nextToken();
return this.parseTopLevel(node)
};
prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
...function parse () {
var node = this.options.program || this.startNode();
this.nextToken();
return this.parseTopLevel(node)
}...
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
};
local.fsRmrfSync = function (pathname) {
...function(node, params, isAsync) {
var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
this.initFunction(node);
if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
node.params = this.toAssignableList(params, true);
this.parseFunctionBody(node, true, false);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, "ArrowFunctionExpression")
}...
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
if (this.awaitIdentPos > 0)
{ this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true
)
}
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.callee = base;
...function() {
if (!this.awaitPos) { this.awaitPos = this.start; }
var node = this.startNode();
this.next();
node.argument = this.parseMaybeUnary(null, true);
return this.finishNode(node, "AwaitExpression")
}...
};
// Parse unary operators, both prefix and postfix.
pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
var startPos = this.start, startLoc = this.startLoc, expr;
if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction
))) {
expr = this.parseAwait();
sawUnary = true;
} else if (this.type.prefix) {
var node = this.startNode(), update = this.type === types.incDec;
node.operator = this.value;
node.prefix = true;
this.next();
node.argument = this.parseMaybeUnary(null, true);
...function() {
if (this.options.ecmaVersion >= 6) {
switch (this.type) {
case types.bracketL:
var node = this.startNode();
this.next();
node.elements = this.parseBindingList(types.bracketR, true, true);
return this.finishNode(node, "ArrayPattern")
case types.braceL:
return this.parseObj(true)
}
}
return this.parseIdent()
}...
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.type === types._catch) {
var clause = this.startNode();
this.next();
if (this.eat(types.parenL)) {
clause.param = this.parseBindingAtom();
var simple = clause.param.type === "Identifier";
this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
this.expect(types.parenR);
} else {
if (this.options.ecmaVersion < 10) { this.unexpected(); }
clause.param = null;
...function(close, allowEmpty, allowTrailingComma) {
var elts = [], first = true;
while (!this.eat(close)) {
if (first) { first = false; }
else { this.expect(types.comma); }
if (allowEmpty && this.type === types.comma) {
elts.push(null);
} else if (allowTrailingComma && this.afterTrailingComma(close)) {
break
} else if (this.type === types.ellipsis) {
var rest = this.parseRestBinding();
this.parseBindingListItem(rest);
elts.push(rest);
if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
this.expect(close);
break
} else {
var elem = this.parseMaybeDefault(this.start, this.startLoc);
this.parseBindingListItem(elem);
elts.push(elem);
}
}
return elts
}...
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression"
;)
};
pp$1.parseFunctionParams = function(node) {
this.expect(types.parenL);
node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion &
gt;= 8);
this.checkYieldAwaitInDefaultParams();
};
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseClass = function(node, isStatement) {
...function(param) {
return param
}...
else { this.expect(types.comma); }
if (allowEmpty && this.type === types.comma) {
elts.push(null);
} else if (allowTrailingComma && this.afterTrailingComma(close)) {
break
} else if (this.type === types.ellipsis) {
var rest = this.parseRestBinding();
this.parseBindingListItem(rest);
elts.push(rest);
if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
this.expect(close);
break
} else {
var elem = this.parseMaybeDefault(this.start, this.startLoc);
this.parseBindingListItem(elem);
...function(createNewLexicalScope, node) {
if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
if ( node === void 0 ) node = this.startNode();
node.body = [];
this.expect(types.braceL);
if (createNewLexicalScope) { this.enterScope(0); }
while (!this.eat(types.braceR)) {
var stmt = this.parseStatement(null);
node.body.push(stmt);
}
if (createNewLexicalScope) { this.exitScope(); }
return this.finishNode(node, "BlockStatement")
}...
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
case types.braceL: return this.parseBlock(true, node)
case types.semi: return this.parseEmptyStatement(node)
case types._export:
case types._import:
if (this.options.ecmaVersion > 10 && starttype === types._import) {
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
...function(node, keyword) {
var isBreak = keyword === "break";
this.next();
if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
else if (this.type !== types.name) { this.unexpected(); }
else {
node.label = this.parseIdent();
this.semicolon();
}
// Verify that there is an actual destination to break or
// continue to.
var i = 0;
for (; i < this.labels.length; ++i) {
var lab = this.labels[i];
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
if (node.label && isBreak) { break }
}
}
if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
}...
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case types._break: case types._continue: return this.parseBreakContinueStatement(node
, starttype.keyword)
case types._debugger: return this.parseDebuggerStatement(node)
case types._do: return this.parseDoStatement(node)
case types._for: return this.parseForStatement(node)
case types._function:
// Function as sole body of either an if statement or a labeled statement
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
...function(node, isStatement) {
this.next();
// ecma-262 14.6 Class Definitions
// A class definition is always strict mode code.
var oldStrict = this.strict;
this.strict = true;
this.parseClassId(node, isStatement);
this.parseClassSuper(node);
var classBody = this.startNode();
var hadConstructor = false;
classBody.body = [];
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
var element = this.parseClassElement(node.superClass !== null);
if (element) {
classBody.body.push(element);
if (element.type === "MethodDefinition" && element.kind === "constructor") {
if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
hadConstructor = true;
}
}
}
node.body = this.finishNode(classBody, "ClassBody");
this.strict = oldStrict;
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
}...
// Function as sole body of either an if statement or a labeled statement
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.
options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false, !context)
case types._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
...function(constructorAllowsSuper) {
var this$1 = this;
if (this.eat(types.semi)) { return null }
var method = this.startNode();
var tryContextual = function (k, noLineBreak) {
if ( noLineBreak === void 0 ) noLineBreak = false;
var start = this$1.start, startLoc = this$1.startLoc;
if (!this$1.eatContextual(k)) { return false }
if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
if (method.key) { this$1.unexpected(); }
method.computed = false;
method.key = this$1.startNodeAt(start, startLoc);
method.key.name = k;
this$1.finishNode(method.key, "Identifier");
return false
};
method.kind = "method";
method.static = tryContextual("static");
var isGenerator = this.eat(types.star);
var isAsync = false;
if (!isGenerator) {
if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
isAsync = true;
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
} else if (tryContextual("get")) {
method.kind = "get";
} else if (tryContextual("set")) {
method.kind = "set";
}
}
if (!method.key) { this.parsePropertyName(method); }
var key = method.key;
var allowsDirectSuper = false;
if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
key.type === "Literal" && key.value === "constructor")) {
if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
method.kind = "constructor";
allowsDirectSuper = constructorAllowsSuper;
} else if (method.static && key.type === "Identifier" && key.name === "prototype") {
this.raise(key.start, "Classes may not have a static property named prototype");
}
this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
if (method.kind === "get" && method.value.params.length !== 0)
{ this.raiseRecoverable(method.value.start, "getter should have no params"); }
if (method.kind === "set" && method.value.params.length !== 1)
{ this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
if (method.kind === "set" && method.value.params[0].type === "RestElement")
{ this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
return method
}...
this.parseClassId(node, isStatement);
this.parseClassSuper(node);
var classBody = this.startNode();
var hadConstructor = false;
classBody.body = [];
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
var element = this.parseClassElement(node.superClass !== null);
if (element) {
classBody.body.push(element);
if (element.type === "MethodDefinition" && element.kind === "constructor") {
if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
hadConstructor = true;
}
}
...function(node, isStatement) {
if (this.type === types.name) {
node.id = this.parseIdent();
if (isStatement)
{ this.checkLVal(node.id, BIND_LEXICAL, false); }
} else {
if (isStatement === true)
{ this.unexpected(); }
node.id = null;
}
}...
this.next();
// ecma-262 14.6 Class Definitions
// A class definition is always strict mode code.
var oldStrict = this.strict;
this.strict = true;
this.parseClassId(node, isStatement);
this.parseClassSuper(node);
var classBody = this.startNode();
var hadConstructor = false;
classBody.body = [];
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
var element = this.parseClassElement(node.superClass !== null);
...function(method, isGenerator, isAsync, allowsDirectSuper) {
method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
return this.finishNode(method, "MethodDefinition")
}...
if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
method.kind = "constructor";
allowsDirectSuper = constructorAllowsSuper;
} else if (method.static && key.type === "Identifier" && key.name === "prototype") {
this.raise(key.start, "Classes may not have a static property named prototype");
}
this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
if (method.kind === "get" && method.value.params.length !== 0)
{ this.raiseRecoverable(method.value.start, "getter should have no params"); }
if (method.kind === "set" && method.value.params.length !== 1)
{ this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
if (method.kind === "set" && method.value.params[0].type === "RestElement")
{ this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
return method
...function(node) {
node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
}...
// ecma-262 14.6 Class Definitions
// A class definition is always strict mode code.
var oldStrict = this.strict;
this.strict = true;
this.parseClassId(node, isStatement);
this.parseClassSuper(node);
var classBody = this.startNode();
var hadConstructor = false;
classBody.body = [];
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
var element = this.parseClassElement(node.superClass !== null);
if (element) {
...function(node) {
this.next();
this.semicolon();
return this.finishNode(node, "DebuggerStatement")
}...
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case types._debugger: return this.parseDebuggerStatement(node)
case types._do: return this.parseDoStatement(node)
case types._for: return this.parseForStatement(node)
case types._function:
// Function as sole body of either an if statement or a labeled statement
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.
options.ecmaVersion >= 6) { this.unexpected(); }
...function(node) {
this.next();
this.labels.push(loopLabel);
node.body = this.parseStatement("do");
this.labels.pop();
this.expect(types._while);
node.test = this.parseParenExpression();
if (this.options.ecmaVersion >= 6)
{ this.eat(types.semi); }
else
{ this.semicolon(); }
return this.finishNode(node, "DoWhileStatement")
}...
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case types._debugger: return this.parseDebuggerStatement(node)
case types._do: return this.parseDoStatement(node)
case types._for: return this.parseForStatement(node)
case types._function:
// Function as sole body of either an if statement or a labeled statement
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.
options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false, !context)
...function() {
var node = this.startNode();
this.next();
if (this.type !== types.parenL) {
this.unexpected();
}
return this.finishNode(node, "Import")
}...
return this.parseNew()
case types.backQuote:
return this.parseTemplate()
case types._import:
if (this.options.ecmaVersion > 10) {
return this.parseDynamicImport()
} else {
return this.unexpected()
}
default:
this.unexpected();
}
...function(node) {
this.next();
return this.finishNode(node, "EmptyStatement")
}...
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
case types.braceL: return this.parseBlock(true, node)
case types.semi: return this.parseEmptyStatement(node)
case types._export:
case types._import:
if (this.options.ecmaVersion > 10 && starttype === types._import) {
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
if (nextCh === 40) // '('
...function(node, exports) {
this.next();
// export * from '...'
if (this.eat(types.star)) {
this.expectContextual("from");
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
this.semicolon();
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(types._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart);
var isAsync;
if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode();
this.next();
if (isAsync) { this.next(); }
node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
} else if (this.type === types._class) {
var cNode = this.startNode();
node.declaration = this.parseClass(cNode, "nullableID");
} else {
node.declaration = this.parseMaybeAssign();
this.semicolon();
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(null);
if (node.declaration.type === "VariableDeclaration")
{ this.checkVariableExport(exports, node.declaration.declarations); }
else
{ this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
node.specifiers = [];
node.source = null;
} else { // export { x, y as z } [from '...']
node.declaration = null;
node.specifiers = this.parseExportSpecifiers(exports);
if (this.eatContextual("from")) {
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
} else {
for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
// check for keywords used as local names
var spec = list[i];
this.checkUnreserved(spec.local);
// check if export is defined
this.checkLocalExport(spec.local);
}
node.source = null;
}
this.semicolon();
}
return this.finishNode(node, "ExportNamedDeclaration")
}...
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
{ this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
if (!this.inModule)
{ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module&apos
;"); }
}
return starttype === types._import ? this.parseImport(node) : this.parseExport(node
, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
...function(exports) {
var nodes = [], first = true;
// export { x, y as z } [from '...']
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
if (!first) {
this.expect(types.comma);
if (this.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var node = this.startNode();
node.local = this.parseIdent(true);
node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
this.checkExport(exports, node.exported.name, node.exported.start);
nodes.push(this.finishNode(node, "ExportSpecifier"));
}
return nodes
}...
{ this.checkVariableExport(exports, node.declaration.declarations); }
else
{ this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
node.specifiers = [];
node.source = null;
} else { // export { x, y as z } [from '...']
node.declaration = null;
node.specifiers = this.parseExportSpecifiers(exports);
if (this.eatContextual("from")) {
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
} else {
for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
// check for keywords used as local names
var spec = list[i];
...function(refDestructuringErrors) {
// If a division operator appears in an expression position, the
// tokenizer got confused, and we force it to read a regexp instead.
if (this.type === types.slash) { this.readRegexp(); }
var node, canBeArrow = this.potentialArrowAt === this.start;
switch (this.type) {
case types._super:
if (!this.allowSuper)
{ this.raise(this.start, "'super' keyword outside a method"); }
node = this.startNode();
this.next();
if (this.type === types.parenL && !this.allowDirectSuper)
{ this.raise(node.start, "super() call outside constructor of a subclass"); }
// The `super` keyword can appear at below:
// SuperProperty:
// super [ Expression ]
// super . IdentifierName
// SuperCall:
// super Arguments
if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
{ this.unexpected(); }
return this.finishNode(node, "Super")
case types._this:
node = this.startNode();
this.next();
return this.finishNode(node, "ThisExpression")
case types.name:
var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
var id = this.parseIdent(false);
if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function
))
{ return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
if (canBeArrow && !this.canInsertSemicolon()) {
if (this.eat(types.arrow))
{ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
id = this.parseIdent(false);
if (this.canInsertSemicolon() || !this.eat(types.arrow))
{ this.unexpected(); }
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
}
}
return id
case types.regexp:
var value = this.value;
node = this.parseLiteral(value.value);
node.regex = {pattern: value.pattern, flags: value.flags};
return node
case types.num: case types.string:
return this.parseLiteral(this.value)
case types._null: case types._true: case types._false:
node = this.startNode();
node.value = this.type === types._null ? null : this.type === types._true;
node.raw = this.type.keyword;
this.next();
return this.finishNode(node, "Literal")
case types.parenL:
var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
{ refDestructuringErrors.parenthesizedAssign = start; }
if (refDestructuringErrors.parenthesizedBind < 0)
{ refDestructuringErrors.parenthesizedBind = start; }
}
return expr
case types.bracketL:
node = this.startNode();
this.next();
node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
return this.finishNode(node, "ArrayExpression")
case types.braceL:
return this.parseObj(false, refDestructuringErrors)
case types._function:
node = this.startNode();
this.next();
return this.parseFunction(node, 0)
case types._class:
return this.parseClass(this.startNode(), false)
case types._new:
return this.parseNew()
case types.backQuote:
return this.parseTemplate()
case types._import:
if (this.options.ecmaVersion > 10) {
return this.parseDynamicImport()
} else {
return this.unexpected()
}
default:
this.unexpected();
}
}...
pp$1.parseExport = function(node, exports) {
this.next();
// export * from '...'
if (this.eat(types.star)) {
this.expectContextual("from");
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
this.semicolon();
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(types._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart);
var isAsync;
if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
...function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
var elts = [], first = true;
while (!this.eat(close)) {
if (!first) {
this.expect(types.comma);
if (allowTrailingComma && this.afterTrailingComma(close)) { break }
} else { first = false; }
var elt = (void 0);
if (allowEmpty && this.type === types.comma)
{ elt = null; }
else if (this.type === types.ellipsis) {
elt = this.parseSpread(refDestructuringErrors);
if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
{ refDestructuringErrors.trailingComma = this.start; }
} else {
elt = this.parseMaybeAssign(false, refDestructuringErrors);
}
elts.push(elt);
}
return elts
}...
if (computed) { this.expect(types.bracketR); }
base = this.finishNode(node, "MemberExpression");
} else if (!noCalls && this.eat(types.parenL)) {
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos
= this.awaitIdentPos;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 &
;& base.type !== "Import", false, refDestructuringErrors);
if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
if (this.awaitIdentPos > 0)
{ this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
...function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
var prec = this.type.binop;
if (prec != null && (!noIn || this.type !== types._in)) {
if (prec > minPrec) {
var logical = this.type === types.logicalOR || this.type === types.logicalAND;
var op = this.value;
this.next();
var startPos = this.start, startLoc = this.startLoc;
var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical);
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
}
}
return left
}...
// Start the precedence parser.
pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeUnary(refDestructuringErrors, false);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
};
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
...function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeUnary(refDestructuringErrors, false);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -
1, noIn)
}...
return left
};
// Parse a ternary conditional (`?:`) operator.
pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprOps(noIn, refDestructuringErrors);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
if (this.eat(types.question)) {
var node = this.startNodeAt(startPos, startLoc);
node.test = expr;
node.consequent = this.parseMaybeAssign();
this.expect(types.colon);
node.alternate = this.parseMaybeAssign(noIn);
...function(refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprAtom(refDestructuringErrors);
var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr }
var result = this.parseSubscripts(expr, startPos, startLoc);
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
}
return result
}...
if (isStatement === true)
{ this.unexpected(); }
node.id = null;
}
};
pp$1.parseClassSuper = function(node) {
node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
};
// Parses module export declaration.
pp$1.parseExport = function(node, exports) {
this.next();
// export * from '...'
...function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
if (this.type === types.comma) {
var node = this.startNodeAt(startPos, startLoc);
node.expressions = [expr];
while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
return this.finishNode(node, "SequenceExpression")
}
return expr
}...
Parser.parse = function parse (input, options) {
return new this(options, input).parse()
};
Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
var parser = new this(options, input, pos);
parser.nextToken();
return parser.parseExpression()
};
Parser.tokenizer = function tokenizer (input, options) {
return new this(options, input)
};
Object.defineProperties( Parser.prototype, prototypeAccessors );
...function(node, expr) {
node.expression = expr;
this.semicolon();
return this.finishNode(node, "ExpressionStatement")
}...
case types._export:
case types._import:
if (this.options.ecmaVersion > 10 && starttype === types._import) {
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
if (nextCh === 40) // '('
{ return this.parseExpressionStatement(node, this.parseExpression()) }
}
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
{ this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
if (!this.inModule)
{ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'&
quot;); }
...function(node, init) {
node.init = init;
this.expect(types.semi);
node.test = this.type === types.semi ? null : this.parseExpression();
this.expect(types.semi);
node.update = this.type === types.parenR ? null : this.parseExpression();
this.expect(types.parenR);
node.body = this.parseStatement("for");
this.exitScope();
this.labels.pop();
return this.finishNode(node, "ForStatement")
}...
this.next();
var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction
)) && this.eatContextual("await")) ? this.lastTokStart : -1;
this.labels.push(loopLabel);
this.enterScope(0);
this.expect(types.parenL);
if (this.type === types.semi) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, null)
}
var isLet = this.isLet();
if (this.type === types._var || this.type === types._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
this.next();
this.parseVar(init$1, true, kind);
this.finishNode(init$1, "VariableDeclaration");
...function(node, init) {
var isForIn = this.type === types._in;
this.next();
if (
init.type === "VariableDeclaration" &&
init.declarations[0].init != null &&
(
!isForIn ||
this.options.ecmaVersion < 8 ||
this.strict ||
init.kind !== "var" ||
init.declarations[0].id.type !== "Identifier"
)
) {
this.raise(
init.start,
((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
);
} else if (init.type === "AssignmentPattern") {
this.raise(init.start, "Invalid left-hand side in for-loop");
}
node.left = init;
node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
this.expect(types.parenR);
node.body = this.parseStatement("for");
this.exitScope();
this.labels.pop();
return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
}...
this.finishNode(init$1, "VariableDeclaration");
if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init
$1.declarations.length === 1) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
return this.parseForIn(node, init$1)
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init$1)
}
var refDestructuringErrors = new DestructuringErrors;
var init = this.parseExpression(true, refDestructuringErrors);
if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
...function(node) {
this.next();
var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) &&
this.eatContextual("await")) ? this.lastTokStart : -1;
this.labels.push(loopLabel);
this.enterScope(0);
this.expect(types.parenL);
if (this.type === types.semi) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, null)
}
var isLet = this.isLet();
if (this.type === types._var || this.type === types._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
this.next();
this.parseVar(init$1, true, kind);
this.finishNode(init$1, "VariableDeclaration");
if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length ===
1) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
return this.parseForIn(node, init$1)
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init$1)
}
var refDestructuringErrors = new DestructuringErrors;
var init = this.parseExpression(true, refDestructuringErrors);
if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
this.toAssignable(init, false, refDestructuringErrors);
this.checkLVal(init);
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true);
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init)
}...
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case types._debugger: return this.parseDebuggerStatement(node)
case types._do: return this.parseDoStatement(node)
case types._for: return this.parseForStatement(node)
case types._function:
// Function as sole body of either an if statement or a labeled statement
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.
options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false, !context)
case types._class:
...function(node, statement, allowExpressionBody, isAsync) {
this.initFunction(node);
if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
{ this.unexpected(); }
node.generator = this.eat(types.star);
}
if (this.options.ecmaVersion >= 8)
{ node.async = !!isAsync; }
if (statement & FUNC_STATEMENT) {
node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
if (node.id && !(statement & FUNC_HANGING_STATEMENT))
// If it is a regular function declaration in sloppy mode, then it is
// subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
// mode depends on properties of the current scope (see
// treatFunctionsAsVar).
{ this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL
: BIND_FUNCTION); }
}
var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
this.enterScope(functionFlags(node.async, node.generator));
if (!(statement & FUNC_STATEMENT))
{ node.id = this.type === types.name ? this.parseIdent() : null; }
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody, false);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
}...
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init)
};
pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
this.next();
return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT
), false, isAsync)
};
pp$1.parseIfStatement = function(node) {
this.next();
node.test = this.parseParenExpression();
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement("if");
...function(node, isArrowFunction, isMethod) {
var isExpression = isArrowFunction && this.type !== types.braceL;
var oldStrict = this.strict, useStrict = false;
if (isExpression) {
node.body = this.parseMaybeAssign();
node.expression = true;
this.checkParams(node, false);
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end);
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (useStrict && nonSimple)
{ this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
}
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
var oldLabels = this.labels;
this.labels = [];
if (useStrict) { this.strict = true; }
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
node.body = this.parseBlock(false);
node.expression = false;
this.adaptDirectivePrologue(node.body.body);
this.labels = oldLabels;
}
this.exitScope();
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); }
this.strict = oldStrict;
}...
this.awaitIdentPos = 0;
this.enterScope(functionFlags(node.async, node.generator));
if (!(statement & FUNC_STATEMENT))
{ node.id = this.type === types.name ? this.parseIdent() : null; }
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody, false);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression"
;)
};
...function(node) {
this.expect(types.parenL);
node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
}...
this.awaitPos = 0;
this.awaitIdentPos = 0;
this.enterScope(functionFlags(node.async, node.generator));
if (!(statement & FUNC_STATEMENT))
{ node.id = this.type === types.name ? this.parseIdent() : null; }
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody, false);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression"
;)
};
...function(node, isAsync, declarationPosition) {
this.next();
return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
}...
case types._do: return this.parseDoStatement(node)
case types._for: return this.parseForStatement(node)
case types._function:
// Function as sole body of either an if statement or a labeled statement
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.
options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false, !context)
case types._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
...function(liberal, isBinding) {
var node = this.startNode();
if (this.type === types.name) {
node.name = this.value;
} else if (this.type.keyword) {
node.name = this.type.keyword;
// To fix https://github.com/acornjs/acorn/issues/575
// `class` and `function` keywords push new context into this.context.
// But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
// If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
if ((node.name === "class" || node.name === "function") &&
(this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
this.context.pop();
}
} else {
this.unexpected();
}
this.next();
this.finishNode(node, "Identifier");
if (!liberal) {
this.checkUnreserved(node);
if (node.name === "await" && !this.awaitIdentPos)
{ this.awaitIdentPos = node.start; }
}
return node
}...
pp$1.parseBreakContinueStatement = function(node, keyword) {
var isBreak = keyword === "break";
this.next();
if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
else if (this.type !== types.name) { this.unexpected(); }
else {
node.label = this.parseIdent();
this.semicolon();
}
// Verify that there is an actual destination to break or
// continue to.
var i = 0;
for (; i < this.labels.length; ++i) {
...function(node) {
this.next();
node.test = this.parseParenExpression();
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement("if");
node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
return this.finishNode(node, "IfStatement")
}...
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.
options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false, !context)
case types._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
...function(node) {
this.next();
// import '...'
if (this.type === types.string) {
node.specifiers = empty;
node.source = this.parseExprAtom();
} else {
node.specifiers = this.parseImportSpecifiers();
this.expectContextual("from");
node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
}
this.semicolon();
return this.finishNode(node, "ImportDeclaration")
}...
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
{ this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
if (!this.inModule)
{ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module&apos
;"); }
}
return starttype === types._import ? this.parseImport(node) : this.parseExport(node
, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
...function() {
var nodes = [], first = true;
if (this.type === types.name) {
// import defaultObj, { x, y as z } from '...'
var node = this.startNode();
node.local = this.parseIdent();
this.checkLVal(node.local, BIND_LEXICAL);
nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
if (!this.eat(types.comma)) { return nodes }
}
if (this.type === types.star) {
var node$1 = this.startNode();
this.next();
this.expectContextual("as");
node$1.local = this.parseIdent();
this.checkLVal(node$1.local, BIND_LEXICAL);
nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
return nodes
}
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
if (!first) {
this.expect(types.comma);
if (this.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var node$2 = this.startNode();
node$2.imported = this.parseIdent(true);
if (this.eatContextual("as")) {
node$2.local = this.parseIdent();
} else {
this.checkUnreserved(node$2.imported);
node$2.local = node$2.imported;
}
this.checkLVal(node$2.local, BIND_LEXICAL);
nodes.push(this.finishNode(node$2, "ImportSpecifier"));
}
return nodes
}...
pp$1.parseImport = function(node) {
this.next();
// import '...'
if (this.type === types.string) {
node.specifiers = empty;
node.source = this.parseExprAtom();
} else {
node.specifiers = this.parseImportSpecifiers();
this.expectContextual("from");
node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
}
this.semicolon();
return this.finishNode(node, "ImportDeclaration")
};
...function(node, maybeName, expr, context) {
for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
{
var label = list[i$1];
if (label.name === maybeName)
{ this.raise(expr.start, "Label '" + maybeName + "' is already declared");
} }
var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
for (var i = this.labels.length - 1; i >= 0; i--) {
var label$1 = this.labels[i];
if (label$1.statementStart === node.start) {
// Update information about previous labels on this node
label$1.statementStart = this.start;
label$1.kind = kind;
} else { break }
}
this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
this.labels.pop();
node.label = expr;
return this.finishNode(node, "LabeledStatement")
}...
if (context) { this.unexpected(); }
this.next();
return this.parseFunctionStatement(node, true, !context)
}
var maybeName = this.value, expr = this.parseExpression();
if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
{ return this.parseLabeledStatement(node, maybeName, expr, context) }
else { return this.parseExpressionStatement(node, expr) }
}
};
pp$1.parseBreakContinueStatement = function(node, keyword) {
var isBreak = keyword === "break";
this.next();
...function(value) {
var node = this.startNode();
node.value = value;
node.raw = this.input.slice(this.start, this.end);
if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1); }
this.next();
return this.finishNode(node, "Literal")
}...
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
}
}
return id
case types.regexp:
var value = this.value;
node = this.parseLiteral(value.value);
node.regex = {pattern: value.pattern, flags: value.flags};
return node
case types.num: case types.string:
return this.parseLiteral(this.value)
case types._null: case types._true: case types._false:
...function(noIn, refDestructuringErrors, afterLeftParse) {
if (this.isContextual("yield")) {
if (this.inGenerator) { return this.parseYield(noIn) }
// The tokenizer will assume an expression is allowed after
// `yield`, but this isn't that kind of yield
else { this.exprAllowed = false; }
}
var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1;
if (refDestructuringErrors) {
oldParenAssign = refDestructuringErrors.parenthesizedAssign;
oldTrailingComma = refDestructuringErrors.trailingComma;
oldShorthandAssign = refDestructuringErrors.shorthandAssign;
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -
1;
} else {
refDestructuringErrors = new DestructuringErrors;
ownDestructuringErrors = true;
}
var startPos = this.start, startLoc = this.startLoc;
if (this.type === types.parenL || this.type === types.name)
{ this.potentialArrowAt = this.start; }
var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
if (this.type.isAssign) {
var node = this.startNodeAt(startPos, startLoc);
node.operator = this.value;
node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;
if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); }
refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
this.checkLVal(left);
this.next();
node.right = this.parseMaybeAssign(noIn);
return this.finishNode(node, "AssignmentExpression")
} else {
if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
}
if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
if (oldShorthandAssign > -1) { refDestructuringErrors.shorthandAssign = oldShorthandAssign; }
return left
}...
init.start,
((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
);
} else if (init.type === "AssignmentPattern") {
this.raise(init.start, "Invalid left-hand side in for-loop");
}
node.left = init;
node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
this.expect(types.parenR);
node.body = this.parseStatement("for");
this.exitScope();
this.labels.pop();
return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
};
...function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprOps(noIn, refDestructuringErrors);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
if (this.eat(types.question)) {
var node = this.startNodeAt(startPos, startLoc);
node.test = expr;
node.consequent = this.parseMaybeAssign();
this.expect(types.colon);
node.alternate = this.parseMaybeAssign(noIn);
return this.finishNode(node, "ConditionalExpression")
}
return expr
}...
refDestructuringErrors = new DestructuringErrors;
ownDestructuringErrors = true;
}
var startPos = this.start, startLoc = this.startLoc;
if (this.type === types.parenL || this.type === types.name)
{ this.potentialArrowAt = this.start; }
var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
if (this.type.isAssign) {
var node = this.startNodeAt(startPos, startLoc);
node.operator = this.value;
node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;
if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); }
refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
...function(startPos, startLoc, left) {
left = left || this.parseBindingAtom();
if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
var node = this.startNodeAt(startPos, startLoc);
node.left = left;
node.right = this.parseMaybeAssign();
return this.finishNode(node, "AssignmentPattern")
}...
var rest = this.parseRestBinding();
this.parseBindingListItem(rest);
elts.push(rest);
if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
this.expect(close);
break
} else {
var elem = this.parseMaybeDefault(this.start, this.startLoc);
this.parseBindingListItem(elem);
elts.push(elem);
}
}
return elts
};
...function(refDestructuringErrors, sawUnary) {
var startPos = this.start, startLoc = this.startLoc, expr;
if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
expr = this.parseAwait();
sawUnary = true;
} else if (this.type.prefix) {
var node = this.startNode(), update = this.type === types.incDec;
node.operator = this.value;
node.prefix = true;
this.next();
node.argument = this.parseMaybeUnary(null, true);
this.checkExpressionErrors(refDestructuringErrors, true);
if (update) { this.checkLVal(node.argument); }
else if (this.strict && node.operator === "delete" &&
node.argument.type === "Identifier")
{ this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
else { sawUnary = true; }
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
} else {
expr = this.parseExprSubscripts(refDestructuringErrors);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
while (this.type.postfix && !this.canInsertSemicolon()) {
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.operator = this.value;
node$1.prefix = false;
node$1.argument = expr;
this.checkLVal(expr);
this.next();
expr = this.finishNode(node$1, "UpdateExpression");
}
}
if (!sawUnary && this.eat(types.starstar))
{ return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
else
{ return expr }
}...
return expr
};
// Start the precedence parser.
pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeUnary(refDestructuringErrors, false);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos
, startLoc, -1, noIn)
};
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
...function(isGenerator, isAsync, allowDirectSuper) {
var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.initFunction(node);
if (this.options.ecmaVersion >= 6)
{ node.generator = isGenerator; }
if (this.options.ecmaVersion >= 8)
{ node.async = !!isAsync; }
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
this.expect(types.parenL);
node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
this.parseFunctionBody(node, false, true);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, "FunctionExpression")
}...
{ this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
if (method.kind === "set" && method.value.params[0].type === "RestElement")
{ this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
return method
};
pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
return this.finishNode(method, "MethodDefinition")
};
pp$1.parseClassId = function(node, isStatement) {
if (this.type === types.name) {
node.id = this.parseIdent();
if (isStatement)
...function() {
var node = this.startNode();
var meta = this.parseIdent(true);
if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
node.meta = meta;
var containsEsc = this.containsEsc;
node.property = this.parseIdent(true);
if (node.property.name !== "target" || containsEsc)
{ this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); }
if (!this.inNonArrowFunction())
{ this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc;
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
if (this.options.ecmaVersion > 10 && node.callee.type === "Import") {
this.raise(node.callee.start, "Cannot use new with import(...)");
}
if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 && node.callee.type
!== "Import", false); }
else { node.arguments = empty$1; }
return this.finishNode(node, "NewExpression")
}...
this.next();
return this.parseFunction(node, 0)
case types._class:
return this.parseClass(this.startNode(), false)
case types._new:
return this.parseNew()
case types.backQuote:
return this.parseTemplate()
case types._import:
if (this.options.ecmaVersion > 10) {
return this.parseDynamicImport()
...function(isPattern, refDestructuringErrors) {
var node = this.startNode(), first = true, propHash = {};
node.properties = [];
this.next();
while (!this.eat(types.braceR)) {
if (!first) {
this.expect(types.comma);
if (this.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var prop = this.parseProperty(isPattern, refDestructuringErrors);
if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
node.properties.push(prop);
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
}...
case types.bracketL:
var node = this.startNode();
this.next();
node.elements = this.parseBindingList(types.bracketR, true, true);
return this.finishNode(node, "ArrayPattern")
case types.braceL:
return this.parseObj(true)
}
}
return this.parseIdent()
};
pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
var elts = [], first = true;
...function(canBeArrow) {
var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
if (this.options.ecmaVersion >= 6) {
this.next();
var innerStartPos = this.start, innerStartLoc = this.startLoc;
var exprList = [], first = true, lastIsComma = false;
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
this.yieldPos = 0;
this.awaitPos = 0;
// Do not save awaitIdentPos to allow checking awaits nested in parameters
while (this.type !== types.parenR) {
first ? first = false : this.expect(types.comma);
if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
lastIsComma = true;
break
} else if (this.type === types.ellipsis) {
spreadStart = this.start;
exprList.push(this.parseParenItem(this.parseRestBinding()));
if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
break
} else {
exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
}
}
var innerEndPos = this.start, innerEndLoc = this.startLoc;
this.expect(types.parenR);
if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
return this.parseParenArrowList(startPos, startLoc, exprList)
}
if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
if (spreadStart) { this.unexpected(spreadStart); }
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
} else {
val = exprList[0];
}
} else {
val = this.parseParenExpression();
}
if (this.options.preserveParens) {
var par = this.startNodeAt(startPos, startLoc);
par.expression = val;
return this.finishNode(par, "ParenthesizedExpression")
} else {
return val
}
}...
node = this.startNode();
node.value = this.type === types._null ? null : this.type === types._true;
node.raw = this.type.keyword;
this.next();
return this.finishNode(node, "Literal")
case types.parenL:
var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
{ refDestructuringErrors.parenthesizedAssign = start; }
if (refDestructuringErrors.parenthesizedBind < 0)
{ refDestructuringErrors.parenthesizedBind = start; }
}
return expr
...function(startPos, startLoc, exprList) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
}...
this.expect(types.parenR);
if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
return this.parseParenArrowList(startPos, startLoc, exprList)
}
if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
if (spreadStart) { this.unexpected(spreadStart); }
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
...function() {
this.expect(types.parenL);
var val = this.parseExpression();
this.expect(types.parenR);
return val
}...
pp$1.parseDoStatement = function(node) {
this.next();
this.labels.push(loopLabel);
node.body = this.parseStatement("do");
this.labels.pop();
this.expect(types._while);
node.test = this.parseParenExpression();
if (this.options.ecmaVersion >= 6)
{ this.eat(types.semi); }
else
{ this.semicolon(); }
return this.finishNode(node, "DoWhileStatement")
};
...function(item) {
return item
}...
while (this.type !== types.parenR) {
first ? first = false : this.expect(types.comma);
if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
lastIsComma = true;
break
} else if (this.type === types.ellipsis) {
spreadStart = this.start;
exprList.push(this.parseParenItem(this.parseRestBinding()));
if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
break
} else {
exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
}
}
var innerEndPos = this.start, innerEndLoc = this.startLoc;
...function(isPattern, refDestructuringErrors) {
var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
if (isPattern) {
prop.argument = this.parseIdent(false);
if (this.type === types.comma) {
this.raise(this.start, "Comma is not permitted after the rest element");
}
return this.finishNode(prop, "RestElement")
}
// To disallow parenthesized identifier via `this.toAssignable()`.
if (this.type === types.parenL && refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0) {
refDestructuringErrors.parenthesizedAssign = this.start;
}
if (refDestructuringErrors.parenthesizedBind < 0) {
refDestructuringErrors.parenthesizedBind = this.start;
}
}
// Parse argument.
prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
// To disallow trailing comma via `this.toAssignable()`.
if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
refDestructuringErrors.trailingComma = this.start;
}
// Finish
return this.finishNode(prop, "SpreadElement")
}
if (this.options.ecmaVersion >= 6) {
prop.method = false;
prop.shorthand = false;
if (isPattern || refDestructuringErrors) {
startPos = this.start;
startLoc = this.startLoc;
}
if (!isPattern)
{ isGenerator = this.eat(types.star); }
}
var containsEsc = this.containsEsc;
this.parsePropertyName(prop);
if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
isAsync = true;
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
this.parsePropertyName(prop, refDestructuringErrors);
} else {
isAsync = false;
}
this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
return this.finishNode(prop, "Property")
}...
this.next();
while (!this.eat(types.braceR)) {
if (!first) {
this.expect(types.comma);
if (this.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var prop = this.parseProperty(isPattern, refDestructuringErrors);
if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
node.properties.push(prop);
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
};
pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
...function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(types.bracketL)) {
prop.computed = true;
prop.key = this.parseMaybeAssign();
this.expect(types.bracketR);
return prop.key
} else {
prop.computed = false;
}
}
return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.
allowReserved !== "never")
}...
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
} else if (tryContextual("get")) {
method.kind = "get";
} else if (tryContextual("set")) {
method.kind = "set";
}
}
if (!method.key) { this.parsePropertyName(method); }
var key = method.key;
var allowsDirectSuper = false;
if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor
" ||
key.type === "Literal" && key.value === "constructor")) {
if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
...function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
if ((isGenerator || isAsync) && this.type === types.colon)
{ this.unexpected(); }
if (this.eat(types.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors
);
prop.kind = "init";
} else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
if (isPattern) { this.unexpected(); }
prop.kind = "init";
prop.method = true;
prop.value = this.parseMethod(isGenerator, isAsync);
} else if (!isPattern && !containsEsc &&
this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
(prop.key.name === "get" || prop.key.name === "set") &&
(this.type !== types.comma && this.type !== types.braceR)) {
if (isGenerator || isAsync) { this.unexpected(); }
prop.kind = prop.key.name;
this.parsePropertyName(prop);
prop.value = this.parseMethod(false);
var paramCount = prop.kind === "get" ? 0 : 1;
if (prop.value.params.length !== paramCount) {
var start = prop.value.start;
if (prop.kind === "get")
{ this.raiseRecoverable(start, "getter should have no params"); }
else
{ this.raiseRecoverable(start, "setter should have exactly one param"); }
} else {
if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
{ this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
}
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
if (isGenerator || isAsync) { this.unexpected(); }
this.checkUnreserved(prop.key);
if (prop.key.name === "await" && !this.awaitIdentPos)
{ this.awaitIdentPos = startPos; }
prop.kind = "init";
if (isPattern) {
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
} else if (this.type === types.eq && refDestructuringErrors) {
if (refDestructuringErrors.shorthandAssign < 0)
{ refDestructuringErrors.shorthandAssign = this.start; }
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
} else {
prop.value = prop.key;
}
prop.shorthand = true;
} else { this.unexpected(); }
}...
if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp
(prop)) {
isAsync = true;
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
this.parsePropertyName(prop, refDestructuringErrors);
} else {
isAsync = false;
}
this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc,
refDestructuringErrors, containsEsc);
return this.finishNode(prop, "Property")
};
pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc
) {
if ((isGenerator || isAsync) && this.type === types.colon)
{ this.unexpected(); }
...function() {
var node = this.startNode();
this.next();
// RestElement inside of a function parameter must be an identifier
if (this.options.ecmaVersion === 6 && this.type !== types.name)
{ this.unexpected(); }
node.argument = this.parseBindingAtom();
return this.finishNode(node, "RestElement")
}...
if (first) { first = false; }
else { this.expect(types.comma); }
if (allowEmpty && this.type === types.comma) {
elts.push(null);
} else if (allowTrailingComma && this.afterTrailingComma(close)) {
break
} else if (this.type === types.ellipsis) {
var rest = this.parseRestBinding();
this.parseBindingListItem(rest);
elts.push(rest);
if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
this.expect(close);
break
} else {
var elem = this.parseMaybeDefault(this.start, this.startLoc);
...function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction)
{ this.raise(this.start, "'return' outside of function"); }
this.next();
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
else { node.argument = this.parseExpression(); this.semicolon(); }
return this.finishNode(node, "ReturnStatement")
}...
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.
options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false, !context)
case types._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
...function(refDestructuringErrors) {
var node = this.startNode();
this.next();
node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
return this.finishNode(node, "SpreadElement")
}...
if (allowTrailingComma && this.afterTrailingComma(close)) { break }
} else { first = false; }
var elt = (void 0);
if (allowEmpty && this.type === types.comma)
{ elt = null; }
else if (this.type === types.ellipsis) {
elt = this.parseSpread(refDestructuringErrors);
if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
{ refDestructuringErrors.trailingComma = this.start; }
} else {
elt = this.parseMaybeAssign(false, refDestructuringErrors);
}
elts.push(elt);
}
...function(context, topLevel, exports) {
var starttype = this.type, node = this.startNode(), kind;
if (this.isLet(context)) {
starttype = types._var;
kind = "let";
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case types._debugger: return this.parseDebuggerStatement(node)
case types._do: return this.parseDoStatement(node)
case types._for: return this.parseForStatement(node)
case types._function:
// Function as sole body of either an if statement or a labeled statement
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected
(); }
return this.parseFunctionStatement(node, false, !context)
case types._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
case types.braceL: return this.parseBlock(true, node)
case types.semi: return this.parseEmptyStatement(node)
case types._export:
case types._import:
if (this.options.ecmaVersion > 10 && starttype === types._import) {
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
if (nextCh === 40) // '('
{ return this.parseExpressionStatement(node, this.parseExpression()) }
}
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
{ this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
if (!this.inModule)
{ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
}
return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
if (this.isAsyncFunction()) {
if (context) { this.unexpected(); }
this.next();
return this.parseFunctionStatement(node, true, !context)
}
var maybeName = this.value, expr = this.parseExpression();
if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
{ return this.parseLabeledStatement(node, maybeName, expr, context) }
else { return this.parseExpressionStatement(node, expr) }
}
}...
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp$1.parseTopLevel = function(node) {
var exports = {};
if (!node.body) { node.body = []; }
while (this.type !== types.eof) {
var stmt = this.parseStatement(null, true, exports);
node.body.push(stmt);
}
if (this.inModule)
{ for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
{
var name = list[i];
...function(base, startPos, startLoc, noCalls, maybeAsyncArrow) {
var computed = this.eat(types.bracketL);
if (computed || this.eat(types.dot)) {
var node = this.startNodeAt(startPos, startLoc);
node.object = base;
node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
node.computed = !!computed;
if (computed) { this.expect(types.bracketR); }
base = this.finishNode(node, "MemberExpression");
} else if (!noCalls && this.eat(types.parenL)) {
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos
= this.awaitIdentPos;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 && base.type !== "Import", false, refDestructuringErrors
);
if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
if (this.awaitIdentPos > 0)
{ this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
}
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.callee = base;
node$1.arguments = exprList;
if (node$1.callee.type === "Import") {
if (node$1.arguments.length !== 1) {
this.raise(node$1.start, "import() requires exactly one argument");
}
var importArg = node$1.arguments[0];
if (importArg && importArg.type === "SpreadElement") {
this.raise(importArg.start, "... is not allowed in import()");
}
}
base = this.finishNode(node$1, "CallExpression");
} else if (this.type === types.backQuote) {
var node$2 = this.startNodeAt(startPos, startLoc);
node$2.tag = base;
node$2.quasi = this.parseTemplate({isTagged: true});
base = this.finishNode(node$2, "TaggedTemplateExpression");
}
return base
}...
return result
};
pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === &
quot;async" &&
this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === &
quot;async";
while (true) {
var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow
);
if (element === base || element.type === "ArrowFunctionExpression") { return element }
base = element;
}
};
pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow) {
var computed = this.eat(types.bracketL);
...function(base, startPos, startLoc, noCalls) {
var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async";
while (true) {
var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow);
if (element === base || element.type === "ArrowFunctionExpression") { return element }
base = element;
}
}...
// Parse call, dot, and `[]`-subscript expressions.
pp$3.parseExprSubscripts = function(refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprAtom(refDestructuringErrors);
var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this
.lastTokEnd) !== ")";
if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr }
var result = this.parseSubscripts(expr, startPos, startLoc);
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
}
return result
};
...function(node) {
this.next();
node.discriminant = this.parseParenExpression();
node.cases = [];
this.expect(types.braceL);
this.labels.push(switchLabel);
this.enterScope(0);
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
var cur;
for (var sawDefault = false; this.type !== types.braceR;) {
if (this.type === types._case || this.type === types._default) {
var isCase = this.type === types._case;
if (cur) { this.finishNode(cur, "SwitchCase"); }
node.cases.push(cur = this.startNode());
cur.consequent = [];
this.next();
if (isCase) {
cur.test = this.parseExpression();
} else {
if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
sawDefault = true;
cur.test = null;
}
this.expect(types.colon);
} else {
if (!cur) { this.unexpected(); }
cur.consequent.push(this.parseStatement(null));
}
}
this.exitScope();
if (cur) { this.finishNode(cur, "SwitchCase"); }
this.next(); // Closing brace
this.labels.pop();
return this.finishNode(node, "SwitchStatement")
}...
if ((context && (this.strict || context !== "if" && context !== "label")) && this.
options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false, !context)
case types._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
...function(ref) {
if ( ref === void 0 ) ref = {};
var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
var node = this.startNode();
this.next();
node.expressions = [];
var curElt = this.parseTemplateElement({isTagged: isTagged});
node.quasis = [curElt];
while (!curElt.tail) {
if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
this.expect(types.dollarBraceL);
node.expressions.push(this.parseExpression());
this.expect(types.braceR);
node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
}
this.next();
return this.finishNode(node, "TemplateLiteral")
}...
this.raise(importArg.start, "... is not allowed in import()");
}
}
base = this.finishNode(node$1, "CallExpression");
} else if (this.type === types.backQuote) {
var node$2 = this.startNodeAt(startPos, startLoc);
node$2.tag = base;
node$2.quasi = this.parseTemplate({isTagged: true});
base = this.finishNode(node$2, "TaggedTemplateExpression");
}
return base
};
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
...function(ref) {
var isTagged = ref.isTagged;
var elem = this.startNode();
if (this.type === types.invalidTemplate) {
if (!isTagged) {
this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
}
elem.value = {
raw: this.value,
cooked: null
};
} else {
elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
};
}
this.next();
elem.tail = this.type === types.backQuote;
return this.finishNode(elem, "TemplateElement")
}...
pp$3.parseTemplate = function(ref) {
if ( ref === void 0 ) ref = {};
var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
var node = this.startNode();
this.next();
node.expressions = [];
var curElt = this.parseTemplateElement({isTagged: isTagged});
node.quasis = [curElt];
while (!curElt.tail) {
if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
this.expect(types.dollarBraceL);
node.expressions.push(this.parseExpression());
this.expect(types.braceR);
node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
...function(node) {
this.next();
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
{ this.raise(this.lastTokEnd, "Illegal newline after throw"); }
node.argument = this.parseExpression();
this.semicolon();
return this.finishNode(node, "ThrowStatement")
}...
return this.parseFunctionStatement(node, false, !context)
case types._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
...function(node) {
var exports = {};
if (!node.body) { node.body = []; }
while (this.type !== types.eof) {
var stmt = this.parseStatement(null, true, exports);
node.body.push(stmt);
}
if (this.inModule)
{ for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
{
var name = list[i];
this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
} }
this.adaptDirectivePrologue(node.body);
this.next();
node.sourceType = this.options.sourceType;
return this.finishNode(node, "Program")
}...
};
var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },
allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } };
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode();
this.nextToken();
return this.parseTopLevel(node)
};
prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
...function(node) {
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.type === types._catch) {
var clause = this.startNode();
this.next();
if (this.eat(types.parenL)) {
clause.param = this.parseBindingAtom();
var simple = clause.param.type === "Identifier";
this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
this.expect(types.parenR);
} else {
if (this.options.ecmaVersion < 10) { this.unexpected(); }
clause.param = null;
this.enterScope(0);
}
clause.body = this.parseBlock(false);
this.exitScope();
node.handler = this.finishNode(clause, "CatchClause");
}
node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
if (!node.handler && !node.finalizer)
{ this.raise(node.start, "Missing catch or finally clause"); }
return this.finishNode(node, "TryStatement")
}...
case types._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
case types.braceL: return this.parseBlock(true, node)
...function(node, isFor, kind) {
node.declarations = [];
node.kind = kind;
for (;;) {
var decl = this.startNode();
this.parseVarId(decl, kind);
if (this.eat(types.eq)) {
decl.init = this.parseMaybeAssign(isFor);
} else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
this.unexpected();
} else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
} else {
decl.init = null;
}
node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
if (!this.eat(types.comma)) { break }
}
return node
}...
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, null)
}
var isLet = this.isLet();
if (this.type === types._var || this.type === types._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
this.next();
this.parseVar(init$1, true, kind);
this.finishNode(init$1, "VariableDeclaration");
if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init
$1.declarations.length === 1) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
...function(decl, kind) {
decl.id = this.parseBindingAtom();
this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
}...
// Parse a list of variable declarations.
pp$1.parseVar = function(node, isFor, kind) {
node.declarations = [];
node.kind = kind;
for (;;) {
var decl = this.startNode();
this.parseVarId(decl, kind);
if (this.eat(types.eq)) {
decl.init = this.parseMaybeAssign(isFor);
} else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this
.isContextual("of")))) {
this.unexpected();
} else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual
("of")))) {
this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
} else {
...function(node, kind) {
this.next();
this.parseVar(node, false, kind);
this.semicolon();
return this.finishNode(node, "VariableDeclaration")
}...
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
case types.braceL: return this.parseBlock(true, node)
case types.semi: return this.parseEmptyStatement(node)
case types._export:
case types._import:
if (this.options.ecmaVersion > 10 && starttype === types._import) {
...function(node) {
this.next();
node.test = this.parseParenExpression();
this.labels.push(loopLabel);
node.body = this.parseStatement("while");
this.labels.pop();
return this.finishNode(node, "WhileStatement")
}...
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
case types.braceL: return this.parseBlock(true, node)
case types.semi: return this.parseEmptyStatement(node)
case types._export:
case types._import:
if (this.options.ecmaVersion > 10 && starttype === types._import) {
skipWhiteSpace.lastIndex = this.pos;
...function(node) {
if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
this.next();
node.object = this.parseParenExpression();
node.body = this.parseStatement("with");
return this.finishNode(node, "WithStatement")
}...
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
case types.braceL: return this.parseBlock(true, node)
case types.semi: return this.parseEmptyStatement(node)
case types._export:
case types._import:
if (this.options.ecmaVersion > 10 && starttype === types._import) {
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
...function(noIn) {
if (!this.yieldPos) { this.yieldPos = this.start; }
var node = this.startNode();
this.next();
if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
node.delegate = false;
node.argument = null;
} else {
node.delegate = this.eat(types.star);
node.argument = this.parseMaybeAssign(noIn);
}
return this.finishNode(node, "YieldExpression")
}...
};
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
if (this.isContextual("yield")) {
if (this.inGenerator) { return this.parseYield(noIn) }
// The tokenizer will assume an expression is allowed after
// `yield`, but this isn't that kind of yield
else { this.exprAllowed = false; }
}
var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1;
if (refDestructuringErrors) {
...function(pos, message) {
var loc = getLineInfo(this.input, pos);
message += " (" + loc.line + ":" + loc.column + ")";
var err = new SyntaxError(message);
err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
throw err
}...
pp.expect = function(type) {
this.eat(type) || this.unexpected();
};
// Raise an unexpected token error.
pp.unexpected = function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token");
};
function DestructuringErrors() {
this.shorthandAssign =
this.trailingComma =
this.parenthesizedAssign =
this.parenthesizedBind =
...function(pos, message) {
var loc = getLineInfo(this.input, pos);
message += " (" + loc.line + ":" + loc.column + ")";
var err = new SyntaxError(message);
err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
throw err
}...
this.doubleProto =
-1;
}
pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
if (!refDestructuringErrors) { return }
if (refDestructuringErrors.trailingComma > -1)
{ this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not
permitted after the rest element"); }
var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
};
pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
if (!refDestructuringErrors) { return false }
var shorthandAssign = refDestructuringErrors.shorthandAssign;
...function() {
var ch = this.input.charCodeAt(this.pos), code;
if (ch === 123) { // '{'
if (this.options.ecmaVersion < 6) { this.unexpected(); }
var codePos = ++this.pos;
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
++this.pos;
if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
} else {
code = this.readHexChar(4);
}
return code
}...
pp$9.readEscapedChar = function(inTemplate) {
var ch = this.input.charCodeAt(++this.pos);
++this.pos;
switch (ch) {
case 110: return "\n" // 'n' -> '\n'
case 114: return "\r" // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
case 117: return codePointToString$1(this.readCodePoint()) // 'u'
case 116: return "\t" // 't' -> '\t'
case 98: return "\b" // 'b' -> '\b'
case 118: return "\u000b" // 'v' -> '\u000b'
case 102: return "\f" // 'f' -> '\f'
case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
...function(inTemplate) {
var ch = this.input.charCodeAt(++this.pos);
++this.pos;
switch (ch) {
case 110: return "\n" // 'n' -> '\n'
case 114: return "\r" // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
case 117: return codePointToString$1(this.readCodePoint()) // 'u'
case 116: return "\t" // 't' -> '\t'
case 98: return "\b" // 'b' -> '\b'
case 118: return "\u000b" // 'v' -> '\u000b'
case 102: return "\f" // 'f' -> '\f'
case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
return ""
default:
if (ch >= 48 && ch <= 55) {
var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
var octal = parseInt(octalStr, 8);
if (octal > 255) {
octalStr = octalStr.slice(0, -1);
octal = parseInt(octalStr, 8);
}
this.pos += octalStr.length - 1;
ch = this.input.charCodeAt(this.pos);
if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
this.invalidStringToken(
this.pos - 1 - octalStr.length,
inTemplate
? "Octal literal in template string"
: "Octal literal in strict mode"
);
}
return String.fromCharCode(octal)
}
if (isNewLine(ch)) {
// Unicode new line characters after \ get removed from output in both
// template literals and strings
return ""
}
return String.fromCharCode(ch)
}
}...
var out = "", chunkStart = ++this.pos;
for (;;) {
if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
var ch = this.input.charCodeAt(this.pos);
if (ch === quote) { break }
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(false);
chunkStart = this.pos;
} else {
if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
...function(len) {
var codePos = this.pos;
var n = this.readInt(16, len);
if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
return n
}...
pp$9.readCodePoint = function() {
var ch = this.input.charCodeAt(this.pos), code;
if (ch === 123) { // '{'
if (this.options.ecmaVersion < 6) { this.unexpected(); }
var codePos = ++this.pos;
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
++this.pos;
if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
} else {
code = this.readHexChar(4);
}
return code
};
...function(radix, len) {
var start = this.pos, total = 0;
for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
var code = this.input.charCodeAt(this.pos), val = (void 0);
if (code >= 97) { val = code - 97 + 10; } // a
else if (code >= 65) { val = code - 65 + 10; } // A
else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
else { val = Infinity; }
if (val >= radix) { break }
++this.pos;
total = total * radix + val;
}
if (this.pos === start || len != null && this.pos - start !== len) { return null }
return total
}...
return total
};
pp$9.readRadixNumber = function(radix) {
var start = this.pos;
this.pos += 2; // 0x
var val = this.readInt(radix);
if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
val = typeof BigInt !== "undefined" ? BigInt(this.input.slice(start, this.pos)) : null;
++this.pos;
} else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
return this.finishToken(types.num, val)
};
...function() {
for (; this.pos < this.input.length; this.pos++) {
switch (this.input[this.pos]) {
case "\\":
++this.pos;
break
case "$":
if (this.input[this.pos + 1] !== "{") {
break
}
// falls through
case "`":
return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
// no default
}
}
this.raise(this.start, "Unterminated template");
}...
pp$9.tryReadTemplateToken = function() {
this.inTemplateElement = true;
try {
this.readTmplToken();
} catch (err) {
if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
this.readInvalidTemplateToken();
} else {
throw err
}
}
this.inTemplateElement = false;
};
...function(startsWithDot) {
var start = this.pos;
if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number"); }
var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
if (octal && this.strict) { this.raise(start, "Invalid number"); }
if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
var next = this.input.charCodeAt(this.pos);
if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
var str$1 = this.input.slice(start, this.pos);
var val$1 = typeof BigInt !== "undefined" ? BigInt(str$1) : null;
++this.pos;
if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
return this.finishToken(types.num, val$1)
}
if (next === 46 && !octal) { // '.'
++this.pos;
this.readInt(10);
next = this.input.charCodeAt(this.pos);
}
if ((next === 69 || next === 101) && !octal) { // 'eE'
next = this.input.charCodeAt(++this.pos);
if (next === 43 || next === 45) { ++this.pos; } // '+-'
if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
}
if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
var str = this.input.slice(start, this.pos);
var val = octal ? parseInt(str, 8) : parseFloat(str);
return this.finishToken(types.num, val)
}...
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp$9.readToken_dot = function() {
var next = this.input.charCodeAt(this.pos + 1);
if (next >= 48 && next <= 57) { return this.readNumber(true) }
var next2 = this.input.charCodeAt(this.pos + 2);
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3;
return this.finishToken(types.ellipsis)
} else {
++this.pos;
return this.finishToken(types.dot)
...function(radix) {
var start = this.pos;
this.pos += 2; // 0x
var val = this.readInt(radix);
if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
val = typeof BigInt !== "undefined" ? BigInt(this.input.slice(start, this.pos)) : null;
++this.pos;
} else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
return this.finishToken(types.num, val)
}...
case 96: // '`'
if (this.options.ecmaVersion < 6) { break }
++this.pos;
return this.finishToken(types.backQuote)
case 48: // '0'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x&apos
;, '0X' - hex number
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
...function() {
var escaped, inClass, start = this.pos;
for (;;) {
if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
var ch = this.input.charAt(this.pos);
if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
if (!escaped) {
if (ch === "[") { inClass = true; }
else if (ch === "]" && inClass) { inClass = false; }
else if (ch === "/" && !inClass) { break }
escaped = ch === "\\";
} else { escaped = false; }
++this.pos;
}
var pattern = this.input.slice(start, this.pos);
++this.pos;
var flagsStart = this.pos;
var flags = this.readWord1();
if (this.containsEsc) { this.unexpected(flagsStart); }
// Validate pattern
var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
state.reset(start, pattern, flags);
this.validateRegExpFlags(state);
this.validateRegExpPattern(state);
// Create Literal#value property value.
var value = null;
try {
value = new RegExp(pattern, flags);
} catch (e) {
// ESTree requires null if it failed to instantiate RegExp object.
// https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
}
return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
}...
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
pp$3.parseExprAtom = function(refDestructuringErrors) {
// If a division operator appears in an expression position, the
// tokenizer got confused, and we force it to read a regexp instead.
if (this.type === types.slash) { this.readRegexp(); }
var node, canBeArrow = this.potentialArrowAt === this.start;
switch (this.type) {
case types._super:
if (!this.allowSuper)
{ this.raise(this.start, "'super' keyword outside a method"); }
node = this.startNode();
...function(quote) {
var out = "", chunkStart = ++this.pos;
for (;;) {
if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
var ch = this.input.charCodeAt(this.pos);
if (ch === quote) { break }
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(false);
chunkStart = this.pos;
} else {
if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return this.finishToken(types.string, out)
}...
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
return this.readNumber(false)
// Quotes produce strings.
case 34: case 39: // '"', "'"
return this.readString(code)
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
...function() {
var out = "", chunkStart = this.pos;
for (;;) {
if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
var ch = this.input.charCodeAt(this.pos);
if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
if (ch === 36) {
this.pos += 2;
return this.finishToken(types.dollarBraceL)
} else {
++this.pos;
return this.finishToken(types.backQuote)
}
}
out += this.input.slice(chunkStart, this.pos);
return this.finishToken(types.template, out)
}
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(true);
chunkStart = this.pos;
} else if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos);
++this.pos;
switch (ch) {
case 13:
if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
case 10:
out += "\n";
break
default:
out += String.fromCharCode(ch);
break
}
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
chunkStart = this.pos;
} else {
++this.pos;
}
}
}...
// Reads template string tokens.
var INVALID_TEMPLATE_ESCAPE_ERROR = {};
pp$9.tryReadTemplateToken = function() {
this.inTemplateElement = true;
try {
this.readTmplToken();
} catch (err) {
if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
this.readInvalidTemplateToken();
} else {
throw err
}
}
...function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
{ return this.readWord() }
return this.getTokenFromCode(code)
}...
if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
this.start = this.pos;
if (this.options.locations) { this.startLoc = this.curPosition(); }
if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
if (curContext.override) { return curContext.override(this) }
else { this.readToken(this.fullCharCodeAtPos()); }
};
pp$9.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
{ return this.readWord() }
...function() { // '^'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(types.bitwiseXOR, 1)
}...
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
...function() {
var next = this.input.charCodeAt(this.pos + 1);
if (next >= 48 && next <= 57) { return this.readNumber(true) }
var next2 = this.input.charCodeAt(this.pos + 2);
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3;
return this.finishToken(types.ellipsis)
} else {
++this.pos;
return this.finishToken(types.dot)
}
}...
};
pp$9.getTokenFromCode = function(code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot()
// Punctuation tokens.
case 40: ++this.pos; return this.finishToken(types.parenL)
case 41: ++this.pos; return this.finishToken(types.parenR)
case 59: ++this.pos; return this.finishToken(types.semi)
case 44: ++this.pos; return this.finishToken(types.comma)
case 91: ++this.pos; return this.finishToken(types.bracketL)
...function(code) { // '=!'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
this.pos += 2;
return this.finishToken(types.arrow)
}
return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
}...
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 126: // '~'
return this.finishOp(types.prefix, 1)
}
this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
};
...function(code) { // '<>'
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
return this.finishOp(types.bitShift, size)
}
if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
this.input.charCodeAt(this.pos + 3) === 45) {
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4);
this.skipSpace();
return this.nextToken()
}
if (next === 61) { size = 2; }
return this.finishOp(types.relational, size)
}...
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 126: // '~'
return this.finishOp(types.prefix, 1)
}
...function(code) { // '%*'
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
var tokentype = code === 42 ? types.star : types.modulo;
// exponentiation operator ** and **=
if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
++size;
tokentype = types.starstar;
next = this.input.charCodeAt(this.pos + 2);
}
if (next === 61) { return this.finishOp(types.assign, size + 1) }
return this.finishOp(tokentype, size)
}...
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
...function(code) { // '|&'
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) }
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
}...
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
...function(code) { // '+-'
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) {
if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
(this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
// A `-->` line comment
this.skipLineComment(3);
this.skipSpace();
return this.nextToken()
}
return this.finishOp(types.incDec, 2)
}
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(types.plusMin, 1)
}...
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
...function() { // '/'
var next = this.input.charCodeAt(this.pos + 1);
if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(types.slash, 1)
}...
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
...function() {
var word = this.readWord1();
var type = types.name;
if (this.keywords.test(word)) {
if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + word); }
type = keywords$1[word];
}
return this.finishToken(type, word)
}...
else { this.readToken(this.fullCharCodeAtPos()); }
};
pp$9.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
{ return this.readWord() }
return this.getTokenFromCode(code)
};
pp$9.fullCharCodeAtPos = function() {
var code = this.input.charCodeAt(this.pos);
if (code <= 0xd7ff || code >= 0xe000) { return code }
...function() {
this.containsEsc = false;
var word = "", first = true, chunkStart = this.pos;
var astral = this.options.ecmaVersion >= 6;
while (this.pos < this.input.length) {
var ch = this.fullCharCodeAtPos();
if (isIdentifierChar(ch, astral)) {
this.pos += ch <= 0xffff ? 1 : 2;
} else if (ch === 92) { // "\"
this.containsEsc = true;
word += this.input.slice(chunkStart, this.pos);
var escStart = this.pos;
if (this.input.charCodeAt(++this.pos) !== 117) // "u"
{ this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
++this.pos;
var esc = this.readCodePoint();
if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
{ this.invalidStringToken(escStart, "Invalid Unicode escape"); }
word += codePointToString$1(esc);
chunkStart = this.pos;
} else {
break
}
first = false;
}
return word + this.input.slice(chunkStart, this.pos)
}...
escaped = ch === "\\";
} else { escaped = false; }
++this.pos;
}
var pattern = this.input.slice(start, this.pos);
++this.pos;
var flagsStart = this.pos;
var flags = this.readWord1();
if (this.containsEsc) { this.unexpected(flagsStart); }
// Validate pattern
var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
state.reset(start, pattern, flags);
this.validateRegExpFlags(state);
this.validateRegExpPattern(state);
...function(state) {
while (state.pos < state.source.length && this.regexp_eatTerm(state))
{ }
}...
state.raise("Invalid named capture referenced");
}
}
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
pp$8.regexp_disjunction = function(state) {
this.regexp_alternative(state);
while (state.eat(0x7C /* | */)) {
this.regexp_alternative(state);
}
// Make the same message as V8.
if (this.regexp_eatQuantifier(state, true)) {
state.raise("Nothing to repeat");
...function(state) {
while (this.regexp_eatClassAtom(state)) {
var left = state.lastIntValue;
if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
var right = state.lastIntValue;
if (state.switchU && (left === -1 || right === -1)) {
state.raise("Invalid character class");
}
if (left !== -1 && right !== -1 && left > right) {
state.raise("Range out of order in character class");
}
}
}
}...
return this.regexp_eatUnicodePropertyValue(state)
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
pp$8.regexp_eatCharacterClass = function(state) {
if (state.eat(0x5B /* [ */)) {
state.eat(0x5E /* ^ */);
this.regexp_classRanges(state);
if (state.eat(0x5D /* [ */)) {
return true
}
// Unreachable since it threw "unterminated regular expression" error before.
state.raise("Unterminated character class");
}
return false
...function(state) {
this.regexp_alternative(state);
while (state.eat(0x7C /* | */)) {
this.regexp_alternative(state);
}
// Make the same message as V8.
if (this.regexp_eatQuantifier(state, true)) {
state.raise("Nothing to repeat");
}
if (state.eat(0x7B /* { */)) {
state.raise("Lone quantifier brackets");
}
}...
state.lastStringValue = "";
state.lastAssertionIsQuantifiable = false;
state.numCapturingParens = 0;
state.maxBackReference = 0;
state.groupNames.length = 0;
state.backReferenceNames.length = 0;
this.regexp_disjunction(state);
if (state.pos !== state.source.length) {
// Make the same messages as V8.
if (state.eat(0x29 /* ) */)) {
state.raise("Unmatched ')'");
}
if (state.eat(0x5D /* [ */) || state.eat(0x7D /* } */)) {
...function(state) {
var start = state.pos;
state.lastAssertionIsQuantifiable = false;
// ^, $
if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
return true
}
// \b \B
if (state.eat(0x5C /* \ */)) {
if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
return true
}
state.pos = start;
}
// Lookahead / Lookbehind
if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
var lookbehind = false;
if (this.options.ecmaVersion >= 9) {
lookbehind = state.eat(0x3C /* < */);
}
if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
this.regexp_disjunction(state);
if (!state.eat(0x29 /* ) */)) {
state.raise("Unterminated group");
}
state.lastAssertionIsQuantifiable = !lookbehind;
return true
}
}
state.pos = start;
return false
}...
pp$8.regexp_alternative = function(state) {
while (state.pos < state.source.length && this.regexp_eatTerm(state))
{ }
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
pp$8.regexp_eatTerm = function(state) {
if (this.regexp_eatAssertion(state)) {
// Handle `QuantifiableAssertion Quantifier` alternative.
// `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
// is a QuantifiableAssertion.
if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
// Make the same message as V8.
if (state.switchU) {
state.raise("Invalid quantifier");
...function(state) {
return (
this.regexp_eatPatternCharacters(state) ||
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state)
)
}...
if (state.switchU) {
state.raise("Invalid quantifier");
}
}
return true
}
if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
this.regexp_eatQuantifier(state);
return true
}
return false
};
...function(state) {
if (
this.regexp_eatBackReference(state) ||
this.regexp_eatCharacterClassEscape(state) ||
this.regexp_eatCharacterEscape(state) ||
(state.switchN && this.regexp_eatKGroupName(state))
) {
return true
}
if (state.switchU) {
// Make the same message as V8.
if (state.current() === 0x63 /* c */) {
state.raise("Invalid unicode escape");
}
state.raise("Invalid escape");
}
return false
}...
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state)
)
};
pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (this.regexp_eatAtomEscape(state)) {
return true
}
state.pos = start;
}
return false
};
pp$8.regexp_eatUncapturingGroup = function(state) {
...function(state) {
var start = state.pos;
if (this.regexp_eatDecimalEscape(state)) {
var n = state.lastIntValue;
if (state.switchU) {
// For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
if (n > state.maxBackReference) {
state.maxBackReference = n;
}
return true
}
if (n <= state.numCapturingParens) {
return true
}
state.pos = start;
}
return false
}...
function isRegExpIdentifierPart(ch) {
return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch ===
0x200D /* <ZWJ> */
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
pp$8.regexp_eatAtomEscape = function(state) {
if (
this.regexp_eatBackReference(state) ||
this.regexp_eatCharacterClassEscape(state) ||
this.regexp_eatCharacterEscape(state) ||
(state.switchN && this.regexp_eatKGroupName(state))
) {
return true
}
if (state.switchU) {
...function(state, noError) {
var start = state.pos;
if (state.eat(0x7B /* { */)) {
var min = 0, max = -1;
if (this.regexp_eatDecimalDigits(state)) {
min = state.lastIntValue;
if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
max = state.lastIntValue;
}
if (state.eat(0x7D /* } */)) {
// SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
if (max !== -1 && max < min && !noError) {
state.raise("numbers out of order in {} quantifier");
}
return true
}
}
if (state.switchU && !noError) {
state.raise("Incomplete quantifier");
}
state.pos = start;
}
return false
}...
// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
return (
state.eat(0x2A /* * */) ||
state.eat(0x2B /* + */) ||
state.eat(0x3F /* ? */) ||
this.regexp_eatBracedQuantifier(state, noError)
)
};
pp$8.regexp_eatBracedQuantifier = function(state, noError) {
var start = state.pos;
if (state.eat(0x7B /* { */)) {
var min = 0, max = -1;
if (this.regexp_eatDecimalDigits(state)) {
...function(state) {
var start = state.pos;
if (state.eat(0x63 /* c */)) {
if (this.regexp_eatControlLetter(state)) {
return true
}
state.pos = start;
}
return false
}...
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
pp$8.regexp_eatCharacterEscape = function(state) {
return (
this.regexp_eatControlEscape(state) ||
this.regexp_eatCControlLetter(state) ||
this.regexp_eatZero(state) ||
this.regexp_eatHexEscapeSequence(state) ||
this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
};
...function(state) {
if (state.eat(0x28 /* ( */)) {
if (this.options.ecmaVersion >= 9) {
this.regexp_groupSpecifier(state);
} else if (state.current() === 0x3F /* ? */) {
state.raise("Invalid group");
}
this.regexp_disjunction(state);
if (state.eat(0x29 /* ) */)) {
state.numCapturingParens += 1;
return true
}
state.raise("Unterminated group");
}
return false
}...
pp$8.regexp_eatAtom = function(state) {
return (
this.regexp_eatPatternCharacters(state) ||
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state)
)
};
pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (this.regexp_eatAtomEscape(state)) {
return true
...function(state) {
if (state.eat(0x5B /* [ */)) {
state.eat(0x5E /* ^ */);
this.regexp_classRanges(state);
if (state.eat(0x5D /* [ */)) {
return true
}
// Unreachable since it threw "unterminated regular expression" error before.
state.raise("Unterminated character class");
}
return false
}...
// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
pp$8.regexp_eatAtom = function(state) {
return (
this.regexp_eatPatternCharacters(state) ||
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state)
)
};
pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
...function(state) {
var ch = state.current();
if (isCharacterClassEscape(ch)) {
state.lastIntValue = -1;
state.advance();
return true
}
if (
state.switchU &&
this.options.ecmaVersion >= 9 &&
(ch === 0x50 /* P */ || ch === 0x70 /* p */)
) {
state.lastIntValue = -1;
state.advance();
if (
state.eat(0x7B /* { */) &&
this.regexp_eatUnicodePropertyValueExpression(state) &&
state.eat(0x7D /* } */)
) {
return true
}
state.raise("Invalid property name");
}
return false
}...
return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch ===
0x200D /* <ZWJ> */
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
pp$8.regexp_eatAtomEscape = function(state) {
if (
this.regexp_eatBackReference(state) ||
this.regexp_eatCharacterClassEscape(state) ||
this.regexp_eatCharacterEscape(state) ||
(state.switchN && this.regexp_eatKGroupName(state))
) {
return true
}
if (state.switchU) {
// Make the same message as V8.
...function(state) {
return (
this.regexp_eatControlEscape(state) ||
this.regexp_eatCControlLetter(state) ||
this.regexp_eatZero(state) ||
this.regexp_eatHexEscapeSequence(state) ||
this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
}...
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
pp$8.regexp_eatAtomEscape = function(state) {
if (
this.regexp_eatBackReference(state) ||
this.regexp_eatCharacterClassEscape(state) ||
this.regexp_eatCharacterEscape(state) ||
(state.switchN && this.regexp_eatKGroupName(state))
) {
return true
}
if (state.switchU) {
// Make the same message as V8.
if (state.current() === 0x63 /* c */) {
...function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (this.regexp_eatClassEscape(state)) {
return true
}
if (state.switchU) {
// Make the same message as V8.
var ch$1 = state.current();
if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
state.raise("Invalid class escape");
}
state.raise("Invalid escape");
}
state.pos = start;
}
var ch = state.current();
if (ch !== 0x5D /* [ */) {
state.lastIntValue = ch;
state.advance();
return true
}
return false
}...
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
pp$8.regexp_classRanges = function(state) {
while (this.regexp_eatClassAtom(state)) {
var left = state.lastIntValue;
if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
var right = state.lastIntValue;
if (state.switchU && (left === -1 || right === -1)) {
state.raise("Invalid character class");
}
if (left !== -1 && right !== -1 && left > right) {
...function(state) {
var ch = state.current();
if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
state.lastIntValue = ch % 0x20;
state.advance();
return true
}
return false
}...
if (state.switchU && state.eat(0x2D /* - */)) {
state.lastIntValue = 0x2D; /* - */
return true
}
if (!state.switchU && state.eat(0x63 /* c */)) {
if (this.regexp_eatClassControlLetter(state)) {
return true
}
state.pos = start;
}
return (
this.regexp_eatCharacterClassEscape(state) ||
...function(state) {
var start = state.pos;
if (state.eat(0x62 /* b */)) {
state.lastIntValue = 0x08; /* <BS> */
return true
}
if (state.switchU && state.eat(0x2D /* - */)) {
state.lastIntValue = 0x2D; /* - */
return true
}
if (!state.switchU && state.eat(0x63 /* c */)) {
if (this.regexp_eatClassControlLetter(state)) {
return true
}
state.pos = start;
}
return (
this.regexp_eatCharacterClassEscape(state) ||
this.regexp_eatCharacterEscape(state)
)
}...
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
pp$8.regexp_eatClassAtom = function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (this.regexp_eatClassEscape(state)) {
return true
}
if (state.switchU) {
// Make the same message as V8.
var ch$1 = state.current();
if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
state.raise("Invalid class escape");
...function(state) {
var ch = state.current();
if (ch === 0x74 /* t */) {
state.lastIntValue = 0x09; /* \t */
state.advance();
return true
}
if (ch === 0x6E /* n */) {
state.lastIntValue = 0x0A; /* \n */
state.advance();
return true
}
if (ch === 0x76 /* v */) {
state.lastIntValue = 0x0B; /* \v */
state.advance();
return true
}
if (ch === 0x66 /* f */) {
state.lastIntValue = 0x0C; /* \f */
state.advance();
return true
}
if (ch === 0x72 /* r */) {
state.lastIntValue = 0x0D; /* \r */
state.advance();
return true
}
return false
}...
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
pp$8.regexp_eatCharacterEscape = function(state) {
return (
this.regexp_eatControlEscape(state) ||
this.regexp_eatCControlLetter(state) ||
this.regexp_eatZero(state) ||
this.regexp_eatHexEscapeSequence(state) ||
this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
...function(state) {
var ch = state.current();
if (isControlLetter(ch)) {
state.lastIntValue = ch % 0x20;
state.advance();
return true
}
return false
}...
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
};
pp$8.regexp_eatCControlLetter = function(state) {
var start = state.pos;
if (state.eat(0x63 /* c */)) {
if (this.regexp_eatControlLetter(state)) {
return true
}
state.pos = start;
}
return false
};
pp$8.regexp_eatZero = function(state) {
...function(state) {
var start = state.pos;
var ch = 0;
state.lastIntValue = 0;
while (isDecimalDigit(ch = state.current())) {
state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
state.advance();
}
return state.pos !== start
}...
this.regexp_eatBracedQuantifier(state, noError)
)
};
pp$8.regexp_eatBracedQuantifier = function(state, noError) {
var start = state.pos;
if (state.eat(0x7B /* { */)) {
var min = 0, max = -1;
if (this.regexp_eatDecimalDigits(state)) {
min = state.lastIntValue;
if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
max = state.lastIntValue;
}
if (state.eat(0x7D /* } */)) {
// SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
if (max !== -1 && max < min && !noError) {
...function(state) {
state.lastIntValue = 0;
var ch = state.current();
if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
do {
state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
state.advance();
} while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
return true
}
return false
}...
}
state.raise("Invalid escape");
}
return false
};
pp$8.regexp_eatBackReference = function(state) {
var start = state.pos;
if (this.regexp_eatDecimalEscape(state)) {
var n = state.lastIntValue;
if (state.switchU) {
// For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
if (n > state.maxBackReference) {
state.maxBackReference = n;
}
return true
...function(state) {
return (
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state) ||
this.regexp_eatInvalidBracedQuantifier(state) ||
this.regexp_eatExtendedPatternCharacter(state)
)
}...
if (state.switchU) {
state.raise("Invalid quantifier");
}
}
return true
}
if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
this.regexp_eatQuantifier(state);
return true
}
return false
};
...function(state) {
var ch = state.current();
if (
ch !== -1 &&
ch !== 0x24 /* $ */ &&
!(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
ch !== 0x2E /* . */ &&
ch !== 0x3F /* ? */ &&
ch !== 0x5B /* [ */ &&
ch !== 0x5E /* ^ */ &&
ch !== 0x7C /* | */
) {
state.advance();
return true
}
return false
}...
return (
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state) ||
this.regexp_eatInvalidBracedQuantifier(state) ||
this.regexp_eatExtendedPatternCharacter(state)
)
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
if (this.regexp_eatBracedQuantifier(state, true)) {
state.raise("Nothing to repeat");
...function(state, length) {
var start = state.pos;
state.lastIntValue = 0;
for (var i = 0; i < length; ++i) {
var ch = state.current();
if (!isHexDigit(ch)) {
state.pos = start;
return false
}
state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
state.advance();
}
return true
}...
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state) {
var start = state.pos;
if (state.eat(0x75 /* u */)) {
if (this.regexp_eatFixedHexDigits(state, 4)) {
var lead = state.lastIntValue;
if (state.switchU && lead >= 0xD800 && lead <= 0xDBFF) {
var leadSurrogateEnd = state.pos;
if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
var trail = state.lastIntValue;
if (trail >= 0xDC00 && trail <= 0xDFFF) {
state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
...function(state) {
state.lastStringValue = "";
if (state.eat(0x3C /* < */)) {
if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
return true
}
state.raise("Invalid capture group name");
}
return false
}...
};
// GroupSpecifier[U] ::
// [empty]
// `?` GroupName[?U]
pp$8.regexp_groupSpecifier = function(state) {
if (state.eat(0x3F /* ? */)) {
if (this.regexp_eatGroupName(state)) {
if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
state.raise("Duplicate capture group name");
}
state.groupNames.push(state.lastStringValue);
return
}
state.raise("Invalid group");
...function(state) {
var start = state.pos;
var ch = 0;
state.lastIntValue = 0;
while (isHexDigit(ch = state.current())) {
state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
state.advance();
}
return state.pos !== start
}...
state.lastIntValue = lead;
}
return true
}
if (
state.switchU &&
state.eat(0x7B /* { */) &&
this.regexp_eatHexDigits(state) &&
state.eat(0x7D /* } */) &&
isValidUnicode(state.lastIntValue)
) {
return true
}
if (state.switchU) {
state.raise("Invalid unicode escape");
...function(state) {
var start = state.pos;
if (state.eat(0x78 /* x */)) {
if (this.regexp_eatFixedHexDigits(state, 2)) {
return true
}
if (state.switchU) {
state.raise("Invalid escape");
}
state.pos = start;
}
return false
}...
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
pp$8.regexp_eatCharacterEscape = function(state) {
return (
this.regexp_eatControlEscape(state) ||
this.regexp_eatCControlLetter(state) ||
this.regexp_eatZero(state) ||
this.regexp_eatHexEscapeSequence(state) ||
this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
};
pp$8.regexp_eatCControlLetter = function(state) {
var start = state.pos;
...function(state) {
if (state.switchU) {
if (this.regexp_eatSyntaxCharacter(state)) {
return true
}
if (state.eat(0x2F /* / */)) {
state.lastIntValue = 0x2F; /* / */
return true
}
return false
}
var ch = state.current();
if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
state.lastIntValue = ch;
state.advance();
return true
}
return false
}...
return (
this.regexp_eatControlEscape(state) ||
this.regexp_eatCControlLetter(state) ||
this.regexp_eatZero(state) ||
this.regexp_eatHexEscapeSequence(state) ||
this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
};
pp$8.regexp_eatCControlLetter = function(state) {
var start = state.pos;
if (state.eat(0x63 /* c */)) {
if (this.regexp_eatControlLetter(state)) {
return true
...function(state) {
if (this.regexp_eatBracedQuantifier(state, true)) {
state.raise("Nothing to repeat");
}
return false
}...
pp$8.regexp_eatExtendedAtom = function(state) {
return (
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state) ||
this.regexp_eatInvalidBracedQuantifier(state) ||
this.regexp_eatExtendedPatternCharacter(state)
)
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
if (this.regexp_eatBracedQuantifier(state, true)) {
...function(state) {
if (state.eat(0x6B /* k */)) {
if (this.regexp_eatGroupName(state)) {
state.backReferenceNames.push(state.lastStringValue);
return true
}
state.raise("Invalid named reference");
}
return false
}...
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
pp$8.regexp_eatAtomEscape = function(state) {
if (
this.regexp_eatBackReference(state) ||
this.regexp_eatCharacterClassEscape(state) ||
this.regexp_eatCharacterEscape(state) ||
(state.switchN && this.regexp_eatKGroupName(state))
) {
return true
}
if (state.switchU) {
// Make the same message as V8.
if (state.current() === 0x63 /* c */) {
state.raise("Invalid unicode escape");
...function(state) {
if (this.regexp_eatOctalDigit(state)) {
var n1 = state.lastIntValue;
if (this.regexp_eatOctalDigit(state)) {
var n2 = state.lastIntValue;
if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
} else {
state.lastIntValue = n1 * 8 + n2;
}
} else {
state.lastIntValue = n1;
}
return true
}
return false
}...
pp$8.regexp_eatCharacterEscape = function(state) {
return (
this.regexp_eatControlEscape(state) ||
this.regexp_eatCControlLetter(state) ||
this.regexp_eatZero(state) ||
this.regexp_eatHexEscapeSequence(state) ||
this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
};
pp$8.regexp_eatCControlLetter = function(state) {
var start = state.pos;
if (state.eat(0x63 /* c */)) {
if (this.regexp_eatControlLetter(state)) {
...function(state) {
return this.regexp_eatUnicodePropertyValue(state)
}...
this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
return true
}
}
state.pos = start;
// LoneUnicodePropertyNameOrValue
if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
var nameOrValue = state.lastStringValue;
this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
return true
}
return false
};
pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
...function(state) {
var ch = state.current();
if (isOctalDigit(ch)) {
state.lastIntValue = ch - 0x30; /* 0 */
state.advance();
return true
}
state.lastIntValue = 0;
return false
}...
}
return ch - 0x30 /* 0 */
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
// Allows only 0-377(octal) i.e. 0-255(decimal).
pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
if (this.regexp_eatOctalDigit(state)) {
var n1 = state.lastIntValue;
if (this.regexp_eatOctalDigit(state)) {
var n2 = state.lastIntValue;
if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
} else {
state.lastIntValue = n1 * 8 + n2;
...function(state) {
var start = state.pos;
var ch = 0;
while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
state.advance();
}
return state.pos !== start
}...
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
pp$8.regexp_eatAtom = function(state) {
return (
this.regexp_eatPatternCharacters(state) ||
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state)
)
};
...function(state, noError) {
if ( noError === void 0 ) noError = false;
if (this.regexp_eatQuantifierPrefix(state, noError)) {
state.eat(0x3F /* ? */);
return true
}
return false
}...
pp$8.regexp_disjunction = function(state) {
this.regexp_alternative(state);
while (state.eat(0x7C /* | */)) {
this.regexp_alternative(state);
}
// Make the same message as V8.
if (this.regexp_eatQuantifier(state, true)) {
state.raise("Nothing to repeat");
}
if (state.eat(0x7B /* { */)) {
state.raise("Lone quantifier brackets");
}
};
...function(state, noError) {
return (
state.eat(0x2A /* * */) ||
state.eat(0x2B /* + */) ||
state.eat(0x3F /* ? */) ||
this.regexp_eatBracedQuantifier(state, noError)
)
}...
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
pp$8.regexp_eatQuantifier = function(state, noError) {
if ( noError === void 0 ) noError = false;
if (this.regexp_eatQuantifierPrefix(state, noError)) {
state.eat(0x3F /* ? */);
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
...function(state) {
state.lastStringValue = "";
if (this.regexp_eatRegExpIdentifierStart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
while (this.regexp_eatRegExpIdentifierPart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
}
return true
}
return false
}...
// GroupName[U] ::
// `<` RegExpIdentifierName[?U] `>`
// Note: this updates `state.lastStringValue` property with the eaten name.
pp$8.regexp_eatGroupName = function(state) {
state.lastStringValue = "";
if (state.eat(0x3C /* < */)) {
if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
return true
}
state.raise("Invalid capture group name");
}
return false
};
...function(state) {
var start = state.pos;
var ch = state.current();
state.advance();
if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) {
ch = state.lastIntValue;
}
if (isRegExpIdentifierPart(ch)) {
state.lastIntValue = ch;
return true
}
state.pos = start;
return false
}...
// RegExpIdentifierStart[?U]
// RegExpIdentifierName[?U] RegExpIdentifierPart[?U]
// Note: this updates `state.lastStringValue` property with the eaten name.
pp$8.regexp_eatRegExpIdentifierName = function(state) {
state.lastStringValue = "";
if (this.regexp_eatRegExpIdentifierStart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
while (this.regexp_eatRegExpIdentifierPart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
}
return true
}
return false
};
...function(state) {
var start = state.pos;
var ch = state.current();
state.advance();
if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) {
ch = state.lastIntValue;
}
if (isRegExpIdentifierStart(ch)) {
state.lastIntValue = ch;
return true
}
state.pos = start;
return false
}...
// RegExpIdentifierName[U] ::
// RegExpIdentifierStart[?U]
// RegExpIdentifierName[?U] RegExpIdentifierPart[?U]
// Note: this updates `state.lastStringValue` property with the eaten name.
pp$8.regexp_eatRegExpIdentifierName = function(state) {
state.lastStringValue = "";
if (this.regexp_eatRegExpIdentifierStart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
while (this.regexp_eatRegExpIdentifierPart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
}
return true
}
return false
...function(state) {
var start = state.pos;
if (state.eat(0x75 /* u */)) {
if (this.regexp_eatFixedHexDigits(state, 4)) {
var lead = state.lastIntValue;
if (state.switchU && lead >= 0xD800 && lead <= 0xDBFF) {
var leadSurrogateEnd = state.pos;
if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
var trail = state.lastIntValue;
if (trail >= 0xDC00 && trail <= 0xDFFF) {
state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
return true
}
}
state.pos = leadSurrogateEnd;
state.lastIntValue = lead;
}
return true
}
if (
state.switchU &&
state.eat(0x7B /* { */) &&
this.regexp_eatHexDigits(state) &&
state.eat(0x7D /* } */) &&
isValidUnicode(state.lastIntValue)
) {
return true
}
if (state.switchU) {
state.raise("Invalid unicode escape");
}
state.pos = start;
}
return false
}...
// `_`
// `\` RegExpUnicodeEscapeSequence[?U]
pp$8.regexp_eatRegExpIdentifierStart = function(state) {
var start = state.pos;
var ch = state.current();
state.advance();
if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) {
ch = state.lastIntValue;
}
if (isRegExpIdentifierStart(ch)) {
state.lastIntValue = ch;
return true
}
...function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (this.regexp_eatAtomEscape(state)) {
return true
}
state.pos = start;
}
return false
}...
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
pp$8.regexp_eatAtom = function(state) {
return (
this.regexp_eatPatternCharacters(state) ||
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state)
)
};
pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
var start = state.pos;
...function(state) {
var ch = state.current();
if (isSyntaxCharacter(ch)) {
state.lastIntValue = ch;
state.advance();
return true
}
return false
}...
function isValidUnicode(ch) {
return ch >= 0 && ch <= 0x10FFFF
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
pp$8.regexp_eatIdentityEscape = function(state) {
if (state.switchU) {
if (this.regexp_eatSyntaxCharacter(state)) {
return true
}
if (state.eat(0x2F /* / */)) {
state.lastIntValue = 0x2F; /* / */
return true
}
return false
...function(state) {
if (this.regexp_eatAssertion(state)) {
// Handle `QuantifiableAssertion Quantifier` alternative.
// `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
// is a QuantifiableAssertion.
if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
// Make the same message as V8.
if (state.switchU) {
state.raise("Invalid quantifier");
}
}
return true
}
if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
this.regexp_eatQuantifier(state);
return true
}
return false
}...
if (state.eat(0x7B /* { */)) {
state.raise("Lone quantifier brackets");
}
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
pp$8.regexp_alternative = function(state) {
while (state.pos < state.source.length && this.regexp_eatTerm(state))
{ }
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
pp$8.regexp_eatTerm = function(state) {
if (this.regexp_eatAssertion(state)) {
// Handle `QuantifiableAssertion Quantifier` alternative.
...function(state) {
var start = state.pos;
if (state.eat(0x28 /* ( */)) {
if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
this.regexp_disjunction(state);
if (state.eat(0x29 /* ) */)) {
return true
}
state.raise("Unterminated group");
}
state.pos = start;
}
return false
}...
// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
pp$8.regexp_eatAtom = function(state) {
return (
this.regexp_eatPatternCharacters(state) ||
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state)
)
};
pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (this.regexp_eatAtomEscape(state)) {
...function(state) {
var ch = 0;
state.lastStringValue = "";
while (isUnicodePropertyNameCharacter(ch = state.current())) {
state.lastStringValue += codePointToString(ch);
state.advance();
}
return state.lastStringValue !== ""
}...
// UnicodePropertyValueExpression ::
// UnicodePropertyName `=` UnicodePropertyValue
// LoneUnicodePropertyNameOrValue
pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
var start = state.pos;
// UnicodePropertyName `=` UnicodePropertyValue
if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
var name = state.lastStringValue;
if (this.regexp_eatUnicodePropertyValue(state)) {
var value = state.lastStringValue;
this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
return true
}
}
...function(state) {
var ch = 0;
state.lastStringValue = "";
while (isUnicodePropertyValueCharacter(ch = state.current())) {
state.lastStringValue += codePointToString(ch);
state.advance();
}
return state.lastStringValue !== ""
}...
// LoneUnicodePropertyNameOrValue
pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
var start = state.pos;
// UnicodePropertyName `=` UnicodePropertyValue
if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
var name = state.lastStringValue;
if (this.regexp_eatUnicodePropertyValue(state)) {
var value = state.lastStringValue;
this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
return true
}
}
state.pos = start;
...function(state) {
var start = state.pos;
// UnicodePropertyName `=` UnicodePropertyValue
if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
var name = state.lastStringValue;
if (this.regexp_eatUnicodePropertyValue(state)) {
var value = state.lastStringValue;
this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
return true
}
}
state.pos = start;
// LoneUnicodePropertyNameOrValue
if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
var nameOrValue = state.lastStringValue;
this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
return true
}
return false
}...
this.options.ecmaVersion >= 9 &&
(ch === 0x50 /* P */ || ch === 0x70 /* p */)
) {
state.lastIntValue = -1;
state.advance();
if (
state.eat(0x7B /* { */) &&
this.regexp_eatUnicodePropertyValueExpression(state) &&
state.eat(0x7D /* } */)
) {
return true
}
state.raise("Invalid property name");
}
...function(state) {
if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
state.lastIntValue = 0;
state.advance();
return true
}
return false
}...
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
pp$8.regexp_eatCharacterEscape = function(state) {
return (
this.regexp_eatControlEscape(state) ||
this.regexp_eatCControlLetter(state) ||
this.regexp_eatZero(state) ||
this.regexp_eatHexEscapeSequence(state) ||
this.regexp_eatRegExpUnicodeEscapeSequence(state) ||
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
};
pp$8.regexp_eatCControlLetter = function(state) {
...function(state) {
if (state.eat(0x3F /* ? */)) {
if (this.regexp_eatGroupName(state)) {
if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
state.raise("Duplicate capture group name");
}
state.groupNames.push(state.lastStringValue);
return
}
state.raise("Invalid group");
}
}...
state.pos = start;
}
return false
};
pp$8.regexp_eatCapturingGroup = function(state) {
if (state.eat(0x28 /* ( */)) {
if (this.options.ecmaVersion >= 9) {
this.regexp_groupSpecifier(state);
} else if (state.current() === 0x3F /* ? */) {
state.raise("Invalid group");
}
this.regexp_disjunction(state);
if (state.eat(0x29 /* ) */)) {
state.numCapturingParens += 1;
return true
...function(state) {
state.pos = 0;
state.lastIntValue = 0;
state.lastStringValue = "";
state.lastAssertionIsQuantifiable = false;
state.numCapturingParens = 0;
state.maxBackReference = 0;
state.groupNames.length = 0;
state.backReferenceNames.length = 0;
this.regexp_disjunction(state);
if (state.pos !== state.source.length) {
// Make the same messages as V8.
if (state.eat(0x29 /* ) */)) {
state.raise("Unmatched ')'");
}
if (state.eat(0x5D /* [ */) || state.eat(0x7D /* } */)) {
state.raise("Lone quantifier brackets");
}
}
if (state.maxBackReference > state.numCapturingParens) {
state.raise("Invalid escape");
}
for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
var name = list[i];
if (state.groupNames.indexOf(name) === -1) {
state.raise("Invalid named capture referenced");
}
}
}...
/**
* Validate the pattern part of a given RegExpLiteral.
*
* @param {RegExpValidationState} state The state to validate RegExp.
* @returns {void}
*/
pp$8.validateRegExpPattern = function(state) {
this.regexp_pattern(state);
// The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
// parsing contains a |GroupName|, reparse with the goal symbol
// |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
// exception if _P_ did not conform to the grammar, if any elements of _P_
// were not matched by the parse, or if any Early Error conditions exist.
if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
...function(state, name, value) {
if (!has(state.unicodeProperties.nonBinary, name))
{ state.raise("Invalid property name"); }
if (!state.unicodeProperties.nonBinary[name].test(value))
{ state.raise("Invalid property value"); }
}...
var start = state.pos;
// UnicodePropertyName `=` UnicodePropertyValue
if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
var name = state.lastStringValue;
if (this.regexp_eatUnicodePropertyValue(state)) {
var value = state.lastStringValue;
this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
return true
}
}
state.pos = start;
// LoneUnicodePropertyNameOrValue
if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
...function(state, nameOrValue) {
if (!state.unicodeProperties.binary.test(nameOrValue))
{ state.raise("Invalid property name"); }
}...
}
}
state.pos = start;
// LoneUnicodePropertyNameOrValue
if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
var nameOrValue = state.lastStringValue;
this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
return true
}
return false
};
pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
if (!has(state.unicodeProperties.nonBinary, name))
{ state.raise("Invalid property name"); }
...function() {
if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
}...
pp$1.parseBreakContinueStatement = function(node, keyword) {
var isBreak = keyword === "break";
this.next();
if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
else if (this.type !== types.name) { this.unexpected(); }
else {
node.label = this.parseIdent();
this.semicolon();
}
// Verify that there is an actual destination to break or
// continue to.
var i = 0;
for (; i < this.labels.length; ++i) {
var lab = this.labels[i];
...function() {
return this.type.keyword === "var" ||
this.type.keyword === "const" ||
this.type.keyword === "class" ||
this.type.keyword === "function" ||
this.isLet() ||
this.isAsyncFunction()
}...
} else {
node.declaration = this.parseMaybeAssign();
this.semicolon();
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(null);
if (node.declaration.type === "VariableDeclaration")
{ this.checkVariableExport(exports, node.declaration.declarations); }
else
{ this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
node.specifiers = [];
node.source = null;
...function() {
var startLoc = this.options.onComment && this.curPosition();
var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
this.pos = end + 2;
if (this.options.locations) {
lineBreakG.lastIndex = start;
var match;
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this.curLine;
this.lineStart = match.index + match[0].length;
}
}
if (this.options.onComment)
{ this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition()); }
}...
++this.curLine;
this.lineStart = this.pos;
}
break
case 47: // '/'
switch (this.input.charCodeAt(this.pos + 1)) {
case 42: // '*'
this.skipBlockComment();
break
case 47:
this.skipLineComment(2);
break
default:
break loop
}
...function(startSkip) {
var start = this.pos;
var startLoc = this.options.onComment && this.curPosition();
var ch = this.input.charCodeAt(this.pos += startSkip);
while (this.pos < this.input.length && !isNewLine(ch)) {
ch = this.input.charCodeAt(++this.pos);
}
if (this.options.onComment)
{ this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
startLoc, this.curPosition()); }
}...
// Labels in scope.
this.labels = [];
// Thus-far undefined exports.
this.undefinedExports = {};
// If enabled, skip leading hashbang line.
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
{ this.skipLineComment(2); }
// Scope tracking for duplicate variable names (see scope.js)
this.scopeStack = [];
this.enterScope(SCOPE_TOP);
// For RegExp validation
this.regexpState = null;
...function() {
loop: while (this.pos < this.input.length) {
var ch = this.input.charCodeAt(this.pos);
switch (ch) {
case 32: case 160: // ' '
++this.pos;
break
case 13:
if (this.input.charCodeAt(this.pos + 1) === 10) {
++this.pos;
}
case 10: case 8232: case 8233:
++this.pos;
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
break
case 47: // '/'
switch (this.input.charCodeAt(this.pos + 1)) {
case 42: // '*'
this.skipBlockComment();
break
case 47:
this.skipLineComment(2);
break
default:
break loop
}
break
default:
if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this.pos;
} else {
break loop
}
}
}
}...
};
// Read a single token, updating the parser object's token-related
// properties.
pp$9.nextToken = function() {
var curContext = this.curContext();
if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
this.start = this.pos;
if (this.options.locations) { this.startLoc = this.curPosition(); }
if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
if (curContext.override) { return curContext.override(this) }
else { this.readToken(this.fullCharCodeAtPos()); }
...function() {
return new Node(this, this.start, this.startLoc)
}...
// For RegExp validation
this.regexpState = null;
};
var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },
allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } };
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode();
this.nextToken();
return this.parseTopLevel(node)
};
prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
...function(pos, loc) {
return new Node(this, pos, loc)
}...
if ( noLineBreak === void 0 ) noLineBreak = false;
var start = this$1.start, startLoc = this$1.startLoc;
if (!this$1.eatContextual(k)) { return false }
if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
if (method.key) { this$1.unexpected(); }
method.computed = false;
method.key = this$1.startNodeAt(start, startLoc);
method.key.name = k;
this$1.finishNode(method.key, "Identifier");
return false
};
method.kind = "method";
method.static = tryContextual("static");
...function(start) {
for (;;) {
// Try to find string literal.
skipWhiteSpace.lastIndex = start;
start += skipWhiteSpace.exec(this.input)[0].length;
var match = literal.exec(this.input.slice(start));
if (!match) { return false }
if ((match[1] || match[2]) === "use strict") { return true }
start += match[0].length;
// Skip semicolon, if any.
skipWhiteSpace.lastIndex = start;
start += skipWhiteSpace.exec(this.input)[0].length;
if (this.input[start] === ";")
{ start++; }
}
}...
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext();
this.exprAllowed = true;
// Figure out if it's a module code.
this.inModule = options.sourceType === "module";
this.strict = this.inModule || this.strictDirective(this.pos);
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1;
// Positions to delayed-check that yield/await does not exist in default parameters.
this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
// Labels in scope.
...function(node, isBinding, refDestructuringErrors) {
if (this.options.ecmaVersion >= 6 && node) {
switch (node.type) {
case "Identifier":
if (this.inAsync && node.name === "await")
{ this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
break
case "ObjectPattern":
case "ArrayPattern":
case "RestElement":
break
case "ObjectExpression":
node.type = "ObjectPattern";
if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
this.toAssignable(prop, isBinding);
// Early error:
// AssignmentRestProperty[Yield, Await] :
// `...` DestructuringAssignmentTarget[Yield, Await]
//
// It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
if (
prop.type === "RestElement" &&
(prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
) {
this.raise(prop.argument.start, "Unexpected token");
}
}
break
case "Property":
// AssignmentProperty has type === "Property"
if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
this.toAssignable(node.value, isBinding);
break
case "ArrayExpression":
node.type = "ArrayPattern";
if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
this.toAssignableList(node.elements, isBinding);
break
case "SpreadElement":
node.type = "RestElement";
this.toAssignable(node.argument, isBinding);
if (node.argument.type === "AssignmentPattern")
{ this.raise(node.argument.start, "Rest elements cannot have a default value"); }
break
case "AssignmentExpression":
if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
node.type = "AssignmentPattern";
delete node.operator;
this.toAssignable(node.left, isBinding);
// falls through to AssignmentPattern
case "AssignmentPattern":
break
case "ParenthesizedExpression":
this.toAssignable(node.expression, isBinding, refDestructuringErrors);
break
case "MemberExpression":
if (!isBinding) { break }
default:
this.raise(node.start, "Assigning to rvalue");
}
} else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
return node
}...
var init = this.parseExpression(true, refDestructuringErrors);
if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
this.toAssignable(init, false, refDestructuringErrors);
this.checkLVal(init);
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true);
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init)
...function(exprList, isBinding) {
var end = exprList.length;
for (var i = 0; i < end; i++) {
var elt = exprList[i];
if (elt) { this.toAssignable(elt, isBinding); }
}
if (end) {
var last = exprList[end - 1];
if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier
")
{ this.unexpected(last.argument.start); }
}
return exprList
}...
if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"
;); }
this.toAssignable(node.value, isBinding);
break
case "ArrayExpression":
node.type = "ArrayPattern";
if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
this.toAssignableList(node.elements, isBinding);
break
case "SpreadElement":
node.type = "RestElement";
this.toAssignable(node.argument, isBinding);
if (node.argument.type === "AssignmentPattern")
{ this.raise(node.argument.start, "Rest elements cannot have a default value"); }
...function(scope) {
return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
}...
};
prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope
(this.currentScope()) };
// Switch to a getter for 7.0.0.
Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION
) > 0 };
Parser.extend = function extend () {
var plugins = [], len = arguments.length;
while ( len-- ) plugins[ len ] = arguments[ len ];
...function() {
this.inTemplateElement = true;
try {
this.readTmplToken();
} catch (err) {
if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
this.readInvalidTemplateToken();
} else {
throw err
}
}
this.inTemplateElement = false;
}...
var types$1 = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", false),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken
(); }),
f_stat: new TokContext("function", false),
f_expr: new TokContext("function", true),
f_expr_gen: new TokContext("function", true, false, null, true),
f_gen: new TokContext("function", false, false, null, true)
};
var pp$7 = Parser.prototype;
...function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token");
}...
this.next();
return true
};
// Asserts that following token is given contextual keyword.
pp.expectContextual = function(name) {
if (!this.eatContextual(name)) { this.unexpected(); }
};
// Test whether a semicolon can be inserted at the current position.
pp.canInsertSemicolon = function() {
return this.type === types.eof ||
this.type === types.braceR ||
...function(prevType) {
var update, type = this.type;
if (type.keyword && prevType === types.dot)
{ this.exprAllowed = false; }
else if (update = type.updateContext)
{ update.call(this, prevType); }
else
{ this.exprAllowed = type.beforeExpr; }
}...
pp$9.finishToken = function(type, val) {
this.end = this.pos;
if (this.options.locations) { this.endLoc = this.curPosition(); }
var prevType = this.type;
this.type = type;
this.value = val;
this.updateContext(prevType);
};
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
...function(state) {
var validFlags = state.validFlags;
var flags = state.flags;
for (var i = 0; i < flags.length; i++) {
var flag = flags.charAt(i);
if (validFlags.indexOf(flag) === -1) {
this.raise(state.start, "Invalid regular expression flag");
}
if (flags.indexOf(flag, i + 1) > -1) {
this.raise(state.start, "Duplicate regular expression flag");
}
}
}...
var flagsStart = this.pos;
var flags = this.readWord1();
if (this.containsEsc) { this.unexpected(flagsStart); }
// Validate pattern
var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
state.reset(start, pattern, flags);
this.validateRegExpFlags(state);
this.validateRegExpPattern(state);
// Create Literal#value property value.
var value = null;
try {
value = new RegExp(pattern, flags);
} catch (e) {
...function(state) {
this.regexp_pattern(state);
// The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
// parsing contains a |GroupName|, reparse with the goal symbol
// |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
// exception if _P_ did not conform to the grammar, if any elements of _P_
// were not matched by the parse, or if any Early Error conditions exist.
if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
state.switchN = true;
this.regexp_pattern(state);
}
}...
var flags = this.readWord1();
if (this.containsEsc) { this.unexpected(flagsStart); }
// Validate pattern
var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
state.reset(start, pattern, flags);
this.validateRegExpFlags(state);
this.validateRegExpPattern(state);
// Create Literal#value property value.
var value = null;
try {
value = new RegExp(pattern, flags);
} catch (e) {
// ESTree requires null if it failed to instantiate RegExp object.
...function offset (n) {
return new Position(this.line, this.column + n)
}n/a
function Controller() { }n/a
function attachComments(tree, providedComments, tokens) {
// At first, we should calculate extended comment ranges.
var comments = [], comment, len, i, cursor;
if (!tree.range) {
throw new Error('attachComments needs range information');
}
// tokens array is empty, we attach comments to tree as 'leadingComments'
if (!tokens.length) {
if (providedComments.length) {
for (i = 0, len = providedComments.length; i < len; i += 1) {
comment = deepCopy(providedComments[i]);
comment.extendedRange = [0, tree.range[0]];
comments.push(comment);
}
tree.leadingComments = comments;
}
return tree;
}
for (i = 0, len = providedComments.length; i < len; i += 1) {
comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
}
// This is based on John Freeman's implementation.
cursor = 0;
traverse(tree, {
enter: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (comment.extendedRange[1] > node.range[0]) {
break;
}
if (comment.extendedRange[1] === node.range[0]) {
if (!node.leadingComments) {
node.leadingComments = [];
}
node.leadingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
cursor = 0;
traverse(tree, {
leave: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (node.range[1] < comment.extendedRange[0]) {
break;
}
if (node.range[1] === comment.extendedRange[0]) {
if (!node.trailingComments) {
node.trailingComments = [];
}
node.trailingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
return tree;
}n/a
cloneEnvironment = function () { return clone({}); }n/a
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}...
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
};
local.identity = function (val) {
/*
* this function will return <val>
*/
...function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}...
}
return outer.root;
};
function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}
...function __execute(callback, element) {
var previous, result;
result = undefined;
previous = this.__current;
this.__current = element;
this.__state = null;
if (callback) {
result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
}
this.__current = previous;
return result;
}...
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
ret = this.__execute(visitor.leave, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
continue;
}
...function(root, visitor) {
this.visitor = visitor;
this.root = root;
this.__worklist = [];
this.__leavelist = [];
this.__current = null;
this.__state = null;
this.__fallback = null;
if (visitor.fallback === 'iteration') {
this.__fallback = objectKeys;
} else if (typeof visitor.fallback === 'function') {
this.__fallback = visitor.fallback;
}
this.__keys = VisitorKeys;
if (visitor.keys) {
this.__keys = extend(objectCreate(this.__keys), visitor.keys);
}
}...
key,
current,
current2,
candidates,
candidate,
sentinel;
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
...break = function () {
this.notify(BREAK);
}n/a
function current() {
return this.__current.node;
}...
};
RegExpValidationState.prototype.advance = function advance () {
this.pos = this.nextIndex(this.pos);
};
RegExpValidationState.prototype.eat = function eat (ch) {
if (this.current() === ch) {
this.advance();
return true
}
return false
};
function codePointToString(ch) {
...function notify(flag) {
this.__state = flag;
}...
Controller.prototype.notify = function notify(flag) {
this.__state = flag;
};
// API:
// skip child nodes of current node
Controller.prototype.skip = function () {
this.notify(SKIP);
};
// API:
// break traversals
Controller.prototype['break'] = function () {
this.notify(BREAK);
};
...function parents() {
var i, iz, result;
// first node is sentinel
result = [];
for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
result.push(this.__leavelist[i].node);
}
return result;
}n/a
function path() {
var i, iz, j, jz, result, element;
function addToPath(result, path) {
if (isArray(path)) {
for (j = 0, jz = path.length; j < jz; ++j) {
result.push(path[j]);
}
} else {
result.push(path);
}
}
// root node
if (!this.__current.path) {
return null;
}
// first node is sentinel, second node is root element
result = [];
for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
element = this.__leavelist[i];
addToPath(result, element.path);
}
addToPath(result, this.__current.path);
return result;
}n/a
remove = function () {
this.notify(REMOVE);
}...
function removeElem(element) {
var i,
key,
nextElem,
parent;
if (element.ref.remove()) {
// When the reference is an element of an array.
key = element.ref.key;
parent = element.ref.parent;
// If removed from array, then decrease following items' keys.
i = worklist.length;
while (i--) {
...function replace(root, visitor) {
var worklist,
leavelist,
node,
nodeType,
target,
element,
current,
current2,
candidates,
candidate,
sentinel,
outer,
key;
function removeElem(element) {
var i,
key,
nextElem,
parent;
if (element.ref.remove()) {
// When the reference is an element of an array.
key = element.ref.key;
parent = element.ref.parent;
// If removed from array, then decrease following items' keys.
i = worklist.length;
while (i--) {
nextElem = worklist[i];
if (nextElem.ref && nextElem.ref.parent === parent) {
if (nextElem.ref.key < key) {
break;
}
--nextElem.ref.key;
}
}
}
}
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
outer = {
root: root
};
element = new Element(root, null, null, new Reference(outer, 'root'));
worklist.push(element);
leavelist.push(element);
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
target = this.__execute(visitor.leave, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
continue;
}
target = this.__execute(visitor.enter, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
element.node = target;
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
element.node = null;
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
// node may be null
node = element.node;
if (!node) {
continue;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || target === SKIP) {
continue;
}
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2
));
} else if (isNode(candidat......
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
};
local.identity = function (val) {
/*
* this function will return <val>
*/
...skip = function () {
this.notify(SKIP);
}n/a
function traverse(root, visitor) {
var worklist,
leavelist,
element,
node,
nodeType,
ret,
key,
current,
current2,
candidates,
candidate,
sentinel;
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
worklist.push(new Element(root, null, null, null));
leavelist.push(new Element(null, null, null, null));
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
ret = this.__execute(visitor.leave, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
continue;
}
if (element.node) {
ret = this.__execute(visitor.enter, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || ret === SKIP) {
continue;
}
node = element.node;
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', null);
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, null);
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
worklist.push(new Element(candidate, key, null, null));
}
}
}
}
}...
}
return outer.root;
};
function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}
...type = function () {
var node = this.current();
return node.type || this.__current.wrap;
}...
token = tokenStream.token();
endChar = token.endChar;
value = token.value + this._expr(inFunction).text;
if (unary === null) {
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
tokenStream.mustMatch(Tokens.type(endChar));
value += endChar;
this._readWhitespace();
//see if there's a simple match
} else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH,
Tokens.ANGLE, Tokens.TIME,
Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])) {
...function _debugEnd() { [native code] }n/a
function _debugProcess() { [native code] }n/a
(er, fromPromise) => {
// It's possible that defaultTriggerAsyncId was set for a constructor
// call that threw and was never cleared. So clear it now.
clearDefaultTriggerAsyncId();
// If diagnostic reporting is enabled, call into its handler to see
// whether it is interested in handling the situation.
// Ignore if the error is scoped inside a domain.
// use == in the checks as we want to allow for null and undefined
if (er == null || er.domain == null) {
try {
const report = internalBinding('report');
if (report != null && report.shouldReportOnUncaughtException()) {
report.writeReport(er ? er.message : 'Exception',
'Exception',
null,
er ? er.stack : undefined);
}
} catch {} // Ignore the exception. Diagnostic reporting is unavailable.
}
const type = fromPromise ? 'unhandledRejection' : 'uncaughtException';
process.emit('uncaughtExceptionMonitor', er, type);
if (exceptionHandlerState.captureFn !== null) {
exceptionHandlerState.captureFn(er);
} else if (!process.emit('uncaughtException', er, type)) {
// If someone handled it, then great. Otherwise, die in C++ land
// since that means that we'll exit the process, emit the 'exit' event.
try {
if (!process._exiting) {
process._exiting = true;
process.exitCode = 1;
process.emit('exit', 1);
}
} catch {
// Nothing to be done about it at this point.
}
return false;
}
// If we handled an error, then make sure any ticks get processed
// by ensuring that the next Immediate cycle isn't empty.
require('timers').setImmediate(noop);
// Emit the after() hooks now that the exception has been handled.
if (afterHooksExist()) {
do {
emitAfter(executionAsyncId());
} while (hasAsyncIdStack());
// Or completely empty the id stack.
} else {
clearAsyncIdStack();
}
return true;
}n/a
function _getActiveHandles() { [native code] }n/a
function _getActiveRequests() { [native code] }n/a
function _kill() { [native code] }n/a
function _linkedBinding(module) {
module = String(module);
let mod = bindingObj[module];
if (typeof mod !== 'object')
mod = bindingObj[module] = getLinkedBinding(module);
return mod;
}n/a
function _rawDebug(...args) {
binding._rawDebug(format.apply(null, args));
}n/a
function _startProfilerIdleNotifier() { [native code] }n/a
function _stopProfilerIdleNotifier() { [native code] }n/a
function runNextTicks() {
if (!hasTickScheduled() && !hasRejectionToWarn())
runMicrotasks();
if (!hasTickScheduled() && !hasRejectionToWarn())
return;
processTicksAndRejections();
}n/a
function abort() { [native code] }...
xhrInit();
// init timerTimeout
xhr.timerTimeout = setTimeout(function () {
xhr.err = xhr.err || new Error(
"onTimeout - "
+ timeout + " ms - " + "ajax " + xhr.method + " " + xhr.url
);
xhr.abort();
// cleanup reqStream and resStream
streamCleanup(xhr.reqStream);
streamCleanup(xhr.resStream);
}, timeout);
// increment cnt
ajaxProgressUpdate.cnt |= 0;
ajaxProgressUpdate.cnt += 1;
...function deprecated(...args) {
if (!warned) {
warned = true;
if (code !== undefined) {
if (!codesWarned.has(code)) {
process.emitWarning(msg, 'DeprecationWarning', code, deprecated);
codesWarned.add(code);
}
} else {
process.emitWarning(msg, 'DeprecationWarning', deprecated);
}
}
if (new.target) {
return ReflectConstruct(fn, args, new.target);
}
return fn.apply(this, args);
}...
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
...function binding(module) {
module = String(module);
// Deprecated specific process.binding() modules, but not all, allow
// selective fallback to internalBinding for the deprecated ones.
if (internalBindingWhitelist.has(module)) {
return internalBinding(module);
}
// eslint-disable-next-line no-restricted-syntax
throw new Error(`No such module: ${module}`);
}...
&& typeof dict[key] === "function"
) {
local[tmp][key] = local[tmp][key] || String(dict[key]);
}
});
});
Object.keys(local[tmp]).forEach(function (key) {
if (process.binding("natives")[key]) {
local[tmp][key] = undefined;
}
});
});
// autofix - local-function
dictFnc = {};
dictProp = {};
...function wrappedChdir(directory) {
validateString(directory, 'directory');
rawMethods.chdir(directory);
// Mark cache that it requires an update.
cachedCwd = '';
}n/a
function cpuUsage(prevValue) {
// If a previous value was passed in, ensure it has the correct shape.
if (prevValue) {
if (!previousValueIsValid(prevValue.user)) {
if (typeof prevValue !== 'object')
throw new ERR_INVALID_ARG_TYPE('prevValue', 'object', prevValue);
if (typeof prevValue.user !== 'number') {
throw new ERR_INVALID_ARG_TYPE('prevValue.user',
'number', prevValue.user);
}
throw new ERR_INVALID_OPT_VALUE.RangeError('prevValue.user',
prevValue.user);
}
if (!previousValueIsValid(prevValue.system)) {
if (typeof prevValue.system !== 'number') {
throw new ERR_INVALID_ARG_TYPE('prevValue.system',
'number', prevValue.system);
}
throw new ERR_INVALID_OPT_VALUE.RangeError('prevValue.system',
prevValue.system);
}
}
// Call the native function to get the current values.
const errmsg = _cpuUsage(cpuValues);
if (errmsg) {
throw new ERR_CPU_USAGE(errmsg);
}
// If a previous value was passed in, return diff of current from previous.
if (prevValue) {
return {
user: cpuValues[0] - prevValue.user,
system: cpuValues[1] - prevValue.system
};
}
// If no previous value passed in, return current value.
return {
user: cpuValues[0],
system: cpuValues[1]
};
}n/a
function wrappedCwd() {
if (cachedCwd === '')
cachedCwd = rawMethods.cwd();
return cachedCwd;
}...
let code2;
let dictFnc;
let dictProp;
let tmp;
if (local.isBrowser) {
return code;
}
file = local.path.resolve(file).replace(process.cwd() + local.path.sep, "");
switch (file) {
case "README.md":
case "lib." + process.env.npm_package_nameLib + ".js":
case "lib." + process.env.npm_package_nameLib + ".sh":
case "lib.apidoc.js":
case "lib.github_crud.js":
case "lib.istanbul.js":
...function dlopen() { [native code] }n/a
function emitWarning(warning, type, code, ctor) {
let detail;
if (type !== null && typeof type === 'object' && !ArrayIsArray(type)) {
ctor = type.ctor;
code = type.code;
if (typeof type.detail === 'string')
detail = type.detail;
type = type.type || 'Warning';
} else if (typeof type === 'function') {
ctor = type;
code = undefined;
type = 'Warning';
}
if (type !== undefined && typeof type !== 'string') {
throw new ERR_INVALID_ARG_TYPE('type', 'string', type);
}
if (typeof code === 'function') {
ctor = code;
code = undefined;
} else if (code !== undefined && typeof code !== 'string') {
throw new ERR_INVALID_ARG_TYPE('code', 'string', code);
}
if (typeof warning === 'string') {
warning = createWarningObject(warning, type, code, ctor, detail);
} else if (!(warning instanceof Error)) {
throw new ERR_INVALID_ARG_TYPE('warning', ['Error', 'string'], warning);
}
if (warning.name === 'DeprecationWarning') {
if (process.noDeprecation)
return;
if (process.throwDeprecation)
throw warning;
}
process.nextTick(doEmitWarning, warning);
}n/a
exit = function () {
/*
* this function will do nothing
*/
return;
}...
* <fileRemote|dirRemote> <commitMessage>
* will delete from github <fileRemote|dirRemote>
*/
local.github_crud.githubCrudContentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (err) {
process.exit(Boolean(err));
});
};
local.cliDict.get = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
...function getegid() { [native code] }n/a
function geteuid() { [native code] }n/a
function getgid() { [native code] }n/a
function getgroups() { [native code] }n/a
function getuid() { [native code] }n/a
function hasUncaughtExceptionCaptureCallback() {
return exceptionHandlerState.captureFn !== null;
}n/a
function hrtime(time) {
_hrtime(hrValues);
if (time !== undefined) {
if (!ArrayIsArray(time)) {
throw new ERR_INVALID_ARG_TYPE('time', 'Array', time);
}
if (time.length !== 2) {
throw new ERR_OUT_OF_RANGE('time', 2, time.length);
}
const sec = (hrValues[0] * 0x100000000 + hrValues[1]) - time[0];
const nsec = hrValues[2] - time[1];
const needsBorrow = nsec < 0;
return [needsBorrow ? sec - 1 : sec, needsBorrow ? nsec + 1e9 : nsec];
}
return [
hrValues[0] * 0x100000000 + hrValues[1],
hrValues[2]
];
}n/a
function initgroups(user, extraGroup) {
validateId(user, 'user');
validateId(extraGroup, 'extraGroup');
// Result is 0 on success, 1 if user is unknown, 2 if group is unknown.
const result = _initgroups(user, extraGroup);
if (result === 1) {
throw new ERR_UNKNOWN_CREDENTIAL('User', user);
} else if (result === 2) {
throw new ERR_UNKNOWN_CREDENTIAL('Group', extraGroup);
}
}n/a
function kill(pid, sig) {
let err;
// eslint-disable-next-line eqeqeq
if (pid != (pid | 0)) {
throw new ERR_INVALID_ARG_TYPE('pid', 'number', pid);
}
// Preserve null signal
if (sig === (sig | 0)) {
// XXX(joyeecheung): we have to use process._kill here because
// it's monkey-patched by tests.
err = process._kill(pid, sig);
} else {
sig = sig || 'SIGTERM';
if (constants[sig]) {
err = process._kill(pid, constants[sig]);
} else {
throw new ERR_UNKNOWN_SIGNAL(sig);
}
}
if (err)
throw errnoException(err, 'kill');
return true;
}...
stdio = ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'];
}
const chromeProcess = childProcess.spawn(
chromeExecutable,
chromeArguments,
{
// On non-windows platforms, `detached: false` makes child process a leader of a new
// process group, making it possible to kill child process tree with `.kill(-pid
)` command.
// @see https://nodejs.org/api/child_process.html#child_process_options_detached
detached: process.platform !== 'win32',
env,
stdio
}
);
...function memoryUsage() {
_memoryUsage(memValues);
return {
rss: memValues[0],
heapTotal: memValues[1],
heapUsed: memValues[2],
external: memValues[3],
arrayBuffers: memValues[4]
};
}n/a
function nextTick(callback) {
if (typeof callback !== 'function')
throw new ERR_INVALID_CALLBACK(callback);
if (process._exiting)
return;
let args;
switch (arguments.length) {
case 1: break;
case 2: args = [arguments[1]]; break;
case 3: args = [arguments[1], arguments[2]]; break;
case 4: args = [arguments[1], arguments[2], arguments[3]]; break;
default:
args = new Array(arguments.length - 1);
for (let i = 1; i < arguments.length; i++)
args[i - 1] = arguments[i];
}
if (queue.isEmpty())
setHasTickScheduled(true);
const asyncId = newAsyncId();
const triggerAsyncId = getDefaultTriggerAsyncId();
const tickObject = {
[async_id_symbol]: asyncId,
[trigger_async_id_symbol]: triggerAsyncId,
callback,
args
};
if (initHooksExist())
emitInit(asyncId, 'TickObject', triggerAsyncId, tickObject);
queue.push(tickObject);
}...
//
if (this.options.port != null) {
server.close(() => this.emit('close'));
return;
}
}
process.nextTick(emitClose, this);
}
/**
* See if a given request should be handled by this server instance.
*
* @param {http.IncomingMessage} req Request object to inspect
* @return {Boolean} `true` if the request is valid, else `false`
...function() {
process.stdin.resume();
return process.stdin;
}n/a
function reallyExit() { [native code] }n/a
function resourceUsage() {
_resourceUsage(resourceValues);
return {
userCPUTime: resourceValues[0],
systemCPUTime: resourceValues[1],
maxRSS: resourceValues[2],
sharedMemorySize: resourceValues[3],
unsharedDataSize: resourceValues[4],
unsharedStackSize: resourceValues[5],
minorPageFault: resourceValues[6],
majorPageFault: resourceValues[7],
swappedOut: resourceValues[8],
fsRead: resourceValues[9],
fsWrite: resourceValues[10],
ipcSent: resourceValues[11],
ipcReceived: resourceValues[12],
signalsCount: resourceValues[13],
voluntaryContextSwitches: resourceValues[14],
involuntaryContextSwitches: resourceValues[15]
};
}n/a
function(fn) {
const err = new ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE();
err.stack = err.stack + '\n' + '-'.repeat(40) + '\n' + domainRequireStack;
throw err;
}n/a
function(id) {
validateId(id, 'id');
// Result is 0 on success, 1 if credential is unknown.
const result = method(id);
if (result === 1) {
throw new ERR_UNKNOWN_CREDENTIAL(type, id);
}
}n/a
function(id) {
validateId(id, 'id');
// Result is 0 on success, 1 if credential is unknown.
const result = method(id);
if (result === 1) {
throw new ERR_UNKNOWN_CREDENTIAL(type, id);
}
}n/a
function(id) {
validateId(id, 'id');
// Result is 0 on success, 1 if credential is unknown.
const result = method(id);
if (result === 1) {
throw new ERR_UNKNOWN_CREDENTIAL(type, id);
}
}n/a
function setgroups(groups) {
if (!ArrayIsArray(groups)) {
throw new ERR_INVALID_ARG_TYPE('groups', 'Array', groups);
}
for (let i = 0; i < groups.length; i++) {
validateId(groups[i], `groups[${i}]`);
}
// Result is 0 on success. A positive integer indicates that the
// corresponding group was not found.
const result = _setgroups(groups);
if (result > 0) {
throw new ERR_UNKNOWN_CREDENTIAL('Group', groups[result - 1]);
}
}n/a
function(id) {
validateId(id, 'id');
// Result is 0 on success, 1 if credential is unknown.
const result = method(id);
if (result === 1) {
throw new ERR_UNKNOWN_CREDENTIAL(type, id);
}
}n/a
function wrappedUmask(mask) {
if (mask !== undefined) {
mask = parseFileMode(mask, 'mask');
}
return rawMethods.umask(mask);
}n/a
function uptime() { [native code] }n/a
function require(path) {
return mod.require(path);
}...
}).slice(0, 256).map(readExample);
// init moduleMain
local.tryCatchOnError(function () {
console.error("apidocCreate - requiring " + opt.dir + " ...");
moduleMain = {};
moduleMain = (
opt.moduleDict[opt.env.npm_package_name]
|| opt.require(opt.dir)
|| opt.require(
opt.dir + "/"
+ (opt.packageJson.bin)[Object.keys(opt.packageJson.bin)[0]]
) || {}
);
opt.circularSet.add(moduleMain);
console.error("apidocCreate - ... required " + opt.dir);
...function resolve(request, options) {
validateString(request, 'request');
return Module._resolveFilename(request, mod, false, options);
}...
let fs;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
...function ok(...args) {
innerOk(ok, args.length, ...args);
}...
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
...assertOrThrow = function (passed, msg) {
/*
* this function will throw err.<msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is a string, then leave as is
? msg
// else JSON.stringify msg
: JSON.stringify(msg, undefined, 4)
)
);
}...
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...cliRun = function (opt) {
/*
* this function will run cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
strDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " &quo......
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...coalesce = function (...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== null && arg !== undefined && arg !== "") {
break;
}
ii += 1;
}
return arg;
}...
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
...function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
}n/a
fsReadFileOrDefaultSync = function (pathname, type, dflt) {
/*
* this function will sync-read <pathname> with given <type> and <dflt>
*/
let fs;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
}...
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "
;")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
...fsRmrfSync = function (pathname) {
/*
* this function will sync "rm -rf" <pathname>
*/
let child_process;
// do nothing if module does not exist
try {
child_process = require("child_process");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
if (process.platform !== "win32") {
child_process.spawnSync("rm", [
"-rf", pathname
], {
stdio: [
"ignore", 1, 2
]
});
return;
}
try {
child_process.spawnSync("rd", [
"/s", "/q", pathname
], {
stdio: [
"ignore", 1, "ignore"
]
});
} catch (ignore) {}
}...
return "image/jpeg";
default:
return file;
}
}
};
const removeFolder = function (dir, onError) {
local.fsRmrfSync(dir);
onError();
};
removeFolder.sync = local.fsRmrfSync;
const removeRecursive = removeFolder;
let EventEmitter = require('events');
let URL = require('url');
// let WebSocket = require('ws');
...fsWriteFileWithMkdirpSync = function (pathname, data, msg) {
/*
* this function will sync write <data> to <pathname> with "mkdir -p"
*/
let fs;
let success;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
// try to write pathname
try {
fs.writeFileSync(pathname, data);
success = true;
} catch (ignore) {
// mkdir -p
fs.mkdirSync(require("path").dirname(pathname), {
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
}...
|| local.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
) {
onError(undefined, opt);
return;
}
// save apidoc.html
local.fsWriteFileWithMkdirpSync(
"tmp/build/apidoc.html",
local.apidocCreate(local.objectAssignDefault(opt, {
blacklistDict: local,
require: require2
})),
"wrote file apidoc - {{pathname}}"
);
...identity = function (val) {
/*
* this function will return <val>
*/
return val;
}...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...jslintAndPrint = function (code = "", file = "undefined", opt = {}) {
/*
* this function will jslint/csslint <code> and print any errors to stderr
*/
let ii;
let tmp;
if (!(opt && opt.gotoState)) {
local.jslintResult = {
gotoState: 0
};
}
opt = Object.assign(local.jslintResult, opt);
opt.gotoState += 1;
switch (opt.gotoState) {
// jslint - init
case 1:
// cleanup
opt.errList = [];
opt.errMsg = "";
// preserve lineno
if (opt.iiStart) {
opt.lineOffset |= 0;
ii = 0;
while (true) {
ii = code.indexOf("\n", ii);
if (ii === 0 || ii > opt.iiStart) {
break;
}
ii += 1;
opt.lineOffset += 1;
}
code = code.slice(opt.iiStart, opt.iiEnd || code.length);
}
switch (opt.fileType0) {
// de-embed-js - '\\n\\\n...\\n\\\n'
case ".\\n\\":
// rgx - remove \\n\\
code = code.replace((
/\\n\\$|\\(.)/gm
), function (ignore, match1) {
return match1 || "";
});
break;
// de-embed-js - '\n...\n'
case ".sh":
// rgx - convert '"'"' to '
code = code.replace((
/'"'"'/g
), "'");
break;
}
// init
opt = Object.assign(opt, {
".css": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".html": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".js": (
/^\/\*jslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".json": (
/^\s*?(?:\[|\{)/
),
".md": (
/(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".sh": (
/(^#\u0020jslint\u0020utility2:true$)/m
),
code0: code,
fileType: (
/\.\w+?$|$/m
).exec(file)[0]
});
// jslint - .json
if (opt.fileType === ".js" && opt[".json"].test(code)) {
opt.fileType = ".json";
}
try {
opt.conditionalPassed = opt[opt.fileType].exec(code);
} catch (ignore) {}
opt.utility2 = (
opt.conditionalPassed && opt.conditionalPassed[1]
) || opt.autofix;
if (
opt.conditional
&& (!opt.conditionalPassed || opt.coverage)
) {
break;
}
opt.gotoState = 10;
break;
// jslint - autofix
case 11:
code = local.jslintAutofix(code, file, opt);
local.jslintResult = opt;
break;
// jslint - csslint and jslint
case 12:
// restore lineOffset
code = "\n".repeat(opt.lineOffset | 0) + code;
switch (opt.fileType) {
case ".css":
// csslint
Object.assign(opt, local.CSSLint.verify(code));
// init errList
opt.errList = opt.messages.map(function (err) {
err.column = err.col;
err.message = (
err.type + " - " + err.rule.id + " - " + err.message
+ "\n " + err.rule.desc
);
return err;
});
break;
case ".html":
case ".md":
case ".sh":
break;
default:
// jslint - .js......
return;
}
// read file
local.fs.readFile(opt.file, "utf8", opt.gotoNext);
break;
case 2:
// jslint
local.jslint.jslintAndPrint(data, opt.file);
local.assertOrThrow(
!local.jslint.jslintResult.errMsg,
local.jslint.jslintResult.errMsg.replace((
/\u001b\[\d*m/g
), "")
);
// validate
...jslintAndPrintDir = function (dir, opt, onError) {
/*
* this function will jslint files in shallow <dir>
*/
let onParallel;
onParallel = local.onParallel(onError);
local.fs.readdirSync(dir).forEach(function (file) {
let timeStart;
file = local.path.resolve(file);
switch ((
/\.\w+?$|$/m
).exec(file)[0]) {
case ".css":
case ".html":
case ".js":
case ".json":
case ".md":
case ".sh":
if ((
/\b(?:assets\.app\.js|lock|min|raw|rollup)\b/
).test(file)) {
return;
}
onParallel.cnt += 1;
// jslint file
local.fs.readFile(file, "utf8", function (err, data) {
// handle err
local.assertOrThrow(!err, err);
timeStart = Date.now();
local.jslintAndPrint(data, file, opt);
console.error(
"jslint - " + (Date.now() - timeStart) + "ms " + file
);
onParallel();
});
break;
}
});
}...
});
// jslint process.cwd()
if (!local.env.npm_config_mode_library) {
local.child_process.spawn("node", [
"-e", (
"require("
+ JSON.stringify(__filename)
+ ").jslint.jslintAndPrintDir("
+ JSON.stringify(process.cwd())
+ ", {autofix:true,conditional:true}, process.exit);"
)
], {
env: Object.assign({}, local.env, {
npm_config_mode_library: "1"
}),
...jslintAutofix = function (code, file, opt) {
/*
* this function will jslint-autofix <code>
*/
let code0;
let code2;
let dataList;
let ignoreList;
let ii;
let rgx1;
let rgx2;
let tmp;
// autofix-all
if (opt.autofix) {
// autofix-all - normalize local-function
if (
globalThis.utility2
&& typeof globalThis.utility2.jslintAutofixLocalFunction
=== "function"
) {
code = globalThis.utility2.jslintAutofixLocalFunction(code, file);
}
// autofix-all - remove trailing-whitespace
code = code.replace((
/\u0020+$/gm
), "");
// autofix-all - remove leading-whitespace before )]}
code = code.replace((
/\n+?(\n\u0020*?[)\]}])/g
), "$1");
// autofix-all - normalize newlines to \n\n
code = code.replace((
/([^\n])\n{3}([^\n])/g
), "$1\n\n$2");
// autofix-all - normalize newlines to \n\n\n\n
code = code.replace((
/\n{5,}/g
), "\n\n\n\n");
// autofix-all - recurse <script>...</script>, <style>...</style>
code = code.replace((
/(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/\\n\\\n(?:^.*?\\n\\\n)*?)(';$|<\/script>\\n\\$|<\/style>\\n\\$)/gm
), function (ignore, match1, match2, ii) {
return local.jslintAndPrint(
code,
file + (
match2.indexOf("style") > -1
? ".<style>.css"
: ".<script>.js"
),
Object.assign({}, opt, {
fileType0: ".\\n\\",
iiEnd: ii + match1.length,
iiStart: ii,
gotoState: 0
})
) + match2;
});
}
switch (opt.autofix && opt.fileType) {
case ".css":
break;
case ".html":
// autofix-html - recurse <script>...</script>, <style>...</style>
code = code.replace((
/^(\/\*\u0020jslint\u0020utility2:true\u0020\*\/\n[\S\s]*?\n)(<\/(?:script|style)>)$/gm
), function (ignore, match1, match2, ii) {
return local.jslintAndPrint(
code,
file + (
match2.indexOf("style") >= 0
? ".<style>.css"
: ".<script>.js"
),
Object.assign({}, opt, {
fileType0: opt.fileType,
iiEnd: ii + match1.length,
iiStart: ii,
gotoState: 0
})
) + match2;
});
break;
case ".js":
case ".json":
// autofix-js - demux code to [code, ignoreList]
ignoreList = [];
code = code.replace((
/^\u0020*?\/\*\u0020jslint\u0020ignore:start\u0020\*\/$[\S\s]*?^\/\*\u0020jslint\u0020ignore:end\u0020\*\/$/gm
), function (match0) {
ignoreList.push(match0);
return "/* jslint ignore:start:end */";
});
// autofix-js - escape non-ascii
code = code.replace((
/[^\n\r\t\u0020-\u007e]/g
), function (match0) {
return "\\u" + (
"0000"
+ match0.charCodeAt(0).toString(16)
).slice(-4);
});
// autofix-js - demux code2 to [code2, ignoreList]
code2 = "";
dataList = [];
ii = 0;
rgx1 = (
/\\.|\/\*|\*\/|\/\/!!|\/\/|["'\/`]|$/gm
);
// parse rgx
// https://github.com/douglascrockford/JSLint/blob/557afd32bcaa35480d31a86f02d3a8c06a4e5b5c/jslin...n/a
jslintGetColumnLine = function (code, ii) {
/*
* this function will transform <code> and <ii> to {column, line, evidence}
*/
let column;
let evidence;
let line;
evidence = code.slice(0, ii).split("\n");
line = evidence.length - 1;
column = evidence[line].length;
evidence = evidence[line] + code.slice(ii, ii + 100).split("\n")[0];
return {
column,
evidence,
line
};
}n/a
jslintUtility2 = function (code, ignore, opt) {
/*
* this function will jslint <code> with utiity2-specific rules
*/
let code2;
let err;
let indent;
let previous;
// jslintUtility2 - all
if (opt.utility2) {
code2 = code;
// ignore start to end
code2 = code2.replace((
/^\/\*\u0020jslint\u0020ignore:start\u0020\*\/$[\S\s]+?^\/\*\u0020jslint\u0020ignore:end\u0020\*\/$/gm
), function (match0) {
// preserve lineno
return match0.replace((
/.+/g
), "");
});
// lint whitespace
code2.replace((
/^\u0020+?(?:\*|\/\/!!)|^\u0020+|[\r\t]/gm
), function (match0, ii) {
switch (match0.slice(-1)) {
case " ":
if (match0.length % 4 === 0) {
return "";
}
err = {
message: "non 4-space indent"
};
break;
case "\r":
err = {
message: "unexpected \\r"
};
break;
case "\t":
err = {
message: "unexpected \\t"
};
break;
default:
return "";
}
Object.assign(err, local.jslintGetColumnLine(code2, ii));
opt.errList.push({
column: err.column + 1,
evidence: JSON.stringify(err.evidence),
line: err.line + 1,
message: err.message
});
return "";
});
}
switch (opt.utility2 && opt.fileType) {
// jslintUtility2 - .css
case ".css":
// ignore comment
code2 = code2.replace((
/^\u0020*?\/\*[\S\s]*?\*\/\u0020*?$/gm
), function (match0) {
// preserve lineno
return match0.replace((
/.+/g
), "");
});
code2.replace((
/\S\u0020{2}|\u0020,|^\S.*?[,;{}]./gm
), function (match0, ii) {
switch (match0.slice(-2)) {
case " ":
err = {
colOffset: 2,
message: "unexpected multi-whitespace"
};
break;
case " ,":
err = {
colOffset: 1,
message: "unexpected whitespace before comma"
};
break;
default:
err = {
colOffset: match0.length,
message: "unexpected multiline-statement"
};
}
Object.assign(err, local.jslintGetColumnLine(code2, ii));
opt.errList.push({
column: err.column + err.colOffset,
evidence: JSON.stringify(err.evidence),
line: err.line + 1,
message: err.message
});
return "";
});
// validate line-sorted - css-selector
previous = "";
code2 = code2.replace((
/^.|[#.>]|[,}]$|\u0020\{$|\b\w/gm
), function (match0) {
switch (match0) {
case " ":
return match0;
case " {":
return "\u0001" + match0;
case "#":
return "\u0002" + match0;
case ",":
return "\u0000" + match0;
case ".":
return "\u0001" + match0;
case ">":
return "\u0003" + match0;
case "}":
return match0;
default:...n/a
jslint_export = function ( source = "", option_object = empty(),
global_array = []
) {
// hack-jslint - init lines_extra
line_ignore = undefined;
lines = (
Array.isArray(source)
? source
: source.split(
/\n|\r\n?/
)
);
lines_extra = lines.map(function () {
return {};
});
try {
warnings = [];
option = Object.assign(empty(), option_object);
anon = "anonymous";
block_stack = [];
declared_globals = empty();
directive_mode = true;
directives = [];
early_stop = true;
exports = empty();
froms = [];
fudge = (
option.fudge
? 1
: 0
);
functions = [];
global = {
id: "(global)",
body: true,
context: empty(),
from: 0,
level: 0,
line: 0,
live: [],
loop: 0,
switch: 0,
thru: 0
};
blockage = global;
functionage = global;
json_mode = false;
mega_mode = false;
module_mode = false;
next_token = global;
property = empty();
shebang = false;
stack = [];
tenure = undefined;
token = global;
token_nr = 0;
var_mode = undefined;
populate(standard, declared_globals, false);
populate(global_array, declared_globals, false);
Object.keys(option).forEach(function (name) {
if (option[name] === true) {
const allowed = allowed_option[name];
if (Array.isArray(allowed)) {
populate(allowed, declared_globals, false);
}
}
});
tokenize(source);
advance();
if (json_mode) {
tree = json_value();
advance("(end)");
} else {
// Because browsers encourage combining of script files, the first token might
// be a semicolon to defend against a missing semicolon in the preceding file.
if (option.browser) {
if (next_token.id === ";") {
advance(";");
}
} else {
// If we are not in a browser, then the file form of strict pragma may be used.
if (
next_token.value === "use strict"
) {
advance("(string)");
advance(";");
}
}
tree = statements();
advance("(end)");
functionage = global;
walk_statement(tree);
if (warnings.length === 0) {
uninitialized_and_unused();
if (!option.white) {
whitage();
}
}
}
if (!option.browser) {
directives.forEach(function (comment) {
if (comment.directive === "global") {
warn("missing_browser", comment);
}
});
}
early_stop = false;
} catch (e) {
// hack-jslint - early_stop
e.early_stop = true;
e.column = e.column || -1;
e.line = e.line || -1;
if (e.name !== "JSLintError") {
warnings.push(e);
}
}
// hack-jslint - autofix
warnings = warnings.filter(function (warning) {
let indent;
warning.source = warning.source || "";
warning.a = warning.a || warning.source.trim();
switch (option.autofix && warning.code) {
// expected_a_at_b_c: "Expected '{a}' at column {b}, not column {c}.",
case "expected_a_at_b_c":
// autofix indent - increment
indent = warning.b - warning.c;
if (indent >= 0) {
lines_extra[warning.line].source_autofixed = (...n/a
jsonStringifyOrdered = function (obj, replacer, space) {
/*
* this function will JSON.stringify <obj>,
* with object-keys sorted and circular-references removed
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax
*/
let circularSet;
let stringify;
let tmp;
stringify = function (obj) {
/*
* this function will recursively JSON.stringify obj,
* with object-keys sorted and circular-references removed
*/
// if obj is not an object or function,
// then JSON.stringify as normal
if (!(
obj
&& typeof obj === "object"
&& typeof obj.toJSON !== "function"
)) {
return JSON.stringify(obj);
}
// ignore circular-reference
if (circularSet.has(obj)) {
return;
}
circularSet.add(obj);
// if obj is an array, then recurse items
if (Array.isArray(obj)) {
tmp = "[" + obj.map(function (obj) {
// recurse
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
if (typeof tmp === "string") {
return JSON.stringify(key) + ":" + tmp;
}
}).filter(function (obj) {
return typeof obj === "string";
}).join(",") + "}";
circularSet.delete(obj);
return tmp;
};
circularSet = new Set();
return JSON.stringify((
(typeof obj === "object" && obj)
// recurse
? JSON.parse(stringify(obj))
: obj
), replacer, space);
}...
<!-- swgg-script-extra-end -->\n\
</body>\n\
</html>\n\
');
/* jslint ignore:end */
local.assetsDict[
"/assets.swgg.swagger.schema.json"
] = local.jsonStringifyOrdered(
local.objectAssignRecurse(
JSON.parse(local.assetsDict["/assets.swgg.json-schema.json"].replace((
/"\$ref":".*?#/g
), "\"$ref\":\"http://json-schema.org/draft-04/schema#")),
JSON.parse(local.assetsDict["/assets.swgg.schema.json"].replace((
/"\$ref":".*?#/g
), "\"$ref\":\"http://json-schema.org/draft-04/schema#")),
...nop = function () {
/*
* this function will do nothing
*/
return;
}...
// run shared js-env code - function
(function () {
let process;
let require;
// hack-jslint
local.nop(require);
globalThis.__coverageInclude__ = local.coalesce(
globalThis.__coverageInclude__,
{}
);
// mock builtins
process = local.process || {
cwd: function () {
...objectAssignDefault = function (tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...onErrorWithStack = function (onError) {
/*
* this function will wrap <onError> with wrapper preserving current-stack
*/
let onError2;
let stack;
stack = new Error().stack;
onError2 = function (err, data, meta) {
// append current-stack to err.stack
if (
err
&& typeof err.stack === "string"
&& err !== local.errorDefault
) {
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
}...
};
local.gotoNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.gotoNext,
* and append current-stack to any err
*/
opt.gotoNext = local.onErrorWithStack(function (err, data, meta) {
try {
opt.gotoState += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
...onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if cnt === 0 or err occurred, then call onError(err)
*/
let onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement cnt
onParallel.cnt -= 1;
// validate cnt
if (!(onParallel.cnt >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.cnt = " + onParallel.cnt
);
// ensure onError is run only once
} else if (onParallel.cnt < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure cnt <= 0
onParallel.cnt = -Math.abs(onParallel.cnt);
}
// call onError when isDone
if (onParallel.cnt <= 0) {
onError(err, data);
return;
}
onEach();
};
// init cnt
onParallel.cnt = 0;
// return callback
return onParallel;
}...
elem: opt.list[onParallel.ii],
ii: onParallel.ii,
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
...function Stream(opts) {
EE.call(this, opts);
}n/a
function Reporter(lines, ruleset, allow, ignore) {
"use strict";
/**
* List of messages being reported.
* @property messages
* @type String[]
*/
this.messages = [];
/**
* List of statistics being reported.
* @property stats
* @type String[]
*/
this.stats = [];
/**
* Lines of code being reported on. Used to provide contextual information
* for messages.
* @property lines
* @type String[]
*/
this.lines = lines;
/**
* Information about the rules. Used to determine whether an issue is an
* error or warning.
* @property ruleset
* @type Object
*/
this.ruleset = ruleset;
/**
* Lines with specific rule messages to leave out of the report.
* @property allow
* @type Object
*/
this.allow = allow;
if (!this.allow) {
this.allow = {};
}
/**
* Linesets not to include in the report.
* @property ignore
* @type [][]
*/
this.ignore = ignore;
if (!this.ignore) {
this.ignore = [];
}
}n/a
function(formatter) {
// formatters.push(formatter);
formatters[formatter.id] = formatter;
}n/a
function(rule) {
rules.push(rule);
rules[rule.id] = rule;
}n/a
function() {
rules = [];
}n/a
function(results, filename, formatId, options) {
var formatter = api.getFormatter(formatId),
result = null;
if (formatter) {
result = formatter.startFormat();
result += formatter.formatResults(results, filename, options || {});
result += formatter.endFormat();
}
return result;
}...
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
ws.protocol = protocol;
}
}
if (extensions[PerMessageDeflate.extensionName]) {
const params = extensions[PerMessageDeflate.extensionName].params;
const value = extension.format({
[PerMessageDeflate.extensionName]: [params]
});
headers.push(`Sec-WebSocket-Extensions: ${value}`);
ws._extensions = extensions;
}
//
...function(formatId) {
return formatters[formatId];
}n/a
function() {
return [].concat(rules).sort(function(a, b) {
return a.id > b.id ? 1 : 0;
});
}n/a
function() {
var ruleset = {},
i = 0,
len = rules.length;
while (i < len) {
ruleset[rules[i++].id] = 1; // by default, everything is a warning
}
return ruleset;
}n/a
function(formatId) {
return formatters.hasOwnProperty(formatId);
}n/a
function(text, ruleset) {
var i = 0,
reporter,
lines,
allow = {},
ignore = [],
report,
parser = new parserlib.css.Parser({
starHack: true,
ieFilters: true,
underscoreHack: true,
strict: false
});
// normalize line endings
lines = text.replace(/\n\r?/g, "$split$").split("$split$");
// find 'allow' comments
CSSLint.Util.forEach(lines, function (line, lineno) {
var allowLine = line && line.match(/\/\*[ \t]*csslint[ \t]+allow:[ \t]*([^\*]*)\*\//i),
allowRules = allowLine && allowLine[1],
allowRuleset = {};
if (allowRules) {
allowRules.toLowerCase().split(",").forEach(function(allowRule) {
allowRuleset[allowRule.trim()] = true;
});
if (Object.keys(allowRuleset).length > 0) {
allow[lineno + 1] = allowRuleset;
}
}
});
var ignoreStart = null,
ignoreEnd = null;
CSSLint.Util.forEach(lines, function (line, lineno) {
// Keep oldest, "unclosest" ignore:start
if (ignoreStart === null && line.match(/\/\*[ \t]*csslint[ \t]+ignore:start[ \t]*\*\//i)) {
ignoreStart = lineno;
}
if (line.match(/\/\*[ \t]*csslint[ \t]+ignore:end[ \t]*\*\//i)) {
ignoreEnd = lineno;
}
if (ignoreStart !== null && ignoreEnd !== null) {
ignore.push([ignoreStart, ignoreEnd]);
ignoreStart = ignoreEnd = null;
}
});
// Close remaining ignore block, if any
if (ignoreStart !== null) {
ignore.push([ignoreStart, lines.length]);
}
if (!ruleset) {
ruleset = api.getRuleset();
}
if (embeddedRuleset.test(text)) {
// defensively copy so that caller's version does not get modified
ruleset = clone(ruleset);
ruleset = applyEmbeddedRuleset(text, ruleset);
}
reporter = new Reporter(lines, ruleset, allow, ignore);
ruleset.errors = 2; // always report parsing errors as errors
for (i in ruleset) {
if (ruleset.hasOwnProperty(i) && ruleset[i]) {
if (rules[i]) {
rules[i].init(parser, reporter);
}
}
}
// capture most horrible error type
try {
parser.parse(text);
} catch (ex) {
reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {});
}
report = {
messages : reporter.messages,
stats : reporter.stats,
ruleset : reporter.ruleset,
allow : reporter.allow,
ignore : reporter.ignore
};
// sort by line numbers, rollups at the bottom
report.messages.sort(function (a, b) {
if (a.rollup && !b.rollup) {
return 1;
} else if (!a.rollup && b.rollup) {
return -1;
} else {
return a.line - b.line;
}
});
return report;
}n/a
function Reporter(lines, ruleset, allow, ignore) {
"use strict";
/**
* List of messages being reported.
* @property messages
* @type String[]
*/
this.messages = [];
/**
* List of statistics being reported.
* @property stats
* @type String[]
*/
this.stats = [];
/**
* Lines of code being reported on. Used to provide contextual information
* for messages.
* @property lines
* @type String[]
*/
this.lines = lines;
/**
* Information about the rules. Used to determine whether an issue is an
* error or warning.
* @property ruleset
* @type Object
*/
this.ruleset = ruleset;
/**
* Lines with specific rule messages to leave out of the report.
* @property allow
* @type Object
*/
this.allow = allow;
if (!this.allow) {
this.allow = {};
}
/**
* Linesets not to include in the report.
* @property ignore
* @type [][]
*/
this.ignore = ignore;
if (!this.ignore) {
this.ignore = [];
}
}n/a
function(message, line, col, rule) {
"use strict";
this.messages.push({
type : "error",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule || {}
});
}...
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
};
local.identity = function (val) {
/*
* this function will return <val>
*/
...function(message, line, col, rule) {
"use strict";
this.messages.push({
type : "info",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
}n/a
function(message, line, col, rule) {
"use strict";
// Check if rule violation should be allowed
if (this.allow.hasOwnProperty(line) && this.allow[line].hasOwnProperty(rule.id)) {
return;
}
var ignore = false;
CSSLint.Util.forEach(this.ignore, function (range) {
if (range[0] <= line && line <= range[1]) {
ignore = true;
}
});
if (ignore) {
return;
}
this.messages.push({
type : this.ruleset[rule.id] === 2 ? "error" : "warning",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
}n/a
function(message, rule) {
"use strict";
this.messages.push({
type : "error",
rollup : true,
message : message,
rule : rule
});
}n/a
function(message, rule) {
"use strict";
this.messages.push({
type : "warning",
rollup : true,
message : message,
rule : rule
});
}n/a
function(name, value) {
"use strict";
this.stats[name] = value;
}...
let onParallel;
if (local.isBrowser) {
onError(undefined, opt);
return;
}
onParallel = local.onParallel(onError);
onParallel.cnt += 1;
local.fs.stat(__filename, function (err, stat) {
// test default watchFile handling-behavior
onParallel.cnt += 1;
local.fs.utimes(__filename, stat.atime, new Date(), onParallel);
// test nop watchFile handling-behavior
onParallel.cnt += 1;
setTimeout(function () {
local.fs.utimes(__filename, stat.atime, stat.mtime, onParallel);
...function(message, line, col, rule) {
"use strict";
this.report(message, line, col, rule);
}...
options.source_map.add(
mapping.token.file,
mapping.line, mapping.col,
mapping.token.line, mapping.token.col,
!mapping.name && mapping.token.type == "name" ? mapping.token.value : mapping.name
);
} catch(ex) {
mapping.token.file != null && AST_Node.warn("Couldn't figure out
mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
file: mapping.token.file,
line: mapping.token.line,
col: mapping.token.col,
cline: mapping.line,
ccol: mapping.col,
name: mapping.name || ""
});
..._default = function () {
/*
* <file1> <file2> ...
* will jslint <file1> <file2> ... and print errors to stderr
*/
// jslint files
process.argv.slice(2).forEach(function (file) {
if (file[0] === "-") {
return;
}
local.jslintAndPrint(
local.fs.readFileSync(local.path.resolve(file), "utf8"),
file,
{
autofix: process.argv.indexOf("--autofix") >= 0,
conditional: process.argv.indexOf("--conditional") >= 0
}
);
});
// if err occurred, then exit with non-zero code
process.exit(Boolean(local.jslintResult.errList.length));
}...
local.cliDict._help();
return;
}
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
local.moduleDirname = function (module, pathList) {
/*
* this function will search <pathList> for <module>'s __dirname
*/
let result;
...dir = function () {
/*
* <dir>
* will jslint files in shallow <dir>
*/
local.jslintAndPrintDir(process.argv[3], {
autofix: process.argv.indexOf("--autofix") >= 0,
conditional: process.argv.indexOf("--conditional") >= 0
}, process.exit);
}n/a
function c
(e, n, r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i=
n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function(
e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n
.highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(!
a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i(
e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p
();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults
,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked."
;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0
)+"</pre>";throw h}}n/a
function r(e, t){this.options=t||c.defaults,this.links=
e,this.rules=n.normal,this.renderer=this.options.renderer||new i,this.renderer.options=
this.options;if(!this.links)throw new Error("Tokens array requires a `links` property."
);this.options.gfm?this.options.breaks?this.rules=n.breaks:this.rules=n.gfm:this
.options.pedantic&&(this.rules=n.pedantic)}n/a
function t(t){this.tokens=[],this.tokens.links={},this.options=t||c.
defaults,this.rules=e.normal,this.options.gfm&&(this.options.tables?this.rules=e
.tables:this.rules=e.gfm)}n/a
function s
(e){this.tokens=[],this.token=null,this.options=e||c.defaults,this.options.renderer=
this.options.renderer||new i,this.renderer=this.options.renderer,this.renderer.options=
this.options}n/a
function i(e){this.options=e||{}}n/a
function(e, t, n){var i=new r(t,n);return i.output(e)}n/a
function(e, n){var r=new t(n);return r.lex(e)}n/a
function(e){return l(c.defaults,e),c}n/a
function c
(e, n, r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i=
n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function(
e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n
.highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(!
a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i(
e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p
();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults
,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked."
;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0
)+"</pre>";throw h}}...
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
};
local.fsRmrfSync = function (pathname) {
...function(e, t, n){var r=new s(t,n);return r.parse
(e)}n/a
function(e){return l(c.defaults,e),c}n/a
function r(e, t){this.options=t||c.defaults,this.links=
e,this.rules=n.normal,this.renderer=this.options.renderer||new i,this.renderer.options=
this.options;if(!this.links)throw new Error("Tokens array requires a `links` property."
);this.options.gfm?this.options.breaks?this.rules=n.breaks:this.rules=n.gfm:this
.options.pedantic&&(this.rules=n.pedantic)}n/a
function(e, t, n){var i=new r(t,n);return i.output(e)}...
};n._inside=/(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/,n._href=/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/
,n.link=a(n.link)("inside",n._inside)("href",n._href)(),n.reflink=a(n.reflink)("inside"
,n._inside)(),n.normal=l({},n),n.pedantic=l({},n.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/
,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),n.gfm=l({},n.normal
,{escape:a(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del
:/^~~(?=\S)([\s\S]*?\S)~~/,text:a(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=
l({},n.gfm,{br:a(n.br)("{2,}","*")(),text:a(n.gfm.text)("{2,}","*")()}),r.rules=
n,r.output=function(e,t,n){var i=new r(t,n);return i.output(e)},r.prototype.output=
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
...function(e){if(!this.options.
mangle)return e;var t="",n=e.length,r=0,i;for(;r<n;r++)i=e.charCodeAt(r),Math.random
()>.5&&(i="x"+i.toString(16)),t+="&#"+i+";";return t}...
,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),n.gfm=l({},n.normal
,{escape:a(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del
:/^~~(?=\S)([\s\S]*?\S)~~/,text:a(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=
l({},n.gfm,{br:a(n.br)("{2,}","*")(),text:a(n.gfm.text)("{2,}","*")()}),r.rules=
n,r.output=function(e,t,n){var i=new r(t,n);return i.output(e)},r.prototype.output=
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring
(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
.test(s[0])&&(this.inLink=!1),e=e.substring(s[0].length),t+=this.options.sanitize?
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
...function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
.test(s[0])&&(this.inLink=!1),e=e.substring(s[0].length),t+=this.options.sanitize?
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t}...
};n._inside=/(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/,n._href=/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/
,n.link=a(n.link)("inside",n._inside)("href",n._href)(),n.reflink=a(n.reflink)("inside"
,n._inside)(),n.normal=l({},n),n.pedantic=l({},n.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/
,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),n.gfm=l({},n.normal
,{escape:a(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del
:/^~~(?=\S)([\s\S]*?\S)~~/,text:a(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=
l({},n.gfm,{br:a(n.br)("{2,}","*")(),text:a(n.gfm.text)("{2,}","*")()}),r.rules=
n,r.output=function(e,t,n){var i=new r(t,n);return i.output(e)},r.prototype.output=
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
...function(e, t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))}...
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
.test(s[0])&&(this.inLink=!1),e=e.substring(s[0].length),t+=this.options.sanitize?
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
...function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
).replace(/\.{3}/g,"\u2026"):e}...
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
).replace(/\.{3}/g,"\u2026"):e},r.prototype.mangle=function(e){if(!this.options.
...function t(t){this.tokens=[],this.tokens.links={},this.options=t||c.
defaults,this.rules=e.normal,this.options.gfm&&(this.options.tables?this.rules=e
.tables:this.rules=e.gfm)}n/a
function(e, n){var r=new t(n);return r.lex(e)}...
e,t){return t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?
String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring
(1)):""})}function a(e,t){return e=e.source,t=t||"",function n(r,i){return r?(i=
i.source||i,i=i.replace(/(^|[^\[])\^/g,"$1"),e=e.replace(r,i),n):new RegExp(e,t)
}}function f(){}function l(e){var t=1,n,r;for(;t<arguments.length;t++){n=arguments
[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}function c
(e,n,r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i=
n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function(
e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n
.highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(!
a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i(
e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p
();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults
,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked."
;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0
...function(e){return e=
e.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g
,"\n"),this.token(e,!0)}...
e,t){return t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?
String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring
(1)):""})}function a(e,t){return e=e.source,t=t||"",function n(r,i){return r?(i=
i.source||i,i=i.replace(/(^|[^\[])\^/g,"$1"),e=e.replace(r,i),n):new RegExp(e,t)
}}function f(){}function l(e){var t=1,n,r;for(;t<arguments.length;t++){n=arguments
[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}function c
(e,n,r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i=
n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function(
e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n
.highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(!
a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i(
e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p
();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults
,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked."
;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0
...function(t, n, r){var t=t.replace(/^ +$/gm
,""),i,s,o,u,a,f,l,c,h;while(t){if(o=this.rules.newline.exec(t))t=t.substring(o[0
].length),o[0].length>1&&this.tokens.push({type:"space"});if(o=this.rules.code.exec
(t)){t=t.substring(o[0].length),o=o[0].replace(/^ {4}/gm,""),this.tokens.push({type
:"code",text:this.options.pedantic?o:o.replace(/\n+$/,"")});continue}if(o=this.rules
.fences.exec(t)){t=t.substring(o[0].length),this.tokens.push({type:"code",lang:o
[2],text:o[3]||""});continue}if(o=this.rules.heading.exec(t)){t=t.substring(o[0]
.length),this.tokens.push({type:"heading",depth:o[1].length,text:o[2]});continue}
if(n&&(o=this.rules.nptable.exec(t))){t=t.substring(o[0].length),f={type:"table"
,header:o[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:o[2].replace(/^ *|\| *$/g
,"").split(/ *\| */),cells:o[3].replace(/\n$/,"").split("\n")};for(c=0;c<f.align
.length;c++)/^ *-+: *$/.test(f.align[c])?f.align[c]="right":/^ *:-+: *$/.test(f.
align[c])?f.align[c]="center":/^ *:-+ *$/.test(f.align[c])?f.align[c]="left":f.align
[c]=null;for(c=0;c<f.cells.length;c++)f.cells[c]=f.cells[c].split(/ *\| */);this
.tokens.push(f);continue}if(o=this.rules.lheading.exec(t)){t=t.substring(o[0].length
),this.tokens.push({type:"heading",depth:o[2]==="="?1:2,text:o[1]});continue}if(
o=this.rules.hr.exec(t)){t=t.substring(o[0].length),this.tokens.push({type:"hr"}
);continue}if(o=this.rules.blockquote.exec(t)){t=t.substring(o[0].length),this.tokens
.push({type:"blockquote_start"}),o=o[0].replace(/^ *> ?/gm,""),this.token(o,n,!0
),this.tokens.push({type:"blockquote_end"});continue}if(o=this.rules.list.exec(t
)){t=t.substring(o[0].length),u=o[2],this.tokens.push({type:"list_start",ordered
:u.length>1}),o=o[0].match(this.rules.item),i=!1,h=o.length,c=0;for(;c<h;c++)f=o
[c],l=f.length,f=f.replace(/^ *([*+-]|\d+\.) +/,""),~f.indexOf("\n ")&&(l-=f.length
,f=this.options.pedantic?f.replace(/^ {1,4}/gm,""):f.replace(new RegExp("^ {1,"+
l+"}","gm"),"")),this.options.smartLists&&c!==h-1&&(a=e.bullet.exec(o[c+1])[0],u!==
a&&!(u.length>1&&a.length>1)&&(t=o.slice(c+1).join("\n")+t,c=h-1)),s=i||/\n\n(?!\s*$)/
.test(f),c!==h-1&&(i=f.charAt(f.length-1)==="\n",s||(s=i)),this.tokens.push({type
:s?"loose_item_start":"list_item_start"}),this.token(f,!1,r),this.tokens.push({type
:"list_item_end"});this.tokens.push({type:"list_end"});continue}if(o=this.rules.
html.exec(t)){t=t.substring(o[0].length),this.tokens.push({type:this.options.sanitize?"paragraph"
:"html",pre:!this.options.sanitizer&&(o[1]==="pre"||o[1]==="script"||o[1]==="style"
),text:o[0]});continue}if(!r&&n&&(o=this.rules.def.exec(t))){t=t.substring(o[0].
length),this.tokens.links[o[1].toLowerCase()]={href:o[2],title:o[3]};continue}if(
n&&(o=this.rules.table.exec(t))){t=t.substring(o[0].length),f={type:"table",header
:o[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:o[2].replace(/^ *|\| *$/g
,"").split(/ *\| */),cells:o[3].replace(/(?: *\| *)?\n$/,"").split("\n")};for(c=0
;c<f.align.length;c++)/^ *-+: *$/.test(f.align[c])?f.align[c]="right":/^ *:-+: *$/
.test(f.align[c])?f.align[c]="center":/^ *:-+ *$/.test(f.align[c])?f.align[c]="left"
:f.align[c]=null;for(c=0;c<f.cells.length;c++)f.cells[c]=f.cells[c].replace(/^ *\| *| *\| *$/g
,"").split(/ *\| */);this.tokens.push(f);continue}if(n&&(o=this.rules.paragraph.
exec(t))){t=t.substring(o[0].length),this.tokens.push({type:"paragraph",text:o[1
].charAt(o[1].length-1)==="\n"?o[1].slice(0,-1):o[1]});c......
throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol);
case Tokens.NAMESPACE_SYM:
token = tokenStream.LT(1);
this._namespace(false);
throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol);
default:
tokenStream.get(); //get the last token
this._unexpectedToken(tokenStream.token());
}
}
}
} catch (ex) {
if (ex instanceof SyntaxError && !this.options.strict) {
this.fire({
type: "error",
...function s
(e){this.tokens=[],this.token=null,this.options=e||c.defaults,this.options.renderer=
this.options.renderer||new i,this.renderer=this.options.renderer,this.renderer.options=
this.options}n/a
function(e, t, n){var r=new s(t,n);return r.parse
(e)}...
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
};
local.fsRmrfSync = function (pathname) {
...function(){return this.token=this.tokens.pop()}...
};
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp.eat = function(type) {
if (this.type === type) {
this.next();
return true
} else {
return false
}
};
// Tests whether parsed token is a contextual keyword.
...function(e){this.inline=new r(e.links,this.options,this.renderer
),this.tokens=e.reverse();var t="";while(this.next())t+=this.tok();return t}...
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
};
local.fsRmrfSync = function (pathname) {
...function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)}...
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start"
;:
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
function(e){return l(c.defaults,e),c},c.defaults={gfm:!0,tables:!0,breaks:!1,pedantic
:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,
...function( ){return this.tokens[this.tokens.length-1]||0}...
//try to read character set
this._charset();
this._skipCruft();
//try to read imports - may be more than one
while (tokenStream.peek() === Tokens.IMPORT_SYM) {
this._import();
this._skipCruft();
}
//try to read namespaces - may be more than one
while (tokenStream.peek() === Tokens.NAMESPACE_SYM) {
this._namespace();
...function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}}...
e,t,n){if(this.options.sanitize){try{var r=decodeURIComponent(u(e)).replace(/[^\w:]/g
,"").toLowerCase()}catch(i){return""}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:"
;
)===0||r.indexOf("data:")===0)return""}var s='<a href="'+e+'"';return t&
;&(s+=' title="'+
t+'"'),s+=">"+n+"</a>",s},i.prototype.image=function(e,t,n){var r='<img src=&
quot;'+e+'" alt="'+
n+'"';return t&&(r+=' title="'+t+'"'),r+=this.options.xhtml?"/>"
;:">",r},i.prototype
.text=function(e){return e},s.parse=function(e,t,n){var r=new s(t,n);return r.parse
(e)},s.prototype.parse=function(e){this.inline=new r(e.links,this.options,this.renderer
),this.tokens=e.reverse();var t="";while(this.next())t+=this.tok();return t
},s.prototype
.next=function(){return this.token=this.tokens.pop()},s.prototype.peek=function(
){return this.tokens[this.tokens.length-1]||0},s.prototype.parseText=function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
...function i(e){this.options=e||{}}n/a
function(e){return"<blockquote>\n"+e+"</blockquote>\n"}...
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while
(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
...function(){return this.options.xhtml?"<br/>":"<br>"}...
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
...function( e, t, n){if(this.options.highlight){var r=this.options.highlight(e,t);r!=null&&r!==
e&&(n=!0,e=r)}return t?'<pre><code class="'+this.options.langPrefix+o(t,!0)+'">'+
(n?e:o(e,!0))+"\n</code></pre>\n":"<pre><code>"+(n?e:o(e,!0))+"\n</code></pre>"}...
),this.tokens=e.reverse();var t="";while(this.next())t+=this.tok();return t},s.prototype
.next=function(){return this.token=this.tokens.pop()},s.prototype.peek=function(
){return this.tokens[this.tokens.length-1]||0},s.prototype.parseText=function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"
;table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
...function(e){return"<code>"+
e+"</code>"}...
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
...function(e){return"<del>"+e+"</del>"}...
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
...function(e){return"<em>"+e+"</em>"}...
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
...function(e, t, n){return"<h"+
t+' id="'+this.options.headerPrefix+n.toLowerCase().replace(/[^\w]+/g,"-")+'">'+
e+"</h"+t+">\n"}n/a
function(){return this.options.xhtml?"<hr/>\n":"<hr>\n"
}...
.text=function(e){return e},s.parse=function(e,t,n){var r=new s(t,n);return r.parse
(e)},s.prototype.parse=function(e){this.inline=new r(e.links,this.options,this.renderer
),this.tokens=e.reverse();var t="";while(this.next())t+=this.tok();return t},s.prototype
.next=function(){return this.token=this.tokens.pop()},s.prototype.peek=function(
){return this.tokens[this.tokens.length-1]||0},s.prototype.parseText=function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading"
;:return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
...function(e){return e}...
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph
"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
function(e){return l(c.defaults,e),c},c.defaults={gfm:!0,tables:!0,breaks:!1,pedantic
:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,
langPrefix:"lang-",smartypants:!1,headerPrefix:"",renderer:new i,xhtml:!1},c.Parser=
s,c.parser=s.parse,c.Renderer=i,c.Lexer=t,c.lexer=t.lex,c.InlineLexer=r,c.inlineLexer=
r.output,c.parse=c,typeof module!="undefined"&&typeof exports=="object"?module.exports=
...function(e, t, n){var r='<img src="'+e+'" alt="'+
n+'"';return t&&(r+=' title="'+t+'"'),r+=this.options.xhtml?"/>":">",r}...
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
).replace(/\.{3}/g,"\u2026"):e},r.prototype.mangle=function(e){if(!this.options.
mangle)return e;var t="",n=e.length,r=0,i;for(;r<n;r++)i=e.charCodeAt(r),Math.random
()>.5&&(i="x"+i.toString(16)),t+="&#"+i+";";return t},i.prototype.code=function(
e,t,n){if(this.options.highlight){var r=this.options.highlight(e,t);r!=null&&r!==
...function( e, t, n){if(this.options.sanitize){try{var r=decodeURIComponent(u(e)).replace(/[^\w:]/g
,"").toLowerCase()}catch(i){return""}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:"
)===0||r.indexOf("data:")===0)return""}var s='<a href="'+e+'"';return t&&(s+=' title="'+
t+'"'),s+=">"+n+"</a>",s}...
,{escape:a(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del
:/^~~(?=\S)([\s\S]*?\S)~~/,text:a(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=
l({},n.gfm,{br:a(n.br)("{2,}","*")(),text:a(n.gfm.text)("{2,}","*")()}),r.rules=
n,r.output=function(e,t,n){var i=new r(t,n);return i.output(e)},r.prototype.output=
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
.test(s[0])&&(this.inLink=!1),e=e.substring(s[0].length),t+=this.options.sanitize?
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
...function(e, t){var n=t?"ol":"ul";return"<"+n+">\n"+e+"</"+n+">\n"
}...
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start
"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
...function(e){return"<li>"+e+"</li>\n"}...
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start"
;:
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
function(e){return l(c.defaults,e),c},c.defaults={gfm:!0,tables:!0,breaks:!1,pedantic
:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,
...function(e){return"<p>"+e+"</p>\n"}...
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text"
;:
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
function(e){return l(c.defaults,e),c},c.defaults={gfm:!0,tables:!0,breaks:!1,pedantic
:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,
langPrefix:"lang-",smartypants:!1,headerPrefix:"",renderer:new i,xhtml:!1},c.Parser=
s,c.parser=s.parse,c.Renderer=i,c.Lexer=t,c.lexer=t.lex,c.InlineLexer=r,c.inlineLexer=
r.output,c.parse=c,typeof module!="undefined"&&typeof exports=="object"?module.exports=
c:typeof define=="function"&&define.amd?define(function(){return c}):this.marked=
...function(e){return"<strong>"+e+"</strong>"}...
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
...function(e, t){return"<table>\n<thead>\n"+
e+"</thead>\n"+"<tbody>\n"+t+"</tbody>\n"+"</table>\n"}...
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start
"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
...function(e, t){var n=t.header?"th"
:"td",r=t.align?"<"+n+' style="text-align:'+t.align+'">':"<"+n+">";return r+e+"</"+
n+">\n"}...
){return this.tokens[this.tokens.length-1]||0},s.prototype.parseText=function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
...function( e){return"<tr>\n"+e+"</tr>\n"}...
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
...function(e){return e}...
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
).replace(/\.{3}/g,"\u2026"):e},r.prototype.mangle=function(e){if(!this.options.
...function ok(...args) {
innerOk(ok, args.length, ...args);
}...
key = '0123456789abcdef0123456789abcdef';
mode = undefined;
local.cryptoAesXxxCbcRawEncrypt({
data,
key,
mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data,
key,
mode
}, console.log);
});
*/
...assertOrThrow = function (passed, msg) {
/*
* this function will throw err.<msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is a string, then leave as is
? msg
// else JSON.stringify msg
: JSON.stringify(msg, undefined, 4)
)
);
}...
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...cliRun = function (opt) {
/*
* this function will run cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
strDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " &quo......
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...coalesce = function (...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== null && arg !== undefined && arg !== "") {
break;
}
ii += 1;
}
return arg;
}...
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(str);
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertOrThrow(undefined, new Error(
...function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
}n/a
fsReadFileOrDefaultSync = function (pathname, type, dflt) {
/*
* this function will sync-read <pathname> with given <type> and <dflt>
*/
let fs;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return dflt;
}
pathname = require("path").resolve(pathname);
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
}...
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "
;")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
...fsRmrfSync = function (pathname) {
/*
* this function will sync "rm -rf" <pathname>
*/
let child_process;
// do nothing if module does not exist
try {
child_process = require("child_process");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
if (process.platform !== "win32") {
child_process.spawnSync("rm", [
"-rf", pathname
], {
stdio: [
"ignore", 1, 2
]
});
return;
}
try {
child_process.spawnSync("rd", [
"/s", "/q", pathname
], {
stdio: [
"ignore", 1, "ignore"
]
});
} catch (ignore) {}
}...
return "image/jpeg";
default:
return file;
}
}
};
const removeFolder = function (dir, onError) {
local.fsRmrfSync(dir);
onError();
};
removeFolder.sync = local.fsRmrfSync;
const removeRecursive = removeFolder;
let EventEmitter = require('events');
let URL = require('url');
// let WebSocket = require('ws');
...fsWriteFileWithMkdirpSync = function (pathname, data, msg) {
/*
* this function will sync write <data> to <pathname> with "mkdir -p"
*/
let fs;
let success;
// do nothing if module does not exist
try {
fs = require("fs");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
// try to write pathname
try {
fs.writeFileSync(pathname, data);
success = true;
} catch (ignore) {
// mkdir -p
fs.mkdirSync(require("path").dirname(pathname), {
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
success = true;
}
if (success && msg) {
console.error(msg.replace("{{pathname}}", pathname));
}
return success;
}...
|| local.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
) {
onError(undefined, opt);
return;
}
// save apidoc.html
local.fsWriteFileWithMkdirpSync(
"tmp/build/apidoc.html",
local.apidocCreate(local.objectAssignDefault(opt, {
blacklistDict: local,
require: require2
})),
"wrote file apidoc - {{pathname}}"
);
...identity = function (val) {
/*
* this function will return <val>
*/
return val;
}...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...nop = function () {
/*
* this function will do nothing
*/
return;
}...
// run shared js-env code - function
(function () {
let process;
let require;
// hack-jslint
local.nop(require);
globalThis.__coverageInclude__ = local.coalesce(
globalThis.__coverageInclude__,
{}
);
// mock builtins
process = local.process || {
cwd: function () {
...objectAssignDefault = function (tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...puppeteerLaunch = function () { [native code] }...
local.timeoutDefault,
new Error(
"timeout - " + local.timeoutDefault + " ms - "
+ testName
)
);
// create puppeteer browser
local.puppeteerLaunch({
args: [
"--headless",
"--incognito",
"--no-sandbox",
"--remote-debugging-port=0"
],
dumpio: !opt.modeSilent,
...function Stream(opts) {
EE.call(this, opts);
}n/a
class Accessibility {
/**
* @param {!Puppeteer.CDPSession} client
*/
constructor(client) {
this._client = client;
}
/**
* @param {{interestingOnly?: boolean, root?: ?Puppeteer.ElementHandle}=} options
* @return {!Promise<!SerializedAXNode>}
*/
async snapshot(options = {}) {
const {
interestingOnly = true,
root = null,
} = options;
const {nodes} = await this._client.send('Accessibility.getFullAXTree');
let backendNodeId = null;
if (root) {
const {node} = await this._client.send('DOM.describeNode', {objectId: root._remoteObject.objectId});
backendNodeId = node.backendNodeId;
}
const defaultRoot = AXNode.createTree(nodes);
let needle = defaultRoot;
if (backendNodeId) {
needle = defaultRoot.find(node => node._payload.backendDOMNodeId === backendNodeId);
if (!needle)
return null;
}
if (!interestingOnly)
return serializeTree(needle)[0];
/** @type {!Set<!AXNode>} */
const interestingNodes = new Set();
collectInterestingNodes(interestingNodes, defaultRoot, false);
if (!interestingNodes.has(needle))
return null;
return serializeTree(needle, interestingNodes)[0];
}
}n/a
class Browser extends EventEmitter {
/**
* @param {!Puppeteer.Connection} connection
* @param {!Array<string>} contextIds
* @param {boolean} ignoreHTTPSErrors
* @param {?Puppeteer.Viewport} defaultViewport
* @param {?Puppeteer.ChildProcess} process
* @param {function()=} closeCallback
*/
static async create(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback) {
const browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback);
await connection.send('Target.setDiscoverTargets', {discover: true});
return browser;
}
/**
* @param {!Puppeteer.Connection} connection
* @param {!Array<string>} contextIds
* @param {boolean} ignoreHTTPSErrors
* @param {?Puppeteer.Viewport} defaultViewport
* @param {?Puppeteer.ChildProcess} process
* @param {(function():Promise)=} closeCallback
*/
constructor(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback) {
super();
this._ignoreHTTPSErrors = ignoreHTTPSErrors;
this._defaultViewport = defaultViewport;
this._process = process;
this._screenshotTaskQueue = new TaskQueue();
this._connection = connection;
this._closeCallback = closeCallback || new Function();
this._defaultContext = new BrowserContext(this._connection, this, null);
/** @type {Map<string, BrowserContext>} */
this._contexts = new Map();
for (const contextId of contextIds)
this._contexts.set(contextId, new BrowserContext(this._connection, this, contextId));
/** @type {Map<string, Target>} */
this._targets = new Map();
this._connection.on(Events.Connection.Disconnected, () => this.emit(Events.Browser.Disconnected));
this._connection.on('Target.targetCreated', this._targetCreated.bind(this));
this._connection.on('Target.targetDestroyed', this._targetDestroyed.bind(this));
this._connection.on('Target.targetInfoChanged', this._targetInfoChanged.bind(this));
}
/**
* @return {?Puppeteer.ChildProcess}
*/
process() {
return this._process;
}
/**
* @return {!Promise<!BrowserContext>}
*/
async createIncognitoBrowserContext() {
const {browserContextId} = await this._connection.send('Target.createBrowserContext');
const context = new BrowserContext(this._connection, this, browserContextId);
this._contexts.set(browserContextId, context);
return context;
}
/**
* @return {!Array<!BrowserContext>}
*/
browserContexts() {
return [this._defaultContext, ...Array.from(this._contexts.values())];
}
/**
* @return {!BrowserContext}
*/
defaultBrowserContext() {
return this._defaultContext;
}
/**
* @param {?string} contextId
*/
async _disposeContext(contextId) {
await this._connection.send('Target.disposeBrowserContext', {browserContextId: contextId || undefined});
this._contexts.delete(contextId);
}
/**
* @param {!Protocol.Target.targetCreatedPayload} event
*/
async _targetCreated(event) {
const targetInfo = event.targetInfo;
const {browserContextId} = targetInfo;
const context = (browserContextId && this._contexts.has(browserContextId)) ? this._contexts.get(browserContextId) : this._defaultContext
;
const target = new Target(targetInfo, context, () => this._connection.createSession(targetInfo), this._ignoreHTTPSErrors, this
._defaultViewport, this._screenshotTaskQueue);
assert(!this._targets.has(event.targetInfo.targetId), 'Target should not exist before targetCreated');
this._targets.set(event.targetInfo.targetId, target);
if (await target._initializedPromise) {
this.emit(Events.Browser.TargetCreated, target);
context.emit(Events.BrowserContext.TargetCreated, target);
}
}
/**
* @param {{targetId: string}} event
*/
async _targetDestroyed(event) {
const target = this._targets.get(e...n/a
class BrowserContext extends EventEmitter {
/**
* @param {!Puppeteer.Connection} connection
* @param {!Browser} browser
* @param {?string} contextId
*/
constructor(connection, browser, contextId) {
super();
this._connection = connection;
this._browser = browser;
this._id = contextId;
}
/**
* @return {!Array<!Target>} target
*/
targets() {
return this._browser.targets().filter(target => target.browserContext() === this);
}
/**
* @param {function(!Target):boolean} predicate
* @param {{timeout?: number}=} options
* @return {!Promise<!Target>}
*/
waitForTarget(predicate, options) {
return this._browser.waitForTarget(target => target.browserContext() === this && predicate(target), options);
}
/**
* @return {!Promise<!Array<!Puppeteer.Page>>}
*/
async pages() {
const pages = await Promise.all(
this.targets()
.filter(target => target.type() === 'page')
.map(target => target.page())
);
return pages.filter(page => !!page);
}
/**
* @return {boolean}
*/
isIncognito() {
return !!this._id;
}
/**
* @param {string} origin
* @param {!Array<string>} permissions
*/
async overridePermissions(origin, permissions) {
const webPermissionToProtocol = new Map([
['geolocation', 'geolocation'],
['midi', 'midi'],
['notifications', 'notifications'],
['push', 'push'],
['camera', 'videoCapture'],
['microphone', 'audioCapture'],
['background-sync', 'backgroundSync'],
['ambient-light-sensor', 'sensors'],
['accelerometer', 'sensors'],
['gyroscope', 'sensors'],
['magnetometer', 'sensors'],
['accessibility-events', 'accessibilityEvents'],
['clipboard-read', 'clipboardRead'],
['clipboard-write', 'clipboardWrite'],
['payment-handler', 'paymentHandler'],
// chrome-specific permissions we have.
['midi-sysex', 'midiSysex'],
]);
permissions = permissions.map(permission => {
const protocolPermission = webPermissionToProtocol.get(permission);
if (!protocolPermission)
throw new Error('Unknown permission: ' + permission);
return protocolPermission;
});
await this._connection.send('Browser.grantPermissions', {origin, browserContextId: this._id || undefined, permissions});
}
async clearPermissionOverrides() {
await this._connection.send('Browser.resetPermissions', {browserContextId: this._id || undefined});
}
/**
* @return {!Promise<!Puppeteer.Page>}
*/
newPage() {
return this._browser._createPageInContext(this._id);
}
/**
* @return {!Browser}
*/
browser() {
return this._browser;
}
async close() {
assert(this._id, 'Non-incognito profiles cannot be closed!');
await this._browser._disposeContext(this._id);
}
}n/a
class CDPSession extends EventEmitter {
/**
* @param {!Connection} connection
* @param {string} targetType
* @param {string} sessionId
*/
constructor(connection, targetType, sessionId) {
super();
/** @type {!Map<number, {resolve: function, reject: function, error: !Error, method: string}>}*/
this._callbacks = new Map();
this._connection = connection;
this._targetType = targetType;
this._sessionId = sessionId;
}
/**
* @param {string} method
* @param {!Object=} params
* @return {!Promise<?Object>}
*/
send(method, params = {}) {
if (!this._connection)
return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the ${this._targetType} has been
closed.`));
const id = this._connection._rawSend({sessionId: this._sessionId, method, params});
return new Promise((resolve, reject) => {
this._callbacks.set(id, {resolve, reject, error: new Error(), method});
});
}
/**
* @param {{id?: number, method: string, params: Object, error: {message: string, data: any}, result?: *}} object
*/
_onMessage(object) {
if (object.id && this._callbacks.has(object.id)) {
const callback = this._callbacks.get(object.id);
this._callbacks.delete(object.id);
if (object.error)
callback.reject(createProtocolError(callback.error, callback.method, object));
else
callback.resolve(object.result);
} else {
assert(!object.id);
this.emit(object.method, object.params);
}
}
async detach() {
if (!this._connection)
throw new Error(`Session already detached. Most likely the ${this._targetType} has been closed.`);
await this._connection.send('Target.detachFromTarget', {sessionId: this._sessionId});
}
_onClosed() {
for (const callback of this._callbacks.values())
callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));
this._callbacks.clear();
this._connection = null;
this.emit(Events.CDPSession.Disconnected);
}
}n/a
class ConsoleMessage {
/**
* @param {string} type
* @param {string} text
* @param {!Array<!Puppeteer.JSHandle>} args
* @param {ConsoleMessage.Location} location
*/
constructor(type, text, args, location = {}) {
this._type = type;
this._text = text;
this._args = args;
this._location = location;
}
/**
* @return {string}
*/
type() {
return this._type;
}
/**
* @return {string}
*/
text() {
return this._text;
}
/**
* @return {!Array<!Puppeteer.JSHandle>}
*/
args() {
return this._args;
}
/**
* @return {Object}
*/
location() {
return this._location;
}
}n/a
class Coverage {
/**
* @param {!Puppeteer.CDPSession} client
*/
constructor(client) {
this._jsCoverage = new JSCoverage(client);
this._cssCoverage = new CSSCoverage(client);
}
/**
* @param {!{resetOnNavigation?: boolean, reportAnonymousScripts?: boolean}} options
*/
async startJSCoverage(options) {
return await this._jsCoverage.start(options);
}
/**
* @return {!Promise<!Array<!CoverageEntry>>}
*/
async stopJSCoverage() {
return await this._jsCoverage.stop();
}
/**
* @param {{resetOnNavigation?: boolean}=} options
*/
async startCSSCoverage(options) {
return await this._cssCoverage.start(options);
}
/**
* @return {!Promise<!Array<!CoverageEntry>>}
*/
async stopCSSCoverage() {
return await this._cssCoverage.stop();
}
}n/a
class Dialog {
/**
* @param {!Puppeteer.CDPSession} client
* @param {string} type
* @param {string} message
* @param {(string|undefined)} defaultValue
*/
constructor(client, type, message, defaultValue = '') {
this._client = client;
this._type = type;
this._message = message;
this._handled = false;
this._defaultValue = defaultValue;
}
/**
* @return {string}
*/
type() {
return this._type;
}
/**
* @return {string}
*/
message() {
return this._message;
}
/**
* @return {string}
*/
defaultValue() {
return this._defaultValue;
}
/**
* @param {string=} promptText
*/
async accept(promptText) {
assert(!this._handled, 'Cannot accept dialog which is already handled!');
this._handled = true;
await this._client.send('Page.handleJavaScriptDialog', {
accept: true,
promptText: promptText
});
}
async dismiss() {
assert(!this._handled, 'Cannot dismiss dialog which is already handled!');
this._handled = true;
await this._client.send('Page.handleJavaScriptDialog', {
accept: false
});
}
}n/a
class ElementHandle extends JSHandle {
/**
* @param {!Puppeteer.ExecutionContext} context
* @param {!Puppeteer.CDPSession} client
* @param {!Protocol.Runtime.RemoteObject} remoteObject
* @param {!Puppeteer.Page} page
* @param {!Puppeteer.FrameManager} frameManager
*/
constructor(context, client, remoteObject, page, frameManager) {
super(context, client, remoteObject);
this._client = client;
this._remoteObject = remoteObject;
this._page = page;
this._frameManager = frameManager;
this._disposed = false;
}
/**
* @override
* @return {?ElementHandle}
*/
asElement() {
return this;
}
/**
* @return {!Promise<?Puppeteer.Frame>}
*/
async contentFrame() {
const nodeInfo = await this._client.send('DOM.describeNode', {
objectId: this._remoteObject.objectId
});
if (typeof nodeInfo.node.frameId !== 'string')
return null;
return this._frameManager.frame(nodeInfo.node.frameId);
}
async _scrollIntoViewIfNeeded() {
const error = await this.executionContext().evaluate(async(element, pageJavascriptEnabled) => {
if (!element.isConnected)
return 'Node is detached from document';
if (element.nodeType !== Node.ELEMENT_NODE)
return 'Node is not of type HTMLElement';
// force-scroll if page's javascript is disabled.
if (!pageJavascriptEnabled) {
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});
return false;
}
const visibleRatio = await new Promise(resolve => {
const observer = new IntersectionObserver(entries => {
resolve(entries[0].intersectionRatio);
observer.disconnect();
});
observer.observe(element);
});
if (visibleRatio !== 1.0)
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});
return false;
}, this, this._page._javascriptEnabled);
if (error)
throw new Error(error);
}
/**
* @return {!Promise<!{x: number, y: number}>}
*/
async _clickablePoint() {
const [result, layoutMetrics] = await Promise.all([
this._client.send('DOM.getContentQuads', {
objectId: this._remoteObject.objectId
}).catch(debugError),
this._client.send('Page.getLayoutMetrics'),
]);
if (!result || !result.quads.length)
throw new Error('Node is either not visible or not an HTMLElement');
// Filter out quads that have too small area to click into.
const {clientWidth, clientHeight} = layoutMetrics.layoutViewport;
const quads = result.quads.map(quad => this._fromProtocolQuad(quad)).map(quad => this._intersectQuadWithViewport(quad, clientWidth
, clientHeight)).filter(quad => computeQuadArea(quad) > 1);
if (!quads.length)
throw new Error('Node is either not visible or not an HTMLElement');
// Return the middle point of the first quad.
const quad = quads[0];
let x = 0;
let y = 0;
for (const point of quad) {
x += point.x;
y += point.y;
}
return {
x: x / 4,
y: y / 4
};
}
/**
* @return {!Promise<void|Protocol.DOM.getBoxModelReturnValue>}
*/
_getBoxModel() {
return this._client.send('DOM.getBoxModel', {
objectId: this._remoteObject.objectId
}).catch(error => debugError(error));
}
/**
* @param {!Array<number>} quad
* @return {!Array<{x: number, y: number}>}
*/
_fromProtocolQuad(quad) {
return [
{x: quad[0], y: quad[1]},
{x: quad[2], y: quad[3]},
{x: quad[4], y: quad[5]},
{x: quad[6], y: quad[7]}
];
}
/**
* @param {!Array<{x: number, y: number}>} quad
* @param {number} width
* @param {number} height
* @return {!Array<{x: number, y: number}>}
*/
_intersectQuadWithViewport(quad,...n/a
class ExecutionContext {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Protocol.Runtime.ExecutionContextDescription} contextPayload
* @param {?Puppeteer.DOMWorld} world
*/
constructor(client, contextPayload, world) {
this._client = client;
this._world = world;
this._contextId = contextPayload.id;
}
/**
* @return {?Puppeteer.Frame}
*/
frame() {
return this._world ? this._world.frame() : null;
}
/**
* @param {Function|string} pageFunction
* @param {...*} args
* @return {!Promise<*>}
*/
async evaluate(pageFunction, ...args) {
return await this._evaluateInternal(true /* returnByValue */, pageFunction, ...args);
}
/**
* @param {Function|string} pageFunction
* @param {...*} args
* @return {!Promise<!JSHandle>}
*/
async evaluateHandle(pageFunction, ...args) {
return this._evaluateInternal(false /* returnByValue */, pageFunction, ...args);
}
/**
* @param {boolean} returnByValue
* @param {Function|string} pageFunction
* @param {...*} args
* @return {!Promise<*>}
*/
async _evaluateInternal(returnByValue, pageFunction, ...args) {
const suffix = `//# sourceURL=${EVALUATION_SCRIPT_URL}`;
if (helper.isString(pageFunction)) {
const contextId = this._contextId;
const expression = /** @type {string} */ (pageFunction);
const expressionWithSourceUrl = SOURCE_URL_REGEX.test(expression) ? expression : expression + '\n' + suffix;
const {exceptionDetails, result: remoteObject} = await this._client.send('Runtime.evaluate', {
expression: expressionWithSourceUrl,
contextId,
returnByValue,
awaitPromise: true,
userGesture: true
}).catch(rewriteError);
if (exceptionDetails)
throw new Error('Evaluation failed: ' + helper.getExceptionMessage(exceptionDetails));
return returnByValue ? helper.valueFromRemoteObject(remoteObject) : createJSHandle(this, remoteObject);
}
if (typeof pageFunction !== 'function')
throw new Error(`Expected to get |string| or |function| as the first argument, but got "${pageFunction}" instead.`);
let functionText = pageFunction.toString();
// hack-coverage - un-instrument
functionText = functionText.replace((/\b__cov_.*?\+\+/g), "0");
try {
new Function('(' + functionText + ')');
} catch (e1) {
// This means we might have a function shorthand. Try another
// time prefixing 'function '.
if (functionText.startsWith('async '))
functionText = 'async function ' + functionText.substring('async '.length);
else
functionText = 'function ' + functionText;
try {
new Function('(' + functionText + ')');
} catch (e2) {
// We tried hard to serialize, but there's a weird beast here.
throw new Error('Passed function is not well-serializable!');
}
}
let callFunctionOnPromise;
try {
callFunctionOnPromise = this._client.send('Runtime.callFunctionOn', {
functionDeclaration: functionText + '\n' + suffix + '\n',
executionContextId: this._contextId,
arguments: args.map(convertArgument.bind(this)),
returnByValue,
awaitPromise: true,
userGesture: true
});
} catch (err) {
if (err instanceof TypeError && err.message.startsWith('Converting circular structure to JSON'))
err.message += ' Are you passing a nested JSHandle?';
throw err;
}
const { exceptionDetails, result: remoteObject } = await callFunctionOnPromise.catch(rewriteError);
if (exceptionDetails)
throw new Error('Evaluation failed: ' + helper.getExceptionMessage(exceptionDetails));
return returnByValue ? helper.valueFromRemoteObject(remoteObject) : crea...n/a
class FileChooser {
/**
* @param {Puppeteer.CDPSession} client
* @param {!Protocol.Page.fileChooserOpenedPayload} event
*/
constructor(client, event) {
this._client = client;
this._multiple = event.mode !== 'selectSingle';
this._handled = false;
}
/**
* @return {boolean}
*/
isMultiple() {
return this._multiple;
}
/**
* @param {!Array<string>} filePaths
* @return {!Promise}
*/
async accept(filePaths) {
assert(!this._handled, 'Cannot accept FileChooser which is already handled!');
this._handled = true;
const files = filePaths.map(filePath => path.resolve(filePath));
await this._client.send('Page.handleFileChooser', {
action: 'accept',
files,
});
}
/**
* @return {!Promise}
*/
async cancel() {
assert(!this._handled, 'Cannot cancel FileChooser which is already handled!');
this._handled = true;
await this._client.send('Page.handleFileChooser', {
action: 'cancel',
});
}
}n/a
class Frame {
/**
* @param {!FrameManager} frameManager
* @param {!Puppeteer.CDPSession} client
* @param {?Frame} parentFrame
* @param {string} frameId
*/
constructor(frameManager, client, parentFrame, frameId) {
this._frameManager = frameManager;
this._client = client;
this._parentFrame = parentFrame;
this._url = '';
this._id = frameId;
this._detached = false;
this._loaderId = '';
/** @type {!Set<string>} */
this._lifecycleEvents = new Set();
/** @type {!DOMWorld} */
this._mainWorld = new DOMWorld(frameManager, this, frameManager._timeoutSettings);
/** @type {!DOMWorld} */
this._secondaryWorld = new DOMWorld(frameManager, this, frameManager._timeoutSettings);
/** @type {!Set<!Frame>} */
this._childFrames = new Set();
if (this._parentFrame)
this._parentFrame._childFrames.add(this);
}
/**
* @param {string} url
* @param {!{referer?: string, timeout?: number, waitUntil?: string|!Array<string>}=} options
* @return {!Promise<?Puppeteer.Response>}
*/
async goto(url, options) {
return await this._frameManager.navigateFrame(this, url, options);
}
/**
* @param {!{timeout?: number, waitUntil?: string|!Array<string>}=} options
* @return {!Promise<?Puppeteer.Response>}
*/
async waitForNavigation(options) {
return await this._frameManager.waitForFrameNavigation(this, options);
}
/**
* @return {!Promise<!ExecutionContext>}
*/
executionContext() {
return this._mainWorld.executionContext();
}
/**
* @param {Function|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<!Puppeteer.JSHandle>}
*/
async evaluateHandle(pageFunction, ...args) {
return this._mainWorld.evaluateHandle(pageFunction, ...args);
}
/**
* @param {Function|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<*>}
*/
async evaluate(pageFunction, ...args) {
return this._mainWorld.evaluate(pageFunction, ...args);
}
/**
* @param {string} selector
* @return {!Promise<?Puppeteer.ElementHandle>}
*/
async $(selector) {
return this._mainWorld.$(selector);
}
/**
* @param {string} expression
* @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
*/
async $x(expression) {
return this._mainWorld.$x(expression);
}
/**
* @param {string} selector
* @param {Function|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<(!Object|undefined)>}
*/
async $eval(selector, pageFunction, ...args) {
return this._mainWorld.$eval(selector, pageFunction, ...args);
}
/**
* @param {string} selector
* @param {Function|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<(!Object|undefined)>}
*/
async $$eval(selector, pageFunction, ...args) {
return this._mainWorld.$$eval(selector, pageFunction, ...args);
}
/**
* @param {string} selector
* @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
*/
async $$(selector) {
return this._mainWorld.$$(selector);
}
/**
* @return {!Promise<String>}
*/
async content() {
return this._secondaryWorld.content();
}
/**
* @param {string} html
* @param {!{timeout?: number, waitUntil?: string|!Array<string>}=} options
*/
async setContent(html, options = {}) {
return this._secondaryWorld.setContent(html, options);
}
/**
* @return {string}
*/
name() {
return this._name || '';
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {?Frame}
*/
parentFrame() {
return this._parentFrame;
}
/**
* @return {!Array.<!Frame>}
*/
childFrames() {
return Array.from(this._childFrames);
}
/**
* @return {boolean}
*/
isDetached() {
return this._detached;
}
/**
* @param {!{url?: string,...n/a
class JSHandle {
/**
* @param {!Puppeteer.ExecutionContext} context
* @param {!Puppeteer.CDPSession} client
* @param {!Protocol.Runtime.RemoteObject} remoteObject
*/
constructor(context, client, remoteObject) {
this._context = context;
this._client = client;
this._remoteObject = remoteObject;
this._disposed = false;
}
/**
* @return {!Puppeteer.ExecutionContext}
*/
executionContext() {
return this._context;
}
/**
* @param {string} propertyName
* @return {!Promise<?JSHandle>}
*/
async getProperty(propertyName) {
const objectHandle = await this._context.evaluateHandle((object, propertyName) => {
const result = {__proto__: null};
result[propertyName] = object[propertyName];
return result;
}, this, propertyName);
const properties = await objectHandle.getProperties();
const result = properties.get(propertyName) || null;
await objectHandle.dispose();
return result;
}
/**
* @return {!Promise<!Map<string, !JSHandle>>}
*/
async getProperties() {
const response = await this._client.send('Runtime.getProperties', {
objectId: this._remoteObject.objectId,
ownProperties: true
});
const result = new Map();
for (const property of response.result) {
if (!property.enumerable)
continue;
result.set(property.name, createJSHandle(this._context, property.value));
}
return result;
}
/**
* @return {!Promise<?Object>}
*/
async jsonValue() {
if (this._remoteObject.objectId) {
const response = await this._client.send('Runtime.callFunctionOn', {
functionDeclaration: 'function() { return this; }',
objectId: this._remoteObject.objectId,
returnByValue: true,
awaitPromise: true,
});
return helper.valueFromRemoteObject(response.result);
}
return helper.valueFromRemoteObject(this._remoteObject);
}
/**
* @return {?Puppeteer.ElementHandle}
*/
asElement() {
return null;
}
async dispose() {
if (this._disposed)
return;
this._disposed = true;
await helper.releaseObject(this._client, this._remoteObject);
}
/**
* @override
* @return {string}
*/
toString() {
if (this._remoteObject.objectId) {
const type = this._remoteObject.subtype || this._remoteObject.type;
return 'JSHandle@' + type;
}
return 'JSHandle:' + helper.valueFromRemoteObject(this._remoteObject);
}
}n/a
class Keyboard {
/**
* @param {!Puppeteer.CDPSession} client
*/
constructor(client) {
this._client = client;
this._modifiers = 0;
this._pressedKeys = new Set();
}
/**
* @param {string} key
* @param {{text?: string}=} options
*/
async down(key, options = { text: undefined }) {
const description = this._keyDescriptionForString(key);
const autoRepeat = this._pressedKeys.has(description.code);
this._pressedKeys.add(description.code);
this._modifiers |= this._modifierBit(description.key);
const text = options.text === undefined ? description.text : options.text;
await this._client.send('Input.dispatchKeyEvent', {
type: text ? 'keyDown' : 'rawKeyDown',
modifiers: this._modifiers,
windowsVirtualKeyCode: description.keyCode,
code: description.code,
key: description.key,
text: text,
unmodifiedText: text,
autoRepeat,
location: description.location,
isKeypad: description.location === 3
});
}
/**
* @param {string} key
* @return {number}
*/
_modifierBit(key) {
if (key === 'Alt')
return 1;
if (key === 'Control')
return 2;
if (key === 'Meta')
return 4;
if (key === 'Shift')
return 8;
return 0;
}
/**
* @param {string} keyString
* @return {KeyDescription}
*/
_keyDescriptionForString(keyString) {
const shift = this._modifiers & 8;
const description = {
key: '',
keyCode: 0,
code: '',
text: '',
location: 0
};
const definition = keyDefinitions[keyString];
assert(definition, `Unknown key: "${keyString}"`);
if (definition.key)
description.key = definition.key;
if (shift && definition.shiftKey)
description.key = definition.shiftKey;
if (definition.keyCode)
description.keyCode = definition.keyCode;
if (shift && definition.shiftKeyCode)
description.keyCode = definition.shiftKeyCode;
if (definition.code)
description.code = definition.code;
if (definition.location)
description.location = definition.location;
if (description.key.length === 1)
description.text = description.key;
if (definition.text)
description.text = definition.text;
if (shift && definition.shiftText)
description.text = definition.shiftText;
// if any modifiers besides shift are pressed, no text should be sent
if (this._modifiers & ~8)
description.text = '';
return description;
}
/**
* @param {string} key
*/
async up(key) {
const description = this._keyDescriptionForString(key);
this._modifiers &= ~this._modifierBit(description.key);
this._pressedKeys.delete(description.code);
await this._client.send('Input.dispatchKeyEvent', {
type: 'keyUp',
modifiers: this._modifiers,
key: description.key,
windowsVirtualKeyCode: description.keyCode,
code: description.code,
location: description.location
});
}
/**
* @param {string} char
*/
async sendCharacter(char) {
await this._client.send('Input.insertText', {text: char});
}
/**
* @param {string} text
* @param {{delay: (number|undefined)}=} options
*/
async type(text, options) {
let delay = 0;
if (options && options.delay)
delay = options.delay;
for (const char of text) {
if (keyDefinitions[char])
await this.press(char, {delay});
else
await this.sendCharacter(char);
if (delay)
await new Promise(f => setTimeout(f, delay));
}
}
/**
* @param {string} key
* @param {!{delay?: number, text?: string}=} options
*/
async press(key, options = {}) {
const {delay = null} = options;
await this.down(key, options);
if (delay !== null)
await new Promise(f => se...n/a
class Mouse {
/**
* @param {Puppeteer.CDPSession} client
* @param {!Keyboard} keyboard
*/
constructor(client, keyboard) {
this._client = client;
this._keyboard = keyboard;
this._x = 0;
this._y = 0;
/** @type {'none'|'left'|'right'|'middle'} */
this._button = 'none';
}
/**
* @param {number} x
* @param {number} y
* @param {!{steps?: number}=} options
*/
async move(x, y, options = {}) {
const {steps = 1} = options;
const fromX = this._x, fromY = this._y;
this._x = x;
this._y = y;
for (let i = 1; i <= steps; i++) {
await this._client.send('Input.dispatchMouseEvent', {
type: 'mouseMoved',
button: this._button,
x: fromX + (this._x - fromX) * (i / steps),
y: fromY + (this._y - fromY) * (i / steps),
modifiers: this._keyboard._modifiers
});
}
}
/**
* @param {number} x
* @param {number} y
* @param {!{delay?: number, button?: "left"|"right"|"middle", clickCount?: number}=} options
*/
async click(x, y, options = {}) {
const {delay = null} = options;
if (delay !== null) {
await Promise.all([
this.move(x, y),
this.down(options),
]);
await new Promise(f => setTimeout(f, delay));
await this.up(options);
} else {
await Promise.all([
this.move(x, y),
this.down(options),
this.up(options),
]);
}
}
/**
* @param {!{button?: "left"|"right"|"middle", clickCount?: number}=} options
*/
async down(options = {}) {
const {button = 'left', clickCount = 1} = options;
this._button = button;
await this._client.send('Input.dispatchMouseEvent', {
type: 'mousePressed',
button,
x: this._x,
y: this._y,
modifiers: this._keyboard._modifiers,
clickCount
});
}
/**
* @param {!{button?: "left"|"right"|"middle", clickCount?: number}=} options
*/
async up(options = {}) {
const {button = 'left', clickCount = 1} = options;
this._button = 'none';
await this._client.send('Input.dispatchMouseEvent', {
type: 'mouseReleased',
button,
x: this._x,
y: this._y,
modifiers: this._keyboard._modifiers,
clickCount
});
}
}n/a
class Page extends EventEmitter {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.Target} target
* @param {boolean} ignoreHTTPSErrors
* @param {?Puppeteer.Viewport} defaultViewport
* @param {!Puppeteer.TaskQueue} screenshotTaskQueue
* @return {!Promise<!Page>}
*/
static async create(client, target, ignoreHTTPSErrors, defaultViewport, screenshotTaskQueue) {
const page = new Page(client, target, ignoreHTTPSErrors, screenshotTaskQueue);
await page._initialize();
if (defaultViewport)
await page.setViewport(defaultViewport);
return page;
}
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.Target} target
* @param {boolean} ignoreHTTPSErrors
* @param {!Puppeteer.TaskQueue} screenshotTaskQueue
*/
constructor(client, target, ignoreHTTPSErrors, screenshotTaskQueue) {
super();
this._closed = false;
this._client = client;
this._target = target;
this._keyboard = new Keyboard(client);
this._mouse = new Mouse(client, this._keyboard);
this._timeoutSettings = new TimeoutSettings();
this._touchscreen = new Touchscreen(client, this._keyboard);
this._accessibility = new Accessibility(client);
/** @type {!FrameManager} */
this._frameManager = new FrameManager(client, this, ignoreHTTPSErrors, this._timeoutSettings);
this._emulationManager = new EmulationManager(client);
this._tracing = new Tracing(client);
/** @type {!Map<string, Function>} */
this._pageBindings = new Map();
this._coverage = new Coverage(client);
this._javascriptEnabled = true;
/** @type {?Puppeteer.Viewport} */
this._viewport = null;
this._screenshotTaskQueue = screenshotTaskQueue;
/** @type {!Map<string, Worker>} */
this._workers = new Map();
client.on('Target.attachedToTarget', event => {
if (event.targetInfo.type !== 'worker') {
// If we don't detach from service workers, they will never die.
client.send('Target.detachFromTarget', {
sessionId: event.sessionId
}).catch(debugError);
return;
}
const session = Connection.fromSession(client).session(event.sessionId);
const worker = new Worker(session, event.targetInfo.url, this._addConsoleMessage.bind(this), this._handleException.bind(this
));
this._workers.set(event.sessionId, worker);
this.emit(Events.Page.WorkerCreated, worker);
});
client.on('Target.detachedFromTarget', event => {
const worker = this._workers.get(event.sessionId);
if (!worker)
return;
this.emit(Events.Page.WorkerDestroyed, worker);
this._workers.delete(event.sessionId);
});
this._frameManager.on(Events.FrameManager.FrameAttached, event => this.emit(Events.Page.FrameAttached, event));
this._frameManager.on(Events.FrameManager.FrameDetached, event => this.emit(Events.Page.FrameDetached, event));
this._frameManager.on(Events.FrameManager.FrameNavigated, event => this.emit(Events.Page.FrameNavigated, event));
const networkManager = this._frameManager.networkManager();
networkManager.on(Events.NetworkManager.Request, event => this.emit(Events.Page.Request, event));
networkManager.on(Events.NetworkManager.Response, event => this.emit(Events.Page.Response, event));
networkManager.on(Events.NetworkManager.RequestFailed, event => this.emit(Events.Page.RequestFailed, event));
networkManager.on(Events.NetworkManager.RequestFinished, event => this.emit(Events.Page.RequestFinished, event));
this._fileChooserInterceptionIsDisabled = false;
this._fileChooserInterceptors = new Set();
client.on('Page.domContentEventFired', event => this.emit(Events.Page.DOMContentLoaded));
client.on('Page.loadEventFired', event => this.emit(Events.Page.Load));
client.on('Runtime.consoleAPICalled', event => this._onConsoleAPI(event));
client.on(&apos...n/a
class {
/**
* @param {string} projectRoot
* @param {string} preferredRevision
* @param {boolean} isPuppeteerCore
*/
constructor(projectRoot, preferredRevision, isPuppeteerCore) {
this._projectRoot = projectRoot;
this._launcher = new Launcher(projectRoot, preferredRevision, isPuppeteerCore);
}
/**
* @param {!(Launcher.LaunchOptions & Launcher.ChromeArgOptions & Launcher.BrowserOptions)=} options
* @return {!Promise<!Puppeteer.Browser>}
*/
launch(options) {
return this._launcher.launch(options);
}
/**
* @param {!(Launcher.BrowserOptions & {browserWSEndpoint?: string, browserURL?: string, transport?: !Puppeteer.ConnectionTransport
})} options
* @return {!Promise<!Puppeteer.Browser>}
*/
connect(options) {
return this._launcher.connect(options);
}
/**
* @return {string}
*/
executablePath() {
return this._launcher.executablePath();
}
/**
* @return {Object}
*/
get devices() {
return DeviceDescriptors;
}
/**
* @return {Object}
*/
get errors() {
return Errors;
}
/**
* @param {!Launcher.ChromeArgOptions=} options
* @return {!Array<string>}
*/
defaultArgs(options) {
return this._launcher.defaultArgs(options);
}
/**
* @param {!BrowserFetcher.Options=} options
* @return {!BrowserFetcher}
*/
createBrowserFetcher(options) {
return new BrowserFetcher(this._projectRoot, options);
}
}n/a
class Request {
/**
* @param {!Puppeteer.CDPSession} client
* @param {?Puppeteer.Frame} frame
* @param {string} interceptionId
* @param {boolean} allowInterception
* @param {!Protocol.Network.requestWillBeSentPayload} event
* @param {!Array<!Request>} redirectChain
*/
constructor(client, frame, interceptionId, allowInterception, event, redirectChain) {
this._client = client;
this._requestId = event.requestId;
this._isNavigationRequest = event.requestId === event.loaderId && event.type === 'Document';
this._interceptionId = interceptionId;
this._allowInterception = allowInterception;
this._interceptionHandled = false;
this._response = null;
this._failureText = null;
this._url = event.request.url;
this._resourceType = event.type.toLowerCase();
this._method = event.request.method;
this._postData = event.request.postData;
this._headers = {};
this._frame = frame;
this._redirectChain = redirectChain;
for (const key of Object.keys(event.request.headers))
this._headers[key.toLowerCase()] = event.request.headers[key];
this._fromMemoryCache = false;
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {string}
*/
resourceType() {
return this._resourceType;
}
/**
* @return {string}
*/
method() {
return this._method;
}
/**
* @return {string|undefined}
*/
postData() {
return this._postData;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?Response}
*/
response() {
return this._response;
}
/**
* @return {?Puppeteer.Frame}
*/
frame() {
return this._frame;
}
/**
* @return {boolean}
*/
isNavigationRequest() {
return this._isNavigationRequest;
}
/**
* @return {!Array<!Request>}
*/
redirectChain() {
return this._redirectChain.slice();
}
/**
* @return {?{errorText: string}}
*/
failure() {
if (!this._failureText)
return null;
return {
errorText: this._failureText
};
}
/**
* @param {!{url?: string, method?:string, postData?: string, headers?: !Object}} overrides
*/
async continue(overrides = {}) {
// Request interception is not supported for data: urls.
if (this._url.startsWith('data:'))
return;
assert(this._allowInterception, 'Request Interception is not enabled!');
assert(!this._interceptionHandled, 'Request is already handled!');
const {
url,
method,
postData,
headers
} = overrides;
this._interceptionHandled = true;
await this._client.send('Fetch.continueRequest', {
requestId: this._interceptionId,
url,
method,
postData,
headers: headers ? headersArray(headers) : undefined,
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {!{status: number, headers: Object, contentType: string, body: (string|Buffer)}} response
*/
async respond(response) {
// Mocking responses for dataURL requests is not currently supported.
if (this._url.startsWith('data:'))
return;
assert(this._allowInterception, 'Request Interception is not enabled!');
assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @
type {?Buffer} */(response.body || null);
/** @type {!Object<string, string>} */
const responseHeaders = {};
if (response.headers) {
for (const header of Object.keys(response.headers))
responseHeaders[header.toLowerCase()] = response.headers[header];
}...n/a
class Response {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Request} request
* @param {!Protocol.Network.Response} responsePayload
*/
constructor(client, request, responsePayload) {
this._client = client;
this._request = request;
this._contentPromise = null;
this._bodyLoadedPromise = new Promise(fulfill => {
this._bodyLoadedPromiseFulfill = fulfill;
});
this._remoteAddress = {
ip: responsePayload.remoteIPAddress,
port: responsePayload.remotePort,
};
this._status = responsePayload.status;
this._statusText = responsePayload.statusText;
this._url = request.url();
this._fromDiskCache = !!responsePayload.fromDiskCache;
this._fromServiceWorker = !!responsePayload.fromServiceWorker;
this._headers = {};
for (const key of Object.keys(responsePayload.headers))
this._headers[key.toLowerCase()] = responsePayload.headers[key];
this._securityDetails = responsePayload.securityDetails ? new SecurityDetails(responsePayload.securityDetails) : null;
}
/**
* @return {{ip: string, port: number}}
*/
remoteAddress() {
return this._remoteAddress;
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {boolean}
*/
ok() {
return this._status === 0 || (this._status >= 200 && this._status <= 299);
}
/**
* @return {number}
*/
status() {
return this._status;
}
/**
* @return {string}
*/
statusText() {
return this._statusText;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?SecurityDetails}
*/
securityDetails() {
return this._securityDetails;
}
/**
* @return {!Promise<!Buffer>}
*/
buffer() {
if (!this._contentPromise) {
this._contentPromise = this._bodyLoadedPromise.then(async error => {
if (error)
throw error;
const response = await this._client.send('Network.getResponseBody', {
requestId: this._request._requestId
});
return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');
});
}
return this._contentPromise;
}
/**
* @return {!Promise<string>}
*/
async text() {
const content = await this.buffer();
return content.toString('utf8');
}
/**
* @return {!Promise<!Object>}
*/
async json() {
const content = await this.text();
return JSON.parse(content);
}
/**
* @return {!Request}
*/
request() {
return this._request;
}
/**
* @return {boolean}
*/
fromCache() {
return this._fromDiskCache || this._request._fromMemoryCache;
}
/**
* @return {boolean}
*/
fromServiceWorker() {
return this._fromServiceWorker;
}
/**
* @return {?Puppeteer.Frame}
*/
frame() {
return this._request.frame();
}
}n/a
class SecurityDetails {
/**
* @param {!Protocol.Network.SecurityDetails} securityPayload
*/
constructor(securityPayload) {
this._subjectName = securityPayload['subjectName'];
this._issuer = securityPayload['issuer'];
this._validFrom = securityPayload['validFrom'];
this._validTo = securityPayload['validTo'];
this._protocol = securityPayload['protocol'];
}
/**
* @return {string}
*/
subjectName() {
return this._subjectName;
}
/**
* @return {string}
*/
issuer() {
return this._issuer;
}
/**
* @return {number}
*/
validFrom() {
return this._validFrom;
}
/**
* @return {number}
*/
validTo() {
return this._validTo;
}
/**
* @return {string}
*/
protocol() {
return this._protocol;
}
}n/a
class Target {
/**
* @param {!Protocol.Target.TargetInfo} targetInfo
* @param {!Puppeteer.BrowserContext} browserContext
* @param {!function():!Promise<!Puppeteer.CDPSession>} sessionFactory
* @param {boolean} ignoreHTTPSErrors
* @param {?Puppeteer.Viewport} defaultViewport
* @param {!Puppeteer.TaskQueue} screenshotTaskQueue
*/
constructor(targetInfo, browserContext, sessionFactory, ignoreHTTPSErrors, defaultViewport, screenshotTaskQueue) {
this._targetInfo = targetInfo;
this._browserContext = browserContext;
this._targetId = targetInfo.targetId;
this._sessionFactory = sessionFactory;
this._ignoreHTTPSErrors = ignoreHTTPSErrors;
this._defaultViewport = defaultViewport;
this._screenshotTaskQueue = screenshotTaskQueue;
/** @type {?Promise<!Puppeteer.Page>} */
this._pagePromise = null;
/** @type {?Promise<!Worker>} */
this._workerPromise = null;
this._initializedPromise = new Promise(fulfill => this._initializedCallback = fulfill).then(async success => {
if (!success)
return false;
const opener = this.opener();
if (!opener || !opener._pagePromise || this.type() !== 'page')
return true;
const openerPage = await opener._pagePromise;
if (!openerPage.listenerCount(Events.Page.Popup))
return true;
const popupPage = await this.page();
openerPage.emit(Events.Page.Popup, popupPage);
return true;
});
this._isClosedPromise = new Promise(fulfill => this._closedCallback = fulfill);
this._isInitialized = this._targetInfo.type !== 'page' || this._targetInfo.url !== '';
if (this._isInitialized)
this._initializedCallback(true);
}
/**
* @return {!Promise<!Puppeteer.CDPSession>}
*/
createCDPSession() {
return this._sessionFactory();
}
/**
* @return {!Promise<?Page>}
*/
async page() {
if ((this._targetInfo.type === 'page' || this._targetInfo.type === 'background_page') && !this._pagePromise) {
this._pagePromise = this._sessionFactory()
.then(client => Page.create(client, this, this._ignoreHTTPSErrors, this._defaultViewport, this._screenshotTaskQueue));
}
return this._pagePromise;
}
/**
* @return {!Promise<?Worker>}
*/
async worker() {
if (this._targetInfo.type !== 'service_worker' && this._targetInfo.type !== 'shared_worker')
return null;
if (!this._workerPromise) {
this._workerPromise = this._sessionFactory().then(async client => {
// Top level workers have a fake page wrapping the actual worker.
const [targetAttached] = await Promise.all([
new Promise(x => client.once('Target.attachedToTarget', x)),
client.send('Target.setAutoAttach', {autoAttach: true, waitForDebuggerOnStart: false, flatten: true}),
]);
const session = Connection.fromSession(client).session(targetAttached.sessionId);
// TODO(einbinder): Make workers send their console logs.
return new Worker(session, this._targetInfo.url, () => {} /* consoleAPICalled */, () => {} /* exceptionThrown */);
});
}
return this._workerPromise;
}
/**
* @return {string}
*/
url() {
return this._targetInfo.url;
}
/**
* @return {"page"|"background_page"|"service_worker"|"shared_worker"|"other"|"browser"}
*/
type() {
const type = this._targetInfo.type;
if (type === 'page' || type === 'background_page' || type === 'service_worker' || type === 'shared_worker' || type === 'browser
')
return type;
return 'other';
}
/**
* @return {!Puppeteer.Browser}
*/
browser() {
return this._browserContext.browser();
}
/**
* @return {!Puppeteer.BrowserContext}
*/
browserContext() {...n/a
class TimeoutError extends CustomError {}n/a
class Touchscreen {
/**
* @param {Puppeteer.CDPSession} client
* @param {Keyboard} keyboard
*/
constructor(client, keyboard) {
this._client = client;
this._keyboard = keyboard;
}
/**
* @param {number} x
* @param {number} y
*/
async tap(x, y) {
// Touches appear to be lost during the first frame after navigation.
// This waits a frame before sending the tap.
// @see https://crbug.com/613219
await this._client.send('Runtime.evaluate', {
expression: 'new Promise(x => requestAnimationFrame(() => requestAnimationFrame(x)))',
awaitPromise: true
});
const touchPoints = [{x: Math.round(x), y: Math.round(y)}];
await this._client.send('Input.dispatchTouchEvent', {
type: 'touchStart',
touchPoints,
modifiers: this._keyboard._modifiers
});
await this._client.send('Input.dispatchTouchEvent', {
type: 'touchEnd',
touchPoints: [],
modifiers: this._keyboard._modifiers
});
}
}n/a
class Tracing {
/**
* @param {!Puppeteer.CDPSession} client
*/
constructor(client) {
this._client = client;
this._recording = false;
this._path = '';
}
/**
* @param {!{path?: string, screenshots?: boolean, categories?: !Array<string>}} options
*/
async start(options = {}) {
assert(!this._recording, 'Cannot start recording trace while already recording trace.');
const defaultCategories = [
'-*', 'devtools.timeline', 'v8.execute', 'disabled-by-default-devtools.timeline',
'disabled-by-default-devtools.timeline.frame', 'toplevel',
'blink.console', 'blink.user_timing', 'latencyInfo', 'disabled-by-default-devtools.timeline.stack',
'disabled-by-default-v8.cpu_profiler', 'disabled-by-default-v8.cpu_profiler.hires'
];
const {
path = null,
screenshots = false,
categories = defaultCategories,
} = options;
if (screenshots)
categories.push('disabled-by-default-devtools.screenshot');
this._path = path;
this._recording = true;
await this._client.send('Tracing.start', {
transferMode: 'ReturnAsStream',
categories: categories.join(',')
});
}
/**
* @return {!Promise<!Buffer>}
*/
async stop() {
let fulfill;
const contentPromise = new Promise(x => fulfill = x);
this._client.once('Tracing.tracingComplete', event => {
helper.readProtocolStream(this._client, event.stream, this._path).then(fulfill);
});
await this._client.send('Tracing.end');
this._recording = false;
return contentPromise;
}
}n/a
class Worker extends EventEmitter {
/**
* @param {Puppeteer.CDPSession} client
* @param {string} url
* @param {function(string, !Array<!JSHandle>, Protocol.Runtime.StackTrace=):void} consoleAPICalled
* @param {function(!Protocol.Runtime.ExceptionDetails):void} exceptionThrown
*/
constructor(client, url, consoleAPICalled, exceptionThrown) {
super();
this._client = client;
this._url = url;
this._executionContextPromise = new Promise(x => this._executionContextCallback = x);
/** @type {function(!Protocol.Runtime.RemoteObject):!JSHandle} */
let jsHandleFactory;
this._client.once('Runtime.executionContextCreated', async event => {
jsHandleFactory = remoteObject => new JSHandle(executionContext, client, remoteObject);
const executionContext = new ExecutionContext(client, event.context, null);
this._executionContextCallback(executionContext);
});
// This might fail if the target is closed before we recieve all execution contexts.
this._client.send('Runtime.enable', {}).catch(debugError);
this._client.on('Runtime.consoleAPICalled', event => consoleAPICalled(event.type, event.args.map(jsHandleFactory), event.stackTrace
));
this._client.on('Runtime.exceptionThrown', exception => exceptionThrown(exception.exceptionDetails));
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {!Promise<ExecutionContext>}
*/
async executionContext() {
return this._executionContextPromise;
}
/**
* @param {Function|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<*>}
*/
async evaluate(pageFunction, ...args) {
return (await this._executionContextPromise).evaluate(pageFunction, ...args);
}
/**
* @param {Function|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<!JSHandle>}
*/
async evaluateHandle(pageFunction, ...args) {
return (await this._executionContextPromise).evaluateHandle(pageFunction, ...args);
}
}n/a