@dou-ui/code 0.1.0-alpha.23 → 0.1.0-alpha.25

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.
Files changed (41) hide show
  1. package/dist/assets/default-BWWFJmzn.js.map +1 -0
  2. package/dist/code-diff.js.map +1 -1
  3. package/dist/code-diff.vue_vue_type_script_setup_true_lang.js +196 -18
  4. package/dist/code-diff.vue_vue_type_script_setup_true_lang.js.map +1 -1
  5. package/dist/code-editor.js.map +1 -1
  6. package/dist/code-editor.vue_vue_type_script_setup_true_lang.js +636 -461
  7. package/dist/code-editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
  8. package/dist/extension.js.map +1 -1
  9. package/dist/index.js +3 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/language/highlighter.js +1 -1
  12. package/dist/language/highlighter.js.map +1 -1
  13. package/dist/language/language.js +24 -2
  14. package/dist/language/language.js.map +1 -1
  15. package/dist/language/remote-tokens.js +131 -0
  16. package/dist/language/remote-tokens.js.map +1 -0
  17. package/dist/language/worker-client.js +308 -33
  18. package/dist/language/worker-client.js.map +1 -1
  19. package/dist/language/worker-protocol.js.map +1 -1
  20. package/dist/shiki/index.js +54 -3
  21. package/dist/shiki/index.js.map +1 -1
  22. package/dist/style.css +1 -1
  23. package/dist/types/code-diff.vue.d.ts +4 -1
  24. package/dist/types/code-editor.vue.d.ts +2 -1
  25. package/dist/types/extension.d.ts +13 -1
  26. package/dist/types/index.d.ts +18 -6
  27. package/dist/types/language/language.d.ts +27 -0
  28. package/dist/types/language/remote-tokens.d.ts +38 -0
  29. package/dist/types/language/worker-client.d.ts +85 -15
  30. package/dist/types/language/worker-protocol.d.ts +53 -2
  31. package/dist/types/shiki/index.d.ts +36 -1
  32. package/dist/types/types.d.ts +43 -8
  33. package/dist/types/view/measure.d.ts +6 -0
  34. package/dist/types/worker/index.d.ts +27 -12
  35. package/dist/view/measure.js +23 -5
  36. package/dist/view/measure.js.map +1 -1
  37. package/dist/worker/default.js +1 -1
  38. package/dist/worker/index.js +280 -53
  39. package/dist/worker/index.js.map +1 -1
  40. package/package.json +3 -3
  41. package/dist/assets/default-BZBMZKf_.js.map +0 -1
@@ -1,13 +1,23 @@
1
1
  import { decodeState, languagesIn } from "./worker-protocol.js";
2
+ import { markRaw } from "vue";
2
3
  // src/language/worker-client.ts
3
4
  var nextId = 1;
5
+ var nextDiffId = 1;
4
6
  /** Lines sent to the worker in one message, so sending a long text never holds up the page long. */
5
7
  var PIECE = 2e4;
8
+ /** Default idle keep-alive for pooled workers (ms) so fast list scrolling reuses warm workers. */
9
+ var DEFAULT_IDLE_TIMEOUT = 1e4;
10
+ function defaultPoolSize() {
11
+ const cores = typeof navigator !== "undefined" ? navigator.hardwareConcurrency : 0;
12
+ if (!cores || !Number.isFinite(cores)) return 2;
13
+ if (cores <= 1) return 1;
14
+ return Math.min(4, Math.max(2, Math.floor(cores / 2)));
15
+ }
6
16
  /**
7
17
  * The editor's side of a highlighting worker (`serveCodeHighlighting`).
8
- * The text goes over the first time states far ahead are wanted (most
9
- * texts never need it), in pieces between other work; every change
10
- * follows it.
18
+ * The text goes over the first time syntax data is wanted, in pieces between
19
+ * other work; every change follows it. Newer viewport requests preempt older
20
+ * ones, and `cancel()` aborts pending work when scrolled out of view.
11
21
  */
