@hpcc-js/observablehq-compiler 3.7.8 → 3.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/compiler.ts CHANGED
@@ -1,340 +1,340 @@
1
-
2
- import { type Notebook, type Definition, compileNotebook, fixRelativeUrl, isRelativePath, obfuscatedImport } from "./kit/index.ts";
3
- import { ohq, splitModule } from "./observable-shim.ts";
4
- import { parseCell, ParsedImportCell } from "./cst.ts";
5
- import { Writer } from "./writer.ts";
6
- import { encodeBacktick, fetchEx, ojs2notebook, omd2notebook } from "./util.ts";
7
-
8
- // Inspector Factory ---
9
- export type InspectorFactoryEx = (name: string | undefined, id: string | number) => Inspector;
10
-
11
- export interface Inspector {
12
- _node?: HTMLDivElement;
13
- pending(): void;
14
- fulfilled(value: any): void;
15
- rejected(error: Error): void;
16
- }
17
-
18
- // Module ---
19
-
20
- interface ImportDefine {
21
- (runtime: ohq.Runtime, inspector?: InspectorFactoryEx): ohq.Module;
22
- delete: () => void;
23
- write: (w: Writer) => void;
24
- }
25
-
26
- async function importFile(relativePath: string, baseUrl: string) {
27
- const path = fixRelativeUrl(relativePath, baseUrl);
28
- const content = await fetchEx(path).then(r => r.text());
29
- let notebook: ohq.Notebook;
30
- if (relativePath.endsWith(".ojsnb")) {
31
- notebook = JSON.parse(content);
32
- } else if (relativePath.endsWith(".ojs")) {
33
- notebook = ojs2notebook(content);
34
- } else if (relativePath.endsWith(".omd")) {
35
- notebook = omd2notebook(content);
36
- } else {
37
- console.warn(`Unknown file type: ${relativePath}, assuming .ojsnb`);
38
- notebook = JSON.parse(content);
39
- }
40
- const retVal: ImportDefine = compile(notebook, { baseUrl }) as any;
41
- retVal.delete = () => { };
42
- retVal.write = (w: Writer) => {
43
- w.import(path);
44
- };
45
- return retVal;
46
- }
47
-
48
- // Import precompiled notebook from observable ---
49
- async function importCompiledNotebook(partial: string) {
50
- const url = `https://api.observablehq.com/${partial[0] === "@" ? partial : `d/${partial}`}.js?v=3`;
51
- let impMod = {
52
- default: function (runtime: ohq.Runtime, inspector?: InspectorFactoryEx): ohq.Module | undefined {
53
- return undefined;
54
- } as any
55
- };
56
- try {
57
- impMod = await obfuscatedImport(url);
58
- } catch (e) {
59
- }
60
- const retVal: ImportDefine = impMod.default;
61
- retVal.delete = () => { };
62
- retVal.write = (w: Writer) => {
63
- w.import(url);
64
- };
65
- return retVal;
66
- }
67
-
68
- // Recursive notebook parsing and compiling
69
- async function importNotebook(partial: string) {
70
- const url = `https://api.observablehq.com/document/${partial}`;
71
- const notebook = fetchEx(url)
72
- .then(r => {
73
- return r.json();
74
- }).catch(e => {
75
- console.error(url);
76
- console.error(e);
77
- });
78
- const retVal: ImportDefine = compile(await notebook) as any;
79
- retVal.delete = () => { };
80
- retVal.write = (w: Writer) => {
81
- w.import(url);
82
- };
83
- return retVal;
84
- }
85
-
86
- async function createModule(node: ohq.Node, parsed: ParsedImportCell, text: string, { baseUrl, importMode }: CompileOptions) {
87
- const otherModule = isRelativePath(parsed.src) ?
88
- await importFile(parsed.src, baseUrl ?? "") :
89
- importMode === "recursive" ?
90
- await importNotebook(parsed.src) :
91
- await importCompiledNotebook(parsed.src);
92
-
93
- const importVariables: ImportVariableFunc[] = [];
94
- const variables: VariableFunc[] = [];
95
- parsed.specifiers.forEach(spec => {
96
- const viewof = spec.view ? "viewof " : "";
97
- importVariables.push(createImportVariable(viewof + spec.name, viewof + spec.alias));
98
- if (spec.view) {
99
- importVariables.push(createImportVariable(spec.name, spec.alias));
100
- }
101
- });
102
-
103
- const retVal = (runtime: ohq.Runtime, main: ohq.Module, inspector?: InspectorFactoryEx) => {
104
-
105
- let mod = runtime.module(otherModule);
106
- if (parsed.injections.length) {
107
- mod = mod.derive(parsed.injections, main);
108
- }
109
- variables.forEach(v => v(main, inspector));
110
- importVariables.forEach(v => v(main, mod));
111
- return mod;
112
- };
113
- retVal.importVariables = importVariables;
114
- retVal.variables = variables;
115
- retVal.delete = () => {
116
- importVariables.forEach(v => v.delete());
117
- variables.forEach(v => v.delete());
118
- otherModule.delete();
119
- };
120
- retVal.write = (w: Writer) => {
121
- otherModule.write(w);
122
- w.importDefine(parsed);
123
- };
124
- return retVal;
125
- }
126
- type ModuleFunc = Awaited<ReturnType<typeof createModule>>;
127
-
128
- // Variable ---
129
- function createVariable(node: ohq.Node, inspect: boolean, name?: string, inputs?: string[], definition?: any, inline = false) {
130
-
131
- let i: ohq.Inspector | undefined;
132
- let v: ohq.Variable | undefined;
133
-
134
- const retVal = (module: ohq.Module, inspector?: InspectorFactoryEx) => {
135
- if (inspect && inspector) {
136
- i = inspector(name, node.id);
137
- }
138
- v = module.variable(i);
139
- if (arguments.length > 1) {
140
- try {
141
- v.define(name, inputs, definition);
142
- } catch (e: any) {
143
- console.error(e?.message);
144
- }
145
- }
146
- if (node.pinned) {
147
- v = inspector ? module.variable(inspector(name, node.id)) : module.variable();
148
- try {
149
- v.define(undefined, ["md"], (md: any) => {
150
- return md`\`\`\`js
151
- ${node.value}
152
- \`\`\``;
153
- });
154
- } catch (e: any) {
155
- console.error(e?.message);
156
- }
157
- }
158
- return v;
159
- };
160
- retVal.delete = () => {
161
- try {
162
- i?._node?.remove();
163
- } catch (e) {
164
- }
165
- i = undefined;
166
- try {
167
- v?.delete();
168
- } catch (e) {
169
- }
170
- v = undefined;
171
- };
172
- retVal.write = (w: Writer) => {
173
- if (inline) {
174
- w.define({ id: name, inputs, func: definition }, inspect, true);
175
- } else {
176
- const id = w.function({ id: name, func: definition });
177
- w.define({ id: name, inputs, func: definition }, inspect, false, id);
178
- }
179
- };
180
- return retVal;
181
- }
182
- type VariableFunc = ReturnType<typeof createVariable>;
183
-
184
- function createImportVariable(name: string, alias?: string) {
185
-
186
- let v: ohq.Variable;
187
-
188
- const retVal = (main: ohq.Module, otherModule: ohq.Module) => {
189
- v = main.variable();
190
- if (alias === undefined) {
191
- v.import(name, otherModule);
192
- } else {
193
- v.import(name, alias, otherModule);
194
- }
195
- };
196
-
197
- retVal.delete = () => {
198
- v?.delete();
199
- };
200
- return retVal;
201
- }
202
- type ImportVariableFunc = ReturnType<typeof createImportVariable>;
203
-
204
- // Cell ---
205
- async function createCell(node: ohq.Node, options: CompileOptions) {
206
- const modules: ModuleFunc[] = [];
207
- const variables: VariableFunc[] = [];
208
- try {
209
- const text = node.mode && node.mode !== "js" ? `${node.mode}\`${encodeBacktick(node.value)}\`` : node.value;
210
- const parsedModule = splitModule(text);
211
- for (const cell of parsedModule) {
212
- const parsed = parseCell(cell.text, options.baseUrl ?? "");
213
- switch (parsed.type) {
214
- case "import":
215
- modules.push(await createModule(node, parsed, cell.text, options));
216
- break;
217
- case "viewof":
218
- variables.push(createVariable(node, true, parsed.variable.id, parsed.variable.inputs, parsed.variable.func));
219
- variables.push(createVariable(node, false, parsed.variableValue.id, parsed.variableValue.inputs, parsed.variableValue.func, true));
220
- break;
221
- case "mutable":
222
- variables.push(createVariable(node, false, parsed.initial.id, parsed.initial.inputs, parsed.initial.func));
223
- variables.push(createVariable(node, false, parsed.variable.id, parsed.variable.inputs, parsed.variable.func));
224
- variables.push(createVariable(node, true, parsed.variableValue.id, parsed.variableValue.inputs, parsed.variableValue.func, true));
225
- break;
226
- case "variable":
227
- variables.push(createVariable(node, true, parsed.id, parsed.inputs, parsed.func));
228
- break;
229
- }
230
- }
231
- } catch (e: any) {
232
- variables.push(createVariable(node, true, undefined, [], e.message ?? "Unkown error"));
233
- }
234
-
235
- const retVal = (runtime: ohq.Runtime, main: ohq.Module, inspector?: InspectorFactoryEx) => {
236
- modules.forEach(imp => imp(runtime, main, inspector));
237
- variables.forEach(v => v(main, inspector));
238
- };
239
- retVal.id = node.id;
240
- retVal.modules = modules;
241
- retVal.variables = variables;
242
- retVal.delete = () => {
243
- variables.forEach(v => v.delete());
244
- modules.forEach(mod => mod.delete());
245
- };
246
- retVal.write = (w: Writer) => {
247
- modules.forEach(imp => imp.write(w));
248
- variables.forEach(v => v.write(w));
249
- };
250
- return retVal;
251
- }
252
- export type CellFunc = Awaited<ReturnType<typeof createCell>>;
253
-
254
- // File ---
255
- function createFile(file: ohq.File, options: CompileOptions): [string, any] {
256
- function toString() {
257
- // TODO Double check url should not be URL?
258
- return (globalThis as any).url ?? "";
259
- }
260
- return [file.name, { url: new URL(fixRelativeUrl(file.url, options.baseUrl ?? "")), mimeType: file.mime_type, toString }];
261
- }
262
- type FileFunc = ReturnType<typeof createFile>;
263
-
264
- // Interpret ---
265
- export interface CompileOptions {
266
- baseUrl?: string;
267
- importMode?: "recursive" | "precompiled";
268
- }
269
- export function notebook(_files: ohq.File[] = [], _cells: CellFunc[] = [], { baseUrl = ".", importMode = "precompiled" }: CompileOptions = {}) {
270
- const files: FileFunc[] = _files.map(f => createFile(f, { baseUrl, importMode }));
271
- const fileAttachments = new Map<string, any>(files);
272
- const cells = new Map<string | number, CellFunc>(_cells.map(c => [c.id, c]));
273
-
274
- const retVal = (runtime: ohq.Runtime, inspector?: InspectorFactoryEx): ohq.Module => {
275
- const main = runtime.module();
276
- main.builtin("FileAttachment", runtime.fileAttachments(name => {
277
- return fileAttachments.get(name) ?? { url: new URL(fixRelativeUrl(name, baseUrl)), mimeType: null };
278
- }));
279
- main.builtin("fetchEx", fetchEx);
280
-
281
- cells.forEach(cell => {
282
- cell(runtime, main, inspector);
283
- });
284
- return main;
285
- };
286
- retVal.fileAttachments = fileAttachments;
287
- retVal.cells = cells;
288
- retVal.set = async (n: ohq.Node): Promise<CellFunc> => {
289
- const cell = await createCell(n, { baseUrl, importMode });
290
- retVal.delete(cell.id);
291
- cells.set(cell.id, cell);
292
- return cell;
293
- };
294
- retVal.get = (id: string | number): CellFunc | undefined => {
295
- return cells.get(id);
296
- };
297
- retVal.delete = (id: string | number): boolean => {
298
- const cell = cells.get(id);
299
- if (cell) {
300
- cell.delete();
301
- return cells.delete(id);
302
- }
303
- return false;
304
- };
305
- retVal.clear = () => {
306
- cells.forEach(cell => cell.delete());
307
- cells.clear();
308
- };
309
- retVal.write = (w: Writer) => {
310
- w.files(_files);
311
- cells.forEach(cell => cell.write(w));
312
- };
313
- retVal.toString = (w = new Writer()) => {
314
- retVal.write(w);
315
- return w.toString().trim();
316
- };
317
- return retVal;
318
- }
319
- type NotebookFunc = ReturnType<typeof notebook>;
320
-
321
- export function isNotebookKit(value: any): value is Notebook {
322
- return !!value && Array.isArray(value.cells);
323
- }
324
-
325
- export function isOhqNotebook(value: any): value is ohq.Notebook {
326
- return !!value && Array.isArray(value.nodes);
327
- }
328
- export async function compile(notebookOrOjs: Notebook): Promise<Definition[]>;
329
- export async function compile(notebookOrOjs: ohq.Notebook, options?: CompileOptions): Promise<NotebookFunc>;
330
- export async function compile(notebookOrOjs: string, options?: CompileOptions): Promise<NotebookFunc>;
331
- export async function compile(notebookOrOjs: Notebook | ohq.Notebook | string, { baseUrl = ".", importMode = "precompiled" }: CompileOptions = {}) {
332
- if (isNotebookKit(notebookOrOjs)) {
333
- return compileNotebook(notebookOrOjs);
334
- } else if (typeof notebookOrOjs === "string") {
335
- notebookOrOjs = ojs2notebook(notebookOrOjs);
336
- }
337
- const _cells: CellFunc[] = await Promise.all(notebookOrOjs.nodes.map(n => createCell(n, { baseUrl, importMode })));
338
- return notebook(notebookOrOjs.files, _cells, { baseUrl, importMode });
339
- }
340
- export type CompileFunc = Awaited<ReturnType<typeof compile>>;
1
+
2
+ import { type Notebook, type Definition, compileNotebook, fixRelativeUrl, isRelativePath, obfuscatedImport } from "./kit/index.ts";
3
+ import { ohq, splitModule } from "./observable-shim.ts";
4
+ import { parseCell, ParsedImportCell } from "./cst.ts";
5
+ import { Writer } from "./writer.ts";
6
+ import { encodeBacktick, fetchEx, ojs2notebook, omd2notebook } from "./util.ts";
7
+
8
+ // Inspector Factory ---
9
+ export type InspectorFactoryEx = (name: string | undefined, id: string | number) => Inspector;
10
+
11
+ export interface Inspector {
12
+ _node?: HTMLDivElement;
13
+ pending(): void;
14
+ fulfilled(value: any): void;
15
+ rejected(error: Error): void;
16
+ }
17
+
18
+ // Module ---
19
+
20
+ interface ImportDefine {
21
+ (runtime: ohq.Runtime, inspector?: InspectorFactoryEx): ohq.Module;
22
+ delete: () => void;
23
+ write: (w: Writer) => void;
24
+ }
25
+
26
+ async function importFile(relativePath: string, baseUrl: string) {
27
+ const path = fixRelativeUrl(relativePath, baseUrl);
28
+ const content = await fetchEx(path).then(r => r.text());
29
+ let notebook: ohq.Notebook;
30
+ if (relativePath.endsWith(".ojsnb")) {
31
+ notebook = JSON.parse(content);
32
+ } else if (relativePath.endsWith(".ojs")) {
33
+ notebook = ojs2notebook(content);
34
+ } else if (relativePath.endsWith(".omd")) {
35
+ notebook = omd2notebook(content);
36
+ } else {
37
+ console.warn(`Unknown file type: ${relativePath}, assuming .ojsnb`);
38
+ notebook = JSON.parse(content);
39
+ }
40
+ const retVal: ImportDefine = compile(notebook, { baseUrl }) as any;
41
+ retVal.delete = () => { };
42
+ retVal.write = (w: Writer) => {
43
+ w.import(path);
44
+ };
45
+ return retVal;
46
+ }
47
+
48
+ // Import precompiled notebook from observable ---
49
+ async function importCompiledNotebook(partial: string) {
50
+ const url = `https://api.observablehq.com/${partial[0] === "@" ? partial : `d/${partial}`}.js?v=3`;
51
+ let impMod = {
52
+ default: function (runtime: ohq.Runtime, inspector?: InspectorFactoryEx): ohq.Module | undefined {
53
+ return undefined;
54
+ } as any
55
+ };
56
+ try {
57
+ impMod = await obfuscatedImport(url);
58
+ } catch (e) {
59
+ }
60
+ const retVal: ImportDefine = impMod.default;
61
+ retVal.delete = () => { };
62
+ retVal.write = (w: Writer) => {
63
+ w.import(url);
64
+ };
65
+ return retVal;
66
+ }
67
+
68
+ // Recursive notebook parsing and compiling
69
+ async function importNotebook(partial: string) {
70
+ const url = `https://api.observablehq.com/document/${partial}`;
71
+ const notebook = fetchEx(url)
72
+ .then(r => {
73
+ return r.json();
74
+ }).catch(e => {
75
+ console.error(url);
76
+ console.error(e);
77
+ });
78
+ const retVal: ImportDefine = compile(await notebook) as any;
79
+ retVal.delete = () => { };
80
+ retVal.write = (w: Writer) => {
81
+ w.import(url);
82
+ };
83
+ return retVal;
84
+ }
85
+
86
+ async function createModule(node: ohq.Node, parsed: ParsedImportCell, text: string, { baseUrl, importMode }: CompileOptions) {
87
+ const otherModule = isRelativePath(parsed.src) ?
88
+ await importFile(parsed.src, baseUrl ?? "") :
89
+ importMode === "recursive" ?
90
+ await importNotebook(parsed.src) :
91
+ await importCompiledNotebook(parsed.src);
92
+
93
+ const importVariables: ImportVariableFunc[] = [];
94
+ const variables: VariableFunc[] = [];
95
+ parsed.specifiers.forEach(spec => {
96
+ const viewof = spec.view ? "viewof " : "";
97
+ importVariables.push(createImportVariable(viewof + spec.name, viewof + spec.alias));
98
+ if (spec.view) {
99
+ importVariables.push(createImportVariable(spec.name, spec.alias));
100
+ }
101
+ });
102
+
103
+ const retVal = (runtime: ohq.Runtime, main: ohq.Module, inspector?: InspectorFactoryEx) => {
104
+
105
+ let mod = runtime.module(otherModule);
106
+ if (parsed.injections.length) {
107
+ mod = mod.derive(parsed.injections, main);
108
+ }
109
+ variables.forEach(v => v(main, inspector));
110
+ importVariables.forEach(v => v(main, mod));
111
+ return mod;
112
+ };
113
+ retVal.importVariables = importVariables;
114
+ retVal.variables = variables;
115
+ retVal.delete = () => {
116
+ importVariables.forEach(v => v.delete());
117
+ variables.forEach(v => v.delete());
118
+ otherModule.delete();
119
+ };
120
+ retVal.write = (w: Writer) => {
121
+ otherModule.write(w);
122
+ w.importDefine(parsed);
123
+ };
124
+ return retVal;
125
+ }
126
+ type ModuleFunc = Awaited<ReturnType<typeof createModule>>;
127
+
128
+ // Variable ---
129
+ function createVariable(node: ohq.Node, inspect: boolean, name?: string, inputs?: string[], definition?: any, inline = false) {
130
+
131
+ let i: ohq.Inspector | undefined;
132
+ let v: ohq.Variable | undefined;
133
+
134
+ const retVal = (module: ohq.Module, inspector?: InspectorFactoryEx) => {
135
+ if (inspect && inspector) {
136
+ i = inspector(name, node.id);
137
+ }
138
+ v = module.variable(i);
139
+ if (arguments.length > 1) {
140
+ try {
141
+ v.define(name, inputs, definition);
142
+ } catch (e: any) {
143
+ console.error(e?.message);
144
+ }
145
+ }
146
+ if (node.pinned) {
147
+ v = inspector ? module.variable(inspector(name, node.id)) : module.variable();
148
+ try {
149
+ v.define(undefined, ["md"], (md: any) => {
150
+ return md`\`\`\`js
151
+ ${node.value}
152
+ \`\`\``;
153
+ });
154
+ } catch (e: any) {
155
+ console.error(e?.message);
156
+ }
157
+ }
158
+ return v;
159
+ };
160
+ retVal.delete = () => {
161
+ try {
162
+ i?._node?.remove();
163
+ } catch (e) {
164
+ }
165
+ i = undefined;
166
+ try {
167
+ v?.delete();
168
+ } catch (e) {
169
+ }
170
+ v = undefined;
171
+ };
172
+ retVal.write = (w: Writer) => {
173
+ if (inline) {
174
+ w.define({ id: name, inputs, func: definition }, inspect, true);
175
+ } else {
176
+ const id = w.function({ id: name, func: definition });
177
+ w.define({ id: name, inputs, func: definition }, inspect, false, id);
178
+ }
179
+ };
180
+ return retVal;
181
+ }
182
+ type VariableFunc = ReturnType<typeof createVariable>;
183
+
184
+ function createImportVariable(name: string, alias?: string) {
185
+
186
+ let v: ohq.Variable;
187
+
188
+ const retVal = (main: ohq.Module, otherModule: ohq.Module) => {
189
+ v = main.variable();
190
+ if (alias === undefined) {
191
+ v.import(name, otherModule);
192
+ } else {
193
+ v.import(name, alias, otherModule);
194
+ }
195
+ };
196
+
197
+ retVal.delete = () => {
198
+ v?.delete();
199
+ };
200
+ return retVal;
201
+ }
202
+ type ImportVariableFunc = ReturnType<typeof createImportVariable>;
203
+
204
+ // Cell ---
205
+ async function createCell(node: ohq.Node, options: CompileOptions) {
206
+ const modules: ModuleFunc[] = [];
207
+ const variables: VariableFunc[] = [];
208
+ try {
209
+ const text = node.mode && node.mode !== "js" ? `${node.mode}\`${encodeBacktick(node.value)}\`` : node.value;
210
+ const parsedModule = splitModule(text);
211
+ for (const cell of parsedModule) {
212
+ const parsed = parseCell(cell.text, options.baseUrl ?? "");
213
+ switch (parsed.type) {
214
+ case "import":
215
+ modules.push(await createModule(node, parsed, cell.text, options));
216
+ break;
217
+ case "viewof":
218
+ variables.push(createVariable(node, true, parsed.variable.id, parsed.variable.inputs, parsed.variable.func));
219
+ variables.push(createVariable(node, false, parsed.variableValue.id, parsed.variableValue.inputs, parsed.variableValue.func, true));
220
+ break;
221
+ case "mutable":
222
+ variables.push(createVariable(node, false, parsed.initial.id, parsed.initial.inputs, parsed.initial.func));
223
+ variables.push(createVariable(node, false, parsed.variable.id, parsed.variable.inputs, parsed.variable.func));
224
+ variables.push(createVariable(node, true, parsed.variableValue.id, parsed.variableValue.inputs, parsed.variableValue.func, true));
225
+ break;
226
+ case "variable":
227
+ variables.push(createVariable(node, true, parsed.id, parsed.inputs, parsed.func));
228
+ break;
229
+ }
230
+ }
231
+ } catch (e: any) {
232
+ variables.push(createVariable(node, true, undefined, [], e.message ?? "Unkown error"));
233
+ }
234
+
235
+ const retVal = (runtime: ohq.Runtime, main: ohq.Module, inspector?: InspectorFactoryEx) => {
236
+ modules.forEach(imp => imp(runtime, main, inspector));
237
+ variables.forEach(v => v(main, inspector));
238
+ };
239
+ retVal.id = node.id;
240
+ retVal.modules = modules;
241
+ retVal.variables = variables;
242
+ retVal.delete = () => {
243
+ variables.forEach(v => v.delete());
244
+ modules.forEach(mod => mod.delete());
245
+ };
246
+ retVal.write = (w: Writer) => {
247
+ modules.forEach(imp => imp.write(w));
248
+ variables.forEach(v => v.write(w));
249
+ };
250
+ return retVal;
251
+ }
252
+ export type CellFunc = Awaited<ReturnType<typeof createCell>>;
253
+
254
+ // File ---
255
+ function createFile(file: ohq.File, options: CompileOptions): [string, any] {
256
+ function toString() {
257
+ // TODO Double check url should not be URL?
258
+ return (globalThis as any).url ?? "";
259
+ }
260
+ return [file.name, { url: new URL(fixRelativeUrl(file.url, options.baseUrl ?? "")), mimeType: file.mime_type, toString }];
261
+ }
262
+ type FileFunc = ReturnType<typeof createFile>;
263
+
264
+ // Interpret ---
265
+ export interface CompileOptions {
266
+ baseUrl?: string;
267
+ importMode?: "recursive" | "precompiled";
268
+ }
269
+ export function notebook(_files: ohq.File[] = [], _cells: CellFunc[] = [], { baseUrl = ".", importMode = "precompiled" }: CompileOptions = {}) {
270
+ const files: FileFunc[] = _files.map(f => createFile(f, { baseUrl, importMode }));
271
+ const fileAttachments = new Map<string, any>(files);
272
+ const cells = new Map<string | number, CellFunc>(_cells.map(c => [c.id, c]));
273
+
274
+ const retVal = (runtime: ohq.Runtime, inspector?: InspectorFactoryEx): ohq.Module => {
275
+ const main = runtime.module();
276
+ main.builtin("FileAttachment", runtime.fileAttachments(name => {
277
+ return fileAttachments.get(name) ?? { url: new URL(fixRelativeUrl(name, baseUrl)), mimeType: null };
278
+ }));
279
+ main.builtin("fetchEx", fetchEx);
280
+
281
+ cells.forEach(cell => {
282
+ cell(runtime, main, inspector);
283
+ });
284
+ return main;
285
+ };
286
+ retVal.fileAttachments = fileAttachments;
287
+ retVal.cells = cells;
288
+ retVal.set = async (n: ohq.Node): Promise<CellFunc> => {
289
+ const cell = await createCell(n, { baseUrl, importMode });
290
+ retVal.delete(cell.id);
291
+ cells.set(cell.id, cell);
292
+ return cell;
293
+ };
294
+ retVal.get = (id: string | number): CellFunc | undefined => {
295
+ return cells.get(id);
296
+ };
297
+ retVal.delete = (id: string | number): boolean => {
298
+ const cell = cells.get(id);
299
+ if (cell) {
300
+ cell.delete();
301
+ return cells.delete(id);
302
+ }
303
+ return false;
304
+ };
305
+ retVal.clear = () => {
306
+ cells.forEach(cell => cell.delete());
307
+ cells.clear();
308
+ };
309
+ retVal.write = (w: Writer) => {
310
+ w.files(_files);
311
+ cells.forEach(cell => cell.write(w));
312
+ };
313
+ retVal.toString = (w = new Writer()) => {
314
+ retVal.write(w);
315
+ return w.toString().trim();
316
+ };
317
+ return retVal;
318
+ }
319
+ type NotebookFunc = ReturnType<typeof notebook>;
320
+
321
+ export function isNotebookKit(value: any): value is Notebook {
322
+ return !!value && Array.isArray(value.cells);
323
+ }
324
+
325
+ export function isOhqNotebook(value: any): value is ohq.Notebook {
326
+ return !!value && Array.isArray(value.nodes);
327
+ }
328
+ export async function compile(notebookOrOjs: Notebook): Promise<Definition[]>;
329
+ export async function compile(notebookOrOjs: ohq.Notebook, options?: CompileOptions): Promise<NotebookFunc>;
330
+ export async function compile(notebookOrOjs: string, options?: CompileOptions): Promise<NotebookFunc>;
331
+ export async function compile(notebookOrOjs: Notebook | ohq.Notebook | string, { baseUrl = ".", importMode = "precompiled" }: CompileOptions = {}) {
332
+ if (isNotebookKit(notebookOrOjs)) {
333
+ return compileNotebook(notebookOrOjs);
334
+ } else if (typeof notebookOrOjs === "string") {
335
+ notebookOrOjs = ojs2notebook(notebookOrOjs);
336
+ }
337
+ const _cells: CellFunc[] = await Promise.all(notebookOrOjs.nodes.map(n => createCell(n, { baseUrl, importMode })));
338
+ return notebook(notebookOrOjs.files, _cells, { baseUrl, importMode });
339
+ }
340
+ export type CompileFunc = Awaited<ReturnType<typeof compile>>;