dsh-typst-plugin 0.0.0-stage → 0.1.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 (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +121 -0
  3. package/README.md +120 -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 +41996 -0
  9. package/lib/client.js.map +7 -0
  10. package/lib/config.d.ts +107 -0
  11. package/lib/config.d.ts.map +1 -0
  12. package/lib/config.js +167 -0
  13. package/lib/config.js.map +1 -0
  14. package/lib/constants.d.ts +77 -0
  15. package/lib/constants.d.ts.map +1 -0
  16. package/lib/constants.js +85 -0
  17. package/lib/constants.js.map +1 -0
  18. package/lib/contract.d.ts +263 -0
  19. package/lib/contract.d.ts.map +1 -0
  20. package/lib/contract.js +9 -0
  21. package/lib/contract.js.map +1 -0
  22. package/lib/diagnostic-text.d.ts +13 -0
  23. package/lib/diagnostic-text.d.ts.map +1 -0
  24. package/lib/diagnostic-text.js +28 -0
  25. package/lib/diagnostic-text.js.map +1 -0
  26. package/lib/errors.d.ts +119 -0
  27. package/lib/errors.d.ts.map +1 -0
  28. package/lib/errors.js +161 -0
  29. package/lib/errors.js.map +1 -0
  30. package/lib/host/facts.d.ts +31 -0
  31. package/lib/host/facts.d.ts.map +1 -0
  32. package/lib/host/facts.js +145 -0
  33. package/lib/host/facts.js.map +1 -0
  34. package/lib/host/which.d.ts +20 -0
  35. package/lib/host/which.d.ts.map +1 -0
  36. package/lib/host/which.js +50 -0
  37. package/lib/host/which.js.map +1 -0
  38. package/lib/index.d.ts +2 -0
  39. package/lib/index.d.ts.map +1 -0
  40. package/lib/index.js +2 -0
  41. package/lib/index.js.map +1 -0
  42. package/lib/remote.d.ts +70 -0
  43. package/lib/remote.d.ts.map +1 -0
  44. package/lib/remote.js +156 -0
  45. package/lib/remote.js.map +1 -0
  46. package/lib/service.d.ts +71 -0
  47. package/lib/service.d.ts.map +1 -0
  48. package/lib/service.js +213 -0
  49. package/lib/service.js.map +1 -0
  50. package/lib/skills/typst.d.ts +13 -0
  51. package/lib/skills/typst.d.ts.map +1 -0
  52. package/lib/skills/typst.js +78 -0
  53. package/lib/skills/typst.js.map +1 -0
  54. package/lib/status-codec.d.ts +11 -0
  55. package/lib/status-codec.d.ts.map +1 -0
  56. package/lib/status-codec.js +11 -0
  57. package/lib/status-codec.js.map +1 -0
  58. package/lib/tools/registration.d.ts +23 -0
  59. package/lib/tools/registration.d.ts.map +1 -0
  60. package/lib/tools/registration.js +758 -0
  61. package/lib/tools/registration.js.map +1 -0
  62. package/lib/tools/shared.d.ts +30 -0
  63. package/lib/tools/shared.d.ts.map +1 -0
  64. package/lib/tools/shared.js +79 -0
  65. package/lib/tools/shared.js.map +1 -0
  66. package/lib/typert.d.ts +25 -0
  67. package/lib/typert.d.ts.map +1 -0
  68. package/lib/typert.js +116 -0
  69. package/lib/typert.js.map +1 -0
  70. package/lib/typst/diagnostics.d.ts +58 -0
  71. package/lib/typst/diagnostics.d.ts.map +1 -0
  72. package/lib/typst/diagnostics.js +237 -0
  73. package/lib/typst/diagnostics.js.map +1 -0
  74. package/lib/typst/flags.d.ts +8 -0
  75. package/lib/typst/flags.d.ts.map +1 -0
  76. package/lib/typst/flags.js +8 -0
  77. package/lib/typst/flags.js.map +1 -0
  78. package/lib/typst/locate.d.ts +61 -0
  79. package/lib/typst/locate.d.ts.map +1 -0
  80. package/lib/typst/locate.js +152 -0
  81. package/lib/typst/locate.js.map +1 -0
  82. package/lib/typst/mainfile.d.ts +40 -0
  83. package/lib/typst/mainfile.d.ts.map +1 -0
  84. package/lib/typst/mainfile.js +136 -0
  85. package/lib/typst/mainfile.js.map +1 -0
  86. package/lib/typst/match.d.ts +67 -0
  87. package/lib/typst/match.d.ts.map +1 -0
  88. package/lib/typst/match.js +227 -0
  89. package/lib/typst/match.js.map +1 -0
  90. package/lib/typst/oneshot.d.ts +48 -0
  91. package/lib/typst/oneshot.d.ts.map +1 -0
  92. package/lib/typst/oneshot.js +86 -0
  93. package/lib/typst/oneshot.js.map +1 -0
  94. package/lib/typst/owners.d.ts +28 -0
  95. package/lib/typst/owners.d.ts.map +1 -0
  96. package/lib/typst/owners.js +98 -0
  97. package/lib/typst/owners.js.map +1 -0
  98. package/lib/typst/pdf-extract.d.ts +28 -0
  99. package/lib/typst/pdf-extract.d.ts.map +1 -0
  100. package/lib/typst/pdf-extract.js +111 -0
  101. package/lib/typst/pdf-extract.js.map +1 -0
  102. package/lib/typst/process.d.ts +73 -0
  103. package/lib/typst/process.d.ts.map +1 -0
  104. package/lib/typst/process.js +147 -0
  105. package/lib/typst/process.js.map +1 -0
  106. package/lib/typst/text.d.ts +62 -0
  107. package/lib/typst/text.d.ts.map +1 -0
  108. package/lib/typst/text.js +282 -0
  109. package/lib/typst/text.js.map +1 -0
  110. package/lib/typst/watcher.d.ts +76 -0
  111. package/lib/typst/watcher.d.ts.map +1 -0
  112. package/lib/typst/watcher.js +210 -0
  113. package/lib/typst/watcher.js.map +1 -0
  114. package/lib/wire-schemas.d.ts +433 -0
  115. package/lib/wire-schemas.d.ts.map +1 -0
  116. package/lib/wire-schemas.js +428 -0
  117. package/lib/wire-schemas.js.map +1 -0
  118. package/lib/workspace/containment.d.ts +25 -0
  119. package/lib/workspace/containment.d.ts.map +1 -0
  120. package/lib/workspace/containment.js +54 -0
  121. package/lib/workspace/containment.js.map +1 -0
  122. package/lib/workspace/session.d.ts +268 -0
  123. package/lib/workspace/session.d.ts.map +1 -0
  124. package/lib/workspace/session.js +1576 -0
  125. package/lib/workspace/session.js.map +1 -0
  126. package/locale/en.json +15 -0
  127. package/locale/zh.json +15 -0
  128. package/package.json +113 -4
  129. package/release-provenance.json +137 -0
@@ -0,0 +1,1576 @@
1
+ /**
2
+ * One workspace's Typst workbench state: toolchain detection, main-file
3
+ * choice, the `typst watch` lifecycle, preview snapshots, agent highlights,
4
+ * source matching, and the settle algorithm `typst_check` relies on.
5
+ * Ported from the ZCode typst-workbench server (0.2.0) `src/app/session.ts`,
6
+ * adapted to this repository's error domain and framed as a plain class the
7
+ * cordis service registers per workspace root (unit-testable without a
8
+ * harness). Host half only.
9
+ * @module dsh-typst/workspace/session
10
+ */
11
+ import { createHash } from "node:crypto";
12
+ import { mkdir, lstat, open, readFile, realpath, rm, stat, } from "node:fs/promises";
13
+ import { tmpdir } from "node:os";
14
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, } from "node:path";
15
+ import { workspaceWritableRoots, SandboxInvalidRootError, } from "@deepseek-ai/dsh-sandbox";
16
+ import { LIMITS, SOURCE_BYTES_MAX, SOURCE_FILE_MAX_BYTES, SOURCE_FILES_MAX, INPUT_FILES_MAX, } from "../constants.js";
17
+ import { INSTALL_HINT, TypstError, TYPST_INVALID_ARGUMENT, TYPST_MAIN_CHANGED, TYPST_MISSING, TYPST_NOT_FOUND, TYPST_NO_MAIN, TYPST_NO_PREVIEW, TYPST_PAGE_OUT_OF_RANGE, TYPST_PATH_OUTSIDE_WORKSPACE, TYPST_QUOTE_NOT_FOUND, TYPST_SANDBOX_INVALID_ROOT, TYPST_SANDBOX_READ_ONLY, TYPST_TIMEOUT, TYPST_TOO_OLD, TYPST_UNUSABLE, TYPST_WATCH_FAILED, } from "../errors.js";
18
+ import { detectFacts, cargoSpec } from "../host/facts.js";
19
+ import { locateTypst, searchedDirs } from "../typst/locate.js";
20
+ import { chooseMain, indexTypFiles } from "../typst/mainfile.js";
21
+ import { pageCount, extractPages, pdfjsDataDir } from "../typst/pdf-extract.js";
22
+ import { exportPdf, renderPages, } from "../typst/oneshot.js";
23
+ import { parsePages, findQuote, rectsFor, textAt, } from "../typst/text.js";
24
+ import { fuzzyFind, skeleton, lineStarts, lineRange, locateInSources, } from "../typst/match.js";
25
+ import { Watcher } from "../typst/watcher.js";
26
+ import { makeBuildDir } from "../typst/owners.js";
27
+ import { ProcessRunner } from "../typst/process.js";
28
+ import { isWithin, resolveInside } from "./containment.js";
29
+ import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
30
+ /**
31
+ * The real path of a file, or the path itself when it cannot be resolved.
32
+ *
33
+ * typst reports the paths it resolved, and a resolved path is the real one:
34
+ * macOS's temporary directory is a symlink to /private/var, so the report and
35
+ * the workspace root spell the same file two ways. Both sides are resolved
36
+ * before they are compared.
37
+ * @param path - the path to resolve.
38
+ * @returns the real path, or the input when it does not exist.
39
+ */
40
+ async function realish(path) {
41
+ return realpath(path).catch(() => path);
42
+ }
43
+ export class WorkspaceSession {
44
+ workspaceRoot;
45
+ realRoot = null;
46
+ log;
47
+ env;
48
+ process;
49
+ options;
50
+ listeners = new Set();
51
+ stateVersion = 0;
52
+ toolchain = { state: "missing" };
53
+ main = null;
54
+ candidates = [];
55
+ candidatesAt = 0;
56
+ generation = 1;
57
+ compileToken = 0;
58
+ startingWatcher = null;
59
+ previewError = null;
60
+ discovery = {
61
+ scanning: false,
62
+ includeExcluded: false,
63
+ visited: 0,
64
+ errors: [],
65
+ };
66
+ indexing = null;
67
+ indexingPromise = null;
68
+ mainQueue = Promise.resolve();
69
+ /**
70
+ * The candidates the current document includes, as typst's own dependency
71
+ * report names them. Kept between compiles so the panel can list fragments
72
+ * apart from documents before the first successful compile settles.
73
+ */
74
+ fragments = [];
75
+ status = { phase: "idle", run: 0 };
76
+ diagnostics = [];
77
+ /** Full diagnostic count of the last round, before the frame cap. */
78
+ diagnosticsTotal = 0;
79
+ watcher = null;
80
+ retiring = null;
81
+ stopPromise = Promise.resolve();
82
+ watcherStartedAt = 0;
83
+ buildDir = null;
84
+ /** Cancellation handles for in-flight one-shot compiles. */
85
+ liveOneshots = new Set();
86
+ /** When the in-flight compile started; also when the last finished one started (check uses this). */
87
+ compilingSince = null;
88
+ finishedStartedAt = 0;
89
+ finishGeneration = 0;
90
+ /** Monotonic count of finished compiles; lets settle notice a wake it missed. */
91
+ finishVersion = 0;
92
+ /** Input signature the last completed compile consumed. */
93
+ compiledInputs = null;
94
+ finishWaiters = new Set();
95
+ restartTimer = null;
96
+ snapshots = new Map();
97
+ current = null;
98
+ seq = 0;
99
+ highlights = [];
100
+ highlightSeq = 0;
101
+ view = null;
102
+ viewSeq = 0;
103
+ activation = null;
104
+ activated = false;
105
+ closed = false;
106
+ pagesCache = new Map();
107
+ /** Per-compile excerpt cache: one read per file, keyed by mtime. */
108
+ excerptCache = new Map();
109
+ // Setup page: host facts, "handed to the agent", re-lookup while open.
110
+ facts = null;
111
+ factsPending = null;
112
+ setupTimer = null;
113
+ setupTicks = 0;
114
+ setupSubscribers = 0;
115
+ rechecking = null;
116
+ recheckShell = false;
117
+ constructor(options) {
118
+ this.options = options;
119
+ this.workspaceRoot = resolve(options.workspaceRoot);
120
+ this.log = options.log ?? (() => undefined);
121
+ this.env = options.env ?? process.env;
122
+ this.process = new ProcessRunner(options.subprocess);
123
+ }
124
+ /**
125
+ * The plugin settings this session compiles with, read per request. The
126
+ * settings page commits volatile values in place, so a long-lived session
127
+ * sees a change without being rebuilt.
128
+ */
129
+ settings() {
130
+ return (this.options.resolveSettings?.() ?? {
131
+ typstPath: this.options.typstPath ?? "",
132
+ fontPaths: this.options.fontPaths ?? [],
133
+ packagePath: this.options.packagePath ?? "",
134
+ excludeDirs: this.options.excludeDirs ?? [],
135
+ });
136
+ }
137
+ onChange(listener) {
138
+ this.listeners.add(listener);
139
+ return () => this.listeners.delete(listener);
140
+ }
141
+ /**
142
+ * Await state changes until `signal` aborts, yielding once per coalesced
143
+ * burst (the watch stream's push side). Every yielded tick means "state
144
+ * changed since the last frame"; the caller re-reads `state()`.
145
+ */
146
+ async *onChangeWaiter(signal) {
147
+ const queue = [];
148
+ let wake = null;
149
+ const off = this.onChange(() => {
150
+ queue.push(Symbol("change"));
151
+ wake?.();
152
+ wake = null;
153
+ });
154
+ const abort = () => {
155
+ wake?.();
156
+ wake = null;
157
+ };
158
+ signal.addEventListener("abort", abort, { once: true });
159
+ try {
160
+ while (!signal.aborted) {
161
+ if (queue.length === 0) {
162
+ await new Promise((done) => {
163
+ wake = done;
164
+ });
165
+ }
166
+ if (signal.aborted)
167
+ return;
168
+ // Coalesce the burst: one frame per drain, not per emit.
169
+ queue.length = 0;
170
+ yield Symbol("change");
171
+ }
172
+ }
173
+ finally {
174
+ off();
175
+ signal.removeEventListener("abort", abort);
176
+ }
177
+ }
178
+ emit() {
179
+ this.stateVersion += 1;
180
+ for (const listener of this.listeners)
181
+ listener();
182
+ }
183
+ /** The full state frame the panel renders. */
184
+ state() {
185
+ return {
186
+ version: this.stateVersion,
187
+ generation: this.generation,
188
+ previewError: this.previewError,
189
+ discovery: { ...this.discovery },
190
+ toolchain: this.toolchainView(),
191
+ workspace: basename(this.workspaceRoot),
192
+ workspaceRoot: this.workspaceRoot,
193
+ main: this.main,
194
+ candidates: this.candidates,
195
+ fragments: this.fragments,
196
+ status: this.status,
197
+ diagnostics: this.diagnostics,
198
+ diagnosticsTotal: this.diagnosticsTotal,
199
+ diagnosticsTruncated: this.diagnosticsTotal > this.diagnostics.length,
200
+ snapshot: this.current,
201
+ highlights: this.highlights,
202
+ view: this.view,
203
+ viewSeq: this.viewSeq,
204
+ setup: {
205
+ facts: this.facts,
206
+ searched: searchedDirs(process.platform, this.env, this.env.HOME ?? this.env.USERPROFILE ?? ""),
207
+ },
208
+ };
209
+ }
210
+ toolchainView() {
211
+ const toolchain = this.toolchain;
212
+ switch (toolchain.state) {
213
+ case "ready":
214
+ return {
215
+ state: "ready",
216
+ version: toolchain.version,
217
+ path: toolchain.path,
218
+ source: toolchain.source,
219
+ };
220
+ case "missing":
221
+ return { state: "missing" };
222
+ case "too_old":
223
+ return {
224
+ state: "too_old",
225
+ version: toolchain.version,
226
+ path: toolchain.path,
227
+ source: toolchain.source,
228
+ error: toolchain.error,
229
+ };
230
+ case "error":
231
+ return {
232
+ state: "error",
233
+ path: toolchain.path,
234
+ source: toolchain.source,
235
+ error: toolchain.error,
236
+ };
237
+ }
238
+ }
239
+ /**
240
+ * Whether this session has started, or is starting, its watch. A session
241
+ * that never ran reads the new settings when its first request activates
242
+ * it, so a settings commit must not activate one just to restart it.
243
+ */
244
+ get active() {
245
+ return this.activation !== null;
246
+ }
247
+ // -------------------------------------------------------------------------
248
+ // Startup: toolchain, main file, watch
249
+ // -------------------------------------------------------------------------
250
+ /** Started on the first tool call or panel subscription; a no-op afterwards. */
251
+ activate() {
252
+ this.activation ??= (async () => {
253
+ this.realRoot = await realpath(this.workspaceRoot).catch(() => this.workspaceRoot);
254
+ void this.detectFacts();
255
+ await this.detectToolchain();
256
+ await this.refreshCandidates(true);
257
+ if (!this.main)
258
+ this.main = await this.selectInitialMain();
259
+ await this.startWatcher();
260
+ this.activated = true;
261
+ this.emit();
262
+ })().catch((error) => {
263
+ this.activation = null;
264
+ throw error;
265
+ });
266
+ return this.activation;
267
+ }
268
+ /** Whether a located toolchain differs from the previously cached one. */
269
+ toolchainChanged(before, after) {
270
+ return (before.state !== after.state ||
271
+ (before.state !== "missing" &&
272
+ after.state !== "missing" &&
273
+ before.path !== after.path) ||
274
+ (before.state === "ready" &&
275
+ after.state === "ready" &&
276
+ before.version !== after.version));
277
+ }
278
+ async detectToolchain(shell = true) {
279
+ const before = this.toolchain;
280
+ this.toolchain = await locateTypst({
281
+ setting: this.settings().typstPath,
282
+ env: this.env,
283
+ shell,
284
+ process: this.process,
285
+ cwd: this.workspaceRoot,
286
+ });
287
+ if (!this.toolchainChanged(before, this.toolchain))
288
+ return;
289
+ if (this.toolchain.state === "ready") {
290
+ this.log(`typst ${this.toolchain.version} at ${this.toolchain.path} (${this.toolchain.source})`);
291
+ }
292
+ else {
293
+ this.log(`typst not usable: ${this.toolchain.state} ${"error" in this.toolchain ? this.toolchain.error : ""}`);
294
+ }
295
+ }
296
+ /** Host facts are probed once (OS, arch, package managers do not change mid-session). */
297
+ detectFacts(force = false) {
298
+ if (this.facts && !force)
299
+ return Promise.resolve();
300
+ this.factsPending ??= detectFacts([cargoSpec(this.env)])
301
+ .then((facts) => {
302
+ if (JSON.stringify(facts) === JSON.stringify(this.facts))
303
+ return;
304
+ this.facts = facts;
305
+ this.emit();
306
+ })
307
+ .catch((error) => this.log(`could not detect host facts: ${error}`))
308
+ .finally(() => {
309
+ this.factsPending = null;
310
+ });
311
+ return this.factsPending;
312
+ }
313
+ // -------------------------------------------------------------------------
314
+ // Setup page: re-lookup, hand-off
315
+ // -------------------------------------------------------------------------
316
+ /**
317
+ * Look Typst up again (the agent or the user just installed it). A usable
318
+ * Typst rescans files and starts the preview. `shell: false` skips the
319
+ * login shell (the panel's periodic recheck uses it to avoid spawning
320
+ * shells frequently).
321
+ */
322
+ async recheck(shell = true) {
323
+ if (this.rechecking !== null) {
324
+ // A caller that needs the login-shell probe must not be dropped because
325
+ // a shell-less panel recheck happened to be in flight.
326
+ if (shell)
327
+ this.recheckShell = true;
328
+ await this.rechecking;
329
+ return;
330
+ }
331
+ this.rechecking = this.runRecheck(shell).finally(() => {
332
+ this.rechecking = null;
333
+ });
334
+ await this.rechecking;
335
+ if (this.recheckShell) {
336
+ this.recheckShell = false;
337
+ await this.recheck(true);
338
+ }
339
+ }
340
+ async runRecheck(shell) {
341
+ await this.activate();
342
+ const before = this.toolchain;
343
+ await this.detectToolchain(shell);
344
+ if (!this.toolchainChanged(before, this.toolchain))
345
+ return;
346
+ if (this.toolchain.state === "ready") {
347
+ await this.stopWatcher();
348
+ await this.refreshCandidates(true);
349
+ if (!this.main)
350
+ this.main = await this.selectInitialMain();
351
+ await this.startWatcher();
352
+ }
353
+ this.emit();
354
+ }
355
+ /** While the panel subscribes and Typst is unusable, re-lookup every few seconds; the preview starts by itself once Typst runs. */
356
+ watchSetup(enabled) {
357
+ this.setupSubscribers = Math.max(0, this.setupSubscribers + (enabled ? 1 : -1));
358
+ if (enabled && !this.setupTimer && !this.closed) {
359
+ this.setupTicks = 0;
360
+ this.setupTimer = setInterval(() => {
361
+ if (this.toolchain.state === "ready" || this.rechecking)
362
+ return;
363
+ const shell = ++this.setupTicks % LIMITS.setupShellEvery === 0;
364
+ if (shell)
365
+ void this.detectFacts(true);
366
+ void this.recheck(shell).catch((error) => this.log(`recheck failed: ${error}`));
367
+ }, LIMITS.setupWatchMs);
368
+ this.setupTimer.unref?.();
369
+ }
370
+ else if (!enabled && this.setupSubscribers === 0 && this.setupTimer) {
371
+ clearInterval(this.setupTimer);
372
+ this.setupTimer = null;
373
+ }
374
+ }
375
+ /** Locate typst again, rescan files, and restart the watch (the panel's restart button). */
376
+ async restart() {
377
+ await this.activate();
378
+ await this.stopWatcher();
379
+ await this.detectToolchain();
380
+ await this.refreshCandidates(true);
381
+ if (!this.main)
382
+ this.main = await this.selectInitialMain();
383
+ await this.startWatcher();
384
+ this.emit();
385
+ }
386
+ /** Refresh complete discovery; indexed absence never proves the selected main disappeared. */
387
+ async refreshCandidates(force = false) {
388
+ if (!force && Date.now() - this.candidatesAt < 2_000)
389
+ return;
390
+ const mainAtStart = this.main;
391
+ if (this.indexingPromise && this.indexing)
392
+ await this.indexingPromise;
393
+ else
394
+ await this.discover(this.discovery.includeExcluded);
395
+ if (mainAtStart && !(await this.validMain(mainAtStart))) {
396
+ // A concurrent setMain may have chosen a different main while discovery
397
+ // was in flight; never overwrite that choice with this refresh's view.
398
+ if (this.main !== mainAtStart)
399
+ return;
400
+ await this.stopWatcher();
401
+ this.candidates = this.candidates.filter((path) => path !== mainAtStart);
402
+ this.main = chooseMain(this.candidates, null);
403
+ this.resetPreview();
404
+ await this.startWatcher();
405
+ }
406
+ else if (!this.main && this.activated) {
407
+ this.main = await this.selectInitialMain();
408
+ await this.startWatcher();
409
+ }
410
+ this.emit();
411
+ }
412
+ async validMain(path) {
413
+ try {
414
+ return (await stat(await this.insideWorkspace(path))).isFile();
415
+ }
416
+ catch (error) {
417
+ const code = error.code;
418
+ if (code === "ENOENT" ||
419
+ code === "ENOTDIR" ||
420
+ code === TYPST_PATH_OUTSIDE_WORKSPACE)
421
+ return false;
422
+ // A transient stat failure must not silently discard the main file and
423
+ // clear the preview; keep the choice and try again next refresh.
424
+ this.log(`Could not inspect ${path}: ${String(error)}`);
425
+ return true;
426
+ }
427
+ }
428
+ async selectInitialMain() {
429
+ const remembered = await this.remembered();
430
+ return remembered && (await this.validMain(remembered))
431
+ ? remembered
432
+ : chooseMain(this.candidates, null);
433
+ }
434
+ async discover(includeExcluded, signal) {
435
+ this.indexing?.abort();
436
+ const controller = new AbortController();
437
+ this.indexing = controller;
438
+ const stopped = signal
439
+ ? AbortSignal.any([signal, controller.signal])
440
+ : controller.signal;
441
+ this.discovery = {
442
+ scanning: true,
443
+ includeExcluded,
444
+ visited: 0,
445
+ errors: [],
446
+ };
447
+ this.emit();
448
+ const operation = (async () => {
449
+ const found = new Set();
450
+ let lastEmit = 0;
451
+ try {
452
+ for await (const batch of indexTypFiles(this.workspaceRoot, includeExcluded, stopped, this.settings().excludeDirs)) {
453
+ if (this.closed || stopped.aborted || this.indexing !== controller)
454
+ return;
455
+ for (const file of batch.added)
456
+ found.add(file);
457
+ if (this.main)
458
+ found.add(this.main);
459
+ const now = Date.now();
460
+ if (batch.done || now - lastEmit >= LIMITS.notifyMs) {
461
+ lastEmit = now;
462
+ this.candidates = [...found];
463
+ this.discovery = {
464
+ scanning: true,
465
+ includeExcluded,
466
+ visited: batch.visited,
467
+ errors: batch.errors,
468
+ };
469
+ this.emit();
470
+ }
471
+ }
472
+ this.candidates = [...found];
473
+ this.candidatesAt = Date.now();
474
+ this.emit();
475
+ }
476
+ catch (error) {
477
+ // A newer discover supersedes this one; that is normal and must not
478
+ // reject the caller (refreshCandidates, setMain, restart) with an
479
+ // AbortError it did not cause.
480
+ if (stopped.aborted || this.indexing !== controller)
481
+ return;
482
+ throw error;
483
+ }
484
+ finally {
485
+ if (this.indexing === controller) {
486
+ this.indexing = null;
487
+ this.discovery = { ...this.discovery, scanning: false };
488
+ this.emit();
489
+ }
490
+ }
491
+ })();
492
+ this.indexingPromise = operation;
493
+ return operation;
494
+ }
495
+ startWatcher() {
496
+ this.startingWatcher ??= this.performStartWatcher().finally(() => {
497
+ this.startingWatcher = null;
498
+ });
499
+ return this.startingWatcher;
500
+ }
501
+ async performStartWatcher() {
502
+ await this.stopPromise;
503
+ if (this.closed ||
504
+ this.watcher ||
505
+ this.toolchain.state !== "ready" ||
506
+ !this.main) {
507
+ if (!this.watcher)
508
+ this.status = { phase: "idle", run: this.status.run };
509
+ return;
510
+ }
511
+ if (!this.buildDir)
512
+ this.buildDir = await this.makeBuildDir();
513
+ if (this.closed ||
514
+ this.watcher ||
515
+ !this.main ||
516
+ this.toolchain.state !== "ready")
517
+ return;
518
+ const settings = this.settings();
519
+ const fontPaths = await this.fontPaths(settings.fontPaths);
520
+ const watcher = new Watcher({
521
+ typst: this.toolchain.path,
522
+ version: this.toolchain.version,
523
+ cwd: this.workspaceRoot,
524
+ root: this.workspaceRoot,
525
+ fontPaths,
526
+ packagePath: settings.packagePath || undefined,
527
+ main: this.main,
528
+ buildDir: this.buildDir,
529
+ process: this.process,
530
+ env: this.env,
531
+ toFile: (path) => this.displayPath(path),
532
+ log: this.log,
533
+ }, {
534
+ compiling: (startedAt) => {
535
+ if (this.watcher !== watcher)
536
+ return;
537
+ this.compileToken++;
538
+ this.compilingSince = startedAt;
539
+ this.status = {
540
+ ...this.status,
541
+ phase: "compiling",
542
+ error: undefined,
543
+ };
544
+ this.emit();
545
+ },
546
+ finished: async (result) => {
547
+ if (this.watcher !== watcher)
548
+ return;
549
+ await this.finish(result.outcome, result.diagnostics, result.durationMs, result.bytes, result.previewError);
550
+ },
551
+ fatal: (message) => {
552
+ if (this.watcher !== watcher)
553
+ return;
554
+ void this.finish("error", [
555
+ {
556
+ severity: "error",
557
+ message,
558
+ location: null,
559
+ hints: [],
560
+ trace: [],
561
+ },
562
+ ]);
563
+ },
564
+ exit: ({ code, signal, tail, expected }) => {
565
+ if (this.watcher !== watcher)
566
+ return;
567
+ this.watcher = null;
568
+ if (expected || this.closed)
569
+ return;
570
+ this.log(`typst watch exited (code ${code}, signal ${signal}): ${tail}`);
571
+ this.status = {
572
+ ...this.status,
573
+ phase: "crashed",
574
+ error: tail.split("\n").filter(Boolean).slice(-6).join("\n") ||
575
+ `typst exited with code ${code}`,
576
+ };
577
+ this.wakeWaiters();
578
+ this.emit();
579
+ if (Date.now() - this.watcherStartedAt > 10_000 &&
580
+ !this.restartTimer) {
581
+ this.restartTimer = setTimeout(() => {
582
+ this.restartTimer = null;
583
+ void this.startWatcher().then(() => this.emit());
584
+ }, 1_000);
585
+ }
586
+ },
587
+ });
588
+ this.watcher = watcher;
589
+ this.watcherStartedAt = Date.now();
590
+ this.compilingSince = null;
591
+ this.status = { ...this.status, phase: "starting", error: undefined };
592
+ try {
593
+ watcher.start();
594
+ }
595
+ catch (error) {
596
+ this.watcher = null;
597
+ this.status = {
598
+ ...this.status,
599
+ phase: "crashed",
600
+ error: error instanceof Error ? error.message : String(error),
601
+ };
602
+ }
603
+ }
604
+ stopWatcher() {
605
+ const watcher = this.watcher;
606
+ this.watcher = null;
607
+ if (this.restartTimer)
608
+ clearTimeout(this.restartTimer);
609
+ this.restartTimer = null;
610
+ this.compileToken++;
611
+ if (!watcher)
612
+ return this.stopPromise;
613
+ this.retiring = watcher;
614
+ const done = watcher.stop().finally(() => {
615
+ if (this.retiring === watcher)
616
+ this.retiring = null;
617
+ });
618
+ this.stopPromise = done;
619
+ return done;
620
+ }
621
+ async makeBuildDir() {
622
+ return makeBuildDir(this.options.dataDir ?? join(tmpdir(), "dsh-typst"), this.log);
623
+ }
624
+ async finish(outcome, diagnostics, durationMs, bytes, previewFailure) {
625
+ const generation = this.generation;
626
+ const token = this.compileToken;
627
+ const startedAt = this.compilingSince ?? Date.now();
628
+ const shown = diagnostics.slice(0, LIMITS.diagnostics);
629
+ const diagnosticsWithExcerpts = await Promise.all(shown.map((entry) => this.withExcerpt(entry)));
630
+ if (generation !== this.generation ||
631
+ token !== this.compileToken ||
632
+ this.closed)
633
+ return;
634
+ const run = this.status.run + 1;
635
+ if (outcome !== "error") {
636
+ this.previewError = previewFailure ?? null;
637
+ if (bytes)
638
+ await this.addSnapshot(bytes, generation, token, run);
639
+ else
640
+ this.previewError ??=
641
+ "Typst did not produce preview bytes. Retry the preview.";
642
+ }
643
+ if (generation !== this.generation ||
644
+ token !== this.compileToken ||
645
+ this.closed)
646
+ return;
647
+ this.finishedStartedAt = startedAt;
648
+ this.finishGeneration = generation;
649
+ this.compiledInputs = (await this.inputsModifiedAt()).signature;
650
+ this.compilingSince = null;
651
+ this.diagnostics = diagnosticsWithExcerpts;
652
+ this.diagnosticsTotal = diagnostics.length;
653
+ this.status = {
654
+ phase: outcome,
655
+ run: this.status.run + 1,
656
+ durationMs,
657
+ finishedAt: Date.now(),
658
+ };
659
+ // The fragment set belongs to the state a waiter reads, so it is settled
660
+ // before the waiters wake: a caller that waits for the compile must see
661
+ // the document's fragments in the frame it gets.
662
+ if (outcome !== "error")
663
+ await this.refreshFragments(generation, token);
664
+ if (generation !== this.generation ||
665
+ token !== this.compileToken ||
666
+ this.closed)
667
+ return;
668
+ // With no highlights there is nothing to extract: wake immediately. With
669
+ // highlights, the relocated identities are part of the state a waiter
670
+ // reads, so finish that before waking.
671
+ if (this.current && this.highlights.length > 0) {
672
+ await this.relocateHighlights(this.current.seq);
673
+ if (generation !== this.generation ||
674
+ token !== this.compileToken ||
675
+ this.closed)
676
+ return;
677
+ }
678
+ this.wakeWaiters();
679
+ this.finishVersion++;
680
+ this.emit();
681
+ void this.refreshCandidates().catch((error) => this.log(`Discovery failed: ${String(error)}`));
682
+ }
683
+ /**
684
+ * Recompute the fragment set from typst's dependency report.
685
+ *
686
+ * typst names every file it loaded for the current root, so the candidates
687
+ * among them other than the main file are exactly the fragments the
688
+ * document pulls in. The report is empty until the first successful
689
+ * compile, and the previous set is kept rather than emptied, so the panel
690
+ * does not lose the distinction mid-session.
691
+ */
692
+ async refreshFragments(generation, token) {
693
+ const deps = (await this.watcher?.deps().catch(() => [])) ?? [];
694
+ if (deps.length === 0)
695
+ return;
696
+ // typst reports the paths it resolved, and a resolved path is the real
697
+ // one: both sides are resolved before they are compared.
698
+ const loaded = new Set(await Promise.all(deps.map((path) => realish(path))));
699
+ const fragments = [];
700
+ for (const candidate of this.candidates) {
701
+ if (candidate === this.main)
702
+ continue;
703
+ const absolute = resolve(this.workspaceRoot, candidate);
704
+ if (loaded.has(await realish(absolute)))
705
+ fragments.push(candidate);
706
+ }
707
+ if (generation !== this.generation ||
708
+ token !== this.compileToken ||
709
+ this.closed ||
710
+ fragments.join("\n") === this.fragments.join("\n"))
711
+ return;
712
+ this.fragments = fragments;
713
+ this.emit();
714
+ }
715
+ wakeWaiters() {
716
+ for (const wake of this.finishWaiters)
717
+ wake();
718
+ }
719
+ waitForFinish(ms, signal) {
720
+ return new Promise((done) => {
721
+ let settled = false;
722
+ let timer;
723
+ const finish = (value) => {
724
+ if (settled)
725
+ return;
726
+ settled = true;
727
+ clearTimeout(timer);
728
+ this.finishWaiters.delete(wake);
729
+ signal?.removeEventListener("abort", onAbort);
730
+ done(value);
731
+ };
732
+ const wake = () => finish(true);
733
+ const onAbort = () => finish(false);
734
+ timer = setTimeout(() => finish(false), ms);
735
+ timer.unref?.();
736
+ this.finishWaiters.add(wake);
737
+ if (signal !== undefined) {
738
+ if (signal.aborted)
739
+ finish(false);
740
+ else
741
+ signal.addEventListener("abort", onAbort, { once: true });
742
+ }
743
+ });
744
+ }
745
+ resetPreview() {
746
+ this.generation++;
747
+ this.compileToken++;
748
+ this.finishGeneration = 0;
749
+ this.compiledInputs = null;
750
+ this.previewError = null;
751
+ this.snapshots.clear();
752
+ this.pagesCache.clear();
753
+ this.excerptCache.clear();
754
+ this.current = null;
755
+ this.diagnostics = [];
756
+ this.diagnosticsTotal = 0;
757
+ this.highlights = [];
758
+ this.fragments = [];
759
+ this.view = null;
760
+ this.status = { phase: "idle", run: this.status.run };
761
+ }
762
+ // -------------------------------------------------------------------------
763
+ // Main file
764
+ // -------------------------------------------------------------------------
765
+ get mainsFile() {
766
+ return this.options.dataDir
767
+ ? join(this.options.dataDir, "main-files.json")
768
+ : null;
769
+ }
770
+ async remembered() {
771
+ const file = this.mainsFile;
772
+ if (!file)
773
+ return null;
774
+ try {
775
+ const saved = JSON.parse(await readFile(file, "utf8"));
776
+ if (typeof saved === "object" && saved !== null) {
777
+ const value = saved[this.realRoot ?? this.workspaceRoot];
778
+ return typeof value === "string" ? value : null;
779
+ }
780
+ return null;
781
+ }
782
+ catch {
783
+ return null;
784
+ }
785
+ }
786
+ async remember(main) {
787
+ const file = this.mainsFile;
788
+ if (!file)
789
+ return;
790
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
791
+ await withFileLock(file, async () => {
792
+ let saved = {};
793
+ try {
794
+ const parsed = JSON.parse(await readFile(file, "utf8"));
795
+ if (typeof parsed === "object" && parsed !== null)
796
+ saved = parsed;
797
+ }
798
+ catch {
799
+ // First save.
800
+ }
801
+ saved[this.realRoot ?? this.workspaceRoot] = main;
802
+ await writeFileAtomic(file, JSON.stringify(saved, null, 2), {
803
+ mode: 0o600,
804
+ dirMode: 0o700,
805
+ });
806
+ }, { waitMs: 2_000 });
807
+ }
808
+ setMain(path) {
809
+ const operation = this.mainQueue.then(() => this.selectMain(path));
810
+ this.mainQueue = operation.catch(() => undefined);
811
+ return operation;
812
+ }
813
+ async selectMain(path) {
814
+ await this.activate();
815
+ const absolute = await this.insideWorkspace(path);
816
+ if (extname(absolute) !== ".typ") {
817
+ throw new TypstError(`${path} is not a .typ file.`, TYPST_INVALID_ARGUMENT);
818
+ }
819
+ const info = await stat(absolute).catch(() => null);
820
+ if (!info?.isFile())
821
+ throw new TypstError(`${path} does not exist.`, TYPST_NOT_FOUND);
822
+ const main = this.relativePath(absolute);
823
+ await this.refreshCandidates(true);
824
+ if (!this.candidates.includes(main))
825
+ this.candidates = [...this.candidates, main];
826
+ if (main !== this.main || !this.watcher) {
827
+ await this.stopWatcher();
828
+ this.main = main;
829
+ // The fragment set belongs to the root that reported it; a new root
830
+ // has to compile before the panel can tell its fragments again.
831
+ this.fragments = [];
832
+ this.resetPreview();
833
+ await this.startWatcher();
834
+ }
835
+ await this.remember(main).catch((error) => this.log(`could not remember the main file: ${error}`));
836
+ this.emit();
837
+ return main;
838
+ }
839
+ // -------------------------------------------------------------------------
840
+ // Check: wait until the latest changes have compiled
841
+ // -------------------------------------------------------------------------
842
+ /** Both the toolchain and the main file are ready, or a telling error is thrown. */
843
+ requireReady() {
844
+ const toolchain = this.toolchain;
845
+ if (toolchain.state === "missing") {
846
+ throw new TypstError(`Typst was not found on this computer. ${INSTALL_HINT}`, TYPST_MISSING);
847
+ }
848
+ if (toolchain.state === "too_old") {
849
+ throw new TypstError(`${toolchain.error} Update Typst (${toolchain.path}).`, TYPST_TOO_OLD);
850
+ }
851
+ if (toolchain.state !== "ready") {
852
+ throw new TypstError("error" in toolchain ? toolchain.error : "Typst is not available.", TYPST_UNUSABLE);
853
+ }
854
+ if (!this.main) {
855
+ throw new TypstError(this.candidates.length
856
+ ? `Choose the main file with typst_set_main. .typ files in the workspace: ${this.candidates.slice(0, 20).join(", ")}${this.candidates.length > 20 ? ", …" : ""}.`
857
+ : "There are no .typ files in the workspace yet. Create one (for example main.typ), then call typst_set_main or typst_check.", TYPST_NO_MAIN);
858
+ }
859
+ }
860
+ /**
861
+ * Newest modification and a stable signature over the input files (typst's
862
+ * deps; else the main file and the workspace's .typ files). The signature
863
+ * includes size and mtime, so a rolled-back mtime or a same-mtime rewrite is
864
+ * still detected as a different input set.
865
+ */
866
+ async inputsModifiedAt() {
867
+ let files = (await this.watcher?.deps()) ?? [];
868
+ if (!files.length) {
869
+ files = [this.main, ...this.candidates]
870
+ .filter((path) => typeof path === "string")
871
+ .map((path) => resolve(this.workspaceRoot, path));
872
+ }
873
+ let latest = 0;
874
+ const parts = [];
875
+ await Promise.all(files.slice(0, INPUT_FILES_MAX).map(async (file) => {
876
+ const info = await stat(file).catch(() => null);
877
+ if (!info) {
878
+ parts.push(`${file}:missing`);
879
+ return;
880
+ }
881
+ latest = Math.max(latest, info.mtimeMs);
882
+ parts.push(`${file}:${info.mtimeMs}:${info.size}`);
883
+ }));
884
+ parts.sort();
885
+ return {
886
+ max: latest,
887
+ future: latest > Date.now() + 1_000,
888
+ signature: parts.join("\n"),
889
+ };
890
+ }
891
+ /** Wait until every change already on disk has compiled (restart the watch when it missed changes). */
892
+ async settle(timeoutMs = LIMITS.checkTimeoutMs, signal) {
893
+ await this.activate();
894
+ if (this.closed) {
895
+ throw new TypstError("The workspace session is closed.", TYPST_WATCH_FAILED);
896
+ }
897
+ if (!this.main)
898
+ await this.refreshCandidates(true);
899
+ this.requireReady();
900
+ const deadline = Date.now() + timeoutMs;
901
+ let restarted = false;
902
+ for (;;) {
903
+ signal?.throwIfAborted();
904
+ if (this.closed) {
905
+ throw new TypstError("The workspace session is closed.", TYPST_WATCH_FAILED);
906
+ }
907
+ if (!this.watcher) {
908
+ if (restarted) {
909
+ throw new TypstError(`typst watch stopped: ${this.status.error ?? "unknown error"}`, TYPST_WATCH_FAILED);
910
+ }
911
+ restarted = true;
912
+ await this.startWatcher();
913
+ this.emit();
914
+ if (!this.watcher) {
915
+ throw new TypstError(this.status.error ?? "typst watch could not start.", TYPST_WATCH_FAILED);
916
+ }
917
+ continue;
918
+ }
919
+ const version = this.finishVersion;
920
+ const busy = this.status.phase === "starting" || this.status.phase === "compiling";
921
+ const inputs = await this.inputsModifiedAt();
922
+ // A compile may finish while the input signatures are being read; its
923
+ // wake happened before the waiter below exists, so re-evaluate instead.
924
+ if (this.finishVersion !== version)
925
+ continue;
926
+ if (!busy &&
927
+ this.status.run > 0 &&
928
+ this.finishGeneration === this.generation &&
929
+ this.compiledInputs !== null &&
930
+ this.compiledInputs === inputs.signature)
931
+ return;
932
+ if (!busy &&
933
+ this.status.run > 0 &&
934
+ this.finishGeneration === this.generation &&
935
+ this.compiledInputs === null &&
936
+ !inputs.future &&
937
+ this.finishedStartedAt >= inputs.max)
938
+ return;
939
+ const remaining = deadline - Date.now();
940
+ if (remaining <= 0) {
941
+ throw new TypstError(`Typst did not finish compiling within ${Math.round(timeoutMs / 1e3)} s. The document may be very large or stuck in a loop.`, TYPST_TIMEOUT);
942
+ }
943
+ const finished = await this.waitForFinish(busy ? remaining : Math.min(remaining, LIMITS.settleMs), signal);
944
+ signal?.throwIfAborted();
945
+ if (!finished && !busy && !restarted) {
946
+ this.log("typst watch did not pick up the latest changes; restarting it");
947
+ restarted = true;
948
+ await this.stopWatcher();
949
+ await this.startWatcher();
950
+ this.emit();
951
+ }
952
+ }
953
+ }
954
+ // -------------------------------------------------------------------------
955
+ // Snapshots
956
+ // -------------------------------------------------------------------------
957
+ async addSnapshot(bytes, generation, token, run) {
958
+ if (bytes.length > LIMITS.pdfBytes) {
959
+ this.previewError = `Preview PDF exceeds ${LIMITS.pdfBytes} bytes (${bytes.length}).`;
960
+ return;
961
+ }
962
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
963
+ let pages;
964
+ try {
965
+ pages =
966
+ this.current?.sha256 === sha256
967
+ ? this.current.pages
968
+ : await pageCount(bytes);
969
+ }
970
+ catch (error) {
971
+ this.previewError = `Could not read the preview PDF: ${String(error)}`;
972
+ return;
973
+ }
974
+ if (generation !== this.generation ||
975
+ token !== this.compileToken ||
976
+ !this.main)
977
+ return;
978
+ const info = {
979
+ generation,
980
+ main: this.main,
981
+ run,
982
+ seq: ++this.seq,
983
+ bytes: bytes.length,
984
+ pages,
985
+ sha256,
986
+ createdAt: Date.now(),
987
+ };
988
+ this.snapshots.set(info.seq, { info, bytes });
989
+ const retainedBytes = () => {
990
+ let total = 0;
991
+ for (const snapshot of this.snapshots.values())
992
+ total += snapshot.bytes.length;
993
+ return total;
994
+ };
995
+ while (this.snapshots.size > LIMITS.snapshots ||
996
+ retainedBytes() > LIMITS.snapshotBytes) {
997
+ if (this.snapshots.size <= 1)
998
+ break;
999
+ const oldest = this.snapshots.keys().next().value;
1000
+ if (oldest === undefined)
1001
+ break;
1002
+ this.snapshots.delete(oldest);
1003
+ this.pagesCache.delete(oldest);
1004
+ }
1005
+ this.current = info;
1006
+ }
1007
+ /** Read precisely the requested retained artifact, never silently substitute the latest. */
1008
+ previewBytes(identity) {
1009
+ const snapshot = this.snapshots.get(identity.seq);
1010
+ if (!snapshot ||
1011
+ snapshot.info.generation !== identity.generation ||
1012
+ snapshot.info.sha256 !== identity.sha256) {
1013
+ throw new TypstError("The requested preview expired or belongs to another main file. Refresh the preview.", TYPST_NOT_FOUND);
1014
+ }
1015
+ return snapshot;
1016
+ }
1017
+ async pagesOf(seq) {
1018
+ const cached = this.pagesCache.get(seq);
1019
+ if (cached)
1020
+ return cached;
1021
+ const snapshot = this.snapshots.get(seq);
1022
+ if (!snapshot)
1023
+ throw new TypstError(`Preview ${seq} is no longer available.`, TYPST_NOT_FOUND);
1024
+ const pages = await extractPages(snapshot.bytes, pdfjsDataDir());
1025
+ this.pagesCache.set(seq, pages);
1026
+ return pages;
1027
+ }
1028
+ /** A preview is required (something compiled successfully). */
1029
+ requireSnapshot() {
1030
+ if (!this.current) {
1031
+ throw new TypstError(this.status.phase === "error"
1032
+ ? "The document has not compiled successfully yet; fix the errors first (see typst_check)."
1033
+ : "There is no preview yet.", TYPST_NO_PREVIEW);
1034
+ }
1035
+ return this.current;
1036
+ }
1037
+ // -------------------------------------------------------------------------
1038
+ // Panel view and highlights
1039
+ // -------------------------------------------------------------------------
1040
+ showPage(pageIndex) {
1041
+ const snapshot = this.requireSnapshot();
1042
+ if (!Number.isInteger(pageIndex) ||
1043
+ pageIndex < 0 ||
1044
+ pageIndex >= snapshot.pages) {
1045
+ throw new TypstError(`The document has ${snapshot.pages} page(s).`, TYPST_INVALID_ARGUMENT);
1046
+ }
1047
+ this.view = {
1048
+ kind: "page",
1049
+ pageIndex,
1050
+ identity: {
1051
+ generation: snapshot.generation,
1052
+ seq: snapshot.seq,
1053
+ sha256: snapshot.sha256,
1054
+ },
1055
+ };
1056
+ this.viewSeq += 1;
1057
+ this.emit();
1058
+ }
1059
+ /**
1060
+ * When a highlight is created from source lines, count how many times the
1061
+ * same rendered passage occurred before the recorded range. Typst emits
1062
+ * repeated text in document order, so that ordinal disambiguates identical
1063
+ * quotes on the same page.
1064
+ */
1065
+ async occurrenceForSource(text, source) {
1066
+ const files = await this.sourceFiles().catch(() => []);
1067
+ const file = files.find((entry) => entry.path === source.file);
1068
+ if (!file)
1069
+ return 0;
1070
+ const starts = lineStarts(file.text);
1071
+ const before = file.text.slice(0, starts[source.line - 1] ?? 0);
1072
+ const folded = (value) => value.replace(/\s+/g, " ").trim().toLowerCase();
1073
+ const needle = folded(text);
1074
+ if (!needle)
1075
+ return 0;
1076
+ const haystack = folded(before);
1077
+ let ordinal = 0;
1078
+ let from = 0;
1079
+ for (;;) {
1080
+ const at = haystack.indexOf(needle, from);
1081
+ if (at < 0)
1082
+ return ordinal;
1083
+ ordinal++;
1084
+ from = at + needle.length;
1085
+ }
1086
+ }
1087
+ /** Find text in the preview: quote matching first (tolerant of whitespace, quotes, line breaks), then skeleton approximation. */
1088
+ findText(pages, text, preferredPage, from, occurrence) {
1089
+ const exact = findQuote(pages, text, preferredPage, from, occurrence);
1090
+ if (exact)
1091
+ return {
1092
+ pageIndex: exact.pageIndex,
1093
+ start: exact.start,
1094
+ end: exact.end,
1095
+ score: 1,
1096
+ };
1097
+ let best = null;
1098
+ for (const page of pages) {
1099
+ const [hit] = fuzzyFind(text, skeleton(page.text), { max: 1 });
1100
+ if (hit &&
1101
+ (!best ||
1102
+ hit.score > best.score + 0.05 ||
1103
+ (preferredPage === page.index && hit.score >= best.score - 0.05))) {
1104
+ best = { pageIndex: page.index, ...hit };
1105
+ }
1106
+ }
1107
+ return best;
1108
+ }
1109
+ async highlight(target, comment = "") {
1110
+ const snapshot = this.requireSnapshot();
1111
+ const pages = await this.pagesOf(snapshot.seq);
1112
+ let text;
1113
+ let source;
1114
+ if (target.quote) {
1115
+ text = target.quote;
1116
+ }
1117
+ else if (target.file && target.line) {
1118
+ if (extname(target.file).toLowerCase() !== ".typ") {
1119
+ throw new TypstError(`${target.file} is not a .typ file.`, TYPST_INVALID_ARGUMENT);
1120
+ }
1121
+ const absolute = await this.insideWorkspace(target.file);
1122
+ const handle = await open(absolute, "r").catch(() => {
1123
+ throw new TypstError(`${target.file} does not exist.`, TYPST_NOT_FOUND);
1124
+ });
1125
+ let content;
1126
+ try {
1127
+ const info = await handle.stat();
1128
+ if (!info.isFile()) {
1129
+ throw new TypstError(`${target.file} is not a regular file.`, TYPST_INVALID_ARGUMENT);
1130
+ }
1131
+ if (info.size > SOURCE_FILE_MAX_BYTES) {
1132
+ throw new TypstError(`${target.file} is too large to inspect (${info.size} bytes).`, TYPST_INVALID_ARGUMENT);
1133
+ }
1134
+ content = await handle.readFile("utf8");
1135
+ }
1136
+ finally {
1137
+ await handle.close();
1138
+ }
1139
+ const starts = lineStarts(content);
1140
+ const endLine = Math.max(target.line, target.endLine ?? target.line);
1141
+ if (target.line > starts.length) {
1142
+ throw new TypstError(`${target.file} has ${starts.length} lines.`, TYPST_INVALID_ARGUMENT);
1143
+ }
1144
+ const range = lineRange(content, starts, target.line, endLine);
1145
+ text = content.slice(range.start, range.end);
1146
+ source = {
1147
+ file: this.relativePath(absolute),
1148
+ line: target.line,
1149
+ endLine: Math.min(endLine, starts.length),
1150
+ };
1151
+ }
1152
+ else {
1153
+ throw new TypstError("Give a quote, or a file and line.", TYPST_INVALID_ARGUMENT);
1154
+ }
1155
+ if (this.closed ||
1156
+ snapshot.generation !== this.generation ||
1157
+ snapshot.seq !== this.current?.seq)
1158
+ throw new TypstError("The preview changed while locating the quote. Run typst_check and try again.", TYPST_NOT_FOUND);
1159
+ const occurrence = source
1160
+ ? await this.occurrenceForSource(text, source)
1161
+ : undefined;
1162
+ const found = this.findText(pages, text, undefined, undefined, occurrence);
1163
+ if (!found) {
1164
+ throw new TypstError(source
1165
+ ? `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).`
1166
+ : "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.", TYPST_QUOTE_NOT_FOUND);
1167
+ }
1168
+ const page = pages[found.pageIndex];
1169
+ const highlight = {
1170
+ id: `h${++this.highlightSeq}`,
1171
+ quote: textAt(page, found.start, found.end),
1172
+ comment,
1173
+ ...(source ? { source } : {}),
1174
+ identity: {
1175
+ generation: snapshot.generation,
1176
+ seq: snapshot.seq,
1177
+ sha256: snapshot.sha256,
1178
+ },
1179
+ seq: snapshot.seq,
1180
+ pageIndex: found.pageIndex,
1181
+ startOffset: found.start,
1182
+ ...(occurrence === undefined ? {} : { occurrence }),
1183
+ rects: rectsFor(page, found.start, found.end),
1184
+ stale: false,
1185
+ createdAt: Date.now(),
1186
+ };
1187
+ this.highlights.push(highlight);
1188
+ this.view = {
1189
+ kind: "highlight",
1190
+ id: highlight.id,
1191
+ identity: highlight.identity,
1192
+ };
1193
+ this.viewSeq += 1;
1194
+ this.emit();
1195
+ return { highlight, exact: found.score === 1 };
1196
+ }
1197
+ /** After a new snapshot, relocate highlights; unmatched annotations remain visible as stale. */
1198
+ async relocateHighlights(seq) {
1199
+ let pages;
1200
+ try {
1201
+ pages = await this.pagesOf(seq);
1202
+ }
1203
+ catch {
1204
+ return;
1205
+ }
1206
+ if (this.current?.seq !== seq)
1207
+ return;
1208
+ this.highlights = this.highlights.map((highlight) => {
1209
+ const from = highlight.startOffset;
1210
+ const occurrence = highlight.occurrence;
1211
+ const found = this.findText(pages, highlight.quote, highlight.pageIndex, from, occurrence) ??
1212
+ (from === undefined
1213
+ ? null
1214
+ : this.findText(pages, highlight.quote, highlight.pageIndex));
1215
+ if (!found)
1216
+ return { ...highlight, stale: true, rects: [] };
1217
+ const page = pages[found.pageIndex];
1218
+ return {
1219
+ ...highlight,
1220
+ identity: {
1221
+ generation: this.current.generation,
1222
+ seq,
1223
+ sha256: this.current.sha256,
1224
+ },
1225
+ seq,
1226
+ stale: false,
1227
+ pageIndex: found.pageIndex,
1228
+ startOffset: found.start,
1229
+ ...(highlight.occurrence === undefined
1230
+ ? {}
1231
+ : { occurrence: highlight.occurrence }),
1232
+ rects: rectsFor(page, found.start, found.end),
1233
+ };
1234
+ });
1235
+ const activeView = this.view;
1236
+ if (activeView?.kind === "highlight") {
1237
+ const current = this.highlights.find((entry) => entry.id === activeView.id);
1238
+ if (current !== undefined) {
1239
+ this.view = { ...activeView, identity: current.identity };
1240
+ }
1241
+ }
1242
+ this.emit();
1243
+ }
1244
+ clearHighlights(ids) {
1245
+ const before = this.highlights.length;
1246
+ this.highlights = ids?.length
1247
+ ? this.highlights.filter((entry) => !ids.includes(entry.id))
1248
+ : [];
1249
+ const view = this.view;
1250
+ if (view?.kind === "highlight" &&
1251
+ !this.highlights.some((entry) => entry.id === view.id)) {
1252
+ this.view = null;
1253
+ }
1254
+ this.emit();
1255
+ return before - this.highlights.length;
1256
+ }
1257
+ // -------------------------------------------------------------------------
1258
+ // Rendered text → source
1259
+ // -------------------------------------------------------------------------
1260
+ /** The project's source files: workspace `.typ` files among typst's reported deps; all candidates when deps are missing. */
1261
+ async sourceFiles(signal) {
1262
+ const deps = ((await this.watcher?.deps()) ?? []).filter((file) => file.endsWith(".typ"));
1263
+ const paths = deps.length
1264
+ ? deps
1265
+ : this.candidates.map((path) => resolve(this.workspaceRoot, path));
1266
+ const root = this.realRoot ?? this.workspaceRoot;
1267
+ const files = [];
1268
+ let bytes = 0;
1269
+ for (const absolute of paths) {
1270
+ signal?.throwIfAborted();
1271
+ if (files.length >= SOURCE_FILES_MAX || bytes > SOURCE_BYTES_MAX)
1272
+ break;
1273
+ const real = await realish(absolute);
1274
+ if (!isWithin(root, real))
1275
+ continue;
1276
+ const rel = relative(root, real);
1277
+ const info = await stat(real).catch(() => null);
1278
+ if (!info?.isFile() || info.size > SOURCE_FILE_MAX_BYTES)
1279
+ continue;
1280
+ const text = await readFile(real, "utf8");
1281
+ if (bytes + text.length > SOURCE_BYTES_MAX)
1282
+ break;
1283
+ bytes += text.length;
1284
+ files.push({ path: rel.split(sep).join("/"), text });
1285
+ }
1286
+ return files.sort((a, b) => Number(b.path === this.main) - Number(a.path === this.main));
1287
+ }
1288
+ async locateSource(text, focus, signal) {
1289
+ await this.activate();
1290
+ return locateInSources(await this.sourceFiles(signal), text, focus, 3, {
1291
+ ...(signal === undefined ? {} : { signal }),
1292
+ maxBytes: SOURCE_BYTES_MAX,
1293
+ });
1294
+ }
1295
+ /**
1296
+ * Font directories passed to Typst via `--font-path`: the workspace's
1297
+ * conventional `fonts/` and `assets/fonts/` first, then the configured
1298
+ * directories. Project fonts therefore win on a family clash, and a
1299
+ * configured directory typst cannot read is left for typst to ignore.
1300
+ * @param configured - font directories from the current settings snapshot.
1301
+ * @returns the ordered `--font-path` directories.
1302
+ */
1303
+ async fontPaths(configured) {
1304
+ const candidates = [
1305
+ join(this.workspaceRoot, "fonts"),
1306
+ join(this.workspaceRoot, "assets", "fonts"),
1307
+ ];
1308
+ const resolved = [];
1309
+ for (const dir of candidates) {
1310
+ const s = await stat(dir).catch(() => null);
1311
+ if (s?.isDirectory())
1312
+ resolved.push(dir);
1313
+ }
1314
+ const seen = new Set(resolved);
1315
+ for (const dir of configured) {
1316
+ if (seen.has(dir))
1317
+ continue;
1318
+ seen.add(dir);
1319
+ resolved.push(dir);
1320
+ }
1321
+ return resolved;
1322
+ }
1323
+ // -------------------------------------------------------------------------
1324
+ // One-shot compiles: render images, export
1325
+ // -------------------------------------------------------------------------
1326
+ async oneshot(signal) {
1327
+ this.requireReady();
1328
+ const settings = this.settings();
1329
+ const fontPaths = await this.fontPaths(settings.fontPaths);
1330
+ return {
1331
+ typst: this.toolchain.path,
1332
+ cwd: this.workspaceRoot,
1333
+ root: this.workspaceRoot,
1334
+ fontPaths,
1335
+ packagePath: settings.packagePath || undefined,
1336
+ main: this.main,
1337
+ process: this.process,
1338
+ env: this.env,
1339
+ ...(signal === undefined ? {} : { signal }),
1340
+ scratch: this.buildDir ?? (this.buildDir = await this.makeBuildDir()),
1341
+ toFile: (path) => this.displayPath(path),
1342
+ };
1343
+ }
1344
+ /** Track one one-shot compile so close/killNow can abort it. */
1345
+ async withOneshot(signal, body) {
1346
+ const controller = new AbortController();
1347
+ const fused = signal === undefined
1348
+ ? controller.signal
1349
+ : AbortSignal.any([signal, controller.signal]);
1350
+ this.liveOneshots.add(controller);
1351
+ try {
1352
+ return await body(fused);
1353
+ }
1354
+ finally {
1355
+ this.liveOneshots.delete(controller);
1356
+ }
1357
+ }
1358
+ async renderPages(spec, ppi, signal) {
1359
+ await this.activate();
1360
+ const mainAtStart = this.main;
1361
+ const generationAtStart = this.generation;
1362
+ const options = await this.oneshot(signal);
1363
+ if (this.main !== mainAtStart || this.generation !== generationAtStart) {
1364
+ throw new TypstError("The main file changed while preparing the render; call typst_render_pages again.", TYPST_MAIN_CHANGED);
1365
+ }
1366
+ const settled = await this.settle(LIMITS.checkTimeoutMs, signal)
1367
+ .then(() => true)
1368
+ .catch(() => false);
1369
+ // A failed settle leaves the last snapshot in place; its page count is
1370
+ // stale, so do not use it to reject a page the new document may have.
1371
+ const total = settled ? this.current?.pages : undefined;
1372
+ let pages;
1373
+ try {
1374
+ pages = parsePages(spec, total ?? 10_000).map((index) => index + 1);
1375
+ }
1376
+ catch (error) {
1377
+ throw new TypstError(error instanceof Error ? error.message : String(error), TYPST_INVALID_ARGUMENT);
1378
+ }
1379
+ if (!pages.length) {
1380
+ throw new TypstError(total ? `The document has ${total} page(s).` : "No pages selected.", TYPST_INVALID_ARGUMENT);
1381
+ }
1382
+ if (pages.length > LIMITS.renderPages) {
1383
+ throw new TypstError(`Render at most ${LIMITS.renderPages} pages at a time.`, TYPST_INVALID_ARGUMENT);
1384
+ }
1385
+ const result = await this.withOneshot(signal, (fused) => renderPages({ ...options, signal: fused }, pages, ppi));
1386
+ const diagnostics = await Promise.all(result.diagnostics
1387
+ .slice(0, LIMITS.diagnostics)
1388
+ .map((entry) => this.withExcerpt(entry)));
1389
+ return { ...result, diagnostics, pages, total };
1390
+ }
1391
+ async exportPdf(path, extra, signal, policy) {
1392
+ await this.activate();
1393
+ const mainAtStart = this.main;
1394
+ const generationAtStart = this.generation;
1395
+ const absolute = await this.insideWorkspace(path);
1396
+ if (extname(absolute).toLowerCase() !== ".pdf") {
1397
+ throw new TypstError("The output path must end in .pdf.", TYPST_INVALID_ARGUMENT);
1398
+ }
1399
+ if (policy !== undefined) {
1400
+ if (policy.mode === "read-only") {
1401
+ throw new TypstError("The session is read-only; exporting a PDF would write to the workspace.", TYPST_SANDBOX_READ_ONLY);
1402
+ }
1403
+ if (policy.mode === "workspace-write") {
1404
+ let roots;
1405
+ try {
1406
+ roots = workspaceWritableRoots(policy);
1407
+ }
1408
+ catch (error) {
1409
+ if (error instanceof SandboxInvalidRootError) {
1410
+ throw new TypstError(error.message, TYPST_SANDBOX_INVALID_ROOT, {
1411
+ cause: error,
1412
+ });
1413
+ }
1414
+ throw error;
1415
+ }
1416
+ if (!roots.some((root) => isWithin(root, absolute))) {
1417
+ throw new TypstError("The output path is outside the session's writable roots.", TYPST_PATH_OUTSIDE_WORKSPACE);
1418
+ }
1419
+ }
1420
+ }
1421
+ const existing = await lstat(absolute).catch(() => null);
1422
+ if (existing?.isSymbolicLink()) {
1423
+ throw new TypstError("The output path is a symbolic link; choose a regular .pdf path.", TYPST_PATH_OUTSIDE_WORKSPACE);
1424
+ }
1425
+ if (existing?.isDirectory()) {
1426
+ throw new TypstError("The output path is a directory.", TYPST_INVALID_ARGUMENT);
1427
+ }
1428
+ const settled = await this.settle(LIMITS.checkTimeoutMs, signal)
1429
+ .then(() => true)
1430
+ .catch(() => false);
1431
+ const total = settled ? this.current?.pages : undefined;
1432
+ if (typeof extra.pages === "string" && extra.pages.trim().length > 0) {
1433
+ let selected;
1434
+ try {
1435
+ selected = parsePages(extra.pages, 10_000);
1436
+ }
1437
+ catch (error) {
1438
+ throw new TypstError(error instanceof Error ? error.message : String(error), TYPST_INVALID_ARGUMENT);
1439
+ }
1440
+ if (selected.length === 0) {
1441
+ throw new TypstError("No pages selected.", TYPST_INVALID_ARGUMENT);
1442
+ }
1443
+ if (total !== undefined && selected.some((page) => page >= total)) {
1444
+ throw new TypstError(`The document has ${total} page(s); the page selection is out of range.`, TYPST_PAGE_OUT_OF_RANGE);
1445
+ }
1446
+ }
1447
+ const options = await this.oneshot(signal);
1448
+ if (this.main !== mainAtStart || this.generation !== generationAtStart) {
1449
+ throw new TypstError("The main file changed while preparing the export; call typst_export_pdf again.", TYPST_MAIN_CHANGED);
1450
+ }
1451
+ await mkdir(dirname(absolute), { recursive: true, mode: 0o700 });
1452
+ const result = await this.withOneshot(signal, (fused) => exportPdf({ ...options, signal: fused }, absolute, extra));
1453
+ const diagnostics = await Promise.all(result.diagnostics
1454
+ .slice(0, LIMITS.diagnostics)
1455
+ .map((entry) => this.withExcerpt(entry)));
1456
+ if (!result.ok)
1457
+ return { ...result, diagnostics, path: this.relativePath(absolute) };
1458
+ const bytes = new Uint8Array(await readFile(absolute));
1459
+ return {
1460
+ ...result,
1461
+ diagnostics,
1462
+ path: this.relativePath(absolute),
1463
+ bytes: bytes.length,
1464
+ pages: await pageCount(bytes).catch(() => undefined),
1465
+ };
1466
+ }
1467
+ // -------------------------------------------------------------------------
1468
+ // Paths
1469
+ // -------------------------------------------------------------------------
1470
+ /** Workspace-relative path (/ separated), against the canonical root. */
1471
+ relativePath(absolute) {
1472
+ return relative(this.realRoot ?? this.workspaceRoot, absolute)
1473
+ .split(sep)
1474
+ .join("/");
1475
+ }
1476
+ /** A path as typst printed it (relative to the workspace root, or absolute) → display path. */
1477
+ displayPath(path) {
1478
+ if (!isAbsolute(path))
1479
+ return path.split(sep).join("/");
1480
+ for (const root of [this.workspaceRoot, this.realRoot]) {
1481
+ if (!root)
1482
+ continue;
1483
+ const rel = relative(root, path);
1484
+ if (!rel.startsWith("..") && !isAbsolute(rel))
1485
+ return rel.split(sep).join("/");
1486
+ }
1487
+ return path;
1488
+ }
1489
+ /** Resolve a path inside the workspace (through symlinks); refuse escapes. */
1490
+ async insideWorkspace(path) {
1491
+ if (!path || path.includes("\0")) {
1492
+ throw new TypstError("Empty path.", TYPST_INVALID_ARGUMENT);
1493
+ }
1494
+ const root = this.realRoot ??
1495
+ (await realpath(this.workspaceRoot).catch(() => this.workspaceRoot));
1496
+ try {
1497
+ return await resolveInside(root, resolve(this.workspaceRoot, path));
1498
+ }
1499
+ catch {
1500
+ throw new TypstError(`${path} is outside the workspace.`, TYPST_PATH_OUTSIDE_WORKSPACE);
1501
+ }
1502
+ }
1503
+ /** The erroring line of a workspace file. */
1504
+ async withExcerpt(diagnostic) {
1505
+ const location = diagnostic.location;
1506
+ if (!location || location.file.startsWith("@") || isAbsolute(location.file))
1507
+ return diagnostic;
1508
+ try {
1509
+ const file = resolve(this.workspaceRoot, location.file);
1510
+ const info = await stat(file);
1511
+ let cached = this.excerptCache.get(file);
1512
+ if (cached === undefined || cached.mtimeMs !== info.mtimeMs) {
1513
+ cached = {
1514
+ mtimeMs: info.mtimeMs,
1515
+ lines: (await readFile(file, "utf8")).split("\n"),
1516
+ };
1517
+ this.excerptCache.set(file, cached);
1518
+ }
1519
+ const line = cached.lines[location.line - 1];
1520
+ return line === undefined
1521
+ ? diagnostic
1522
+ : { ...diagnostic, excerpt: line.replace(/\s+$/, "").slice(0, 300) };
1523
+ }
1524
+ catch {
1525
+ return diagnostic;
1526
+ }
1527
+ }
1528
+ // -------------------------------------------------------------------------
1529
+ async close() {
1530
+ if (this.closed)
1531
+ return;
1532
+ this.closed = true;
1533
+ this.indexing?.abort();
1534
+ this.setupSubscribers = 0;
1535
+ this.watchSetup(false);
1536
+ for (const oneshot of this.liveOneshots)
1537
+ oneshot.abort();
1538
+ this.liveOneshots.clear();
1539
+ this.wakeWaiters();
1540
+ await this.stopWatcher();
1541
+ this.retiring?.killNow();
1542
+ this.retiring = null;
1543
+ this.snapshots.clear();
1544
+ this.pagesCache.clear();
1545
+ this.excerptCache.clear();
1546
+ this.highlights = [];
1547
+ this.fragments = [];
1548
+ this.current = null;
1549
+ this.view = null;
1550
+ this.diagnostics = [];
1551
+ this.diagnosticsTotal = 0;
1552
+ if (this.buildDir) {
1553
+ await rm(this.buildDir, { recursive: true, force: true }).catch(() => undefined);
1554
+ this.buildDir = null;
1555
+ }
1556
+ this.listeners.clear();
1557
+ }
1558
+ /** Synchronously end the watch (process exit). */
1559
+ killNow() {
1560
+ this.closed = true;
1561
+ this.compileToken++;
1562
+ if (this.restartTimer)
1563
+ clearTimeout(this.restartTimer);
1564
+ this.restartTimer = null;
1565
+ this.indexing?.abort();
1566
+ for (const oneshot of this.liveOneshots)
1567
+ oneshot.abort();
1568
+ this.liveOneshots.clear();
1569
+ this.wakeWaiters();
1570
+ this.retiring?.killNow();
1571
+ this.retiring = null;
1572
+ this.watcher?.killNow();
1573
+ this.watcher = null;
1574
+ }
1575
+ }
1576
+ //# sourceMappingURL=session.js.map