@@ -4,7 +4,9 @@ import {parseCell} from "@observablehq/parser";
44import type { Identifier , ImportDeclaration , Node } from "acorn" ;
55import { rewriteFileExpressions } from "./files.js" ;
66import { flatMapImportSpecifiers , rewriteImportDeclarations } from "./imports.js" ;
7+ import { resolveNpmImport } from "./imports/npm.js" ;
78import { Sourcemap } from "./sourcemap.js" ;
9+ import { getStringLiteralValue , isStringLiteral } from "./strings.js" ;
810import type { TranspiledJavaScript , TranspileOptions } from "./transpile.js" ;
911import { transpileJavaScript } from "./transpile.js" ;
1012import { simple } from "./walk.js" ;
@@ -19,6 +21,7 @@ export function transpileObservable(
1921 if ( cell . tag ) throw new Error ( "tagged ojs cells are not supported" ) ;
2022 const output = new Sourcemap ( input ) . trim ( ) ;
2123 rewriteSpecialReferences ( output , cell . body ) ;
24+ rewriteDynamicImports ( output , cell . body ) ;
2225 if ( options ?. resolveFiles ) rewriteFileExpressions ( output , cell . body ) ;
2326 const inputs = Array . from ( new Set ( cell . references . map ( asReference ) ) ) ;
2427 let start = "" ;
@@ -92,6 +95,24 @@ function transformObservableImport(body: ImportDeclaration): void {
9295 ] ;
9396}
9497
98+ /**
99+ * Rewrite a bare dynamic import such as import("d3") to a CDN URL, like
100+ * import("https://cdn.jsdelivr.net/npm/d3/+esm"), using the same resolution as
101+ * static imports. Protocol (npm:, https:, …) and local imports are left alone.
102+ */
103+ function rewriteDynamicImports ( output : Sourcemap , body : Node ) : void {
104+ simple ( body , {
105+ ImportExpression ( { source} ) {
106+ if ( ! isStringLiteral ( source ) ) return ;
107+ let value = getStringLiteralValue ( source ) ;
108+ if ( / ^ ( \w + : | \. ? \. ? \/ ) / . test ( value ) ) return ;
109+ if ( / \. ( j s | m j s | c j s ) $ / . test ( value ) ) value += "/+esm" ;
110+ const resolution = resolveNpmImport ( `npm:${ value } ` ) ;
111+ output . replaceLeft ( source . start , source . end , JSON . stringify ( resolution ) ) ;
112+ }
113+ } ) ;
114+ }
115+
95116/** Rewrite viewof x ↦ viewof$x, and mutable x ↦ mutable$x.value. */
96117function rewriteSpecialReferences ( output : Sourcemap , body : Node ) : void {
97118 simple ( body , {
0 commit comments