12
22
  var SyntaxWorkerClient = class {
13
23
  worker;
@@ -18,7 +28,12 @@ var SyntaxWorkerClient = class {
18
28
  id = nextId++;
19
29
  /** Changes sent so far; the worker's answers name how many it had taken in. */
20
30
  version = 0;
31
+ /** Monotonic request counter so newer viewport requests preempt stale ones. */
32
+ seq = 0;
21
33
  asking = false;
34
+ paused = false;
35
+ busy = false;
36
+ lastAsked = null;
22
37
  closed = false;
23
38
  /** Sending the text: messages wait until it is all there. */
24
39
  sending = false;
@@ -26,6 +41,7 @@ var SyntaxWorkerClient = class {
26
41
  queue = [];
27
42
  timer = null;
28
43
  languages;
44
+ mode;
29
45
  constructor(worker, language, text, tabSize, handlers) {
30
46
  this.worker = worker;
31
47
  this.language = language;
@@ -33,8 +49,14 @@ var SyntaxWorkerClient = class {
33
49
  this.tabSize = tabSize;
34
50
  this.handlers = handlers;
35
51
  this.languages = languagesIn(language);
52
+ this.mode = language.workerMode === "tokens" ? "tokens" : "auto";
36
53
  worker.addEventListener("error", this.fail);
37
54
  }
55
+ setBusy(next) {
56
+ if (this.busy === next) return;
57
+ this.busy = next;
58
+ this.handlers.onBusyChange?.(next);
59
+ }
38
60
  fail = (event) => {
39
61
  if (this.closed) return;
40
62
  this.dispose();
@@ -42,6 +64,8 @@ var SyntaxWorkerClient = class {
42
64
  };
43
65
  post(message) {
44
66
  if (this.sending) {
67
+ if (message.t === "read") this.queue = this.queue.filter((item) => item.t !== "read");
68
+ else if (message.t === "cancel") this.queue = this.queue.filter((item) => item.t !== "read");
45
69
  this.queue.push(message);
46
70
  return;
47
71
  }
@@ -56,7 +80,8 @@ var SyntaxWorkerClient = class {
56
80
  id: this.id,
57
81
  language: this.language.name,
58
82
  nested,
59
- tabSize: this.tabSize
83
+ tabSize: this.tabSize,
84
+ mode: this.mode
60
85
  });
61
86
  this.sending = true;
62
87
  const doc = this.text();
@@ -92,9 +117,22 @@ var SyntaxWorkerClient = class {
92
117
  this.handlers.unsupported(message.missing);
93
118
  return;
94
119
  }
95
- if (message.t !== "states") return;
96
- this.asking = false;
120
+ if (message.t !== "states" && message.t !== "tokens") return;
121
+ if (message.seq === void 0 || message.seq === this.seq) {
122
+ this.asking = false;
123
+ this.lastAsked = null;
124
+ this.setBusy(false);
125
+ }
97
126
  if (message.version !== this.version) return;
127
+ if (message.t === "tokens") {
128
+ if (!this.handlers.tokens) {
129
+ this.dispose();
130
+ this.handlers.unsupported();
131
+ return;
132
+ }
133
+ this.handlers.tokens(message.from, message.lines, message.frontier, message.ranges);
134
+ return;
135
+ }
98
136
  const points = [];
99
137
  for (const [line, state] of message.points) {
100
138
  const decoded = decodeState(state, (name) => this.languages.get(name));
@@ -111,6 +149,7 @@ var SyntaxWorkerClient = class {
111
149
  change(changes) {
112
150
  if (this.closed || !this.opened || changes.empty) return;
113
151
  this.version++;
152
+ this.lastAsked = null;
114
153
  this.post({
115
154
  t: "change",
116
155
  id: this.id,
@@ -122,21 +161,58 @@ var SyntaxWorkerClient = class {
122
161
  length: changes.length
123
162
  });
124
163
  }
125
- /** Asks for the states from line index `from` on, once the worker has read up to `until`. */
126
- want(from, until) {
127
- if (this.closed || this.asking) return;
164
+ /**
165
+ * Requests syntax data up to `until` (and flat tokens for 1-based inclusive
166
+ * `[tokensFrom, tokensTo]` or disjoint `tokenRanges` when in `tokens` mode).
167
+ * A new range preempts any older in-flight request.
168
+ */
169
+ want(from, until, tokensFrom, tokensTo, tokenRanges) {
170
+ if (this.closed) return;
171
+ const tokenRangesKey = tokenRanges?.map(([a, b]) => `${a}:${b}`).join(",");
172
+ if (this.asking && this.lastAsked && this.lastAsked.from === from && this.lastAsked.until === until && this.lastAsked.tokensFrom === tokensFrom && this.lastAsked.tokensTo === tokensTo && this.lastAsked.tokenRangesKey === tokenRangesKey) return;
128
173
  if (!this.opened) this.open();
174
+ this.paused = false;
129
175
  this.asking = true;
176
+ this.lastAsked = {
177
+ from,
178
+ until,
179
+ tokensFrom,
180
+ tokensTo,
181
+ tokenRangesKey
182
+ };
183
+ this.setBusy(true);
184
+ const seq = ++this.seq;
130
185
  this.post({
131
186
  t: "read",
132
187
  id: this.id,
133
188
  from,
134
- until
189
+ until,
190
+ tokensFrom,
191
+ tokensTo,
192
+ tokenRanges,
193
+ seq
194
+ });
195
+ }
196
+ /** Cancels any pending highlighting task for this document (e.g. when scrolled out of view). */
197
+ cancel() {
198
+ if (this.closed) return;
199
+ if (!this.asking && !this.lastAsked && this.paused) return;
200
+ if (this.asking) this.seq++;
201
+ this.asking = false;
202
+ this.lastAsked = null;
203
+ this.paused = true;
204
+ this.setBusy(false);
205
+ if (this.opened) this.post({
206
+ t: "cancel",
207
+ id: this.id
135
208
  });
136
209
  }
137
210
  dispose() {
138
211
  if (this.closed) return;
139
212
  this.closed = true;
213
+ this.asking = false;
214
+ this.lastAsked = null;
215
+ this.setBusy(false);
140
216
  if (this.timer) clearTimeout(this.timer);
141
217
  this.worker.removeEventListener("error", this.fail);
142
218
  if (!this.opened) return;
@@ -149,32 +225,231 @@ var SyntaxWorkerClient = class {
149
225
  });
150
226
  }
151
227
  };
152
- /** DouCodeEditor's own worker, with the built-in languages: one for all editors, ended when none uses it. */
153
- var own = null;
154
- async function ownWorker() {
155
- const { default: CodeWorker } = await import("../worker/default.js");
156
- if (!own) {
157
- const entry = {
158
- worker: new CodeWorker(),
159
- users: 0
160
- };
161
- entry.worker.addEventListener("error", () => own === entry && (own = null));
162
- own = entry;
163
- }
164
- const entry = own;
165
- entry.users++;
166
- let released = false;
228
+ /** Runs `diffText` asynchronously inside a `serveCodeHighlighting` worker, with cancellation support. */
229
+ function requestWorkerDiff(worker, original, modified, options) {
230
+ const id = nextDiffId++;
231
+ let settled = false;
232
+ let cleanup = null;
167
233
  return {
168
- worker: entry.worker,
169
- release() {
170
- if (released) return;
171
- released = true;
172
- if (--entry.users > 0) return;
173
- entry.worker.terminate();
174
- if (own === entry) own = null;
234
+ promise: new Promise((resolve, reject) => {
235
+ const onMessage = (event) => {
236
+ const message = event.data;
237
+ if (!message || message.t !== "diffResult" || message.id !== id) return;
238
+ settled = true;
239
+ cleanup?.();
240
+ resolve(message.hunks);
241
+ };
242
+ const onError = (event) => {
243
+ if (settled) return;
244
+ settled = true;
245
+ cleanup?.();
246
+ reject(event.error ?? event.message ?? event);
247
+ };
248
+ cleanup = () => {
249
+ worker.removeEventListener("message", onMessage);
250
+ worker.removeEventListener("error", onError);
251
+ };
252
+ worker.addEventListener("message", onMessage);
253
+ worker.addEventListener("error", onError);
254
+ const msg = {
255
+ t: "diff",
256
+ id,
257
+ original,
258
+ modified,
259
+ options
260
+ };
261
+ worker.postMessage(msg);
262
+ }),
263
+ cancel() {
264
+ if (settled) return;
265
+ settled = true;
266
+ cleanup?.();
267
+ const msg = {
268
+ t: "cancelDiff",
269
+ id
270
+ };
271
+ worker.postMessage(msg);
175
272
  }
176
273
  };
177
274
  }
275
+ var WorkerPoolImpl = class {
276
+ factory;
277
+ maxWorkers;
278
+ idleTimeout;
279
+ slots = [];
280
+ spawning = [];
281
+ generation = 0;
282
+ constructor(factory, options = {}) {
283
+ this.factory = factory;
284
+ this.maxWorkers = Math.max(1, Math.floor(options.maxWorkers ?? defaultPoolSize()));
285
+ this.idleTimeout = Math.max(0, options.idleTimeout ?? DEFAULT_IDLE_TIMEOUT);
286
+ }
287
+ get size() {
288
+ return this.slots.length;
289
+ }
290
+ evict(slot) {
291
+ if (slot.idleTimer) {
292
+ clearTimeout(slot.idleTimer);
293
+ slot.idleTimer = null;
294
+ }
295
+ slot.failed = true;
296
+ slot.worker.removeEventListener("error", slot.onError);
297
+ const index = this.slots.indexOf(slot);
298
+ if (index >= 0) this.slots.splice(index, 1);
299
+ slot.worker.terminate();
300
+ }
301
+ lease(slot) {
302
+ if (slot.idleTimer) {
303
+ clearTimeout(slot.idleTimer);
304
+ slot.idleTimer = null;
305
+ }
306
+ slot.users++;
307
+ let released = false;
308
+ let busy = false;
309
+ const setBusy = (next) => {
310
+ if (released || busy === next) return;
311
+ busy = next;
312
+ slot.activeTasks = Math.max(0, slot.activeTasks + (next ? 1 : -1));
313
+ };
314
+ return {
315
+ worker: slot.worker,
316
+ setBusy,
317
+ release: () => {
318
+ if (released) return;
319
+ setBusy(false);
320
+ released = true;
321
+ slot.users = Math.max(0, slot.users - 1);
322
+ if (slot.users > 0 || slot.failed) return;
323
+ if (this.idleTimeout <= 0) {
324
+ this.evict(slot);
325
+ return;
326
+ }
327
+ slot.idleTimer = setTimeout(() => {
328
+ slot.idleTimer = null;
329
+ if (slot.users === 0 && !slot.failed) this.evict(slot);
330
+ }, this.idleTimeout);
331
+ }
332
+ };
333
+ }
334
+ pickBest() {
335
+ let best = null;
336
+ for (const slot of this.slots) {
337
+ if (slot.failed) continue;
338
+ if (!best || slot.activeTasks < best.activeTasks || slot.activeTasks === best.activeTasks && slot.users < best.users) best = slot;
339
+ }
340
+ return best;
341
+ }
342
+ async acquire() {
343
+ const gen = this.generation;
344
+ const idle = this.slots.find((slot) => !slot.failed && slot.users === 0 && slot.activeTasks === 0);
345
+ if (idle) return this.lease(idle);
346
+ if (this.slots.length + this.spawning.length < this.maxWorkers) {
347
+ const creating = Promise.resolve().then(() => this.factory()).then((worker) => {
348
+ if (gen !== this.generation) {
349
+ worker.terminate();
350
+ throw new Error("[@dou-ui/code] worker pool disposed");
351
+ }
352
+ const slot = {
353
+ worker,
354
+ users: 0,
355
+ activeTasks: 0,
356
+ idleTimer: null,
357
+ failed: false,
358
+ onError: () => this.evict(slot)
359
+ };
360
+ worker.addEventListener("error", slot.onError);
361
+ this.slots.push(slot);
362
+ return {
363
+ slot,
364
+ acquired: this.lease(slot)
365
+ };
366
+ });
367
+ this.spawning.push(creating);
368
+ try {
369
+ const { slot, acquired } = await creating;
370
+ if (gen !== this.generation || slot.failed) {
371
+ acquired.release();
372
+ throw new Error(gen !== this.generation ? "[@dou-ui/code] worker pool disposed" : "[@dou-ui/code] worker failed during startup");
373
+ }
374
+ return acquired;
375
+ } finally {
376
+ const idx = this.spawning.indexOf(creating);
377
+ if (idx >= 0) this.spawning.splice(idx, 1);
378
+ }
379
+ }
380
+ const best = this.pickBest();
381
+ if (best) return this.lease(best);
382
+ const first = this.spawning[0];
383
+ if (first) {
384
+ const { slot } = await first;
385
+ if (gen !== this.generation) throw new Error("[@dou-ui/code] worker pool disposed");
386
+ if (!slot.failed) return this.lease(slot);
387
+ }
388
+ if (gen !== this.generation) throw new Error("[@dou-ui/code] worker pool disposed");
389
+ return this.acquire();
390
+ }
391
+ dispose() {
392
+ this.generation++;
393
+ const current = this.slots.slice();
394
+ this.slots = [];
395
+ for (const slot of current) {
396
+ if (slot.idleTimer) {
397
+ clearTimeout(slot.idleTimer);
398
+ slot.idleTimer = null;
399
+ }
400
+ slot.failed = true;
401
+ slot.worker.removeEventListener("error", slot.onError);
402
+ slot.worker.terminate();
403
+ }
404
+ }
405
+ };
406
+ var pools = /* @__PURE__ */ new WeakMap();
407
+ /**
408
+ * Creates a lazily-spawned worker pool that can be passed to the `worker` prop
409
+ * of multiple `DouCodeEditor` and `DouCodeDiff` instances.
410
+ *
411
+ * Workers are created only when concurrent tasks need them (up to `maxWorkers`)
412
+ * and kept warm briefly when idle so scrolling through a multi-file list avoids
413
+ * re-initializing workers or Shiki WASM grammars.
414
+ */
415
+ function createCodeWorkerPool(factory, options) {
416
+ const impl = new WorkerPoolImpl(factory, options);
417
+ const handle = markRaw({
418
+ kind: "pool",
419
+ get size() {
420
+ return impl.size;
421
+ },
422
+ get maxWorkers() {
423
+ return impl.maxWorkers;
424
+ },
425
+ dispose() {
426
+ impl.dispose();
427
+ }
428
+ });
429
+ pools.set(handle, impl);
430
+ return handle;
431
+ }
432
+ function isCodeWorkerPool(value) {
433
+ return typeof value === "object" && value !== null && value.kind === "pool" && pools.has(value);
434
+ }
435
+ function acquirePoolWorker(pool) {
436
+ const impl = pools.get(pool);
437
+ if (!impl) return Promise.reject(/* @__PURE__ */ new Error("[@dou-ui/code] invalid code worker pool"));
438
+ return impl.acquire();
439
+ }
440
+ /** Built-in lazy worker pool for `worker: true` (built-in languages + async diff). */
441
+ var ownPool = null;
442
+ function getOwnPool() {
443
+ if (!ownPool) ownPool = new WorkerPoolImpl(async () => {
444
+ const { default: CodeWorker } = await import("../worker/default.js");
445
+ return new CodeWorker();
446
+ });
447
+ return ownPool;
448
+ }
449
+ /** Acquires a worker from the built-in lazily-spawned worker pool (`worker: true`). */
450
+ function ownWorker() {
451
+ return getOwnPool().acquire();
452
+ }
178
453
  /** Editors using each worker made by a `worker` function: one handed to several ends with the last. */
179
454
  var holders = /* @__PURE__ */ new Map();
180
455
  /** Counts an editor using `worker`; the returned function lets go, ending the worker after the last. */
@@ -193,6 +468,6 @@ function holdWorker(worker) {
193
468
  worker.terminate();
194
469
  };
195
470
  }
196
- export { SyntaxWorkerClient, holdWorker, ownWorker };
471
+ export { SyntaxWorkerClient, acquirePoolWorker, createCodeWorkerPool, defaultPoolSize, holdWorker, isCodeWorkerPool, ownWorker, requestWorkerDiff };
197
472
 
198
473
  //# sourceMappingURL=worker-client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker-client.js","names":[],"sources":["../../src/language/worker-client.ts"],"sourcesContent":["import type { ChangeSet } from '../core/changes'\nimport type { CodeText } from '../core/text'\nimport type { CodeLanguage } from './language'\nimport { decodeState, type FromWorker, languagesIn, type ToWorker } from './worker-protocol'\n\nlet nextId = 1\n\n/** Lines sent to the worker in one message, so sending a long text never holds up the page long. */\nconst PIECE = 20_000\n\n/**\n * The editor's side of a highlighting worker (`serveCodeHighlighting`).\n * The text goes over the first time states far ahead are wanted (most\n * texts never need it), in pieces between other work; every change\n * follows it.\n */\nexport class SyntaxWorkerClient {\n private readonly id = nextId++\n /** Changes sent so far; the worker's answers name how many it had taken in. */\n private version = 0\n private asking = false\n private closed = false\n /** Sending the text: messages wait until it is all there. */\n private sending = false\n private opened = false\n private queue: ToWorker[] = []\n private timer: ReturnType<typeof setTimeout> | null = null\n private readonly languages: Map<string, CodeLanguage>\n\n constructor(\n private readonly worker: Worker,\n private readonly language: CodeLanguage,\n /** The text as it is now. */\n private readonly text: () => CodeText,\n private readonly tabSize: number,\n private readonly handlers: {\n states: (points: Array<[line: number, state: unknown]>) => void\n /** The worker hasn't the language named `missing`, or can't send its states (no `missing`). */\n unsupported: (missing?: string) => void\n /** The worker could not run (it failed to load, or threw). */\n failed: (error: unknown) => void\n },\n ) {\n this.languages = languagesIn(language)\n worker.addEventListener('error', this.fail)\n }\n\n private fail = (event: Event) => {\n if (this.closed) return\n this.dispose()\n this.handlers.failed((event as ErrorEvent).error ?? (event as ErrorEvent).message ?? event)\n }\n\n private post(message: ToWorker) {\n if (this.sending) {\n this.queue.push(message)\n return\n }\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- a worker takes no origin\n this.worker.postMessage(message)\n }\n\n private open() {\n this.opened = true\n this.worker.addEventListener('message', this.listen)\n const nested = [...this.languages.keys()].filter((name) => name !== this.language.name)\n this.post({\n t: 'open',\n id: this.id,\n language: this.language.name,\n nested,\n tabSize: this.tabSize,\n })\n this.sending = true\n const doc = this.text()\n let from = 1\n const next = () => {\n this.timer = null\n if (this.closed) return\n const to = Math.min(doc.lines, from + PIECE - 1)\n const done = to >= doc.lines\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- a worker takes no origin\n this.worker.postMessage({ t: 'text', id: this.id, lines: doc.lineTexts(from, to), done })\n from = to + 1\n if (!done) {\n this.timer = setTimeout(next, 0)\n return\n }\n this.sending = false\n const queue = this.queue\n this.queue = []\n for (const message of queue) this.post(message)\n }\n next()\n }\n\n private listen = (event: MessageEvent) => {\n const message = event.data as FromWorker\n if (this.closed || !message || message.id !== this.id) return\n if (message.t === 'unsupported') {\n this.dispose()\n this.handlers.unsupported(message.missing)\n return\n }\n if (message.t !== 'states') return\n this.asking = false\n // Changed since it was asked: what it read is for another text; asking again gets the new one.\n if (message.version !== this.version) return\n const points: Array<[number, unknown]> = []\n for (const [line, state] of message.points) {\n const decoded = decodeState(state, (name) => this.languages.get(name))\n if (decoded === undefined) {\n this.dispose()\n this.handlers.unsupported()\n return\n }\n points.push([line, decoded])\n }\n this.handlers.states(points)\n }\n\n /** Passes on a change made to the text, once the worker has it. */\n change(changes: ChangeSet): void {\n if (this.closed || !this.opened || changes.empty) return\n this.version++\n this.post({\n t: 'change',\n id: this.id,\n changes: changes.changes.map((change) => [change.from, change.to, change.insert]),\n length: changes.length,\n })\n }\n\n /** Asks for the states from line index `from` on, once the worker has read up to `until`. */\n want(from: number, until: number): void {\n if (this.closed || this.asking) return\n if (!this.opened) this.open()\n this.asking = true\n this.post({ t: 'read', id: this.id, from, until })\n }\n\n dispose(): void {\n if (this.closed) return\n this.closed = true\n if (this.timer) clearTimeout(this.timer)\n this.worker.removeEventListener('error', this.fail)\n if (!this.opened) return\n this.worker.removeEventListener('message', this.listen)\n this.sending = false\n this.queue = []\n this.post({ t: 'close', id: this.id })\n }\n}\n\n/** DouCodeEditor's own worker, with the built-in languages: one for all editors, ended when none uses it. */\nlet own: { worker: Worker; users: number } | null = null\n\nexport async function ownWorker(): Promise<{ worker: Worker; release: () => void }> {\n const { default: CodeWorker } = await import('../worker/default?worker&inline')\n if (!own) {\n const entry = { worker: new CodeWorker(), users: 0 }\n // a worker that failed isn't handed out again: the next editor starts another\n entry.worker.addEventListener('error', () => own === entry && (own = null))\n own = entry\n }\n const entry = own\n entry.users++\n let released = false\n return {\n worker: entry.worker,\n release() {\n if (released) return\n released = true\n if (--entry.users > 0) return\n entry.worker.terminate()\n if (own === entry) own = null\n },\n }\n}\n\n/** Editors using each worker made by a `worker` function: one handed to several ends with the last. */\nconst holders = new Map<Worker, number>()\n\n/** Counts an editor using `worker`; the returned function lets go, ending the worker after the last. */\nexport function holdWorker(worker: Worker): () => void {\n holders.set(worker, (holders.get(worker) ?? 0) + 1)\n let released = false\n return () => {\n if (released) return\n released = true\n const left = holders.get(worker)! - 1\n if (left > 0) {\n holders.set(worker, left)\n return\n }\n holders.delete(worker)\n worker.terminate()\n }\n}\n"],"mappings":";;AAKA,IAAI,SAAS;;AAGb,IAAM,QAAQ;;;;;;;AAQd,IAAa,qBAAb,MAAgC;CAcX;CACA;CAEA;CACA;CACA;CAlBnB,KAAsB;;CAEtB,UAAkB;CAClB,SAAiB;CACjB,SAAiB;;CAEjB,UAAkB;CAClB,SAAiB;CACjB,QAA4B,CAAC;CAC7B,QAAsD;CACtD;CAEA,YACE,QACA,UAEA,MACA,SACA,UAOA;EAZiB,KAAA,SAAA;EACA,KAAA,WAAA;EAEA,KAAA,OAAA;EACA,KAAA,UAAA;EACA,KAAA,WAAA;EAQjB,KAAK,YAAY,YAAY,QAAQ;EACrC,OAAO,iBAAiB,SAAS,KAAK,IAAI;CAC5C;CAEA,QAAgB,UAAi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A,IAAI,MAAgD;AAEpD,eAAsB,YAA8D;CAClF,MAAM,EAAE,SAAS,eAAe,MAAM,OAAO;CAC7C,IAAI,CAAC,KAAK;EACR,MAAM,QAAQ;GAAE,QAAQ,IAAI,WAAW;GAAG,OAAO;EAAE;EAEnD,MAAM,OAAO,iBAAiB,eAAe,QAAQ,UAAU,MAAM,KAAK;EAC1E,MAAM;CACR;CACA,MAAM,QAAQ;CACd,MAAM;CACN,IAAI,WAAW;CACf,OAAO;EACL,QAAQ,MAAM;EACd,UAAU;GACR,IAAI,UAAU;GACd,WAAW;GACX,IAAI,EAAE,MAAM,QAAQ,GAAG;GACvB,MAAM,OAAO,UAAU;GACvB,IAAI,QAAQ,OAAO,MAAM;EAC3B;CACF;AACF;;AAGA,IAAM,0BAAU,IAAI,IAAoB;;AAGxC,SAAgB,WAAW,QAA4B;CACrD,QAAQ,IAAI,SAAS,QAAQ,IAAI,MAAM,KAAK,KAAK,CAAC;CAClD,IAAI,WAAW;CACf,aAAa;EACX,IAAI,UAAU;EACd,WAAW;EACX,MAAM,OAAO,QAAQ,IAAI,MAAM,IAAK;EACpC,IAAI,OAAO,GAAG;GACZ,QAAQ,IAAI,QAAQ,IAAI;GACxB;EACF;EACA,QAAQ,OAAO,MAAM;EACrB,OAAO,UAAU;CACnB;AACF"}
1
+ {"version":3,"file":"worker-client.js","names":[],"sources":["../../src/language/worker-client.ts"],"sourcesContent":["import { markRaw } from 'vue'\nimport type { ChangeSet } from '../core/changes'\nimport type { CodeDiffHunk, CodeDiffOptions } from '../core/diff'\nimport type { CodeText } from '../core/text'\nimport type { CodeLanguage, CodeLineTokens } from './language'\nimport {\n decodeState,\n type FromWorker,\n languagesIn,\n type ToWorker,\n type WorkerSyntaxMode,\n} from './worker-protocol'\n\nlet nextId = 1\nlet nextDiffId = 1\n\n/** Lines sent to the worker in one message, so sending a long text never holds up the page long. */\nconst PIECE = 20_000\n\n/** Default idle keep-alive for pooled workers (ms) so fast list scrolling reuses warm workers. */\nconst DEFAULT_IDLE_TIMEOUT = 10_000\n\nexport function defaultPoolSize(): number {\n const cores = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency : 0\n if (!cores || !Number.isFinite(cores)) return 2\n if (cores <= 1) return 1\n return Math.min(4, Math.max(2, Math.floor(cores / 2)))\n}\n\nexport interface SyntaxWorkerHandlers {\n states: (points: Array<[line: number, state: unknown]>) => void\n /** Flat per-line tokens returned in `tokens` mode (e.g. Shiki or non-serializable states). */\n tokens?: (\n from: number,\n lines: readonly CodeLineTokens[],\n frontier: number,\n ranges?: ReadonlyArray<readonly [from: number, lines: readonly CodeLineTokens[]]>,\n ) => void\n /** The worker hasn't the language named `missing`, or can't highlight it (no `missing`). */\n unsupported: (missing?: string) => void\n /** The worker could not run (it failed to load, or threw). */\n failed: (error: unknown) => void\n /** Notifies a worker pool whether this client currently has an in-flight request. */\n onBusyChange?: (busy: boolean) => void\n}\n\ninterface AskedRange {\n from: number\n until: number\n tokensFrom?: number\n tokensTo?: number\n tokenRangesKey?: string\n}\n\n/**\n * The editor's side of a highlighting worker (`serveCodeHighlighting`).\n * The text goes over the first time syntax data is wanted, in pieces between\n * other work; every change follows it. Newer viewport requests preempt older\n * ones, and `cancel()` aborts pending work when scrolled out of view.\n */\nexport class SyntaxWorkerClient {\n private readonly id = nextId++\n /** Changes sent so far; the worker's answers name how many it had taken in. */\n private version = 0\n /** Monotonic request counter so newer viewport requests preempt stale ones. */\n private seq = 0\n private asking = false\n private paused = false\n private busy = false\n private lastAsked: AskedRange | null = null\n private closed = false\n /** Sending the text: messages wait until it is all there. */\n private sending = false\n private opened = false\n private queue: ToWorker[] = []\n private timer: ReturnType<typeof setTimeout> | null = null\n private readonly languages: Map<string, CodeLanguage>\n private readonly mode: WorkerSyntaxMode\n\n constructor(\n private readonly worker: Worker,\n private readonly language: CodeLanguage,\n /** The text as it is now. */\n private readonly text: () => CodeText,\n private readonly tabSize: number,\n private readonly handlers: SyntaxWorkerHandlers,\n ) {\n this.languages = languagesIn(language)\n this.mode = language.workerMode === 'tokens' ? 'tokens' : 'auto'\n worker.addEventListener('error', this.fail)\n }\n\n private setBusy(next: boolean) {\n if (this.busy === next) return\n this.busy = next\n this.handlers.onBusyChange?.(next)\n }\n\n private fail = (event: Event) => {\n if (this.closed) return\n this.dispose()\n this.handlers.failed((event as ErrorEvent).error ?? (event as ErrorEvent).message ?? event)\n }\n\n private post(message: ToWorker) {\n if (this.sending) {\n if (message.t === 'read') {\n // Only the latest viewport request matters while text chunks are still being streamed.\n this.queue = this.queue.filter((item) => item.t !== 'read')\n } else if (message.t === 'cancel') {\n this.queue = this.queue.filter((item) => item.t !== 'read')\n }\n this.queue.push(message)\n return\n }\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- a worker takes no origin\n this.worker.postMessage(message)\n }\n\n private open() {\n this.opened = true\n this.worker.addEventListener('message', this.listen)\n const nested = [...this.languages.keys()].filter((name) => name !== this.language.name)\n this.post({\n t: 'open',\n id: this.id,\n language: this.language.name,\n nested,\n tabSize: this.tabSize,\n mode: this.mode,\n })\n this.sending = true\n const doc = this.text()\n let from = 1\n const next = () => {\n this.timer = null\n if (this.closed) return\n const to = Math.min(doc.lines, from + PIECE - 1)\n const done = to >= doc.lines\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- a worker takes no origin\n this.worker.postMessage({ t: 'text', id: this.id, lines: doc.lineTexts(from, to), done })\n from = to + 1\n if (!done) {\n this.timer = setTimeout(next, 0)\n return\n }\n this.sending = false\n const queue = this.queue\n this.queue = []\n for (const message of queue) this.post(message)\n }\n next()\n }\n\n private listen = (event: MessageEvent) => {\n const message = event.data as FromWorker\n if (this.closed || !message || message.id !== this.id) return\n if (message.t === 'unsupported') {\n this.dispose()\n this.handlers.unsupported(message.missing)\n return\n }\n if (message.t !== 'states' && message.t !== 'tokens') return\n const isLatestSeq = message.seq === undefined || message.seq === this.seq\n if (isLatestSeq) {\n this.asking = false\n this.lastAsked = null\n this.setBusy(false)\n }\n // Changed since it was asked: what it read is for another text; asking again gets the new one.\n if (message.version !== this.version) return\n if (message.t === 'tokens') {\n if (!this.handlers.tokens) {\n this.dispose()\n this.handlers.unsupported()\n return\n }\n this.handlers.tokens(message.from, message.lines, message.frontier, message.ranges)\n return\n }\n const points: Array<[number, unknown]> = []\n for (const [line, state] of message.points) {\n const decoded = decodeState(state, (name) => this.languages.get(name))\n if (decoded === undefined) {\n this.dispose()\n this.handlers.unsupported()\n return\n }\n points.push([line, decoded])\n }\n this.handlers.states(points)\n }\n\n /** Passes on a change made to the text, once the worker has it. */\n change(changes: ChangeSet): void {\n if (this.closed || !this.opened || changes.empty) return\n this.version++\n this.lastAsked = null\n this.post({\n t: 'change',\n id: this.id,\n changes: changes.changes.map((change) => [change.from, change.to, change.insert]),\n length: changes.length,\n })\n }\n\n /**\n * Requests syntax data up to `until` (and flat tokens for 1-based inclusive\n * `[tokensFrom, tokensTo]` or disjoint `tokenRanges` when in `tokens` mode).\n * A new range preempts any older in-flight request.\n */\n want(\n from: number,\n until: number,\n tokensFrom?: number,\n tokensTo?: number,\n tokenRanges?: Array<[from: number, to: number]>,\n ): void {\n if (this.closed) return\n const tokenRangesKey = tokenRanges?.map(([a, b]) => `${a}:${b}`).join(',')\n if (\n this.asking &&\n this.lastAsked &&\n this.lastAsked.from === from &&\n this.lastAsked.until === until &&\n this.lastAsked.tokensFrom === tokensFrom &&\n this.lastAsked.tokensTo === tokensTo &&\n this.lastAsked.tokenRangesKey === tokenRangesKey\n ) {\n return\n }\n if (!this.opened) this.open()\n this.paused = false\n this.asking = true\n this.lastAsked = { from, until, tokensFrom, tokensTo, tokenRangesKey }\n this.setBusy(true)\n const seq = ++this.seq\n this.post({ t: 'read', id: this.id, from, until, tokensFrom, tokensTo, tokenRanges, seq })\n }\n\n /** Cancels any pending highlighting task for this document (e.g. when scrolled out of view). */\n cancel(): void {\n if (this.closed) return\n if (!this.asking && !this.lastAsked && this.paused) return\n if (this.asking) this.seq++\n this.asking = false\n this.lastAsked = null\n this.paused = true\n this.setBusy(false)\n if (this.opened) this.post({ t: 'cancel', id: this.id })\n }\n\n dispose(): void {\n if (this.closed) return\n this.closed = true\n this.asking = false\n this.lastAsked = null\n this.setBusy(false)\n if (this.timer) clearTimeout(this.timer)\n this.worker.removeEventListener('error', this.fail)\n if (!this.opened) return\n this.worker.removeEventListener('message', this.listen)\n this.sending = false\n this.queue = []\n this.post({ t: 'close', id: this.id })\n }\n}\n\nexport interface WorkerDiffRequest {\n promise: Promise<CodeDiffHunk[]>\n cancel(): void\n}\n\n/** Runs `diffText` asynchronously inside a `serveCodeHighlighting` worker, with cancellation support. */\nexport function requestWorkerDiff(\n worker: Worker,\n original: string,\n modified: string,\n options?: CodeDiffOptions,\n): WorkerDiffRequest {\n const id = nextDiffId++\n let settled = false\n let cleanup: (() => void) | null = null\n\n const promise = new Promise<CodeDiffHunk[]>((resolve, reject) => {\n const onMessage = (event: MessageEvent) => {\n const message = event.data as FromWorker\n if (!message || message.t !== 'diffResult' || message.id !== id) return\n settled = true\n cleanup?.()\n resolve(message.hunks)\n }\n const onError = (event: Event) => {\n if (settled) return\n settled = true\n cleanup?.()\n reject((event as ErrorEvent).error ?? (event as ErrorEvent).message ?? event)\n }\n cleanup = () => {\n worker.removeEventListener('message', onMessage)\n worker.removeEventListener('error', onError)\n }\n worker.addEventListener('message', onMessage)\n worker.addEventListener('error', onError)\n const msg: ToWorker = { t: 'diff', id, original, modified, options }\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- a worker takes no origin\n worker.postMessage(msg)\n })\n\n return {\n promise,\n cancel() {\n if (settled) return\n settled = true\n cleanup?.()\n const msg: ToWorker = { t: 'cancelDiff', id }\n // oxlint-disable-next-line unicorn/require-post-message-target-origin -- a worker takes no origin\n worker.postMessage(msg)\n },\n }\n}\n\n// ---------------------------------------------------------------- worker pool\n\nexport interface CodeWorkerPoolOptions {\n /**\n * Maximum number of workers spawned lazily on demand.\n * Defaults to `Math.min(4, Math.max(2, Math.floor((hardwareConcurrency || 4) / 2)))` (1 on single-core).\n */\n maxWorkers?: number\n /**\n * Milliseconds to keep an idle worker alive after its last user releases it,\n * avoiding repeated worker/WASM startup during fast list scrolling.\n * Defaults to `10_000`. Set to `0` to terminate immediately when idle.\n */\n idleTimeout?: number\n}\n\n/**\n * A lazily-spawned pool of highlighting workers shared across `DouCodeEditor`\n * and `DouCodeDiff` instances via the `worker` prop.\n */\nexport interface CodeWorkerPool {\n readonly kind: 'pool'\n /** Number of currently live worker instances in the pool. */\n readonly size: number\n /** Maximum number of workers the pool may spawn. */\n readonly maxWorkers: number\n /** Terminates all live workers and clears idle timers. */\n dispose(): void\n}\n\n/** Accepted values for the `worker` prop on `DouCodeEditor` and `DouCodeDiff`. */\nexport type CodeWorkerOption = boolean | (() => Worker) | CodeWorkerPool\n\nexport interface AcquiredWorker {\n worker: Worker\n release: () => void\n setBusy?: (busy: boolean) => void\n}\n\ninterface WorkerSlot {\n worker: Worker\n users: number\n activeTasks: number\n idleTimer: ReturnType<typeof setTimeout> | null\n failed: boolean\n onError: () => void\n}\n\nclass WorkerPoolImpl {\n readonly maxWorkers: number\n private readonly idleTimeout: number\n private slots: WorkerSlot[] = []\n private spawning: Promise<{ slot: WorkerSlot; acquired: AcquiredWorker }>[] = []\n private generation = 0\n\n constructor(\n private readonly factory: () => Worker | Promise<Worker>,\n options: CodeWorkerPoolOptions = {},\n ) {\n this.maxWorkers = Math.max(1, Math.floor(options.maxWorkers ?? defaultPoolSize()))\n this.idleTimeout = Math.max(0, options.idleTimeout ?? DEFAULT_IDLE_TIMEOUT)\n }\n\n get size(): number {\n return this.slots.length\n }\n\n private evict(slot: WorkerSlot) {\n if (slot.idleTimer) {\n clearTimeout(slot.idleTimer)\n slot.idleTimer = null\n }\n slot.failed = true\n slot.worker.removeEventListener('error', slot.onError)\n const index = this.slots.indexOf(slot)\n if (index >= 0) this.slots.splice(index, 1)\n slot.worker.terminate()\n }\n\n private lease(slot: WorkerSlot): AcquiredWorker {\n if (slot.idleTimer) {\n clearTimeout(slot.idleTimer)\n slot.idleTimer = null\n }\n slot.users++\n let released = false\n let busy = false\n const setBusy = (next: boolean) => {\n if (released || busy === next) return\n busy = next\n slot.activeTasks = Math.max(0, slot.activeTasks + (next ? 1 : -1))\n }\n return {\n worker: slot.worker,\n setBusy,\n release: () => {\n if (released) return\n setBusy(false)\n released = true\n slot.users = Math.max(0, slot.users - 1)\n if (slot.users > 0 || slot.failed) return\n if (this.idleTimeout <= 0) {\n this.evict(slot)\n return\n }\n slot.idleTimer = setTimeout(() => {\n slot.idleTimer = null\n if (slot.users === 0 && !slot.failed) this.evict(slot)\n }, this.idleTimeout)\n },\n }\n }\n\n private pickBest(): WorkerSlot | null {\n let best: WorkerSlot | null = null\n for (const slot of this.slots) {\n if (slot.failed) continue\n if (\n !best ||\n slot.activeTasks < best.activeTasks ||\n (slot.activeTasks === best.activeTasks && slot.users < best.users)\n ) {\n best = slot\n }\n }\n return best\n }\n\n async acquire(): Promise<AcquiredWorker> {\n const gen = this.generation\n\n // 1. Reuse a completely idle warm worker if one is available.\n const idle = this.slots.find(\n (slot) => !slot.failed && slot.users === 0 && slot.activeTasks === 0,\n )\n if (idle) return this.lease(idle)\n\n // 2. Otherwise lazily spawn a new worker if under the pool limit.\n if (this.slots.length + this.spawning.length < this.maxWorkers) {\n const creating = Promise.resolve()\n .then(() => this.factory())\n .then((worker) => {\n if (gen !== this.generation) {\n worker.terminate()\n throw new Error('[@dou-ui/code] worker pool disposed')\n }\n const slot: WorkerSlot = {\n worker,\n users: 0,\n activeTasks: 0,\n idleTimer: null,\n failed: false,\n onError: () => this.evict(slot),\n }\n worker.addEventListener('error', slot.onError)\n this.slots.push(slot)\n return { slot, acquired: this.lease(slot) }\n })\n this.spawning.push(creating)\n try {\n const { slot, acquired } = await creating\n if (gen !== this.generation || slot.failed) {\n acquired.release()\n throw new Error(\n gen !== this.generation\n ? '[@dou-ui/code] worker pool disposed'\n : '[@dou-ui/code] worker failed during startup',\n )\n }\n return acquired\n } finally {\n const idx = this.spawning.indexOf(creating)\n if (idx >= 0) this.spawning.splice(idx, 1)\n }\n }\n\n // 3. At capacity: reuse the least-loaded live worker, or wait for an in-flight spawn.\n const best = this.pickBest()\n if (best) return this.lease(best)\n const first = this.spawning[0]\n if (first) {\n const { slot } = await first\n if (gen !== this.generation) {\n throw new Error('[@dou-ui/code] worker pool disposed')\n }\n if (!slot.failed) return this.lease(slot)\n }\n if (gen !== this.generation) {\n throw new Error('[@dou-ui/code] worker pool disposed')\n }\n return this.acquire()\n }\n\n dispose(): void {\n this.generation++\n const current = this.slots.slice()\n this.slots = []\n for (const slot of current) {\n if (slot.idleTimer) {\n clearTimeout(slot.idleTimer)\n slot.idleTimer = null\n }\n slot.failed = true\n slot.worker.removeEventListener('error', slot.onError)\n slot.worker.terminate()\n }\n }\n}\n\nconst pools = new WeakMap<CodeWorkerPool, WorkerPoolImpl>()\n\n/**\n * Creates a lazily-spawned worker pool that can be passed to the `worker` prop\n * of multiple `DouCodeEditor` and `DouCodeDiff` instances.\n *\n * Workers are created only when concurrent tasks need them (up to `maxWorkers`)\n * and kept warm briefly when idle so scrolling through a multi-file list avoids\n * re-initializing workers or Shiki WASM grammars.\n */\nexport function createCodeWorkerPool(\n factory: () => Worker,\n options?: CodeWorkerPoolOptions,\n): CodeWorkerPool {\n const impl = new WorkerPoolImpl(factory, options)\n const handle: CodeWorkerPool = markRaw({\n kind: 'pool',\n get size() {\n return impl.size\n },\n get maxWorkers() {\n return impl.maxWorkers\n },\n dispose() {\n impl.dispose()\n },\n })\n pools.set(handle, impl)\n return handle\n}\n\nexport function isCodeWorkerPool(value: unknown): value is CodeWorkerPool {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as CodeWorkerPool).kind === 'pool' &&\n pools.has(value as CodeWorkerPool)\n )\n}\n\nexport function acquirePoolWorker(pool: CodeWorkerPool): Promise<AcquiredWorker> {\n const impl = pools.get(pool)\n if (!impl) return Promise.reject(new Error('[@dou-ui/code] invalid code worker pool'))\n return impl.acquire()\n}\n\n/** Built-in lazy worker pool for `worker: true` (built-in languages + async diff). */\nlet ownPool: WorkerPoolImpl | null = null\n\nfunction getOwnPool(): WorkerPoolImpl {\n if (!ownPool) {\n ownPool = new WorkerPoolImpl(async () => {\n const { default: CodeWorker } = await import('../worker/default?worker&inline')\n return new CodeWorker()\n })\n }\n return ownPool\n}\n\n/** Acquires a worker from the built-in lazily-spawned worker pool (`worker: true`). */\nexport function ownWorker(): Promise<AcquiredWorker> {\n return getOwnPool().acquire()\n}\n\n/** Disposes the built-in worker pool (useful in tests or teardown). */\nexport function disposeOwnWorkerPool(): void {\n ownPool?.dispose()\n ownPool = null\n}\n\n/** Editors using each worker made by a `worker` function: one handed to several ends with the last. */\nconst holders = new Map<Worker, number>()\n\n/** Counts an editor using `worker`; the returned function lets go, ending the worker after the last. */\nexport function holdWorker(worker: Worker): () => void {\n holders.set(worker, (holders.get(worker) ?? 0) + 1)\n let released = false\n return () => {\n if (released) return\n released = true\n const left = holders.get(worker)! - 1\n if (left > 0) {\n holders.set(worker, left)\n return\n }\n holders.delete(worker)\n worker.terminate()\n }\n}\n"],"mappings":";;;AAaA,IAAI,SAAS;AACb,IAAI,aAAa;;AAGjB,IAAM,QAAQ;;AAGd,IAAM,uBAAuB;AAE7B,SAAgB,kBAA0B;CACxC,MAAM,QAAQ,OAAO,cAAc,cAAc,UAAU,sBAAsB;CACjF,IAAI,CAAC,SAAS,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO;CAC9C,IAAI,SAAS,GAAG,OAAO;CACvB,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,CAAC,CAAC,CAAC;AACvD;;;;;;;AAiCA,IAAa,qBAAb,MAAgC;CAoBX;CACA;CAEA;CACA;CACA;CAxBnB,KAAsB;;CAEtB,UAAkB;;CAElB,MAAc;CACd,SAAiB;CACjB,SAAiB;CACjB,OAAe;CACf,YAAuC;CACvC,SAAiB;;CAEjB,UAAkB;CAClB,SAAi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B;AAErC;AAEA,SAAgB,kBAAkB,MAA+C;CAC/E,MAAM,OAAO,MAAM,IAAI,IAAI;CAC3B,IAAI,CAAC,MAAM,OAAO,QAAQ,uBAAO,IAAI,MAAM,yCAAyC,CAAC;CACrF,OAAO,KAAK,QAAQ;AACtB;;AAGA,IAAI,UAAiC;AAErC,SAAS,aAA6B;CACpC,IAAI,CAAC,SACH,UAAU,IAAI,eAAe,YAAY;EACvC,MAAM,EAAE,SAAS,eAAe,MAAM,OAAO;EAC7C,OAAO,IAAI,WAAW;CACxB,CAAC;CAEH,OAAO;AACT;;AAGA,SAAgB,YAAqC;CACnD,OAAO,WAAW,CAAC,CAAC,QAAQ;AAC9B;;AASA,IAAM,0BAAU,IAAI,IAAoB;;AAGxC,SAAgB,WAAW,QAA4B;CACrD,QAAQ,IAAI,SAAS,QAAQ,IAAI,MAAM,KAAK,KAAK,CAAC;CAClD,IAAI,WAAW;CACf,aAAa;EACX,IAAI,UAAU;EACd,WAAW;EACX,MAAM,OAAO,QAAQ,IAAI,MAAM,IAAK;EACpC,IAAI,OAAO,GAAG;GACZ,QAAQ,IAAI,QAAQ,IAAI;GACxB;EACF;EACA,QAAQ,OAAO,MAAM;EACrB,OAAO,UAAU;CACnB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"worker-protocol.js","names":[],"sources":["../../src/language/worker-protocol.ts"],"sourcesContent":["import type { CodeLanguage } from './language'\n\n/*\n * Messages between the editor and a highlighting worker, and how states\n * cross over: languages inside a state (the script in an HTML file) go by\n * name, everything else as plain data.\n */\n\n/** A change as sent: `[from, to, insert]`. */\nexport type WireChange = [from: number, to: number, insert: string]\n\nexport type ToWorker =\n /** `nested`: the names of the languages it may hold, which the worker's language must hold too. */\n | { t: 'open'; id: number; language: string; nested: string[]; tabSize: number }\n /** The text, in pieces of whole lines; `done` on the last. */\n | { t: 'text'; id: number; lines: string[]; done: boolean }\n | { t: 'change'; id: number; changes: WireChange[]; length: number }\n | { t: 'read'; id: number; from: number; until: number }\n | { t: 'close'; id: number }\n\nexport type FromWorker =\n | { t: 'states'; id: number; version: number; points: Array<[line: number, state: unknown]> }\n /** The worker hasn't the language named `missing`, or (without it) can't send its states. */\n | { t: 'unsupported'; id: number; missing?: string }\n\nconst LANGUAGE = '$codeLanguage'\n\nconst isLanguage = (value: object): value is CodeLanguage =>\n typeof (value as CodeLanguage).token === 'function' &&\n typeof (value as CodeLanguage).startState === 'function'\n\n/** A state as plain data, its languages replaced by their names. */\nexport function encodeState(value: unknown): unknown {\n if (typeof value !== 'object' || value === null) return value\n if (Array.isArray(value)) return value.map(encodeState)\n if (isLanguage(value)) return { [LANGUAGE]: value.name }\n const out: Record<string, unknown> = {}\n for (const key in value) out[key] = encodeState((value as Record<string, unknown>)[key])\n return out\n}\n\n/** A state back from plain data; `undefined` when it names a language `find` doesn't know. */\nexport function decodeState(\n value: unknown,\n find: (name: string) => CodeLanguage | undefined,\n): unknown {\n if (typeof value !== 'object' || value === null) return value\n if (Array.isArray(value)) {\n const out: unknown[] = []\n for (const item of value) {\n const decoded = decodeState(item, find)\n if (decoded === undefined && item !== undefined) return undefined\n out.push(decoded)\n }\n return out\n }\n const record = value as Record<string, unknown>\n if (typeof record[LANGUAGE] === 'string') return find(record[LANGUAGE])\n const out: Record<string, unknown> = {}\n for (const key in record) {\n const decoded = decodeState(record[key], find)\n if (decoded === undefined && record[key] !== undefined) return undefined\n out[key] = decoded\n }\n return out\n}\n\n/** A language and every language it may hold, by name. */\nexport function languagesIn(language: CodeLanguage): Map<string, CodeLanguage> {\n const found = new Map<string, CodeLanguage>()\n const visit = (item: CodeLanguage) => {\n if (found.has(item.name)) return\n found.set(item.name, item)\n for (const inner of item.nested ?? []) visit(inner)\n }\n visit(language)\n return found\n}\n"],"mappings":";AAyBA,IAAM,WAAW;AAEjB,IAAM,cAAc,UAClB,OAAQ,MAAuB,UAAU,cACzC,OAAQ,MAAuB,eAAe;;AAGhD,SAAgB,YAAY,OAAyB;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,WAAW;CACtD,IAAI,WAAW,KAAK,GAAG,OAAO,GAAG,WAAW,MAAM,KAAK;CACvD,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,OAAO,OAAO,IAAI,OAAO,YAAa,MAAkC,IAAI;CACvF,OAAO;AACT;;AAGA,SAAgB,YACd,OACA,MACS;CACT,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,MAAiB,CAAC;EACxB,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,UAAU,YAAY,MAAM,IAAI;GACtC,IAAI,YAAY,KAAA,KAAa,SAAS,KAAA,GAAW,OAAO,KAAA;GACxD,IAAI,KAAK,OAAO;EAClB;EACA,OAAO;CACT;CACA,MAAM,SAAS;CACf,IAAI,OAAO,OAAO,cAAc,UAAU,OAAO,KAAK,OAAO,SAAS;CACtE,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,OAAO,QAAQ;EACxB,MAAM,UAAU,YAAY,OAAO,MAAM,IAAI;EAC7C,IAAI,YAAY,KAAA,KAAa,OAAO,SAAS,KAAA,GAAW,OAAO,KAAA;EAC/D,IAAI,OAAO;CACb;CACA,OAAO;AACT;;AAGA,SAAgB,YAAY,UAAmD;CAC7E,MAAM,wBAAQ,IAAI,IAA0B;CAC5C,MAAM,SAAS,SAAuB;EACpC,IAAI,MAAM,IAAI,KAAK,IAAI,GAAG;EAC1B,MAAM,IAAI,KAAK,MAAM,IAAI;EACzB,KAAK,MAAM,SAAS,KAAK,UAAU,CAAC,GAAG,MAAM,KAAK;CACpD;CACA,MAAM,QAAQ;CACd,OAAO;AACT"}
1
+ {"version":3,"file":"worker-protocol.js","names":[],"sources":["../../src/language/worker-protocol.ts"],"sourcesContent":["import type { CodeDiffHunk, CodeDiffOptions } from '../core/diff'\nimport type { CodeLanguage, CodeLineTokens } from './language'\n\n/*\n * Messages between the editor and a highlighting worker, and how states\n * cross over: languages inside a state (the script in an HTML file) go by\n * name, everything else as plain data. Languages whose states cannot cross\n * postMessage (such as Shiki's TextMate StateStack) run in `tokens` mode:\n * the worker keeps the state and sends flat line token arrays directly.\n */\n\n/** A change as sent: `[from, to, insert]`. */\nexport type WireChange = [from: number, to: number, insert: string]\n\n/** How a worker transfers syntax results back to the page for a document. */\nexport type WorkerSyntaxMode = 'auto' | 'states' | 'tokens'\n\nexport type ToWorker =\n /** `nested`: the names of the languages it may hold, which the worker's language must hold too. */\n | {\n t: 'open'\n id: number\n language: string\n nested: string[]\n tabSize: number\n mode?: WorkerSyntaxMode\n }\n /** The text, in pieces of whole lines; `done` on the last. */\n | { t: 'text'; id: number; lines: string[]; done: boolean }\n | { t: 'change'; id: number; changes: WireChange[]; length: number }\n | {\n t: 'read'\n id: number\n from: number\n until: number\n /** 1-based inclusive line range whose flat tokens should be returned in `tokens` mode. */\n tokensFrom?: number\n tokensTo?: number\n /**\n * Specific 1-based inclusive line ranges whose flat tokens should be\n * returned in `tokens` mode, skipping folded or collapsed hidden lines.\n */\n tokenRanges?: Array<[from: number, to: number]>\n /** Monotonic request sequence so newer viewport requests preempt older ones. */\n seq?: number\n }\n /** Cancels any pending highlighting work for this document without closing it. */\n | { t: 'cancel'; id: number }\n | { t: 'close'; id: number }\n /** Requests an asynchronous text diff inside the worker. */\n | {\n t: 'diff'\n id: number\n original: string\n modified: string\n options?: CodeDiffOptions\n }\n /** Cancels a queued diff request before it runs. */\n | { t: 'cancelDiff'; id: number }\n\nexport type FromWorker =\n | {\n t: 'states'\n id: number\n version: number\n seq?: number\n points: Array<[line: number, state: unknown]>\n }\n /** Flat per-line token arrays starting at 1-based line `from` (inclusive), or disjoint `ranges`. */\n | {\n t: 'tokens'\n id: number\n version: number\n seq?: number\n from: number\n lines: CodeLineTokens[]\n /** Present when the request asked for multiple disjoint visible line ranges. */\n ranges?: Array<[from: number, lines: CodeLineTokens[]]>\n frontier: number\n }\n /** The worker hasn't the language named `missing`, or (without it) can't highlight it. */\n | { t: 'unsupported'; id: number; missing?: string }\n /** Result of an asynchronous `diff` request. */\n | { t: 'diffResult'; id: number; hunks: CodeDiffHunk[] }\n\nconst LANGUAGE = '$codeLanguage'\n\nconst isLanguage = (value: object): value is CodeLanguage =>\n typeof (value as CodeLanguage).token === 'function' &&\n typeof (value as CodeLanguage).startState === 'function'\n\n/** A state as plain data, its languages replaced by their names. */\nexport function encodeState(value: unknown): unknown {\n if (typeof value !== 'object' || value === null) return value\n if (Array.isArray(value)) return value.map(encodeState)\n if (isLanguage(value)) return { [LANGUAGE]: value.name }\n const out: Record<string, unknown> = {}\n for (const key in value) out[key] = encodeState((value as Record<string, unknown>)[key])\n return out\n}\n\n/** A state back from plain data; `undefined` when it names a language `find` doesn't know. */\nexport function decodeState(\n value: unknown,\n find: (name: string) => CodeLanguage | undefined,\n): unknown {\n if (typeof value !== 'object' || value === null) return value\n if (Array.isArray(value)) {\n const out: unknown[] = []\n for (const item of value) {\n const decoded = decodeState(item, find)\n if (decoded === undefined && item !== undefined) return undefined\n out.push(decoded)\n }\n return out\n }\n const record = value as Record<string, unknown>\n if (typeof record[LANGUAGE] === 'string') return find(record[LANGUAGE])\n const out: Record<string, unknown> = {}\n for (const key in record) {\n const decoded = decodeState(record[key], find)\n if (decoded === undefined && record[key] !== undefined) return undefined\n out[key] = decoded\n }\n return out\n}\n\n/** A language and every language it may hold, by name. */\nexport function languagesIn(language: CodeLanguage): Map<string, CodeLanguage> {\n const found = new Map<string, CodeLanguage>()\n const visit = (item: CodeLanguage) => {\n if (found.has(item.name)) return\n found.set(item.name, item)\n for (const inner of item.nested ?? []) visit(inner)\n }\n visit(language)\n return found\n}\n"],"mappings":";AAqFA,IAAM,WAAW;AAEjB,IAAM,cAAc,UAClB,OAAQ,MAAuB,UAAU,cACzC,OAAQ,MAAuB,eAAe;;AAGhD,SAAgB,YAAY,OAAyB;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,WAAW;CACtD,IAAI,WAAW,KAAK,GAAG,OAAO,GAAG,WAAW,MAAM,KAAK;CACvD,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,OAAO,OAAO,IAAI,OAAO,YAAa,MAAkC,IAAI;CACvF,OAAO;AACT;;AAGA,SAAgB,YACd,OACA,MACS;CACT,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,MAAiB,CAAC;EACxB,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,UAAU,YAAY,MAAM,IAAI;GACtC,IAAI,YAAY,KAAA,KAAa,SAAS,KAAA,GAAW,OAAO,KAAA;GACxD,IAAI,KAAK,OAAO;EAClB;EACA,OAAO;CACT;CACA,MAAM,SAAS;CACf,IAAI,OAAO,OAAO,cAAc,UAAU,OAAO,KAAK,OAAO,SAAS;CACtE,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,OAAO,QAAQ;EACxB,MAAM,UAAU,YAAY,OAAO,MAAM,IAAI;EAC7C,IAAI,YAAY,KAAA,KAAa,OAAO,SAAS,KAAA,GAAW,OAAO,KAAA;EAC/D,IAAI,OAAO;CACb;CACA,OAAO;AACT;;AAGA,SAAgB,YAAY,UAAmD;CAC7E,MAAM,wBAAQ,IAAI,IAA0B;CAC5C,MAAM,SAAS,SAAuB;EACpC,IAAI,MAAM,IAAI,KAAK,IAAI,GAAG;EAC1B,MAAM,IAAI,KAAK,MAAM,IAAI;EACzB,KAAK,MAAM,SAAS,KAAK,UAAU,CAAC,GAAG,MAAM,KAAK;CACpD;CACA,MAAM,QAAQ;CACd,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { defineCodeLanguage } from "../language/language.js";
1
+ import { defineCodeLanguage, remoteCodeLanguage } from "../language/language.js";
2
2
  // src/shiki/index.ts
3
3
  /** Scope prefixes and the kind each is drawn as; the first that matches a token's scopes, from the innermost scope out, wins. */
4
4
  var SCOPES = [
@@ -132,9 +132,60 @@ function shikiLanguage(highlighter, language, options = {}) {
132
132
  comment: options.comment,
133
133
  brackets: options.brackets,
134
134
  autoClose: options.autoClose,
135
- indentAfter: options.indentAfter
135
+ indentAfter: options.indentAfter,
136
+ workerMode: "tokens"
136
137
  });
137
138
  }
138
- export { shikiLanguage, tokenTypeOfScopes };
139
+ /**
140
+ * Creates a `resolve` callback for `serveCodeHighlighting` that lazy-loads
141
+ * Shiki grammars inside the worker and wraps them with `shikiLanguage`.
142
+ *
143
+ * ```ts
144
+ * // shiki.worker.ts
145
+ * import { createHighlighter } from 'shiki'
146
+ * import { createShikiLanguageResolver } from '@dou-ui/code/shiki'
147
+ * import { serveCodeHighlighting, typescript } from '@dou-ui/code/worker'
148
+ *
149
+ * let highlighter: ReturnType<typeof createHighlighter> | undefined
150
+ * serveCodeHighlighting({
151
+ * languages: [typescript],
152
+ * resolve: createShikiLanguageResolver(
153
+ * () => (highlighter ??= createHighlighter({ langs: [], themes: [] })),
154
+ * ),
155
+ * })
156
+ * ```
157
+ */
158
+ function createShikiLanguageResolver(highlighterOrOptions) {
159
+ const opts = typeof highlighterOrOptions === "function" ? { highlighter: highlighterOrOptions } : highlighterOrOptions;
160
+ let shared = null;
161
+ const getHighlighter = () => {
162
+ if (!shared) {
163
+ const pending = Promise.resolve().then(() => opts.highlighter()).catch((error) => {
164
+ if (shared === pending) shared = null;
165
+ throw error;
166
+ });
167
+ shared = pending;
168
+ }
169
+ return shared;
170
+ };
171
+ return async (name) => {
172
+ try {
173
+ const hl = await getHighlighter();
174
+ const loaded = hl.getLoadedLanguages?.();
175
+ if (!loaded || !loaded.includes(name)) {
176
+ if (opts.loadLanguage) await opts.loadLanguage(hl, name);
177
+ else if (hl.loadLanguage) await hl.loadLanguage(name);
178
+ }
179
+ const langOptions = typeof opts.options === "function" ? opts.options(name) : opts.options;
180
+ return shikiLanguage(hl, name, {
181
+ ...langOptions,
182
+ name: langOptions?.name ?? name
183
+ });
184
+ } catch {
185
+ return null;
186
+ }
187
+ };
188
+ }
189
+ export { createShikiLanguageResolver, remoteCodeLanguage, shikiLanguage, tokenTypeOfScopes };
139
190
 
140
191
  //# sourceMappingURL=index.js.map