// File modules of 32 KiB or more load off the JS thread: the file is read, // then compiled (streamed) or its code cache consumed on a background thread, // and only the result is finalized on the module's own thread. Every module // here is written at run time under a name unique to this run (modules // evaluate once per process, and code caches outlive the process), with a body // above that threshold by construction. describe("Large file modules", function () { var STREAMING_THRESHOLD = 32 * 1024; // With a fresh code cache, only modules this large load off the JS thread. var CACHE_CONSUME_THRESHOLD = 256 * 1024; var LINES = 1500; var CONSUME_LINES = 5000; var fileManager = NSFileManager.defaultManager; var runId = String(Date.now()); var fixtureDir = NSBundle.mainBundle.resourcePath + "/app/tests/esm/large-" + runId; // import() reads a leading "/" as the app root, so imports use specifiers // relative to this file, and require() the absolute path. var fixtureSpec = "./esm/large-" + runId; var isDebugBuild = typeof require("ns:module").canonicalizeHttpUrlKey === "function"; var originalTimeout; function writeModule(name, body) { var path = fixtureDir + "/" + name + ".mjs"; var data = NSString.stringWithString(body).dataUsingEncoding(NSUTF8StringEncoding); if (!fileManager.createFileAtPathContentsAttributes(path, data, null)) { throw new Error("could not write " + path); } return path; } // `lines` real declarations whose evaluation folds into `total`, so a // value depends on the whole body. `stackLine` is the line of the // `new Error` that stack() returns the trace of. function bigModule(k, lines, options) { options = options || {}; var body = (options.bom ? "" : "") + "let acc = 0;\nconst strs = [];\n"; for (var i = 0; i < lines; i++) { body += "function f" + i + "(x) { return (x * 3 + " + i + ") % 1000; } acc += f" + i + "(" + i + ");"; if (options.unicode) { body += " strs.push(\"café 日本語 😀 " + i + "\");"; } body += "\n"; } if (options.error) { body += "export const broken = ;\n"; } body += "const evaluations = globalThis.__nsFileModuleEvaluations ||" + " (globalThis.__nsFileModuleEvaluations = {});\n" + "evaluations[\"" + k + "\"] = (evaluations[\"" + k + "\"] || 0) + 1;\n" + "export const id = \"" + k + "\";\n" + "export const count = " + lines + ";\n" + "export const total = acc;\n" + "export const first = strs[0];\n" + "export const last = strs[strs.length - 1];\n" + "export const token = {};\n"; var stackLine = body.split("\n").length; body += "export function stack() { return new Error(\"here\").stack; }\n"; return { body: body, stackLine: stackLine }; } function evaluations(k) { return (globalThis.__nsFileModuleEvaluations || {})[k]; } function expectWholeBody(mod, k, lines, evaluationCount) { var total = 0; for (var i = 0; i < lines; i++) { total += (i * 3 + i) % 1000; } expect(mod.id).toBe(k); expect(mod.count).toBe(lines); expect(mod.total).toBe(total); expect(evaluations(k)).toBe(evaluationCount || 1); } function writeBig(name, k, lines, options) { var module = bigModule(k, lines, options); if (lines > 0) { expect(module.body.length).toBeGreaterThan(STREAMING_THRESHOLD); } module.path = writeModule(name, module.body); module.spec = fixtureSpec + "/" + name + ".mjs"; return module; } function formatError(error) { var name = error && error.name ? error.name + ": " : ""; return name + String((error && error.message) || error); } function modifiedSeconds(path) { var attributes = fileManager.attributesOfItemAtPathError(path, null); // NSDate arrives as a JS Date. var date = attributes && attributes.objectForKey("NSFileModificationDate"); return date ? Math.floor(date.getTime() / 1000) : -1; } // Resolves once a code cache stamped with `path`'s current modification // time exists, the one the runtime treats as fresh. function freshCodeCache(path) { var deadline = Date.now() + 5000; return new Promise(function (resolve, reject) { (function poll() { var source = modifiedSeconds(path); if (codeCacheEntries(path).some(function (entry) { return modifiedSeconds(entry) === source; })) { resolve(); } else if (Date.now() > deadline) { reject(new Error("no fresh code cache for " + path)); } else { setTimeout(poll, 100); } })(); }); } // How many requests the XCTest module server has received for `target`, // read synchronously so the JS thread does not yield. function serverRequestCount(origin, target) { var url = NSURL.URLWithString(origin + "/esm/request-stats.json?target=" + encodeURIComponent(target)); var data = NSData.dataWithContentsOfURL(url); if (!data) { return 0; } return JSON.parse(String(NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding))) .count; } function hostOrigin() { try { var reportUrl = NSProcessInfo.processInfo.environment.objectForKey("REPORT_BASEURL"); return reportUrl ? new URL(String(reportUrl)).origin : null; } catch (e) { return null; } } function failWith(done) { return function (error) { expect("rejected: " + formatError(error)).toBe("resolved"); done(); }; } // The frame of stack()'s own `new Error`, as ":". function errorPosition(mod) { var frame = mod.stack().split("\n")[1] || ""; var match = frame.match(/:(\d+):(\d+)\)?\s*$/); return match ? match[1] + ":" + match[2] : frame; } // Runs `body` from a fresh task. Jasmine may start a spec from a promise // continuation, where V8 ignores microtask checkpoints and a pumping // require() refuses to run. function inTask(done, body) { __ns__setTimeout(function () { try { body(); } catch (e) { expect("threw: " + formatError(e)).toBe("no exception"); } done(); }, 0); } function delay(ms) { return new Promise(function (resolve) { setTimeout(resolve, ms); }); } // Names in the caches directory of `path`'s module code cache. function codeCacheEntries(path) { // NSCachesDirectory in NSUserDomainMask, where the runtime keeps them. var caches = String(fileManager.URLsForDirectoryInDomains(13, 1).firstObject.path); var suffix = "-" + path.split("/").slice(-1)[0] + ".mcache"; var found = []; var names = fileManager.contentsOfDirectoryAtPathError(caches, null); for (var i = 0; names && i < names.count; i++) { var name = String(names.objectAtIndex(i)); if (name.length > suffix.length && name.slice(-suffix.length) === suffix && name.indexOf("large-" + runId) !== -1) { found.push(caches + "/" + name); } } return found; } beforeAll(function () { fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError( fixtureDir, true, null, null); }); afterAll(function () { if (fileManager.fileExistsAtPath(fixtureDir)) { fileManager.removeItemAtPathError(fixtureDir, null); } }); beforeEach(function () { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; }); afterEach(function () { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it("evaluates one loaded with import() after import() returns", function (done) { var module = writeBig("dynamic", "file-dynamic", LINES); var loading = import(module.spec); expect(evaluations("file-dynamic")).toBeUndefined(); loading.then(function (mod) { expectWholeBody(mod, "file-dynamic", LINES); done(); }).catch(failWith(done)); }); it("reports source positions as a small module does", function (done) { var small = writeBig("positions-small", "file-positions-small", 0); var ascii = writeBig("positions-ascii", "file-positions-ascii", LINES); var unicode = writeBig("positions-unicode", "file-positions-unicode", LINES, { unicode: true }); var bom = writeBig("positions-bom", "file-positions-bom", LINES, { bom: true }); Promise.all([ import(small.spec), import(ascii.spec), import(unicode.spec), import(bom.spec), ]).then(function (mods) { var column = errorPosition(mods[0]).split(":")[1]; expect(errorPosition(mods[0])).toBe(small.stackLine + ":" + column); expect(errorPosition(mods[1])).toBe(ascii.stackLine + ":" + column); expect(errorPosition(mods[2])).toBe(unicode.stackLine + ":" + column); expect(errorPosition(mods[3])).toBe(bom.stackLine + ":" + column); done(); }).catch(failWith(done)); }); it("evaluates non-ASCII string literals to the right values", function (done) { var module = writeBig("unicode", "file-unicode", LINES, { unicode: true }); import(module.spec).then(function (mod) { expectWholeBody(mod, "file-unicode", LINES); expect(mod.first).toBe("café 日本語 😀 0"); expect(mod.last).toBe("café 日本語 😀 " + (LINES - 1)); done(); }).catch(failWith(done)); }); it("evaluates one reached through a static import from a small module", function (done) { writeBig("static-child", "file-static-child", LINES); writeModule("static-parent", "export * as child from \"./static-child.mjs\";\n" + "export const parent = \"file-static-parent\";\n"); import(fixtureSpec + "/static-parent.mjs").then(function (mod) { expect(mod.parent).toBe("file-static-parent"); expectWholeBody(mod.child, "file-static-child", LINES); done(); }).catch(failWith(done)); }); it("gives a pending import() and a require() of the same module one instance", function (done) { var module = writeBig("shared", "file-shared", LINES); var loading = import(module.spec); var required = require(module.path); expect(evaluations("file-shared")).toBe(1); loading.then(function (mod) { expectWholeBody(mod, "file-shared", LINES); expect(mod.token).toBe(required.token); done(); }).catch(failWith(done)); }); it("returns from require() with the module evaluated", function () { var module = writeBig("required", "file-required", LINES); var required = require(module.path); expectWholeBody(required, "file-required", LINES); }); it("runs no timers while require() waits for a large module", function (done) { var module = writeBig("required-timer", "file-required-timer", LINES); var fired = false; inTask(function () { setTimeout(function () { expect(fired).toBe(true); done(); }, 0); }, function () { setTimeout(function () { fired = true; }, 0); var required = require(module.path); expect(fired).toBe(false); expectWholeBody(required, "file-required-timer", LINES); }); }); it("runs no promise jobs while require() waits for a large module", function (done) { var module = writeBig("required-microtask", "file-required-microtask", LINES); inTask(done, function () { var ran = false; Promise.resolve().then(function () { ran = true; }); var required = require(module.path); expect(ran).toBe(false); expectWholeBody(required, "file-required-microtask", LINES); }); }); it("settles a top-level await import() of a large module in a pumping require()", function (done) { var nsModule = require("ns:module"); if (typeof nsModule.createPumpingRequire !== "function") { pending("createPumpingRequire is not available in this build"); done(); return; } writeBig("tla-child", "file-tla-child", LINES); writeModule("tla-parent", "const child = await import(\"./tla-child.mjs\");\n" + "export const id = child.id;\n" + "export const total = child.total;\n" + "export const count = child.count;\n"); inTask(done, function () { var pumpingRequire = nsModule.createPumpingRequire(fixtureDir + "/anything.js"); var startedAt = Date.now(); var mod = pumpingRequire("./tla-parent.mjs"); expect(Date.now() - startedAt).toBeLessThan(10000); expectWholeBody(mod, "file-tla-child", LINES); }); }); it("does not evaluate an earlier import() while a pumping require() awaits", function (done) { var nsModule = require("ns:module"); if (typeof nsModule.createPumpingRequire !== "function") { pending("createPumpingRequire is not available in this build"); done(); return; } var earlier = writeBig("pumping-earlier", "file-pumping-earlier", LINES); writeBig("pumping-child", "file-pumping-child", LINES); writeModule("pumping-parent", "const child = await import(\"./pumping-child.mjs\");\n" + "export const id = child.id;\n" + "export const total = child.total;\n" + "export const count = child.count;\n"); __ns__setTimeout(function () { var loading; try { loading = import(earlier.spec); // Holds the JS thread while the earlier load compiles, so its // completion is queued when require() starts pumping. var until = performance.now() + 300; while (performance.now() < until) {} var mod = nsModule.createPumpingRequire(fixtureDir + "/anything.js")( "./pumping-parent.mjs"); expectWholeBody(mod, "file-pumping-child", LINES); expect(evaluations("file-pumping-earlier")).toBeUndefined(); } catch (e) { expect("threw: " + formatError(e)).toBe("no exception"); } loading.then(function (mod) { expectWholeBody(mod, "file-pumping-earlier", LINES); done(); }).catch(failWith(done)); }, 0); }); it("does not evaluate a pending import() inside a require() of another module", function (done) { var imported = writeBig("pending-import", "file-pending-import", LINES); var requiredModule = writeBig("pending-require", "file-pending-require", LINES); var loading = import(imported.spec); var required = require(requiredModule.path); expectWholeBody(required, "file-pending-require", LINES); expect(evaluations("file-pending-import")).toBeUndefined(); loading.then(function (mod) { expectWholeBody(mod, "file-pending-import", LINES); done(); }).catch(failWith(done)); }); it("does not evaluate a pending HTTP import() inside a require() of a large module", function (done) { var origin = hostOrigin(); if (!isDebugBuild || !origin) { pending("needs the Debug build's HTTP loader and the XCTest module server"); } var k = "file-pending-http-" + runId; var target = "/esm/big.mjs?k=" + k + "&lines=10"; var requiredModule = writeBig("pending-http-require", "file-pending-http-require", LINES); var loading = import(origin + target); // Holds the JS thread until the server has answered, plus a margin for // the response to arrive, so its completion is already queued when // require() starts waiting. var deadline = performance.now() + 5000; while (serverRequestCount(origin, target) === 0 && performance.now() < deadline) {} expect(serverRequestCount(origin, target)).toBe(1); var until = performance.now() + 250; while (performance.now() < until) {} var required = require(requiredModule.path); expectWholeBody(required, "file-pending-http-require", LINES); expect((globalThis.__nsBigModuleEvaluations || {})[k]).toBeUndefined(); loading.then(function (mod) { expect(mod.id).toBe(k); expect(globalThis.__nsBigModuleEvaluations[k]).toBe(1); done(); }).catch(failWith(done)); }); it("resolves one module for concurrent imports from several call sites", function (done) { writeBig("concurrent", "file-concurrent", LINES); writeModule("concurrent-a", "export * as child from \"./concurrent.mjs\";\n"); writeModule("concurrent-b", "export * as child from \"./concurrent.mjs\";\n"); var spec = fixtureSpec + "/concurrent.mjs"; Promise.all([ import(spec), import(fixtureSpec + "/concurrent-a.mjs"), import(spec), import(fixtureSpec + "/concurrent-b.mjs"), ]) .then(function (mods) { expectWholeBody(mods[0], "file-concurrent", LINES); expect(mods[2]).toBe(mods[0]); expect(mods[1].child).toBe(mods[0]); expect(mods[3].child).toBe(mods[0]); done(); }).catch(failWith(done)); }); it("settles concurrent imports of a module after its top-level await", function (done) { writeModule("tla-shared", bigModule("file-tla-shared", LINES).body + "await new Promise(function (resolve) { setTimeout(resolve, 50); });\n" + "export const settled = true;\n"); var spec = fixtureSpec + "/tla-shared.mjs"; // Reads the export as each import settles: one that settles early sees // it in its temporal dead zone. function settledExport() { return import(spec).then(function (mod) { return mod.settled; }); } Promise.all([settledExport(), settledExport()]).then(function (values) { expect(values).toEqual([true, true]); done(); }).catch(failWith(done)); }); it("rejects a syntax error with the text a small module produces", function (done) { var small = writeBig("syntax-small", "file-syntax-small", 0, { error: true }); var large = writeBig("syntax-large", "file-syntax-large", LINES, { error: true }); function rejectionOf(module) { return import(module.spec).then(function () { return "resolved"; }, function (error) { return formatError(error).split(module.path).join(""); }); } Promise.all([rejectionOf(small), rejectionOf(large)]).then(function (texts) { expect(texts[0]).toContain("SyntaxError"); expect(texts[1]).toBe(texts[0]); done(); }).catch(failWith(done)); }); // Large enough that, outside the development flavor, the third load // consumes the code cache the second one left, on a background thread. it("loads an edited file's new source under a new query", function (done) { var module = writeBig("edited", "file-edited-1", CONSUME_LINES); var spec = module.spec; import(spec + "?v=1").then(function (mod) { expectWholeBody(mod, "file-edited-1", CONSUME_LINES); // Past the code cache's quiet period, so a cache of the first // source exists outside the development flavor. return delay(1500); }).then(function () { var edited = bigModule("file-edited-2", CONSUME_LINES + 7).body; expect(edited.length).toBeGreaterThan(CACHE_CONSUME_THRESHOLD); writeModule("edited", edited); return import(spec + "?v=2"); }).then(function (mod) { expectWholeBody(mod, "file-edited-2", CONSUME_LINES + 7); return isDebugBuild ? undefined : freshCodeCache(module.path); }).then(function () { return import(spec + "?v=3"); }).then(function (mod) { expectWholeBody(mod, "file-edited-2", CONSUME_LINES + 7, 2); done(); }).catch(failWith(done)); }); it("writes a code cache only outside the development flavor", function (done) { var module = writeBig("cache-probe", "file-cache-probe", LINES); import(module.spec).then(function (mod) { expectWholeBody(mod, "file-cache-probe", LINES); var deadline = Date.now() + 5000; function poll() { var entries = codeCacheEntries(module.path); if (entries.length > 0 || Date.now() > deadline) { expect(entries.length).toBe(isDebugBuild ? 0 : 1); for (var i = 0; i < entries.length; i++) { fileManager.removeItemAtPathError(entries[i], null); } done(); return; } setTimeout(poll, isDebugBuild ? 1000 : 100); } poll(); }).catch(failWith(done)); }); it("evaluates one loaded by a worker", function (done) { var module = writeBig("worker", "file-worker", LINES); var worker = new Worker("./fileModuleImportWorker.js"); worker.onmessage = function (msg) { if (msg.data === "loading") { return; } worker.terminate(); expect(msg.data).toBe("ok:file-worker:" + LINES); done(); }; worker.onerror = function (error) { worker.terminate(); expect("worker error: " + formatError(error)).toBe("ok"); done(); }; worker.postMessage(module.spec); }); it("starts a worker whose entry statically imports a large module", function (done) { writeBig("worker-entry-child", "file-worker-entry-child", LINES); writeModule("worker-entry", "import { id, count } from \"./worker-entry-child.mjs\";\n" + "postMessage(\"ok:\" + id + \":\" + count);\n"); var worker = new Worker("./esm/large-" + runId + "/worker-entry.mjs"); worker.onmessage = function (msg) { worker.terminate(); expect(msg.data).toBe("ok:file-worker-entry-child:" + LINES); done(); }; worker.onerror = function (error) { worker.terminate(); expect("worker error: " + formatError(error)).toBe("ok"); done(); }; }); it("survives workers terminated while their large modules load", function (done) { // Each worker is terminated a little later after issuing its import, // so the points fall before, during and after the background load. var MODULE_LINES = 20000; var STEPS = 12; var STEP_MS = 4; var spec = writeBig("terminated", "file-terminated", MODULE_LINES).spec; function importOnMain() { var module = writeBig("after-workers", "file-after-workers", LINES); import(module.spec).then(function (mod) { expectWholeBody(mod, "file-after-workers", LINES); done(); }).catch(failWith(done)); } function sweep(step) { if (step === STEPS) { importOnMain(); return; } var worker = new Worker("./fileModuleImportWorker.js"); var ended = false; function next() { if (!ended) { ended = true; worker.terminate(); sweep(step + 1); } } worker.onmessage = function (msg) { if (msg.data === "loading") { setTimeout(next, step * STEP_MS); } else { expect(String(msg.data)).toMatch(/^ok:file-terminated:/); next(); } }; worker.onerror = function (error) { fail("worker " + step + " errored: " + formatError(error)); next(); }; worker.postMessage(spec); } sweep(0); }, 60000); });