-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathrollup.ts
197 lines (185 loc) · 7.82 KB
/
rollup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import {extname} from "node:path/posix";
import {nodeResolve} from "@rollup/plugin-node-resolve";
import type {CallExpression} from "acorn";
import {simple} from "acorn-walk";
import {build} from "esbuild";
import type {AstNode, OutputChunk, Plugin, ResolveIdResult} from "rollup";
import {rollup} from "rollup";
import esbuild from "rollup-plugin-esbuild";
import {getStylePath} from "./files.js";
import type {StringLiteral} from "./javascript/source.js";
import {getStringLiteralValue, isStringLiteral} from "./javascript/source.js";
import {resolveNpmImport} from "./npm.js";
import {getObservableUiOrigin} from "./observableApiClient.js";
import {isPathImport, relativePath} from "./path.js";
import {Sourcemap} from "./sourcemap.js";
import {THEMES, renderTheme} from "./theme.js";
const STYLE_MODULES = {
"observablehq:default.css": getStylePath("default.css"),
...Object.fromEntries(THEMES.map(({name, path}) => [`observablehq:theme-${name}.css`, path]))
};
// These libraries are currently bundled in to a wrapper.
const BUNDLED_MODULES = [
"@observablehq/inputs", // observablehq:stdlib/inputs.js
"@observablehq/inspector", // observablehq:runtime.js
"@observablehq/runtime", // observablehq:runtime.js
"isoformat", // observablehq:runtime.js
"minisearch" // observablehq:search.js
];
function rewriteInputsNamespace(code: string) {
return code.replace(/\b__ns__\b/g, "inputs-3a86ea");
}
export async function bundleStyles({
minify = false,
path,
theme,
resolve
}: {
minify?: boolean;
path?: string;
theme?: string[];
resolve?: ({path}: {path: string}) => {path: string; external: true} | undefined;
}): Promise<string> {
const result = await build({
bundle: true,
...(path ? {entryPoints: [path]} : {stdin: {contents: renderTheme(theme!), loader: "css"}}),
write: false,
plugins: [
{
name: "resolve CSS assets",
setup(build) {
build.onResolve({filter: /^\w+:\/\//}, ({path}) => ({path, external: true}));
if (resolve) build.onResolve({filter: /./}, resolve);
}
}
],
minify,
alias: STYLE_MODULES
});
const text = result.outputFiles[0].text;
return rewriteInputsNamespace(text); // TODO only for inputs
}
export async function rollupClient(
input: string,
root: string,
path: string,
{define, keepNames, minify}: {define?: {[key: string]: string}; keepNames?: boolean; minify?: boolean} = {}
): Promise<string> {
const bundle = await rollup({
input,
external: [/^https:/],
plugins: [
nodeResolve({resolveOnly: BUNDLED_MODULES}),
importResolve(input, root, path),
esbuild({
format: "esm",
platform: "browser",
target: ["es2022", "chrome96", "firefox96", "safari16", "node18"],
exclude: [], // don’t exclude node_modules
keepNames,
minify,
define: {
"global.__minisearch": '"./minisearch.json"',
"process.env.OBSERVABLE_ORIGIN": JSON.stringify(String(getObservableUiOrigin()).replace(/\/$/, "")),
...define
}
}),
importMetaResolve(root, path)
],
onwarn(message, warn) {
if (message.code === "CIRCULAR_DEPENDENCY") return;
warn(message);
}
});
try {
const output = await bundle.generate({format: "es"});
let code = output.output.find((o): o is OutputChunk => o.type === "chunk")!.code; // TODO don’t assume one chunk?
code = rewriteTypeScriptImports(code);
code = rewriteInputsNamespace(code); // TODO only for inputs
return code;
} finally {
await bundle.close();
}
}
// For reasons not entirely clear (to me), when we resolve a relative import to
// a TypeScript file, such as resolving observablehq:stdlib/foo to
// ./src/client/stdlib/foo.js, Rollup (or rollup-plugin-esbuild?) notices that
// there is a foo.ts and rewrites the import to foo.ts. But the imported file at
// runtime won’t be TypeScript and will only exist at foo.js, so here we rewrite
// the import back to what it was supposed to be. This is a dirty hack but it
// gets the job done. 🤷 https://github.com/observablehq/framework/issues/478
function rewriteTypeScriptImports(code: string): string {
return code.replace(/(?<=\bimport\(([`'"])[\w./]+)\.ts(?=\1\))/g, ".js");
}
function importResolve(input: string, root: string, path: string): Plugin {
async function resolve(specifier: string | AstNode): Promise<ResolveIdResult> {
return typeof specifier !== "string" || specifier === input
? null
: specifier.startsWith("observablehq:")
? {id: relativePath(path, `/_observablehq/${specifier.slice("observablehq:".length)}${extname(specifier) ? "" : ".js"}`), external: true} // prettier-ignore
: specifier === "npm:@observablehq/runtime"
? {id: relativePath(path, "/_observablehq/runtime.js"), external: true}
: specifier === "npm:@observablehq/stdlib" || specifier === "@observablehq/stdlib"
? {id: relativePath(path, "/_observablehq/stdlib.js"), external: true}
: specifier === "npm:@observablehq/dot"
? {id: relativePath(path, "/_observablehq/stdlib/dot.js"), external: true} // TODO publish to npm
: specifier === "npm:@observablehq/duckdb"
? {id: relativePath(path, "/_observablehq/stdlib/duckdb.js"), external: true} // TODO publish to npm
: specifier === "npm:@observablehq/inputs"
? {id: relativePath(path, "/_observablehq/stdlib/inputs.js"), external: true} // TODO publish to npm
: specifier === "npm:@observablehq/mermaid"
? {id: relativePath(path, "/_observablehq/stdlib/mermaid.js"), external: true} // TODO publish to npm
: specifier === "npm:@observablehq/tex"
? {id: relativePath(path, "/_observablehq/stdlib/tex.js"), external: true} // TODO publish to npm
: specifier === "npm:@observablehq/sqlite"
? {id: relativePath(path, "/_observablehq/stdlib/sqlite.js"), external: true} // TODO publish to npm
: specifier === "npm:@observablehq/xlsx"
? {id: relativePath(path, "/_observablehq/stdlib/xlsx.js"), external: true} // TODO publish to npm
: specifier === "npm:@observablehq/zip"
? {id: relativePath(path, "/_observablehq/stdlib/zip.js"), external: true} // TODO publish to npm
: specifier.startsWith("npm:")
? {id: relativePath(path, await resolveNpmImport(root, specifier.slice("npm:".length))), external: true}
: !/^[a-z]:\\/i.test(specifier) && !isPathImport(specifier) && !BUNDLED_MODULES.includes(specifier) // e.g., inputs.js imports "htl"
? {id: relativePath(path, await resolveNpmImport(root, specifier)), external: true}
: null;
}
return {
name: "resolve-import",
resolveId: resolve,
resolveDynamicImport: resolve
};
}
function importMetaResolve(root: string, path: string): Plugin {
return {
name: "resolve-import-meta-resolve",
async transform(code) {
const program = this.parse(code);
const resolves: CallExpression[] = [];
simple(program, {
CallExpression(node) {
if (
node.callee.type === "MemberExpression" &&
node.callee.object.type === "MetaProperty" &&
node.callee.property.type === "Identifier" &&
node.callee.property.name === "resolve" &&
node.arguments.length === 1 &&
isStringLiteral(node.arguments[0])
) {
resolves.push(node);
}
}
});
if (!resolves.length) return null;
const output = new Sourcemap(code);
for (const node of resolves) {
const source = node.arguments[0];
const specifier = getStringLiteralValue(source as StringLiteral);
if (specifier.startsWith("npm:")) {
const resolution = relativePath(path, await resolveNpmImport(root, specifier.slice("npm:".length)));
output.replaceLeft(source.start, source.end, JSON.stringify(resolution));
}
}
return {code: String(output)};
}
};
}