@vedivad/typst-web-service 0.7.12 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,21 +1,57 @@
1
+ /** LSP Position (0-based line and character). */
2
+ interface LspPosition {
3
+ line: number;
4
+ character: number;
5
+ }
6
+ /** LSP Range. */
7
+ interface LspRange {
8
+ start: LspPosition;
9
+ end: LspPosition;
10
+ }
1
11
  /** LSP Diagnostic as returned by tinymist. */
2
12
  interface LspDiagnostic {
3
- range: {
4
- start: {
5
- line: number;
6
- character: number;
7
- };
8
- end: {
9
- line: number;
10
- character: number;
11
- };
12
- };
13
+ range: LspRange;
13
14
  severity?: number;
14
15
  message: string;
15
16
  source?: string;
16
17
  }
18
+ /** LSP MarkupContent (markdown or plaintext). */
19
+ interface LspMarkupContent {
20
+ kind: "markdown" | "plaintext";
21
+ value: string;
22
+ }
23
+ /** LSP CompletionItem (subset actually populated by tinymist). */
24
+ interface LspCompletionItem {
25
+ label: string;
26
+ kind?: number;
27
+ detail?: string;
28
+ documentation?: string | LspMarkupContent;
29
+ insertText?: string;
30
+ filterText?: string;
31
+ sortText?: string;
32
+ textEdit?: {
33
+ range: LspRange;
34
+ newText: string;
35
+ };
36
+ }
37
+ /** LSP CompletionList. */
38
+ interface LspCompletionList {
39
+ isIncomplete: boolean;
40
+ items: LspCompletionItem[];
41
+ }
42
+ /** Response shape for `textDocument/completion`. */
43
+ type LspCompletionResponse = LspCompletionList | LspCompletionItem[] | null;
44
+ /** LSP Hover contents — legacy and current forms tinymist may emit. */
45
+ type LspHoverContents = string | LspMarkupContent | (string | {
46
+ language: string;
47
+ value: string;
48
+ })[];
49
+ /** Response shape for `textDocument/hover`. */
50
+ interface LspHover {
51
+ contents: LspHoverContents;
52
+ range?: LspRange;
53
+ }
17
54
 
