@manifest-configuration-language/browser 0.3.21 → 0.3.23

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/index.js DELETED
@@ -1,807 +0,0 @@
1
- import PQueue from "p-queue";
2
- import {
3
- maxProjectBytes,
4
- maxProjectFileBytes,
5
- maxProjectFiles,
6
- maxProjectPathDepth,
7
- maxProjectPathLength,
8
- maxRenameNameLength,
9
- maxSourceBytes,
10
- maxSourceMapBytes,
11
- } from "./limits.js";
12
-
13
- export {
14
- maxProjectBytes,
15
- maxProjectFileBytes,
16
- maxProjectFiles,
17
- maxProjectPathDepth,
18
- maxProjectPathLength,
19
- maxRenameNameLength,
20
- maxSourceBytes,
21
- maxSourceMapBytes,
22
- };
23
-
24
- export function isValidProjectPath(value) {
25
- if (
26
- typeof value !== "string" ||
27
- value.length === 0 ||
28
- value.startsWith("/") ||
29
- /^[a-z]:/i.test(value) ||
30
- value.includes("\\") ||
31
- value.includes("\0")
32
- ) {
33
- return false;
34
- }
35
- let pathLength = 0;
36
- let pathDepth = 1;
37
- for (const character of value) {
38
- if (++pathLength > maxProjectPathLength) return false;
39
- if (character === "/" && ++pathDepth > maxProjectPathDepth) return false;
40
- }
41
- return value.split("/").every((part) => part !== "" && part !== "." && part !== "..");
42
- }
43
-
44
- export function isValidProjectFileSet(paths) {
45
- if (!Array.isArray(paths)) return false;
46
- const files = new Set();
47
- const directories = new Set();
48
- for (const filePath of paths) {
49
- if (!isValidProjectPath(filePath) || files.has(filePath) || directories.has(filePath))
50
- return false;
51
- let separator = filePath.indexOf("/");
52
- while (separator !== -1) {
53
- const directory = filePath.slice(0, separator);
54
- if (files.has(directory)) return false;
55
- directories.add(directory);
56
- separator = filePath.indexOf("/", separator + 1);
57
- }
58
- files.add(filePath);
59
- }
60
- return true;
61
- }
62
-
63
- const defaultInitializationTimeoutMs = 30_000;
64
- const defaultOperationTimeoutMs = 10_000;
65
- const operationPriorities = {
66
- render: 30,
67
- evaluate: 30,
68
- check: 30,
69
- parse: 20,
70
- format: 20,
71
- rename: 20,
72
- renameFileImports: 20,
73
- references: 20,
74
- definition: 20,
75
- completion: 20,
76
- hover: 20,
77
- lint: 10,
78
- };
79
- const latestOnlyOperations = new Set(["completion", "hover", "lint"]);
80
- const requestPriorities = { interactive: 40, background: 0 };
81
- const wasmURL = new URL("../dist/mcl.wasm", import.meta.url).href;
82
- const wasmExecURL = new URL("../dist/wasm_exec.js", import.meta.url).href;
83
-
84
- export class MclRuntimeError extends Error {
85
- constructor(error) {
86
- super(error.message);
87
- this.name = "MclRuntimeError";
88
- this.code = error.code;
89
- this.path = error.path;
90
- this.line = error.line;
91
- this.column = error.column;
92
- this.endLine = error.endLine;
93
- this.endColumn = error.endColumn;
94
- this.related = error.related;
95
- }
96
- }
97
-
98
- export function createMclRuntime(options = {}) {
99
- const workerFactory =
100
- options.workerFactory ??
101
- (() => new Worker(new URL("./worker.js", import.meta.url), { type: "module" }));
102
- const initializationTimeoutMs = options.initializationTimeoutMs ?? defaultInitializationTimeoutMs;
103
- let worker;
104
- let ready;
105
- let disposed = false;
106
- const queue = new PQueue({ concurrency: 1 });
107
- queue.on("error", () => {});
108
- const queueSignals = new Set();
109
- const latestPending = new Map();
110
- let sequence = 0;
111
- let workerGeneration = 0;
112
- let workerProject;
113
- let stopCurrent;
114
- let stopInitialization;
115
-
116
- function emitStatus(status, details = {}) {
117
- try {
118
- Promise.resolve(options.onStatus?.({ status, workerGeneration, ...details })).catch(() => {});
119
- } catch {
120
- // Observability callbacks must not affect runtime behavior.
121
- }
122
- }
123
-
124
- function emitOperation(operation, startedAt, outcome, details = {}) {
125
- try {
126
- const durationMs = Math.max(0, performance.now() - startedAt);
127
- Promise.resolve(options.onOperation?.({
128
- operation,
129
- durationMs,
130
- queueWaitMs: details.executionStartedAt !== undefined
131
- ? Math.max(0, details.executionStartedAt - startedAt)
132
- : durationMs,
133
- executionDurationMs: details.executionDurationMs ?? 0,
134
- ...(details.wasmDurationMs === undefined
135
- ? {}
136
- : { wasmDurationMs: details.wasmDurationMs }),
137
- ...(details.workerGeneration === undefined
138
- ? {}
139
- : { workerGeneration: details.workerGeneration }),
140
- outcome,
141
- })).catch(() => {});
142
- } catch {
143
- // Observability callbacks must not affect runtime behavior.
144
- }
145
- }
146
-
147
- function enqueue(operation, run, signal, scope = "runtime", requestedPriority, timing) {
148
- if (signal?.aborted) return Promise.reject(signal.reason ?? abortError());
149
- const priority =
150
- requestPriorities[requestedPriority] ?? operationPriorities[operation] ?? 0;
151
- const key = (name) => JSON.stringify([scope, name]);
152
- const pendingKey = key(operation);
153
- const pendingGroup = () => {
154
- let group = latestPending.get(pendingKey);
155
- if (!group) {
156
- group = new Map();
157
- latestPending.set(pendingKey, group);
158
- }
159
- return group;
160
- };
161
- const removePending = (pendingPriority, pending) => {
162
- const group = latestPending.get(pendingKey);
163
- if (group?.get(pendingPriority) !== pending) return;
164
- group.delete(pendingPriority);
165
- if (group.size === 0) latestPending.delete(pendingKey);
166
- };
167
- const supersedePending = (name, maximumPriority, message) => {
168
- const groupKey = key(name);
169
- const group = latestPending.get(groupKey);
170
- if (!group) return;
171
- for (const [pendingPriority, pending] of group) {
172
- if (pendingPriority > maximumPriority) continue;
173
- group.delete(pendingPriority);
174
- pending.controller.abort(new DOMException(message, "AbortError"));
175
- }
176
- if (group.size === 0) latestPending.delete(groupKey);
177
- };
178
-
179
- if (["render", "evaluate", "check"].includes(operation)) {
180
- supersedePending("lint", priority, "An explicit run replaced this pending lint");
181
- } else if (priority > requestPriorities.background && operation !== "lint") {
182
- supersedePending(
183
- "lint",
184
- requestPriorities.background,
185
- "An interactive operation replaced this pending background lint",
186
- );
187
- }
188
-
189
- const queueController = new AbortController();
190
- const pending = { controller: queueController, started: false };
191
- if (latestOnlyOperations.has(operation)) {
192
- supersedePending(operation, priority, "A newer operation replaced this request");
193
- pendingGroup().set(priority, pending);
194
- }
195
-
196
- queueSignals.add(queueController);
197
- const abortWhileQueued = () => {
198
- if (!pending.started) queueController.abort(signal.reason ?? abortError());
199
- };
200
- signal?.addEventListener("abort", abortWhileQueued, { once: true });
201
-
202
- return queue
203
- .add(
204
- async () => {
205
- pending.started = true;
206
- if (latestOnlyOperations.has(operation)) removePending(priority, pending);
207
- if (timing) timing.executionStartedAt = performance.now();
208
- try {
209
- return await run();
210
- } finally {
211
- if (timing) {
212
- timing.executionDurationMs = Math.max(
213
- 0,
214
- performance.now() - timing.executionStartedAt,
215
- );
216
- }
217
- }
218
- },
219
- { priority, signal: queueController.signal },
220
- )
221
- .finally(() => {
222
- signal?.removeEventListener("abort", abortWhileQueued);
223
- queueSignals.delete(queueController);
224
- if (latestOnlyOperations.has(operation)) removePending(priority, pending);
225
- });
226
- }
227
-
228
- function abortError() {
229
- return new DOMException("The operation was aborted", "AbortError");
230
- }
231
-
232
- function startWorker() {
233
- if (disposed) return Promise.reject(new Error("MCL runtime has been disposed"));
234
- if (ready) return ready;
235
- const initializationStartedAt = performance.now();
236
- const currentWorker = workerFactory();
237
- worker = currentWorker;
238
- workerGeneration++;
239
- workerProject = undefined;
240
- let lastStatus;
241
- const reportStatus = (status) => {
242
- if (lastStatus === status) return;
243
- lastStatus = status;
244
- if (status === "ready" || status === "error") {
245
- emitStatus(status, {
246
- initializationDurationMs: Math.max(0, performance.now() - initializationStartedAt),
247
- });
248
- } else {
249
- emitStatus(status);
250
- }
251
- };
252
- let resolveReady;
253
- let rejectReady;
254
- let initialized = false;
255
- const initialization = new Promise((resolve, reject) => {
256
- resolveReady = resolve;
257
- rejectReady = reject;
258
- });
259
- ready = initialization;
260
- const timer = setTimeout(
261
- () => fail(new Error("MCL WebAssembly initialization timed out")),
262
- initializationTimeoutMs,
263
- );
264
- const onMessage = (event) => {
265
- if (event.data?.type === "status") {
266
- reportStatus(event.data.status);
267
- } else if (event.data?.type === "ready") {
268
- initialized = true;
269
- reportStatus("ready");
270
- clearTimeout(timer);
271
- currentWorker.removeEventListener("message", onMessage);
272
- currentWorker.removeEventListener("error", onError);
273
- if (stopInitialization === fail) stopInitialization = undefined;
274
- resolveReady();
275
- } else if (event.data?.type === "fatal") {
276
- fail(new Error(event.data.message || "MCL WebAssembly initialization failed"));
277
- }
278
- };
279
- const onError = (event) => {
280
- reportStatus("error");
281
- fail(new Error(event.message || "MCL worker failed"));
282
- };
283
- function fail(error) {
284
- if (!initialized) reportStatus("error");
285
- clearTimeout(timer);
286
- currentWorker.removeEventListener("message", onMessage);
287
- currentWorker.removeEventListener("error", onError);
288
- currentWorker.terminate();
289
- if (worker === currentWorker) {
290
- worker = undefined;
291
- ready = undefined;
292
- }
293
- if (stopInitialization === fail) stopInitialization = undefined;
294
- rejectReady(error);
295
- }
296
- stopInitialization = fail;
297
- try {
298
- currentWorker.addEventListener("message", onMessage);
299
- currentWorker.addEventListener("error", onError);
300
- currentWorker.postMessage({ type: "configure", wasmURL, wasmExecURL });
301
- } catch (error) {
302
- fail(error);
303
- }
304
- return initialization;
305
- }
306
-
307
- async function waitUntilReady(signal) {
308
- if (!signal) return startWorker();
309
- if (signal.aborted) throw new DOMException("The operation was aborted", "AbortError");
310
- let onAbort;
311
- try {
312
- await Promise.race([
313
- startWorker(),
314
- new Promise((_, reject) => {
315
- onAbort = () => {
316
- stopInitialization?.(new DOMException("The operation was aborted", "AbortError"));
317
- };
318
- signal.addEventListener("abort", onAbort, { once: true });
319
- }),
320
- ]);
321
- } finally {
322
- signal.removeEventListener("abort", onAbort);
323
- }
324
- }
325
-
326
- async function syncProjectToWorker(project, requestOptions, currentWorker, currentGeneration) {
327
- const previous = workerProject;
328
- const reset = !previous || previous.id !== project.id;
329
- const previousFiles = reset ? Object.create(null) : previous.snapshot.files;
330
- const updates = Object.create(null);
331
- const binaryFiles = Object.create(null);
332
- const transferables = [];
333
- const deleted = [];
334
- for (const [filePath, content] of Object.entries(project.snapshot.files)) {
335
- if (
336
- !reset &&
337
- Object.hasOwn(previousFiles, filePath) &&
338
- sameContent(previousFiles[filePath], content)
339
- )
340
- continue;
341
- if (typeof content === "string") {
342
- updates[filePath] = { encoding: "utf8", content };
343
- } else {
344
- const copy = new Uint8Array(content);
345
- updates[filePath] = { encoding: "binary" };
346
- binaryFiles[filePath] = copy;
347
- transferables.push(copy.buffer);
348
- }
349
- }
350
- if (!reset) {
351
- for (const filePath of Object.keys(previousFiles)) {
352
- if (!Object.hasOwn(project.snapshot.files, filePath)) deleted.push(filePath);
353
- }
354
- }
355
- if (!reset && Object.keys(updates).length === 0 && deleted.length === 0) return;
356
-
357
- const requestId = ++sequence;
358
- const update = JSON.stringify({ reset, files: updates, deleted });
359
- await new Promise((resolve, reject) => {
360
- let settled = false;
361
- const cleanup = () => {
362
- currentWorker.removeEventListener("message", onMessage);
363
- currentWorker.removeEventListener("error", onError);
364
- requestOptions.signal?.removeEventListener("abort", onAbort);
365
- };
366
- const finish = (callback, value) => {
367
- if (settled) return;
368
- settled = true;
369
- cleanup();
370
- if (stopCurrent === stop) stopCurrent = undefined;
371
- callback(value);
372
- };
373
- const onMessage = (event) => {
374
- if (worker !== currentWorker || workerGeneration !== currentGeneration) return;
375
- const response = event.data;
376
- if (response?.type !== "project-updated" || response.requestId !== requestId) return;
377
- if (!response.value.ok) finish(reject, new MclRuntimeError(response.value.error));
378
- else {
379
- workerProject = { id: project.id, snapshot: project.snapshot };
380
- finish(resolve);
381
- }
382
- };
383
- const stop = (error) => {
384
- finish(reject, error);
385
- currentWorker.terminate();
386
- if (worker === currentWorker) {
387
- worker = undefined;
388
- ready = undefined;
389
- workerProject = undefined;
390
- }
391
- };
392
- const onError = (event) => stop(new Error(event.message || "MCL worker failed"));
393
- const onAbort = () => stop(new DOMException("The operation was aborted", "AbortError"));
394
- currentWorker.addEventListener("message", onMessage);
395
- currentWorker.addEventListener("error", onError);
396
- requestOptions.signal?.addEventListener("abort", onAbort, { once: true });
397
- stopCurrent = stop;
398
- if (requestOptions.signal?.aborted) return onAbort();
399
- try {
400
- currentWorker.postMessage(
401
- { type: "project-update", requestId, projectId: project.id, update, binaryFiles },
402
- transferables,
403
- );
404
- } catch (error) {
405
- stop(error);
406
- }
407
- });
408
- }
409
-
410
- async function execute(
411
- operation,
412
- source,
413
- files,
414
- requestOptions = {},
415
- entrypoint = "main.mcl",
416
- position,
417
- project,
418
- ) {
419
- if (operation === "renameFileImports") {
420
- const { oldPath, newPath } = requestOptions;
421
- if (
422
- !isValidProjectPath(oldPath) ||
423
- !oldPath.endsWith(".mcl") ||
424
- !isValidProjectPath(newPath) ||
425
- !newPath.endsWith(".mcl")
426
- ) {
427
- throw new TypeError("oldPath and newPath must be valid project-relative MCL paths");
428
- }
429
- if (oldPath === newPath)
430
- throw new TypeError("oldPath and newPath must be distinct");
431
- }
432
- const signal = requestOptions.signal;
433
- if (signal?.aborted) throw new DOMException("The operation was aborted", "AbortError");
434
- const startedAt = performance.now();
435
- const timing = {};
436
- let operationWorkerGeneration;
437
- const run = async () => {
438
- if (disposed) throw new Error("MCL runtime has been disposed");
439
- if (requestOptions.signal?.aborted)
440
- throw new DOMException("The operation was aborted", "AbortError");
441
- const timeoutMs =
442
- requestOptions.timeoutMs ?? options.operationTimeoutMs ?? defaultOperationTimeoutMs;
443
- const timeoutError = new MclRuntimeError({
444
- code: "MCL-WASM-TIMEOUT",
445
- message: "MCL operation timed out",
446
- });
447
- let timer;
448
- try {
449
- if (timeoutMs <= 0) throw timeoutError;
450
- timer = setTimeout(() => {
451
- if (stopCurrent) stopCurrent(timeoutError);
452
- else stopInitialization?.(timeoutError);
453
- }, timeoutMs);
454
- await waitUntilReady(requestOptions.signal);
455
- if (requestOptions.signal?.aborted)
456
- throw new DOMException("The operation was aborted", "AbortError");
457
- const currentWorker = worker;
458
- const currentGeneration = workerGeneration;
459
- operationWorkerGeneration = currentGeneration;
460
- if (project) {
461
- await syncProjectToWorker(
462
- project,
463
- requestOptions,
464
- currentWorker,
465
- currentGeneration,
466
- timeoutError,
467
- );
468
- }
469
- const preparedFiles = project
470
- ? undefined
471
- : prepareFilesForTransfer(source, files, entrypoint);
472
- const requestId = ++sequence;
473
- const completeWasmTiming = () => {
474
- if (timing.wasmStartedAt === undefined || timing.wasmDurationMs !== undefined) return;
475
- timing.wasmDurationMs = Math.max(0, performance.now() - timing.wasmStartedAt);
476
- };
477
- return await new Promise((resolve, reject) => {
478
- let settled = false;
479
- const cleanup = () => {
480
- clearTimeout(timer);
481
- currentWorker.removeEventListener("message", onMessage);
482
- currentWorker.removeEventListener("error", onError);
483
- requestOptions.signal?.removeEventListener("abort", onAbort);
484
- };
485
- const finish = (callback, value) => {
486
- if (settled) return;
487
- settled = true;
488
- cleanup();
489
- if (stopCurrent === stop) stopCurrent = undefined;
490
- callback(value);
491
- };
492
- const onMessage = (event) => {
493
- if (worker !== currentWorker || workerGeneration !== currentGeneration) return;
494
- const response = event.data;
495
- if (response?.type !== "response" || response.requestId !== requestId) return;
496
- completeWasmTiming();
497
- if (!response.value.ok) finish(reject, new MclRuntimeError(response.value.error));
498
- else if (operation === "lint")
499
- finish(resolve, { operation, diagnostics: response.value.result });
500
- else finish(resolve, { operation, ...response.value.result });
501
- };
502
- const onError = (event) => stop(new Error(event.message || "MCL worker failed"));
503
- const onAbort = () => stop(new DOMException("The operation was aborted", "AbortError"));
504
- const stop = (error) => {
505
- completeWasmTiming();
506
- finish(reject, error);
507
- currentWorker.terminate();
508
- if (worker === currentWorker) {
509
- worker = undefined;
510
- ready = undefined;
511
- }
512
- };
513
- currentWorker.addEventListener("message", onMessage);
514
- currentWorker.addEventListener("error", onError);
515
- requestOptions.signal?.addEventListener("abort", onAbort, { once: true });
516
- stopCurrent = stop;
517
- try {
518
- const message = {
519
- type: "run",
520
- requestId,
521
- operation,
522
- source,
523
- entrypoint,
524
- position,
525
- newName: requestOptions.newName,
526
- oldPath: requestOptions.oldPath,
527
- newPath: requestOptions.newPath,
528
- };
529
- if (project) message.projectId = project.id;
530
- else message.files = preparedFiles.files;
531
- timing.wasmStartedAt = performance.now();
532
- currentWorker.postMessage(message, preparedFiles?.transferables ?? []);
533
- } catch (error) {
534
- stop(error);
535
- }
536
- });
537
- } catch (error) {
538
- clearTimeout(timer);
539
- throw error;
540
- }
541
- };
542
- try {
543
- const result = await enqueue(
544
- operation,
545
- run,
546
- signal,
547
- project?.id ?? "runtime",
548
- requestOptions.priority,
549
- timing,
550
- );
551
- emitOperation(operation, startedAt, "success", {
552
- ...timing,
553
- workerGeneration: operationWorkerGeneration,
554
- });
555
- return result;
556
- } catch (error) {
557
- emitOperation(operation, startedAt, error?.name === "AbortError" ? "aborted" : "error", {
558
- ...timing,
559
- workerGeneration: operationWorkerGeneration,
560
- });
561
- throw error;
562
- }
563
- }
564
-
565
- function warmUp(requestOptions = {}) {
566
- const signal = requestOptions.signal;
567
- if (signal?.aborted)
568
- return Promise.reject(new DOMException("The operation was aborted", "AbortError"));
569
- const run = async () => {
570
- if (disposed) throw new Error("MCL runtime has been disposed");
571
- if (signal?.aborted) throw new DOMException("The operation was aborted", "AbortError");
572
- const timeoutMs = requestOptions.timeoutMs ?? initializationTimeoutMs;
573
- const timeoutError = new MclRuntimeError({
574
- code: "MCL-WASM-TIMEOUT",
575
- message: "MCL WebAssembly initialization timed out",
576
- });
577
- let timer;
578
- try {
579
- if (timeoutMs <= 0) throw timeoutError;
580
- timer = setTimeout(() => stopInitialization?.(timeoutError), timeoutMs);
581
- await waitUntilReady(signal);
582
- } finally {
583
- clearTimeout(timer);
584
- }
585
- };
586
- return enqueue("warmUp", run, signal, "runtime", requestOptions.priority);
587
- }
588
-
589
- function openProject(files) {
590
- const snapshot = createProjectSnapshot(files);
591
- const id = `mcl-project-${++sequence}`;
592
- return makeProject(id, snapshot);
593
- }
594
-
595
- function sameContent(left, right) {
596
- if (left === right) return true;
597
- if (typeof left !== typeof right) return false;
598
- if (typeof left === "string") return left === right;
599
- if (left.byteLength !== right.byteLength) return false;
600
- for (let index = 0; index < left.byteLength; index++) {
601
- if (left[index] !== right[index]) return false;
602
- }
603
- return true;
604
- }
605
-
606
- function createProjectSnapshot(files, previous) {
607
- const entries = Object.entries(files ?? {});
608
- if (entries.length === 0)
609
- throw new TypeError("Project must contain at least one MCL source file");
610
- if (entries.length > maxProjectFiles)
611
- throw new RangeError(`Project has more than ${maxProjectFiles} files`);
612
- if (!isValidProjectFileSet(entries.map(([filePath]) => filePath)))
613
- throw new TypeError(
614
- "Project file paths must be valid and cannot conflict with a file or directory path",
615
- );
616
- let totalBytes = 0;
617
- const projectFiles = Object.create(null);
618
- const fileSizes = Object.create(null);
619
- for (const [filePath, input] of entries) {
620
- if (typeof input !== "string" && !(input instanceof Uint8Array))
621
- throw new TypeError(`Project file ${filePath} must be a string or Uint8Array`);
622
- const previousContent = previous?.files[filePath];
623
- const unchanged = previousContent !== undefined && sameContent(previousContent, input);
624
- const content = unchanged
625
- ? previousContent
626
- : typeof input === "string"
627
- ? input
628
- : new Uint8Array(input);
629
- const fileBytes = unchanged
630
- ? previous.sizes[filePath]
631
- : typeof content === "string"
632
- ? new TextEncoder().encode(content).byteLength
633
- : content.byteLength;
634
- if (!unchanged && fileBytes > maxProjectFileBytes)
635
- throw new RangeError(
636
- `Project file ${filePath} exceeds the ${maxProjectFileBytes}-byte limit`,
637
- );
638
- totalBytes += fileBytes;
639
- if (totalBytes > maxProjectBytes)
640
- throw new RangeError(`Project files exceed the ${maxProjectBytes}-byte limit`);
641
- projectFiles[filePath] = content;
642
- fileSizes[filePath] = fileBytes;
643
- }
644
- const sourcePaths = Object.keys(projectFiles)
645
- .filter((filePath) => filePath.endsWith(".mcl"))
646
- .sort();
647
- if (sourcePaths.length === 0)
648
- throw new TypeError("Project must contain at least one MCL source file");
649
- const defaultEntrypoint = Object.hasOwn(projectFiles, "main.mcl")
650
- ? "main.mcl"
651
- : sourcePaths.length === 1
652
- ? sourcePaths[0]
653
- : undefined;
654
- return Object.freeze({
655
- files: Object.freeze(projectFiles),
656
- sizes: Object.freeze(fileSizes),
657
- defaultEntrypoint,
658
- });
659
- }
660
-
661
- function makeProject(id, snapshot) {
662
- const runProjectOperation = async (operation, requestOptions = {}) => {
663
- const entrypoint = requestOptions.entrypoint ?? snapshot.defaultEntrypoint;
664
- if (!entrypoint)
665
- throw new TypeError("Set entrypoint when the project has multiple MCL source files");
666
- if (!isSafeRelativePath(entrypoint) || !Object.hasOwn(snapshot.files, entrypoint))
667
- throw new TypeError(`Project entrypoint does not exist: ${entrypoint}`);
668
- const entry = snapshot.files[entrypoint];
669
- const source =
670
- typeof entry === "string" ? entry : new TextDecoder("utf-8", { fatal: true }).decode(entry);
671
- const sourceBytes = new TextEncoder().encode(source).byteLength;
672
- if (sourceBytes > maxSourceBytes)
673
- throw new RangeError(`Source exceeds the ${maxSourceBytes}-byte limit`);
674
- return execute(
675
- operation,
676
- source,
677
- undefined,
678
- requestOptions,
679
- entrypoint,
680
- requestOptions.position,
681
- { id, snapshot },
682
- );
683
- };
684
- return Object.freeze({
685
- update: (nextFiles) => makeProject(id, createProjectSnapshot(nextFiles, snapshot)),
686
- parse: (requestOptions) => runProjectOperation("parse", requestOptions),
687
- lint: (requestOptions) => runProjectOperation("lint", requestOptions),
688
- complete: (requestOptions) => runProjectOperation("completion", requestOptions),
689
- definition: (requestOptions) => runProjectOperation("definition", requestOptions),
690
- hover: (requestOptions) => runProjectOperation("hover", requestOptions),
691
- references: (requestOptions) => runProjectOperation("references", requestOptions),
692
- rename: (requestOptions) => runProjectOperation("rename", requestOptions),
693
- renameFileImports: (requestOptions) =>
694
- runProjectOperation("renameFileImports", requestOptions),
695
- format: (requestOptions) => runProjectOperation("format", requestOptions),
696
- check: (requestOptions) => runProjectOperation("check", requestOptions),
697
- evaluate: (requestOptions) => runProjectOperation("evaluate", requestOptions),
698
- render: (requestOptions) => runProjectOperation("render", requestOptions),
699
- });
700
- }
701
-
702
- function isSafeRelativePath(filePath) {
703
- return isValidProjectPath(filePath);
704
- }
705
-
706
- function prepareFilesForTransfer(source, files, entrypoint) {
707
- if (!isSafeRelativePath(entrypoint))
708
- throw new TypeError(`Invalid project entrypoint: ${entrypoint}`);
709
- const sourceBytes = new TextEncoder().encode(source).byteLength;
710
- if (sourceBytes > maxSourceBytes)
711
- throw new RangeError(`Source exceeds the ${maxSourceBytes}-byte limit`);
712
- const entries = Object.entries(files ?? {});
713
- if (entries.length + 1 > maxProjectFiles)
714
- throw new RangeError(`Project has more than ${maxProjectFiles} files`);
715
- let totalBytes = sourceBytes;
716
- const transferredFiles = Object.create(null);
717
- const transferables = [];
718
- for (const [filePath, content] of entries) {
719
- if (!isSafeRelativePath(filePath) || filePath === entrypoint)
720
- throw new TypeError(`Invalid project file path: ${filePath}`);
721
- if (typeof content === "string") {
722
- const fileBytes = new TextEncoder().encode(content).byteLength;
723
- if (fileBytes > maxProjectFileBytes)
724
- throw new RangeError(
725
- `Project file ${filePath} exceeds the ${maxProjectFileBytes}-byte limit`,
726
- );
727
- totalBytes += fileBytes;
728
- transferredFiles[filePath] = content;
729
- } else if (content instanceof Uint8Array) {
730
- if (content.byteLength > maxProjectFileBytes)
731
- throw new RangeError(
732
- `Project file ${filePath} exceeds the ${maxProjectFileBytes}-byte limit`,
733
- );
734
- totalBytes += content.byteLength;
735
- const copy = new Uint8Array(content);
736
- transferredFiles[filePath] = copy;
737
- transferables.push(copy.buffer);
738
- } else {
739
- throw new TypeError(`Project file ${filePath} must be a string or Uint8Array`);
740
- }
741
- if (totalBytes > maxProjectBytes)
742
- throw new RangeError(`Project files exceed the ${maxProjectBytes}-byte limit`);
743
- }
744
- return { files: transferredFiles, transferables };
745
- }
746
-
747
- function runSourceNavigation(operation, source, filesOrOptions, requestOptions) {
748
- const files = requestOptions === undefined ? undefined : filesOrOptions;
749
- const options = requestOptions ?? filesOrOptions;
750
- if (!options?.position) throw new TypeError("A source position is required");
751
- return execute(
752
- operation,
753
- source,
754
- files,
755
- options,
756
- options.entrypoint ?? "main.mcl",
757
- options.position,
758
- );
759
- }
760
-
761
- function runSourceFileRename(source, filesOrOptions, requestOptions) {
762
- const files = requestOptions === undefined ? undefined : filesOrOptions;
763
- const options = requestOptions ?? filesOrOptions;
764
- if (!options?.oldPath || !options?.newPath)
765
- throw new TypeError("oldPath and newPath are required");
766
- return execute(
767
- "renameFileImports",
768
- source,
769
- files,
770
- options,
771
- options.entrypoint ?? "main.mcl",
772
- undefined,
773
- );
774
- }
775
-
776
- return {
777
- openProject,
778
- warmUp,
779
- parse: (source, requestOptions) => execute("parse", source, undefined, requestOptions),
780
- lint: (source, requestOptions) => execute("lint", source, undefined, requestOptions),
781
- format: (source, requestOptions) => execute("format", source, undefined, requestOptions),
782
- check: (source, files, requestOptions) => execute("check", source, files, requestOptions),
783
- evaluate: (source, files, requestOptions) => execute("evaluate", source, files, requestOptions),
784
- render: (source, files, requestOptions) => execute("render", source, files, requestOptions),
785
- definition: (source, filesOrOptions, requestOptions) =>
786
- runSourceNavigation("definition", source, filesOrOptions, requestOptions),
787
- hover: (source, filesOrOptions, requestOptions) =>
788
- runSourceNavigation("hover", source, filesOrOptions, requestOptions),
789
- references: (source, filesOrOptions, requestOptions) =>
790
- runSourceNavigation("references", source, filesOrOptions, requestOptions),
791
- rename: (source, filesOrOptions, requestOptions) =>
792
- runSourceNavigation("rename", source, filesOrOptions, requestOptions),
793
- renameFileImports: (source, filesOrOptions, requestOptions) =>
794
- runSourceFileRename(source, filesOrOptions, requestOptions),
795
- dispose() {
796
- if (disposed) return;
797
- disposed = true;
798
- for (const controller of queueSignals)
799
- controller.abort(new Error("MCL runtime has been disposed"));
800
- stopCurrent?.(new Error("MCL runtime has been disposed"));
801
- stopInitialization?.(new Error("MCL runtime has been disposed"));
802
- worker?.terminate();
803
- worker = undefined;
804
- ready = undefined;
805
- },
806
- };
807
- }