dsh-typst-plugin 0.1.0-alpha.0 → 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 (120) hide show
  1. package/README.en.md +86 -52
  2. package/README.md +93 -59
  3. package/cordis.patch.yml +1 -1
  4. package/docs/images/icon.png +0 -0
  5. package/lib/client.js +2088 -1136
  6. package/lib/client.js.map +4 -4
  7. package/lib/config.d.ts +66 -9
  8. package/lib/config.d.ts.map +1 -1
  9. package/lib/config.js +161 -25
  10. package/lib/config.js.map +1 -7
  11. package/lib/constants.d.ts +21 -2
  12. package/lib/constants.d.ts.map +1 -1
  13. package/lib/constants.js +83 -60
  14. package/lib/constants.js.map +1 -7
  15. package/lib/contract.d.ts +90 -6
  16. package/lib/contract.d.ts.map +1 -1
  17. package/lib/contract.js +9 -1
  18. package/lib/contract.js.map +1 -7
  19. package/lib/diagnostic-text.d.ts +13 -0
  20. package/lib/diagnostic-text.d.ts.map +1 -0
  21. package/lib/diagnostic-text.js +28 -0
  22. package/lib/diagnostic-text.js.map +1 -0
  23. package/lib/errors.d.ts +57 -15
  24. package/lib/errors.d.ts.map +1 -1
  25. package/lib/errors.js +154 -79
  26. package/lib/errors.js.map +1 -7
  27. package/lib/host/facts.d.ts.map +1 -1
  28. package/lib/host/facts.js +133 -139
  29. package/lib/host/facts.js.map +1 -7
  30. package/lib/host/which.d.ts +20 -0
  31. package/lib/host/which.d.ts.map +1 -0
  32. package/lib/host/which.js +50 -0
  33. package/lib/host/which.js.map +1 -0
  34. package/lib/index.js +2 -5
  35. package/lib/index.js.map +1 -7
  36. package/lib/remote.d.ts +5 -4
  37. package/lib/remote.d.ts.map +1 -1
  38. package/lib/remote.js +153 -143
  39. package/lib/remote.js.map +1 -7
  40. package/lib/service.d.ts +28 -4
  41. package/lib/service.d.ts.map +1 -1
  42. package/lib/service.js +202 -99
  43. package/lib/service.js.map +1 -7
  44. package/lib/skills/typst.js +74 -68
  45. package/lib/skills/typst.js.map +1 -7
  46. package/lib/status-codec.js +10 -5
  47. package/lib/status-codec.js.map +1 -7
  48. package/lib/tools/registration.d.ts +4 -3
  49. package/lib/tools/registration.d.ts.map +1 -1
  50. package/lib/tools/registration.js +726 -493
  51. package/lib/tools/registration.js.map +1 -7
  52. package/lib/tools/shared.d.ts +4 -5
  53. package/lib/tools/shared.d.ts.map +1 -1
  54. package/lib/tools/shared.js +73 -64
  55. package/lib/tools/shared.js.map +1 -7
  56. package/lib/typert.d.ts +5 -3
  57. package/lib/typert.d.ts.map +1 -1
  58. package/lib/typert.js +113 -64
  59. package/lib/typert.js.map +1 -7
  60. package/lib/typst/diagnostics.d.ts.map +1 -1
  61. package/lib/typst/diagnostics.js +218 -152
  62. package/lib/typst/diagnostics.js.map +1 -7
  63. package/lib/typst/flags.d.ts +8 -0
  64. package/lib/typst/flags.d.ts.map +1 -0
  65. package/lib/typst/flags.js +8 -0
  66. package/lib/typst/flags.js.map +1 -0
  67. package/lib/typst/locate.d.ts +6 -13
  68. package/lib/typst/locate.d.ts.map +1 -1
  69. package/lib/typst/locate.js +138 -180
  70. package/lib/typst/locate.js.map +1 -7
  71. package/lib/typst/mainfile.d.ts +23 -4
  72. package/lib/typst/mainfile.d.ts.map +1 -1
  73. package/lib/typst/mainfile.js +131 -59
  74. package/lib/typst/mainfile.js.map +1 -7
  75. package/lib/typst/match.d.ts +9 -1
  76. package/lib/typst/match.d.ts.map +1 -1
  77. package/lib/typst/match.js +213 -157
  78. package/lib/typst/match.js.map +1 -7
  79. package/lib/typst/oneshot.d.ts +8 -5
  80. package/lib/typst/oneshot.d.ts.map +1 -1
  81. package/lib/typst/oneshot.js +76 -66
  82. package/lib/typst/oneshot.js.map +1 -7
  83. package/lib/typst/owners.d.ts +28 -0
  84. package/lib/typst/owners.d.ts.map +1 -0
  85. package/lib/typst/owners.js +98 -0
  86. package/lib/typst/owners.js.map +1 -0
  87. package/lib/typst/pdf-extract.d.ts +1 -2
  88. package/lib/typst/pdf-extract.d.ts.map +1 -1
  89. package/lib/typst/pdf-extract.js +98 -74
  90. package/lib/typst/pdf-extract.js.map +1 -7
  91. package/lib/typst/process.d.ts +73 -0
  92. package/lib/typst/process.d.ts.map +1 -0
  93. package/lib/typst/process.js +147 -0
  94. package/lib/typst/process.js.map +1 -0
  95. package/lib/typst/text.d.ts +4 -7
  96. package/lib/typst/text.d.ts.map +1 -1
  97. package/lib/typst/text.js +258 -290
  98. package/lib/typst/text.js.map +1 -7
  99. package/lib/typst/watcher.d.ts +16 -17
  100. package/lib/typst/watcher.d.ts.map +1 -1
  101. package/lib/typst/watcher.js +199 -208
  102. package/lib/typst/watcher.js.map +1 -7
  103. package/lib/wire-schemas.d.ts +8 -153
  104. package/lib/wire-schemas.d.ts.map +1 -1
  105. package/lib/wire-schemas.js +405 -361
  106. package/lib/wire-schemas.js.map +1 -7
  107. package/lib/workspace/containment.d.ts +25 -0
  108. package/lib/workspace/containment.d.ts.map +1 -0
  109. package/lib/workspace/containment.js +54 -0
  110. package/lib/workspace/containment.js.map +1 -0
  111. package/lib/workspace/session.d.ts +73 -14
  112. package/lib/workspace/session.d.ts.map +1 -1
  113. package/lib/workspace/session.js +1516 -1172
  114. package/lib/workspace/session.js.map +1 -7
  115. package/locale/en.json +8 -2
  116. package/locale/zh.json +8 -2
  117. package/package.json +36 -179
  118. package/release-provenance.json +137 -0
  119. package/lib/typst/pdfjs-worker.d.js +0 -1
  120. package/lib/typst/pdfjs-worker.d.js.map +0 -7
