texlite 0.24.0 → 0.25.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 (241) hide show
  1. package/DESIGN.md +85 -2
  2. package/NPM_TESTING.md +46 -2
  3. package/OPERATIONS.md +136 -6
  4. package/README.md +1 -2
  5. package/README.zh-CN.md +2 -2
  6. package/THIRD_PARTY_NOTICES.md +12 -0
  7. package/dist/client/assets/AdminUsers-D4ljqr_D.js +1 -0
  8. package/dist/client/assets/AdminUsers-D4ljqr_D.js.br +0 -0
  9. package/dist/client/assets/AdminUsers-D4ljqr_D.js.gz +0 -0
  10. package/dist/client/assets/AgentManagement-DwRMP_nD.js +1 -0
  11. package/dist/client/assets/AgentManagement-DwRMP_nD.js.br +0 -0
  12. package/dist/client/assets/AgentManagement-DwRMP_nD.js.gz +0 -0
  13. package/dist/client/assets/AgentTerminal-CSsr21PC.js +2 -0
  14. package/dist/client/assets/AgentTerminal-CSsr21PC.js.br +0 -0
  15. package/dist/client/assets/AgentTerminal-CSsr21PC.js.gz +0 -0
  16. package/dist/client/assets/{AgentTerminalSurface-DliOcop5.js → AgentTerminalSurface-BLroKMGe.js} +1 -1
  17. package/dist/client/assets/{AgentTerminalSurface-DliOcop5.js.br → AgentTerminalSurface-BLroKMGe.js.br} +0 -0
  18. package/dist/client/assets/AgentTerminalSurface-BLroKMGe.js.gz +0 -0
  19. package/dist/client/assets/{AvatarSettingsDialog-iuEbMO4a.js → AvatarSettingsDialog-BgVGfSzn.js} +1 -1
  20. package/dist/client/assets/AvatarSettingsDialog-BgVGfSzn.js.br +0 -0
  21. package/dist/client/assets/AvatarSettingsDialog-BgVGfSzn.js.gz +0 -0
  22. package/dist/client/assets/CitationBibtexEditor-DLPom-qx.js +1 -0
  23. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js +3 -0
  24. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js.br +0 -0
  25. package/dist/client/assets/CitationLibraryDialog-Cn-kFi8E.js.gz +0 -0
  26. package/dist/client/assets/Dashboard-7JrR0t6C.js +5 -0
  27. package/dist/client/assets/Dashboard-7JrR0t6C.js.br +0 -0
  28. package/dist/client/assets/Dashboard-7JrR0t6C.js.gz +0 -0
  29. package/dist/client/assets/DrawioEditor-CYQnzKDd.js +1 -0
  30. package/dist/client/assets/DrawioEditor-CYQnzKDd.js.br +0 -0
  31. package/dist/client/assets/DrawioEditor-CYQnzKDd.js.gz +0 -0
  32. package/dist/client/assets/GitDialog-DMCVR8QK.js +4 -0
  33. package/dist/client/assets/GitDialog-DMCVR8QK.js.br +0 -0
  34. package/dist/client/assets/GitDialog-DMCVR8QK.js.gz +0 -0
  35. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js +1 -0
  36. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js.br +0 -0
  37. package/dist/client/assets/GitHubAccountDialog-BbJpR9Vq.js.gz +0 -0
  38. package/dist/client/assets/{HistoryDialog-upkR8E0L.js → HistoryDialog-CcPWpTLn.js} +3 -3
  39. package/dist/client/assets/HistoryDialog-CcPWpTLn.js.br +0 -0
  40. package/dist/client/assets/HistoryDialog-CcPWpTLn.js.gz +0 -0
  41. package/dist/client/assets/LatexEditor-D7C9jpJO.js +25 -0
  42. package/dist/client/assets/LatexEditor-D7C9jpJO.js.br +0 -0
  43. package/dist/client/assets/LatexEditor-D7C9jpJO.js.gz +0 -0
  44. package/dist/client/assets/{MarkdownPreview-_AXp5G7f.js → MarkdownPreview-Txs5upCY.js} +1 -1
  45. package/dist/client/assets/MarkdownPreview-Txs5upCY.js.br +0 -0
  46. package/dist/client/assets/MarkdownPreview-Txs5upCY.js.gz +0 -0
  47. package/dist/client/assets/{ProjectIconPickerDialog-BxjEYsau.js → ProjectIconPickerDialog-CUlPlfmL.js} +1 -1
  48. package/dist/client/assets/ProjectIconPickerDialog-CUlPlfmL.js.br +0 -0
  49. package/dist/client/assets/ProjectIconPickerDialog-CUlPlfmL.js.gz +0 -0
  50. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js +1 -0
  51. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js.br +0 -0
  52. package/dist/client/assets/ProjectSearchDialog-Bt6NyHIJ.js.gz +0 -0
  53. package/dist/client/assets/ProjectSettings-B6e7EAxq.js +4 -0
  54. package/dist/client/assets/ProjectSettings-B6e7EAxq.js.br +0 -0
  55. package/dist/client/assets/ProjectSettings-B6e7EAxq.js.gz +0 -0
  56. package/dist/client/assets/ProjectWorkspace-D0EMITec.js +25 -0
  57. package/dist/client/assets/ProjectWorkspace-D0EMITec.js.br +0 -0
  58. package/dist/client/assets/ProjectWorkspace-D0EMITec.js.gz +0 -0
  59. package/dist/client/assets/{QuickOpenDialog-HlkWqVR9.js → QuickOpenDialog-D6yjnquG.js} +1 -1
  60. package/dist/client/assets/QuickOpenDialog-D6yjnquG.js.br +0 -0
  61. package/dist/client/assets/QuickOpenDialog-D6yjnquG.js.gz +0 -0
  62. package/dist/client/assets/{ReadOnlySource-BIdN1YP_.js → ReadOnlySource-BOAnB5L0.js} +1 -1
  63. package/dist/client/assets/{SelectionHistoryDialog-Cb8I-G6m.js → SelectionHistoryDialog-D6ql9E0j.js} +2 -2
  64. package/dist/client/assets/SelectionHistoryDialog-D6ql9E0j.js.br +0 -0
  65. package/dist/client/assets/SelectionHistoryDialog-D6ql9E0j.js.gz +0 -0
  66. package/dist/client/assets/SharedProjectPage-DuscqDx5.js +2 -0
  67. package/dist/client/assets/SharedProjectPage-DuscqDx5.js.br +0 -0
  68. package/dist/client/assets/SharedProjectPage-DuscqDx5.js.gz +0 -0
  69. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js +1 -0
  70. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js.br +0 -0
  71. package/dist/client/assets/SystemMetricsDialog-KiKZOF2N.js.gz +0 -0
  72. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js +1 -0
  73. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js.br +0 -0
  74. package/dist/client/assets/TagManagementDialog-BHbqvu3K.js.gz +0 -0
  75. package/dist/client/assets/ThemeSwitcher-5cgNbWiG.js +1 -0
  76. package/dist/client/assets/{TikzGalleryDialog-cPUDQ5Wj.js → TikzGalleryDialog-CFbLjNTt.js} +1 -1
  77. package/dist/client/assets/TikzGalleryDialog-CFbLjNTt.js.br +0 -0
  78. package/dist/client/assets/TikzGalleryDialog-CFbLjNTt.js.gz +0 -0
  79. package/dist/client/assets/{WordCountDialog-AiuR3rra.js → WordCountDialog-hXC-cpPs.js} +1 -1
  80. package/dist/client/assets/WordCountDialog-hXC-cpPs.js.br +0 -0
  81. package/dist/client/assets/WordCountDialog-hXC-cpPs.js.gz +0 -0
  82. package/dist/client/assets/{chktex--32C-Pkl.js → chktex-CLzMD_9a.js} +1 -1
  83. package/dist/client/assets/file-down-DA4jGFrF.js +1 -0
  84. package/dist/client/assets/i18n-B8sR-BXw.js +13 -0
  85. package/dist/client/assets/i18n-B8sR-BXw.js.br +0 -0
  86. package/dist/client/assets/i18n-B8sR-BXw.js.gz +0 -0
  87. package/dist/client/assets/index-D6faTuJe.css +1 -0
  88. package/dist/client/assets/index-D6faTuJe.css.br +0 -0
  89. package/dist/client/assets/index-D6faTuJe.css.gz +0 -0
  90. package/dist/client/assets/index-dScQ5LCu.js +2 -0
  91. package/dist/client/assets/index-dScQ5LCu.js.br +0 -0
  92. package/dist/client/assets/index-dScQ5LCu.js.gz +0 -0
  93. package/dist/client/assets/relativeTime-zIVNCN0k.js +1 -0
  94. package/dist/client/assets/relativeTime-zIVNCN0k.js.br +0 -0
  95. package/dist/client/assets/relativeTime-zIVNCN0k.js.gz +0 -0
  96. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js +2 -0
  97. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js.br +0 -0
  98. package/dist/client/assets/sourceCursorStore-DWCXVKvp.js.gz +0 -0
  99. package/dist/client/assets/{spellCheck-DpWPgtM7.js → spellCheck-DpyzDbmq.js} +1 -1
  100. package/dist/client/assets/spellCheck-DpyzDbmq.js.br +0 -0
  101. package/dist/client/assets/spellCheck-DpyzDbmq.js.gz +0 -0
  102. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js +1 -0
  103. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js.br +0 -0
  104. package/dist/client/assets/useDeletionTransitions-Bm4I5qej.js.gz +0 -0
  105. package/dist/client/index.html +3 -4
  106. package/dist/server/agents/adapters/claude.js +5 -2
  107. package/dist/server/agents/adapters/common.js +18 -5
  108. package/dist/server/agents/execution.js +25 -4
  109. package/dist/server/agents/launcher.js +5 -2
  110. package/dist/server/agents/processIdentity.js +1 -1
  111. package/dist/server/agents/terminal.js +5 -2
  112. package/dist/server/agents/windowsJob.js +141 -0
  113. package/dist/server/app.js +24 -6
  114. package/dist/server/auth.js +3 -2
  115. package/dist/server/browserOrigin.js +15 -0
  116. package/dist/server/chktex.js +23 -11
  117. package/dist/server/collaboration.js +2 -1
  118. package/dist/server/compileDiagnostics.js +13 -9
  119. package/dist/server/compiler.js +70 -25
  120. package/dist/server/config.js +5 -1
  121. package/dist/server/db.js +4 -0
  122. package/dist/server/drawioLocks.js +114 -0
  123. package/dist/server/drawioOwnedBrowser.js +122 -0
  124. package/dist/server/drawioPdf.js +182 -0
  125. package/dist/server/environment.js +17 -8
  126. package/dist/server/files.js +86 -20
  127. package/dist/server/git.js +20 -16
  128. package/dist/server/harper.js +29 -10
  129. package/dist/server/history.js +62 -15
  130. package/dist/server/i18n.js +15 -0
  131. package/dist/server/index.js +15 -8
  132. package/dist/server/locales/zh-Hant.js +9 -0
  133. package/dist/server/pdfFonts.js +78 -0
  134. package/dist/server/pm2.js +2 -1
  135. package/dist/server/processTree.js +128 -7
  136. package/dist/server/projectDeletionCleanup.js +62 -0
  137. package/dist/server/projectMutations.js +3 -0
  138. package/dist/server/projectReplace.js +2 -2
  139. package/dist/server/projectSearch.js +2 -1
  140. package/dist/server/projectTemplateCache.js +94 -0
  141. package/dist/server/projectTemplateDownload.js +75 -0
  142. package/dist/server/projectTextSave.js +56 -0
  143. package/dist/server/routes/agents.js +2 -15
  144. package/dist/server/routes/compile.js +67 -9
  145. package/dist/server/routes/drawio.js +192 -0
  146. package/dist/server/routes/projectFiles.js +106 -20
  147. package/dist/server/routes/projects.js +81 -20
  148. package/dist/server/routes/users.js +10 -14
  149. package/dist/server/synctex.js +20 -3
  150. package/dist/server/texcount.js +27 -23
  151. package/dist/server/zip.js +37 -11
  152. package/dist/shared/drawio.js +79 -0
  153. package/dist/shared/fileTypes.js +1 -1
  154. package/dist/shared/pdfFonts.js +14 -0
  155. package/dist/shared/projectImport.js +21 -0
  156. package/package.json +3 -1
  157. package/dist/client/assets/AdminUsers-C-8tXzvj.js +0 -1
  158. package/dist/client/assets/AdminUsers-C-8tXzvj.js.br +0 -0
  159. package/dist/client/assets/AdminUsers-C-8tXzvj.js.gz +0 -0
  160. package/dist/client/assets/AgentManagement-DXgfP7l_.js +0 -1
  161. package/dist/client/assets/AgentManagement-DXgfP7l_.js.br +0 -0
  162. package/dist/client/assets/AgentManagement-DXgfP7l_.js.gz +0 -0
  163. package/dist/client/assets/AgentTerminal-DD4sskCS.js +0 -2
  164. package/dist/client/assets/AgentTerminal-DD4sskCS.js.br +0 -0
  165. package/dist/client/assets/AgentTerminal-DD4sskCS.js.gz +0 -0
  166. package/dist/client/assets/AgentTerminalSurface-DliOcop5.js.gz +0 -0
  167. package/dist/client/assets/AvatarSettingsDialog-iuEbMO4a.js.br +0 -0
  168. package/dist/client/assets/AvatarSettingsDialog-iuEbMO4a.js.gz +0 -0
  169. package/dist/client/assets/CitationBibtexEditor-CDiYDj3M.js +0 -1
  170. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js +0 -3
  171. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js.br +0 -0
  172. package/dist/client/assets/CitationLibraryDialog-CJlL-Ytx.js.gz +0 -0
  173. package/dist/client/assets/Dashboard-DqwGd9wd.js +0 -5
  174. package/dist/client/assets/Dashboard-DqwGd9wd.js.br +0 -0
  175. package/dist/client/assets/Dashboard-DqwGd9wd.js.gz +0 -0
  176. package/dist/client/assets/GitDialog-DUGAigLx.js +0 -4
  177. package/dist/client/assets/GitDialog-DUGAigLx.js.br +0 -0
  178. package/dist/client/assets/GitDialog-DUGAigLx.js.gz +0 -0
  179. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js +0 -1
  180. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js.br +0 -0
  181. package/dist/client/assets/GitHubAccountDialog-B4eD622i.js.gz +0 -0
  182. package/dist/client/assets/HistoryDialog-upkR8E0L.js.br +0 -0
  183. package/dist/client/assets/HistoryDialog-upkR8E0L.js.gz +0 -0
  184. package/dist/client/assets/InfoPopover-CQ3Q10tN.js +0 -1
  185. package/dist/client/assets/LatexEditor-DvDYTc0r.js +0 -25
  186. package/dist/client/assets/LatexEditor-DvDYTc0r.js.br +0 -0
  187. package/dist/client/assets/LatexEditor-DvDYTc0r.js.gz +0 -0
  188. package/dist/client/assets/MarkdownPreview-_AXp5G7f.js.br +0 -0
  189. package/dist/client/assets/MarkdownPreview-_AXp5G7f.js.gz +0 -0
  190. package/dist/client/assets/ProjectIconPickerDialog-BxjEYsau.js.br +0 -0
  191. package/dist/client/assets/ProjectIconPickerDialog-BxjEYsau.js.gz +0 -0
  192. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js +0 -1
  193. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js.br +0 -0
  194. package/dist/client/assets/ProjectSearchDialog-BB8thfK9.js.gz +0 -0
  195. package/dist/client/assets/ProjectSettings-Dx-b26uN.js +0 -4
  196. package/dist/client/assets/ProjectSettings-Dx-b26uN.js.br +0 -0
  197. package/dist/client/assets/ProjectSettings-Dx-b26uN.js.gz +0 -0
  198. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js +0 -25
  199. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js.br +0 -0
  200. package/dist/client/assets/ProjectWorkspace-DiurYeU1.js.gz +0 -0
  201. package/dist/client/assets/QuickOpenDialog-HlkWqVR9.js.br +0 -0
  202. package/dist/client/assets/QuickOpenDialog-HlkWqVR9.js.gz +0 -0
  203. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js.br +0 -0
  204. package/dist/client/assets/SelectionHistoryDialog-Cb8I-G6m.js.gz +0 -0
  205. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js +0 -2
  206. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js.br +0 -0
  207. package/dist/client/assets/SharedProjectPage-BBLOLjnD.js.gz +0 -0
  208. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js +0 -1
  209. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js.br +0 -0
  210. package/dist/client/assets/SystemMetricsDialog-Dr4pYWG6.js.gz +0 -0
  211. package/dist/client/assets/TagManagementDialog-D4fYVboy.js +0 -1
  212. package/dist/client/assets/TagManagementDialog-D4fYVboy.js.br +0 -0
  213. package/dist/client/assets/TagManagementDialog-D4fYVboy.js.gz +0 -0
  214. package/dist/client/assets/ThemeSwitcher-BgzkYTeA.js +0 -1
  215. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js.br +0 -0
  216. package/dist/client/assets/TikzGalleryDialog-cPUDQ5Wj.js.gz +0 -0
  217. package/dist/client/assets/WordCountDialog-AiuR3rra.js.br +0 -0
  218. package/dist/client/assets/WordCountDialog-AiuR3rra.js.gz +0 -0
  219. package/dist/client/assets/dist-DdUqlCPw.js +0 -1
  220. package/dist/client/assets/dist-DdUqlCPw.js.br +0 -0
  221. package/dist/client/assets/dist-DdUqlCPw.js.gz +0 -0
  222. package/dist/client/assets/i18n-Dpk6KCs6.js +0 -13
  223. package/dist/client/assets/i18n-Dpk6KCs6.js.br +0 -0
  224. package/dist/client/assets/i18n-Dpk6KCs6.js.gz +0 -0
  225. package/dist/client/assets/index-B1vejuOw.js +0 -2
  226. package/dist/client/assets/index-B1vejuOw.js.br +0 -0
  227. package/dist/client/assets/index-B1vejuOw.js.gz +0 -0
  228. package/dist/client/assets/index-Blr4J_Pq.css +0 -1
  229. package/dist/client/assets/index-Blr4J_Pq.css.br +0 -0
  230. package/dist/client/assets/index-Blr4J_Pq.css.gz +0 -0
  231. package/dist/client/assets/relativeTime-CcP1IEvr.js +0 -1
  232. package/dist/client/assets/relativeTime-CcP1IEvr.js.br +0 -0
  233. package/dist/client/assets/relativeTime-CcP1IEvr.js.gz +0 -0
  234. package/dist/client/assets/sourceCursorStore-EycYBVxj.js +0 -1
  235. package/dist/client/assets/sourceCursorStore-EycYBVxj.js.br +0 -0
  236. package/dist/client/assets/sourceCursorStore-EycYBVxj.js.gz +0 -0
  237. package/dist/client/assets/spellCheck-DpWPgtM7.js.br +0 -0
  238. package/dist/client/assets/spellCheck-DpWPgtM7.js.gz +0 -0
  239. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js +0 -1
  240. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js.br +0 -0
  241. package/dist/client/assets/useDeletionTransitions-DvxVkRuo.js.gz +0 -0
