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,76 +1,86 @@
1
+ /**
2
+ * One-shot typst compiles that do not touch the preview: rendering pages to
3
+ * PNG for the agent to look at, and exporting PDFs into the workspace.
4
+ * Ported from the ZCode typst-workbench server (0.2.0) `src/typst/
5
+ * oneshot.ts`. Host half only.
6
+ * @module dsh-typst/typst/oneshot
7
+ */
1
8
  import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
2
9
  import { join } from "node:path";
3
10
  import { LIMITS } from "../constants.js";
4
- import { TypstError } from "../errors.js";
11
+ import { TYPST_TIMEOUT, TypstError } from "../errors.js";
5
12
  import { parseDiagnostics } from "./diagnostics.js";
6
- import { run } from "./locate.js";
13
+ import { typstFlags } from "./flags.js";
7
14
  async function compile(options, output, extra) {
8
- const rootArgs = options.root ? ["--root", options.root] : [];
9
- const fontArgs = (options.fontPaths ?? []).flatMap((dir) => [
10
- "--font-path",
11
- dir
12
- ]);
13
- const result = await run(
14
- options.typst,
15
- ["compile", options.main, output, ...extra, ...rootArgs, ...fontArgs],
16
- {
17
- cwd: options.cwd,
18
- env: options.env,
19
- timeoutMs: options.timeoutMs ?? LIMITS.oneshotTimeoutMs
20
- }
21
- );
22
- if (result.timedOut) {
23
- throw new TypstError(
24
- `typst compile did not finish within ${Math.round((options.timeoutMs ?? LIMITS.oneshotTimeoutMs) / 1e3)} s.`,
25
- "TYPST_TIMEOUT"
26
- );
27
- }
28
- const diagnostics = parseDiagnostics(result.stderr, options.toFile);
29
- if (result.code !== 0 && !diagnostics.some((entry) => entry.severity === "error")) {
30
- diagnostics.push({
31
- severity: "error",
32
- message: (result.stderr || result.stdout).trim().slice(0, 500) || `typst exited with code ${result.code}`,
33
- location: null,
34
- hints: [],
35
- trace: []
15
+ const result = await options.process.run([
16
+ options.typst,
17
+ "compile",
18
+ options.main,
19
+ output,
20
+ ...extra,
21
+ ...typstFlags(options),
22
+ ], {
23
+ cwd: options.cwd,
24
+ timeoutMs: options.timeoutMs ?? LIMITS.oneshotTimeoutMs,
25
+ ...(options.env === undefined ? {} : { env: options.env }),
26
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
36
27
  });
37
- }
38
- return { ok: result.code === 0, diagnostics };
39
- }
40
- async function renderPages(options, pages, ppi) {
41
- const dir = await mkdtemp(join(options.scratch, "render-"));
42
- try {
43
- const result = await compile(options, join(dir, "page-{p}.png"), [
44
- "--pages",
45
- pages.join(","),
46
- "--ppi",
47
- String(ppi)
48
- ]);
49
- if (!result.ok) return { ...result, images: [] };
50
- const images = [];
51
- for (const name of await readdir(dir)) {
52
- const match = /^page-(\d+)\.png$/.exec(name);
53
- if (match) {
54
- images.push({
55
- page: Number(match[1]),
56
- png: new Uint8Array(await readFile(join(dir, name)))
28
+ if (result.timedOut) {
29
+ throw new TypstError(`typst compile did not finish within ${Math.round((options.timeoutMs ?? LIMITS.oneshotTimeoutMs) / 1e3)} s.`, TYPST_TIMEOUT);
30
+ }
31
+ const diagnostics = parseDiagnostics(result.stderr, options.toFile);
32
+ if (result.code !== 0 &&
33
+ !diagnostics.some((entry) => entry.severity === "error")) {
34
+ diagnostics.push({
35
+ severity: "error",
36
+ message: (result.stderr || result.stdout).trim().slice(0, 500) ||
37
+ `typst exited with code ${result.code}`,
38
+ location: null,
39
+ hints: [],
40
+ trace: [],
57
41
  });
58
- }
59
42
  }
60
- images.sort((a, b) => a.page - b.page);
61
- return { ...result, images };
62
- } finally {
63
- await rm(dir, { recursive: true, force: true });
64
- }
43
+ return { ok: result.code === 0, diagnostics };
44
+ }
45
+ /**
46
+ * Render the given 1-based pages to PNGs in a scratch directory and read
47
+ * them back, page-ordered; the scratch directory is always removed.
48
+ */
49
+ export async function renderPages(options, pages, ppi) {
50
+ const dir = await mkdtemp(join(options.scratch, "render-"));
51
+ try {
52
+ const result = await compile(options, join(dir, "page-{p}.png"), [
53
+ "--pages",
54
+ pages.join(","),
55
+ "--ppi",
56
+ String(ppi),
57
+ ]);
58
+ if (!result.ok)
59
+ return { ...result, images: [] };
60
+ const images = [];
61
+ for (const name of await readdir(dir)) {
62
+ const match = /^page-(\d+)\.png$/.exec(name);
63
+ if (match) {
64
+ images.push({
65
+ page: Number(match[1]),
66
+ png: new Uint8Array(await readFile(join(dir, name))),
67
+ });
68
+ }
69
+ }
70
+ images.sort((a, b) => a.page - b.page);
71
+ return { ...result, images };
72
+ }
73
+ finally {
74
+ await rm(dir, { recursive: true, force: true });
75
+ }
65
76
  }
66
- async function exportPdf(options, output, extra) {
67
- const args = [];
68
- if (extra.pdfStandard) args.push("--pdf-standard", extra.pdfStandard);
69
- if (extra.pages) args.push("--pages", extra.pages);
70
- return compile(options, output, args);
77
+ /** Compile a PDF into the workspace (optionally a PDF standard and a page selection). */
78
+ export async function exportPdf(options, output, extra) {
79
+ const args = [];
80
+ if (extra.pdfStandard)
81
+ args.push("--pdf-standard", extra.pdfStandard);
82
+ if (extra.pages)
83
+ args.push("--pages", extra.pages);
84
+ return compile(options, output, args);
71
85
  }
72
- export {
73
- exportPdf,
74
- renderPages
75
- };
76
- //# sourceMappingURL=oneshot.js.map
86
+ //# sourceMappingURL=oneshot.js.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/typst/oneshot.ts"],
4
- "sourcesContent": ["/**\n * One-shot typst compiles that do not touch the preview: rendering pages to\n * PNG for the agent to look at, and exporting PDFs into the workspace.\n * Ported from the ZCode typst-workbench server (0.2.0) `src/typst/\n * oneshot.ts`. Host half only.\n * @module dsh-typst/typst/oneshot\n */\n\nimport { mkdtemp, readdir, readFile, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { LIMITS } from \"../constants.js\";\nimport { TypstError } from \"../errors.js\";\nimport { parseDiagnostics } from \"./diagnostics.js\";\nimport { run } from \"./locate.js\";\nimport type { DiagnosticView } from \"../contract.js\";\n\nexport interface OneshotOptions {\n typst: string;\n cwd: string;\n /** Project sandbox root passed to Typst via `--root`. */\n root?: string;\n /** Extra directories searched recursively for fonts via `--font-path`. */\n fontPaths?: string[];\n main: string;\n env?: NodeJS.ProcessEnv;\n /** Where render scratch directories are created. */\n scratch: string;\n toFile?: (path: string) => string;\n timeoutMs?: number;\n}\n\nexport interface CompileResult {\n ok: boolean;\n diagnostics: DiagnosticView[];\n}\n\nasync function compile(\n options: OneshotOptions,\n output: string,\n extra: string[],\n): Promise<CompileResult> {\n const rootArgs = options.root ? [\"--root\", options.root] : [];\n const fontArgs = (options.fontPaths ?? []).flatMap((dir) => [\n \"--font-path\",\n dir,\n ]);\n const result = await run(\n options.typst,\n [\"compile\", options.main, output, ...extra, ...rootArgs, ...fontArgs],\n {\n cwd: options.cwd,\n env: options.env,\n timeoutMs: options.timeoutMs ?? LIMITS.oneshotTimeoutMs,\n },\n );\n if (result.timedOut) {\n throw new TypstError(\n `typst compile did not finish within ${Math.round((options.timeoutMs ?? LIMITS.oneshotTimeoutMs) / 1e3)} s.`,\n \"TYPST_TIMEOUT\",\n );\n }\n const diagnostics = parseDiagnostics(result.stderr, options.toFile);\n if (\n result.code !== 0 &&\n !diagnostics.some((entry) => entry.severity === \"error\")\n ) {\n diagnostics.push({\n severity: \"error\",\n message:\n (result.stderr || result.stdout).trim().slice(0, 500) ||\n `typst exited with code ${result.code}`,\n location: null,\n hints: [],\n trace: [],\n });\n }\n return { ok: result.code === 0, diagnostics };\n}\n\nexport interface RenderedImage {\n page: number;\n png: Uint8Array;\n}\n\nexport interface RenderPagesResult extends CompileResult {\n images: RenderedImage[];\n}\n\n/**\n * Render the given 1-based pages to PNGs in a scratch directory and read\n * them back, page-ordered; the scratch directory is always removed.\n */\nexport async function renderPages(\n options: OneshotOptions,\n pages: number[],\n ppi: number,\n): Promise<RenderPagesResult> {\n const dir = await mkdtemp(join(options.scratch, \"render-\"));\n try {\n const result = await compile(options, join(dir, \"page-{p}.png\"), [\n \"--pages\",\n pages.join(\",\"),\n \"--ppi\",\n String(ppi),\n ]);\n if (!result.ok) return { ...result, images: [] };\n const images: RenderedImage[] = [];\n for (const name of await readdir(dir)) {\n const match = /^page-(\\d+)\\.png$/.exec(name);\n if (match) {\n images.push({\n page: Number(match[1]),\n png: new Uint8Array(await readFile(join(dir, name))),\n });\n }\n }\n images.sort((a, b) => a.page - b.page);\n return { ...result, images };\n } finally {\n await rm(dir, { recursive: true, force: true });\n }\n}\n\nexport interface ExportExtra {\n pdfStandard?: string;\n pages?: string;\n}\n\n/** Compile a PDF into the workspace (optionally a PDF standard and a page selection). */\nexport async function exportPdf(\n options: OneshotOptions,\n output: string,\n extra: ExportExtra,\n): Promise<CompileResult> {\n const args: string[] = [];\n if (extra.pdfStandard) args.push(\"--pdf-standard\", extra.pdfStandard);\n if (extra.pages) args.push(\"--pages\", extra.pages);\n return compile(options, output, args);\n}\n"],
5
- "mappings": "AAQA,SAAS,SAAS,SAAS,UAAU,UAAU;AAC/C,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,wBAAwB;AACjC,SAAS,WAAW;AAuBpB,eAAe,QACb,SACA,QACA,OACwB;AACxB,QAAM,WAAW,QAAQ,OAAO,CAAC,UAAU,QAAQ,IAAI,IAAI,CAAC;AAC5D,QAAM,YAAY,QAAQ,aAAa,CAAC,GAAG,QAAQ,CAAC,QAAQ;AAAA,IAC1D;AAAA,IACA;AAAA,EACF,CAAC;AACD,QAAM,SAAS,MAAM;AAAA,IACnB,QAAQ;AAAA,IACR,CAAC,WAAW,QAAQ,MAAM,QAAQ,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ;AAAA,IACpE;AAAA,MACE,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,MACb,WAAW,QAAQ,aAAa,OAAO;AAAA,IACzC;AAAA,EACF;AACA,MAAI,OAAO,UAAU;AACnB,UAAM,IAAI;AAAA,MACR,uCAAuC,KAAK,OAAO,QAAQ,aAAa,OAAO,oBAAoB,GAAG,CAAC;AAAA,MACvG;AAAA,IACF;AAAA,EACF;AACA,QAAM,cAAc,iBAAiB,OAAO,QAAQ,QAAQ,MAAM;AAClE,MACE,OAAO,SAAS,KAChB,CAAC,YAAY,KAAK,CAAC,UAAU,MAAM,aAAa,OAAO,GACvD;AACA,gBAAY,KAAK;AAAA,MACf,UAAU;AAAA,MACV,UACG,OAAO,UAAU,OAAO,QAAQ,KAAK,EAAE,MAAM,GAAG,GAAG,KACpD,0BAA0B,OAAO,IAAI;AAAA,MACvC,UAAU;AAAA,MACV,OAAO,CAAC;AAAA,MACR,OAAO,CAAC;AAAA,IACV,CAAC;AAAA,EACH;AACA,SAAO,EAAE,IAA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,CAAC;YACtC,MAAM,KAAK,GAAG,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC7C,IAAI,KAAK,EAAE,CAAC;gBACV,MAAM,CAAC,IAAI,CAAC;oBACV,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;oBACtB,GAAG,EAAE,IAAI,UAAU,CAAC,MAAM,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;iBACrD,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;QACvC,OAAO,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,CAAC;IAC/B,CAAC;YAAS,CAAC;QACT,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClD,CAAC;AACH,CAAC;AAOD,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,OAAuB,EACvB,MAAc,EACd,KAAkB;IAElB,MAAM,IAAI,GAAa,EAAE,CAAC;IAC1B,IAAI,KAAK,CAAC,WAAW;QAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,KAAK,CAAC,WAAW,CAAC,CAAC;IACtE,IAAI,KAAK,CAAC,KAAK;QAAE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IACnD,OAAO,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Build-directory ownership. A workspace session's scratch tree lives under
3
+ * `<dataDir>/build/<harness-pid>-<nonce>/` and carries an `owner.json` naming
4
+ * the harness process that created it. Cleanup removes only directories whose
5
+ * recorded owner is gone; a directory without a valid owner record stays in
6
+ * place.
7
+ *
8
+ * The build root is shared across workspaces, so ownership is recorded per
9
+ * directory and cleanup operates one directory at a time.
10
+ * @module dsh-typst/typst/owners
11
+ */
12
+ /**
13
+ * Remove build directories whose owner harness is gone. A directory owned by
14
+ * this process or by another live process is never touched; a directory
15
+ * without a valid owner record is left in place.
16
+ * @param base - the shared `<dataDir>/build` root.
17
+ * @param log - optional narration for a removed directory.
18
+ */
19
+ export declare function cleanupDeadBuildDirs(base: string, log?: (message: string) => void): Promise<void>;
20
+ /**
21
+ * Create this session's build directory under the shared root, after pruning
22
+ * directories whose previous owners are gone.
23
+ * @param dataDir - the plugin's private cache directory.
24
+ * @param log - optional narration.
25
+ * @returns the new directory, mode 0700, with a 0600 owner record.
26
+ */
27
+ export declare function makeBuildDir(dataDir: string, log?: (message: string) => void): Promise<string>;
28
+ //# sourceMappingURL=owners.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"owners.d.ts","sourceRoot":"","sources":["../../src/typst/owners.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AA+CH;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CACxC,IAAI,EAAE,MAAM,EACZ,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC9B,OAAO,CAAC,IAAI,CAAC,CAgBf;AAED;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC9B,OAAO,CAAC,MAAM,CAAC,CAcjB"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Build-directory ownership. A workspace session's scratch tree lives under
3
+ * `<dataDir>/build/<harness-pid>-<nonce>/` and carries an `owner.json` naming
4
+ * the harness process that created it. Cleanup removes only directories whose
5
+ * recorded owner is gone; a directory without a valid owner record stays in
6
+ * place.
7
+ *
8
+ * The build root is shared across workspaces, so ownership is recorded per
9
+ * directory and cleanup operates one directory at a time.
10
+ * @module dsh-typst/typst/owners
11
+ */
12
+ import { randomBytes } from "node:crypto";
13
+ import { mkdir, readFile, readdir, rm } from "node:fs/promises";
14
+ import { join } from "node:path";
15
+ import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
16
+ /** Whether a pid names a live process (EPERM still means it exists). */
17
+ function alive(pid) {
18
+ try {
19
+ process.kill(pid, 0);
20
+ return true;
21
+ }
22
+ catch (error) {
23
+ return error.code === "EPERM";
24
+ }
25
+ }
26
+ async function readOwner(path) {
27
+ const raw = await readFile(path, "utf8").catch(() => null);
28
+ if (raw === null)
29
+ return null;
30
+ try {
31
+ const value = JSON.parse(raw);
32
+ if (typeof value !== "object" || value === null)
33
+ return null;
34
+ const record = value;
35
+ if (typeof record.pid !== "number" ||
36
+ !Number.isInteger(record.pid) ||
37
+ record.pid <= 0)
38
+ return null;
39
+ return {
40
+ pid: record.pid,
41
+ startedAt: typeof record.startedAt === "string" ? record.startedAt : "unknown",
42
+ };
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ /**
49
+ * Remove build directories whose owner harness is gone. A directory owned by
50
+ * this process or by another live process is never touched; a directory
51
+ * without a valid owner record is left in place.
52
+ * @param base - the shared `<dataDir>/build` root.
53
+ * @param log - optional narration for a removed directory.
54
+ */
55
+ export async function cleanupDeadBuildDirs(base, log) {
56
+ let entries;
57
+ try {
58
+ entries = await readdir(base, { withFileTypes: true });
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ for (const entry of entries) {
64
+ if (!entry.isDirectory())
65
+ continue;
66
+ const dir = join(base, entry.name);
67
+ const owner = await readOwner(join(dir, "owner.json"));
68
+ if (owner === null)
69
+ continue;
70
+ if (owner.pid === process.pid || alive(owner.pid))
71
+ continue;
72
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
73
+ log?.(`removed stale typst build directory ${entry.name}`);
74
+ }
75
+ }
76
+ /**
77
+ * Create this session's build directory under the shared root, after pruning
78
+ * directories whose previous owners are gone.
79
+ * @param dataDir - the plugin's private cache directory.
80
+ * @param log - optional narration.
81
+ * @returns the new directory, mode 0700, with a 0600 owner record.
82
+ */
83
+ export async function makeBuildDir(dataDir, log) {
84
+ const base = join(dataDir, "build");
85
+ await mkdir(base, { recursive: true, mode: 0o700 });
86
+ await cleanupDeadBuildDirs(base, log);
87
+ const dir = join(base, `${process.pid}-${randomBytes(6).toString("hex")}`);
88
+ await mkdir(dir, { recursive: false, mode: 0o700 });
89
+ const record = {
90
+ pid: process.pid,
91
+ startedAt: new Date().toISOString(),
92
+ };
93
+ await writeFileAtomic(join(dir, "owner.json"), JSON.stringify(record), {
94
+ mode: 0o600,
95
+ });
96
+ return dir;
97
+ }
98
+ //# sourceMappingURL=owners.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"owners.js","sourceRoot":"","sources":["../../src/typst/owners.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAShE,wEAAwE;AACxE,SAAS,KAAK,CAAC,GAAW;IACxB,IAAI,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAQ,KAA+B,CAAC,IAAI,KAAK,OAAO,CAAC;IAC3D,CAAC;AACH,CAAC;AAED,KAAK,UAAU,SAAS,CAAC,IAAY;IACnC,MAAM,GAAG,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,I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IACH,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -12,9 +12,8 @@ import { type PageText } from "./text.js";
12
12
  * The directory pdf.js should read its cmaps and standard fonts from (the
13
13
  * installed pdfjs-dist package), or null when it cannot be resolved; typst
14
14
  * embeds its fonts, so extraction works without them.
15
- * @param hint - an extra candidate directory to prefer.
16
15
  */
17
- export declare function pdfjsDataDir(hint?: string | null): string | null;
16
+ export declare function pdfjsDataDir(): string | null;
18
17
  /**
19
18
  * Number of pages in a PDF, or a rejection when the bytes are not readable.
20
19
  * Runs without cmaps: only the structure is read.
@@ -1 +1 @@
1
- {"version":3,"file":"pdf-extract.d.ts","sourceRoot":"","sources":["../../src/typst/pdf-extract.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,EAAa,KAAK,QAAQ,EAAoB,MAAM,WAAW,CAAC;AAwCvE;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAahE;AA2BD;;;GAGG;AACH,wBAAsB,SAAS,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAOjE;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAChC,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,QAAQ,EAAE,CAAC,CA0BrB"}
1
+ {"version":3,"file":"pdf-extract.d.ts","sourceRoot":"","sources":["../../src/typst/pdf-extract.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,EAAa,KAAK,QAAQ,EAAoB,MAAM,WAAW,CAAC;AAgDvE;;;;GAIG;AACH,wBAAgB,YAAY,IAAI,MAAM,GAAG,IAAI,CAS5C;AA2BD;;;GAGG;AACH,wBAAsB,SAAS,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAOjE;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAChC,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,QAAQ,EAAE,CAAC,CAerB"}
@@ -1,87 +1,111 @@
1
+ /**
2
+ * Server-side PDF inspection with the user-space geometry the highlight
3
+ * engine needs: page count and per-page text + spans. pdf.js runs on the
4
+ * main thread through its fake-worker entry (`globalThis.pdfjsWorker`), the
5
+ * same arrangement the ZCode typst-workbench server (0.2.0) ships. Loading
6
+ * is lazy: a session that never highlights never pays for the module.
7
+ * Host half only.
8
+ * @module dsh-typst/typst/pdf-extract
9
+ */
1
10
  import { existsSync } from "node:fs";
2
11
  import { createRequire } from "node:module";
3
12
  import { dirname, join, resolve, sep } from "node:path";
4
13
  import { buildPage } from "./text.js";
5
14
  let loading = null;
15
+ /** Load pdf.js (legacy build) once; the fake-worker entry must be set first. */
6
16
  async function pdfjs() {
7
- loading ??= (async () => {
8
- const [pdf, worker] = await Promise.all([
9
- // pdf.js's own types describe the browser surface; the extraction
10
- // surface used here is the small one below, so the module is trusted
11
- // through `unknown` and consumed via PdfJsModule.
12
- import("pdfjs-dist/legacy/build/pdf.mjs"),
13
- import("pdfjs-dist/legacy/build/pdf.worker.mjs")
14
- ]);
15
- globalThis.pdfjsWorker = worker;
16
- return pdf;
17
- })();
18
- return loading;
17
+ if (loading !== null)
18
+ return loading;
19
+ const pending = (async () => {
20
+ const [pdf, worker] = await Promise.all([
21
+ // pdf.js's own types describe the browser surface; the extraction
22
+ // surface used here is the small one below, so the module is trusted
23
+ // through `unknown` and consumed via PdfJsModule.
24
+ import("pdfjs-dist/legacy/build/pdf.mjs"),
25
+ import("pdfjs-dist/legacy/build/pdf.worker.mjs"),
26
+ ]);
27
+ globalThis.pdfjsWorker = worker;
28
+ return pdf;
29
+ })();
30
+ loading = pending;
31
+ try {
32
+ return await pending;
33
+ }
34
+ catch (error) {
35
+ // A rejected import must not be cached forever: a transient module-load
36
+ // failure would otherwise disable page counts and highlights for the
37
+ // whole process.
38
+ if (loading === pending)
39
+ loading = null;
40
+ throw error;
41
+ }
19
42
  }
20
- function pdfjsDataDir(hint) {
21
- const candidates = [];
22
- if (hint) candidates.push(hint);
23
- try {
24
- const require2 = createRequire(import.meta.url);
25
- candidates.push(dirname(require2.resolve("pdfjs-dist/package.json")));
26
- } catch {
27
- }
28
- for (const candidate of candidates) {
29
- if (existsSync(join(candidate, "cmaps"))) return resolve(candidate) + sep;
30
- }
31
- return null;
43
+ /**
44
+ * The directory pdf.js should read its cmaps and standard fonts from (the
45
+ * installed pdfjs-dist package), or null when it cannot be resolved; typst
46
+ * embeds its fonts, so extraction works without them.
47
+ */
48
+ export function pdfjsDataDir() {
49
+ try {
50
+ const require = createRequire(import.meta.url);
51
+ const dir = dirname(require.resolve("pdfjs-dist/package.json"));
52
+ if (existsSync(join(dir, "cmaps")))
53
+ return resolve(dir) + sep;
54
+ }
55
+ catch {
56
+ // Not resolvable (vendored without node_modules).
57
+ }
58
+ return null;
32
59
  }
33
60
  async function open(data, dataDir) {
34
- const module = await pdfjs();
35
- return module.getDocument({
36
- data: new Uint8Array(data),
37
- ...dataDir ? {
38
- cMapUrl: `${dataDir}cmaps${sep}`,
39
- cMapPacked: true,
40
- standardFontDataUrl: `${dataDir}standard_fonts${sep}`
41
- } : {},
42
- disableFontFace: true,
43
- useSystemFonts: false,
44
- verbosity: 0
45
- });
61
+ const module = await pdfjs();
62
+ return module.getDocument({
63
+ data: new Uint8Array(data),
64
+ ...(dataDir
65
+ ? {
66
+ cMapUrl: `${dataDir}cmaps${sep}`,
67
+ cMapPacked: true,
68
+ standardFontDataUrl: `${dataDir}standard_fonts${sep}`,
69
+ }
70
+ : {}),
71
+ disableFontFace: true,
72
+ useSystemFonts: false,
73
+ verbosity: 0,
74
+ });
46
75
  }
47
- async function pageCount(data) {
48
- const task = await open(data, null);
49
- try {
50
- return (await task.promise).numPages;
51
- } finally {
52
- await task.destroy();
53
- }
76
+ /**
77
+ * Number of pages in a PDF, or a rejection when the bytes are not readable.
78
+ * Runs without cmaps: only the structure is read.
79
+ */
80
+ export async function pageCount(data) {
81
+ const task = await open(data, null);
82
+ try {
83
+ return (await task.promise).numPages;
84
+ }
85
+ finally {
86
+ await task.destroy();
87
+ }
54
88
  }
55
- async function extractPages(data, dataDir) {
56
- const task = await open(data, dataDir);
57
- try {
58
- const doc = await task.promise;
59
- const labels = await doc.getPageLabels().catch(() => null);
60
- const pages = [];
61
- for (let index = 0; index < doc.numPages; index++) {
62
- const page = await doc.getPage(index + 1);
63
- const [x1, y1, x2, y2] = page.view;
64
- const content = await page.getTextContent();
65
- pages.push(
66
- buildPage(content.items, {
67
- index,
68
- label: labels?.[index] || String(index + 1),
69
- width: x2 - x1,
70
- height: y2 - y1,
71
- originX: x1,
72
- originY: y1
73
- })
74
- );
75
- page.cleanup();
89
+ /**
90
+ * Extract per-page text + spans for quote matching and highlight rectangles.
91
+ * @param data - the PDF bytes.
92
+ * @param dataDir - cmap/standard-font directory from {@link pdfjsDataDir}.
93
+ */
94
+ export async function extractPages(data, dataDir) {
95
+ const task = await open(data, dataDir);
96
+ try {
97
+ const doc = await task.promise;
98
+ const pages = [];
99
+ for (let index = 0; index < doc.numPages; index++) {
100
+ const page = await doc.getPage(index + 1);
101
+ const content = await page.getTextContent();
102
+ pages.push(buildPage(content.items, { index }));
103
+ page.cleanup();
104
+ }
105
+ return pages;
106
+ }
107
+ finally {
108
+ await task.destroy();
76
109
  }
77
- return pages;
78
- } finally {
79
- await task.destroy();
80
- }
81
110
  }
82
- export {
83
- extractPages,
84
- pageCount,
85
- pdfjsDataDir
86
- };
87
- //# sourceMappingURL=pdf-extract.js.map
111
+ //# sourceMappingURL=pdf-extract.js.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/typst/pdf-extract.ts"],
4
- "sourcesContent": ["/**\n * Server-side PDF inspection with the user-space geometry the highlight\n * engine needs: page count and per-page text + spans. pdf.js runs on the\n * main thread through its fake-worker entry (`globalThis.pdfjsWorker`), the\n * same arrangement the ZCode typst-workbench server (0.2.0) ships. Loading\n * is lazy: a session that never highlights never pays for the module.\n * Host half only.\n * @module dsh-typst/typst/pdf-extract\n */\n\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport { buildPage, type PageText, type PdfTextItem } from \"./text.js\";\n\ninterface PdfJsDocument {\n numPages: number;\n getPageLabels(): Promise<string[] | null>;\n getPage(index: number): Promise<PdfJsPage>;\n destroy(): Promise<void>;\n}\n\ninterface PdfJsPage {\n view: [number, number, number, number];\n getTextContent(): Promise<{ items: PdfTextItem[] }>;\n cleanup(): void;\n}\n\ninterface PdfJsModule {\n getDocument(params: Record<string, unknown>): {\n promise: Promise<PdfJsDocument>;\n destroy(): Promise<void>;\n };\n}\n\nlet loading: Promise<PdfJsModule> | null = null;\n\n/** Load pdf.js (legacy build) once; the fake-worker entry must be set first. */\nasync function pdfjs(): Promise<PdfJsModule> {\n loading ??= (async () => {\n const [pdf, worker] = await Promise.all([\n // pdf.js's own types describe the browser surface; the extraction\n // surface used here is the small one below, so the module is trusted\n // through `unknown` and consumed via PdfJsModule.\n import(\"pdfjs-dist/legacy/build/pdf.mjs\") as Promise<unknown>,\n import(\"pdfjs-dist/legacy/build/pdf.worker.mjs\"),\n ]);\n (globalThis as Record<string, unknown>).pdfjsWorker = worker;\n return pdf as PdfJsModule;\n })();\n return loading;\n}\n\n/**\n * The directory pdf.js should read its cmaps and standard fonts from (the\n * installed pdfjs-dist package), or null when it cannot be resolved; typst\n * embeds its fonts, so extraction works without them.\n * @param hint - an extra candidate directory to prefer.\n */\nexport function pdfjsDataDir(hint?: string | null): string | null {\n const candidates: string[] = [];\n if (hint) candidates.push(hint);\n try {\n const require = createRequire(import.meta.url);\n candidates.push(dirname(require.resolve(\"pdfjs-dist/package.json\")));\n } catch {\n // Not resolvable (vendored without node_modules): fall through.\n }\n for (const candidate of candidates) {\n if (existsSync(join(candidate, \"cmaps\"))) return resolve(candidate) + sep;\n }\n return null;\n}\n\ninterface OpenTask {\n promise: Promise<PdfJsDocument>;\n destroy(): Promise<void>;\n}\n\nasync function open(\n data: Uint8Array,\n dataDir: string | null,\n): Promise<OpenTask> {\n const module = await pdfjs();\n return module.getDocument({\n data: new Uint8Array(data),\n ...(dataDir\n ? {\n cMapUrl: `${dataDir}cmaps${sep}`,\n cMapPacked: true,\n standardFontDataUrl: `${dataDir}standard_fonts${sep}`,\n }\n : {}),\n disableFontFace: true,\n useSystemFonts: false,\n verbosity: 0,\n }) as OpenTask;\n}\n\n/**\n * Number of pages in a PDF, or a rejection when the bytes are not readable.\n * Runs without cmaps: only the structure is read.\n */\nexport async function pageCount(data: Uint8Array): Promise<number> {\n const task = await open(data, null);\n try {\n return (await task.promise).numPages;\n } finally {\n await task.destroy();\n }\n}\n\n/**\n * Extract per-page text + spans for quote matching and highlight rectangles.\n * @param data - the PDF bytes.\n * @param dataDir - cmap/standard-font directory from {@link pdfjsDataDir}.\n */\nexport async function extractPages(\n data: Uint8Array,\n dataDir: string | null,\n): Promise<PageText[]> {\n const task = await open(data, dataDir);\n try {\n const doc = await task.promise;\n const labels = await doc.getPageLabels().catch(() => null);\n const pages: PageText[] = [];\n for (let index = 0; index < doc.numPages; index++) {\n const page = await doc.getPage(index + 1);\n const [x1, y1, x2, y2] = page.view;\n const content = await page.getTextContent();\n pages.push(\n buildPage(content.items, {\n index,\n label: labels?.[index] || String(index + 1),\n width: x2 - x1,\n height: y2 - y1,\n originX: x1,\n originY: y1,\n }),\n );\n page.cleanup();\n }\n return pages;\n } finally {\n await task.destroy();\n }\n}\n"],
5
- "mappings": "AAUA,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,MAAM,SAAS,WAAW;AAC5C,SAAS,iBAAkD;AAsB3D,IAAI,UAAuC;AAG3C,eAAe,QAA8B;AAC3C,eAAa,YAAY;AACvB,UAAM,CAAC,KAAK,MAAM,IAAI,MAAM,QAAQ,I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-shell lookup go through the harness `ctx.subprocess` seam, which
4
+ * supplies the scrubbed environment, managed process range, abort propagation
5
+ * and host-exit teardown.
6
+ *
7
+ * Two shapes are exposed: {@link ProcessRunner.run} collects a short command's
8
+ * output for toolchain probes and one-shot compiles; {@link ProcessRunner.spawnPiped}
9
+ * streams a long-running child (the watch) with incremental UTF-8 decoding.
10
+ * @module dsh-typst/typst/process
11
+ */
12
+ import type { SubprocessHandle, SubprocessOutcome, SubprocessRuntime } from "@deepseek-ai/dsh-subprocess";
13
+ /** Spawn facts shared by every typst child. */
14
+ export interface ProcessOptions {
15
+ /** Child working directory. */
16
+ cwd: string;
17
+ /** Explicit environment entries merged onto the provider's scrubbed base. */
18
+ env?: NodeJS.ProcessEnv;
19
+ /** Cancellation; the provider starts its managed-range termination. */
20
+ signal?: AbortSignal;
21
+ /** Grace period before the provider escalates termination. */
22
+ graceMs?: number;
23
+ }
24
+ /** The outcome of one short command; a nonzero exit is a normal value. */
25
+ export interface ProcessResult {
26
+ code: number | null;
27
+ signal: NodeJS.Signals | null;
28
+ stdout: string;
29
+ stderr: string;
30
+ timedOut: boolean;
31
+ aborted: boolean;
32
+ }
33
+ /** A long-running child whose stdout and stderr are decoded as text. */
34
+ export interface PipedProcess {
35
+ readonly handle: SubprocessHandle;
36
+ readonly done: Promise<SubprocessOutcome>;
37
+ /** Attach one listener fed by both streams; call once, immediately after spawn. */
38
+ onOutput(listener: (text: string) => void): void;
39
+ /** Start the provider's managed-range termination. */
40
+ terminate(): void;
41
+ /** Wait until the managed range is empty; false when `signal` aborted first. */
42
+ waitForExit(signal?: AbortSignal): Promise<boolean>;
43
+ }
44
+ /**
45
+ * Wrap the host subprocess capability. One instance is owned by the workbench
46
+ * service and shared by every workspace session.
47
+ */
48
+ export declare class ProcessRunner {
49
+ private readonly runtime;
50
+ constructor(runtime: SubprocessRuntime);
51
+ /**
52
+ * Spawn a long-running child with raw pipes. Both streams are decoded with
53
+ * a streaming decoder, so a multi-byte character split across chunks is
54
+ * never replaced with U+FFFD.
55
+ * @param argv - executable and arguments; never shell-interpreted.
56
+ * @param options - cwd, explicit env, cancellation and grace.
57
+ * @returns the live handle plus text-output helpers.
58
+ */
59
+ spawnPiped(argv: readonly string[], options: ProcessOptions): PipedProcess;
60
+ /**
61
+ * Run a short command to completion with bounded collected output.
62
+ * A nonzero exit resolves; only a spawn/provider failure or the deadline
63
+ * produces the failure shape.
64
+ * @param argv - executable and arguments.
65
+ * @param options - cwd, explicit env, cancellation, deadline and output cap.
66
+ * @returns exit facts plus decoded stdout/stderr.
67
+ */
68
+ run(argv: readonly string[], options: ProcessOptions & {
69
+ timeoutMs?: number;
70
+ collectBytes?: number;
71
+ }): Promise<ProcessResult>;
72
+ }
73
+ //# sourceMappingURL=process.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process.d.ts","sourceRoot":"","sources":["../../src/typst/process.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EACV,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,6BAA6B,CAAC;AAKrC,+CAA+C;AAC/C,MAAM,WAAW,cAAc;IAC7B,+BAA+B;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,6EAA6E;IAC7E,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,uEAAuE;IACvE,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,8DAA8D;IAC9D,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,0EAA0E;AAC1E,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,OAAO,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,wEAAwE;AACxE,MAAM,WAAW,YAAY;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