@@ -1,1232 +1,1576 @@
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";
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";
10
13
  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";
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";
42
18
  import { detectFacts, cargoSpec } from "../host/facts.js";
43
19
  import { locateTypst, searchedDirs } from "../typst/locate.js";
44
20
  import { chooseMain, indexTypFiles } from "../typst/mainfile.js";
45
21
  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";
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
+ */
64
40
  async function realish(path) {
65
- return realpath(path).catch(() => path);
41
+ return realpath(path).catch(() => path);
66
42
  }
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;
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: [],
152
65
  };
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);
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);
168
123
  }
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
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;
221
157
  };
222
- case "error":
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() {
223
185
  return {
224
- state: "error",
225
- path: toolchain.path,
226
- source: toolchain.source,
227
- error: toolchain.error
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
+ },
228
208
  };
229
209
  }
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
- );
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();
270
354
  }
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") {
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();
301
378
  await this.stopWatcher();
379
+ await this.detectToolchain();
302
380
  await this.refreshCandidates(true);
303
- if (!this.main) this.main = await this.selectInitialMain();
381
+ if (!this.main)
382
+ this.main = await this.selectInitialMain();
304
383
  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;
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();
332
411
  }
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();
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
+ }
358
427
  }
359
- this.emit();
360
- }
361
- async validMain(path) {
362
- try {
363
- return (await stat(await this.insideWorkspace(path))).isFile();
364
- } catch {
365
- return false;
428
+ async selectInitialMain() {
429
+ const remembered = await this.remembered();
430
+ return remembered && (await this.validMain(remembered))
431
+ ? remembered
432
+ : chooseMain(this.candidates, null);
366
433
  }
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 = {
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 = {
397
442
  scanning: true,
398
443
  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: []
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
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
- };
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;
514
494
  }
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.";
495
+ startWatcher() {
496
+ this.startingWatcher ??= this.performStartWatcher().finally(() => {
497
+ this.startingWatcher = null;
498
+ });
499
+ return this.startingWatcher;
550
500
  }
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);
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;
593
620
  }
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;
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)}`));
646
682
  }
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 {
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();
657
714
  }
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
- );
715
+ wakeWaiters() {
716
+ for (const wake of this.finishWaiters)
717
+ wake();
675
718
  }
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();
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
+ });
689
744
  }
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
- );
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 };
707
761
  }
708
- if (toolchain.state === "too_old") {
709
- throw new TypstError(
710
- `${toolchain.error} Update Typst (${toolchain.path}).`,
711
- TYPST_TOO_OLD
712
- );
762
+ // -------------------------------------------------------------------------
763
+ // Main file
764
+ // -------------------------------------------------------------------------
765
+ get mainsFile() {
766
+ return this.options.dataDir
767
+ ? join(this.options.dataDir, "main-files.json")
768
+ : null;
713
769
  }
714
- if (toolchain.state !== "ready") {
715
- throw new TypstError(
716
- "error" in toolchain ? toolchain.error : "Typst is not available.",
717
- TYPST_UNUSABLE
718
- );
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
+ }
719
785
  }
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
- );
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 });
725
807
  }
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));
808
+ setMain(path) {
809
+ const operation = this.mainQueue.then(() => this.selectMain(path));
810
+ this.mainQueue = operation.catch(() => undefined);
811
+ return operation;
732
812
  }
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();
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}`));
789
836
  this.emit();