@@ -1,14 +1,14 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { createHash } from "node:crypto";
4
- import { spawn } from "node:child_process";
5
4
  import { performance } from "node:perf_hooks";
6
5
  import { pipeline } from "node:stream/promises";
7
6
  import { Transform } from "node:stream";
8
7
  import { gunzipSync, gzipSync } from "node:zlib";
9
8
  import { listProjectFilesAsync, outputRoot, resolveSourcePath, safeRelativePath, texFileStem } from "./files.js";
10
9
  import { parseCompileDiagnostics } from "./compileDiagnostics.js";
11
- import { detachedProcessGroup, killProcessGroup } from "./processTree.js";
10
+ import { afterProcessStop, spawnOwnedCommand, stopProcessTree } from "./processTree.js";
11
+ import { relocateSyncTeXInputs } from "./synctex.js";
12
12
  /** A controlled stop is a normal compile outcome, never a server error. */
13
13
  export class CompileCancelledError extends Error {
14
14
  constructor() {
@@ -84,10 +84,15 @@ export class CompileQueue {
84
84
  export class ProjectCompileCoordinator {
85
85
  queue;
86
86
  targets = new Map();
87
+ closing = false;
87
88
  constructor(queue) {
88
89
  this.queue = queue;
89
90
  }
90
91
  request(input) {
92
+ if (this.closing) {
93
+ input.onDiscarded("cancelled");
94
+ return Promise.resolve(cancelledCompileResult(input));
95
+ }
91
96
  const targetKey = `${input.projectId}\0${input.target ?? ""}`;
92
97
  const state = this.targets.get(targetKey) ?? { active: null, pending: null };
93
98
  this.targets.set(targetKey, state);
@@ -132,12 +137,25 @@ export class ProjectCompileCoordinator {
132
137
  cancel(projectId, target) {
133
138
  const targetKey = `${projectId}\0${target ?? ""}`;
134
139
  const state = this.targets.get(targetKey);
135
- const active = state?.active;
140
+ return state ? this.cancelState(state) : null;
141
+ }
142
+ async close() {
143
+ this.closing = true;
144
+ const active = [];
145
+ for (const state of this.targets.values()) {
146
+ if (state.active)
147
+ active.push(state.active.promise);
148
+ this.cancelState(state);
149
+ }
150
+ await Promise.allSettled(active);
151
+ }
152
+ cancelState(state) {
153
+ const active = state.active;
136
154
  if (!active)
137
155
  return null;
138
156
  const status = active.started ? "running" : "queued";
139
157
  active.controller.abort();
140
- if (state?.pending) {
158
+ if (state.pending) {
141
159
  const pending = state.pending;
142
160
  state.pending = null;
143
161
  pending.controller.abort();
@@ -270,7 +288,26 @@ async function copyAndDigest(source, destination) {
270
288
  return digest.digest("hex");
271
289
  }
272
290
  export function discardCompileSnapshot(snapshot) {
273
- fs.rmSync(snapshot.root, { recursive: true, force: true });
291
+ removeUnpublishedCompileRun(snapshot.root);
292
+ }
293
+ const removeCompileRunOptions = {
294
+ recursive: true, force: true,
295
+ ...(process.platform === "win32" ? { maxRetries: 3, retryDelay: 100 } : {})
296
+ };
297
+ const warnCompileCleanup = (error, directory) => {
298
+ process.emitWarning(`Could not remove retired compile run ${directory}: ${String(error)}`, { code: "TEXLITE_COMPILE_CLEANUP" });
299
+ };
300
+ function removeUnpublishedCompileRun(directory, warn = warnCompileCleanup) {
301
+ try {
302
+ fs.rmSync(directory, removeCompileRunOptions);
303
+ }
304
+ catch (error) {
305
+ if (process.platform !== "win32" || !["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"].includes(error.code ?? ""))
306
+ throw error;
307
+ // An antivirus scanner or another reader can still have a handle open.
308
+ // Keep the stale bundle for the startup sweep instead of failing the run.
309
+ warn(error, directory);
310
+ }
274
311
  }
275
312
  /**
276
313
  * Returns whether the incremental latexmk cache for a root document exists.
@@ -306,7 +343,7 @@ export function cleanCompileArtifacts(config, projectId, mainFile, runIds = [])
306
343
  fs.rmSync(compileRunRoot(config, projectId, runId), { recursive: true, force: true });
307
344
  }
308
345
  }
309
- export function publishCompileArtifacts(config, projectId, snapshot, result) {
346
+ export function publishCompileArtifacts(config, projectId, snapshot, result, warnCleanup = warnCompileCleanup) {
310
347
  if (!result.ok || !result.pdfPath)
311
348
  throw new Error("Cannot publish a failed compilation result");
312
349
  const manifestDirectory = compileTargetRoot(config, projectId, snapshot.mainFile);
@@ -328,8 +365,10 @@ export function publishCompileArtifacts(config, projectId, snapshot, result) {
328
365
  if (previous && previous.runId !== snapshot.runId) {
329
366
  // Keep the previous immutable bundle briefly so an already-open PDF or SyncTeX
330
367
  // request can finish after the manifest switches to the new bundle.
368
+ const directory = compileRunRoot(config, projectId, previous.runId);
331
369
  const cleanup = setTimeout(() => {
332
- fs.rmSync(compileRunRoot(config, projectId, previous.runId), { recursive: true, force: true });
370
+ // Never throw out of the timer if a previous PDF still has an open handle.
371
+ void fs.promises.rm(directory, removeCompileRunOptions).catch((error) => warnCleanup(error, directory));
333
372
  }, 60_000);
334
373
  cleanup.unref();
335
374
  }
@@ -414,7 +453,7 @@ function readPublishedManifest(config, projectId, manifestPath, expectedMainFile
414
453
  }
415
454
  }
416
455
  /** Remove run bundles left by an interrupted process, preserving the published PDF. */
417
- export function pruneOrphanedCompileRuns(config, projectId) {
456
+ export function pruneOrphanedCompileRuns(config, projectId, warnCleanup = warnCompileCleanup) {
418
457
  const runsRoot = path.join(compileDataRoot(config, projectId), "runs");
419
458
  const publishedRunIds = new Set(listPublishedCompileArtifacts(config, projectId).map((artifact) => artifact.runId));
420
459
  if (!fs.existsSync(runsRoot))
@@ -422,7 +461,7 @@ export function pruneOrphanedCompileRuns(config, projectId) {
422
461
  for (const entry of fs.readdirSync(runsRoot, { withFileTypes: true })) {
423
462
  if (!entry.isDirectory() || publishedRunIds.has(entry.name))
424
463
  continue;
425
- fs.rmSync(path.join(runsRoot, entry.name), { recursive: true, force: true });
464
+ removeUnpublishedCompileRun(path.join(runsRoot, entry.name), warnCleanup);
426
465
  }
427
466
  }
428
467
  function compileDataRoot(config, projectId) {
@@ -582,7 +621,7 @@ function copyCompileArtifacts(source, destination) {
582
621
  }
583
622
  function rewriteSynctexSource(synctexPath, cacheSource, snapshotSource) {
584
623
  const original = gunzipSync(fs.readFileSync(synctexPath)).toString("utf8");
585
- const rewritten = original.replaceAll(path.resolve(cacheSource), path.resolve(snapshotSource));
624
+ const rewritten = relocateSyncTeXInputs(original, cacheSource, snapshotSource);
586
625
  if (rewritten !== original)
587
626
  fs.writeFileSync(synctexPath, gzipSync(Buffer.from(rewritten)), { mode: 0o600 });
588
627
  }
@@ -631,52 +670,58 @@ export async function compileProject(config, snapshot, mainFileInput, engine, la
631
670
  args.push(...config.extraArgs, mainFile);
632
671
  const latexmkStartedAt = performance.now();
633
672
  const processResult = await new Promise((resolve, reject) => {
634
- const child = spawn(config.latexmk, args, {
673
+ const child = spawnOwnedCommand(config.latexmk, args, {
635
674
  cwd,
636
- shell: false,
637
- detached: detachedProcessGroup(),
638
- env: { ...process.env, max_print_line: "1000" },
639
- stdio: ["ignore", "pipe", "pipe"]
675
+ env: { ...process.env, max_print_line: "1000" }
640
676
  });
641
677
  let log = "";
642
678
  let cancelled = false;
679
+ let timedOut = false;
643
680
  const append = (chunk) => {
644
- log += chunk.toString("utf8");
681
+ log += chunk;
645
682
  if (log.length > 2_000_000)
646
683
  log = log.slice(-2_000_000);
647
684
  };
648
- child.stdout.on("data", append);
649
- child.stderr.on("data", append);
685
+ child.stdout.setEncoding("utf8").on("data", append);
686
+ child.stderr.setEncoding("utf8").on("data", append);
650
687
  let timeout = null;
651
688
  const cancel = () => {
652
689
  if (cancelled)
653
690
  return;
654
691
  cancelled = true;
655
692
  log += "\nCompilation was cancelled.\n";
656
- killProcessGroup(child);
693
+ void stopProcessTree(child).catch(fail);
657
694
  };
658
695
  const removeAbortListener = () => signal?.removeEventListener("abort", cancel);
659
- child.once("error", (error) => {
696
+ function fail(error) {
660
697
  if (timeout)
661
698
  clearTimeout(timeout);
662
699
  removeAbortListener();
663
700
  reject(error);
664
- });
701
+ }
702
+ child.once("error", fail);
665
703
  timeout = setTimeout(() => {
666
704
  if (cancelled)
667
705
  return;
668
- log += `\nCompilation exceeded ${config.compileTimeoutMs / 1000} seconds and was terminated.\n`;
669
- killProcessGroup(child);
706
+ if (process.platform === "win32")
707
+ timedOut = true;
708
+ else
709
+ log += `\nCompilation exceeded ${config.compileTimeoutMs / 1000} seconds and was terminated.\n`;
710
+ void stopProcessTree(child).catch(fail);
670
711
  }, config.compileTimeoutMs);
671
712
  if (signal?.aborted)
672
713
  cancel();
673
714
  else
674
715
  signal?.addEventListener("abort", cancel, { once: true });
675
- child.on("close", (code) => {
716
+ child.once("close", (code) => {
676
717
  if (timeout)
677
718
  clearTimeout(timeout);
678
719
  removeAbortListener();
679
- resolve({ code, log, cancelled });
720
+ afterProcessStop(child, () => {
721
+ if (timedOut)
722
+ log += `\nCompilation exceeded ${config.compileTimeoutMs / 1000} seconds and was terminated.\n`;
723
+ resolve({ code: timedOut ? null : code, log, cancelled });
724
+ }, reject);
680
725
  });
681
726
  });
682
727
  const latexmkMs = performance.now() - latexmkStartedAt;
@@ -98,6 +98,8 @@ export function loadConfig(configPathOverride) {
98
98
  clientDir,
99
99
  tikzGalleryEnabled: fileConfig.tikzGallery?.enabled ?? CONFIG_DEFAULTS.tikzGalleryEnabled,
100
100
  tikzGalleryDir: resolveConfiguredPath("tikzGallery.path", fileConfig.tikzGallery?.path ?? CONFIG_DEFAULTS.tikzGalleryPath, configDirectory),
101
+ drawioBrowserPath: fileConfig.drawio?.browserPath
102
+ ? resolveConfiguredPath("drawio.browserPath", fileConfig.drawio.browserPath, configDirectory) : undefined,
101
103
  sessionDays: integerSetting("sessionDays", process.env.TEXLITE_SESSION_DAYS, fileConfig.sessionDays, CONFIG_DEFAULTS.sessionDays, CONFIG_LIMITS.sessionDays),
102
104
  compileTimeoutMs: compileTimeoutSeconds * 1000,
103
105
  maxCompileJobs,
@@ -179,7 +181,7 @@ function resolveBasePath(fileConfig) {
179
181
  }
180
182
  return basePath;
181
183
  }
182
- function isEngine(value) {
184
+ export function isEngine(value) {
183
185
  return typeof value === "string" && LATEX_ENGINES.includes(value);
184
186
  }
185
187
  function isPdfLoadingStrategy(value) {
@@ -216,6 +218,8 @@ function validateFileConfig(config) {
216
218
  const storage = optionalSection(config.storage, "storage");
217
219
  optionalString(storage?.dataDir, "storage.dataDir", { min: 1, max: 4_096 });
218
220
  const tikzGallery = optionalSection(config.tikzGallery, "tikzGallery");
221
+ const drawio = optionalSection(config.drawio, "drawio");
222
+ optionalString(drawio?.browserPath, "drawio.browserPath", { min: 1, max: 4_096 });
219
223
  if (tikzGallery && Object.prototype.hasOwnProperty.call(tikzGallery, "enabled") && typeof tikzGallery.enabled !== "boolean") {
220
224
  throw configurationError("tikzGallery.enabled", "must be true or false");
221
225
  }
package/dist/server/db.js CHANGED
@@ -219,6 +219,10 @@ const databaseMigrations = [
219
219
  DELETE FROM project_history_objects;
220
220
  INSERT INTO project_history_objects (project_id, digest, size, refs)
221
221
  SELECT project_id, digest, MAX(size), COUNT(*) FROM project_history_version_objects GROUP BY project_id, digest;`);
222
+ } },
223
+ { version: 26, name: "add_pending_project_deletions", apply: (db) => {
224
+ // These records must outlive the projects they refer to.
225
+ db.exec("CREATE TABLE IF NOT EXISTS pending_project_deletions (project_id TEXT PRIMARY KEY NOT NULL) WITHOUT ROWID");
222
226
  } }
223
227
  ];
224
228
  /** Create the snapshot object index and its triggers, and index existing snapshots. */
@@ -0,0 +1,114 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { httpError } from "./http.js";
3
+ import { drawioPdfPath } from "../shared/drawio.js";
4
+ export const DRAWIO_LOCK_TTL_MS = 60_000;
5
+ export const DRAWIO_LOCK_PING_MS = 20_000;
6
+ const containsPath = (root, file) => file === root || file.startsWith(`${root}/`);
7
+ /** Runtime-only ownership: a token is valid only while its exact socket owns the lease. */
8
+ export class DrawioLocks {
9
+ leases = new Map();
10
+ closed = false;
11
+ key(projectId, path) { return JSON.stringify([projectId, path]); }
12
+ active(projectId, path) {
13
+ const lease = this.leases.get(this.key(projectId, path));
14
+ if (lease && (lease.expiresAt <= Date.now() || lease.socket.readyState !== 1 || !lease.valid())) {
15
+ this.release(lease);
16
+ return undefined;
17
+ }
18
+ return lease;
19
+ }
20
+ acquire(projectId, path, userId, name, socket, valid, revision = "") {
21
+ if (this.closed || !valid()) {
22
+ socket.close(1008, "Access denied");
23
+ return;
24
+ }
25
+ if (socket.readyState !== 1)
26
+ return;
27
+ const existing = this.active(projectId, path);
28
+ if (existing) {
29
+ socket.send(JSON.stringify({ type: "busy", name: existing.name }));
30
+ socket.close(1000);
31
+ return;
32
+ }
33
+ const token = randomUUID();
34
+ const lease = { projectId, path, userId, name, token, socket, valid, expiresAt: Date.now() + DRAWIO_LOCK_TTL_MS,
35
+ timer: setInterval(() => {
36
+ if (this.active(projectId, path) !== lease)
37
+ return;
38
+ try {
39
+ socket.ping();
40
+ }
41
+ catch {
42
+ this.release(lease);
43
+ }
44
+ }, DRAWIO_LOCK_PING_MS) };
45
+ lease.timer.unref();
46
+ this.leases.set(this.key(projectId, path), lease);
47
+ socket.on("pong", () => {
48
+ // A late pong cannot resurrect an expired/replaced lease.
49
+ if (this.active(projectId, path) === lease)
50
+ lease.expiresAt = Date.now() + DRAWIO_LOCK_TTL_MS;
51
+ });
52
+ socket.on("message", (data) => {
53
+ if (data.toString() === "release")
54
+ this.release(lease);
55
+ });
56
+ socket.on("close", () => this.release(lease));
57
+ socket.on("error", () => this.release(lease));
58
+ socket.send(JSON.stringify({ type: "acquired", token, revision }));
59
+ }
60
+ assertOwned(projectId, path, token, userId) {
61
+ const lease = this.active(projectId, path);
62
+ if (!lease || lease.userId !== userId || lease.token !== token)
63
+ throw httpError(409, "DRAWIO_LOCK_LOST");
64
+ }
65
+ *matching(projectId, paths) {
66
+ for (const candidate of this.leases.values()) {
67
+ if (candidate.projectId !== projectId)
68
+ continue;
69
+ const lease = this.active(projectId, candidate.path);
70
+ if (lease && paths.some((path) => containsPath(path, lease.path) || containsPath(path, drawioPdfPath(lease.path))))
71
+ yield lease;
72
+ }
73
+ }
74
+ assertUnlocked(projectId, paths) {
75
+ for (const lease of this.matching(projectId, paths)) {
76
+ throw httpError(409, "DRAWIO_LOCKED", { name: lease.name });
77
+ }
78
+ }
79
+ /** The owning editor may delete its source, but not another lease or just its exported PDF. */
80
+ prepareDelete(projectId, path, userId, token) {
81
+ let removedLease;
82
+ for (const lease of this.matching(projectId, [path])) {
83
+ if (lease.userId !== userId || lease.token !== token || !containsPath(path, lease.path)) {
84
+ throw httpError(409, "DRAWIO_LOCKED", { name: lease.name });
85
+ }
86
+ removedLease = lease;
87
+ }
88
+ if (token !== undefined && !removedLease)
89
+ throw httpError(409, "DRAWIO_LOCK_LOST");
90
+ // Run only after the filesystem deletion succeeds, inside the same mutation.
91
+ return () => { if (removedLease)
92
+ this.release(removedLease); };
93
+ }
94
+ revokeProject(projectId) {
95
+ for (const lease of [...this.leases.values()])
96
+ if (lease.projectId === projectId)
97
+ this.release(lease);
98
+ }
99
+ close() {
100
+ this.closed = true;
101
+ for (const lease of [...this.leases.values()])
102
+ this.release(lease);
103
+ }
104
+ release(lease) {
105
+ const key = this.key(lease.projectId, lease.path);
106
+ if (this.leases.get(key) !== lease)
107
+ return;
108
+ this.leases.delete(key);
109
+ clearInterval(lease.timer);
110
+ // terminate avoids a dead peer keeping the close handshake alive forever.
111
+ if (lease.socket.readyState !== 3)
112
+ lease.socket.terminate();
113
+ }
114
+ }
@@ -0,0 +1,122 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { afterProcessStop, spawnOwnedCommand, stopProcessTree } from "./processTree.js";
5
+ /** Chrome's DevTools pipe carries NUL-terminated UTF-8 JSON, not a TCP endpoint. */
6
+ class DevToolsPipe {
7
+ input;
8
+ output;
9
+ onmessage;
10
+ onclose;
11
+ pending = "";
12
+ closed = false;
13
+ constructor(input, output) {
14
+ this.input = input;
15
+ this.output = output;
16
+ output.setEncoding("utf8").on("data", (chunk) => {
17
+ this.pending += chunk;
18
+ let start = 0;
19
+ for (let end = this.pending.indexOf("\0"); end !== -1; end = this.pending.indexOf("\0", start)) {
20
+ const message = this.pending.slice(start, end);
21
+ setImmediate(() => { if (!this.closed)
22
+ this.onmessage?.(message); });
23
+ start = end + 1;
24
+ }
25
+ this.pending = this.pending.slice(start);
26
+ });
27
+ output.once("close", () => this.close());
28
+ output.on("error", () => this.close());
29
+ input.on("error", () => this.close());
30
+ }
31
+ send(message) {
32
+ if (this.closed)
33
+ throw new Error("DevTools pipe is closed");
34
+ this.input.write(message + "\0");
35
+ }
36
+ close() {
37
+ if (this.closed)
38
+ return;
39
+ this.closed = true;
40
+ this.pending = "";
41
+ this.input.destroy();
42
+ this.output.destroy();
43
+ this.onclose?.();
44
+ }
45
+ }
46
+ /** Launch Chrome through the Windows job gate, retaining Puppeteer's defaults and sandbox. */
47
+ export async function launchOwnedDrawioBrowser(api, executable, signal) {
48
+ signal.throwIfAborted();
49
+ // A unique non-default profile prevents reuse of the user's running browser.
50
+ const profile = await fs.mkdtemp(path.join(os.tmpdir(), "texlite-drawio-"));
51
+ let child;
52
+ let transport;
53
+ let closed;
54
+ let cleanup;
55
+ let launchFailure;
56
+ const release = () => cleanup ??= (async () => {
57
+ signal.removeEventListener("abort", abort);
58
+ transport?.close();
59
+ // Do not remove a profile still held by browser processes, or release
60
+ // this job's renderer slot before the process tree has been stopped.
61
+ if (child)
62
+ await Promise.all([stopProcessTree(child), closed]);
63
+ await fs.rm(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
64
+ })();
65
+ const abort = () => { void release().catch(() => undefined); };
66
+ try {
67
+ const args = await api.defaultArgs({ headless: true, userDataDir: profile });
68
+ signal.throwIfAborted();
69
+ const launched = spawnOwnedCommand(executable, [...args, "--remote-debugging-pipe"], { devtoolsPipe: true });
70
+ child = launched;
71
+ closed = new Promise((resolve) => launched.once("close", () => {
72
+ // Keep the launcher diagnosis (for example, Windows policy denying
73
+ // job assignment) instead of reporting only a broken DevTools pipe.
74
+ afterProcessStop(launched, resolve, (error) => { launchFailure = error; resolve(); });
75
+ }));
76
+ launched.on("error", (error) => { launchFailure = error; transport?.close(); });
77
+ launched.stdout.resume();
78
+ launched.stderr.resume();
79
+ transport = new DevToolsPipe(launched.stdio[3], launched.stdio[4]);
80
+ signal.addEventListener("abort", abort, { once: true });
81
+ const launchTimeout = AbortSignal.timeout(10_000);
82
+ launchTimeout.addEventListener("abort", abort, { once: true });
83
+ let browser;
84
+ try {
85
+ browser = await api.connect({ transport, protocolTimeout: 10_000 });
86
+ signal.throwIfAborted();
87
+ launchTimeout.throwIfAborted();
88
+ }
89
+ finally {
90
+ launchTimeout.removeEventListener("abort", abort);
91
+ }
92
+ return {
93
+ browser,
94
+ close: async () => {
95
+ let timeout;
96
+ try {
97
+ if (!signal.aborted)
98
+ await Promise.race([
99
+ browser.close(),
100
+ new Promise((resolve) => { timeout = setTimeout(resolve, 2_000); timeout.unref(); })
101
+ ]);
102
+ }
103
+ catch {
104
+ // A dead or unresponsive browser is handled by the job below.
105
+ }
106
+ finally {
107
+ clearTimeout(timeout);
108
+ await release();
109
+ }
110
+ }
111
+ };
112
+ }
113
+ catch (error) {
114
+ try {
115
+ await release();
116
+ }
117
+ catch (cleanupError) {
118
+ throw new AggregateError([error, cleanupError], "Could not clean up failed draw.io browser launch");
119
+ }
120
+ throw launchFailure ?? error;
121
+ }
122
+ }
@@ -0,0 +1,182 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { launchOwnedDrawioBrowser } from "./drawioOwnedBrowser.js";
4
+ import { HttpError, httpError } from "./http.js";
5
+ /** Only Chromium-family browsers share this export backend. No browser is downloaded. */
6
+ export function browserCandidates(platform = process.platform, env = process.env) {
7
+ const names = platform === "win32" ? ["chromium.exe", "chrome.exe", "msedge.exe"]
8
+ : ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome", "chrome", "microsoft-edge-stable", "microsoft-edge", "msedge"];
9
+ const directories = (env.PATH ?? "").split(platform === "win32" ? ";" : ":").filter(Boolean);
10
+ const candidates = names.flatMap((name) => directories.map((directory) => path.join(directory, name)));
11
+ if (platform === "darwin")
12
+ candidates.push("/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge");
13
+ if (platform === "win32") {
14
+ for (const directory of [env.LOCALAPPDATA, env.PROGRAMFILES, env["PROGRAMFILES(X86)"]].filter((value) => Boolean(value))) {
15
+ candidates.push(path.join(directory, "Chromium", "Application", "chrome.exe"), path.join(directory, "Google", "Chrome", "Application", "chrome.exe"), path.join(directory, "Microsoft", "Edge", "Application", "msedge.exe"));
16
+ }
17
+ }
18
+ // Keep the requested preference across standard install locations and PATH.
19
+ const rank = (candidate) => /chromium/i.test(candidate) ? 0 : /(?:msedge|microsoft.edge)/i.test(candidate) ? 2 : 1;
20
+ return [...new Set(candidates)].sort((left, right) => rank(left) - rank(right));
21
+ }
22
+ export async function findDrawioBrowser(configured) {
23
+ for (const candidate of configured ? [configured] : browserCandidates()) {
24
+ try {
25
+ await fs.promises.access(candidate, process.platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
26
+ if ((await fs.promises.stat(candidate)).isFile())
27
+ return candidate;
28
+ }
29
+ catch { /* Missing candidates are optional; launch failures are reported separately. */ }
30
+ }
31
+ throw httpError(503, "DRAWIO_BROWSER_UNAVAILABLE");
32
+ }
33
+ async function closeBrowser(browser) {
34
+ const timer = setTimeout(() => { browser.process()?.kill("SIGKILL"); }, 2_000);
35
+ timer.unref();
36
+ try {
37
+ await browser.close();
38
+ }
39
+ catch {
40
+ browser.process()?.kill("SIGKILL");
41
+ }
42
+ finally {
43
+ clearTimeout(timer);
44
+ }
45
+ }
46
+ /** Per-app lifecycle: bounded host work, cancellation, and server-shutdown cleanup. */
47
+ export class DrawioPdfRenderer {
48
+ reportError;
49
+ jobs = new Set();
50
+ pending = new Set();
51
+ closing = false;
52
+ detectedBrowser;
53
+ constructor(reportError) {
54
+ this.reportError = reportError;
55
+ }
56
+ async close() {
57
+ this.closing = true;
58
+ for (const job of this.jobs)
59
+ job.abort();
60
+ await Promise.allSettled([...this.pending]);
61
+ }
62
+ render(svg, browserPath, signal) {
63
+ if (this.closing || this.jobs.size >= 2)
64
+ return Promise.reject(httpError(503, "DRAWIO_EXPORT_BUSY"));
65
+ const controller = new AbortController();
66
+ this.jobs.add(controller);
67
+ const job = this.renderDocument(svg, browserPath, AbortSignal.any([
68
+ controller.signal, AbortSignal.timeout(30_000), ...(signal ? [signal] : [])
69
+ ])).finally(() => { this.jobs.delete(controller); this.pending.delete(job); });
70
+ this.pending.add(job);
71
+ return job;
72
+ }
73
+ async renderDocument(svg, configured, signal) {
74
+ let close;
75
+ try {
76
+ signal.throwIfAborted();
77
+ const executablePath = this.detectedBrowser && this.detectedBrowser.configured === configured
78
+ ? this.detectedBrowser.path : await findDrawioBrowser(configured);
79
+ this.detectedBrowser = { configured, path: executablePath };
80
+ const { default: puppeteer } = await import("puppeteer-core");
81
+ signal.throwIfAborted();
82
+ let browser;
83
+ if (process.platform === "win32") {
84
+ ({ browser, close } = await launchOwnedDrawioBrowser(puppeteer, executablePath, signal));
85
+ }
86
+ else {
87
+ browser = await puppeteer.launch({ executablePath, browser: "chrome", headless: true, pipe: true,
88
+ timeout: 10_000, signal, handleSIGINT: false, handleSIGHUP: false, handleSIGTERM: false });
89
+ close = () => closeBrowser(browser);
90
+ }
91
+ signal.throwIfAborted();
92
+ const page = await browser.newPage();
93
+ page.setDefaultTimeout(10_000);
94
+ // SVG/foreignObject is untrusted. Never run its scripts or allow access
95
+ // to host files, loopback services, or remote resources during export.
96
+ await page.setJavaScriptEnabled(false);
97
+ await page.setRequestInterception(true);
98
+ let blockedResource = false;
99
+ page.on("request", (request) => {
100
+ if (request.url().startsWith("data:"))
101
+ void request.continue();
102
+ else {
103
+ blockedResource = true;
104
+ void request.abort();
105
+ }
106
+ });
107
+ await page.setContent(`<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; font-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><style>html,body{margin:0;padding:0;background:white}svg{display:block}*{box-sizing:border-box}</style></head><body></body></html>`);
108
+ const size = await page.evaluate((source) => {
109
+ const documentSvg = new DOMParser().parseFromString(source, "image/svg+xml");
110
+ const svg = documentSvg.documentElement;
111
+ if (documentSvg.querySelector("parsererror") || svg.localName !== "svg" || svg.namespaceURI !== "http://www.w3.org/2000/svg")
112
+ return null;
113
+ const node = document.importNode(svg, true);
114
+ // Scripts are disabled/CSP-blocked; also remove active containers and
115
+ // navigation so exported PDFs do not inherit executable attachments.
116
+ node.querySelectorAll("script,iframe,object,embed,base,link").forEach((element) => element.remove());
117
+ node.querySelectorAll("a").forEach((link) => { link.removeAttribute("href"); link.removeAttributeNS("http://www.w3.org/1999/xlink", "href"); });
118
+ document.body.append(node);
119
+ const box = node.viewBox.baseVal;
120
+ const width = node.width.baseVal.value || box.width;
121
+ const height = node.height.baseVal.value || box.height;
122
+ if (![width, height].every((value) => Number.isFinite(value) && value >= 1 && value <= 14_000)
123
+ || width * height > 50_000_000)
124
+ return null;
125
+ node.setAttribute("width", String(width));
126
+ node.setAttribute("height", String(height));
127
+ return { width, height };
128
+ }, svg);
129
+ if (!size)
130
+ throw httpError(400, "DRAWIO_INVALID");
131
+ await page.evaluate(async () => {
132
+ await document.fonts.ready;
133
+ await Promise.all(Array.from(document.images, async (image) => { if (!image.complete)
134
+ await image.decode(); }));
135
+ // Draw.io also uses SVG <image>, which is not in document.images.
136
+ await Promise.all(Array.from(document.querySelectorAll("svg image"), async (image) => {
137
+ const href = image.getAttribute("href") ?? image.getAttributeNS("http://www.w3.org/1999/xlink", "href");
138
+ if (!href)
139
+ return;
140
+ if (!href.startsWith("data:image/"))
141
+ throw new Error("External image");
142
+ const probe = new Image();
143
+ probe.src = href;
144
+ await probe.decode();
145
+ }));
146
+ });
147
+ if (blockedResource)
148
+ throw httpError(422, "DRAWIO_EXPORT_FAILED");
149
+ signal.throwIfAborted();
150
+ const bytes = Buffer.from(await page.pdf({ width: `${size.width}px`, height: `${size.height}px`,
151
+ margin: { top: 0, right: 0, bottom: 0, left: 0 }, printBackground: true, displayHeaderFooter: false,
152
+ waitForFonts: true, timeout: 10_000 }));
153
+ if (bytes.length > 20 * 1024 * 1024 || !bytes.subarray(0, 5).equals(Buffer.from("%PDF-")))
154
+ throw httpError(422, "DRAWIO_EXPORT_FAILED");
155
+ return bytes;
156
+ }
157
+ catch (error) {
158
+ this.detectedBrowser = undefined; // Retry detection after installation/removal or a failed launch.
159
+ if (error instanceof AggregateError || (!signal.aborted && !(error instanceof HttpError)))
160
+ this.reportError?.(error);
161
+ if (signal.aborted)
162
+ throw new DOMException("Aborted", "AbortError");
163
+ if (error instanceof HttpError)
164
+ throw error;
165
+ throw httpError(422, "DRAWIO_EXPORT_FAILED");
166
+ }
167
+ finally {
168
+ if (close) {
169
+ try {
170
+ await close();
171
+ }
172
+ catch (error) {
173
+ this.reportError?.(error);
174
+ if (!signal.aborted)
175
+ throw httpError(422, "DRAWIO_EXPORT_FAILED");
176
+ }
177
+ }
178
+ if (signal.aborted)
179
+ throw new DOMException("Aborted", "AbortError");
180
+ }
181
+ }
182
+ }