Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 63 additions & 5 deletions src/javascript/transpile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,16 +201,68 @@ function rewriteImportDeclarations(

const specifiers: string[] = [];
const imports: string[] = [];
const sources: string[] = [];
for (const node of declarations) {
output.delete(node.start, node.end + +(output.input[node.end] === "\n"));
specifiers.push(rewriteImportSpecifiers(node));
imports.push(`import(${annotatePath(resolve(getStringLiteralValue(node.source as StringLiteral)))})`);
const source = getStringLiteralValue(node.source as StringLiteral);
sources.push(source);
imports.push(`import(${annotatePath(resolve(source))})`);
}
if (declarations.length > 1) {
output.insertLeft(0, `const [${specifiers.join(", ")}] = await Promise.all([${imports.join(", ")}]);\n`);
} else if (declarations.length === 1) {
output.insertLeft(0, `const ${specifiers[0]} = await ${imports[0]};\n`);
if (declarations.length === 0) return;
// A named or default import that the module does not export must fail like a
// static import does, instead of silently binding undefined, so the module
// namespaces are inspected before they are destructured.
const names = declarations.map(findImportedNames);
const checked = names.some((names) => names.length > 0);
const modules = checked ? declarations.map((_, i) => unusedName(body, declarations.length > 1 ? `$module${i}` : "$module")) : specifiers; // prettier-ignore
let code =
declarations.length > 1
? `const [${modules.join(", ")}] = await Promise.all([${imports.join(", ")}]);\n`
: `const ${modules[0]} = await ${imports[0]};\n`;
if (checked) {
for (let i = 0; i < declarations.length; ++i) {
for (const name of names[i]) {
const message = `The requested module ${quote(sources[i])} does not provide an export named ${quote(name)}`;
code += `if (!(${JSON.stringify(name)} in ${modules[i]})) throw new SyntaxError(${JSON.stringify(message)});\n`;
}
}
code +=
declarations.length > 1
? `const [${specifiers.join(", ")}] = [${modules.join(", ")}];\n`
: `const ${specifiers[0]} = ${modules[0]};\n`;
}
output.insertLeft(0, code);
}

/** Returns the names that the default and named specifiers of the specified import declaration import. */
function findImportedNames(node: ImportDeclaration): string[] {
const names = new Set<string>();
for (const specifier of node.specifiers) {
if (isDefaultSpecifier(specifier)) {
names.add("default");
} else if (!isNamespaceSpecifier(specifier)) {
names.add(getImportedValue(specifier));
}
}
return Array.from(names);
}

/** Returns the specified name, suffixed as needed so that it is not used as an identifier in the specified node. */
function unusedName(node: Node, name: string): string {
const names = new Set<string>();
simple(node, {
Identifier(node) {
names.add(node.name);
}
});
while (names.has(name)) name += "_";
return name;
}

/** Returns the specified string as a single-quoted string literal, as browsers quote module and export names in this message. */
function quote(string: string): string {
return !/['"\\\n\r]/.test(string) ? `'${string}'` : JSON.stringify(string);
}

function rewriteImportSpecifiers(node: ImportDeclaration): string {
Expand All @@ -235,6 +287,12 @@ function getImportedName(node: ImportSpecifier): string {
return node.imported.type === "Identifier" ? node.imported.name : node.imported.raw!;
}

function getImportedValue(node: ImportSpecifier): string {
return node.imported.type === "Identifier"
? node.imported.name
: getStringLiteralValue(node.imported as StringLiteral);
}

function isDefaultSpecifier(
node: ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier
): node is ImportDefaultSpecifier {
Expand Down
3 changes: 3 additions & 0 deletions test/input/imports/static-mixed-import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import d, {"a-b" as ab, foo} from "./bar.js";

d(ab(foo));
4 changes: 4 additions & 0 deletions test/input/imports/static-namespace-import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import * as bar from "./bar.js";
import {foo} from "./other/foo.js";

bar.foo(foo);
5 changes: 5 additions & 0 deletions test/input/imports/static-shadowed-import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import * as bar from "./bar.js";
import {foo} from "./other/foo.js";

const $module0 = foo;
$module0 + $module1 + bar;
55 changes: 55 additions & 0 deletions test/javascript/transpile-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import assert from "node:assert";
import {readdirSync, statSync} from "node:fs";
import {mkdir, readFile, unlink, writeFile} from "node:fs/promises";
import {basename, join, resolve} from "node:path/posix";
import {pathToFileURL} from "node:url";
import {temporaryDirectoryTask} from "tempy";
import {isEnoent} from "../../src/error.js";
import {parseJavaScript} from "../../src/javascript/parse.js";
import type {TranspileModuleOptions} from "../../src/javascript/transpile.js";
Expand Down Expand Up @@ -95,6 +97,59 @@ describe("transpileJavaScript(input, options)", () => {
});
});

describe("the static imports of a JavaScript code block", () => {
// Runs the specified code block against a module at ./bar.js, and returns the result of the block.
async function run(
input: string,
module: string
): Promise<{status: "fulfilled"; value: any} | {status: "rejected"; error: any}> {
const node = parseJavaScript(input, {path: "block.js"});
const code = transpileJavaScript(node, {id: "0", path: "block.js", resolveImport: mockResolveImport});
return temporaryDirectoryTask(async (root) => {
await mkdir(join(root, "_import"));
await writeFile(join(root, "package.json"), '{"type":"module"}');
await writeFile(join(root, "_import", "bar.js"), module);
await writeFile(
join(root, "block.js"),
`const outcomes = [];\nconst define = ({body}) => outcomes.push(body().then((value) => ({status: "fulfilled", value}), (error) => ({status: "rejected", error})));\n${code}\nexport {outcomes};\n` // prettier-ignore
);
const {outcomes} = await import(pathToFileURL(join(root, "block.js")).href);
return outcomes[0];
});
}

it("throws a SyntaxError for a named import that the module does not export", async () => {
const outcome = await run('import {doesNotExist} from "./bar.js";\ndoesNotExist();', "export const foo = 1;\n"); // prettier-ignore
assert.strictEqual(outcome.status, "rejected");
assert.ok(outcome.error instanceof SyntaxError);
assert.strictEqual(outcome.error.message, "The requested module './bar.js' does not provide an export named 'doesNotExist'"); // prettier-ignore
});
it("throws a SyntaxError for a default import that the module does not export", async () => {
const outcome = await run('import foo from "./bar.js";\nfoo();', "export const foo = 1;\n");
assert.strictEqual(outcome.status, "rejected");
assert.ok(outcome.error instanceof SyntaxError);
assert.strictEqual(
outcome.error.message,
"The requested module './bar.js' does not provide an export named 'default'"
);
});
it("does not throw for an export whose value is undefined", async () => {
const outcome = await run('import {foo} from "./bar.js";\nif (foo !== undefined) throw new Error("foo should be undefined");', "export let foo;\n"); // prettier-ignore
assert.strictEqual(outcome.status, "fulfilled");
assert.deepStrictEqual(outcome.value, {foo: undefined});
});
it("does not throw for a namespace import", async () => {
const outcome = await run('import * as bar from "./bar.js";\nbar.foo();', "export const foo = () => 123;\n"); // prettier-ignore
assert.strictEqual(outcome.status, "fulfilled");
assert.strictEqual(typeof outcome.value.bar.foo, "function");
});
it("checks each import of a block", async () => {
const outcome = await run('import {foo} from "./bar.js";\nimport {doesNotExist} from "./bar.js";\nfoo();', "export const foo = 1;\n"); // prettier-ignore
assert.strictEqual(outcome.status, "rejected");
assert.strictEqual(outcome.error.message, "The requested module './bar.js' does not provide an export named 'doesNotExist'"); // prettier-ignore
});
});

async function testFile(target: string, path: string): Promise<string> {
const input = `import {FileAttachment} from "observablehq:stdlib";\nFileAttachment(${JSON.stringify(target)})`;
const output = await transpileModule(input, {root: "src", path});
Expand Down
4 changes: 3 additions & 1 deletion test/output/build/data-loaders/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
registerFile("./test.txt", {"name":"./test.txt","mimeType":"text/plain","path":"./_file/test.f2ca1bb6.txt","lastModified":/* ts */1706742000000,"size":5});

define({id: "05e74070", inputs: ["display"], outputs: ["test"], body: async (display) => {
const {test} = await import("./_import/import-test.3349a02d.js");
const $module = await import("./_import/import-test.3349a02d.js");
if (!("test" in $module)) throw new SyntaxError("The requested module './import-test.js' does not provide an export named 'test'");
const {test} = $module;

display(await test);
return {test};
Expand Down
5 changes: 4 additions & 1 deletion test/output/build/fetches/foo.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@
registerFile("./foo/foo-data.json", {"name":"./foo/foo-data.json","mimeType":"application/json","path":"./_file/foo/foo-data.67358ed8.json","lastModified":/* ts */1706742000000,"size":10});

define({id: "47a695da", inputs: ["display"], outputs: ["fooJsonData","fooCsvData"], body: async (display) => {
const {fooJsonData, fooCsvData} = await import("./_import/foo/foo.0cc12e18.js");
const $module = await import("./_import/foo/foo.0cc12e18.js");
if (!("fooJsonData" in $module)) throw new SyntaxError("The requested module '/foo/foo.js' does not provide an export named 'fooJsonData'");
if (!("fooCsvData" in $module)) throw new SyntaxError("The requested module '/foo/foo.js' does not provide an export named 'fooCsvData'");
const {fooJsonData, fooCsvData} = $module;

display(fooJsonData);
display(fooCsvData);
Expand Down
7 changes: 6 additions & 1 deletion test/output/build/fetches/top.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@
registerFile("./top-data.json", {"name":"./top-data.json","mimeType":"application/json","path":"./_file/top-data.67358ed8.json","lastModified":/* ts */1706742000000,"size":10});

define({id: "cb908c08", inputs: ["display"], outputs: ["fooCsvData","fooJsonData","topCsvData","topJsonData"], body: async (display) => {
const {fooCsvData, fooJsonData, topCsvData, topJsonData} = await import("./_import/top.bacf54cc.js");
const $module = await import("./_import/top.bacf54cc.js");
if (!("fooCsvData" in $module)) throw new SyntaxError("The requested module '/top.js' does not provide an export named 'fooCsvData'");
if (!("fooJsonData" in $module)) throw new SyntaxError("The requested module '/top.js' does not provide an export named 'fooJsonData'");
if (!("topCsvData" in $module)) throw new SyntaxError("The requested module '/top.js' does not provide an export named 'topCsvData'");
if (!("topJsonData" in $module)) throw new SyntaxError("The requested module '/top.js' does not provide an export named 'topJsonData'");
const {fooCsvData, fooJsonData, topCsvData, topJsonData} = $module;

display(fooJsonData);
display(fooCsvData);
Expand Down
9 changes: 7 additions & 2 deletions test/output/build/imports/foo/foo.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@
registerFile("./hello.txt", {"name":"./hello.txt","mimeType":"text/plain","path":"../_file/foo/hello.5891b5b5.txt","lastModified":/* ts */1706742000000,"size":6});

define({id: "261e010e", inputs: ["display","FileAttachment"], outputs: ["d3","bar","top"], body: async (display,FileAttachment) => {
const [d3, {bar}, {top}] = await Promise.all([import("../_npm/d3@7.8.5/cd372fb8.js"), import("../_import/bar/bar.4460ccc2.js"), import("../_import/top.160847a6.js")]);
const [$module0, $module1, $module2] = await Promise.all([import("../_npm/d3@7.8.5/cd372fb8.js"), import("../_import/bar/bar.4460ccc2.js"), import("../_import/top.160847a6.js")]);
if (!("bar" in $module1)) throw new SyntaxError("The requested module '../bar/bar.js' does not provide an export named 'bar'");
if (!("top" in $module2)) throw new SyntaxError("The requested module '/top.js' does not provide an export named 'top'");
const [d3, {bar}, {top}] = [$module0, $module1, $module2];

display(bar);
display(top);
Expand All @@ -38,7 +41,9 @@
}});

define({id: "ec24b17a", inputs: ["display"], outputs: ["foobar"], body: async (display) => {
const {foobar} = await import("./foo%20bar.js");
const $module = await import("./foo%20bar.js");
if (!("foobar" in $module)) throw new SyntaxError("The requested module './foo%20bar.js' does not provide an export named 'foobar'");
const {foobar} = $module;
display(foobar);
return {foobar};
}});
Expand Down
5 changes: 4 additions & 1 deletion test/output/build/jsr/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
import {define} from "./_observablehq/client.00000001.js";

define({id: "0e3025ad", inputs: ["display"], outputs: ["randomIntegerBetween","randomSeeded","prng"], body: async (display) => {
const {randomIntegerBetween, randomSeeded} = await import("./_jsr/@std/random@0.1.0/mod.e50195f4.js");
const $module = await import("./_jsr/@std/random@0.1.0/mod.e50195f4.js");
if (!("randomIntegerBetween" in $module)) throw new SyntaxError("The requested module 'jsr:@std/random' does not provide an export named 'randomIntegerBetween'");
if (!("randomSeeded" in $module)) throw new SyntaxError("The requested module 'jsr:@std/random' does not provide an export named 'randomSeeded'");
const {randomIntegerBetween, randomSeeded} = $module;

const prng = randomSeeded(1n);

Expand Down
4 changes: 3 additions & 1 deletion test/output/build/typescript/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@
}});

define({id: "5a5e524f", outputs: ["sum"], body: async () => {
const {sum} = await import("./_import/sum.fd55756b.js");
const $module = await import("./_import/sum.fd55756b.js");
if (!("sum" in $module)) throw new SyntaxError("The requested module './sum.js' does not provide an export named 'sum'");
const {sum} = $module;

return {sum};
}});
Expand Down
4 changes: 3 additions & 1 deletion test/output/imports/alias-import.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
define({id: "0", inputs: ["display"], outputs: ["bar"], body: async (display) => {
const {foo: bar} = await import("./_import/bar.js");
const $module = await import("./_import/bar.js");
if (!("foo" in $module)) throw new SyntaxError("The requested module './bar.js' does not provide an export named 'foo'");
const {foo: bar} = $module;

display(bar);
return {bar};
Expand Down
4 changes: 3 additions & 1 deletion test/output/imports/local-fetch-from-import.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
define({id: "0", inputs: ["display"], outputs: ["data"], body: async (display) => {
const {data} = await import("./_import/baz.js");
const $module = await import("./_import/baz.js");
if (!("data" in $module)) throw new SyntaxError("The requested module './baz.js' does not provide an export named 'data'");
const {data} = $module;

display(data);
return {data};
Expand Down
5 changes: 4 additions & 1 deletion test/output/imports/static-all-import.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
define({id: "0", outputs: ["foo","bar"], body: async () => {
const [{foo}, {bar}] = await Promise.all([import("./_import/foo.js"), import("./_import/bar.js")]);
const [$module0, $module1] = await Promise.all([import("./_import/foo.js"), import("./_import/bar.js")]);
if (!("foo" in $module0)) throw new SyntaxError("The requested module './foo.js' does not provide an export named 'foo'");
if (!("bar" in $module1)) throw new SyntaxError("The requested module './bar.js' does not provide an export named 'bar'");
const [{foo}, {bar}] = [$module0, $module1];

foo() + bar();
return {foo,bar};
Expand Down
4 changes: 3 additions & 1 deletion test/output/imports/static-hoisted-import.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
define({id: "0", outputs: ["confetti"], body: async () => {
const {default: confetti} = await import("https://cdn.jsdelivr.net/npm/canvas-confetti");
const $module = await import("https://cdn.jsdelivr.net/npm/canvas-confetti");
if (!("default" in $module)) throw new SyntaxError("The requested module 'npm:canvas-confetti' does not provide an export named 'default'");
const {default: confetti} = $module;
confetti();


Expand Down
4 changes: 3 additions & 1 deletion test/output/imports/static-import.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
define({id: "0", inputs: ["display"], outputs: ["foo"], body: async (display) => {
const {foo} = await import("./_import/bar.js");
const $module = await import("./_import/bar.js");
if (!("foo" in $module)) throw new SyntaxError("The requested module './bar.js' does not provide an export named 'foo'");
const {foo} = $module;

display(foo);
return {foo};
Expand Down
10 changes: 10 additions & 0 deletions test/output/imports/static-mixed-import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
define({id: "0", outputs: ["d","ab","foo"], body: async () => {
const $module = await import("./_import/bar.js");
if (!("default" in $module)) throw new SyntaxError("The requested module './bar.js' does not provide an export named 'default'");
if (!("a-b" in $module)) throw new SyntaxError("The requested module './bar.js' does not provide an export named 'a-b'");
if (!("foo" in $module)) throw new SyntaxError("The requested module './bar.js' does not provide an export named 'foo'");
const {default: d, "a-b": ab, foo} = $module;

d(ab(foo));
return {d,ab,foo};
}});
Loading