790
- }
837
+ return main;
791
838
  }
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;
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
+ }
800
859
  }
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;
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
+ };
808
890
  }
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);
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;
827
1006
  }
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
- );
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;
837
1016
  }
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
- );
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;
854
1027
  }
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
- );
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;
877
1036
  }
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
- );
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();
890
1058
  }
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
- }
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
+ }
919
1086
  }
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
- );
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;
954
1108
  }
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
- );
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 };
966
1196
  }
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;
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();
1001
1243
  }
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;
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;
1028
1256
  }
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
- });
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));
1053
1287
  }
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);
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
+ });
1072
1294
  }
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
- );
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;
1105
1322
  }
1106
- if (!pages.length) {
1107
- throw new TypstError(
1108
- total ? `The document has ${total} page(s).` : "No pages selected.",
1109
- TYPST_INVALID_ARGUMENT
1110
- );
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
+ };
1111
1343
  }
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
- );
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
+ }
1117
1357
  }
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
- );
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 };
1133
1390
  }
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("/");
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;
1165
1488
  }
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);
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
+ }
1172
1502
  }
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
- }
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();
1190
1557
  }
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;
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;
1210
1574
  }
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
1575
  }
1229
- export {
1230
- WorkspaceSession
1231
- };
1232
- //# sourceMappingURL=session.js.map
1576
+ //# sourceMappingURL=session.js.map