18
- type DiagnosticsListener = (uri: string, diagnostics: LspDiagnostic[]) => void;
19
55
  interface TypstAnalyzerOptions {
20
56
  /**
21
57
  * Explicit Worker instance. When omitted, an inlined blob worker is created automatically.
@@ -31,111 +67,77 @@ interface TypstAnalyzerOptions {
31
67
  }
32
68
  /**
33
69
  * Manages a tinymist language server in a Web Worker. Provides LSP-based
34
- * diagnostics, completion, and hover for Typst documents.
35
- *
36
- * Diagnostics are push-based: call `didChange()` to notify the analyzer of
37
- * content changes, and receive diagnostics via `onDiagnostics()` listeners
38
- * whenever tinymist publishes them.
70
+ * completion and hover for Typst documents.
39
71
  *
40
72
  * const analyzer = await TypstAnalyzer.create({ wasmUrl: '...' });
41
- * analyzer.onDiagnostics((uri, diags) => { ... });
42
73
  */
43
74
  declare class TypstAnalyzer {
44
75
  private readonly proxy;
45
76
  private readonly worker;
46
77
  private versionCounter;
47
78
  private openedUris;
48
- private diagnosticsListeners;
49
79
  private constructor();
50
80
  static create(options: TypstAnalyzerOptions): Promise<TypstAnalyzer>;
51
- /**
52
- * Register a listener for push-based diagnostics.
53
- * Returns an unsubscribe function.
54
- */
55
- onDiagnostics(listener: DiagnosticsListener): () => void;
56
81
  didOpen(uri: string, content: string): Promise<void>;
57
82
  didClose(uri: string): Promise<void>;
58
83
  /**
59
84
  * Notify the analyzer that a document has changed.
60
- * Diagnostics will arrive asynchronously via `onDiagnostics()` listeners.
61
85
  */
62
86
  didChange(uri: string, content: string): Promise<void>;
63
- completion(uri: string, line: number, character: number): Promise<unknown>;
64
- hover(uri: string, line: number, character: number): Promise<unknown>;
65
- destroy(): void;
66
- }
67
-
68
- type DiagnosticsSubscriber = (diagnostics: LspDiagnostic[]) => void;
69
- interface AnalyzerSessionOptions {
70
- analyzer: Pick<TypstAnalyzer, "didOpen" | "didChange" | "completion" | "hover" | "onDiagnostics">;
71
- /** Project root used to build stable in-memory analyzer URIs. Default: "/project". */
72
- rootPath?: string;
73
- /** Entry file path within the project. Synced last to ensure dependencies load first. Default: "/main.typ". */
74
- entryPath?: string;
75
- }
76
- /**
77
- * Synchronizes an in-memory Typst project with a TypstAnalyzer.
78
- * Handles multi-file ordering, request queueing, and diagnostic subscriptions.
79
- *
80
- * Diagnostics arrive via the analyzer's push mechanism and are forwarded
81
- * to subscribers registered with `subscribe()`.
82
- *
83
- * const session = new AnalyzerSession({ analyzer });
84
- * session.subscribe("/main.typ", (diags) => { ... });
85
- * await session.sync("/main.typ", files);
86
- */
87
- declare class AnalyzerSession {
88
- private readonly analyzer;
89
- private readonly rootPath;
90
- private readonly entryPath;
91
- private readonly syncedFiles;
92
- private queue;
93
- private readonly listenersByUri;
94
- /** Last push received per URI. Replayed on subscribe() so tab-back shows correct diagnostics instantly. */
95
- private readonly diagnosticsCache;
96
- private readonly unsubscribeAnalyzer;
97
- constructor(options: AnalyzerSessionOptions);
98
- /** Build a tinymist URI from a project-relative path. */
99
- toUri(path: string): string;
100
87
  /**
101
- * Subscribe to push-based diagnostics for a file path.
102
- * Returns an unsubscribe function.
88
+ * Batch document changes. Splits inputs into opens (first-time URIs) and
89
+ * changes (already-open URIs) and sends them in a single worker roundtrip.
103
90
  */
104
- subscribe(path: string, listener: DiagnosticsSubscriber): () => void;
91
+ didChangeMany(docs: Record<string, string>): Promise<void>;
105
92
  /**
106
- * Sync all project files with the analyzer.
107
- * `files` must include the active file's current content under `path`.
108
- *
109
- * If the active file's content hasn't changed since the last sync, a
110
- * lightweight hover is triggered to ensure the analyzer re-analyzes with
111
- * the current project state and publishes fresh diagnostics.
112
- */
113
- sync(path: string, files: Record<string, string>): Promise<void>;
114
- /**
115
- * Sync files and request completions at the given position.
116
- * Returns the raw LSP CompletionList/CompletionItem[] from tinymist.
117
- */
118
- completion(path: string, files: Record<string, string>, line: number, character: number): Promise<unknown>;
119
- /**
120
- * Sync files and request hover info at the given position.
121
- * Returns the raw LSP Hover result from tinymist.
93
+ * Batch document closes. Filters to currently-open URIs and sends the set
94
+ * in a single worker roundtrip.
122
95
  */
123
- hover(path: string, files: Record<string, string>, line: number, character: number): Promise<unknown>;
96
+ didCloseMany(uris: string[]): Promise<void>;
97
+ completion(uri: string, line: number, character: number): Promise<LspCompletionResponse>;
98
+ hover(uri: string, line: number, character: number): Promise<LspHover | null>;
124
99
  destroy(): void;
125
- /**
126
- * Sync all project files: dependencies first, active file last.
127
- * Returns whether the active file's content was actually sent to the analyzer.
128
- */
129
- private syncFiles;
130
- /** Sync a single file. Returns true if content was sent to the analyzer. */
131
- private syncFile;
132
- private orderedPaths;
133
- private enqueue;
134
100
  }
135
101
 
136
- declare function normalizeUntitledUri(uri: string): string;
137
- declare function normalizePath(path: string): string;
102
+ /**
103
+ * Two addressing schemes live in this codebase. This file is the only place
104
+ * that knows how they relate. Keeping the vocabulary and conversions colocated
105
+ * means a new contributor can read one file and understand the model.
106
+ *
107
+ * 1. Path — "/main.typ". Always leading-slash, always forward slashes.
108
+ * Used by the compiler VFS, the `TypstProject` public API,
109
+ * and the `typstFilePath` facet. Addresses a file within
110
+ * the project.
111
+ *
112
+ * 2. AnalyzerUri — "untitled:project/main.typ". What tinymist's LSP expects.
113
+ * Derived from a Path plus the analyzer URI root.
114
+ *
115
+ * The types below are type aliases, not branded/opaque types. That's
116
+ * deliberate: callers can pass string literals where a Path is expected
117
+ * without wrapping, and the aliases only serve as self-documenting
118
+ * signatures. Ingress points still need to call `normalizePath` to defend
119
+ * against un-normalized input — the alias does not imply the string has
120
+ * been normalized.
121
+ */
122
+ /** `/path/to/file.typ` — leading-slash, forward slashes only. */
123
+ type Path = string;
124
+ /** `untitled:project/path/to/file.typ` — what tinymist's LSP consumes. */
125
+ type AnalyzerUri = string;
126
+ /** Ensure a path starts with a leading slash. Idempotent. */
127
+ declare function normalizePath(path: string): Path;
128
+ /**
129
+ * Normalize an analyzer URI root. Ensures leading slash, strips trailing
130
+ * slashes. Special-cases "/" → "" so URIs don't end up with a leading
131
+ * `untitled://`.
132
+ */
138
133
  declare function normalizeRoot(rootPath: string): string;
134
+ /**
135
+ * Build the analyzer URI for a given project path. `root` is expected to
136
+ * already be normalized (see `normalizeRoot`).
137
+ *
138
+ * pathToAnalyzerUri("/main.typ", "/project") -> "untitled:project/main.typ"
139
+ */
140
+ declare function pathToAnalyzerUri(path: Path, root: string): AnalyzerUri;
139
141
 
140
142
  /** Source range for a diagnostic. All values are 0-indexed. */
141
143
  interface DiagnosticRange {
@@ -192,29 +194,30 @@ declare class TypstCompiler {
192
194
  private readonly proxy;
193
195
  private readonly worker;
194
196
  private readonly encoder;
195
- /** The most recent vector artifact from a compile, if any. */
196
- lastVector?: Uint8Array;
197
197
  private constructor();
198
198
  static create(options?: TypstCompilerOptions): Promise<TypstCompiler>;
199
- /** Compile a single source string (treated as /main.typ) or a map of files. */
200
- compile(source: string | Record<string, string>): Promise<CompileResult>;
201
- /** Compile to PDF from a single source string (treated as /main.typ) or a map of files. */
202
- compilePdf(source: string | Record<string, string>): Promise<Uint8Array>;
203
- /** Add or overwrite a text source file. */
204
- addSource(path: string, source: string): Promise<void>;
205
- /** Add or overwrite an in-memory shadow file (text or binary). */
206
- mapShadow(path: string, content: Uint8Array): Promise<void>;
207
- /** Remove an in-memory shadow file by path. */
208
- unmapShadow(path: string): Promise<void>;
209
199
  /**
210
- * Clear all shadow files held by the compiler.
211
- * Note: this also clears files previously added via addSource in the compiler runtime.
200
+ * Compile whatever is currently in the VFS (populated via
201
+ * setText/setBinary/setJson/setMany). Defaults to compiling "/main.typ";
202
+ * override with `entry`.
203
+ */
204
+ compile(entry?: string): Promise<CompileResult>;
205
+ /**
206
+ * Compile to PDF. Operates on whatever is currently in the VFS (populated
207
+ * via setText/setBinary/setJson/setMany). Defaults to compiling "/main.typ";
208
+ * override with `entry`.
212
209
  */
213
- resetShadow(): Promise<void>;
210
+ compilePdf(entry?: string): Promise<Uint8Array>;
214
211
  /** Add or overwrite a text file in the virtual compiler filesystem. */
215
212
  setText(path: string, source: string): Promise<void>;
216
213
  /** Add or overwrite a JSON file in the virtual compiler filesystem. */
217
214
  setJson(path: string, value: unknown, replacer?: (this: unknown, key: string, value: unknown) => unknown, space?: string | number): Promise<void>;
215
+ /**
216
+ * Add or overwrite multiple files in the virtual compiler filesystem in a
217
+ * single worker roundtrip. Strings are UTF-8 encoded; Uint8Arrays are passed
218
+ * through.
219
+ */
220
+ setMany(files: Record<string, string | Uint8Array>): Promise<void>;
218
221
  /** Add or overwrite a binary file in the virtual compiler filesystem. */
219
222
  setBinary(path: string, content: ArrayBuffer | ArrayBufferView): Promise<void>;
220
223
  /** Remove a file from the virtual compiler filesystem. */
@@ -266,6 +269,133 @@ declare class TypstFormatter {
266
269
  formatRange(source: string, start: number, end: number): Promise<FormatRangeResult>;
267
270
  }
268
271
 
272
+ interface TypstProjectOptions {
273
+ compiler: TypstCompiler;
274
+ /**
275
+ * Optional analyzer. When provided, text file operations also sync with the
276
+ * analyzer so completions / hover reflect the current state.
277
+ */
278
+ analyzer?: TypstAnalyzer;
279
+ /** Default entry file path. Default: "/main.typ". */
280
+ entry?: string;
281
+ /**
282
+ * Prefix used to build the `untitled:` URIs handed to the analyzer.
283
+ * Default: "/project". A path of `/main.typ` becomes
284
+ * `untitled:project/main.typ`. Only affects URI construction — the compiler
285
+ * and project VFS use the raw paths unchanged.
286
+ */
287
+ analyzerUriRoot?: string;
288
+ }
289
+ /**
290
+ * Coordinates a compiler + analyzer pair for multi-file Typst projects.
291
+ *
292
+ * Owns the project's virtual filesystem state. Editors push incremental
293
+ * `setText` updates as the user types; the project mirrors those edits to
294
+ * both the compiler's shadow VFS and the analyzer's open-document set, then
295
+ * compiles or services LSP requests against the current state.
296
+ *
297
+ * const project = new TypstProject({ compiler, analyzer });
298
+ * await project.setMany({ "/main.typ": "...", "/utils.typ": "..." });
299
+ * const result = await project.compile();
300
+ */
301
+ type CompileListener = (result: CompileResult) => void;
302
+ declare class TypstProject {
303
+ private readonly compiler;
304
+ private readonly analyzer?;
305
+ private readonly analyzerUriRoot;
306
+ private readonly trackedTextPaths;
307
+ /** Last content written via setText/setMany, per path. Used to skip redundant writes to compiler + analyzer. */
308
+ private readonly lastSyncedContent;
309
+ private readonly compileListeners;
310
+ private compileVersion;
311
+ private _lastResult;
312
+ private _entry;
313
+ private destroyed;
314
+ constructor(options: TypstProjectOptions);
315
+ /** Current entry file path. Assign to change the sticky entry used by subsequent `compile()` calls. */
316
+ get entry(): Path;
317
+ set entry(path: Path);
318
+ /** Whether an analyzer is attached. */
319
+ get hasAnalyzer(): boolean;
320
+ /**
321
+ * Most recent compile result, or `undefined` before the first compile has
322
+ * settled. Useful for lazy-mounted UI that subscribes after boot and needs
323
+ * an initial value.
324
+ */
325
+ get lastResult(): CompileResult | undefined;
326
+ /**
327
+ * Snapshot of tracked text file paths, in insertion order. Updated by
328
+ * `setText`, `setMany`, `remove`, and `clear`. Returns a fresh array — mutate
329
+ * freely without affecting project state.
330
+ */
331
+ get files(): Path[];
332
+ /**
333
+ * Current text content for a tracked file, or `undefined` if the path was
334
+ * never written via `setText`/`setMany` (or was removed). Read-through to the
335
+ * project's sync cache — lets consumers avoid shadowing the VFS themselves.
336
+ */
337
+ getText(path: Path): string | undefined;
338
+ /**
339
+ * Add or overwrite a text file. Goes to the compiler's VFS and, when an
340
+ * analyzer is attached, to the analyzer as a document change. Redundant
341
+ * calls with unchanged content are skipped.
342
+ */
343
+ setText(path: Path, content: string): Promise<void>;
344
+ /**
345
+ * Add or overwrite a JSON file. Compiler-only — the analyzer does not track
346
+ * data files.
347
+ */
348
+ setJson(path: Path, value: unknown): Promise<void>;
349
+ /** Add or overwrite a binary file. Compiler-only. */
350
+ setBinary(path: Path, content: ArrayBuffer | ArrayBufferView): Promise<void>;
351
+ /**
352
+ * Batch set multiple files. Strings route to both compiler and analyzer;
353
+ * Uint8Array entries go to the compiler only.
354
+ */
355
+ setMany(files: Record<Path, string | Uint8Array>): Promise<void>;
356
+ /**
357
+ * Remove a file. Always removed from the compiler's VFS; also closed on the
358
+ * analyzer when it was previously tracked as text.
359
+ */
360
+ remove(path: Path): Promise<void>;
361
+ /** Clear all files from both compiler VFS and analyzer document set. */
362
+ clear(): Promise<void>;
363
+ /**
364
+ * Subscribe to compile results. Fires after every `compile()` whose result is
365
+ * still current (stale results from out-of-order concurrent compiles are
366
+ * dropped). If a compile has already settled, the most recent result is
367
+ * delivered synchronously so late-mounted listeners aren't stuck blank until
368
+ * the next compile. Returns an unsubscribe function.
369
+ */
370
+ onCompile(listener: CompileListener): () => void;
371
+ /**
372
+ * Compile the current VFS state using the sticky entry. Errors from the
373
+ * underlying compiler are converted into a synthetic error diagnostic so
374
+ * callers and listeners always receive a `CompileResult`. Listeners are
375
+ * notified only for the most recent compile — results from an earlier call
376
+ * that resolves after a later one are suppressed.
377
+ */
378
+ compile(): Promise<CompileResult>;
379
+ /** Compile the current VFS state to PDF using the sticky entry. */
380
+ compilePdf(): Promise<Uint8Array>;
381
+ private requireAnalyzer;
382
+ /** Request completions at the given position. Throws when no analyzer is attached. */
383
+ completion(path: Path, line: number, character: number): Promise<LspCompletionResponse>;
384
+ /** Request hover info at the given position. Throws when no analyzer is attached. */
385
+ hover(path: Path, line: number, character: number): Promise<LspHover | null>;
386
+ /**
387
+ * Tear down the project and the services it owns. Destroys the attached
388
+ * compiler and analyzer, drops all listeners, and clears VFS tracking state.
389
+ * Idempotent — calling twice is a no-op. After destruction, further calls on
390
+ * the project are not supported; construct a new one.
391
+ *
392
+ * If you need to share a compiler or analyzer across projects, destroy them
393
+ * yourself and don't call this method — the project does not provide an
394
+ * ownership toggle.
395
+ */
396
+ destroy(): void;
397
+ }
398
+
269
399
  interface TypstRendererOptions {
270
400
  /** URL to the typst-ts-renderer WASM binary. Defaults to jsDelivr CDN. */
271
401
  wasmUrl?: string;
@@ -291,4 +421,4 @@ declare class TypstRenderer {
291
421
  renderSvg(vector: Uint8Array): Promise<string>;
292
422
  }
293
423
 
294
- export { AnalyzerSession, type AnalyzerSessionOptions, type CompileResult, type DiagnosticMessage, type DiagnosticRange, type DiagnosticsSubscriber, type FormatConfig, type FormatRangeResult, type LspDiagnostic, TypstAnalyzer, type TypstAnalyzerOptions, TypstCompiler, type TypstCompilerOptions, TypstFormatter, TypstRenderer, type TypstRendererOptions, normalizePath, normalizeRoot, normalizeUntitledUri };
424
+ export { type AnalyzerUri, type CompileResult, type DiagnosticMessage, type DiagnosticRange, type FormatConfig, type FormatRangeResult, type LspCompletionItem, type LspCompletionList, type LspCompletionResponse, type LspDiagnostic, type LspHover, type LspHoverContents, type LspMarkupContent, type LspPosition, type LspRange, type Path, TypstAnalyzer, type TypstAnalyzerOptions, TypstCompiler, type TypstCompilerOptions, TypstFormatter, TypstProject, type TypstProjectOptions, TypstRenderer, normalizePath, normalizeRoot, pathToAnalyzerUri };