dsh-typst-plugin 0.0.0-stage → 0.1.0-alpha.0

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 (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +87 -0
  3. package/README.md +86 -2
  4. package/cordis.patch.yml +6 -0
  5. package/docs/images/icon.png +0 -0
  6. package/docs/plugin-detail.en.md +2 -0
  7. package/docs/plugin-detail.md +2 -0
  8. package/lib/client.js +41044 -0
  9. package/lib/client.js.map +7 -0
  10. package/lib/config.d.ts +50 -0
  11. package/lib/config.d.ts.map +1 -0
  12. package/lib/config.js +31 -0
  13. package/lib/config.js.map +7 -0
  14. package/lib/constants.d.ts +58 -0
  15. package/lib/constants.d.ts.map +1 -0
  16. package/lib/constants.js +62 -0
  17. package/lib/constants.js.map +7 -0
  18. package/lib/contract.d.ts +179 -0
  19. package/lib/contract.d.ts.map +1 -0
  20. package/lib/contract.js +1 -0
  21. package/lib/contract.js.map +7 -0
  22. package/lib/errors.d.ts +77 -0
  23. package/lib/errors.d.ts.map +1 -0
  24. package/lib/errors.js +86 -0
  25. package/lib/errors.js.map +7 -0
  26. package/lib/host/facts.d.ts +31 -0
  27. package/lib/host/facts.d.ts.map +1 -0
  28. package/lib/host/facts.js +151 -0
  29. package/lib/host/facts.js.map +7 -0
  30. package/lib/index.d.ts +2 -0
  31. package/lib/index.d.ts.map +1 -0
  32. package/lib/index.js +5 -0
  33. package/lib/index.js.map +7 -0
  34. package/lib/remote.d.ts +69 -0
  35. package/lib/remote.d.ts.map +1 -0
  36. package/lib/remote.js +146 -0
  37. package/lib/remote.js.map +7 -0
  38. package/lib/service.d.ts +47 -0
  39. package/lib/service.d.ts.map +1 -0
  40. package/lib/service.js +110 -0
  41. package/lib/service.js.map +7 -0
  42. package/lib/skills/typst.d.ts +13 -0
  43. package/lib/skills/typst.d.ts.map +1 -0
  44. package/lib/skills/typst.js +72 -0
  45. package/lib/skills/typst.js.map +7 -0
  46. package/lib/status-codec.d.ts +11 -0
  47. package/lib/status-codec.d.ts.map +1 -0
  48. package/lib/status-codec.js +6 -0
  49. package/lib/status-codec.js.map +7 -0
  50. package/lib/tools/registration.d.ts +22 -0
  51. package/lib/tools/registration.d.ts.map +1 -0
  52. package/lib/tools/registration.js +525 -0
  53. package/lib/tools/registration.js.map +7 -0
  54. package/lib/tools/shared.d.ts +31 -0
  55. package/lib/tools/shared.d.ts.map +1 -0
  56. package/lib/tools/shared.js +70 -0
  57. package/lib/tools/shared.js.map +7 -0
  58. package/lib/typert.d.ts +23 -0
  59. package/lib/typert.d.ts.map +1 -0
  60. package/lib/typert.js +67 -0
  61. package/lib/typert.js.map +7 -0
  62. package/lib/typst/diagnostics.d.ts +58 -0
  63. package/lib/typst/diagnostics.d.ts.map +1 -0
  64. package/lib/typst/diagnostics.js +171 -0
  65. package/lib/typst/diagnostics.js.map +7 -0
  66. package/lib/typst/locate.d.ts +68 -0
  67. package/lib/typst/locate.d.ts.map +1 -0
  68. package/lib/typst/locate.js +194 -0
  69. package/lib/typst/locate.js.map +7 -0
  70. package/lib/typst/mainfile.d.ts +21 -0
  71. package/lib/typst/mainfile.d.ts.map +1 -0
  72. package/lib/typst/mainfile.js +64 -0
  73. package/lib/typst/mainfile.js.map +7 -0
  74. package/lib/typst/match.d.ts +59 -0
  75. package/lib/typst/match.d.ts.map +1 -0
  76. package/lib/typst/match.js +171 -0
  77. package/lib/typst/match.js.map +7 -0
  78. package/lib/typst/oneshot.d.ts +45 -0
  79. package/lib/typst/oneshot.d.ts.map +1 -0
  80. package/lib/typst/oneshot.js +76 -0
  81. package/lib/typst/oneshot.js.map +7 -0
  82. package/lib/typst/pdf-extract.d.ts +29 -0
  83. package/lib/typst/pdf-extract.d.ts.map +1 -0
  84. package/lib/typst/pdf-extract.js +87 -0
  85. package/lib/typst/pdf-extract.js.map +7 -0
  86. package/lib/typst/pdfjs-worker.d.js +1 -0
  87. package/lib/typst/pdfjs-worker.d.js.map +7 -0
  88. package/lib/typst/text.d.ts +65 -0
  89. package/lib/typst/text.d.ts.map +1 -0
  90. package/lib/typst/text.js +314 -0
  91. package/lib/typst/text.js.map +7 -0
  92. package/lib/typst/watcher.d.ts +77 -0
  93. package/lib/typst/watcher.d.ts.map +1 -0
  94. package/lib/typst/watcher.js +219 -0
  95. package/lib/typst/watcher.js.map +7 -0
  96. package/lib/wire-schemas.d.ts +578 -0
  97. package/lib/wire-schemas.d.ts.map +1 -0
  98. package/lib/wire-schemas.js +384 -0
  99. package/lib/wire-schemas.js.map +7 -0
  100. package/lib/workspace/session.d.ts +209 -0
  101. package/lib/workspace/session.d.ts.map +1 -0
  102. package/lib/workspace/session.js +1232 -0
  103. package/lib/workspace/session.js.map +7 -0
  104. package/locale/en.json +9 -0
  105. package/locale/zh.json +9 -0
  106. package/package.json +256 -4
@@ -0,0 +1,1232 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import {
3
+ mkdir,
4
+ readFile,
5
+ realpath,
6
+ rm,
7
+ stat,
8
+ writeFile
9
+ } from "node:fs/promises";
10
+ import { tmpdir } from "node:os";
11
+ import {
12
+ basename,
13
+ dirname,
14
+ extname,
15
+ isAbsolute,
16
+ join,
17
+ relative,
18
+ resolve,
19
+ sep
20
+ } from "node:path";
21
+ import {
22
+ LIMITS,
23
+ SOURCE_FILE_MAX_BYTES,
24
+ SOURCE_FILES_MAX,
25
+ INPUT_FILES_MAX
26
+ } from "../constants.js";
27
+ import {
28
+ INSTALL_HINT,
29
+ TypstError,
30
+ TYPST_INVALID_ARGUMENT,
31
+ TYPST_MISSING,
32
+ TYPST_NOT_FOUND,
33
+ TYPST_NO_MAIN,
34
+ TYPST_NO_PREVIEW,
35
+ TYPST_PATH_OUTSIDE_WORKSPACE,
36
+ TYPST_QUOTE_NOT_FOUND,
37
+ TYPST_TIMEOUT,
38
+ TYPST_TOO_OLD,
39
+ TYPST_UNUSABLE,
40
+ TYPST_WATCH_FAILED
41
+ } from "../errors.js";
42
+ import { detectFacts, cargoSpec } from "../host/facts.js";
43
+ import { locateTypst, searchedDirs } from "../typst/locate.js";
44
+ import { chooseMain, indexTypFiles } from "../typst/mainfile.js";
45
+ import { pageCount, extractPages, pdfjsDataDir } from "../typst/pdf-extract.js";
46
+ import {
47
+ exportPdf,
48
+ renderPages
49
+ } from "../typst/oneshot.js";
50
+ import {
51
+ parsePages,
52
+ findQuote,
53
+ rectsFor,
54
+ textAt
55
+ } from "../typst/text.js";
56
+ import {
57
+ fuzzyFind,
58
+ skeleton,
59
+ lineStarts,
60
+ lineRange,
61
+ locateInSources
62
+ } from "../typst/match.js";
63
+ import { reapOrphans, Watcher } from "../typst/watcher.js";
64
+ async function realish(path) {
65
+ return realpath(path).catch(() => path);
66
+ }
67
+ class WorkspaceSession {
68
+ workspaceRoot;
69
+ realRoot = null;
70
+ log;
71
+ env;
72
+ options;
73
+ listeners = /* @__PURE__ */ new Set();
74
+ stateVersion = 0;
75
+ toolchain = { state: "missing" };
76
+ main = null;
77
+ candidates = [];
78
+ candidatesAt = 0;
79
+ generation = 1;
80
+ compileToken = 0;
81
+ startingWatcher = null;
82
+ previewError = null;
83
+ discovery = {
84
+ scanning: false,
85
+ includeExcluded: false,
86
+ visited: 0,
87
+ errors: []
88
+ };
89
+ indexing = null;
90
+ indexingPromise = null;
91
+ mainQueue = Promise.resolve();
92
+ /**
93
+ * The candidates the current document includes, as typst's own dependency
94
+ * report names them. Kept between compiles so the panel can list fragments
95
+ * apart from documents before the first successful compile settles.
96
+ */
97
+ fragments = [];
98
+ status = { phase: "idle", run: 0 };
99
+ diagnostics = [];
100
+ watcher = null;
101
+ watcherStartedAt = 0;
102
+ buildDir = null;
103
+ /** When the in-flight compile started; also when the last finished one started (check uses this). */
104
+ compilingSince = null;
105
+ finishedStartedAt = 0;
106
+ finishWaiters = /* @__PURE__ */ new Set();
107
+ restartTimer = null;
108
+ snapshots = /* @__PURE__ */ new Map();
109
+ current = null;
110
+ seq = 0;
111
+ highlights = [];
112
+ highlightSeq = 0;
113
+ view = null;
114
+ viewSeq = 0;
115
+ activation = null;
116
+ activated = false;
117
+ closed = false;
118
+ pagesCache = /* @__PURE__ */ new Map();
119
+ // Setup page: host facts, "handed to the agent", re-lookup while open.
120
+ facts = null;
121
+ factsPending = null;
122
+ setupTimer = null;
123
+ setupTicks = 0;
124
+ setupSubscribers = 0;
125
+ rechecking = null;
126
+ constructor(options) {
127
+ this.options = options;
128
+ this.workspaceRoot = resolve(options.workspaceRoot);
129
+ this.log = options.log ?? (() => void 0);
130
+ this.env = options.env ?? process.env;
131
+ }
132
+ onChange(listener) {
133
+ this.listeners.add(listener);
134
+ return () => this.listeners.delete(listener);
135
+ }
136
+ /**
137
+ * Await state changes until `signal` aborts, yielding once per coalesced
138
+ * burst (the watch stream's push side). Every yielded tick means "state
139
+ * changed since the last frame"; the caller re-reads `state()`.
140
+ */
141
+ async *onChangeWaiter(signal) {
142
+ const queue = [];
143
+ let wake = null;
144
+ const off = this.onChange(() => {
145
+ queue.push(/* @__PURE__ */ Symbol("change"));
146
+ wake?.();
147
+ wake = null;
148
+ });
149
+ const abort = () => {
150
+ wake?.();
151
+ wake = null;
152
+ };
153
+ signal.addEventListener("abort", abort, { once: true });
154
+ try {
155
+ while (!signal.aborted) {
156
+ if (queue.length === 0) {
157
+ await new Promise((done) => {
158
+ wake = done;
159
+ });
160
+ }
161
+ if (signal.aborted) return;
162
+ queue.length = 0;
163
+ yield /* @__PURE__ */ Symbol("change");
164
+ }
165
+ } finally {
166
+ off();
167
+ signal.removeEventListener("abort", abort);
168
+ }
169
+ }
170
+ emit() {
171
+ this.stateVersion += 1;
172
+ for (const listener of this.listeners) listener();
173
+ }
174
+ /** The full state frame the panel renders. */
175
+ state() {
176
+ return {
177
+ version: this.stateVersion,
178
+ generation: this.generation,
179
+ previewError: this.previewError,
180
+ discovery: { ...this.discovery },
181
+ toolchain: this.toolchainView(),
182
+ workspace: basename(this.workspaceRoot),
183
+ main: this.main,
184
+ candidates: this.candidates,
185
+ fragments: this.fragments,
186
+ status: this.status,
187
+ diagnostics: this.diagnostics,
188
+ snapshot: this.current,
189
+ highlights: this.highlights,
190
+ view: this.view,
191
+ viewSeq: this.viewSeq,
192
+ setup: {
193
+ facts: this.facts,
194
+ searched: searchedDirs(
195
+ process.platform,
196
+ this.env,
197
+ this.env.HOME ?? this.env.USERPROFILE ?? ""
198
+ )
199
+ }
200
+ };
201
+ }
202
+ toolchainView() {
203
+ const toolchain = this.toolchain;
204
+ switch (toolchain.state) {
205
+ case "ready":
206
+ return {
207
+ state: "ready",
208
+ version: toolchain.version,
209
+ path: toolchain.path,
210
+ source: toolchain.source
211
+ };
212
+ case "missing":
213
+ return { state: "missing" };
214
+ case "too_old":
215
+ return {
216
+ state: "too_old",
217
+ version: toolchain.version,
218
+ path: toolchain.path,
219
+ source: toolchain.source,
220
+ error: toolchain.error
221
+ };
222
+ case "error":
223
+ return {
224
+ state: "error",
225
+ path: toolchain.path,
226
+ source: toolchain.source,
227
+ error: toolchain.error
228
+ };
229
+ }
230
+ }
231
+ // -------------------------------------------------------------------------
232
+ // Startup: toolchain, main file, watch
233
+ // -------------------------------------------------------------------------
234
+ /** Started on the first tool call or panel subscription; a no-op afterwards. */
235
+ activate() {
236
+ this.activation ??= (async () => {
237
+ this.realRoot = await realpath(this.workspaceRoot).catch(
238
+ () => this.workspaceRoot
239
+ );
240
+ void this.detectFacts();
241
+ await this.detectToolchain();
242
+ await this.refreshCandidates(true);
243
+ if (!this.main) this.main = await this.selectInitialMain();
244
+ await this.startWatcher();
245
+ this.activated = true;
246
+ this.emit();
247
+ })().catch((error) => {
248
+ this.activation = null;
249
+ throw error;
250
+ });
251
+ return this.activation;
252
+ }
253
+ async detectToolchain(shell = true) {
254
+ const before = this.toolchain;
255
+ this.toolchain = await locateTypst({
256
+ setting: this.options.typstPath,
257
+ env: this.env,
258
+ shell
259
+ });
260
+ const changed = before.state !== this.toolchain.state || before.state !== "missing" && this.toolchain.state !== "missing" && before.path !== this.toolchain.path || before.state === "ready" && this.toolchain.state === "ready" && before.version !== this.toolchain.version;
261
+ if (!changed) return;
262
+ if (this.toolchain.state === "ready") {
263
+ this.log(
264
+ `typst ${this.toolchain.version} at ${this.toolchain.path} (${this.toolchain.source})`
265
+ );
266
+ } else {
267
+ this.log(
268
+ `typst not usable: ${this.toolchain.state} ${"error" in this.toolchain ? this.toolchain.error : ""}`
269
+ );
270
+ }
271
+ }
272
+ /** Host facts are probed once (OS, arch, package managers do not change mid-session). */
273
+ detectFacts(force = false) {
274
+ if (this.facts && !force) return Promise.resolve();
275
+ this.factsPending ??= detectFacts([cargoSpec(this.env)]).then((facts) => {
276
+ if (JSON.stringify(facts) === JSON.stringify(this.facts)) return;
277
+ this.facts = facts;
278
+ this.emit();
279
+ }).catch((error) => this.log(`could not detect host facts: ${error}`)).finally(() => {
280
+ this.factsPending = null;
281
+ });
282
+ return this.factsPending;
283
+ }
284
+ // -------------------------------------------------------------------------
285
+ // Setup page: re-lookup, hand-off
286
+ // -------------------------------------------------------------------------
287
+ /**
288
+ * Look Typst up again (the agent or the user just installed it). A usable
289
+ * Typst rescans files and starts the preview. `shell: false` skips the
290
+ * login shell (the panel's periodic recheck uses it to avoid spawning
291
+ * shells frequently).
292
+ */
293
+ recheck(shell = true) {
294
+ this.rechecking ??= (async () => {
295
+ await this.activate();
296
+ const before = this.toolchain;
297
+ await this.detectToolchain(shell);
298
+ const changed = before.state !== this.toolchain.state || before.state !== "missing" && this.toolchain.state !== "missing" && before.path !== this.toolchain.path || before.state === "ready" && this.toolchain.state === "ready" && before.version !== this.toolchain.version;
299
+ if (!changed) return;
300
+ if (this.toolchain.state === "ready") {
301
+ await this.stopWatcher();
302
+ await this.refreshCandidates(true);
303
+ if (!this.main) this.main = await this.selectInitialMain();
304
+ await this.startWatcher();
305
+ }
306
+ this.emit();
307
+ })().finally(() => {
308
+ this.rechecking = null;
309
+ });
310
+ return this.rechecking;
311
+ }
312
+ /** While the panel subscribes and Typst is unusable, re-lookup every few seconds; the preview starts by itself once Typst runs. */
313
+ watchSetup(enabled) {
314
+ this.setupSubscribers = Math.max(
315
+ 0,
316
+ this.setupSubscribers + (enabled ? 1 : -1)
317
+ );
318
+ if (enabled && !this.setupTimer && !this.closed) {
319
+ this.setupTicks = 0;
320
+ this.setupTimer = setInterval(() => {
321
+ if (this.toolchain.state === "ready" || this.rechecking) return;
322
+ const shell = ++this.setupTicks % LIMITS.setupShellEvery === 0;
323
+ if (shell) void this.detectFacts(true);
324
+ void this.recheck(shell).catch(
325
+ (error) => this.log(`recheck failed: ${error}`)
326
+ );
327
+ }, LIMITS.setupWatchMs);
328
+ this.setupTimer.unref?.();
329
+ } else if (!enabled && this.setupSubscribers === 0 && this.setupTimer) {
330
+ clearInterval(this.setupTimer);
331
+ this.setupTimer = null;
332
+ }
333
+ }
334
+ /** Locate typst again, rescan files, and restart the watch (the panel's restart button). */
335
+ async restart() {
336
+ await this.activate();
337
+ await this.stopWatcher();
338
+ await this.detectToolchain();
339
+ await this.refreshCandidates(true);
340
+ if (!this.main) this.main = await this.selectInitialMain();
341
+ await this.startWatcher();
342
+ this.emit();
343
+ }
344
+ /** Refresh complete discovery; indexed absence never proves the selected main disappeared. */
345
+ async refreshCandidates(force = false) {
346
+ if (!force && Date.now() - this.candidatesAt < 2e3) return;
347
+ if (this.indexingPromise && this.indexing) await this.indexingPromise;
348
+ else await this.discover(this.discovery.includeExcluded);
349
+ if (this.main && !await this.validMain(this.main)) {
350
+ await this.stopWatcher();
351
+ this.candidates = this.candidates.filter((path) => path !== this.main);
352
+ this.main = chooseMain(this.candidates, null);
353
+ this.resetPreview();
354
+ await this.startWatcher();
355
+ } else if (!this.main && this.activated) {
356
+ this.main = await this.selectInitialMain();
357
+ await this.startWatcher();
358
+ }
359
+ this.emit();
360
+ }
361
+ async validMain(path) {
362
+ try {
363
+ return (await stat(await this.insideWorkspace(path))).isFile();
364
+ } catch {
365
+ return false;
366
+ }
367
+ }
368
+ async selectInitialMain() {
369
+ const remembered = await this.remembered();
370
+ return remembered && await this.validMain(remembered) ? remembered : chooseMain(this.candidates, null);
371
+ }
372
+ async discover(includeExcluded, signal) {
373
+ this.indexing?.abort();
374
+ const controller = new AbortController();
375
+ this.indexing = controller;
376
+ const stopped = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
377
+ this.discovery = {
378
+ scanning: true,
379
+ includeExcluded,
380
+ visited: 0,
381
+ errors: []
382
+ };
383
+ this.emit();
384
+ const operation = (async () => {
385
+ try {
386
+ for await (const batch of indexTypFiles(
387
+ this.workspaceRoot,
388
+ includeExcluded,
389
+ stopped
390
+ )) {
391
+ if (this.closed || stopped.aborted || this.indexing !== controller)
392
+ return;
393
+ this.candidates = [
394
+ .../* @__PURE__ */ new Set([...batch.files, ...this.main ? [this.main] : []])
395
+ ];
396
+ this.discovery = {
397
+ scanning: true,
398
+ includeExcluded,
399
+ visited: batch.visited,
400
+ errors: batch.errors
401
+ };
402
+ this.emit();
403
+ }
404
+ this.candidatesAt = Date.now();
405
+ } finally {
406
+ if (this.indexing === controller) {
407
+ this.indexing = null;
408
+ this.discovery = { ...this.discovery, scanning: false };
409
+ this.emit();
410
+ }
411
+ }
412
+ })();
413
+ this.indexingPromise = operation;
414
+ return operation;
415
+ }
416
+ startWatcher() {
417
+ this.startingWatcher ??= this.performStartWatcher().finally(() => {
418
+ this.startingWatcher = null;
419
+ });
420
+ return this.startingWatcher;
421
+ }
422
+ async performStartWatcher() {
423
+ if (this.closed || this.watcher || this.toolchain.state !== "ready" || !this.main) {
424
+ if (!this.watcher) this.status = { phase: "idle", run: this.status.run };
425
+ return;
426
+ }
427
+ if (!this.buildDir) this.buildDir = await this.makeBuildDir();
428
+ if (this.closed || this.watcher || !this.main || this.toolchain.state !== "ready")
429
+ return;
430
+ const fontPaths = await this.fontPaths();
431
+ const watcher = new Watcher(
432
+ {
433
+ typst: this.toolchain.path,
434
+ version: this.toolchain.version,
435
+ cwd: this.workspaceRoot,
436
+ root: this.workspaceRoot,
437
+ fontPaths,
438
+ main: this.main,
439
+ buildDir: this.buildDir,
440
+ env: this.env,
441
+ toFile: (path) => this.displayPath(path),
442
+ log: this.log
443
+ },
444
+ {
445
+ compiling: (startedAt) => {
446
+ if (this.watcher !== watcher) return;
447
+ this.compileToken++;
448
+ this.compilingSince = startedAt;
449
+ this.status = {
450
+ ...this.status,
451
+ phase: "compiling",
452
+ error: void 0
453
+ };
454
+ this.emit();
455
+ },
456
+ finished: async (result) => {
457
+ if (this.watcher !== watcher) return;
458
+ await this.finish(
459
+ result.outcome,
460
+ result.diagnostics,
461
+ result.durationMs,
462
+ result.bytes,
463
+ result.previewError
464
+ );
465
+ },
466
+ fatal: (message) => {
467
+ if (this.watcher !== watcher) return;
468
+ void this.finish("error", [
469
+ {
470
+ severity: "error",
471
+ message,
472
+ location: null,
473
+ hints: [],
474
+ trace: []
475
+ }
476
+ ]);
477
+ },
478
+ exit: ({ code, signal, tail, expected }) => {
479
+ if (this.watcher !== watcher) return;
480
+ this.watcher = null;
481
+ if (expected || this.closed) return;
482
+ this.log(
483
+ `typst watch exited (code ${code}, signal ${signal}): ${tail}`
484
+ );
485
+ this.status = {
486
+ ...this.status,
487
+ phase: "crashed",
488
+ error: tail.split("\n").filter(Boolean).slice(-6).join("\n") || `typst exited with code ${code}`
489
+ };
490
+ this.wakeWaiters();
491
+ this.emit();
492
+ if (Date.now() - this.watcherStartedAt > 1e4 && !this.restartTimer) {
493
+ this.restartTimer = setTimeout(() => {
494
+ this.restartTimer = null;
495
+ void this.startWatcher().then(() => this.emit());
496
+ }, 1e3);
497
+ }
498
+ }
499
+ }
500
+ );
501
+ this.watcher = watcher;
502
+ this.watcherStartedAt = Date.now();
503
+ this.compilingSince = null;
504
+ this.status = { ...this.status, phase: "starting", error: void 0 };
505
+ try {
506
+ watcher.start();
507
+ } catch (error) {
508
+ this.watcher = null;
509
+ this.status = {
510
+ ...this.status,
511
+ phase: "crashed",
512
+ error: error instanceof Error ? error.message : String(error)
513
+ };
514
+ }
515
+ }
516
+ async stopWatcher() {
517
+ await this.startingWatcher;
518
+ const watcher = this.watcher;
519
+ this.watcher = null;
520
+ if (this.restartTimer) clearTimeout(this.restartTimer);
521
+ this.restartTimer = null;
522
+ await watcher?.stop();
523
+ }
524
+ async makeBuildDir() {
525
+ const base = join(
526
+ this.options.dataDir ?? join(tmpdir(), "dsh-typst"),
527
+ "build"
528
+ );
529
+ await mkdir(base, { recursive: true });
530
+ await reapOrphans(base, this.log);
531
+ const dir = join(base, `${process.pid}-${randomBytes(4).toString("hex")}`);
532
+ await mkdir(dir, { recursive: true });
533
+ return dir;
534
+ }
535
+ async finish(outcome, diagnostics, durationMs, bytes, previewFailure) {
536
+ const generation = this.generation;
537
+ const token = this.compileToken;
538
+ const startedAt = this.compilingSince ?? Date.now();
539
+ const diagnosticsWithExcerpts = await Promise.all(
540
+ diagnostics.map((entry) => this.withExcerpt(entry))
541
+ );
542
+ if (generation !== this.generation || token !== this.compileToken || this.closed)
543
+ return;
544
+ const run = this.status.run + 1;
545
+ if (outcome !== "error") {
546
+ this.previewError = previewFailure ?? null;
547
+ if (bytes) await this.addSnapshot(bytes, generation, token, run);
548
+ else
549
+ this.previewError ??= "Typst did not produce preview bytes. Retry the preview.";
550
+ }
551
+ if (generation !== this.generation || token !== this.compileToken || this.closed)
552
+ return;
553
+ this.finishedStartedAt = startedAt;
554
+ this.compilingSince = null;
555
+ this.diagnostics = diagnosticsWithExcerpts;
556
+ this.status = {
557
+ phase: outcome,
558
+ run: this.status.run + 1,
559
+ durationMs,
560
+ finishedAt: Date.now()
561
+ };
562
+ if (outcome !== "error") await this.refreshFragments(generation, token);
563
+ if (generation !== this.generation || token !== this.compileToken) return;
564
+ if (this.current) await this.relocateHighlights(this.current.seq);
565
+ if (generation !== this.generation || token !== this.compileToken || this.closed)
566
+ return;
567
+ this.wakeWaiters();
568
+ this.emit();
569
+ void this.refreshCandidates().catch(
570
+ (error) => this.log(`Discovery failed: ${String(error)}`)
571
+ );
572
+ }
573
+ /**
574
+ * Recompute the fragment set from typst's dependency report.
575
+ *
576
+ * typst names every file it loaded for the current root, so the candidates
577
+ * among them other than the main file are exactly the fragments the
578
+ * document pulls in. The report is empty until the first successful
579
+ * compile, and the previous set is kept rather than emptied, so the panel
580
+ * does not lose the distinction mid-session.
581
+ */
582
+ async refreshFragments(generation, token) {
583
+ const deps = await this.watcher?.deps().catch(() => []) ?? [];
584
+ if (deps.length === 0) return;
585
+ const loaded = new Set(
586
+ await Promise.all(deps.map((path) => realish(path)))
587
+ );
588
+ const fragments = [];
589
+ for (const candidate of this.candidates) {
590
+ if (candidate === this.main) continue;
591
+ const absolute = resolve(this.workspaceRoot, candidate);
592
+ if (loaded.has(await realish(absolute))) fragments.push(candidate);
593
+ }
594
+ if (generation !== this.generation || token !== this.compileToken || this.closed || fragments.join("\n") === this.fragments.join("\n"))
595
+ return;
596
+ this.fragments = fragments;
597
+ this.emit();
598
+ }
599
+ wakeWaiters() {
600
+ for (const wake of this.finishWaiters) wake();
601
+ }
602
+ waitForFinish(ms) {
603
+ return new Promise((done) => {
604
+ const wake = () => {
605
+ clearTimeout(timer);
606
+ this.finishWaiters.delete(wake);
607
+ done(true);
608
+ };
609
+ const timer = setTimeout(() => {
610
+ this.finishWaiters.delete(wake);
611
+ done(false);
612
+ }, ms);
613
+ this.finishWaiters.add(wake);
614
+ });
615
+ }
616
+ resetPreview() {
617
+ this.generation++;
618
+ this.compileToken++;
619
+ this.previewError = null;
620
+ this.snapshots.clear();
621
+ this.pagesCache.clear();
622
+ this.current = null;
623
+ this.diagnostics = [];
624
+ this.highlights = [];
625
+ this.view = null;
626
+ this.status = { phase: "idle", run: this.status.run };
627
+ }
628
+ // -------------------------------------------------------------------------
629
+ // Main file
630
+ // -------------------------------------------------------------------------
631
+ get mainsFile() {
632
+ return this.options.dataDir ? join(this.options.dataDir, "main-files.json") : null;
633
+ }
634
+ async remembered() {
635
+ const file = this.mainsFile;
636
+ if (!file) return null;
637
+ try {
638
+ const saved = JSON.parse(await readFile(file, "utf8"));
639
+ if (typeof saved === "object" && saved !== null) {
640
+ const value = saved[this.realRoot ?? this.workspaceRoot];
641
+ return typeof value === "string" ? value : null;
642
+ }
643
+ return null;
644
+ } catch {
645
+ return null;
646
+ }
647
+ }
648
+ async remember(main) {
649
+ const file = this.mainsFile;
650
+ if (!file) return;
651
+ let saved = {};
652
+ try {
653
+ const parsed = JSON.parse(await readFile(file, "utf8"));
654
+ if (typeof parsed === "object" && parsed !== null)
655
+ saved = parsed;
656
+ } catch {
657
+ }
658
+ saved[this.realRoot ?? this.workspaceRoot] = main;
659
+ await mkdir(dirname(file), { recursive: true });
660
+ await writeFile(file, JSON.stringify(saved, null, 2));
661
+ }
662
+ setMain(path) {
663
+ const operation = this.mainQueue.then(() => this.selectMain(path));
664
+ this.mainQueue = operation.catch(() => void 0);
665
+ return operation;
666
+ }
667
+ async selectMain(path) {
668
+ await this.activate();
669
+ const absolute = await this.insideWorkspace(path);
670
+ if (extname(absolute) !== ".typ") {
671
+ throw new TypstError(
672
+ `${path} is not a .typ file.`,
673
+ TYPST_INVALID_ARGUMENT
674
+ );
675
+ }
676
+ const info = await stat(absolute).catch(() => null);
677
+ if (!info?.isFile())
678
+ throw new TypstError(`${path} does not exist.`, TYPST_NOT_FOUND);
679
+ const main = this.relativePath(absolute);
680
+ await this.refreshCandidates(true);
681
+ if (!this.candidates.includes(main))
682
+ this.candidates = [...this.candidates, main];
683
+ if (main !== this.main || !this.watcher) {
684
+ await this.stopWatcher();
685
+ this.main = main;
686
+ this.fragments = [];
687
+ this.resetPreview();
688
+ await this.startWatcher();
689
+ }
690
+ await this.remember(main).catch(
691
+ (error) => this.log(`could not remember the main file: ${error}`)
692
+ );
693
+ this.emit();
694
+ return main;
695
+ }
696
+ // -------------------------------------------------------------------------
697
+ // Check: wait until the latest changes have compiled
698
+ // -------------------------------------------------------------------------
699
+ /** Both the toolchain and the main file are ready, or a telling error is thrown. */
700
+ requireReady() {
701
+ const toolchain = this.toolchain;
702
+ if (toolchain.state === "missing") {
703
+ throw new TypstError(
704
+ `Typst was not found on this computer. ${INSTALL_HINT}`,
705
+ TYPST_MISSING
706
+ );
707
+ }
708
+ if (toolchain.state === "too_old") {
709
+ throw new TypstError(
710
+ `${toolchain.error} Update Typst (${toolchain.path}).`,
711
+ TYPST_TOO_OLD
712
+ );
713
+ }
714
+ if (toolchain.state !== "ready") {
715
+ throw new TypstError(
716
+ "error" in toolchain ? toolchain.error : "Typst is not available.",
717
+ TYPST_UNUSABLE
718
+ );
719
+ }
720
+ if (!this.main) {
721
+ throw new TypstError(
722
+ this.candidates.length ? `Choose the main file with typst_set_main. .typ files in the workspace: ${this.candidates.slice(0, 20).join(", ")}${this.candidates.length > 20 ? ", \u2026" : ""}.` : "There are no .typ files in the workspace yet. Create one (for example main.typ), then call typst_set_main or typst_check.",
723
+ TYPST_NO_MAIN
724
+ );
725
+ }
726
+ }
727
+ /** Newest modification among the input files (typst's deps; else the main file and the workspace's .typ files). */
728
+ async inputsModifiedAt() {
729
+ let files = await this.watcher?.deps() ?? [];
730
+ if (!files.length) {
731
+ files = [this.main, ...this.candidates].filter((path) => typeof path === "string").map((path) => resolve(this.workspaceRoot, path));
732
+ }
733
+ let latest = 0;
734
+ await Promise.all(
735
+ files.slice(0, INPUT_FILES_MAX).map(async (file) => {
736
+ const info = await stat(file).catch(() => null);
737
+ if (info) latest = Math.max(latest, info.mtimeMs);
738
+ })
739
+ );
740
+ return Math.min(latest, Date.now());
741
+ }
742
+ /** Wait until every change already on disk has compiled (restart the watch when it missed changes). */
743
+ async settle(timeoutMs = LIMITS.checkTimeoutMs) {
744
+ await this.activate();
745
+ if (!this.main) await this.refreshCandidates(true);
746
+ this.requireReady();
747
+ const deadline = Date.now() + timeoutMs;
748
+ let restarted = false;
749
+ for (; ; ) {
750
+ if (!this.watcher) {
751
+ if (restarted) {
752
+ throw new TypstError(
753
+ `typst watch stopped: ${this.status.error ?? "unknown error"}`,
754
+ TYPST_WATCH_FAILED
755
+ );
756
+ }
757
+ restarted = true;
758
+ await this.startWatcher();
759
+ this.emit();
760
+ if (!this.watcher) {
761
+ throw new TypstError(
762
+ this.status.error ?? "typst watch could not start.",
763
+ TYPST_WATCH_FAILED
764
+ );
765
+ }
766
+ continue;
767
+ }
768
+ const busy = this.status.phase === "starting" || this.status.phase === "compiling";
769
+ const inputs = await this.inputsModifiedAt();
770
+ if (!busy && this.status.run > 0 && this.finishedStartedAt >= inputs)
771
+ return;
772
+ const remaining = deadline - Date.now();
773
+ if (remaining <= 0) {
774
+ throw new TypstError(
775
+ `Typst did not finish compiling within ${Math.round(timeoutMs / 1e3)} s. The document may be very large or stuck in a loop.`,
776
+ TYPST_TIMEOUT
777
+ );
778
+ }
779
+ const finished = await this.waitForFinish(
780
+ busy ? remaining : Math.min(remaining, LIMITS.settleMs)
781
+ );
782
+ if (!finished && !busy && !restarted) {
783
+ this.log(
784
+ "typst watch did not pick up the latest changes; restarting it"
785
+ );
786
+ restarted = true;
787
+ await this.stopWatcher();
788
+ await this.startWatcher();
789
+ this.emit();
790
+ }
791
+ }
792
+ }
793
+ // -------------------------------------------------------------------------
794
+ // Snapshots
795
+ // -------------------------------------------------------------------------
796
+ async addSnapshot(bytes, generation, token, run) {
797
+ if (bytes.length > LIMITS.pdfBytes) {
798
+ this.previewError = `Preview PDF exceeds ${LIMITS.pdfBytes} bytes (${bytes.length}).`;
799
+ return;
800
+ }
801
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
802
+ let pages;
803
+ try {
804
+ pages = this.current?.sha256 === sha256 ? this.current.pages : await pageCount(bytes);
805
+ } catch (error) {
806
+ this.previewError = `Could not read the preview PDF: ${String(error)}`;
807
+ return;
808
+ }
809
+ if (generation !== this.generation || token !== this.compileToken || !this.main)
810
+ return;
811
+ const info = {
812
+ generation,
813
+ main: this.main,
814
+ run,
815
+ seq: ++this.seq,
816
+ bytes: bytes.length,
817
+ pages,
818
+ sha256,
819
+ createdAt: Date.now()
820
+ };
821
+ this.snapshots.set(info.seq, { info, bytes });
822
+ while (this.snapshots.size > LIMITS.snapshots) {
823
+ const oldest = this.snapshots.keys().next().value;
824
+ if (oldest === void 0) break;
825
+ this.snapshots.delete(oldest);
826
+ this.pagesCache.delete(oldest);
827
+ }
828
+ this.current = info;
829
+ }
830
+ /** The current preview bytes, or a telling error. */
831
+ currentBytes() {
832
+ if (!this.current) {
833
+ throw new TypstError(
834
+ this.status.phase === "error" ? "The document has not compiled successfully yet; fix the errors first (see typst_check)." : "There is no preview yet.",
835
+ TYPST_NO_PREVIEW
836
+ );
837
+ }
838
+ const snapshot = this.snapshots.get(this.current.seq);
839
+ if (!snapshot)
840
+ throw new TypstError(
841
+ `Preview ${this.current.seq} is no longer available.`,
842
+ TYPST_NOT_FOUND
843
+ );
844
+ return snapshot;
845
+ }
846
+ /** Read precisely the requested retained artifact, never silently substitute the latest. */
847
+ previewBytes(identity) {
848
+ const snapshot = this.snapshots.get(identity.seq);
849
+ if (!snapshot || snapshot.info.generation !== identity.generation || snapshot.info.sha256 !== identity.sha256) {
850
+ throw new TypstError(
851
+ "The requested preview expired or belongs to another main file. Refresh the preview.",
852
+ TYPST_NOT_FOUND
853
+ );
854
+ }
855
+ return snapshot;
856
+ }
857
+ async pagesOf(seq) {
858
+ const cached = this.pagesCache.get(seq);
859
+ if (cached) return cached;
860
+ const snapshot = this.snapshots.get(seq);
861
+ if (!snapshot)
862
+ throw new TypstError(
863
+ `Preview ${seq} is no longer available.`,
864
+ TYPST_NOT_FOUND
865
+ );
866
+ const pages = await extractPages(snapshot.bytes, pdfjsDataDir());
867
+ this.pagesCache.set(seq, pages);
868
+ return pages;
869
+ }
870
+ /** A preview is required (something compiled successfully). */
871
+ requireSnapshot() {
872
+ if (!this.current) {
873
+ throw new TypstError(
874
+ this.status.phase === "error" ? "The document has not compiled successfully yet; fix the errors first (see typst_check)." : "There is no preview yet.",
875
+ TYPST_NO_PREVIEW
876
+ );
877
+ }
878
+ return this.current;
879
+ }
880
+ // -------------------------------------------------------------------------
881
+ // Panel view and highlights
882
+ // -------------------------------------------------------------------------
883
+ showPage(pageIndex) {
884
+ const snapshot = this.requireSnapshot();
885
+ if (!Number.isInteger(pageIndex) || pageIndex < 0 || pageIndex >= snapshot.pages) {
886
+ throw new TypstError(
887
+ `The document has ${snapshot.pages} page(s).`,
888
+ TYPST_INVALID_ARGUMENT
889
+ );
890
+ }
891
+ this.view = {
892
+ kind: "page",
893
+ pageIndex,
894
+ identity: {
895
+ generation: snapshot.generation,
896
+ seq: snapshot.seq,
897
+ sha256: snapshot.sha256
898
+ }
899
+ };
900
+ this.viewSeq += 1;
901
+ this.emit();
902
+ }
903
+ /** Find text in the preview: quote matching first (tolerant of whitespace, quotes, line breaks), then skeleton approximation. */
904
+ findText(pages, text, preferredPage) {
905
+ const exact = findQuote(pages, text, preferredPage);
906
+ if (exact)
907
+ return {
908
+ pageIndex: exact.pageIndex,
909
+ start: exact.start,
910
+ end: exact.end,
911
+ score: 1
912
+ };
913
+ let best = null;
914
+ for (const page of pages) {
915
+ const [hit] = fuzzyFind(text, skeleton(page.text), { max: 1 });
916
+ if (hit && (!best || hit.score > best.score + 0.05 || preferredPage === page.index && hit.score >= best.score - 0.05)) {
917
+ best = { pageIndex: page.index, ...hit };
918
+ }
919
+ }
920
+ return best;
921
+ }
922
+ async highlight(target, comment = "") {
923
+ const snapshot = this.requireSnapshot();
924
+ const pages = await this.pagesOf(snapshot.seq);
925
+ let text;
926
+ let source;
927
+ if (target.quote) {
928
+ text = target.quote;
929
+ } else if (target.file && target.line) {
930
+ const absolute = await this.insideWorkspace(target.file);
931
+ const content = await readFile(absolute, "utf8").catch(() => {
932
+ throw new TypstError(`${target.file} does not exist.`, TYPST_NOT_FOUND);
933
+ });
934
+ const starts = lineStarts(content);
935
+ const endLine = Math.max(target.line, target.endLine ?? target.line);
936
+ if (target.line > starts.length) {
937
+ throw new TypstError(
938
+ `${target.file} has ${starts.length} lines.`,
939
+ TYPST_INVALID_ARGUMENT
940
+ );
941
+ }
942
+ const range = lineRange(content, starts, target.line, endLine);
943
+ text = content.slice(range.start, range.end);
944
+ source = {
945
+ file: this.relativePath(absolute),
946
+ line: target.line,
947
+ endLine: Math.min(endLine, starts.length)
948
+ };
949
+ } else {
950
+ throw new TypstError(
951
+ "Give a quote, or a file and line.",
952
+ TYPST_INVALID_ARGUMENT
953
+ );
954
+ }
955
+ if (this.closed || snapshot.generation !== this.generation || snapshot.seq !== this.current?.seq)
956
+ throw new TypstError(
957
+ "The preview changed while locating the quote. Run typst_check and try again.",
958
+ TYPST_NOT_FOUND
959
+ );
960
+ const found = this.findText(pages, text);
961
+ if (!found) {
962
+ throw new TypstError(
963
+ source ? `No text from ${source.file}:${source.line}${source.endLine !== source.line ? `\u2013${source.endLine}` : ""} was found in the preview. The lines may contain only markup or code, or the preview may be out of date (run typst_check).` : "The quote was not found in the preview. Copy the words as they appear in the rendered document (markup is ignored), or point at source lines with file and line.",
964
+ TYPST_QUOTE_NOT_FOUND
965
+ );
966
+ }
967
+ const page = pages[found.pageIndex];
968
+ const highlight = {
969
+ id: `h${++this.highlightSeq}`,
970
+ quote: textAt(page, found.start, found.end),
971
+ comment,
972
+ ...source ? { source } : {},
973
+ identity: {
974
+ generation: snapshot.generation,
975
+ seq: snapshot.seq,
976
+ sha256: snapshot.sha256
977
+ },
978
+ seq: snapshot.seq,
979
+ pageIndex: found.pageIndex,
980
+ rects: rectsFor(page, found.start, found.end),
981
+ stale: false,
982
+ createdAt: Date.now()
983
+ };
984
+ this.highlights.push(highlight);
985
+ this.view = {
986
+ kind: "highlight",
987
+ id: highlight.id,
988
+ identity: highlight.identity
989
+ };
990
+ this.viewSeq += 1;
991
+ this.emit();
992
+ return { highlight, exact: found.score === 1 };
993
+ }
994
+ /** After a new snapshot, relocate highlights; unmatched annotations remain visible as stale. */
995
+ async relocateHighlights(seq) {
996
+ let pages;
997
+ try {
998
+ pages = await this.pagesOf(seq);
999
+ } catch {
1000
+ return;
1001
+ }
1002
+ if (this.current?.seq !== seq) return;
1003
+ this.highlights = this.highlights.map((highlight) => {
1004
+ const found = this.findText(pages, highlight.quote, highlight.pageIndex);
1005
+ if (!found) return { ...highlight, stale: true, rects: [] };
1006
+ const page = pages[found.pageIndex];
1007
+ return {
1008
+ ...highlight,
1009
+ identity: {
1010
+ generation: this.current.generation,
1011
+ seq,
1012
+ sha256: this.current.sha256
1013
+ },
1014
+ seq,
1015
+ stale: false,
1016
+ pageIndex: found.pageIndex,
1017
+ rects: rectsFor(page, found.start, found.end)
1018
+ };
1019
+ });
1020
+ this.emit();
1021
+ }
1022
+ clearHighlights(ids) {
1023
+ const before = this.highlights.length;
1024
+ this.highlights = ids?.length ? this.highlights.filter((entry) => !ids.includes(entry.id)) : [];
1025
+ const view = this.view;
1026
+ if (view?.kind === "highlight" && !this.highlights.some((entry) => entry.id === view.id)) {
1027
+ this.view = null;
1028
+ }
1029
+ this.emit();
1030
+ return before - this.highlights.length;
1031
+ }
1032
+ // -------------------------------------------------------------------------
1033
+ // Rendered text → source
1034
+ // -------------------------------------------------------------------------
1035
+ /** The project's source files: workspace `.typ` files among typst's reported deps; all candidates when deps are missing. */
1036
+ async sourceFiles() {
1037
+ const deps = (await this.watcher?.deps() ?? []).filter(
1038
+ (file) => file.endsWith(".typ")
1039
+ );
1040
+ const paths = deps.length ? deps : this.candidates.map((path) => resolve(this.workspaceRoot, path));
1041
+ const root = this.realRoot ?? this.workspaceRoot;
1042
+ const files = [];
1043
+ for (const absolute of paths.slice(0, SOURCE_FILES_MAX)) {
1044
+ const real = await realish(absolute);
1045
+ const rel = relative(root, real);
1046
+ if (rel.startsWith("..") || isAbsolute(rel)) continue;
1047
+ const info = await stat(real).catch(() => null);
1048
+ if (!info?.isFile() || info.size > SOURCE_FILE_MAX_BYTES) continue;
1049
+ files.push({
1050
+ path: rel.split(sep).join("/"),
1051
+ text: await readFile(real, "utf8")
1052
+ });
1053
+ }
1054
+ return files.sort(
1055
+ (a, b) => Number(b.path === this.main) - Number(a.path === this.main)
1056
+ );
1057
+ }
1058
+ async locateSource(text, focus) {
1059
+ await this.activate();
1060
+ return locateInSources(await this.sourceFiles(), text, focus);
1061
+ }
1062
+ /** Common workspace font directories to pass to Typst via `--font-path`. */
1063
+ async fontPaths() {
1064
+ const candidates = [
1065
+ join(this.workspaceRoot, "fonts"),
1066
+ join(this.workspaceRoot, "assets", "fonts")
1067
+ ];
1068
+ const resolved = [];
1069
+ for (const dir of candidates) {
1070
+ const s = await stat(dir).catch(() => null);
1071
+ if (s?.isDirectory()) resolved.push(dir);
1072
+ }
1073
+ return resolved;
1074
+ }
1075
+ // -------------------------------------------------------------------------
1076
+ // One-shot compiles: render images, export
1077
+ // -------------------------------------------------------------------------
1078
+ async oneshot() {
1079
+ this.requireReady();
1080
+ const fontPaths = await this.fontPaths();
1081
+ return {
1082
+ typst: this.toolchain.path,
1083
+ cwd: this.workspaceRoot,
1084
+ root: this.workspaceRoot,
1085
+ fontPaths,
1086
+ main: this.main,
1087
+ env: this.env,
1088
+ scratch: this.buildDir ?? (this.buildDir = await this.makeBuildDir()),
1089
+ toFile: (path) => this.displayPath(path)
1090
+ };
1091
+ }
1092
+ async renderPages(spec, ppi) {
1093
+ await this.activate();
1094
+ const options = await this.oneshot();
1095
+ await this.settle().catch(() => void 0);
1096
+ const total = this.current?.pages;
1097
+ let pages;
1098
+ try {
1099
+ pages = parsePages(spec, total ?? 1e4).map((index) => index + 1);
1100
+ } catch (error) {
1101
+ throw new TypstError(
1102
+ error instanceof Error ? error.message : String(error),
1103
+ TYPST_INVALID_ARGUMENT
1104
+ );
1105
+ }
1106
+ if (!pages.length) {
1107
+ throw new TypstError(
1108
+ total ? `The document has ${total} page(s).` : "No pages selected.",
1109
+ TYPST_INVALID_ARGUMENT
1110
+ );
1111
+ }
1112
+ if (pages.length > LIMITS.renderPages) {
1113
+ throw new TypstError(
1114
+ `Render at most ${LIMITS.renderPages} pages at a time.`,
1115
+ TYPST_INVALID_ARGUMENT
1116
+ );
1117
+ }
1118
+ const result = await renderPages(options, pages, ppi);
1119
+ const diagnostics = await Promise.all(
1120
+ result.diagnostics.map((entry) => this.withExcerpt(entry))
1121
+ );
1122
+ return { ...result, diagnostics, pages, total };
1123
+ }
1124
+ async exportPdf(path, extra) {
1125
+ await this.activate();
1126
+ const options = await this.oneshot();
1127
+ const absolute = await this.insideWorkspace(path);
1128
+ if (extname(absolute).toLowerCase() !== ".pdf") {
1129
+ throw new TypstError(
1130
+ "The output path must end in .pdf.",
1131
+ TYPST_INVALID_ARGUMENT
1132
+ );
1133
+ }
1134
+ await mkdir(dirname(absolute), { recursive: true });
1135
+ const result = await exportPdf(options, absolute, extra);
1136
+ const diagnostics = await Promise.all(
1137
+ result.diagnostics.map((entry) => this.withExcerpt(entry))
1138
+ );
1139
+ if (!result.ok)
1140
+ return { ...result, diagnostics, path: this.relativePath(absolute) };
1141
+ const bytes = new Uint8Array(await readFile(absolute));
1142
+ return {
1143
+ ...result,
1144
+ diagnostics,
1145
+ path: this.relativePath(absolute),
1146
+ bytes: bytes.length,
1147
+ pages: await pageCount(bytes).catch(() => void 0)
1148
+ };
1149
+ }
1150
+ // -------------------------------------------------------------------------
1151
+ // Paths
1152
+ // -------------------------------------------------------------------------
1153
+ /** Workspace-relative path (/ separated). */
1154
+ relativePath(absolute) {
1155
+ return relative(this.workspaceRoot, absolute).split(sep).join("/");
1156
+ }
1157
+ /** A path as typst printed it (relative to the workspace root, or absolute) → display path. */
1158
+ displayPath(path) {
1159
+ if (!isAbsolute(path)) return path.split(sep).join("/");
1160
+ for (const root of [this.workspaceRoot, this.realRoot]) {
1161
+ if (!root) continue;
1162
+ const rel = relative(root, path);
1163
+ if (!rel.startsWith("..") && !isAbsolute(rel))
1164
+ return rel.split(sep).join("/");
1165
+ }
1166
+ return path;
1167
+ }
1168
+ /** Resolve a path inside the workspace (through symlinks); refuse escapes. */
1169
+ async insideWorkspace(path) {
1170
+ if (!path || path.includes("\0")) {
1171
+ throw new TypstError("Empty path.", TYPST_INVALID_ARGUMENT);
1172
+ }
1173
+ const absolute = resolve(this.workspaceRoot, path);
1174
+ const root = this.realRoot ?? await realpath(this.workspaceRoot).catch(() => this.workspaceRoot);
1175
+ let existing = absolute;
1176
+ let rest = "";
1177
+ for (; ; ) {
1178
+ try {
1179
+ const real = await realpath(existing);
1180
+ const full = rest ? join(real, rest) : real;
1181
+ const rel = relative(root, full);
1182
+ if (rel.startsWith("..") || isAbsolute(rel)) break;
1183
+ return absolute;
1184
+ } catch {
1185
+ const parent = dirname(existing);
1186
+ if (parent === existing) break;
1187
+ rest = rest ? join(basename(existing), rest) : basename(existing);
1188
+ existing = parent;
1189
+ }
1190
+ }
1191
+ throw new TypstError(
1192
+ `${path} is outside the workspace.`,
1193
+ TYPST_PATH_OUTSIDE_WORKSPACE
1194
+ );
1195
+ }
1196
+ /** The erroring line of a workspace file. */
1197
+ async withExcerpt(diagnostic) {
1198
+ const location = diagnostic.location;
1199
+ if (!location || location.file.startsWith("@") || isAbsolute(location.file))
1200
+ return diagnostic;
1201
+ try {
1202
+ const text = await readFile(
1203
+ resolve(this.workspaceRoot, location.file),
1204
+ "utf8"
1205
+ );
1206
+ const line = text.split("\n")[location.line - 1];
1207
+ return line === void 0 ? diagnostic : { ...diagnostic, excerpt: line.replace(/\s+$/, "").slice(0, 300) };
1208
+ } catch {
1209
+ return diagnostic;
1210
+ }
1211
+ }
1212
+ // -------------------------------------------------------------------------
1213
+ async close() {
1214
+ this.closed = true;
1215
+ this.indexing?.abort();
1216
+ this.setupSubscribers = 0;
1217
+ this.watchSetup(false);
1218
+ await this.stopWatcher();
1219
+ if (this.buildDir)
1220
+ await rm(this.buildDir, { recursive: true, force: true }).catch(
1221
+ () => void 0
1222
+ );
1223
+ }
1224
+ /** Synchronously end the watch (process exit). */
1225
+ killNow() {
1226
+ this.watcher?.killNow();
1227
+ }
1228
+ }
1229
+ export {
1230
+ WorkspaceSession
1231
+ };
1232
+ //# sourceMappingURL=session.js.map