-
- Description and source-code:
async function assertErrorThrownAsync(asyncFunc, regexp) {
let err;
try {
await asyncFunc();
} catch (errCaught) {
err = errCaught;
}
assertOrThrow(err, "No error thrown.");
assertOrThrow(
!regexp || new RegExp(regexp).test(err.message),
err
);
}
- Example usage:
...
jstestDescribe((
"test v8CoverageReportCreate handling-behavior"
), function testBehaviorV8CoverageReportCreate() {
jstestIt((
"test null-case handling-behavior"
), async function () {
await assertErrorThrownAsync(function () {
return v8CoverageReportCreate({});
}, "invalid coverageDir");
});
jstestIt((
"test coverage-report jslint.mjs handling-behavior"
), async function () {
// test remove-old-coverage handling-behavior
...
-
- Description and source-code:
function assertJsonEqual(aa, bb, message) {
aa = JSON.stringify(objectDeepCopyWithKeysSorted(aa), undefined, 1);
bb = JSON.stringify(objectDeepCopyWithKeysSorted(bb), undefined, 1);
if (aa !== bb) {
throw new Error(
"\n" + aa + "\n!==\n" + bb
+ (
typeof message === "string"
? " - " + message
: message
? " - " + JSON.stringify(message)
: ""
)
);
}
}
- Example usage:
...
// Debug data1.
// await moduleFs.promises.writeFile(
// ".test_v8_coverage_node_sqlite_merged.json",
// JSON.stringify(objectDeepCopyWithKeysSorted(data1), undefined, 4) + "\n"
// );
assertJsonEqual(data1, data2);
});
});
jstestDescribe((
"test v8CoverageReportCreate handling-behavior"
), function testBehaviorV8CoverageReportCreate() {
jstestIt((
...
-
- Description and source-code:
function assertOrThrow(condition, message) {
if (!condition) {
throw (
(!message || typeof message === "string")
? new Error(String(message).slice(0, 2048))
: message
);
}
}
- Example usage:
...
assertJsonEqual(1, 2, "undefined");
});
await assertErrorThrownAsync(function () {
assertJsonEqual(1, 2, {});
});
// test assertOrThrow error handling-behavior
await assertErrorThrownAsync(function () {
assertOrThrow(undefined, "undefined");
});
await assertErrorThrownAsync(function () {
assertOrThrow(undefined, new Error());
});
});
});
...
-
- Description and source-code:
function debug(...argv) {
__consoleError("\n\ndebugInline");
__consoleError(...argv);
__consoleError("\n");
return argv[0];
}
- Example usage:
N/A
-
- Description and source-code:
async function fsWriteFileWithParents(pathname, data) {
await moduleFsInit();
// Try writing to pathname.
try {
await moduleFs.promises.writeFile(pathname, data);
} catch (ignore) {
// Lazy mkdirp.
await moduleFs.promises.mkdir(modulePath.dirname(pathname), {
recursive: true
});
// Retry writing to pathname.
await moduleFs.promises.writeFile(pathname, data);
}
console.error("wrote file " + pathname);
}
- Example usage:
...
}
]
}, undefined, 4)
]
].map(async function ([
file, data
]) {
await fsWriteFileWithParents(file, data);
}));
await jslint.jslint_cli({
console_error: noop, // comment to debug
mode_cli: true,
process_argv: [
"node", "jslint.mjs",
"v8_coverage_report=.tmp/coverage_misc"
...
-
- Description and source-code:
function globExclude({
excludeList = [],
includeList = [],
pathnameList = []
}) {
function globAssertNotWeird(list, name) {
// This function will check if <list> of strings contain weird characters.
[
[
"\n", (
/^.*?([\u0000-\u0007\r]).*/gm
)
],
[
"\r", (
/^.*?([\n]).*/gm
)
]
].forEach(function ([
separator, rgx
]) {
list.join(separator).replace(rgx, function (match0, char) {
throw new Error(
"Weird character "
+ JSON.stringify(char)
+ " found in " + name + " "
+ JSON.stringify(match0)
);
});
});
}
function globToRegexp(pattern) {
// This function will translate glob <pattern> to javascript-regexp,
// which javascript can then use to "glob" pathnames.
let ii = 0;
let isClass = false;
let strClass = "";
let strRegex = "";
pattern = pattern.replace((
/\/\/+/g
), "/");
pattern = pattern.replace((
/\*\*\*+/g
), "**");
pattern.replace((
/\\\\|\\\[|\\\]|\[|\]|./g
), function (match0) {
switch (match0) {
case "[":
if (isClass) {
strClass += "[";
return;
}
strClass += "\u0000";
strRegex += "\u0000";
isClass = true;
return;
case "]":
if (isClass) {
isClass = false;...
}
- Example usage:
...
"test/support/helper.js": (
/^test\/support\/helper\.js$/gm
)
}).forEach(function ([
pattern, rgx
]) {
assertJsonEqual(
globExclude({
excludeList: [
pattern
]
}).excludeList[0].source,
rgx.source
);
assertJsonEqual(
...
-
- Description and source-code:
function htmlEscape(str) {
return String(str).replace((
/&/g
), "&").replace((
/</g
), "<").replace((
/>/g
), ">");
}
- Example usage:
...
inHole = isHole;
}
chunk += char;
});
lineHtml += htmlEscape(chunk);
break;
default:
lineHtml += htmlEscape(line);
}
html += String(`
<pre>
<span class="lineno">
<a href="#${lineId}" id="${lineId}">${String(ii + 1).padStart(5, " ")}.</a>
</span>
<span class="count
...
-
- Description and source-code:
function jslint(
source = "", // A text to analyze.
option_dict = empty(), // An object whose keys correspond to option
// ... names.
global_list = [] // An array of strings containing global
// ... variables that the file is allowed
// ... readonly access.
) {
let catch_list = []; // The array containing all catch-blocks.
let catch_stack = [ // The stack of catch-blocks.
{
context: empty()
}
];
let cause_dict = empty(); // The object of test-causes.
let directive_list = []; // The directive comments.
let export_dict = empty(); // The exported names and values.
let function_list = []; // The array containing all functions.
let function_stack = []; // The stack of functions.
let global_dict = empty(); // The object containing the global
// ... declarations.
let import_list = []; // The array collecting all import-from strings.
let line_list = String( // The array containing source lines.
"\n" + source
).split(jslint_rgx_crlf).map(function (line_source) {
return {
line_source
};
});
let mode_stop = false; // true if JSLint cannot finish.
let property_dict = empty(); // The object containing the tallied
// ... property names.
let state = empty(); // jslint state-object to be passed between
// jslint functions.
let syntax_dict = empty(); // The object containing the parser.
let tenure = empty(); // The predefined property registry.
let token_global = { // The global object; the outermost context.
async: 0,
body: true,
context: empty(),
finally: 0,
from: 0,
...
}
- Example usage:
...
import fs from "fs";
(async function () {
let result;
let source = "function foo() {console.log(\u0027hello world\u0027);}\n";
// Create JSLint report from <source> in javascript.
result = jslint.jslint(source);
result = jslint.jslint_report(result);
result = `<body class="JSLINT_ JSLINT_REPORT_">\n${result}</body>\n`;
await fs.promises.mkdir(".artifact/", {recursive: true});
await fs.promises.writeFile(".artifact/jslint_report_hello.html", result);
console.error("wrote file .artifact/jslint_report_hello.html");
}());
...
-
- Description and source-code:
async function jslint_apidoc({
example_list,
github_repo,
module_list,
package_name,
pathname,
version
}) {
let elem_ii = 0;
let html;
function elem_create(moduleObj, key, moduleName) {
// This function will create a sub API Doc from elem <moduleObj>[<key>].
let example = "N/A";
let id = encodeURIComponent("apidoc.elem." + moduleName + "." + key);
let name;
let signature;
let source;
name = htmlEscape((typeof moduleObj[key]) + " " + key);
if (typeof moduleObj[key] !== "function") {
return {
name,
signature: (`
<a class="apidocElementLiA" href="#${id}">
${name}
</a>
`),
source: (`
<li>
<h2>
<a href="#${id}" id="${id}">
${name}
</a>
</h2>
</li>
`)
};
}
// init source
source = htmlEscape(trim_start(moduleObj[key].toString()));
// init signature
source = source.replace((
/(\([\S\s]*?\)) \{/
), function (match0, match1) {
signature = htmlEscape(
match1.replace((
/ *?\/\*[\S\s]*?\*\/ */g
), "").replace((
/ *?\/\/.*/g
), "").replace((
/\n{2,}/g
), "\n")
);
return match0;
});
// init comment
source = source.replace((
/\n(?:\/\/.*?\n)+\n/
), "<span class=\"apidocCodeCommentSpan\">$&</span>");
// init example
example_list.some(function (example2) {
example2.replace(
new RegExp((
"((?:\\n.*?){8}(function )?)\\b"
+ key
+ "(\\((?:.*?\\n){8})"
), "g"),
...
}
- Example usage:
...
command[1] = command.slice(1).join("=");
switch (command[0]) {
// PR-362 - Add API Doc.
case "jslint_apidoc":
await jslint_apidoc(Object.assign(JSON.parse(process_argv[3]), {
pathname: command[1]
}));
return;
// PR-363 - Add command jslint_report.
case "jslint_report":
...
-
- Description and source-code:
function jslint_assert(condition, message) {
if (condition) {
return condition;
}
throw new Error(
`This was caused by a bug in JSLint.
Please open an issue with this stack-trace (and possible example-code) at
https://github.com/jslint-org/jslint/issues.
edition = "${jslint_edition}";
${String(message).slice(0, 2000)}`
);
}
- Example usage:
...
// ["let aa={};", "whitage", "opener", "", 0]
test_cause("opener");
// Probably deadcode.
// case "${}":
jslint_assert(
!(left.id + right.id === "${}"),
"Expected !(left.id + right.id === \"${}\")."
);
switch (left.id + right.id) {
case "()":
case "[]":
case "{}":
...
-
- Description and source-code:
async function jslint_cli({
console_error,
console_log,
file,
import_meta_url,
mode_cli,
mode_noop,
option,
process_argv,
process_env,
process_exit,
source
}) {
let command;
let data;
let exit_code = 0;
let mode_report;
let mode_wrapper_vim;
let result;
function jslint_from_file({
code,
file,
line_offset = 0,
mode_conditional,
option = empty()
}) {
let result_from_file;
if (
mode_conditional
&& !(
/^\/\*jslint\b/m
).test(code.slice(0, 65536))
) {
return;
}
option = Object.assign(empty(), option, {
file
});
switch ((
/\.\w+?$|$/m
).exec(file)[0]) {
case ".html":
// Recursively jslint embedded "<script>\n...\n</script>".
code.replace((
/^<script\b[^>]*?>\n([\S\s]*?\n)<\/script>$/gm
), function (ignore, match1, ii) {
jslint_from_file({
code: match1,
file: file + ".<script>.js",
line_offset: string_line_count(code.slice(0, ii)) + 1,
option: Object.assign(empty(), {
browser: true
}, option)
});
return "";
});
return;
case ".md":
// Recursively jslint embedded "node --eval '\n...\n'".
jslint_node_eval({
code,
file,
mode_conditional: true,
option
});
return;
case ".sh":
// Recursively jslint embedded "node --eval '\n...\n'".
jslint_node_eval({
code,
file,
option
});
return;
...
}
- Example usage:
...
}, undefined, 4)
]
].map(async function ([
file, data
]) {
await fsWriteFileWithParents(file, data);
}));
await jslint.jslint_cli({
console_error: noop, // comment to debug
mode_cli: true,
process_argv: [
"node", "jslint.mjs",
"v8_coverage_report=.tmp/coverage_misc"
// "node", ".tmp/coverage_misc/aa.js"
]
...
-
- Description and source-code:
function jslint_phase1_split() {
return;
}
- Example usage:
...
warn,
warn_at,
warning_list
});
// PHASE 1. Split <source> by newlines into <line_list>.
jslint_phase1_split(state);
jslint_assert(catch_stack.length === 1, `catch_stack.length === 1.`);
jslint_assert(
function_stack.length === 0,
`function_stack.length === 0.`
);
// PHASE 2. Lex <line_list> into <token_list>.
...
-
- Description and source-code:
function jslint_phase2_lex(state) {
let {
artifact,
directive_list,
global_dict,
global_list,
line_list,
option_dict,
stop,
stop_at,
tenure,
test_cause,
token_global,
token_list,
warn,
warn_at
} = state;
let char; // The current character being lexed.
let column = 0; // The column number of the next character.
let from; // The starting column number of the token.
let from_mega; // The starting column of megastring.
let line = 0; // The line number of the next character.
let line_disable; // The starting line of "/*jslint-disable*/".
let line_mega; // The starting line of megastring.
let line_source = ""; // The remaining line source string.
let line_whole = ""; // The whole line source string.
let mode_digits_empty_string = 1;
let mode_digits_numeric_separator = 2;
let mode_directive = true; // true if directives are still allowed.
let mode_mega = false; // true if currently parsing a megastring
// ... literal.
let mode_regexp; // true if regular expression literal seen on
// ... this line.
let paren_backtrack_list = []; // List of most recent "(" tokens at any
// ... paren-depth.
let paren_depth = 0; // Keeps track of current paren-depth.
let snippet = ""; // A piece of string.
let token_1; // The first token.
let token_prv = token_global; // The previous token including
// ... comments.
let token_prv_expr = token_global; // The previous token excluding
// ... comm...
}
- Example usage:
...
jslint_assert(
function_stack.length === 0,
`function_stack.length === 0.`
);
// PHASE 2. Lex <line_list> into <token_list>.
jslint_phase2_lex(state);
jslint_assert(catch_stack.length === 1, `catch_stack.length === 1.`);
jslint_assert(
function_stack.length === 0,
`function_stack.length === 0.`
);
// PHASE 3. Parse <token_list> into <token_tree> using the Pratt-parser.
...
-
- Description and source-code:
function jslint_phase3_parse(state) {
// Parsing:
// Parsing weaves the tokens into an abstract syntax tree. During that process,
// a token may be given any of these properties:
// arity string
// label identifier
// name identifier
// expression expressions
// block statements
// else statements (else, default, catch)
// Specialized tokens may have additional properties.
let anon = "anonymous"; // The guessed name for anonymous functions.
let {
artifact,
catch_list,
catch_stack,
export_dict,
function_list,
function_stack,
global_dict,
import_list,
is_equal,
option_dict,
property_dict,
stop,
syntax_dict,
tenure,
test_cause,
token_global,
token_list,
warn,
warn_at
} = state;
let catchage = catch_stack[0]; // The current catch-block.
let functionage = token_global; // The current function.
let mode_var; // "var" if using var; "let" if using let.
let token_ii = 0; // The number of the next token.
let token_now = token_global; // The current token being examined in
// ... the parse.
let token_nxt = token_global; // The next token to be examined in
// ... <token_list>.
function advance(id, match) {
// Produce the next token.
// Attempt to give helpful names to anonymous functions.
if (
token_now.identifier
&& token_now.id !== "function"
&& token_now.id !== "async"
) {
anon = token_now.id;
} else if (
token_now.id === "(string)"
&& jslint_rgx_identifier.test(token_now.value)
...
}
- Example usage:
...
jslint_assert(
function_stack.length === 0,
`function_stack.length === 0.`
);
// PHASE 3. Parse <token_list> into <token_tree> using the Pratt-parser.
jslint_phase3_parse(state);
jslint_assert(catch_stack.length === 1, `catch_stack.length === 1.`);
jslint_assert(
function_stack.length === 0,
`function_stack.length === 0.`
);
// PHASE 4. Walk <token_tree>, traversing all nodes of the tree. It is a
...
-
- Description and source-code:
function jslint_phase4_walk(state) {
let {
artifact,
catch_stack,
function_stack,
global_dict,
is_equal,
is_weird,
option_dict,
syntax_dict,
test_cause,
token_global,
warn
} = state;
let block_stack = []; // The stack of blocks.
let blockage = token_global; // The current block.
let catchage = catch_stack[0]; // The current catch-block.
let functionage = token_global; // The current function.
let postaction;
let postamble;
let posts = empty();
let preaction;
let preamble;
let pres = empty();
// The relational operators.
let relationop = object_assign_from_list(empty(), [
"!=", "!==", "<", "<=", "==", "===", ">", ">="
], true);
// Ambulation of the parse tree.
function action(when) {
// Produce a function that will register task functions that will be called as
// the tree is traversed.
return function (arity, id, task) {
let a_set = when[arity];
let i_set;
// The id parameter is optional. If excluded, the task will be applied to all
// ids.
if (typeof id !== "string") {
task = id;
id = "(all)";
}
// If this arity has no registrations yet, then create a set object to hold
// them.
if (a_set === undefined) {
a_set = empty();
when[arity] = a_set;
}
// If this id has no registrations yet, then create a set array to hold them.
i_set = a_set[id];
if (i_set === undefined) {
i_set = [];
a_set[id] = i_set;
}
// Register the task with the arity and the id.
...
}
- Example usage:
...
);
// PHASE 4. Walk <token_tree>, traversing all nodes of the tree. It is a
// recursive traversal. Each node may be processed on the way down
// (preaction) and on the way up (postaction).
if (!state.mode_json) {
jslint_phase4_walk(state);
}
jslint_assert(catch_stack.length === 1, `catch_stack.length === 1.`);
jslint_assert(
function_stack.length === 0,
`function_stack.length === 0.`
);
...
-
- Description and source-code:
function jslint_phase5_whitage(state) {
let {
artifact,
catch_list,
function_list,
function_stack,
option_dict,
test_cause,
token_global,
token_list,
warn
} = state;
let closer = "(end)";
let free = false;
// free = false
// cause:
// "()=>0"
// "aa()"
// "aa(0,0)"
// "function(){}"
// free = true
// cause:
// "(0)"
// "(aa)"
// "aa(0)"
// "do{}while()"
// "for(){}"
// "if(){}"
// "switch(){}"
// "while(){}"
let left = token_global;
let margin = 0;
let mode_indent = (
// PR-330 - Allow 2-space indent.
option_dict.indent2
? 2
: 4
);
let nr_comments_skipped = 0;
let open = true;
let opening = true;
let right;
// This is the set of infix operators that require a space on each side.
let spaceop = object_assign_from_list(empty(), [
"!=", "!==", "%", "%=", "&", "&&", "&=", "*", "*=", "+=", "-=", "/",
"/=", "<", "<<", "<<=", "<=", "=", "==", "===", "=>", ">", ">=", ">>",
">>=", ">>>", ">>>=", "^", "^=", "|", "|=", "||"
], true);
function at_margin(fit) {
const at = margin + fit;
if (right.from !== at) {
return expected_at(at);
}
}
function delve(the_function) {
Object.keys(the_function.context).forEach(function (id) {
const name = the_function.context[id];
if (id !== "ignore" && name.parent === the_function) {
// test_cause:
// ["function aa(aa) {return aa;}", "delve", "id", "", 0]
test_cause("id");
if (
name.used === 0
// Probably deadcode.
// && (
// name.role !== "function"
// || name.parent.arity !== "unary"
// )
&& jslint_assert(
name.role...
}
- Example usage:
...
function_stack.length === 0,
`function_stack.length === 0.`
);
// PHASE 5. Check whitespace between tokens in <token_list>.
if (!state.mode_json && warning_list.length === 0) {
jslint_phase5_whitage(state);
}
jslint_assert(catch_stack.length === 1, `catch_stack.length === 1.`);
jslint_assert(
function_stack.length === 0,
`function_stack.length === 0.`
);
...
-
- Description and source-code:
function jslint_report({
exports,
froms,
functions,
global,
json,
module,
property,
stop,
warnings
}) {
let html = "";
let length_80 = 1111;
function address(line = 1, column = 1) {
// This function will create HTML address element from <line> and <column>
return `<address>${Number(line)}: ${Number(column)}</address>`;
}
function detail(title, list) {
return (
(Array.isArray(list) && list.length > 0)
? (
// Google Lighthouse Accessibility - <dl>'s do not contain only properly-ordered
// <dt> and <dd> groups, <script>, <template> or <div> elements.
"<dl>"
+ "<dt>" + htmlEscape(title) + "</dt>"
+ "<dd>" + list.join(", ") + "</dd>"
+ "</dl>"
)
: ""
);
}
html += String(`
<style class="JSLINT_REPORT_STYLE">
/* jslint utility2:true */
/*csslint box-model: false, ids:false */
/*csslint ignore:start*/
@font-face {
font-display: swap;
font-family: "Daley";
src: url(
"data:font/woff2;base64,d09GMgABAAAAABy4AA4AAAAAThwAABxiAAEAAAAAAAAAAAAA\
AAAAAAAAAAAAAAAABmAAgiQINAmcDBEICuc41DEBNgIkA4R2C4I+AAQgBYkuByAMgScfYUIF\
7NgjsHGAbcDVFkXZ5Jwd+P96IGPc9rl9ETBEaCzCJkvY2UpziRZ7zftZWk8052U9+NqX6vXL\
KDflSQnlJ0bP+QnPQAy744n9mup6H9PaCDFwM5zjf8exB89bZ1cdrYOP0NgnuRDRWlk9u/fE\
llkxqmfH8lmRQ/DAmER9opk9wR6suc1LvTiXNEe1vbhUCH2USgnEwH3vUm05JQqejGvZvOtz\
7sIKEGgLdDNl/IrfqWVZG/wr42ekomEm91VA1p4LhHBuFzHF8//u7vvbREHMQqGtNLmiOOD/\
X7WWiwqyCE98qt0jk5JJmgR5WJJElBmzRb1F7a66MmSLTNWZ2XSHfKBSKHoVteSEJ6EOdvVw\
fNZOtXKDe39jXdRlkmMnOWIOFBgeEK/b0mFsgffnP...
}
- Example usage:
...
editor.on("lintJslintAfter", function (options) {
// Generate jslint-report from options.result.
document.querySelector(
".JSLINT_REPORT_"
).innerHTML = window.jslint.jslint_report(options.result);
});
// Manually trigger linter.
editor.performLint();
});
</script>
...
-
- Description and source-code:
async function jstestDescribe(description, testFunction) {
let message;
let result;
let timerTimeout;
// Init jstestTimeStart.
if (jstestTimeStart === undefined) {
jstestTimeStart = jstestTimeStart || Date.now();
process.on("exit", jstestOnExit);
}
// PR-457 - Wait awhile for imports to initialize.
await new Promise(function (resolve) {
setTimeout(resolve);
});
// Init jstestItList.
jstestItList = [];
testFunction();
// Wait for jstestItList to resolve.
timerTimeout = setTimeout(noop, 0x7fffffff);
result = await Promise.all(jstestItList);
clearTimeout(timerTimeout);
// Print test results.
message = (
"\n " + (Date.now() - jstestTimeStart) + "ms"
+ " - test describe - " + description + "\n"
+ result.map(function ([
err, description, mode
]) {
jstestItCount += 1;
if (err) {
jstestCountFailed += 1;
err = (
" \u001b[31m\u2718 " + jstestItCount + ". test it - "
+ description + "\n" + err.stack + "\u001b[39m"
);
if (mode === "pass") {
jstestCountFailed -= 1;
err = "";
}
}
return err || (
" \u001b[32m\u2714 " + jstestItCount + ". test it - "
+ description + "\u001b[39m"
);
}).join("\n")
);
console.error(message);
}
- Example usage:
...
// JSON.stringify(objectDeepCopyWithKeysSorted(data1), undefined, 4) + "\n"
// );
assertJsonEqual(data1, data2);
});
});
jstestDescribe((
"test v8CoverageReportCreate handling-behavior"
), function testBehaviorV8CoverageReportCreate() {
jstestIt((
"test null-case handling-behavior"
), async function () {
await assertErrorThrownAsync(function () {
return v8CoverageReportCreate({});
...
-
- Description and source-code:
function jstestIt(description, testFunction, mode) {
jstestCountTotal += 1;
jstestItList.push(new Promise(async function (resolve) {
let err;
try {
await testFunction();
} catch (errCaught) {
err = errCaught;
}
resolve([err, description, mode]);
}));
}
- Example usage:
...
"v8_coverage_report=" + dir,
"node",
file
]
});
});
});
jstestIt((
"test npm handling-behavior"
), async function () {
await jslint.jslint_cli({
console_error: noop, // comment to debug
mode_cli: true,
process_argv: [
"node", "jslint.mjs",
...
-
- Description and source-code:
function jstestOnExit(exitCode, mode) {
let message = (
(
(jstestCountFailed || mode === "testsFailed")
? "\n\u001b[31m"
: "\n\u001b[32m"
)
+ " tests total - " + jstestCountTotal + "\n"
+ " tests failed - " + jstestCountFailed + "\n"
+ "\n"
+ " time finished - "
+ Number(Date.now() - jstestTimeStart).toLocaleString()
+ " ms\n"
+ "\u001b[39m"
);
if (mode !== "testsFailed") {
console.error(message);
}
process.exitCode = exitCode || jstestCountFailed;
return message;
}
- Example usage:
...
"test jstestDescribe error handling-behavior"
), function () {
throw new Error();
}, "pass");
jstestIt((
"test jstestOnExit tests-failed handling-behavior"
), function () {
jstestOnExit(undefined, "testsFailed");
});
});
jstestDescribe((
"test misc handling-behavior"
), function testBehaviorMisc() {
jstestIt((
...
-
- Description and source-code:
async function moduleFsInit() {
// State 3 - Modules already imported.
if (moduleFs !== undefined) {
return;
}
// State 2 - Wait while modules are importing.
if (moduleFsInitResolveList !== undefined) {
return new Promise(function (resolve) {
moduleFsInitResolveList.push(resolve);
});
}
// State 1 - Start importing modules.
moduleFsInitResolveList = [];
[
moduleChildProcess,
moduleFs,
modulePath,
moduleUrl
] = await Promise.all([
import("child_process"),
import("fs"),
import("path"),
import("url")
]);
while (moduleFsInitResolveList.length > 0) {
moduleFsInitResolveList.shift()();
}
}
- Example usage:
...
let sourceJslintMjs;
let testCoverageMergeData;
await (async function init() {
// Coverage-hack - Ugly-hack to get test-coverage for all initialization-states.
moduleFsInit();
moduleFsInit();
// Cleanup directory .tmp
await moduleFs.promises.rm(".tmp", {
recursive: true
}).catch(noop);
...
-
- Description and source-code:
function noop(val) {
return val;
}
- Example usage:
...
jstestDescribe((
"test misc handling-behavior"
), function testBehaviorMisc() {
jstestIt((
"test misc handling-behavior"
), async function () {
// test debugInline handling-behavior
noop(debugInline);
// test assertErrorThrownAsync error handling-behavior
await assertErrorThrownAsync(function () {
return assertErrorThrownAsync(noop);
});
// test assertJsonEqual error handling-behavior
await assertErrorThrownAsync(function () {
assertJsonEqual(1, 2);
...
-
- Description and source-code:
function objectDeepCopyWithKeysSorted(obj) {
let sorted;
if (typeof obj !== "object" || !obj) {
return obj;
}
// Recursively deep-copy list with child-keys sorted.
if (Array.isArray(obj)) {
return obj.map(objectDeepCopyWithKeysSorted);
}
// Recursively deep-copy obj with keys sorted.
sorted = Object.create(null);
Object.keys(obj).sort().forEach(function (key) {
sorted[key] = objectDeepCopyWithKeysSorted(obj[key]);
});
return sorted;
}
- Example usage:
...
];
data1 = v8CoverageListMerge(data1);
data1 = v8CoverageListMerge([data1]);
// Debug data1.
// await moduleFs.promises.writeFile(
// ".test_v8_coverage_node_sqlite_merged.json",
// JSON.stringify(objectDeepCopyWithKeysSorted(data1), undefined, 4) + "\n"
// );
assertJsonEqual(data1, data2);
});
});
jstestDescribe((
...
-
- Description and source-code:
function v8CoverageListMerge(processCovs) {
let resultMerged = []; // List of merged scripts from processCovs.
let urlToScriptDict = new Map(); // Map scriptCov.url to scriptCovs.
function compareRangeList(aa, bb) {
// Compares two range coverages.
// The ranges are first ordered by ascending `startOffset` and then by
// descending `endOffset`.
// This corresponds to a pre-order tree traversal.
if (aa.startOffset !== bb.startOffset) {
return aa.startOffset - bb.startOffset;
}
return bb.endOffset - aa.endOffset;
}
function dictKeyValueAppend(dict, key, val) {
// This function will append <val> to list <dict>[<key>].
let list = dict.get(key);
if (list === undefined) {
list = [];
dict.set(key, list);
}
list.push(val);
}
function mergeTreeList(parentTrees) {
// This function will return RangeTree object with <parentTrees> merged into
// property-children.
// @precondition Same `start` and `end` for all the parentTrees
if (parentTrees.length <= 1) {
return parentTrees[0];
}
// new RangeTree().
return {
// Merge parentTrees into property-children.
children: mergeTreeListToChildren(parentTrees),
delta: parentTrees.reduce(function (aa, bb) {
return aa + bb.delta;
}, 0),
end: parentTrees[0].end,
start: parentTrees[0].start
...
}
- Example usage:
...
"test_v8_coverage_node_sqlite_13216_1633662333140_0.json"
].map(function (file) {
return testCoverageMergeData[file];
});
let data2 = testCoverageMergeData[
"test_v8_coverage_node_sqlite_merged.json"
];
data1 = v8CoverageListMerge(data1);
data1 = v8CoverageListMerge([data1]);
// Debug data1.
// await moduleFs.promises.writeFile(
// ".test_v8_coverage_node_sqlite_merged.json",
// JSON.stringify(objectDeepCopyWithKeysSorted(data1), undefined, 4) + "\n"
// );
...
-
- Description and source-code:
async function v8CoverageReportCreate({
consoleError,
coverageDir,
processArgv = []
}) {
let cwd;
let excludeList = [];
let exitCode = 0;
let fileDict;
let includeList = [];
let modeIncludeNodeModules;
let processArgElem;
let promiseList = [];
let v8CoverageObj;
function htmlRender({
fileList,
lineList,
modeIndex,
pathname
}) {
let html;
let padLines;
let padPathname;
let txt;
let txtBorder;
html = "";
html += String(`
<!DOCTYPE html>
<html lang="en">
<head>
<title>V8 Coverage Report</title>
<style>
/* jslint utility2:true */
/*csslint ignore:start*/
.coverage,
.coverage a,
.coverage div,
.coverage pre,
.coverage span,
.coverage table,
.coverage tbody,
.coverage td,
.coverage th,
.coverage thead,
.coverage tr {
box-sizing: border-box;
font-family: monospace;
}
/*csslint ignore:end*/
/* css - coverage_report - general */
body {
margin: 0;
}
.coverage pre {
margin: 5px 0;
}
.coverage table {
border-collapse: collapse;
}
.coverage td,
.coverage th {
border: 1px solid #777;
line-height: 20px;
margin: 0;
padding: 5px 10px;
}
.coverage td span {
display: inline-block;
width: 100%;
}
.coverage .content {
padding: 0 5px;
}
.coverage .content a {
text-decoration: none;
}
.coverage .count {
margin: 0 5px;
padding: 0 5px;
}
.coverage .footer,
.coverage .header {
padding: 20px;
}
.coverage .footer {
text-align: center;
}
.coverage .percentbar {
height: 12px;
margin: 2px 0;
min-width: 200px;
position: relative;
width: 100%;...
}
- Example usage:
...
/*jslint node*/
import jslint from "../jslint.mjs";
(async function () {
// Create V8 coverage report from program `npm run test` in javascript.
await jslint.v8CoverageReportCreate({
coverageDir: "../.artifact/coverage_sqlite3_js/",
processArgv: [
"--exclude=tes?/",
"--exclude=tes[!0-9A-Z_a-z-]/",
"--exclude=tes[0-9A-Z_a-z-]/",
"--exclude=tes[^0-9A-Z_a-z-]/",
"--exclude=test/**/*.js",
...
-
-