@hydranium/cli 1.0.0-next.37 → 1.0.0-next.370

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 (339) hide show
  1. package/README.md +102 -204
  2. package/bin/hydranium-cli.js +13 -0
  3. package/heap-analysis/heap/core/load.mjs +2 -2
  4. package/heap-analysis/heap/langium/langium.classifier.mjs +22 -11
  5. package/lib/cli-version.js.map +1 -1
  6. package/lib/cli.js +7 -2
  7. package/lib/cli.js.map +1 -1
  8. package/lib/commands/analyze-heap-args.d.ts.map +1 -1
  9. package/lib/commands/analyze-heap-args.js +1 -2
  10. package/lib/commands/analyze-heap-args.js.map +1 -1
  11. package/lib/commands/analyze-heap.d.ts +3 -0
  12. package/lib/commands/analyze-heap.d.ts.map +1 -1
  13. package/lib/commands/analyze-heap.js +2 -1
  14. package/lib/commands/analyze-heap.js.map +1 -1
  15. package/lib/commands/ast-ground-truth-args.d.ts +3 -2
  16. package/lib/commands/ast-ground-truth-args.d.ts.map +1 -1
  17. package/lib/commands/ast-ground-truth-args.js +11 -9
  18. package/lib/commands/ast-ground-truth-args.js.map +1 -1
  19. package/lib/commands/ast-ground-truth-driver.js +4 -2
  20. package/lib/commands/ast-ground-truth-driver.js.map +1 -1
  21. package/lib/commands/ast-ground-truth.js +1 -1
  22. package/lib/commands/ast-ground-truth.js.map +1 -1
  23. package/lib/commands/client-session.d.ts +17 -0
  24. package/lib/commands/client-session.d.ts.map +1 -0
  25. package/lib/commands/client-session.js +27 -0
  26. package/lib/commands/client-session.js.map +1 -0
  27. package/lib/commands/create-args.d.ts +17 -0
  28. package/lib/commands/create-args.d.ts.map +1 -0
  29. package/lib/commands/create-args.js +53 -0
  30. package/lib/commands/create-args.js.map +1 -0
  31. package/lib/commands/create.d.ts +38 -0
  32. package/lib/commands/create.d.ts.map +1 -0
  33. package/lib/commands/create.js +43 -0
  34. package/lib/commands/create.js.map +1 -0
  35. package/lib/commands/delete-args.d.ts +17 -0
  36. package/lib/commands/delete-args.d.ts.map +1 -0
  37. package/lib/commands/delete-args.js +49 -0
  38. package/lib/commands/delete-args.js.map +1 -0
  39. package/lib/commands/delete.d.ts +30 -0
  40. package/lib/commands/delete.d.ts.map +1 -0
  41. package/lib/commands/delete.js +32 -0
  42. package/lib/commands/delete.js.map +1 -0
  43. package/lib/commands/generate-ast-builder.d.ts.map +1 -1
  44. package/lib/commands/generate-ast-builder.js +1 -10
  45. package/lib/commands/generate-ast-builder.js.map +1 -1
  46. package/lib/commands/generate-languages.d.ts +35 -0
  47. package/lib/commands/generate-languages.d.ts.map +1 -0
  48. package/lib/commands/generate-languages.js +105 -0
  49. package/lib/commands/generate-languages.js.map +1 -0
  50. package/lib/commands/generate-transfer-builder.d.ts +33 -0
  51. package/lib/commands/generate-transfer-builder.d.ts.map +1 -0
  52. package/lib/commands/generate-transfer-builder.js +86 -0
  53. package/lib/commands/generate-transfer-builder.js.map +1 -0
  54. package/lib/commands/generate-transfer-model-args.d.ts.map +1 -1
  55. package/lib/commands/generate-transfer-model-args.js +20 -5
  56. package/lib/commands/generate-transfer-model-args.js.map +1 -1
  57. package/lib/commands/generate-transfer-model-config.d.ts.map +1 -1
  58. package/lib/commands/generate-transfer-model-config.js +8 -3
  59. package/lib/commands/generate-transfer-model-config.js.map +1 -1
  60. package/lib/commands/generate-transfer-model.d.ts +40 -9
  61. package/lib/commands/generate-transfer-model.d.ts.map +1 -1
  62. package/lib/commands/generate-transfer-model.js +219 -67
  63. package/lib/commands/generate-transfer-model.js.map +1 -1
  64. package/lib/commands/generated-module-path.d.ts +16 -0
  65. package/lib/commands/generated-module-path.d.ts.map +1 -0
  66. package/lib/commands/generated-module-path.js +21 -0
  67. package/lib/commands/generated-module-path.js.map +1 -0
  68. package/lib/commands/harness-args.d.ts +44 -42
  69. package/lib/commands/harness-args.d.ts.map +1 -1
  70. package/lib/commands/harness-args.js +109 -27
  71. package/lib/commands/harness-args.js.map +1 -1
  72. package/lib/commands/headless-harness.d.ts +37 -20
  73. package/lib/commands/headless-harness.d.ts.map +1 -1
  74. package/lib/commands/headless-harness.js +71 -19
  75. package/lib/commands/headless-harness.js.map +1 -1
  76. package/lib/commands/init-args.d.ts +2 -0
  77. package/lib/commands/init-args.d.ts.map +1 -1
  78. package/lib/commands/init-args.js +74 -31
  79. package/lib/commands/init-args.js.map +1 -1
  80. package/lib/commands/init-hosts.d.ts +24 -0
  81. package/lib/commands/init-hosts.d.ts.map +1 -0
  82. package/lib/commands/init-hosts.js +37 -0
  83. package/lib/commands/init-hosts.js.map +1 -0
  84. package/lib/commands/init-prompt.d.ts +3 -3
  85. package/lib/commands/init-prompt.d.ts.map +1 -1
  86. package/lib/commands/init-prompt.js +4 -5
  87. package/lib/commands/init-prompt.js.map +1 -1
  88. package/lib/commands/init-templates.d.ts +26 -14
  89. package/lib/commands/init-templates.d.ts.map +1 -1
  90. package/lib/commands/init-templates.js +2989 -743
  91. package/lib/commands/init-templates.js.map +1 -1
  92. package/lib/commands/init-wizard.d.ts +3 -0
  93. package/lib/commands/init-wizard.d.ts.map +1 -1
  94. package/lib/commands/init-wizard.js +46 -31
  95. package/lib/commands/init-wizard.js.map +1 -1
  96. package/lib/commands/init-workspace.d.ts +13 -11
  97. package/lib/commands/init-workspace.d.ts.map +1 -1
  98. package/lib/commands/init-workspace.js +21 -7
  99. package/lib/commands/init-workspace.js.map +1 -1
  100. package/lib/commands/init.d.ts +58 -22
  101. package/lib/commands/init.d.ts.map +1 -1
  102. package/lib/commands/init.js +206 -48
  103. package/lib/commands/init.js.map +1 -1
  104. package/lib/commands/kebab.d.ts +15 -0
  105. package/lib/commands/kebab.d.ts.map +1 -0
  106. package/lib/commands/kebab.js +17 -0
  107. package/lib/commands/kebab.js.map +1 -0
  108. package/lib/commands/lint-grammar-args.d.ts +3 -2
  109. package/lib/commands/lint-grammar-args.d.ts.map +1 -1
  110. package/lib/commands/lint-grammar-args.js +13 -10
  111. package/lib/commands/lint-grammar-args.js.map +1 -1
  112. package/lib/commands/lint-grammar-driver.js +2 -1
  113. package/lib/commands/lint-grammar-driver.js.map +1 -1
  114. package/lib/commands/lint-grammar-report.js.map +1 -1
  115. package/lib/commands/lint-grammar.js +1 -1
  116. package/lib/commands/lint-grammar.js.map +1 -1
  117. package/lib/commands/measure-memory-args.d.ts +3 -2
  118. package/lib/commands/measure-memory-args.d.ts.map +1 -1
  119. package/lib/commands/measure-memory-args.js +22 -11
  120. package/lib/commands/measure-memory-args.js.map +1 -1
  121. package/lib/commands/measure-memory-driver.js +5 -3
  122. package/lib/commands/measure-memory-driver.js.map +1 -1
  123. package/lib/commands/measure-memory.js +1 -1
  124. package/lib/commands/measure-memory.js.map +1 -1
  125. package/lib/commands/model-docs-args.d.ts +4 -3
  126. package/lib/commands/model-docs-args.d.ts.map +1 -1
  127. package/lib/commands/model-docs-args.js +12 -10
  128. package/lib/commands/model-docs-args.js.map +1 -1
  129. package/lib/commands/model-docs-driver.js +2 -1
  130. package/lib/commands/model-docs-driver.js.map +1 -1
  131. package/lib/commands/model-docs.js +1 -1
  132. package/lib/commands/model-docs.js.map +1 -1
  133. package/lib/commands/projects-args.d.ts.map +1 -1
  134. package/lib/commands/projects-args.js +5 -5
  135. package/lib/commands/projects-args.js.map +1 -1
  136. package/lib/commands/projects.d.ts +3 -4
  137. package/lib/commands/projects.d.ts.map +1 -1
  138. package/lib/commands/projects.js +2 -2
  139. package/lib/commands/projects.js.map +1 -1
  140. package/lib/commands/query-args.d.ts.map +1 -1
  141. package/lib/commands/query-args.js +6 -5
  142. package/lib/commands/query-args.js.map +1 -1
  143. package/lib/commands/query.d.ts +6 -5
  144. package/lib/commands/query.d.ts.map +1 -1
  145. package/lib/commands/query.js +5 -4
  146. package/lib/commands/query.js.map +1 -1
  147. package/lib/commands/reflect-args.d.ts +3 -2
  148. package/lib/commands/reflect-args.d.ts.map +1 -1
  149. package/lib/commands/reflect-args.js +13 -10
  150. package/lib/commands/reflect-args.js.map +1 -1
  151. package/lib/commands/reflect-driver.js +2 -1
  152. package/lib/commands/reflect-driver.js.map +1 -1
  153. package/lib/commands/reflect-report.js.map +1 -1
  154. package/lib/commands/reflect.js +1 -1
  155. package/lib/commands/reflect.js.map +1 -1
  156. package/lib/commands/save-args.d.ts.map +1 -1
  157. package/lib/commands/save-args.js +7 -4
  158. package/lib/commands/save-args.js.map +1 -1
  159. package/lib/commands/save.d.ts +8 -4
  160. package/lib/commands/save.d.ts.map +1 -1
  161. package/lib/commands/save.js +12 -23
  162. package/lib/commands/save.js.map +1 -1
  163. package/lib/commands/validate-args.d.ts +3 -2
  164. package/lib/commands/validate-args.d.ts.map +1 -1
  165. package/lib/commands/validate-args.js +13 -10
  166. package/lib/commands/validate-args.js.map +1 -1
  167. package/lib/commands/validate-driver.js +2 -1
  168. package/lib/commands/validate-driver.js.map +1 -1
  169. package/lib/commands/validate-report.js.map +1 -1
  170. package/lib/commands/validate.js +1 -1
  171. package/lib/commands/validate.js.map +1 -1
  172. package/lib/commands/watch-args.d.ts.map +1 -1
  173. package/lib/commands/watch-args.js +6 -4
  174. package/lib/commands/watch-args.js.map +1 -1
  175. package/lib/commands/watch.d.ts +3 -4
  176. package/lib/commands/watch.d.ts.map +1 -1
  177. package/lib/commands/watch.js +20 -2
  178. package/lib/commands/watch.js.map +1 -1
  179. package/lib/driver-heap.d.ts +52 -0
  180. package/lib/driver-heap.d.ts.map +1 -0
  181. package/lib/driver-heap.js +51 -0
  182. package/lib/driver-heap.js.map +1 -0
  183. package/lib/index.d.ts +2 -0
  184. package/lib/index.d.ts.map +1 -1
  185. package/lib/index.js +2 -0
  186. package/lib/index.js.map +1 -1
  187. package/lib/log-level.d.ts +21 -11
  188. package/lib/log-level.d.ts.map +1 -1
  189. package/lib/log-level.js +25 -14
  190. package/lib/log-level.js.map +1 -1
  191. package/lib/spawn-data-server.d.ts +9 -4
  192. package/lib/spawn-data-server.d.ts.map +1 -1
  193. package/lib/spawn-data-server.js +5 -4
  194. package/lib/spawn-data-server.js.map +1 -1
  195. package/lib/stderr-connection-logger.d.ts +12 -0
  196. package/lib/stderr-connection-logger.d.ts.map +1 -0
  197. package/lib/stderr-connection-logger.js +16 -0
  198. package/lib/stderr-connection-logger.js.map +1 -0
  199. package/lib/testing/echo-server.js +9 -1
  200. package/lib/testing/echo-server.js.map +1 -1
  201. package/package.json +91 -39
  202. package/src/cli.ts +7 -2
  203. package/src/commands/analyze-heap-args.ts +1 -2
  204. package/src/commands/analyze-heap.ts +4 -1
  205. package/src/commands/ast-ground-truth-args.ts +15 -12
  206. package/src/commands/ast-ground-truth-driver.ts +4 -2
  207. package/src/commands/ast-ground-truth.ts +1 -1
  208. package/src/commands/client-session.ts +33 -0
  209. package/src/commands/create-args.ts +68 -0
  210. package/src/commands/create.ts +83 -0
  211. package/src/commands/delete-args.ts +64 -0
  212. package/src/commands/delete.ts +61 -0
  213. package/src/commands/generate-ast-builder.ts +1 -11
  214. package/src/commands/generate-languages.ts +132 -0
  215. package/src/commands/generate-transfer-builder.ts +101 -0
  216. package/src/commands/generate-transfer-model-args.ts +20 -5
  217. package/src/commands/generate-transfer-model-config.ts +8 -3
  218. package/src/commands/generate-transfer-model.ts +291 -65
  219. package/src/commands/generated-module-path.ts +22 -0
  220. package/src/commands/harness-args.ts +99 -31
  221. package/src/commands/headless-harness.ts +89 -28
  222. package/src/commands/init-args.ts +76 -31
  223. package/src/commands/init-hosts.ts +51 -0
  224. package/src/commands/init-prompt.ts +5 -6
  225. package/src/commands/init-templates.ts +3161 -756
  226. package/src/commands/init-wizard.ts +55 -31
  227. package/src/commands/init-workspace.ts +31 -16
  228. package/src/commands/init.ts +266 -63
  229. package/src/commands/kebab.ts +17 -0
  230. package/src/commands/lint-grammar-args.ts +17 -13
  231. package/src/commands/lint-grammar-driver.ts +2 -1
  232. package/src/commands/lint-grammar.ts +1 -1
  233. package/src/commands/measure-memory-args.ts +27 -14
  234. package/src/commands/measure-memory-driver.ts +5 -3
  235. package/src/commands/measure-memory.ts +1 -1
  236. package/src/commands/model-docs-args.ts +16 -13
  237. package/src/commands/model-docs-driver.ts +2 -1
  238. package/src/commands/model-docs.ts +1 -1
  239. package/src/commands/projects-args.ts +5 -4
  240. package/src/commands/projects.ts +4 -6
  241. package/src/commands/query-args.ts +6 -4
  242. package/src/commands/query.ts +9 -9
  243. package/src/commands/reflect-args.ts +17 -13
  244. package/src/commands/reflect-driver.ts +2 -1
  245. package/src/commands/reflect.ts +1 -1
  246. package/src/commands/save-args.ts +7 -3
  247. package/src/commands/save.ts +24 -27
  248. package/src/commands/validate-args.ts +17 -13
  249. package/src/commands/validate-driver.ts +2 -1
  250. package/src/commands/validate.ts +1 -1
  251. package/src/commands/watch-args.ts +6 -3
  252. package/src/commands/watch.ts +28 -7
  253. package/src/driver-heap.ts +65 -0
  254. package/src/index.ts +2 -0
  255. package/src/log-level.ts +42 -14
  256. package/src/spawn-data-server.ts +17 -5
  257. package/src/stderr-connection-logger.ts +18 -0
  258. package/src/testing/echo-server.ts +11 -2
  259. package/templates/client/gitignore +3 -0
  260. package/templates/client/src/__GRAMMAR_ID__-diagram-module.ts +82 -0
  261. package/templates/editorconfig +15 -0
  262. package/templates/gitignore +1 -0
  263. package/templates/host-browser/esbuild.mjs +82 -0
  264. package/templates/host-browser/gitignore +4 -0
  265. package/templates/host-browser/hydranium-mark.svg +40 -0
  266. package/templates/host-browser/index.html +287 -0
  267. package/templates/host-browser/playwright.config.mts +24 -0
  268. package/templates/host-browser/src/data-status.ts +15 -0
  269. package/templates/host-browser/src/diagram-save.ts +60 -0
  270. package/templates/host-browser/src/diagram.ts +118 -0
  271. package/templates/host-browser/src/editor.ts +102 -0
  272. package/templates/host-browser/src/log.ts +14 -0
  273. package/templates/host-browser/src/monaco-editor-core-worker.d.ts +7 -0
  274. package/templates/host-browser/src/monaco-editor-worker.ts +10 -0
  275. package/templates/host-browser/src/posix-path-shim.ts +23 -0
  276. package/templates/host-browser/src/shown-file.ts +61 -0
  277. package/templates/host-browser/src/workspace.ts +5 -0
  278. package/templates/host-browser/tsconfig.e2e.json +16 -0
  279. package/templates/host-browser/tsconfig.page.json +16 -0
  280. package/templates/host-browser/tsconfig.worker.json +16 -0
  281. package/templates/host-theia-browser/esbuild.mjs +24 -0
  282. package/templates/host-theia-browser/gitignore +9 -0
  283. package/templates/host-theia-browser/playwright.config.mts +42 -0
  284. package/templates/host-theia-browser/start.mjs +50 -0
  285. package/templates/host-theia-browser/tsconfig.e2e.json +16 -0
  286. package/templates/host-theia-electron/esbuild.mjs +27 -0
  287. package/templates/host-theia-electron/gitignore +8 -0
  288. package/templates/host-theia-electron/playwright.config.mts +12 -0
  289. package/templates/host-theia-electron/start.mjs +47 -0
  290. package/templates/host-theia-electron/tsconfig.e2e.json +16 -0
  291. package/templates/host-vscode/esbuild.mjs +38 -0
  292. package/templates/host-vscode/gitignore +7 -0
  293. package/templates/host-vscode/playwright.config.mts +14 -0
  294. package/templates/host-vscode/src/__GRAMMAR_ID__-diagram-editor.ts +19 -0
  295. package/templates/host-vscode/src/show-model-command.ts +24 -0
  296. package/templates/host-vscode/src/webview/__GRAMMAR_ID__-diagram.ts +18 -0
  297. package/templates/host-vscode/src/webview/diagram.css +40 -0
  298. package/templates/host-vscode/start.mjs +22 -0
  299. package/templates/host-vscode/test/install-vscode.mts +21 -0
  300. package/templates/host-vscode/test/vscode-version.mts +10 -0
  301. package/templates/host-vscode/tsconfig.e2e.json +17 -0
  302. package/templates/host-vscode/tsconfig.json +19 -0
  303. package/templates/host-vscode/tsconfig.webview.json +17 -0
  304. package/templates/oxlintrc.json +4 -0
  305. package/templates/protocol/gitignore +3 -0
  306. package/templates/protocol/src/__GRAMMAR_ID__-diagram-types.ts +47 -0
  307. package/templates/server/gitignore +6 -0
  308. package/templates/server/src/glsp/__GRAMMAR_ID__/create-node-operation-handler.ts +62 -0
  309. package/templates/server/src/glsp/__GRAMMAR_ID__/delete-operation-handler.ts +63 -0
  310. package/templates/server/src/glsp/__GRAMMAR_ID__/gmodel-factory.ts +144 -0
  311. package/templates/server/src/glsp/__GRAMMAR_ID__/state.ts +18 -0
  312. package/templates/server/src/glsp/__GRAMMAR_ID__/storage.ts +16 -0
  313. package/templates/server/src/glsp/__GRAMMAR_ID__/submission-handler.ts +24 -0
  314. package/templates/server/src/grammar/common.langium +12 -0
  315. package/templates/server/src/language-server/__GRAMMAR_ID__-serializer.ts +53 -0
  316. package/templates/server/src/language-server/__GRAMMAR_ID__-validation.ts +30 -0
  317. package/templates/server/src/language-server/ast.ts +23 -0
  318. package/templates/server/src/node/services.ts +16 -0
  319. package/templates/server/test/__GRAMMAR_ID__-diagram.test.ts +388 -0
  320. package/templates/server/test/tsconfig.json +4 -0
  321. package/templates/server/tsconfig.test.json +10 -0
  322. package/templates/server/vitest.config.ts +14 -0
  323. package/templates/theia/gitignore +3 -0
  324. package/templates/theia/src/browser/__GRAMMAR_ID__-diagram-frontend-module.ts +65 -0
  325. package/templates/theia/src/browser/__PROJECT_ID__-connection-preload-module.ts +15 -0
  326. package/templates/theia/src/browser/__PROJECT_ID__-data-connection.ts +15 -0
  327. package/templates/theia/src/browser/__PROJECT_ID__-data-port.ts +11 -0
  328. package/templates/theia/src/browser/__PROJECT_ID__-glsp-client-contribution.ts +13 -0
  329. package/templates/theia/src/browser/__PROJECT_ID__-show-model-command.ts +51 -0
  330. package/templates/theia/src/common/__PROJECT_ID__-glsp-contribution.ts +3 -0
  331. package/templates/theia/src/node/__PROJECT_ID__-connection-backend-module.ts +12 -0
  332. package/templates/theia/src/node/__PROJECT_ID__-data-backend-module.ts +15 -0
  333. package/templates/theia/src/node/__PROJECT_ID__-glsp-backend-module.ts +16 -0
  334. package/templates/theia/style/diagram.css +20 -0
  335. package/templates/theia/tsconfig.json +24 -0
  336. package/templates/vscode-servers/gitignore +4 -0
  337. package/templates/vscode-servers/tsconfig.json +19 -0
  338. package/templates/workspace/nodes.__EXTENSION__ +5 -0
  339. package/templates/workspace/references.__EXTENSION__ +2 -0
@@ -21,6 +21,12 @@
21
21
  * `bin` key, the DI module filename, and the data-server port command.
22
22
  * - `__CONFIG_ROOT_CONST__` — SCREAMING_SNAKE project id, naming the
23
23
  * `lsp.configurationRoot` constant a multi-grammar project binds.
24
+ * - `__PROTOCOL_PACKAGE__` — the protocol member's package name, scope
25
+ * included, which the server and every client import ids and wire types
26
+ * from.
27
+ * - `__SERVER_PACKAGE__` / `__CLIENT_PACKAGE__` — the server and client
28
+ * members' package names, which a host imports the language and the diagram
29
+ * definition from.
24
30
  *
25
31
  * GRAMMAR tokens, substituted once per grammar:
26
32
  *
@@ -28,6 +34,10 @@
28
34
  * Drives the PER-LANGUAGE generated symbols (`<grammar>GeneratedModule`,
29
35
  * `<grammar>LanguageMetaData`).
30
36
  * - `__GRAMMAR_ID__` — kebab grammar id: the `.langium` filename.
37
+ * - `__GRAMMAR_ID_CONST__` — SCREAMING_SNAKE grammar id, prefixing the
38
+ * diagram's type-id constants.
39
+ * - `__GRAMMAR_CAMEL__` — lowerCamelCase grammar name, naming the client's
40
+ * diagram module constant.
31
41
  * - `__LANGUAGE_ID__` — kebab routing key: the `langium-config` entry id and
32
42
  * its TextMate output.
33
43
  * - `__EXTENSION__` — the grammar's FIRST file extension, without the dot.
@@ -48,10 +58,22 @@
48
58
  * generator emits `interface <projectName>Element` as the base type every rule
49
59
  * extends, which a rule of that name would collide with.
50
60
  *
51
- * Kept as in-source strings (not on-disk assets) so no build-time copy step
52
- * is needed and the substitution is unit-testable. The `.ts` / `.langium` / JSON
53
- * templates are derived from the in-repo reference example so the generated project
54
- * compiles against the real `@hydranium/*` API once `langium generate` has run.
61
+ * The project is its packages and a starter workspace, each in its own
62
+ * directory: `server/` (the grammar, the language and its heads), `protocol/`
63
+ * (what the server and its clients both import, so a client never installs
64
+ * Langium), `client/` with a diagram (its host-neutral client side),
65
+ * `host-<name>/` per host, `vscode-servers/` with the VS Code host (the server
66
+ * launch it shares with a Theia app), and `workspace/` (starter model files
67
+ * every host and the CLI open). A standalone project adds a root manifest
68
+ * naming them as npm workspaces; a workspace member joins the surrounding root
69
+ * instead.
70
+ *
71
+ * A file that is fixed text with tokens lives in the `templates/` tree the
72
+ * package ships beside `lib`, at the path it is emitted at, tokens included
73
+ * (each ignore file without its dot); one computed from the composition is
74
+ * built here. The tree is read synchronously, so `runInit` stays synchronous,
75
+ * and it is neither formatted with the repo's settings nor given a license
76
+ * header, since either would change what `init` emits.
55
77
  *
56
78
  * Two conventions the templates follow deliberately:
57
79
  *
@@ -70,16 +92,10 @@
70
92
  * is what the detection cannot fix. A very long `--name` can still push a line
71
93
  * over; the adopter's own formatter settles it.
72
94
  */
95
+ import { readFileSync } from 'node:fs';
73
96
  import { readCliVersion } from '../cli-version.js';
74
- /**
75
- * The version every framework package carries before the first release.
76
- *
77
- * A scaffold made by a CLI still at this version pins a range the registry
78
- * cannot serve, so the emitted README keeps its yalc note and `init` keeps its
79
- * install warning while — and only while — it holds: from a published CLI the
80
- * derived pins resolve and either note would be false as printed.
81
- */
82
- export const UNPUBLISHED_FRAMEWORK_VERSION = '0.0.0';
97
+ import { initMembers } from './init.js';
98
+ import { isTheiaHost } from './init-hosts.js';
83
99
  /**
84
100
  * The version `init` pins every `@hydranium/*` dependency at: the scaffolding
85
101
  * CLI's own.
@@ -107,12 +123,52 @@ function frameworkPin(composition) {
107
123
  function screamingSnake(projectId) {
108
124
  return projectId.replace(/-/g, '_').toUpperCase();
109
125
  }
126
+ const VSCODE_EXTENSION_MEMBERS = ['vscode-servers', 'host-vscode'];
127
+ /**
128
+ * A member's package name: `<id>-<member>`, under the scope when there is one,
129
+ * except for the VS Code extensions, whose scoped name `vsce` refuses to
130
+ * package.
131
+ *
132
+ * Suffixed even for the server, because a project of several packages has no
133
+ * member entitled to the bare id, and a later client or host would otherwise
134
+ * read as a part of the server.
135
+ */
136
+ export function memberPackageName(composition, member) {
137
+ const { scope } = composition.packaging;
138
+ const name = `${composition.projectId}-${member}`;
139
+ return scope === undefined || VSCODE_EXTENSION_MEMBERS.includes(member) ? name : `${scope}/${name}`;
140
+ }
141
+ /**
142
+ * The composition as one member sees it: inside a workspace, its placement
143
+ * sits one directory below the project's, so its `extends` and its lint
144
+ * config path reach one level further up.
145
+ */
146
+ function forMember(composition, member) {
147
+ const workspace = composition.packaging.workspace;
148
+ if (workspace === undefined) {
149
+ return composition;
150
+ }
151
+ return {
152
+ ...composition,
153
+ packaging: {
154
+ ...composition.packaging,
155
+ workspace: {
156
+ ...workspace,
157
+ targetPath: `${workspace.targetPath}/${member}`,
158
+ baseTsconfig: workspace.baseTsconfig === undefined ? undefined : `../${workspace.baseTsconfig}`
159
+ }
160
+ }
161
+ };
162
+ }
110
163
  /** Substitute the project-tier tokens. */
111
164
  function project(text, composition) {
112
165
  return text
113
166
  .replace(/__NAME__/g, composition.name)
114
167
  .replace(/__PROJECT_ID__/g, composition.projectId)
115
- .replace(/__CONFIG_ROOT_CONST__/g, screamingSnake(composition.projectId));
168
+ .replace(/__CONFIG_ROOT_CONST__/g, screamingSnake(composition.projectId))
169
+ .replace(/__PROTOCOL_PACKAGE__/g, memberPackageName(composition, 'protocol'))
170
+ .replace(/__SERVER_PACKAGE__/g, memberPackageName(composition, 'server'))
171
+ .replace(/__CLIENT_PACKAGE__/g, memberPackageName(composition, 'client'));
116
172
  }
117
173
  /**
118
174
  * Substitute the grammar-tier tokens for ONE grammar.
@@ -124,7 +180,9 @@ function project(text, composition) {
124
180
  */
125
181
  function grammarTier(text, grammar) {
126
182
  return text
183
+ .replace(/__GRAMMAR_ID_CONST__/g, screamingSnake(grammar.grammarId))
127
184
  .replace(/__GRAMMAR_ID__/g, grammar.grammarId)
185
+ .replace(/__GRAMMAR_CAMEL__/g, grammar.grammar.charAt(0).toLowerCase() + grammar.grammar.slice(1))
128
186
  .replace(/__GRAMMAR__/g, grammar.grammar)
129
187
  .replace(/__LANGUAGE_ID__/g, grammar.languageId)
130
188
  .replace(/__EXTENSION__/g, grammar.extensions[0])
@@ -135,6 +193,25 @@ function grammarTier(text, grammar) {
135
193
  function render(text, composition, grammar) {
136
194
  return grammarTier(project(text, composition), grammar);
137
195
  }
196
+ /** The template tree, the same two levels up from `src/commands` and `lib/commands`. */
197
+ const TEMPLATES = new URL('../../templates/', import.meta.url);
198
+ /** One template file's text. */
199
+ function template(path) {
200
+ return readFileSync(new URL(path, TEMPLATES), 'utf-8');
201
+ }
202
+ /** A template emitted once per project at its own path, rendered with the project tokens. */
203
+ function projectTemplate(path, composition) {
204
+ return { path, content: project(template(path), composition) };
205
+ }
206
+ /** A template emitted once per grammar, its path rendered like its content. */
207
+ function grammarTemplate(path, composition, grammar) {
208
+ return { path: render(path, composition, grammar), content: render(template(path), composition, grammar) };
209
+ }
210
+ /** An ignore file, stored without its dot because `npm pack` drops a nested `.gitignore` and applies it as an ignore file. */
211
+ function ignoreFile(directory) {
212
+ const prefix = directory === '' ? '' : `${directory}/`;
213
+ return { path: `${prefix}.gitignore`, content: template(`${prefix}gitignore`) };
214
+ }
138
215
  /** A comma-separated list of single-quoted TypeScript/JS string literals. */
139
216
  function quotedList(values) {
140
217
  return values.map(value => `'${value}'`).join(', ');
@@ -142,21 +219,22 @@ function quotedList(values) {
142
219
  /**
143
220
  * The column budget the emitted sources wrap at when nothing better is known.
144
221
  *
145
- * **Not "prettier's default"** — that is 80. 120 is a choice, and stating it as
146
- * a default was wrong in a way that mattered: no single width is stable for an
222
+ * **Not "prettier's default"** — that is 80. No single width is stable for an
147
223
  * unknown repo, so emitted code only passes a formatter check relative to a
148
224
  * config. A workspace scaffold detects the surrounding repo's `printWidth` and
149
225
  * uses it (see {@link columnsFor}); a standalone one has no config to read and
150
- * falls back here.
226
+ * falls back here. It is the framework's own width, so a fixed template, which
227
+ * wraps at no budget, reads the same in a standalone scaffold as in the
228
+ * examples this repo formats.
151
229
  */
152
- const DEFAULT_COLUMNS = 120;
230
+ const DEFAULT_COLUMNS = 140;
153
231
  /** The width THIS composition wraps at: the detected workspace one, else {@link DEFAULT_COLUMNS}. */
154
232
  function columnsFor(composition) {
155
233
  return composition.packaging.workspace?.printWidth ?? DEFAULT_COLUMNS;
156
234
  }
157
235
  /**
158
236
  * A named import on one line while it fits the column budget, else one symbol
159
- * per line. Emitted files are supposed to pass a prettier check as-is, and the
237
+ * per line. Emitted files are supposed to pass a format check as-is, and the
160
238
  * generated-module import grows by one symbol per grammar.
161
239
  */
162
240
  function importList(symbols, from, columns, typeOnly = false) {
@@ -175,9 +253,13 @@ function arrayLiteral(elements, indent, columns) {
175
253
  * The FRAMEWORK packages each head adds, carrying no version: every
176
254
  * `@hydranium/*` pin is derived at scaffold time from {@link frameworkPin}, so
177
255
  * none of them can name a version its siblings were not published at.
256
+ *
257
+ * `base` is every head set's: the services every head serves from are composed
258
+ * the same with or without an LSP head.
178
259
  */
179
260
  const HEAD_FRAMEWORK_DEPENDENCIES = {
180
- lsp: ['@hydranium/core', '@hydranium/langium', '@hydranium/protocol'],
261
+ base: ['@hydranium/core', '@hydranium/langium', '@hydranium/protocol'],
262
+ lsp: [],
181
263
  data: ['@hydranium/data-server'],
182
264
  glsp: ['@hydranium/glsp-server']
183
265
  };
@@ -197,15 +279,24 @@ const HEAD_FRAMEWORK_DEPENDENCIES = {
197
279
  * `overrides` block exists to prevent — so a repo gate holds each entry here
198
280
  * against the manifest that declares it.
199
281
  *
200
- * `langium` is required by `lsp` even though hand-written code goes through the
282
+ * `langium` is required even though hand-written code goes through the
201
283
  * `@hydranium/langium` chokepoint, because `langium-cli` emits direct imports
202
- * into the generated files and regenerates them on every build.
284
+ * into the generated files and regenerates them on every build. The `vscode-*`
285
+ * packages are required peers of `@hydranium/core`, so they are `base` too.
203
286
  */
204
287
  const HEAD_THIRD_PARTY_DEPENDENCIES = {
205
- lsp: {
288
+ base: {
206
289
  langium: '4.3.1',
207
- 'vscode-languageserver': '~10.0.1'
290
+ // Exact, as are the protocol and transport it pins, so Langium and the
291
+ // framework share their copies; across copies, an error a handler throws
292
+ // or returns loses its code, and a later patch can pin another protocol.
293
+ 'vscode-languageserver': '10.0.1',
294
+ 'vscode-jsonrpc': '9.0.0',
295
+ 'vscode-languageserver-protocol': '3.18.1',
296
+ // The copy that protocol pins; a root without it takes the one Theia pins.
297
+ 'vscode-languageserver-types': '3.18.0'
208
298
  },
299
+ lsp: {},
209
300
  data: {},
210
301
  glsp: {
211
302
  '@eclipse-glsp/graph': '2.7.0',
@@ -216,25 +307,171 @@ const HEAD_THIRD_PARTY_DEPENDENCIES = {
216
307
  'reflect-metadata': '~0.2.2'
217
308
  }
218
309
  };
219
- /** The dependency block for a head set, merged and sorted as npm writes it. */
310
+ /**
311
+ * What each head adds to the protocol member, which carries only what a
312
+ * client may install. Keyed by head because the `glsp` head implies a diagram,
313
+ * whose element ids extend GLSP's default type names.
314
+ */
315
+ const PROTOCOL_THIRD_PARTY_DEPENDENCIES = {
316
+ lsp: {},
317
+ data: {},
318
+ glsp: { '@eclipse-glsp/protocol': '2.7.0' }
319
+ };
320
+ /** The client member's packages: the diagram definition and what it registers its elements with. */
321
+ const CLIENT_FRAMEWORK_DEPENDENCIES = ['@hydranium/glsp-client'];
322
+ const CLIENT_THIRD_PARTY_DEPENDENCIES = {
323
+ '@eclipse-glsp/client': '2.7.0',
324
+ // GLSP's client imports this package's stylesheet without declaring it, so
325
+ // a page bundling the diagram does not build without it.
326
+ '@vscode/codicons': '0.0.45',
327
+ inversify: '^6.1.3'
328
+ };
329
+ /**
330
+ * What each head adds to the browser host, which bundles the server into its
331
+ * worker and the head's client into its page. `base` is what every page needs.
332
+ *
333
+ * `monaco-editor-core` is exact for the reason `langium` is: Monaco's models
334
+ * live in one copy, and `@hydranium/client-browser` must reach the page's.
335
+ */
336
+ const HOST_BROWSER_FRAMEWORK_DEPENDENCIES = {
337
+ base: ['@hydranium/client-browser', '@hydranium/core', '@hydranium/protocol'],
338
+ lsp: [],
339
+ data: ['@hydranium/data-server'],
340
+ glsp: ['@hydranium/glsp-client', '@hydranium/glsp-server']
341
+ };
342
+ const HOST_BROWSER_THIRD_PARTY_DEPENDENCIES = {
343
+ base: { 'vscode-jsonrpc': '9.0.0', 'vscode-languageserver-protocol': '3.18.1' },
344
+ lsp: { 'monaco-editor-core': '0.56.0' },
345
+ data: {},
346
+ glsp: { '@eclipse-glsp/server': '2.7.0', 'reflect-metadata': '~0.2.2' }
347
+ };
348
+ /** The browser host's tools: the bundler, the smoke tier and the type check. */
349
+ const HOST_BROWSER_DEV_DEPENDENCIES = {
350
+ '@playwright/test': '^1.55.0',
351
+ '@types/node': '^22.0.0',
352
+ esbuild: '^0.28.0',
353
+ rimraf: '^5.0.0',
354
+ typescript: '^7.0.2'
355
+ };
356
+ /** The language client both VS Code extensions start the server with. */
357
+ const VSCODE_LANGUAGE_CLIENT = { 'vscode-languageclient': '^9.0.1' };
358
+ /** The VS Code API's types, at the oldest VS Code both extensions run in, which `engines` names too. */
359
+ const VSCODE_ENGINE = '^1.101.0';
360
+ /**
361
+ * What the GLSP head adds to the VS Code extension: the connector in the
362
+ * extension host and the diagram webview's starter, which bundles the client
363
+ * member.
364
+ */
365
+ const HOST_VSCODE_GLSP_FRAMEWORK_DEPENDENCIES = [
366
+ '@hydranium/client-vscode',
367
+ '@hydranium/glsp-client',
368
+ '@hydranium/glsp-client-vscode',
369
+ '@hydranium/protocol'
370
+ ];
371
+ const HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES = {
372
+ '@eclipse-glsp/client': '2.7.0',
373
+ '@eclipse-glsp/vscode-integration': '2.7.0',
374
+ '@eclipse-glsp/vscode-integration-webview': '2.7.0',
375
+ inversify: '^6.1.3',
376
+ 'vscode-jsonrpc': '9.0.0'
377
+ };
378
+ /** What the data head adds to the VS Code extension: the Show Model command's socket to it. */
379
+ const HOST_VSCODE_DATA_FRAMEWORK_DEPENDENCIES = [
380
+ '@hydranium/client-vscode',
381
+ '@hydranium/data-client-vscode',
382
+ '@hydranium/protocol'
383
+ ];
384
+ // Exact, as the server's is: the socket's connection and the framework's must be one copy.
385
+ const HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES = { 'vscode-jsonrpc': '9.0.0' };
386
+ /** The VS Code extension's tools: the smoke tier, the download it runs in, the type check and the watch. */
387
+ const HOST_VSCODE_DEV_DEPENDENCIES = {
388
+ '@playwright/test': '^1.55.0',
389
+ '@types/node': '^22.0.0',
390
+ '@types/vscode': VSCODE_ENGINE,
391
+ '@vscode/test-electron': '^3.1.0',
392
+ concurrently: '^9.0.0',
393
+ rimraf: '^5.0.0',
394
+ typescript: '^7.0.2'
395
+ };
396
+ /**
397
+ * The Node major a standalone scaffold's `.nvmrc` and printed steps name.
398
+ * `langium generate` from the pinned `langium-cli` fails on Node 24.20 and
399
+ * later, which `engines` still admits.
400
+ */
401
+ export const SCAFFOLD_NODE_MAJOR = '22';
402
+ /**
403
+ * The exact pins of every member the composition emits, for a workspace root
404
+ * to declare too. npm installs a root's own dependencies at the top of the
405
+ * tree, so another member's version of one nests beneath that member instead of
406
+ * taking the place of the copy this package shares with the framework.
407
+ */
408
+ export function workspaceRootPins(composition) {
409
+ const { heads } = composition;
410
+ const members = initMembers(heads, composition.hosts);
411
+ const pins = new Map([
412
+ ...Object.entries(HEAD_THIRD_PARTY_DEPENDENCIES.base),
413
+ ...heads.flatMap(head => [
414
+ ...Object.entries(HEAD_THIRD_PARTY_DEPENDENCIES[head]),
415
+ ...Object.entries(PROTOCOL_THIRD_PARTY_DEPENDENCIES[head])
416
+ ]),
417
+ ...(members.includes('client') ? Object.entries(CLIENT_THIRD_PARTY_DEPENDENCIES) : []),
418
+ ...(members.includes('host-browser')
419
+ ? ['base', ...heads].flatMap(head => Object.entries(HOST_BROWSER_THIRD_PARTY_DEPENDENCIES[head]))
420
+ : []),
421
+ ...(members.includes('host-vscode') && heads.includes('glsp') ? Object.entries(HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES) : []),
422
+ ...(members.includes('host-vscode') && heads.includes('data') ? Object.entries(HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES) : []),
423
+ ...(members.includes('theia') ? theiaThirdPartyDependencies(heads) : []),
424
+ ...(members.includes('host-theia-browser') ? hostTheiaBrowserTheiaDependencies() : []),
425
+ ...(members.includes('host-theia-electron') ? hostTheiaElectronPins() : [])
426
+ ]);
427
+ return [...pins].filter(([, version]) => /^\d+\.\d+\.\d+$/.test(version)).sort(([left], [right]) => left.localeCompare(right));
428
+ }
429
+ /** Whether an npm version is 11.6.0 or later, the first that installs `vitest` 4.1's peer set; `11.6.0-rc.1` is earlier. */
430
+ function installsVitest41(npmVersion) {
431
+ const [release, prerelease] = (npmVersion ?? '0.0.0').split('-', 2);
432
+ const [major, minor, patch] = release.split('.').map(Number);
433
+ return major > 11 || (major === 11 && (minor > 6 || (minor === 6 && (patch > 0 || prerelease === undefined))));
434
+ }
435
+ /**
436
+ * Whether the scaffold holds `vitest` below 4.1, whose peer set crashes npm
437
+ * before 11.6 (every npm a Node 22 release bundles) on the first install. Only a
438
+ * workspace root declaring a newer npm lifts it, and only when `init` runs under
439
+ * an npm known to be newer: npm does not enforce `packageManager`.
440
+ */
441
+ function pinsVitest(composition) {
442
+ const workspace = composition.packaging.workspace;
443
+ return !(installsVitest41(workspace?.packageManagerNpm) && installsVitest41(workspace?.npmVersion));
444
+ }
445
+ /**
446
+ * The version a member pins a sibling member at: exact, at the version every
447
+ * member starts with. npm links a sibling only when the range admits its local
448
+ * version, and otherwise looks for it in the registry, where it was never
449
+ * published.
450
+ */
451
+ const MEMBER_PIN = '0.0.0';
452
+ /** A dependency block, sorted as npm writes it. */
453
+ function sortedBlock(dependencies, indent) {
454
+ return Object.keys(dependencies)
455
+ .sort()
456
+ .map(name => `${indent}"${name}": "${dependencies[name]}"`)
457
+ .join(',\n');
458
+ }
459
+ /** The server's dependency block: the base and head set's packages and the protocol member. */
220
460
  function dependencyBlock(composition, indent) {
221
- const merged = {};
222
- for (const head of composition.heads) {
461
+ const merged = { [memberPackageName(composition, 'protocol')]: MEMBER_PIN };
462
+ for (const head of ['base', ...composition.heads]) {
223
463
  Object.assign(merged, HEAD_THIRD_PARTY_DEPENDENCIES[head]);
224
464
  for (const framework of HEAD_FRAMEWORK_DEPENDENCIES[head]) {
225
465
  merged[framework] = frameworkPin(composition);
226
466
  }
227
467
  }
228
- return Object.keys(merged)
229
- .sort()
230
- .map(name => `${indent}"${name}": "${merged[name]}"`)
231
- .join(',\n');
468
+ return sortedBlock(merged, indent);
232
469
  }
233
470
  // JSON at two-space indent, not the three the `.ts` templates use: that is the
234
471
  // npm convention, and `npm install` rewrites `package.json` at two spaces
235
472
  // regardless — so three would not survive the adopter's first install.
236
473
  //
237
- // The KEY ORDER is `prettier-plugin-packagejson`'s canonical one, `private`
474
+ // The KEY ORDER is the one Oxfmt's `sortPackageJson` canonicalises to, `private`
238
475
  // before `license` included. Any other order is rewritten by the scaffolded
239
476
  // project's own first `format` run — a diff on a file the adopter never touched
240
477
  // — and it makes a byte-compare against a formatted copy of this emission
@@ -254,6 +491,11 @@ function dependencyBlock(composition, indent) {
254
491
  // from this package's own grammar and can reach a consumer from nowhere else; a
255
492
  // listed path that does not exist yet is inert.
256
493
  //
494
+ // `exports` puts `createServices`, the one module reading the real filesystem,
495
+ // behind `./node`, so the root loads in a browser worker that has no `node:fs`.
496
+ // `./lib/*` and `./package.json` stay reachable for a host that resolves
497
+ // `<server>/lib/main.js` to spawn the server.
498
+ //
257
499
  // `repository` is deliberately NOT emitted while `author` is emitted empty. An
258
500
  // empty `author` is the form `npm init` itself writes and asserts nothing, but
259
501
  // `repository` is CONSUMED — the registry page, `npm repo` and publish
@@ -265,16 +507,9 @@ const PACKAGE_JSON = `{
265
507
  "version": "0.0.0",
266
508
  __PRIVATE__ "description": "__NAME__ language server, built with the Hydranium framework.",
267
509
  "keywords": [
268
- "hydranium",
269
- "langium",
270
- "language-server",
271
- "__PROJECT_ID__"
272
- ],
510
+ __KEYWORDS__ ],
273
511
  "license": "UNLICENSED",
274
512
  "author": "",
275
- "type": "module",
276
- "main": "lib/index.js",
277
- "types": "lib/index.d.ts",
278
513
  "bin": {
279
514
  __BIN__ },
280
515
  "files": [
@@ -282,17 +517,32 @@ __BIN__ },
282
517
  "src",
283
518
  "syntaxes"
284
519
  ],
520
+ "type": "module",
521
+ "main": "lib/index.js",
522
+ "types": "lib/index.d.ts",
523
+ "exports": {
524
+ ".": {
525
+ "types": "./lib/index.d.ts",
526
+ "default": "./lib/index.js"
527
+ },
528
+ "./node": {
529
+ "types": "./lib/node/services.d.ts",
530
+ "default": "./lib/node/services.js"
531
+ },
532
+ "./lib/*": "./lib/*",
533
+ "./package.json": "./package.json"
534
+ },
285
535
  "scripts": {
286
- "build": "npm run generate && tsc",
287
- "clean": "rimraf lib syntaxes src/language-server/generated src/language-server/generated-hydranium tsconfig.tsbuildinfo",
536
+ "build": "npm run generate && tsc -b",
537
+ "clean": "rimraf lib syntaxes src/language-server/generated src/language-server/generated-hydranium test/generated-hydranium tsconfig.tsbuildinfo",
288
538
  "generate": "npm run langium:generate && npm run generate:transfer-model",
289
- "generate:transfer-model": "hydranium-cli generate-transfer-model --ast-file src/language-server/generated/ast.ts --augmentation-file src/language-server/ast.ts --out-file src/language-server/generated-hydranium/transfer-model.ts --ast-builder-file src/language-server/generated-hydranium/ast-builder.ts --element-type-name __NAME__Element --terminals-name __NAME__Terminals --regen-command \\"Run: __NPM_RUN__ generate:transfer-model\\"",
539
+ "generate:transfer-model": "hydranium-cli generate-transfer-model --ast-file src/language-server/generated/ast.ts --augmentation-file src/language-server/ast.ts --out-file ../protocol/src/generated-hydranium/transfer-model.ts --ast-builder-file src/language-server/generated-hydranium/ast-builder.ts --transfer-builder-file test/generated-hydranium/transfer-builder.ts --languages-file ../protocol/src/generated-hydranium/languages.ts --element-type-name __NAME__Element --terminals-name __NAME__Terminals --regen-command \\"Run: __NPM_RUN__ generate:transfer-model\\"",
290
540
  "langium:generate": "langium generate",
291
541
  "langium:watch": "langium generate --watch",
292
- __LINT__ "start": "node lib/main.js --stdio",
542
+ __LINT__ "start": "node lib/main.js__START_ARGS__",
293
543
  "test": "npm run typecheck:test && vitest run",
294
544
  "typecheck:test": "tsc --noEmit -p tsconfig.test.json",
295
- "watch": "tsc --watch"
545
+ "watch": "concurrently --kill-others --names langium,transfer-model,tsc \\"npm run langium:watch\\" \\"npm run generate:transfer-model -- --watch\\" \\"tsc -b --watch\\""
296
546
  },
297
547
  "dependencies": {
298
548
  __DEPENDENCIES__
@@ -300,10 +550,11 @@ __DEPENDENCIES__
300
550
  "devDependencies": {
301
551
  "@hydranium/cli": "__FRAMEWORK_PIN__",
302
552
  "@types/node": "^22.0.0",
553
+ "concurrently": "^9.0.0",
303
554
  "langium-cli": "4.3.0",
304
555
  "rimraf": "^5.0.0",
305
- "typescript": "^5.8.0",
306
- "vitest": "^4.0.0"
556
+ "typescript": "^7.0.2",
557
+ "vitest": "__VITEST__"
307
558
  },
308
559
  "engines": {
309
560
  "node": ">=22.13"
@@ -311,16 +562,17 @@ __DEPENDENCIES__
311
562
  }
312
563
  `;
313
564
  /**
314
- * How the scaffold names `npm run` when talking about itself.
565
+ * How the scaffold names `npm run` for one member's script.
315
566
  *
316
- * A workspace member's scripts are routinely invoked from the repo root, where
317
- * a bare `npm run` reaches the ROOT manifest and fails — so the regen hint a
318
- * generated file prints has to name the package, or it sends every reader who
319
- * follows it to the wrong place.
567
+ * Always with `--prefix`, from the directory commands are run in: the
568
+ * workspace root for a member, the project root for a standalone project. A
569
+ * bare `npm run` there reaches the ROOT manifest and fails, and the regen hint
570
+ * a generated file prints is read in `protocol/` as well, where the script it
571
+ * names does not exist.
320
572
  */
321
- function npmRun(composition) {
573
+ function npmRun(composition, member) {
322
574
  const workspace = composition.packaging.workspace;
323
- return workspace === undefined ? 'npm run' : `npm --prefix ${workspace.targetPath} run`;
575
+ return `npm --prefix ${workspace === undefined ? member : `${workspace.targetPath}/${member}`} run`;
324
576
  }
325
577
  /**
326
578
  * The `bin` targets, one per executable entry the head set emits.
@@ -331,7 +583,7 @@ function npmRun(composition) {
331
583
  * name. Without the second key a scaffolded project has no command line that
332
584
  * reaches its own data head at all.
333
585
  *
334
- * Alphabetical, because `prettier-plugin-packagejson` sorts `bin` and any other
586
+ * Alphabetical, because Oxfmt's `sortPackageJson` sorts `bin` and any other
335
587
  * order is rewritten by the scaffolded project's first `format` run.
336
588
  */
337
589
  function binBlock(composition) {
@@ -341,21 +593,37 @@ function binBlock(composition) {
341
593
  }
342
594
  return entries.map(([name, target]) => ` "${name}": "${target}"`).join(',\n') + '\n';
343
595
  }
344
- /** `package.json` with the name, the private flag and the dependency block all derived. */
596
+ /**
597
+ * A member's `lint` script line, over `directories`, or nothing.
598
+ *
599
+ * Emitted only where a root lint config says the repo lints. The absence is
600
+ * the dangerous direction: a task runner runs a script only where one is
601
+ * declared, so a package with no `lint` is SKIPPED rather than reported, and
602
+ * that reads as a clean lint. A wrong invocation is one visible line to edit.
603
+ */
604
+ function lintScript(member, directories) {
605
+ const workspace = member.packaging.workspace;
606
+ if (workspace?.oxlintConfig !== undefined) {
607
+ const config = `${'../'.repeat(workspace.targetPath.split('/').length)}${workspace.oxlintConfig}`;
608
+ return ` "lint": "oxlint --report-unused-disable-directives --format stylish --config ${config} ${directories} --max-warnings 0",\n`;
609
+ }
610
+ return workspace?.eslintConfig !== undefined ? ` "lint": "eslint ${directories} --max-warnings 0",\n` : '';
611
+ }
612
+ /** The server's `package.json`, with the name, the private flag and the dependency block all derived. */
345
613
  function packageJson(composition) {
346
- const { scope } = composition.packaging;
347
- const packageName = scope === undefined ? composition.projectId : `${scope}/${composition.projectId}`;
348
- // Emitted only where a root eslint config says the repo lints. The absence is
349
- // the dangerous direction: a task runner runs a script only where one is
350
- // declared, so a package with no `lint` is SKIPPED rather than reported, and
351
- // that reads as a clean lint. A wrong invocation is one visible line to edit.
352
- const lint = composition.packaging.workspace?.eslintConfig === undefined ? '' : ' "lint": "eslint src test --max-warnings 0",\n';
614
+ const keywords = ['hydranium', 'langium', 'language-server', composition.projectId]
615
+ .sort()
616
+ .map(keyword => ` ${JSON.stringify(keyword)}`)
617
+ .join(',\n') + '\n';
353
618
  return project(PACKAGE_JSON, composition)
354
- .replace('__PACKAGE_NAME__', packageName)
619
+ .replace('__PACKAGE_NAME__', memberPackageName(composition, 'server'))
620
+ .replace('__KEYWORDS__', keywords)
355
621
  .replace('__BIN__', binBlock(composition))
356
- .replace('__LINT__', lint)
622
+ .replace('__LINT__', lintScript(forMember(composition, 'server'), 'src test'))
623
+ .replace('__START_ARGS__', composition.heads.includes('lsp') ? ' --stdio' : ' ../workspace')
624
+ .replace('__VITEST__', pinsVitest(composition) ? '~4.0.18' : '^4.0.0')
357
625
  .replace('__PRIVATE__', composition.packaging.private ? ' "private": true,\n' : '')
358
- .replace('__NPM_RUN__', npmRun(composition))
626
+ .replace('__NPM_RUN__', npmRun(composition, 'server'))
359
627
  .replace('__FRAMEWORK_PIN__', frameworkPin(composition))
360
628
  .replace('__DEPENDENCIES__', dependencyBlock(composition, ' '));
361
629
  }
@@ -418,6 +686,23 @@ const TSCONFIG_COMPILER_OPTIONS = [
418
686
  ['forceConsistentCasingInFileNames', true],
419
687
  ['types', ['node']]
420
688
  ];
689
+ /** The protocol member's compiler options, pruned against a workspace base like the server's. */
690
+ const PROTOCOL_COMPILER_OPTIONS = [
691
+ ['target', 'ES2022'],
692
+ ['lib', ['ES2022']],
693
+ ['module', 'NodeNext'],
694
+ ['moduleResolution', 'NodeNext'],
695
+ ['rootDir', 'src'],
696
+ ['outDir', 'lib'],
697
+ ['strict', true],
698
+ ['skipLibCheck', true],
699
+ ['declaration', true],
700
+ // The server's `tsc -b` builds this project through a reference, which
701
+ // `tsc` refuses unless the referenced project is composite.
702
+ ['composite', true],
703
+ // No ambient Node types: a browser client compiles against this package.
704
+ ['types', []]
705
+ ];
421
706
  /**
422
707
  * The options that describe where THIS package's own files live. Never pruned,
423
708
  * and emitted first in the workspace case: a base config that supplied them
@@ -425,9 +710,19 @@ const TSCONFIG_COMPILER_OPTIONS = [
425
710
  * base is wrong rather than that the member is redundant.
426
711
  */
427
712
  const PACKAGE_LOCAL_OPTIONS = ['rootDir', 'outDir'];
428
- /** Compare two JSON option values. Sound here because compiler options are scalars and flat arrays. */
429
- function jsonEquals(left, right) {
430
- return JSON.stringify(left) === JSON.stringify(right);
713
+ /**
714
+ * The enum-valued options of {@link TSCONFIG_COMPILER_OPTIONS}, whose values
715
+ * `tsc` reads case-insensitively, so `nodenext` and `NodeNext` are one value.
716
+ * An enum-valued option added there belongs here too.
717
+ */
718
+ const CASE_INSENSITIVE_OPTIONS = ['target', 'lib', 'module', 'moduleResolution'];
719
+ /** Compare two option values. Sound here because compiler options are scalars and flat arrays. */
720
+ function optionEquals(key, left, right) {
721
+ const normalise = (value) => {
722
+ const text = JSON.stringify(value);
723
+ return CASE_INSENSITIVE_OPTIONS.includes(key) ? text?.toLowerCase() : text;
724
+ };
725
+ return normalise(left) === normalise(right);
431
726
  }
432
727
  /**
433
728
  * `tsconfig.json`, extending the workspace's base config when there is one.
@@ -436,104 +731,43 @@ function jsonEquals(left, right) {
436
731
  * the same key: inheriting `"module": "CommonJS"` where the scaffold needs
437
732
  * `NodeNext` would break every emitted import, so a differing base value is a
438
733
  * reason to keep the override rather than to trust the parent.
734
+ *
735
+ * `member` is the composition as that member sees it, so `extends` reaches the
736
+ * workspace base from the member's own directory.
439
737
  */
440
- function tsconfigJson(composition) {
441
- const workspace = composition.packaging.workspace;
738
+ function tsconfigJson(member, compilerOptions, include, references = '') {
739
+ const workspace = member.packaging.workspace;
442
740
  const base = workspace?.baseTsconfig === undefined ? undefined : (workspace.baseCompilerOptions ?? {});
443
741
  const options = base === undefined
444
- ? TSCONFIG_COMPILER_OPTIONS
742
+ ? compilerOptions
445
743
  : [
446
- ...TSCONFIG_COMPILER_OPTIONS.filter(([key]) => PACKAGE_LOCAL_OPTIONS.includes(key)),
447
- ...TSCONFIG_COMPILER_OPTIONS.filter(([key, value]) => !PACKAGE_LOCAL_OPTIONS.includes(key) && !jsonEquals(base[key], value))
744
+ ...compilerOptions.filter(([key]) => PACKAGE_LOCAL_OPTIONS.includes(key)),
745
+ ...compilerOptions.filter(([key, value]) => !PACKAGE_LOCAL_OPTIONS.includes(key) && !optionEquals(key, base[key], value))
448
746
  ];
449
747
  const extendsLine = workspace?.baseTsconfig === undefined ? '' : ` "extends": "${workspace.baseTsconfig}",\n`;
450
- const body = options.map(([key, value]) => ` "${key}": ${JSON.stringify(value)}`).join(',\n');
451
- return `{\n${extendsLine} "compilerOptions": {\n${body}\n },\n "include": ["src", "src/**/*.json"]\n}\n`;
452
- }
453
- // `isolatedModules` is what makes this check agree with the transform that
454
- // actually runs the tests. `npm test` is `typecheck:test && vitest run`, and
455
- // vitest compiles through esbuild — a per-file transform with no type
456
- // information, which cannot tell a re-exported TYPE from a re-exported value.
457
- // Without the flag `tsc` accepts `export { SomeType } from './x'` that esbuild
458
- // then emits as a real import of a symbol that does not exist at runtime, so
459
- // the typecheck passes and the suite fails with a confusing missing-export.
460
- const TSCONFIG_TEST = `{
461
- "extends": "./tsconfig.json",
462
- "compilerOptions": {
463
- "rootDir": ".",
464
- "noEmit": true,
465
- "isolatedModules": true,
466
- "types": ["node"]
467
- },
468
- "include": ["src", "test", "src/**/*.json"]
748
+ // An array spaced as a formatter writes it, which `JSON.stringify` does not.
749
+ const json = (value) => (Array.isArray(value) ? `[${value.map(json).join(', ')}]` : JSON.stringify(value));
750
+ const body = options.map(([key, value]) => ` "${key}": ${json(value)}`).join(',\n');
751
+ const referencesLine = references === '' ? '' : `,\n "references": ${references}`;
752
+ return `{\n${extendsLine} "compilerOptions": {\n${body}\n },\n "include": ${include}${referencesLine}\n}\n`;
469
753
  }
470
- `;
471
- const VITEST_CONFIG = `import { defineConfig } from 'vitest/config';
472
-
473
- // Vitest transforms TypeScript itself and resolves \`.js\` specifiers to their
474
- // \`.ts\` source, so tests import from \`../src/\` with the same specifiers the
475
- // compiled output uses. \`include\` is scoped to \`test/\` so \`lib/\` is never
476
- // scanned; \`npm test\` runs \`typecheck:test\` first, because the esbuild
477
- // transform strips types without checking them.
478
-
479
- export default defineConfig({
480
- test: {
481
- environment: 'node',
482
- include: ['test/**/*.{test,spec}.ts']
483
- }
484
- });
485
- `;
486
- const GITIGNORE = `node_modules/
487
- lib/
488
- *.tsbuildinfo
489
-
490
- # Langium-generated TextMate grammar (rewritten by every \`langium generate\`).
491
- syntaxes/
492
- `;
493
754
  /**
494
- * The workspace-member `.gitignore` — one entry, and the one entry a root
495
- * cannot be assumed to have.
496
- *
497
- * A member inherits the root's rules, and `node_modules/`, `lib/` and
498
- * `*.tsbuildinfo` are in every monorepo root already, so repeating them here
499
- * would be three lines to keep in step for no coverage. `syntaxes/` is not like
500
- * them: it is a Langium artefact, so a root that has never held a Langium
501
- * package has no rule for it, and the first `langium generate` then offers
502
- * generated output up for commit with nothing to warn the adopter. Dropping the
503
- * whole file rather than this subset is the mistake this template exists to
504
- * undo.
505
- */
506
- const GITIGNORE_WORKSPACE_MEMBER = `# The workspace root already covers \`node_modules/\`, \`lib/\` and \`*.tsbuildinfo\`.
507
- # It has no reason to know about this one: the TextMate grammar is a Langium
508
- # artefact, rewritten by every \`langium generate\`, so a root that has never held
509
- # a Langium package ignores nothing here and the generated file is offered for
510
- # commit.
511
- syntaxes/
512
- `;
513
- /** The terminals every grammar needs, shared verbatim by the fragment and the lone-grammar case. */
514
- const TERMINALS = `hidden terminal WS: /\\s+/;
515
- terminal ID: /[_a-zA-Z][\\w_]*/;
516
- hidden terminal SL_COMMENT: /\\/\\/[^\\n\\r]*/;
517
- hidden terminal ML_COMMENT: /\\/\\*[\\s\\S]*?\\*\\//;
518
- `;
755
+ * The server's `tsconfig.json`. It references the protocol member, so `tsc -b`
756
+ * compiles protocol first, after `generate` has written its generated modules.
757
+ */
758
+ function serverTsconfigJson(composition) {
759
+ return tsconfigJson(forMember(composition, 'server'), TSCONFIG_COMPILER_OPTIONS, '["src", "src/**/*.json"]', '[{ "path": "../protocol" }]');
760
+ }
519
761
  /**
520
- * The shared lexical fragment, emitted only for a multi-grammar project.
521
- *
522
- * The alternative — every grammar declaring its own `WS` / `ID` — lets the token
523
- * sets drift apart.
762
+ * The terminals every grammar needs: the shared fragment's text after its
763
+ * leading comment run, so a lone grammar declares the same set.
524
764
  */
525
- const COMMON_GRAMMAR = `// Shared lexical basis for this project's grammars. Imported, never registered:
526
- // it has no entry rule and no \`langium-config.json\` entry, so it is a fragment
527
- // rather than a language.
528
- //
529
- // Keeping the tokens here rather than in one of the languages means a grammar
530
- // imports \`common\` for its TOKENS and another language only when it needs that
531
- // language's TYPES — separate reasons that are worth keeping separate.
532
-
533
- ${TERMINALS}`;
765
+ function terminals() {
766
+ return template('server/src/grammar/common.langium').replace(/^(\/\/.*\n)*\n/, '');
767
+ }
534
768
  /** One starter grammar. `shared` decides whether it imports the fragment or declares its own terminals. */
535
769
  function grammarFile(shared) {
536
- const lexis = shared ? "import './common'\n" : `\n${TERMINALS}`;
770
+ const lexis = shared ? "import './common'\n" : `\n${terminals()}`;
537
771
  return `grammar __GRAMMAR__
538
772
  ${shared ? '\n' + lexis : ''}
539
773
  // A minimal starter grammar — replace with your own language. \`__NODE_RULE__\` is
@@ -593,7 +827,10 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
593
827
  };`
594
828
  : `const __NAME__SharedModule: Module<__NAME__SharedServices, PartialLangiumSharedServices> = {};`;
595
829
  const serializerImports = composition.grammars
596
- .map(grammar => `import { ${grammar.grammar}Serializer } from './${grammar.grammarId}-serializer.js';`)
830
+ .flatMap(grammar => [
831
+ `import { ${grammar.grammar}Serializer } from './${grammar.grammarId}-serializer.js';`,
832
+ `import { ${grammar.grammar}ValidationContribution } from './${grammar.grammarId}-validation.js';`
833
+ ])
597
834
  .join('\n');
598
835
  // Each language gets its own adopter module because `Serializer` is a
599
836
  // per-language slot. `additionalLanguages` defaults its `adopter` to the
@@ -603,6 +840,11 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
603
840
  .map(grammar => `const ${grammar.grammar}LanguageModule: Module<__NAME__Services, PartialLangiumServices & DeepPartial<ServerAddedServices>> = {
604
841
  serializer: {
605
842
  Serializer: services => new ${grammar.grammar}Serializer(services)
843
+ },
844
+ validation: {
845
+ checks: {
846
+ names: () => new ${grammar.grammar}ValidationContribution()
847
+ }
606
848
  }
607
849
  };`)
608
850
  .join('\n\n');
@@ -616,11 +858,11 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
616
858
  : `${primary.grammar}: language`;
617
859
  const text = `// DI bootstrap for __NAME__. Composes the framework defaults with adopter
618
860
  // overrides via Langium's \`inject()\` (through the framework's
619
- // \`createIntegrationServices\`). Each adopter module binds ONE slot — its
620
- // language's \`Serializer\`, which the framework cannot default because a
621
- // concrete syntax is grammar knowledge. Everything else (scope, naming, project
622
- // management, build pipeline) boots on the framework defaults; scope
623
- // computation, validation checks and AST extensions go in these same modules.
861
+ // \`createIntegrationServices\`). Each adopter module binds its language's
862
+ // \`Serializer\`, which the framework cannot default because a concrete syntax
863
+ // is grammar knowledge, and its validation checks. Everything else (scope,
864
+ // naming, project management, build pipeline) boots on the framework defaults;
865
+ // scope computation and AST extensions go in these same modules.
624
866
  //
625
867
  // Note which generated symbol comes from which name: the SHARED module is
626
868
  // \`__NAME__GeneratedSharedModule\` (from \`projectName\`) and there is one of it,
@@ -634,7 +876,11 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
634
876
  : `
635
877
  //
636
878
  // A second grammar goes in the \`additionalLanguages\` option of
637
- // \`createIntegrationServices\`, generated from this same \`langium-config.json\`.`}
879
+ // \`createIntegrationServices\`, generated from this same \`langium-config.json\`.
880
+ // With several languages, bind \`lsp.configurationRoot\` in
881
+ // \`__NAME__SharedModule\`, or the framework warns and takes the first
882
+ // language's id. Type that module's second \`Module\` argument as
883
+ // \`PartialLangiumSharedServices & { lsp: { configurationRoot: string } }\`.`}
638
884
 
639
885
  ${importList(['createLspServerLanguageModule', 'createLspServerSharedModule', 'type LspServerAddedServices', 'type LspServerAddedSharedServices'], '@hydranium/core/lsp', columns)}
640
886
  import { createIntegrationServices, type ServerAddedServices, type ServerModuleContext, type ServerSharedServices } from '@hydranium/core';
@@ -701,179 +947,121 @@ ${returnType}
701
947
  `;
702
948
  return project(text, composition);
703
949
  }
704
- const SERVICES = `// Zero-arg service factory for the headless \`hydranium-cli\` tooling: the
705
- // \`reflect\` / \`lint-grammar\` / \`validate\` subcommands import this via
706
- // \`--services ./lib/services.js\`. The head wires its own filesystem here.
707
- //
708
- // The contract is language-count-agnostic — a second grammar needs no edit here.
709
-
710
- import { NodeFileSystem } from '@hydranium/core/node';
711
- import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
712
-
713
- export function createServices(): ReturnType<typeof create__NAME__Services> {
714
- return create__NAME__Services({ ...NodeFileSystem });
715
- }
716
- `;
717
- const AST = `// The language's AST entry point: a re-export of what \`langium generate\`
718
- // emits, plus anywhere you augment those types.
719
- //
720
- // Import the AST from HERE rather than from \`./generated/ast.js\`, so any
721
- // augmentation below travels with every import. One \`langium-cli\` run over N
722
- // grammars emits ONE combined AST module sharing one reflection, so a further
723
- // grammar needs no change here.
724
- //
725
- // \`generate:transfer-model\` reads this file as its \`--augmentation-file\`: the
726
- // generated wire types are derived from the AST *as augmented*, not from the
727
- // raw generated module. Augment a type here and the transfer model follows.
728
- //
729
- // A \`@derived\` property is computed at build time rather than parsed, so it is
730
- // declared here and populated by an AST-extension contribution:
731
- //
732
- // declare module './generated/ast.js' {
733
- // interface __ENTRY_RULE__ {
734
- // /** @derived Populated by an \`ast.extensions.computedProperties\` contribution. */
735
- // readonly _summary?: string;
736
- // }
737
- // }
738
-
739
- export * from './generated/ast.js';
740
- `;
741
950
  /**
742
- * The starter serializer — the concrete-syntax emitter for ONE grammar.
951
+ * How a host finds each socket head's port, in emission order: an LSP request
952
+ * when the LSP head publishes the ports, else the environment variable
953
+ * `main.ts` reads a port from.
743
954
  *
744
- * Emitted per grammar, not per project, because `services.serializer.Serializer`
745
- * is a per-language slot and a serializer is grammar-shaped by definition. That
746
- * is also why the framework refuses to default it: its `UnboundSerializer`
747
- * throws, naming the binding to add, rather than guessing a syntax.
748
- */
749
- const SERIALIZER = `// Concrete-syntax emitter for __GRAMMAR__ — the parser's inverse, turning a
750
- // model back into text this grammar accepts. Derived from the starter grammar
751
- // exactly as \`generated/ast.ts\` is, so replacing the grammar replaces this too.
752
- //
753
- // Without it every structured write fails: the framework's default binding at
754
- // \`services.serializer.Serializer\` THROWS, because a concrete syntax is
755
- // language knowledge no framework can derive. \`ModelService.update\` / \`save\`,
756
- // the data head's \`saveModelDocument\` and a GLSP \`SaveModelAction\` all reach
757
- // it.
758
- //
759
- // \`AbstractSerializer\`'s generic property walk lays out FORMAT-structured
760
- // output — its YAML and JSON subclasses are what it exists for — and cannot
761
- // produce a keyword-delimited syntax like \`node a -> b\`. So \`serializeNode\` is
762
- // a per-\`$type\` emitter here and the two array hooks are unreachable.
763
-
764
- import { AbstractSerializer } from '@hydranium/core';
765
- import type { AstNode } from '@hydranium/langium';
766
- import { type __ENTRY_RULE__, type __NODE_RULE__, is__ENTRY_RULE__, is__NODE_RULE__ } from './ast.js';
767
-
768
- export class __GRAMMAR__Serializer extends AbstractSerializer<__ENTRY_RULE__> {
769
- protected override serializeNode(node: AstNode | Record<string, unknown>): string {
770
- if (is__ENTRY_RULE__(node)) {
771
- return node.nodes.map(child => this.emitNode(child)).join('\\n');
772
- }
773
- if (is__NODE_RULE__(node)) {
774
- return this.emitNode(node);
775
- }
776
- // Defensive: a rule added to the grammar with no emitter added here.
777
- throw new Error(\`__GRAMMAR__Serializer: no emitter for $type \${(node as AstNode).$type}\`);
778
- }
779
-
780
- /** Unreachable — this grammar's one list is emitted by its \`__ENTRY_RULE__\` parent. */
781
- protected override serializeArray(): string {
782
- throw new Error('__GRAMMAR__Serializer: arrays are emitted by the per-$type parent, not the generic dispatch.');
783
- }
784
-
785
- /** Unreachable — same reasoning as {@link serializeArray}. */
786
- protected override serializeReferenceArray(): string {
787
- throw new Error('__GRAMMAR__Serializer: reference arrays are emitted by the per-$type parent, not the generic dispatch.');
788
- }
789
-
790
- /**
791
- * \`serializeReferenceText\` rather than \`node.target?.$refText\`: it is the one
792
- * read that spans BOTH input shapes. A transfer model reaching
793
- * \`serializeTransfer\` carries \`target\` as a plain string rather than a
794
- * \`Reference\`, and a serializer that reaches for \`$refText\` directly emits
795
- * the AST correctly and drops every reference on the transfer path.
796
- */
797
- private emitNode(node: __NODE_RULE__): string {
798
- const target = this.serializeReferenceText(node.target);
799
- return target === undefined ? \`node \${node.name}\` : \`node \${node.name} -> \${target}\`;
800
- }
801
- }
802
- `;
803
- /**
804
- * The exported constant names for the head set, in emission order. Both are
805
- * keyed by the PROJECT rather than by a language: one server of each kind per
955
+ * Keyed by the PROJECT rather than by a language: one server of each kind per
806
956
  * process serves every registered grammar, so a language-derived name would tie
807
957
  * a project-level endpoint to whichever grammar was scaffolded first.
808
958
  */
809
- function portCommandNames(composition) {
959
+ function headPortConstants(composition) {
810
960
  const upper = screamingSnake(composition.projectId);
961
+ const lsp = composition.heads.includes('lsp');
962
+ return socketHeads(composition).map(head => lsp
963
+ ? {
964
+ name: `${upper}_${head.key}_PORT_COMMAND`,
965
+ value: `${composition.projectId}/${head.path}/port`,
966
+ doc: `LSP request the host queries to discover the ${head.label} socket port.`
967
+ }
968
+ : {
969
+ name: `${upper}_${head.key}_PORT_ENV`,
970
+ value: `${upper}_${head.key}_PORT`,
971
+ doc: `Environment variable naming the ${head.label} socket port when no \`--${head.path}-port\` flag does.`
972
+ });
973
+ }
974
+ /** The socket heads of the composition, as `head-ports.ts` names them. */
975
+ function socketHeads(composition) {
811
976
  return [
812
- ...(composition.heads.includes('data') ? [`${upper}_DATA_SERVER_PORT_COMMAND`] : []),
813
- ...(composition.heads.includes('glsp') ? [`${upper}_GLSP_PORT_COMMAND`] : [])
977
+ ...(composition.heads.includes('data')
978
+ ? [{ key: 'DATA_SERVER', path: 'data-server', command: 'dataServer', label: 'data-server' }]
979
+ : []),
980
+ ...(composition.heads.includes('glsp') ? [{ key: 'GLSP_SERVER', path: 'glsp-server', command: 'glsp', label: 'GLSP' }] : [])
814
981
  ];
815
982
  }
983
+ /** Whether the composition emits the servers-only extension, which VS Code starts the server through and a Theia app sideloads. */
984
+ function emitsVscodeServers(composition) {
985
+ return initMembers(composition.heads, composition.hosts).includes('vscode-servers');
986
+ }
987
+ /**
988
+ * The host commands the servers extension answers each socket head's port
989
+ * under, for a host without a language client of its own.
990
+ */
991
+ function hostCommandConstants(composition) {
992
+ if (!emitsVscodeServers(composition)) {
993
+ return [];
994
+ }
995
+ const upper = screamingSnake(composition.projectId);
996
+ return socketHeads(composition).map(head => ({
997
+ name: `${upper}_${head.key}_HOST_COMMAND`,
998
+ value: `${composition.projectId}.port.${head.command}`,
999
+ doc: `Host command the servers extension answers with the ${head.label} socket port.`
1000
+ }));
1001
+ }
816
1002
  /**
817
- * The socket heads' discovery commands, as an importable module.
1003
+ * The socket heads' port commands or variables, in the protocol member.
818
1004
  *
819
- * Deliberately NOT declared in `main.ts`. A host shell has to name the same
820
- * string to reach the head, and `main.ts` opens a connection at module scope,
821
- * so importing a constant from it would start a server. A host that retypes the
822
- * literal instead gets no error when it drifts: the framework's port poll
823
- * defaults to `findPortAttempts = -1`, so a wrong command retries forever
824
- * rather than failing.
1005
+ * A host shell has to name the same string the server reads, and reaches it
1006
+ * here without depending on the server. A host that retypes the literal
1007
+ * instead gets no error when it drifts: the framework's port poll defaults to
1008
+ * `findPortAttempts = -1`, so a wrong command retries forever rather than
1009
+ * failing, and a wrong variable is never read.
825
1010
  */
826
1011
  function headPortsFile(composition) {
827
- const upper = screamingSnake(composition.projectId);
828
- const data = composition.heads.includes('data');
829
- const glsp = composition.heads.includes('glsp');
830
- const blocks = [
831
- ...(data
832
- ? [
833
- `/** LSP request the host queries to discover the data-server socket port. */\nexport const ${upper}_DATA_SERVER_PORT_COMMAND = '${composition.projectId}/data-server/port';`
834
- ]
835
- : []),
836
- ...(glsp
837
- ? [
838
- `/** LSP request the host queries to discover the GLSP socket port. */\nexport const ${upper}_GLSP_PORT_COMMAND = '${composition.projectId}/glsp/port';`
839
- ]
840
- : [])
841
- ];
842
- return `// The LSP requests a host queries to discover this server's socket head${blocks.length > 1 ? 's' : ''}.
1012
+ const constants = [...headPortConstants(composition), ...hostCommandConstants(composition)];
1013
+ const blocks = constants.map(constant => `/** ${constant.doc} */\nexport const ${constant.name} = '${constant.value}';`);
1014
+ const socketHeadCount = socketHeads(composition).length;
1015
+ const heads = `socket head${socketHeadCount > 1 ? 's' : ''}`;
1016
+ const opening = composition.heads.includes('lsp')
1017
+ ? `// The LSP requests a host queries to discover this server's ${heads}.`
1018
+ : `// The environment variables that name the ports of this server's ${heads}.`;
1019
+ const usage = composition.heads.includes('lsp')
1020
+ ? `// The server publishes them and a host shell has to name the same string to
1021
+ // reach the head; both import them from here. A shell that retypes the literal
1022
+ // gets no error when it drifts: the framework's port poll retries indefinitely
1023
+ // by default.`
1024
+ : `// The server reads them and a process that starts it sets them; both import
1025
+ // them from here. A variable retyped with a typo is never read, and the head
1026
+ // then listens on whichever port is free.`;
1027
+ const hostCommands = emitsVscodeServers(composition)
1028
+ ? `
1029
+ //
1030
+ // The host commands are the same ports for a host with no language client,
1031
+ // such as a Theia app sideloading the servers extension: it runs the command
1032
+ // and the extension sends the request.`
1033
+ : '';
1034
+ return `${opening}
843
1035
  //
844
- // Both are keyed by the PROJECT, not the language: one server of each kind per
1036
+ // ${socketHeadCount > 1 ? 'Both are' : 'It is'} keyed by the PROJECT, not the language: one server of each kind per
845
1037
  // process serves every registered grammar, so a language-derived name would tie
846
1038
  // a project-level endpoint to whichever grammar was scaffolded first.
847
1039
  //
848
- // They live here rather than in \`main.ts\` because a host shell has to name the
849
- // same string to reach the head, and \`main.ts\` is an executable entry — nothing
850
- // can import from it. A shell that retypes the literal gets no error when it
851
- // drifts: the framework's port poll retries indefinitely by default. Import
852
- // these instead, and assert any host-side copy against them.
1040
+ ${usage}${hostCommands}
853
1041
 
854
1042
  ${blocks.join('\n\n')}
855
1043
  `;
856
1044
  }
857
- const INDEX = `// Public surface of the __NAME__ language server: the DI factory, the generated
858
- // AST, and the headless \`createServices\` entry.
1045
+ /**
1046
+ * The server's root entry: the DI factory, the generated AST and each diagram
1047
+ * module, all loadable in a browser worker.
1048
+ */
1049
+ function indexFile(composition) {
1050
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
1051
+ const diagramPhrase = diagrams.length === 0 ? '' : diagrams.length === 1 ? ', plus the diagram module' : ', plus the diagram modules';
1052
+ const text = `// Public surface of the __NAME__ language server: the DI factory and the
1053
+ // generated AST${diagramPhrase}.
859
1054
  //
860
- // The entry points under \`src/\` are deliberately NOT re-exported. Each opens a
861
- // transport at module scope, so importing one starts a server as a side effect
862
- // — which is why they are \`bin\` targets and this file is \`main\`.
1055
+ // Everything here loads in a browser worker as well as in Node, so a host can
1056
+ // compose the language wherever it runs it. \`createServices\`, which reads the
1057
+ // real filesystem, is the package's \`./node\` entry instead. The entry points
1058
+ // under \`src/\` are not re-exported either: each opens a transport at module
1059
+ // scope, so importing one starts a server, which is why they are \`bin\` targets.
863
1060
 
864
1061
  export * from './language-server/__PROJECT_ID__-module.js';
865
1062
  export * from './language-server/ast.js';
866
- export { createServices } from './services.js';
867
- `;
868
- /**
869
- * The public surface, plus the head-port commands when there is a socket head.
870
- *
871
- * The commands belong here rather than only in `head-ports.ts` so a host shell
872
- * reaches them from the package root, the same way it reaches `createServices`.
873
- */
874
- function indexFile(composition) {
875
- const base = project(INDEX, composition);
876
- return portCommandNames(composition).length ? `${base}export * from './head-ports.js';\n` : base;
1063
+ ${diagrams.map(grammar => `export * from './glsp/${grammar.grammarId}/diagram-module.js';\n`).join('')}`;
1064
+ return project(text, composition);
877
1065
  }
878
1066
  /**
879
1067
  * The `#!` line every emitted `bin` target carries.
@@ -899,12 +1087,14 @@ const SHEBANG = '#!/usr/bin/env node\n';
899
1087
  */
900
1088
  function mainFile(composition) {
901
1089
  const columns = columnsFor(composition);
902
- const roots = [...composition.grammars.map(grammar => grammar.entryRule)].sort();
1090
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
903
1091
  const upper = screamingSnake(composition.projectId);
1092
+ const lsp = composition.heads.includes('lsp');
904
1093
  const data = composition.heads.includes('data');
905
1094
  const glsp = composition.heads.includes('glsp');
906
1095
  const diagrams = composition.grammars.filter(grammar => grammar.diagram);
907
1096
  const plural = roots.length > 1 ? 's' : '';
1097
+ const portFlags = [...(data ? ['--data-server-port'] : []), ...(glsp ? ['--glsp-server-port'] : [])];
908
1098
  const headNames = composition.heads.map(head => head === 'lsp' ? 'the Langium LSP head' : head === 'data' ? 'a socket data-server (model server) head' : 'a GLSP head');
909
1099
  // Comma-joined but for the last, which takes `and`: a bare `, ` join reads as
910
1100
  // a truncated list, and the emitted comment is the first thing an adopter
@@ -913,7 +1103,7 @@ function mainFile(composition) {
913
1103
  // `reflect-metadata` must be imported before anything that reads a
914
1104
  // decorator's emitted metadata, which inversify does at module scope.
915
1105
  const reflectImport = glsp ? "import 'reflect-metadata';\n" : '';
916
- const coreNodeSymbols = ['NodeFileSystem', ...(data ? ['publishPortOnLspConnection', 'startSocketServer'] : [])];
1106
+ const coreNodeSymbols = ['NodeFileSystem', ...(data ? [...(lsp ? ['publishPortOnLspConnection'] : []), 'startSocketServer'] : [])];
917
1107
  const glspImports = glsp
918
1108
  ? `import { ServerModule } from '@eclipse-glsp/server/node.js';
919
1109
  import { GlspClientLogger, HydraniumGlspAppModule } from '@hydranium/glsp-server';
@@ -930,44 +1120,57 @@ import { startGlspServer } from '@hydranium/glsp-server/node';
930
1120
  // \`TransferElement\` structurally, so naming the AST type here compiles fine and
931
1121
  // silently tells every typed client that a reference is a resolvable object
932
1122
  // rather than a name.
933
- ${importList(roots, './language-server/generated-hydranium/transfer-model.js', columns, true)}
1123
+ ${importList(roots, memberPackageName(composition, 'protocol'), columns, true)}
934
1124
  `
935
1125
  : '';
936
- // The commands live in `head-ports.ts`, not here: a host shell has to name
937
- // the same string to reach the head, and this file is an executable entry, so
938
- // nothing can import from it.
939
- const portCommands = portCommandNames(composition).length
940
- ? importList(portCommandNames(composition), './head-ports.js', columns) + '\n'
941
- : '';
942
- const dataBlock = data
943
- ? `
1126
+ // The names live in the protocol member, not here: a host shell has to name
1127
+ // the same string to reach the head, and this file is an executable entry,
1128
+ // so nothing can import from it.
1129
+ const portNames = headPortConstants(composition).map(constant => constant.name);
1130
+ const portImports = portNames.length ? importList(portNames, memberPackageName(composition, 'protocol'), columns) + '\n' : '';
1131
+ const dataBlock = !data
1132
+ ? ''
1133
+ : !lsp
1134
+ ? `
1135
+ // Data-server head: each accepted client gets its own DataServer.
1136
+ const dataServer = startSocketServer(
1137
+ { shared, workspace, port: portFrom('data-server-port', ${upper}_DATA_SERVER_PORT_ENV), logTag: 'ModelServer', logger: shared.Logger },
1138
+ dataConnection => {
1139
+ new DataServer<${roots.join(' | ')}>(dataConnection, shared);
1140
+ return { dispose: () => undefined };
1141
+ }
1142
+ );
1143
+ `
1144
+ : `
944
1145
  // Data-server head alongside LSP: binds an ephemeral port, published over the LSP
945
1146
  // connection for the host to discover. Each accepted client gets its own DataServer.
946
1147
  //
947
1148
  // Neither the bind nor the publish may be swallowed: either failure leaves the LSP
948
1149
  // head serving text edits while every data client waits on a port command that was
949
1150
  // never registered, and the launcher reports a bind failure only if given a logger.
950
- const dataServer = startSocketServer({ port: 0, logTag: 'ModelServer', logger: shared.Logger }, dataConnection => {
1151
+ const dataServer = startSocketServer({ shared, port: 0, logTag: 'ModelServer', logger: shared.Logger }, dataConnection => {
951
1152
  new DataServer<${roots.join(' | ')}>(dataConnection, shared);
952
1153
  return { dispose: () => undefined };
953
1154
  });
954
1155
  dataServer.started
955
- .then(() => {
956
- const { port } = dataServer;
957
- if (port === undefined) {
958
- // \`started\` resolves only once the address is resolved, so this is
959
- // unreachable; a non-null assertion in its place would publish
960
- // \`undefined\`, which the host cannot tell from an unreachable port.
961
- throw new Error('the data head started without a resolved port');
962
- }
963
- publishPortOnLspConnection(shared.lsp.Connection, ${upper}_DATA_SERVER_PORT_COMMAND, port);
964
- })
1156
+ .then(
1157
+ () => {
1158
+ const { port } = dataServer;
1159
+ if (port === undefined) {
1160
+ // \`started\` resolves only once the address is resolved, so this is
1161
+ // unreachable; a non-null assertion in its place would publish
1162
+ // \`undefined\`, which the host cannot tell from an unreachable port.
1163
+ throw new Error('the data head started without a resolved port');
1164
+ }
1165
+ publishPortOnLspConnection(shared.lsp.Connection, ${upper}_DATA_SERVER_PORT_COMMAND, port);
1166
+ },
1167
+ // The launcher logged its own bind failure; the rejection is control flow.
1168
+ () => undefined
1169
+ )
965
1170
  .catch((error: unknown) => {
966
- const reason = error instanceof Error ? error.message : String(error);
967
- shared.Logger.error(\`[ModelServer] Could not publish the data-server port: \${reason}\`);
1171
+ shared.Logger.error(\`[ModelServer] Could not publish the data-server port: \${describeErrorWithStack(error)}\`);
968
1172
  });
969
- `
970
- : '';
1173
+ `;
971
1174
  const glspBlock = glsp
972
1175
  ? `
973
1176
  // GLSP head on the same shared workspace. \`HydraniumGlspAppModule\` is used
@@ -975,89 +1178,146 @@ dataServer.started
975
1178
  // grammar a request concerns, so nothing per-language belongs there — each
976
1179
  // diagram module declares its own language instead.
977
1180
  //
978
- // GLSP framework logs route through the LSP connection rather than stdout, which
979
- // IS the LSP transport in stdio mode; writing there corrupts the protocol stream.
1181
+ ${lsp
1182
+ ? `// GLSP framework logs route through the LSP connection rather than stdout, which
1183
+ // IS the LSP transport in stdio mode; writing there corrupts the protocol stream.`
1184
+ : `// GLSP framework logs route through the framework's logger to stderr. GLSP's
1185
+ // own startup line goes to stdout, beside the ports line below.`}
980
1186
  const glspServer = startGlspServer({
981
1187
  // The GLSP log threshold lives on the logger, not beside it: the framework
982
1188
  // replaces GLSP's own \`Logger\` binding, so a launcher-level \`logLevel\` would
983
1189
  // be discarded. The logger tracks the framework's process-wide threshold, so
984
- // \`HYDRANIUM_LOG_LEVEL\` and the LSP log-level setting govern GLSP output too;
1190
+ // \`HYDRANIUM_LOG_LEVEL\` ${lsp ? 'and the LSP log-level setting govern' : 'governs'} GLSP output too;
985
1191
  // pass \`logLevel\` only to make GLSP quieter than the rest of the server.
986
1192
  createLogger: caller => new GlspClientLogger(shared, { component: caller }),
987
1193
  serverModule: new ServerModule()${diagrams.map(grammar => `.configureDiagramModule(new ${grammar.grammar}DiagramModule())`).join('')},
988
1194
  appModules: [new HydraniumGlspAppModule({ shared })],
989
- lspConnection: shared.lsp.Connection,
990
- portCommand: ${upper}_GLSP_PORT_COMMAND
1195
+ ${lsp
1196
+ ? ` lspConnection: shared.lsp.Connection,
1197
+ portCommand: ${upper}_GLSP_SERVER_PORT_COMMAND`
1198
+ : ` workspace,
1199
+ port: portFrom('glsp-server-port', ${upper}_GLSP_SERVER_PORT_ENV),
1200
+ logger: shared.Logger`}
991
1201
  });
992
- void glspServer;
993
- `
1202
+ ${lsp ? 'void glspServer;\n' : ''}`
994
1203
  : '';
995
- const text = `${SHEBANG}// Standalone entry point: starts ${headSummary} in the same
996
- // process, so every head shares one model store.
997
- // Invocation: \`node lib/main.js --stdio\`, or the package's \`__PROJECT_ID__\` bin
998
- // script.${data
999
- ? `
1000
- //
1001
- // NOT the entry \`hydranium-cli query\` / \`save\` / \`projects\` / \`watch\` speak to:
1002
- // stdio here carries LSP, and the data head is a socket whose port is published
1003
- // over the LSP connection. Those subcommands spawn \`data-server-main.js\`.`
1004
- : ''}
1005
- //
1006
- // Everything here runs at module scope, so this file is an executable rather
1007
- // than a library entry — import \`./index.js\` instead to compose the language.
1008
-
1009
- ${reflectImport}${glspImports}${importList(coreNodeSymbols, '@hydranium/core/node', columns)}
1010
- ${data ? "import { DataServer } from '@hydranium/data-server';\n" : ''}// The framework's entry point, NOT Langium's \`@hydranium/langium/lsp\` one. It is
1204
+ const lspImports = `// The framework's entry point, NOT Langium's \`@hydranium/langium/lsp\` one. It is
1011
1205
  // signature-compatible and delegates straight through; what it adds first is
1012
1206
  // \`assertLspHeadComposed\`, which fails the start if the LSP head's SHARED module
1013
1207
  // was never composed. Reaching for Langium's is the natural mistake and it is
1014
1208
  // silent: the server boots, links and completes, while echo suppression, the
1015
1209
  // didChangeContent debounce and the last-client-close rebuild are all inert.
1016
- import { startLanguageServer } from '@hydranium/core/lsp';
1210
+ import { startLanguageServer, withHydraniumLspFeatures } from '@hydranium/core/lsp';
1017
1211
  import { ProposedFeatures, createConnection } from 'vscode-languageserver/node';
1018
- ${diagramImports}${transferImports}import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1019
- ${portCommands === '' ? '' : '\n' + portCommands}
1020
- const connection = createConnection(ProposedFeatures.all);
1212
+ `;
1213
+ const lspStart = `
1214
+ const connection = createConnection(withHydraniumLspFeatures(ProposedFeatures.all));
1021
1215
  const { shared } = create__NAME__Services({ connection, ...NodeFileSystem });
1022
1216
  startLanguageServer(shared);
1023
- ${dataBlock}${glspBlock}`;
1217
+ `;
1218
+ // No LSP client names the workspace or asks for the ports here, so the
1219
+ // command line does, and the ports go to stdout once every head listens.
1220
+ const servers = [...(data ? ['dataServer'] : []), ...(glsp ? ['glspServer'] : [])];
1221
+ const socketStart = `
1222
+ const { values, positionals } = parseArgs({
1223
+ options: { ${portFlags.map(flag => `'${flag.slice(2)}': { type: 'string' }`).join(', ')} },
1224
+ allowPositionals: true
1225
+ });
1226
+ // The workspace root: the first argument, else the process cwd.
1227
+ const workspace = positionals[0] ?? process.cwd();
1228
+
1229
+ /** A head's port: its flag, else its environment variable, else 0 for any free port. */
1230
+ function portFrom(flag: keyof typeof values, variable: string): number {
1231
+ const text = values[flag] ?? process.env[variable] ?? '0';
1232
+ const port = Number(text);
1233
+ // Decimal digits only: \`Number\` also reads '' as 0 and takes '1e3' or '0x10'.
1234
+ if (!/^\\d+$/.test(text) || port > 65_535) {
1235
+ throw new Error(\`--\${flag} or \${variable} is '\${text}', not a port\`);
1236
+ }
1237
+ return port;
1238
+ }
1239
+
1240
+ const { shared } = create__NAME__Services({ ...NodeFileSystem });
1241
+ `;
1242
+ const portsLine = `
1243
+ // One JSON line on stdout once every head listens, for the process that started
1244
+ // this one to read the ports from: the one line that starts with \`{\`. Each
1245
+ // head brings the workspace up before it listens; a head that fails to start
1246
+ // has logged why and ends the process, which would otherwise serve without it.
1247
+ ${servers.length === 1 ? `${servers[0]}.started` : `Promise.all([${servers.map(server => `${server}.started`).join(', ')}])`}.then(
1248
+ () => process.stdout.write(\`\${JSON.stringify({ ${servers.map(server => `${server}: ${server}.port`).join(', ')} })}\\n\`),
1249
+ () => process.exit(1)
1250
+ );
1251
+ `;
1252
+ const invocation = lsp
1253
+ ? `// Invocation: \`node lib/main.js --stdio\`, or the package's \`__PROJECT_ID__\` bin
1254
+ // script.`
1255
+ : `// Invocation: \`node lib/main.js [<workspace-path>] ${portFlags.map(flag => `[${flag} <port>]`).join(' ')}\`,
1256
+ // or the package's \`__PROJECT_ID__\` bin script. Each port falls back to its
1257
+ // environment variable, then to any free port.`;
1258
+ const dataNote = !data
1259
+ ? ''
1260
+ : lsp
1261
+ ? `
1262
+ //
1263
+ // NOT the entry the data-server subcommands of \`hydranium-cli\` speak to: stdio
1264
+ // here carries LSP, and the data head is a socket whose port is published over
1265
+ // the LSP connection. Those subcommands spawn \`data-server-main.js\`.`
1266
+ : `
1267
+ //
1268
+ // NOT the entry the data-server subcommands of \`hydranium-cli\` speak to: they
1269
+ // drive the data protocol over a child's stdio, and the data head here is a
1270
+ // socket. Those subcommands spawn \`data-server-main.js\`.`;
1271
+ const text = `${SHEBANG}// Standalone entry point: starts ${headSummary} in the same
1272
+ // process, so every head shares one model store.
1273
+ ${invocation}${dataNote}
1274
+ //
1275
+ // Everything here runs at module scope, so this file is an executable rather
1276
+ // than a library entry — import \`./index.js\` instead to compose the language.
1277
+
1278
+ ${reflectImport}${glspImports}${importList(coreNodeSymbols, '@hydranium/core/node', columns)}
1279
+ ${data ? "import { DataServer } from '@hydranium/data-server';\n" : ''}${data && lsp ? "import { describeErrorWithStack } from '@hydranium/protocol';\n" : ''}${lsp ? lspImports : "import { parseArgs } from 'node:util';\n"}${diagramImports}${transferImports}import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1280
+ ${portImports === '' ? '' : '\n' + portImports}${lsp ? lspStart : socketStart}${dataBlock}${glspBlock}${lsp ? '' : portsLine}`;
1024
1281
  return project(text, composition);
1025
1282
  }
1026
1283
  /**
1027
1284
  * The second executable entry: the data head alone, on stdio.
1028
1285
  *
1029
1286
  * Emitted with the `data` head because it is the ONLY command line that reaches
1030
- * that head from outside the editor. `main.ts` gives stdio to LSP and publishes
1031
- * the data head's socket port over the LSP connection, so a client that is not
1032
- * an LSP client cannot discover it — which is every one of `hydranium-cli`'s
1033
- * `query` / `save` / `projects` / `watch`, all of which drive the data protocol
1034
- * over a spawned child's stdin/stdout. Without this file a scaffolded project
1035
- * has no `--server` value, and the closest guess — the LSP entry — fails as an
1036
- * unrecognised method rather than as a missing head.
1287
+ * that head from outside the editor. `main.ts` serves the data head on a
1288
+ * socket, so a client driving the data protocol over a spawned child's
1289
+ * stdin/stdout cannot reach it — which is every data-server subcommand of
1290
+ * `hydranium-cli`. Without this file a scaffolded project has no `--server`
1291
+ * value, and the closest guess, `main.ts`, fails as an unrecognised method or
1292
+ * an unknown flag rather than as a missing head.
1037
1293
  *
1038
1294
  * A separate process rather than a flag on `main.ts`: only one protocol can own
1039
1295
  * stdio, so the two entries are mutually exclusive by construction.
1040
1296
  */
1041
1297
  function dataServerMainFile(composition) {
1042
1298
  const columns = columnsFor(composition);
1043
- const roots = [...composition.grammars.map(grammar => grammar.entryRule)].sort();
1299
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
1044
1300
  const plural = roots.length > 1 ? 's' : '';
1045
1301
  const text = `${SHEBANG}// Standalone entry point: a data-server head on **stdio**, with no LSP head in
1046
- // the process. This is the transport \`hydranium-cli\` speaks — \`query\`, \`save\`,
1047
- // \`projects\` and \`watch\` all spawn a server command and drive JSON-RPC over its
1048
- // stdin/stdout — so it is what makes those subcommands usable against this
1049
- // language.
1302
+ // the process. This is the transport \`hydranium-cli\` speaks — its data-server
1303
+ // subcommands spawn a server command and drive JSON-RPC over its stdin/stdout —
1304
+ // so it is what makes those subcommands usable against this language.
1050
1305
  //
1051
1306
  // Invocation: \`node lib/data-server-main.js [<workspace-path>]\`, or the
1052
1307
  // package's \`__PROJECT_ID__-data-server\` bin script. The workspace path defaults to
1053
1308
  // the process cwd, which is what the CLI's \`--cwd\` sets on the child.
1054
1309
  //
1055
- // Contrast with \`main.ts\`, the editor entry: there the LSP head owns stdio and
1310
+ ${composition.heads.includes('lsp')
1311
+ ? `// Contrast with \`main.ts\`, the editor entry: there the LSP head owns stdio and
1056
1312
  // the data head is a socket published over the LSP connection. Here there is no
1057
1313
  // LSP connection at all, so the workspace initialization an
1058
1314
  // \`initialize\`/\`initialized\` pair would otherwise drive has to happen here —
1059
1315
  // which is why this entry uses \`startStdioServer\` rather than wiring a
1060
- // connection directly.
1316
+ // connection directly.`
1317
+ : `// Contrast with \`main.ts\`, where the data head is a socket whose port it
1318
+ // prints. Here it owns stdio, and as there, no LSP connection drives the
1319
+ // workspace initialization, so \`startStdioServer\` brings the workspace up
1320
+ // before it listens.`}
1061
1321
  //
1062
1322
  // Everything here runs at module scope, so this file is an executable rather
1063
1323
  // than a library entry — import \`./index.js\` instead to compose the language.
@@ -1065,7 +1325,7 @@ function dataServerMainFile(composition) {
1065
1325
  ${importList(['NodeFileSystem', 'startStdioServer'], '@hydranium/core/node', columns)}
1066
1326
  import { DataServer } from '@hydranium/data-server';
1067
1327
  // The TRANSFER root${plural}, not the AST one${plural} — same reasoning as \`main.ts\`.
1068
- ${importList(roots, './language-server/generated-hydranium/transfer-model.js', columns, true)}
1328
+ ${importList(roots, memberPackageName(composition, 'protocol'), columns, true)}
1069
1329
  import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1070
1330
 
1071
1331
  const { shared } = create__NAME__Services({ ...NodeFileSystem });
@@ -1113,7 +1373,7 @@ function servicesTest(composition) {
1113
1373
  // is missing from the composition.
1114
1374
 
1115
1375
  import { describe, expect, it } from 'vitest';
1116
- import { createServices } from '../src/services.js';
1376
+ import { createServices } from '../src/node/services.js';
1117
1377
 
1118
1378
  describe('__NAME__ services', () => {
1119
1379
  it('composes the DI tree and registers ${title}', () => {
@@ -1154,13 +1414,9 @@ const SERIALIZATION_SUITE = `describe('__GRAMMAR__ serialization', () => {
1154
1414
 
1155
1415
  it('emits the same text from a transfer model, whose references are plain strings', async () => {
1156
1416
  const { __GRAMMAR__ } = createServices();
1157
- const model: Transfer__ENTRY_RULE__ = {
1158
- $type: '__ENTRY_RULE__',
1159
- nodes: [
1160
- { $type: '__NODE_RULE__', name: 'first', target: 'second' },
1161
- { $type: '__NODE_RULE__', name: 'second' }
1162
- ]
1163
- };
1417
+ const model = transferNode(Transfer__ENTRY_RULE__, {
1418
+ nodes: __TRANSFER_NODES__
1419
+ });
1164
1420
 
1165
1421
  expect(await __GRAMMAR__.serializer.Serializer.serializeTransfer(model)).toBe(source);
1166
1422
  });
@@ -1178,11 +1434,23 @@ const SERIALIZATION_SUITE = `describe('__GRAMMAR__ serialization', () => {
1178
1434
  function serializationTest(composition) {
1179
1435
  const columns = columnsFor(composition);
1180
1436
  const astTypes = composition.grammars.map(grammar => grammar.entryRule);
1181
- const transferTypes = composition.grammars.map(grammar => `${grammar.entryRule} as Transfer${grammar.entryRule}`);
1437
+ const transferConstants = composition.grammars.flatMap(grammar => [
1438
+ `${grammar.entryRule} as Transfer${grammar.entryRule}`,
1439
+ grammar.nodeRule
1440
+ ]);
1441
+ const suite = (grammar) => {
1442
+ const nodes = [
1443
+ `transferNode(${grammar.nodeRule}, { name: 'first', target: 'second' })`,
1444
+ `transferNode(${grammar.nodeRule}, { name: 'second' })`
1445
+ ];
1446
+ const single = `[${nodes.join(', ')}]`;
1447
+ const literal = ` nodes: ${single}`.length <= columns ? single : `[\n${nodes.map(node => ` ${node}`).join(',\n')}\n ]`;
1448
+ return render(SERIALIZATION_SUITE, composition, grammar).replace('__TRANSFER_NODES__', literal);
1449
+ };
1182
1450
  const text = `// Round-trips each grammar through its serializer: parse the source, serialize
1183
1451
  // the model, compare the text. The serializer is the parser's inverse, so this
1184
- // is the assertion that keeps \`ModelService.update\` / \`save\` writing files the
1185
- // language server can read back.
1452
+ // is the assertion that keeps a client session's \`update\` / \`save\` writing
1453
+ // files the language server can read back.
1186
1454
  //
1187
1455
  // The transfer case is the one that catches the mistake worth catching.
1188
1456
  // \`ModelService.modelToText\` short-circuits only a RAW STRING, so a typed model
@@ -1192,10 +1460,11 @@ function serializationTest(composition) {
1192
1460
  import { parseHelper } from '@hydranium/core/testing';
1193
1461
  import { describe, expect, it } from 'vitest';
1194
1462
  ${importList(astTypes, '../src/language-server/ast.js', columns, true)}
1195
- ${importList(transferTypes, '../src/language-server/generated-hydranium/transfer-model.js', columns, true)}
1196
- import { createServices } from '../src/services.js';
1463
+ ${importList(transferConstants, memberPackageName(composition, 'protocol'), columns)}
1464
+ import { createServices } from '../src/node/services.js';
1465
+ import { transferNode } from './generated-hydranium/transfer-builder.js';
1197
1466
 
1198
- ${composition.grammars.map(grammar => render(SERIALIZATION_SUITE, composition, grammar)).join('\n\n')}
1467
+ ${composition.grammars.map(suite).join('\n\n')}
1199
1468
  `;
1200
1469
  return text;
1201
1470
  }
@@ -1272,14 +1541,9 @@ const LINKING_SUITE = `describe('__GRAMMAR__ linking', () => {
1272
1541
  });
1273
1542
  });`;
1274
1543
  /**
1275
- * The validation tier, asserting the FRAMEWORK's diagnostics rather than an
1276
- * adopter rule.
1277
- *
1278
- * The scaffold binds no `validation.checks`, so a test over an adopter check
1279
- * would have to invent one and would then assert the test's own fixture rather
1280
- * than the language. What a scaffolded project really guarantees on day one is
1281
- * that a dangling reference is reported, which is a linker diagnostic — and
1282
- * that is the tier a new adopter breaks third.
1544
+ * The validation tier: the linker's diagnostic for a dangling reference, the
1545
+ * tier a new adopter breaks third, and the scaffold's one check, a warning on
1546
+ * a repeated name.
1283
1547
  */
1284
1548
  const VALIDATING_SUITE = `describe('__GRAMMAR__ validation', () => {
1285
1549
  it('reports nothing for a well-formed document', async () => {
@@ -1306,6 +1570,21 @@ const VALIDATING_SUITE = `describe('__GRAMMAR__ validation', () => {
1306
1570
  expect(diagnostics[0].severity).toBe(DiagnosticSeverity.Error);
1307
1571
  expect(diagnostics[0].message).toContain('absent');
1308
1572
  });
1573
+
1574
+ it('warns on each node named like one before it', async () => {
1575
+ const { shared, __GRAMMAR__ } = createServices();
1576
+
1577
+ const document = await parseHelper<__ENTRY_RULE__>(__GRAMMAR__)('node first\\nnode second\\nnode first', {
1578
+ documentUri: 'file:///duplicate.__EXTENSION__'
1579
+ });
1580
+ await shared.workspace.DocumentBuilder.build([document], { validation: true });
1581
+
1582
+ const diagnostics = document.diagnostics ?? [];
1583
+ expect(diagnostics).toHaveLength(1);
1584
+ expect(diagnostics[0].severity).toBe(DiagnosticSeverity.Warning);
1585
+ expect(diagnostics[0].message).toBe("A node named 'first' is already declared.");
1586
+ expect(diagnostics[0].range.start.line).toBe(2);
1587
+ });
1309
1588
  });`;
1310
1589
  /** Assemble one grammar-derived test file: a fixed preamble plus one suite per grammar. */
1311
1590
  function grammarTest(composition, header, imports, suite) {
@@ -1316,7 +1595,7 @@ function grammarTest(composition, header, imports, suite) {
1316
1595
  import { parseHelper } from '@hydranium/core/testing';
1317
1596
  import { describe, expect, it } from 'vitest';
1318
1597
  ${imports.join('\n')}${imports.length ? '\n' : ''}${importList(astTypes, '../src/language-server/ast.js', columns, true)}
1319
- import { createServices } from '../src/services.js';
1598
+ import { createServices } from '../src/node/services.js';
1320
1599
 
1321
1600
  ${composition.grammars.map(grammar => render(suite, composition, grammar)).join('\n\n')}
1322
1601
  `;
@@ -1334,15 +1613,15 @@ const LINKING_HEADER = `// Tier two: does my cross-reference resolve.
1334
1613
  // multi-file workspace depends on and what a single-document test cannot see.`;
1335
1614
  const VALIDATING_HEADER = `// Tier three: does a broken model get reported.
1336
1615
  //
1337
- // These are the FRAMEWORK's own linker diagnostics, not adopter checks — the
1338
- // scaffold binds no \`validation.checks\`, and a test over an invented one would
1339
- // assert its own fixture rather than the language. Bind a check in your
1340
- // language module and assert it here alongside these.`;
1616
+ // A dangling reference is the FRAMEWORK's own linker diagnostic; a repeated
1617
+ // name is reported by the scaffold's own validation check. Bind a further
1618
+ // check in your language module and assert it here alongside these.`;
1341
1619
  /** The README, assembled from lines to avoid escaping the Markdown code fences. */
1342
1620
  function readme(composition) {
1343
1621
  const multi = composition.grammars.length > 1;
1344
1622
  const data = composition.heads.includes('data');
1345
1623
  const primaryExtension = composition.grammars[0].extensions[0];
1624
+ const diagramCount = composition.grammars.filter(grammar => grammar.diagram).length;
1346
1625
  const grammarBullets = composition.grammars.map(grammar => `- \`src/grammar/${grammar.grammarId}.langium\` — the \`${grammar.grammar}\` grammar (.${grammar.extensions.join(', .')})`);
1347
1626
  const lines = [
1348
1627
  '# __NAME__',
@@ -1351,24 +1630,15 @@ function readme(composition) {
1351
1630
  '',
1352
1631
  '## Getting started',
1353
1632
  '',
1354
- // Conditional on the pin this scaffold actually carries — see
1355
- // `UNPUBLISHED_FRAMEWORK_VERSION`.
1356
- ...(composition.frameworkVersion === UNPUBLISHED_FRAMEWORK_VERSION
1357
- ? [
1358
- '> **Pre-publish note.** `@hydranium/*` is not on npm yet, so the `0.0.0`',
1359
- '> pins below are placeholders and `npm install` will fail with a 404 until',
1360
- '> the framework is released. Until then, supply the packages from a local',
1361
- '> framework checkout with [yalc](https://github.com/wclr/yalc) — a plain',
1362
- '> `file:` path or `npm link` is not enough, because the framework packages',
1363
- '> depend on each other by version and npm would try to fetch those from the',
1364
- '> registry too.',
1365
- ''
1366
- ]
1367
- : []),
1633
+ '`langium generate` fails on Node 24.20 and later with `TypeError: Invalid URL`',
1634
+ '([tdegrunt/jsonschema#423](https://github.com/tdegrunt/jsonschema/issues/423)),',
1635
+ 'so build on Node 22.',
1636
+ '',
1368
1637
  '```bash',
1369
1638
  'npm install',
1370
1639
  'npm run langium:generate # generate the AST from the grammar',
1371
1640
  'npm run build # generate + compile to lib/',
1641
+ 'npm run watch # regenerate and recompile on every grammar or source change',
1372
1642
  'npm test # typecheck the tests, then run them',
1373
1643
  '```',
1374
1644
  '',
@@ -1379,25 +1649,26 @@ function readme(composition) {
1379
1649
  // nowhere else.
1380
1650
  '```bash',
1381
1651
  '# Grammar / AST reflection',
1382
- 'npx hydranium-cli reflect --services ./lib/services.js',
1652
+ 'npx hydranium-cli reflect --services ./lib/node/services.js',
1383
1653
  '',
1384
1654
  '# Grammar-convention lint (CI gate)',
1385
- 'npx hydranium-cli lint-grammar --services ./lib/services.js',
1655
+ 'npx hydranium-cli lint-grammar --services ./lib/node/services.js',
1386
1656
  '',
1387
1657
  '# Validate a workspace of model files (non-zero exit on errors)',
1388
- 'npx hydranium-cli validate --services ./lib/services.js <workspace-dir>',
1658
+ 'npx hydranium-cli validate --services ./lib/node/services.js ../workspace',
1389
1659
  ...(data
1390
1660
  ? [
1391
1661
  '',
1392
1662
  '# Data-head operations. `--server` is a command line the CLI spawns and then',
1393
1663
  "# drives the data protocol over the child's stdin/stdout, so it has to name",
1394
- '# `data-server-main.js` — `main.js` gives stdio to LSP and answers these',
1395
- '# methods with "Unhandled method".',
1664
+ ...(composition.heads.includes('lsp')
1665
+ ? ['# `data-server-main.js` — `main.js` gives stdio to LSP and answers these', '# methods with "Unhandled method".']
1666
+ : ['# `data-server-main.js` — `main.js` serves the data head on a socket.']),
1396
1667
  '#',
1397
1668
  '# The workspace goes to the ENTRY, not to `--cwd`: `--cwd` re-roots the child,',
1398
1669
  '# so a relative entry path is refused by name (an absolute one is fine).',
1399
- 'npx hydranium-cli projects --server "node ./lib/data-server-main.js <workspace-dir>"',
1400
- `npx hydranium-cli query --server "node ./lib/data-server-main.js <workspace-dir>" --uri <file:// URI of a .${primaryExtension} file>`
1670
+ 'npx hydranium-cli projects --server "node ./lib/data-server-main.js ../workspace"',
1671
+ `npx hydranium-cli query --server "node ./lib/data-server-main.js ../workspace" --uri <file:// URI of ../workspace/nodes.${primaryExtension}>`
1401
1672
  ]
1402
1673
  : []),
1403
1674
  '```',
@@ -1407,9 +1678,12 @@ function readme(composition) {
1407
1678
  ...grammarBullets,
1408
1679
  ...(multi ? ['- `src/grammar/common.langium` — shared terminals, imported by each grammar (not a language)'] : []),
1409
1680
  '- `src/language-server/__PROJECT_ID__-module.ts` — `create__NAME__Services` DI wiring',
1410
- ...composition.grammars.map(grammar => `- \`src/language-server/${grammar.grammarId}-serializer.ts\` — emits \`${grammar.grammar}\` back to text (the framework defaults this to a throw)`),
1411
- '- `src/services.ts` — zero-arg `createServices()` for the headless CLI',
1412
- '- `src/index.ts` — the package entry (`main`): DI factory + generated AST',
1681
+ ...composition.grammars.flatMap(grammar => [
1682
+ `- \`src/language-server/${grammar.grammarId}-serializer.ts\` — emits \`${grammar.grammar}\` back to text (the framework defaults this to a throw)`,
1683
+ `- \`src/language-server/${grammar.grammarId}-validation.ts\` — the \`${grammar.grammar}\` checks: a warning on a repeated name`
1684
+ ]),
1685
+ "- `src/node/services.ts` — zero-arg `createServices()` for the headless CLI, the package's `./node` entry",
1686
+ `- \`src/index.ts\` — the package root, loadable in a browser worker: DI factory + generated AST${diagramCount === 0 ? '' : diagramCount === 1 ? ' + diagram module' : ' + diagram modules'}`,
1413
1687
  `- \`src/main.ts\` — starts ${composition.heads.join(' + ')}, the \`__PROJECT_ID__\` bin entry`,
1414
1688
  ...(data
1415
1689
  ? [
@@ -1419,7 +1693,8 @@ function readme(composition) {
1419
1693
  : []),
1420
1694
  ...composition.grammars
1421
1695
  .filter(grammar => grammar.diagram)
1422
- .map(grammar => `- \`src/glsp/${grammar.grammarId}/\` — the \`${grammar.grammar}\` diagram: type ids, state, storage, submission handler, GModel factory, configuration, create-node handler, DI module`),
1696
+ .map(grammar => `- \`src/glsp/${grammar.grammarId}/\` — the \`${grammar.grammar}\` diagram: state, storage, submission handler, GModel factory, configuration, create-node handler, DI module`),
1697
+ `- \`../protocol/\` — the \`${memberPackageName(composition, 'protocol')}\` package: what this server and its clients both import (language ids, ${headPortConstants(composition).length === 0 ? '' : composition.heads.includes('lsp') ? 'port commands, ' : 'port variables, '}${composition.grammars.some(grammar => grammar.diagram) ? 'diagram ids, ' : ''}the transfer model), written partly by \`npm run generate\``,
1423
1698
  '- `test/services.test.ts` — the DI tree composes; grows as your language does',
1424
1699
  '- `test/parsing.test.ts` / `linking.test.ts` / `validating.test.ts` — the three tiers a new language breaks first',
1425
1700
  '- `test/serialization.test.ts` — each grammar round-trips through its serializer',
@@ -1472,6 +1747,24 @@ function readme(composition) {
1472
1747
  'atomic set and depends on a single physical copy, so a floating range can',
1473
1748
  'silently resolve a second one.',
1474
1749
  '',
1750
+ '`vscode-languageserver` is pinned to `10.0.1`, and',
1751
+ '`vscode-languageserver-protocol` and `vscode-jsonrpc` to the `3.18.1` and',
1752
+ '`9.0.0` it pins, so Langium, the LSP connection and the framework share one',
1753
+ 'copy of each. With two, an error a Langium handler returns, such as a request',
1754
+ 'for a document the server does not have, reaches the client as a result, and a',
1755
+ 'framework error your own LSP handler throws loses its code. The Langium 4.4',
1756
+ 'upgrade',
1757
+ '([eclipse-emfcloud/hydranium#142](https://github.com/eclipse-emfcloud/hydranium/issues/142))',
1758
+ 'replaces these pins.',
1759
+ '',
1760
+ ...(pinsVitest(composition)
1761
+ ? [
1762
+ '`vitest` is held below 4.1, whose peer set crashes the npm every Node 22',
1763
+ 'release bundles. Raise it once every npm that installs this project is',
1764
+ '11.6 or later.',
1765
+ ''
1766
+ ]
1767
+ : []),
1475
1768
  '## If your repo gates license headers',
1476
1769
  '',
1477
1770
  'The emitted `.ts` files carry no copyright header — the scaffold cannot know',
@@ -1490,189 +1783,49 @@ function readme(composition) {
1490
1783
  /**
1491
1784
  * The GLSP files for ONE grammar's diagram.
1492
1785
  *
1493
- * Per grammar rather than per project because a diagram type has exactly one
1494
- * grammar — `AbstractHydraniumGlspDiagramModule.declareLanguage()` returns that
1495
- * grammar's `LanguageMetaData`, and it is bound on the SESSION container so a
1496
- * grammar with no diagram can sit on the same server.
1786
+ * Per grammar rather than per project because the state, storage and GModel
1787
+ * factory are typed over that grammar's model, and a grammar with no diagram
1788
+ * can sit on the same server.
1497
1789
  *
1498
1790
  * The index and the computed-bounds handler are framework classes used
1499
1791
  * unmodified; storage and the submission handler are thin typed subclasses,
1500
1792
  * which is where an adopter's own load/save and log formatting land.
1501
1793
  *
1502
- * The set is EDITABLE rather than read-only: one create-node handler, registered
1503
- * on the module. GLSP's own `DiagramModule` binds no handler that mutates a
1504
- * source model, so without it the head renders and answers while telling the
1505
- * client it may change nothing — which reads as a broken diagram rather than as a
1506
- * deliberate viewer.
1794
+ * The set is EDITABLE rather than read-only: a create-node and a delete handler,
1795
+ * registered on the module. GLSP's own `DiagramModule` binds no handler that
1796
+ * mutates a source model, so without them the head renders and answers while
1797
+ * telling the client it may change nothing — which reads as a broken diagram
1798
+ * rather than as a deliberate viewer.
1507
1799
  */
1508
1800
  function glspFiles(composition, grammar) {
1509
1801
  const columns = columnsFor(composition);
1510
- const upper = screamingSnake(grammar.grammarId);
1511
- const dir = `src/glsp/${grammar.grammarId}`;
1512
- const render = (text) => grammarTier(project(text, composition), grammar);
1513
- const types = `// GLSP diagram-type and element-type ids for the __GRAMMAR__ diagram.
1514
- //
1515
- // **Authoritative half of a client/server contract.** Every id here has to be
1516
- // registered on the client too: sprotty's registries are exact-key maps with no
1517
- // prefix fallback, so an id the client does not know yields an element with none
1518
- // of a node's features, rendered by \`MissingView\` with only a
1519
- // \`no registered view for type '…'\` console warning. Nothing fails server-side.
1520
- //
1521
- // The ids stay namespaced under the GLSP defaults (\`node:\` / \`edge:\`) so a
1522
- // reader can tell a node id from an edge id at a glance.
1523
-
1524
- import { DefaultTypes } from '@eclipse-glsp/server';
1525
-
1526
- /**
1527
- * The GLSP diagram type — the string GLSP routes every per-diagram-type request
1528
- * by. Mirrored by the client; a mismatch silently DROPS the request rather than
1529
- * reporting an unknown diagram type. Same value as the language id, so the two
1530
- * cannot drift apart as a diagram gains element types.
1531
- */
1532
- export const ${upper}_DIAGRAM_TYPE = '__LANGUAGE_ID__';
1533
-
1534
- /** A \`__NODE_RULE__\` — the starter grammar's one named, referenceable node. */
1535
- export const ${upper}_NODE_TYPE = \`\${DefaultTypes.NODE}:__GRAMMAR_ID__-node\`;
1536
-
1537
- /** A resolved \`target\` reference, drawn as a connection between two nodes. */
1538
- export const ${upper}_EDGE_TYPE = \`\${DefaultTypes.EDGE}:__GRAMMAR_ID__-target\`;
1539
- `;
1540
- const state = `// GLSP state for the __GRAMMAR__ diagram.
1802
+ const fixed = (file) => grammarTemplate(`server/src/glsp/__GRAMMAR_ID__/${file}`, composition, grammar);
1803
+ const computed = (file, text) => ({
1804
+ path: `server/src/glsp/${grammar.grammarId}/${file}`,
1805
+ content: render(text, composition, grammar)
1806
+ });
1807
+ const configuration = `// Diagram configuration for the __GRAMMAR__ diagram.
1541
1808
  //
1542
- // \`FullTextHydraniumGlspState\` is the simplest of the framework source-model
1543
- // strategies (the others project a structured transfer model, over one document
1544
- // or several): the source model is the whole document text, serialised through
1545
- // the per-URI \`Serializer\` and round-tripped by re-parsing. Both seams resolve
1546
- // through shared services, so narrowing the root type is all an adopter adds.
1809
+ // **A hint is \`true\` only where a handler backs it.** The starter
1810
+ // __GRAMMAR__CreateNodeOperationHandler offers creation through the tool palette,
1811
+ // which GLSP assembles from the create handlers' trigger actions — there is no
1812
+ // \`creatable\` hint. __GRAMMAR__DeleteOperationHandler backs \`deletable\` on a
1813
+ // node and an edge; a node of another document stays undeletable, since this
1814
+ // diagram does not own it. Nothing backs reparent / reposition / resize, so
1815
+ // declaring one would offer a gesture whose operation the server rejects: a worse
1816
+ // failure than the tool being absent. Turn a hint on in the same change that adds
1817
+ // its handler.
1547
1818
  //
1548
- // It cannot field-merge — every concurrent edit on a whole-document model is a
1549
- // same-document collision, so undo / redo degrade to drop-on-divergence. Move to
1550
- // \`ReconcilingTransferHydraniumGlspState\` when you need field-level undo.
1819
+ // \`needsClientLayout\` is \`true\` and \`layoutKind\` is \`NONE\`: the starter grammar
1820
+ // persists no bounds, so the client measures and places everything. That is also
1821
+ // why \`ChangeBoundsOperation\` is a poor second handler to add — with nowhere in
1822
+ // the grammar to write a position, a move never reaches the text and is lost on
1823
+ // the next reload.
1551
1824
 
1552
- import { FullTextHydraniumGlspState } from '@hydranium/glsp-server';
1825
+ import { type GModelElementConstructor } from '@eclipse-glsp/graph';
1826
+ ${importList(['type DiagramConfiguration', 'type EdgeTypeHint', 'ServerLayoutKind', 'type ShapeTypeHint', 'getDefaultMapping'], '@eclipse-glsp/server', columns)}
1553
1827
  import { injectable } from 'inversify';
1554
- import type { __ENTRY_RULE__ } from '../../language-server/ast.js';
1555
-
1556
- @injectable()
1557
- export class __GRAMMAR__GlspState extends FullTextHydraniumGlspState<__ENTRY_RULE__> {}
1558
- `;
1559
- const storage = `// Source-model storage for the __GRAMMAR__ diagram, inheriting both framework
1560
- // defaults: \`loadSourceModel\` (open + settle + \`setSourceRoot\`) and
1561
- // \`saveSourceModel\` (through \`ModelService.save\` → the per-URI \`Serializer\` →
1562
- // the multi-client text store → \`WritableFileSystemProvider\`).
1563
- //
1564
- // The subclass exists so a bespoke load or save has a stable place to land.
1565
-
1566
- import { type FullTextSourceModel, HydraniumGlspStorage } from '@hydranium/glsp-server';
1567
- import { injectable } from 'inversify';
1568
- import type { __ENTRY_RULE__ } from '../../language-server/ast.js';
1569
-
1570
- @injectable()
1571
- export class __GRAMMAR__GlspStorage extends HydraniumGlspStorage<__ENTRY_RULE__, FullTextSourceModel> {}
1572
- `;
1573
- const submission = `// Submission handler for the __GRAMMAR__ diagram.
1574
- //
1575
- // Inherits the framework's \`readyEvent = IntegrityService.SettledState\`, which
1576
- // is load-bearing rather than incidental: the GModel factory resolves
1577
- // \`target.ref\`, so it needs a fully-linked AST. Without the gate those reads
1578
- // fire mid-build and warn about resolution before scopes are computed.
1579
- //
1580
- // Only \`formatSourceRoot\` is overridden, so the submit log names the model and
1581
- // its node count instead of a bare \`$type\`.
1582
-
1583
- import { ModelState } from '@eclipse-glsp/server';
1584
- import { type FullTextSourceModel, HydraniumGlspSubmissionHandler } from '@hydranium/glsp-server';
1585
- import { inject, injectable } from 'inversify';
1586
- import type { __ENTRY_RULE__ } from '../../language-server/ast.js';
1587
- import type { __GRAMMAR__GlspState } from './state.js';
1588
-
1589
- @injectable()
1590
- export class __GRAMMAR__SubmissionHandler extends HydraniumGlspSubmissionHandler<__ENTRY_RULE__, FullTextSourceModel> {
1591
- @inject(ModelState) declare protected modelState: __GRAMMAR__GlspState;
1592
-
1593
- protected override formatSourceRoot(root: __ENTRY_RULE__ | undefined): string {
1594
- return root ? \`__ENTRY_RULE__ nodes=\${root.nodes.length}\` : 'none';
1595
- }
1596
- }
1597
- `;
1598
- const factory = `// AST → GModel for the __GRAMMAR__ diagram: one node per \`__NODE_RULE__\`, one
1599
- // edge per resolved \`target\` reference.
1600
- //
1601
- // Ids come from the index rather than being composed here, so the id strategy
1602
- // stays in one place. Nodes are emitted before edges, because a GLSP edge
1603
- // pointing at an id that does not exist fails client-side with a far less
1604
- // obvious error than a missing edge. An unresolved reference is SKIPPED rather
1605
- // than treated as an error: a dangling reference is ordinary editing state, and
1606
- // the LSP head already reports it as a diagnostic.
1607
-
1608
- import { DefaultTypes, GEdge, GGraph, GLabel, type GModelFactory, GNode, ModelState } from '@eclipse-glsp/server';
1609
- import { inject, injectable } from 'inversify';
1610
- import type { __ENTRY_RULE__ } from '../../language-server/ast.js';
1611
- import { ${upper}_EDGE_TYPE, ${upper}_NODE_TYPE } from './types.js';
1612
- import type { __GRAMMAR__GlspState } from './state.js';
1613
-
1614
- @injectable()
1615
- export class __GRAMMAR__GModelFactory implements GModelFactory {
1616
- @inject(ModelState) protected readonly modelState!: __GRAMMAR__GlspState;
1617
-
1618
- createModel(): void {
1619
- const root = this.modelState.sourceRoot;
1620
- const graph = GGraph.builder().id(this.modelState.sourceUri).build();
1621
- if (root) {
1622
- this.buildGraph(root, graph);
1623
- }
1624
- this.modelState.updateRoot(graph);
1625
- }
1626
-
1627
- protected buildGraph(root: __ENTRY_RULE__, graph: GGraph): void {
1628
- for (const node of root.nodes) {
1629
- const id = this.modelState.index.createId(node);
1630
- graph.children.push(
1631
- GNode.builder()
1632
- .id(id)
1633
- .type(${upper}_NODE_TYPE)
1634
- .add(GLabel.builder().id(\`\${id}_name\`).text(node.name).type(DefaultTypes.LABEL).build())
1635
- .build()
1636
- );
1637
- }
1638
- for (const node of root.nodes) {
1639
- const target = node.target?.ref;
1640
- if (!target) {
1641
- continue;
1642
- }
1643
- const sourceId = this.modelState.index.createId(node);
1644
- graph.children.push(
1645
- GEdge.builder()
1646
- .id(\`\${sourceId}_target\`)
1647
- .type(${upper}_EDGE_TYPE)
1648
- .sourceId(sourceId)
1649
- .targetId(this.modelState.index.createId(target))
1650
- .build()
1651
- );
1652
- }
1653
- }
1654
- }
1655
- `;
1656
- const configuration = `// Diagram configuration for the __GRAMMAR__ diagram.
1657
- //
1658
- // **Every hint is \`false\`, and that is not the same as read-only.** The starter
1659
- // __GRAMMAR__CreateNodeOperationHandler makes this diagram editable through the
1660
- // tool palette, which GLSP assembles from the create handlers' trigger actions —
1661
- // there is no \`creatable\` hint. What the hints govern is delete / reparent /
1662
- // reposition / resize, and nothing backs those, so declaring one would offer a
1663
- // gesture whose operation the server rejects: a worse failure than the tool being
1664
- // absent. Turn a hint on in the same change that adds its handler.
1665
- //
1666
- // \`needsClientLayout\` is \`true\` and \`layoutKind\` is \`NONE\`: the starter grammar
1667
- // persists no bounds, so the client measures and places everything. That is also
1668
- // why \`ChangeBoundsOperation\` is a poor second handler to add — with nowhere in
1669
- // the grammar to write a position, a move never reaches the text and is lost on
1670
- // the next reload.
1671
-
1672
- import { type GModelElementConstructor } from '@eclipse-glsp/graph';
1673
- ${importList(['type DiagramConfiguration', 'type EdgeTypeHint', 'ServerLayoutKind', 'type ShapeTypeHint', 'getDefaultMapping'], '@eclipse-glsp/server', columns)}
1674
- import { injectable } from 'inversify';
1675
- import { ${upper}_EDGE_TYPE, ${upper}_NODE_TYPE } from './types.js';
1828
+ import { __GRAMMAR_ID_CONST___EDGE_TYPE, __GRAMMAR_ID_CONST___EXTERNAL_NODE_TYPE, __GRAMMAR_ID_CONST___NODE_TYPE } from '__PROTOCOL_PACKAGE__';
1676
1829
 
1677
1830
  @injectable()
1678
1831
  export class __GRAMMAR__DiagramConfiguration implements DiagramConfiguration {
@@ -1684,7 +1837,14 @@ export class __GRAMMAR__DiagramConfiguration implements DiagramConfiguration {
1684
1837
 
1685
1838
  readonly shapeTypeHints: ShapeTypeHint[] = [
1686
1839
  {
1687
- elementTypeId: ${upper}_NODE_TYPE,
1840
+ elementTypeId: __GRAMMAR_ID_CONST___NODE_TYPE,
1841
+ deletable: true,
1842
+ reparentable: false,
1843
+ repositionable: false,
1844
+ resizable: false
1845
+ },
1846
+ {
1847
+ elementTypeId: __GRAMMAR_ID_CONST___EXTERNAL_NODE_TYPE,
1688
1848
  deletable: false,
1689
1849
  reparentable: false,
1690
1850
  repositionable: false,
@@ -1694,143 +1854,69 @@ export class __GRAMMAR__DiagramConfiguration implements DiagramConfiguration {
1694
1854
 
1695
1855
  readonly edgeTypeHints: EdgeTypeHint[] = [
1696
1856
  {
1697
- elementTypeId: ${upper}_EDGE_TYPE,
1698
- deletable: false,
1857
+ elementTypeId: __GRAMMAR_ID_CONST___EDGE_TYPE,
1858
+ deletable: true,
1699
1859
  repositionable: false,
1700
1860
  routable: false,
1701
- sourceElementTypeIds: [${upper}_NODE_TYPE],
1702
- targetElementTypeIds: [${upper}_NODE_TYPE]
1861
+ sourceElementTypeIds: [__GRAMMAR_ID_CONST___NODE_TYPE],
1862
+ targetElementTypeIds: [__GRAMMAR_ID_CONST___NODE_TYPE, __GRAMMAR_ID_CONST___EXTERNAL_NODE_TYPE]
1703
1863
  }
1704
1864
  ];
1705
1865
  }
1706
- `;
1707
- const createHandler = `// The starter operation handler for the __GRAMMAR__ diagram: the tool-palette
1708
- // entry that creates a \`__NODE_RULE__\`.
1709
- //
1710
- // **Deleting this file and its \`configureOperationHandlers\` registration in
1711
- // \`diagram-module.ts\` gives a read-only viewer**, and nothing else has to change
1712
- // — creation is offered through the palette rather than through a type hint, so
1713
- // every hint in \`diagram-configuration.ts\` is already \`false\`. The scaffold emits
1714
- // the editable direction because that asymmetry runs one way: editable →
1715
- // read-only is a deletion the compiler checks, while read-only → editable is
1716
- // authoring against a seam you have not used yet.
1717
- //
1718
- // **It composes TEXT rather than mutating the AST.** The source model of
1719
- // \`FullTextHydraniumGlspState\` is the document text, and reading it back through
1720
- // \`state.sourceModel\` serialises the AST through the per-URI \`Serializer\`, which
1721
- // this scaffold does not bind — so that getter throws until you do. Appending a
1722
- // declaration to the text the parser last read needs no serializer, which is what
1723
- // makes a scaffolded diagram editable on day one. Bind a \`Serializer\` at
1724
- // \`services.serializer.Serializer\` and this becomes a
1725
- // \`HydraniumGlspRecordingCommand\` over \`state.sourceModel\` instead — the same
1726
- // binding the diagram's own save action needs.
1727
- //
1728
- // **The drop location is discarded.** \`needsClientLayout\` is \`true\` and the
1729
- // starter grammar persists no bounds, so there is nowhere to put a coordinate: the
1730
- // node is appended at the end of the document and the client places it.
1731
- //
1732
- // Like \`types.ts\`, \`gmodel-factory.ts\` and \`diagram-configuration.ts\`, this file
1733
- // knows the starter grammar's concrete syntax — the \`node\` keyword below is that
1734
- // grammar's. Replacing the grammar means replacing these four together.
1735
-
1736
- import { type Command, type CreateNodeOperation, JsonCreateNodeOperationHandler, type MaybePromise } from '@eclipse-glsp/server';
1737
- import { findNextUnique } from '@hydranium/protocol';
1738
- import { injectable } from 'inversify';
1739
- import { ${upper}_NODE_TYPE } from './types.js';
1740
- import type { __GRAMMAR__GlspState } from './state.js';
1741
-
1742
- /** Proposed name for a new node, uniquified against the ones the document already has. */
1743
- const NODE_NAME_STEM = 'Node';
1744
-
1745
- @injectable()
1746
- export class __GRAMMAR__CreateNodeOperationHandler extends JsonCreateNodeOperationHandler {
1747
- declare protected modelState: __GRAMMAR__GlspState;
1748
-
1749
- /** The palette's word for the thing it creates, so a noun rather than an action. */
1750
- override readonly label = '__NODE_RULE__';
1751
- elementTypeIds = [${upper}_NODE_TYPE];
1752
-
1753
- override createCommand(operation: CreateNodeOperation): MaybePromise<Command | undefined> {
1754
- if (!this.elementTypeIds.includes(operation.elementTypeId)) {
1755
- return undefined;
1756
- }
1757
- const state = this.modelState;
1758
- const before = this.documentText();
1759
- const after = this.withNode(
1760
- before,
1761
- findNextUnique(
1762
- NODE_NAME_STEM,
1763
- state.sourceRoot.nodes.map(node => node.name)
1764
- )
1765
- );
1766
- // Whole-document undo, which is all a full-text source model can offer: it
1767
- // has exactly one field, so there is nothing to merge a concurrent edit into.
1768
- return {
1769
- execute: () => state.updateSourceModel({ text: after }),
1770
- undo: () => state.updateSourceModel({ text: before }),
1771
- redo: () => state.updateSourceModel({ text: after })
1772
- };
1773
- }
1774
-
1775
- /** The text the captured source root was parsed from — the baseline an edit appends to. */
1776
- protected documentText(): string {
1777
- return this.modelState.sourceRoot.$document?.textDocument.getText() ?? '';
1778
- }
1779
-
1780
- /** \`text\` with one more node declaration, under exactly one trailing newline. */
1781
- protected withNode(text: string, name: string): string {
1782
- const body = text.trimEnd();
1783
- const declaration = \`node \${name}\`;
1784
- return body.length === 0 ? \`\${declaration}\\n\` : \`\${body}\\n\${declaration}\\n\`;
1785
- }
1786
- }
1787
1866
  `;
1788
1867
  const module = `// GLSP diagram module for __GRAMMAR__ — the DI wiring of one diagram type.
1789
1868
  //
1790
- // \`declareLanguage\` is the multi-grammar seam: it binds the grammar this diagram
1791
- // edits on the SESSION container, so \`modelState.diagramLanguage\` and the
1792
- // per-language lookups resolve to __LANGUAGE_ID__. That is what stops one
1793
- // diagram type from fighting over a process-wide binding when a project holds
1794
- // several grammars — a grammar with no diagram is registered on the same server.
1795
- //
1796
1869
  // \`configureActionHandlers\` REBINDS rather than adds: GLSP's own
1797
1870
  // \`DiagramModule\` already registers \`ComputedBoundsActionHandler\`, and two
1798
1871
  // handlers for one action would both run.
1799
1872
  //
1800
1873
  // \`configureOperationHandlers\` ADDS: GLSP's default pair
1801
1874
  // (\`CompoundOperationHandler\` and \`LayoutOperationHandler\`) mutates no source
1802
- // model, so the starter create handler is what makes this diagram editable at all.
1875
+ // model, so the starter create and delete handlers are what make this diagram
1876
+ // editable at all.
1803
1877
 
1804
1878
  ${importList([
1805
1879
  'ActionHandlerConstructor',
1806
1880
  'BindingTarget',
1881
+ 'ComputedBoundsAction',
1807
1882
  'DiagramConfiguration',
1808
1883
  'GModelFactory',
1809
1884
  'GModelIndex',
1885
+ 'GModelRoot',
1810
1886
  'InstanceMultiBinding',
1811
1887
  'ModelState',
1812
1888
  'ModelSubmissionHandler',
1889
+ 'ModelValidator',
1813
1890
  'OperationHandlerConstructor',
1814
1891
  'SourceModelStorage'
1815
1892
  ], '@eclipse-glsp/server', columns, true)}
1816
1893
  import { ComputedBoundsActionHandler } from '@eclipse-glsp/server';
1817
- import type { LanguageMetaData } from '@hydranium/langium';
1818
- ${importList(['HydraniumGlspComputedBoundsActionHandler', 'AbstractHydraniumGlspDiagramModule', 'HydraniumGlspIndex'], '@hydranium/glsp-server', columns)}
1819
- import { __GRAMMAR__LanguageMetaData } from '../../language-server/generated/module.js';
1894
+ ${importList(['HydraniumGlspComputedBoundsActionHandler', 'AbstractHydraniumGlspDiagramModule', 'HydraniumGlspIndex', 'HydraniumGlspModelValidator'], '@hydranium/glsp-server', columns)}
1820
1895
  import { __GRAMMAR__CreateNodeOperationHandler } from './create-node-operation-handler.js';
1896
+ import { __GRAMMAR__DeleteOperationHandler } from './delete-operation-handler.js';
1821
1897
  import { __GRAMMAR__DiagramConfiguration } from './diagram-configuration.js';
1822
1898
  import { __GRAMMAR__GModelFactory } from './gmodel-factory.js';
1823
1899
  import { __GRAMMAR__GlspState } from './state.js';
1824
1900
  import { __GRAMMAR__GlspStorage } from './storage.js';
1825
1901
  import { __GRAMMAR__SubmissionHandler } from './submission-handler.js';
1826
- import { ${upper}_DIAGRAM_TYPE } from './types.js';
1827
-
1828
- export class __GRAMMAR__DiagramModule extends AbstractHydraniumGlspDiagramModule {
1829
- readonly diagramType = ${upper}_DIAGRAM_TYPE;
1902
+ import { __GRAMMAR_ID_CONST___DIAGRAM_TYPE } from '__PROTOCOL_PACKAGE__';
1903
+ import { injectable } from 'inversify';
1830
1904
 
1831
- protected override declareLanguage(): LanguageMetaData {
1832
- return __GRAMMAR__LanguageMetaData;
1905
+ /**
1906
+ * The framework handler, keeping none of the edge routes the client reports:
1907
+ * it routes an edge before it sizes the nodes, so a self-reference's loop would
1908
+ * stay drawn inside its node. The starter's edges have no routing points, and
1909
+ * the client routes them afresh from the sized nodes.
1910
+ */
1911
+ @injectable()
1912
+ export class __GRAMMAR__ComputedBoundsActionHandler extends HydraniumGlspComputedBoundsActionHandler {
1913
+ protected override applyBounds(root: GModelRoot, action: ComputedBoundsAction): void {
1914
+ super.applyBounds(root, { ...action, routes: undefined });
1833
1915
  }
1916
+ }
1917
+
1918
+ export class __GRAMMAR__DiagramModule extends AbstractHydraniumGlspDiagramModule {
1919
+ readonly diagramType = __GRAMMAR_ID_CONST___DIAGRAM_TYPE;
1834
1920
 
1835
1921
  protected override bindModelState(): BindingTarget<ModelState> {
1836
1922
  return { service: __GRAMMAR__GlspState };
@@ -1857,80 +1943,2240 @@ export class __GRAMMAR__DiagramModule extends AbstractHydraniumGlspDiagramModule
1857
1943
  return { service: HydraniumGlspIndex };
1858
1944
  }
1859
1945
 
1946
+ /**
1947
+ * The language's diagnostics as diagram markers, following each edit. GLSP
1948
+ * binds no validator by default, and without one no marker ever shows.
1949
+ */
1950
+ protected override bindModelValidator(): BindingTarget<ModelValidator> {
1951
+ return HydraniumGlspModelValidator;
1952
+ }
1953
+
1860
1954
  protected override configureActionHandlers(binding: InstanceMultiBinding<ActionHandlerConstructor>): void {
1861
1955
  super.configureActionHandlers(binding);
1862
- binding.rebind(ComputedBoundsActionHandler, HydraniumGlspComputedBoundsActionHandler);
1956
+ binding.rebind(ComputedBoundsActionHandler, __GRAMMAR__ComputedBoundsActionHandler);
1863
1957
  }
1864
1958
 
1865
1959
  protected override configureOperationHandlers(binding: InstanceMultiBinding<OperationHandlerConstructor>): void {
1866
1960
  super.configureOperationHandlers(binding);
1867
1961
  binding.add(__GRAMMAR__CreateNodeOperationHandler);
1962
+ binding.add(__GRAMMAR__DeleteOperationHandler);
1868
1963
  }
1869
1964
  }
1870
1965
  `;
1871
1966
  return [
1872
- { path: `${dir}/types.ts`, content: render(types) },
1873
- { path: `${dir}/state.ts`, content: render(state) },
1874
- { path: `${dir}/storage.ts`, content: render(storage) },
1875
- { path: `${dir}/submission-handler.ts`, content: render(submission) },
1876
- { path: `${dir}/gmodel-factory.ts`, content: render(factory) },
1877
- { path: `${dir}/diagram-configuration.ts`, content: render(configuration) },
1878
- { path: `${dir}/create-node-operation-handler.ts`, content: render(createHandler) },
1879
- { path: `${dir}/diagram-module.ts`, content: render(module) }
1967
+ fixed('state.ts'),
1968
+ fixed('storage.ts'),
1969
+ fixed('submission-handler.ts'),
1970
+ fixed('gmodel-factory.ts'),
1971
+ computed('diagram-configuration.ts', configuration),
1972
+ fixed('create-node-operation-handler.ts'),
1973
+ fixed('delete-operation-handler.ts'),
1974
+ computed('diagram-module.ts', module),
1975
+ grammarTemplate('server/test/__GRAMMAR_ID__-diagram.test.ts', composition, grammar)
1880
1976
  ];
1881
1977
  }
1882
1978
  /**
1883
- * Every file the scaffold emits, fully rendered.
1979
+ * The server member: the grammar, the language and its heads.
1884
1980
  *
1885
1981
  * Grammar-count-dependent emissions live here rather than in a template string:
1886
1982
  * one `.langium` file per grammar, and the shared `common.langium` fragment only
1887
1983
  * when there is more than one grammar to share it.
1888
1984
  */
1889
- export function buildInitTemplates(composition) {
1985
+ function serverFiles(composition) {
1890
1986
  const multi = composition.grammars.length > 1;
1891
1987
  const grammarFiles = composition.grammars.map(grammar => ({
1892
- path: `src/grammar/${grammar.grammarId}.langium`,
1988
+ path: `server/src/grammar/${grammar.grammarId}.langium`,
1893
1989
  content: render(grammarFile(multi), composition, grammar)
1894
1990
  }));
1991
+ // The shared lexical fragment, only for several grammars: each declaring its
1992
+ // own `WS` / `ID` lets the token sets drift apart.
1895
1993
  if (multi) {
1896
- grammarFiles.unshift({ path: 'src/grammar/common.langium', content: COMMON_GRAMMAR });
1994
+ grammarFiles.unshift(projectTemplate('server/src/grammar/common.langium', composition));
1897
1995
  }
1898
1996
  const diagramFiles = composition.grammars.filter(grammar => grammar.diagram).flatMap(grammar => glspFiles(composition, grammar));
1899
1997
  return [
1900
- { path: 'package.json', content: packageJson(composition) },
1901
- { path: 'langium-config.json', content: langiumConfig(composition) },
1902
- { path: 'tsconfig.json', content: tsconfigJson(composition) },
1903
- { path: 'tsconfig.test.json', content: TSCONFIG_TEST },
1904
- { path: 'vitest.config.ts', content: VITEST_CONFIG },
1905
- {
1906
- path: '.gitignore',
1907
- content: composition.packaging.workspace === undefined ? GITIGNORE : GITIGNORE_WORKSPACE_MEMBER
1908
- },
1909
- { path: 'README.md', content: readme(composition) },
1998
+ { path: 'server/package.json', content: packageJson(composition) },
1999
+ { path: 'server/langium-config.json', content: langiumConfig(composition) },
2000
+ { path: 'server/tsconfig.json', content: serverTsconfigJson(composition) },
2001
+ // `isolatedModules` is what makes this check agree with the transform that
2002
+ // actually runs the tests. `npm test` is `typecheck:test && vitest run`, and
2003
+ // vitest compiles each file on its own — a transform with no type
2004
+ // information, which cannot tell a re-exported TYPE from a re-exported value.
2005
+ // Without the flag `tsc` accepts `export { SomeType } from './x'` that the
2006
+ // transform then emits as a real import of a symbol that does not exist at
2007
+ // runtime, so the typecheck passes and the suite fails with a confusing
2008
+ // missing-export.
2009
+ projectTemplate('server/tsconfig.test.json', composition),
2010
+ // Found by name, unlike `tsconfig.test.json`. Under vite 8, vitest's transform
2011
+ // applies a tsconfig only to the files its own `include` lists, so without this
2012
+ // a test declaring a decorated class fails to load.
2013
+ projectTemplate('server/test/tsconfig.json', composition),
2014
+ projectTemplate('server/vitest.config.ts', composition),
2015
+ // Written for a workspace member too: its root may not ignore `lib/` (a `yo
2016
+ // langium` root ignores `out/`), and a rule the root repeats costs nothing.
2017
+ ignoreFile('server'),
2018
+ { path: 'server/README.md', content: readme(composition) },
1910
2019
  ...grammarFiles,
1911
- { path: `src/language-server/${composition.projectId}-module.ts`, content: moduleFile(composition) },
1912
- { path: 'src/language-server/ast.ts', content: render(AST, composition, composition.grammars[0]) },
1913
- ...composition.grammars.map(grammar => ({
1914
- path: `src/language-server/${grammar.grammarId}-serializer.ts`,
1915
- content: render(SERIALIZER, composition, grammar)
1916
- })),
1917
- { path: 'src/index.ts', content: indexFile(composition) },
1918
- { path: 'src/services.ts', content: project(SERVICES, composition) },
1919
- { path: 'src/main.ts', content: mainFile(composition) },
1920
- ...(composition.heads.includes('data') ? [{ path: 'src/data-server-main.ts', content: dataServerMainFile(composition) }] : []),
1921
- ...(portCommandNames(composition).length ? [{ path: 'src/head-ports.ts', content: headPortsFile(composition) }] : []),
2020
+ { path: `server/src/language-server/${composition.projectId}-module.ts`, content: moduleFile(composition) },
2021
+ grammarTemplate('server/src/language-server/ast.ts', composition, composition.grammars[0]),
2022
+ // Per grammar, because `services.serializer.Serializer` is a per-language slot
2023
+ // and a serializer is grammar-shaped by definition. That is also why the
2024
+ // framework refuses to default it: its `UnboundSerializer` throws, naming the
2025
+ // binding to add, rather than guessing a syntax.
2026
+ ...composition.grammars.flatMap(grammar => [
2027
+ grammarTemplate('server/src/language-server/__GRAMMAR_ID__-serializer.ts', composition, grammar),
2028
+ grammarTemplate('server/src/language-server/__GRAMMAR_ID__-validation.ts', composition, grammar)
2029
+ ]),
2030
+ { path: 'server/src/index.ts', content: indexFile(composition) },
2031
+ projectTemplate('server/src/node/services.ts', composition),
2032
+ { path: 'server/src/main.ts', content: mainFile(composition) },
2033
+ ...(composition.heads.includes('data') ? [{ path: 'server/src/data-server-main.ts', content: dataServerMainFile(composition) }] : []),
1922
2034
  ...diagramFiles,
1923
- { path: 'test/services.test.ts', content: servicesTest(composition) },
1924
- { path: 'test/parsing.test.ts', content: grammarTest(composition, PARSING_HEADER, [], PARSING_SUITE) },
2035
+ { path: 'server/test/services.test.ts', content: servicesTest(composition) },
2036
+ { path: 'server/test/parsing.test.ts', content: grammarTest(composition, PARSING_HEADER, [], PARSING_SUITE) },
1925
2037
  {
1926
- path: 'test/linking.test.ts',
2038
+ path: 'server/test/linking.test.ts',
1927
2039
  content: grammarTest(composition, LINKING_HEADER, ["import { AstUtils } from '@hydranium/langium';"], LINKING_SUITE)
1928
2040
  },
1929
2041
  {
1930
- path: 'test/validating.test.ts',
2042
+ path: 'server/test/validating.test.ts',
1931
2043
  content: grammarTest(composition, VALIDATING_HEADER, ["import { DiagnosticSeverity } from 'vscode-languageserver';"], VALIDATING_SUITE)
1932
2044
  },
1933
- { path: 'test/serialization.test.ts', content: serializationTest(composition) }
2045
+ { path: 'server/test/serialization.test.ts', content: serializationTest(composition) }
2046
+ ];
2047
+ }
2048
+ /**
2049
+ * The protocol member's `package.json`.
2050
+ *
2051
+ * Its `build` runs the server's `generate` first, because the server writes
2052
+ * this package's `generated-hydranium/` modules from the grammar: a runner that
2053
+ * builds in dependency order reaches this package before the server, and would
2054
+ * otherwise compile modules that do not exist yet. A full build therefore
2055
+ * generates twice; the second pass rewrites nothing.
2056
+ */
2057
+ function protocolPackageJson(composition) {
2058
+ const member = forMember(composition, 'protocol');
2059
+ const dependencies = {};
2060
+ for (const head of composition.heads) {
2061
+ Object.assign(dependencies, PROTOCOL_THIRD_PARTY_DEPENDENCIES[head]);
2062
+ }
2063
+ const dependencyLines = Object.keys(dependencies).length === 0 ? '' : ` "dependencies": {\n${sortedBlock(dependencies, ' ')}\n },\n`;
2064
+ return `{
2065
+ "name": "${memberPackageName(composition, 'protocol')}",
2066
+ "version": "0.0.0",
2067
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "What the ${composition.name} language server and its clients share: language ids, wire types and diagram ids.",
2068
+ "license": "UNLICENSED",
2069
+ "author": "",
2070
+ "files": [
2071
+ "lib",
2072
+ "src"
2073
+ ],
2074
+ "type": "module",
2075
+ "main": "lib/index.js",
2076
+ "types": "lib/index.d.ts",
2077
+ "scripts": {
2078
+ "build": "npm --prefix ../server run generate && tsc -b",
2079
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
2080
+ ${lintScript(member, 'src')} "watch": "tsc -b --watch"
2081
+ },
2082
+ ${dependencyLines} "devDependencies": {
2083
+ "rimraf": "^5.0.0",
2084
+ "typescript": "^7.0.2"
2085
+ },
2086
+ "engines": {
2087
+ "node": ">=22.13"
2088
+ }
2089
+ }
2090
+ `;
2091
+ }
2092
+ /** The protocol member's root entry, one re-export per module. */
2093
+ function protocolIndexFile(composition) {
2094
+ const modules = [
2095
+ './generated-hydranium/languages.js',
2096
+ './generated-hydranium/transfer-model.js',
2097
+ ...(headPortConstants(composition).length ? ['./head-ports.js'] : []),
2098
+ ...composition.grammars.filter(grammar => grammar.diagram).map(grammar => `./${grammar.grammarId}-diagram-types.js`)
2099
+ ];
2100
+ const text = `// What the __NAME__ server and its clients both import. A client depends on
2101
+ // this package instead of the server, so it never installs Langium to reach a
2102
+ // constant or a wire type.
2103
+ //
2104
+ // The server's \`generate\` writes \`generated-hydranium/\` from the grammar;
2105
+ // commit those modules with the grammar change that produced them. An interface
2106
+ // narrowed here hides the generated constant of the same name; re-export that
2107
+ // constant beside it, and declare the type map under its own name with the
2108
+ // narrowed entry, or the builder and the GLSP state keep the generated one.
2109
+
2110
+ ${modules.map(module => `export * from '${module}';`).join('\n')}
2111
+ `;
2112
+ return project(text, composition);
2113
+ }
2114
+ /** The protocol member's README. */
2115
+ function protocolReadme(composition) {
2116
+ const lines = [
2117
+ `# ${memberPackageName(composition, 'protocol')}`,
2118
+ '',
2119
+ 'What the __NAME__ language server and its clients both import, so a client',
2120
+ 'never depends on the server or installs Langium.',
2121
+ '',
2122
+ '- `src/generated-hydranium/languages.ts` — each language id and its file extensions',
2123
+ '- `src/generated-hydranium/transfer-model.ts` — the wire types of the model, references as plain strings',
2124
+ ...(headPortConstants(composition).length === 0
2125
+ ? []
2126
+ : composition.heads.includes('lsp')
2127
+ ? ['- `src/head-ports.ts` — the LSP requests a host sends to find the socket heads']
2128
+ : ["- `src/head-ports.ts` — the environment variables naming the socket heads' ports"]),
2129
+ ...composition.grammars
2130
+ .filter(grammar => grammar.diagram)
2131
+ .map(grammar => `- \`src/${grammar.grammarId}-diagram-types.ts\` — the \`${grammar.grammar}\` diagram's type ids`),
2132
+ '',
2133
+ "The server's `npm run generate` writes `src/generated-hydranium/` from the",
2134
+ 'grammar, and `npm run build` here runs it first. Commit the generated',
2135
+ 'modules with the grammar change that produced them.',
2136
+ ''
2137
+ ];
2138
+ return project(lines.join('\n'), composition);
2139
+ }
2140
+ /** The protocol member: everything the server and its clients both import. */
2141
+ function protocolFiles(composition) {
2142
+ return [
2143
+ { path: 'protocol/package.json', content: protocolPackageJson(composition) },
2144
+ { path: 'protocol/tsconfig.json', content: tsconfigJson(forMember(composition, 'protocol'), PROTOCOL_COMPILER_OPTIONS, '["src"]') },
2145
+ ignoreFile('protocol'),
2146
+ { path: 'protocol/README.md', content: protocolReadme(composition) },
2147
+ { path: 'protocol/src/index.ts', content: protocolIndexFile(composition) },
2148
+ ...(headPortConstants(composition).length ? [{ path: 'protocol/src/head-ports.ts', content: headPortsFile(composition) }] : []),
2149
+ ...composition.grammars
2150
+ .filter(grammar => grammar.diagram)
2151
+ .map(grammar => grammarTemplate('protocol/src/__GRAMMAR_ID__-diagram-types.ts', composition, grammar))
2152
+ ];
2153
+ }
2154
+ /**
2155
+ * The starter model files every host and the CLI open, two per language: one
2156
+ * declaring nodes, one referencing a node in the other file.
2157
+ *
2158
+ * Named by extension alone, since `init` refuses two grammars sharing one.
2159
+ */
2160
+ function workspaceFiles(composition) {
2161
+ return composition.grammars.flatMap(grammar => [
2162
+ grammarTemplate('workspace/nodes.__EXTENSION__', composition, grammar),
2163
+ grammarTemplate('workspace/references.__EXTENSION__', composition, grammar)
2164
+ ]);
2165
+ }
2166
+ /** The client member's compiler options: the protocol's, with the DOM its diagram renders into. */
2167
+ const CLIENT_COMPILER_OPTIONS = [
2168
+ ['target', 'ES2022'],
2169
+ ['lib', ['ES2022', 'DOM']],
2170
+ ['module', 'NodeNext'],
2171
+ ['moduleResolution', 'NodeNext'],
2172
+ ['rootDir', 'src'],
2173
+ ['outDir', 'lib'],
2174
+ ['strict', true],
2175
+ ['skipLibCheck', true],
2176
+ ['declaration', true],
2177
+ // For inversify's `@injectable`, which a GLSP view needs to be bound.
2178
+ ['experimentalDecorators', true],
2179
+ ['types', []],
2180
+ // A base that sets it fails every `import` in this CommonJS member.
2181
+ ['verbatimModuleSyntax', false]
2182
+ ];
2183
+ /**
2184
+ * The client member's `package.json`.
2185
+ *
2186
+ * CommonJS, unlike its siblings, as GLSP's client is: inversify ships an ES
2187
+ * build and a CommonJS one, so an ES module here would load the first while
2188
+ * GLSP's client loads the second, giving a page two containers' worth of
2189
+ * classes. Node from 22.12 and `tsc` under `nodenext` both let it require the
2190
+ * ES protocol member.
2191
+ */
2192
+ function clientPackageJson(composition) {
2193
+ const dependencies = {
2194
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
2195
+ ...CLIENT_THIRD_PARTY_DEPENDENCIES
2196
+ };
2197
+ for (const framework of CLIENT_FRAMEWORK_DEPENDENCIES) {
2198
+ dependencies[framework] = frameworkPin(composition);
2199
+ }
2200
+ return `{
2201
+ "name": "${memberPackageName(composition, 'client')}",
2202
+ "version": "0.0.0",
2203
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "The host-neutral client side of the ${composition.name} language: what every host of it mounts.",
2204
+ "license": "UNLICENSED",
2205
+ "author": "",
2206
+ "files": [
2207
+ "lib",
2208
+ "src"
2209
+ ],
2210
+ "main": "lib/index.js",
2211
+ "types": "lib/index.d.ts",
2212
+ "scripts": {
2213
+ "build": "tsc -b",
2214
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
2215
+ ${lintScript(forMember(composition, 'client'), 'src')} "watch": "tsc --watch"
2216
+ },
2217
+ "dependencies": {
2218
+ ${sortedBlock(dependencies, ' ')}
2219
+ },
2220
+ "devDependencies": {
2221
+ "rimraf": "^5.0.0",
2222
+ "typescript": "^7.0.2"
2223
+ },
2224
+ "engines": {
2225
+ "node": ">=22.13"
2226
+ }
2227
+ }
2228
+ `;
2229
+ }
2230
+ /** The client member's README. */
2231
+ function clientReadme(composition) {
2232
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
2233
+ const lines = [
2234
+ `# ${memberPackageName(composition, 'client')}`,
2235
+ '',
2236
+ 'The host-neutral client side of the __NAME__ language: what every host of it',
2237
+ 'mounts, whatever that host is. It reads the element ids from the protocol',
2238
+ 'package and never depends on the server.',
2239
+ '',
2240
+ ...diagrams.map(grammar => `- \`src/${grammar.grammarId}-diagram-module.ts\` — the \`${grammar.grammar}\` diagram: a registration per element type, its container module, and \`initialize${grammar.grammar}DiagramContainer\``),
2241
+ '- `src/index.ts` — the package root, re-exporting each module',
2242
+ '',
2243
+ 'A host builds a diagram container with the initializer, passing its own',
2244
+ 'modules: they go first and the diagram definition last, since GLSP gives an',
2245
+ 'element type to whichever module registered it last.',
2246
+ ''
2247
+ ];
2248
+ return project(lines.join('\n'), composition);
2249
+ }
2250
+ /** The client member's root entry, one re-export per diagram module. */
2251
+ function clientIndexFile(composition) {
2252
+ const modules = composition.grammars.filter(grammar => grammar.diagram).map(grammar => `./${grammar.grammarId}-diagram-module.js`);
2253
+ return `// What every host of the ${composition.name} language mounts.
2254
+
2255
+ ${modules.map(module => `export * from '${module}';`).join('\n')}
2256
+ `;
2257
+ }
2258
+ /**
2259
+ * The client member: the host-neutral client side of the language, emitted
2260
+ * when there is a diagram to define. Each host mounts it rather than defining
2261
+ * the diagram again.
2262
+ */
2263
+ function clientFiles(composition) {
2264
+ return [
2265
+ { path: 'client/package.json', content: clientPackageJson(composition) },
2266
+ {
2267
+ path: 'client/tsconfig.json',
2268
+ content: tsconfigJson(forMember(composition, 'client'), CLIENT_COMPILER_OPTIONS, '["src"]', '[{ "path": "../protocol" }]')
2269
+ },
2270
+ ignoreFile('client'),
2271
+ { path: 'client/README.md', content: clientReadme(composition) },
2272
+ { path: 'client/src/index.ts', content: clientIndexFile(composition) },
2273
+ ...composition.grammars
2274
+ .filter(grammar => grammar.diagram)
2275
+ .map(grammar => grammarTemplate('client/src/__GRAMMAR_ID__-diagram-module.ts', composition, grammar))
2276
+ ];
2277
+ }
2278
+ /**
2279
+ * The browser host's `package.json`. Always private: it is an application,
2280
+ * which nothing installs as a dependency.
2281
+ */
2282
+ function hostBrowserPackageJson(composition) {
2283
+ const dependencies = {
2284
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
2285
+ [memberPackageName(composition, 'server')]: MEMBER_PIN,
2286
+ ...(composition.heads.includes('glsp') ? { [memberPackageName(composition, 'client')]: MEMBER_PIN } : {}),
2287
+ // A page with no editor saves through the diagram's own action dispatcher.
2288
+ ...(composition.heads.includes('lsp') ? {} : { '@eclipse-glsp/client': CLIENT_THIRD_PARTY_DEPENDENCIES['@eclipse-glsp/client'] })
2289
+ };
2290
+ for (const head of ['base', ...composition.heads]) {
2291
+ Object.assign(dependencies, HOST_BROWSER_THIRD_PARTY_DEPENDENCIES[head]);
2292
+ for (const framework of HOST_BROWSER_FRAMEWORK_DEPENDENCIES[head]) {
2293
+ dependencies[framework] = frameworkPin(composition);
2294
+ }
2295
+ }
2296
+ return `{
2297
+ "name": "${memberPackageName(composition, 'host-browser')}",
2298
+ "version": "0.0.0",
2299
+ "private": true,
2300
+ "description": "${composition.name} in a browser page, with every head in a web worker and no backend.",
2301
+ "license": "UNLICENSED",
2302
+ "author": "",
2303
+ "type": "module",
2304
+ "scripts": {
2305
+ "build": "npm run typecheck && node esbuild.mjs",
2306
+ "clean": "rimraf out test-results playwright-report",
2307
+ ${lintScript(forMember(composition, 'host-browser'), 'src test')} "start": "node esbuild.mjs --serve",
2308
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
2309
+ "test:e2e:install": "playwright install chromium",
2310
+ "typecheck": "tsc --noEmit -p tsconfig.worker.json && tsc --noEmit -p tsconfig.page.json && tsc --noEmit -p tsconfig.e2e.json"
2311
+ },
2312
+ "dependencies": {
2313
+ ${sortedBlock(dependencies, ' ')}
2314
+ },
2315
+ "devDependencies": {
2316
+ ${sortedBlock(HOST_BROWSER_DEV_DEPENDENCIES, ' ')}
2317
+ },
2318
+ "engines": {
2319
+ "node": ">=22.13"
2320
+ }
2321
+ }
2322
+ `;
2323
+ }
2324
+ /** The workspace URI of a grammar's first starter file, as a template literal over `WORKSPACE_ROOT_URI`. */
2325
+ function starterUri(grammar) {
2326
+ return `\`\${WORKSPACE_ROOT_URI}/nodes.${grammar.extensions[0]}\``;
2327
+ }
2328
+ /**
2329
+ * The worker hosting the heads: every head over the one store, with the
2330
+ * workspace seeded from `../workspace` and saved files kept in IndexedDB.
2331
+ */
2332
+ function hostWorkerFile(composition) {
2333
+ const columns = columnsFor(composition);
2334
+ const lsp = composition.heads.includes('lsp');
2335
+ const data = composition.heads.includes('data');
2336
+ const glsp = composition.heads.includes('glsp');
2337
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
2338
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
2339
+ const serverSymbols = [`create${composition.name}Services`, ...diagrams.map(grammar => `${grammar.grammar}DiagramModule`)].sort((left, right) => left.localeCompare(right));
2340
+ const imports = [
2341
+ ...(glsp
2342
+ ? [
2343
+ '// First, before any class carrying a decorator loads: GLSP reads the metadata',
2344
+ '// its decorators emit as each class is defined.',
2345
+ "import 'reflect-metadata';",
2346
+ "import { ServerModule } from '@eclipse-glsp/server/browser.js';"
2347
+ ]
2348
+ : []),
2349
+ "import { persistentFileSystem } from '@hydranium/core';",
2350
+ importList(['hostHeadsInWorker', 'IndexedDbFileSystemStore', ...(lsp ? ['startLanguageServerInWorker'] : [])], '@hydranium/core/browser', columns),
2351
+ ...(data
2352
+ ? [
2353
+ "import { DataServer } from '@hydranium/data-server';",
2354
+ "import { startDataServerInWorker } from '@hydranium/data-server/browser';"
2355
+ ]
2356
+ : []),
2357
+ ...(glsp
2358
+ ? [
2359
+ "import { GlspClientLogger, HydraniumGlspAppModule } from '@hydranium/glsp-server';",
2360
+ "import { startGlspServerInWorker } from '@hydranium/glsp-server/browser';"
2361
+ ]
2362
+ : []),
2363
+ ...(data ? [importList(roots, memberPackageName(composition, 'protocol'), columns, true)] : []),
2364
+ importList(serverSymbols, memberPackageName(composition, 'server'), columns),
2365
+ "import { WORKSPACE_ROOT_URI } from './workspace.js';"
2366
+ ];
2367
+ const services = `const shared = create${composition.name}Services({ ...fileSystem }).shared;`;
2368
+ const lspCall = `startLanguageServerInWorker(ports.lsp, connection => create${composition.name}Services({ connection, ...fileSystem }).shared);`;
2369
+ const startServices = !lsp
2370
+ ? services
2371
+ : ` const shared = ${lspCall}`.length <= columns
2372
+ ? `const shared = ${lspCall}`
2373
+ : `const shared = startLanguageServerInWorker(
2374
+ ports.lsp,
2375
+ connection => create${composition.name}Services({ connection, ...fileSystem }).shared
2376
+ );`;
2377
+ const dataServer = `connection => new DataServer<${roots.join(' | ')}>(connection, shared)`;
2378
+ const dataCall = `startDataServerInWorker(ports.data, shared, ${dataServer});`;
2379
+ const dataHead = data
2380
+ ? `
2381
+ // The data head serves from the ${lsp ? "LSP head's" : "services'"} store, on its own port.
2382
+ ${` ${dataCall}`.length <= columns
2383
+ ? dataCall
2384
+ : `startDataServerInWorker(
2385
+ ports.data,
2386
+ shared,
2387
+ ${dataServer}
2388
+ );`}`
2389
+ : '';
2390
+ const glspHead = glsp
2391
+ ? `
2392
+ const glsp = startGlspServerInWorker({
2393
+ context: ports.glsp,
2394
+ createLogger: caller => new GlspClientLogger(shared, { component: caller }),
2395
+ serverModule: new ServerModule()${diagrams.map(grammar => `.configureDiagramModule(new ${grammar.grammar}DiagramModule())`).join('')},
2396
+ appModules: [new HydraniumGlspAppModule({ shared })]
2397
+ });
2398
+ // The GLSP head reports a failed start through \`started\`, which the
2399
+ // ready message waits for.
2400
+ return { shared, started: [glsp.started] };`
2401
+ : `
2402
+ return shared;`;
2403
+ const text = `// The worker hosting the heads: every head over one store, in the browser and
2404
+ // with no backend. The page reaches each head over a \`MessagePort\` of its own.
2405
+
2406
+ ${imports.join('\n')}
2407
+
2408
+ /** The files of \`../workspace\`, read by \`esbuild.mjs\` and keyed by their path below the root. */
2409
+ declare const __WORKSPACE_SEED__: Record<string, string>;
2410
+ /** This project's directory, hashed by \`esbuild.mjs\`, so that no other project on the origin opens its store. */
2411
+ declare const __DIRECTORY_KEY__: string;
2412
+
2413
+ // A saved file is kept in IndexedDB and laid over the seed on the next load;
2414
+ // the heads start once the stored files are restored.
2415
+ const store = new IndexedDbFileSystemStore(\`__PROJECT_ID__-workspace-\${__DIRECTORY_KEY__}\`);
2416
+
2417
+ hostHeadsInWorker(
2418
+ persistentFileSystem({ store, seed: __WORKSPACE_SEED__, rootUri: WORKSPACE_ROOT_URI }),
2419
+ (ports, fileSystem) => {
2420
+ ${lsp ? '// The LSP head composes the services, as the Node entry does around stdio.\n ' : ''}${startServices}${dataHead}${glspHead}
2421
+ },
2422
+ ${lsp
2423
+ ? '// The ready message then carries the workspace files the page opens.'
2424
+ : '// With no LSP head the workspace comes up from this root, and the ready\n // message then carries its files.'}
2425
+ { rootUri: WORKSPACE_ROOT_URI }
2426
+ );
2427
+ `;
2428
+ return project(text, composition);
2429
+ }
2430
+ /**
2431
+ * The page, and the one place deciding which head's part of it runs: each
2432
+ * part is a module of its own, and this calls the ones the heads serve.
2433
+ */
2434
+ function hostPageFile(composition) {
2435
+ const lsp = composition.heads.includes('lsp');
2436
+ const data = composition.heads.includes('data');
2437
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2438
+ // A host takes lsp or glsp, and glsp marks a diagram grammar, so without lsp there is one.
2439
+ const diagramLanguage = lsp || diagram === undefined ? undefined : `${screamingSnake(diagram.grammarId)}_LANGUAGE`;
2440
+ const shownLanguage = diagramLanguage ?? 'ALL_LANGUAGES';
2441
+ const parts = [
2442
+ // Every part follows the file the page shows, so the switch comes first. With
2443
+ // no editor it lists only the diagram's files, the only ones the page shows.
2444
+ {
2445
+ module: './shown-file.js',
2446
+ imports: 'startShownFile',
2447
+ call: `const shownFile = await startShownFile(heads, ${diagramLanguage === undefined ? shownLanguage : `[${diagramLanguage}]`});`
2448
+ },
2449
+ // Save is armed with the editor, so it works before the other panes load;
2450
+ // with a diagram it waits for the edits of the one shown, once mounted.
2451
+ ...(lsp
2452
+ ? [
2453
+ {
2454
+ module: './editor.js',
2455
+ imports: 'armEditorSave, startEditor',
2456
+ call: [
2457
+ 'const editor = await startEditor(heads, shownFile);',
2458
+ ...(diagram === undefined
2459
+ ? ['armEditorSave(editor);']
2460
+ : [
2461
+ 'let shownDiagram: Awaited<ReturnType<typeof mountDiagram>> | undefined = undefined;',
2462
+ 'armEditorSave(editor, () => settleDiagramEdits(shownDiagram?.()));'
2463
+ ])
2464
+ ].join('\n ')
2465
+ }
2466
+ ]
2467
+ : []),
2468
+ ...(data
2469
+ ? [
2470
+ {
2471
+ module: './data-status.js',
2472
+ imports: 'showDataStatus',
2473
+ call: `await showDataStatus(heads.data, ${starterUri(composition.grammars[0])});`
2474
+ }
2475
+ ]
2476
+ : []),
2477
+ ...(diagram === undefined
2478
+ ? []
2479
+ : [
2480
+ {
2481
+ module: './diagram.js',
2482
+ imports: lsp ? 'mountDiagram, settleDiagramEdits' : 'mountDiagram',
2483
+ call: `${lsp ? 'shownDiagram' : 'const shownDiagram'} = await mountDiagram(heads.glsp, shownFile, logger, ${lsp ? 'settleDiagramEdits' : 'saveBeforeLeaving'});`
2484
+ }
2485
+ ]),
2486
+ // Without the editor, the diagram is what the page saves through.
2487
+ ...(lsp ? [] : [{ module: './diagram-save.js', imports: 'armDiagramSave, saveBeforeLeaving', call: 'armDiagramSave(shownDiagram);' }])
2488
+ ];
2489
+ const imports = [
2490
+ ...parts.map(part => `import { ${part.imports} } from '${part.module}';`),
2491
+ "import { appendLog, setStatus } from './log.js';",
2492
+ ...(data ? ["import { WORKSPACE_ROOT_URI } from './workspace.js';"] : [])
2493
+ ].sort((left, right) => left.slice(left.indexOf("'")).localeCompare(right.slice(right.indexOf("'"))));
2494
+ return `// The page: it starts the worker, hands each head a channel of its own, and
2495
+ // fills the pane of each head the server runs, one after the other.
2496
+
2497
+ import { connectWorkerHeads } from '@hydranium/client-browser';
2498
+ import { ConsoleLogger, describeError } from '@hydranium/protocol';
2499
+ import { ${shownLanguage} } from '${memberPackageName(composition, 'protocol')}';
2500
+ ${imports.join('\n')}
2501
+
2502
+ /** Where the worker bundle is served, substituted by \`esbuild.mjs\`. */
2503
+ declare const __WORKER_BUNDLE_URL__: string;
2504
+
2505
+ async function main(): Promise<void> {
2506
+ // The page's end of each head's connection logs to the browser console.
2507
+ const logger = new ConsoleLogger();
2508
+ const heads = connectWorkerHeads(new Worker(__WORKER_BUNDLE_URL__), { logger });
2509
+ heads.onWorkerError(report => appendLog(\`worker error during \${report.phase}: \${report.message}\`));
2510
+ setStatus('starting…');
2511
+ ${parts.map(part => ` ${part.call}`).join('\n')}
2512
+ setStatus('ready');
2513
+ }
2514
+
2515
+ main().catch((error: unknown) => setStatus(\`failed: \${describeError(error)}\`));
2516
+ `;
2517
+ }
2518
+ /**
2519
+ * The smoke test: what each head shows on the page, and an edit that survives
2520
+ * a reload, typed in the editor or, with no LSP head, made in the diagram. With
2521
+ * a diagram, also a diagram edit the reload guard and Save catch before the
2522
+ * server has answered it.
2523
+ */
2524
+ function hostSmokeSpec(composition) {
2525
+ const lsp = composition.heads.includes('lsp');
2526
+ const data = composition.heads.includes('data');
2527
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2528
+ const primary = composition.grammars[0];
2529
+ const checks = [
2530
+ ...(lsp ? [" await expect(editor).toContainText('node First');"] : []),
2531
+ ...(data
2532
+ ? [
2533
+ ' // The data head reads the document out of the same store.',
2534
+ ` await expect(page.locator('#data-status')).toHaveText('data head: nodes.${primary.extensions[0]} holds a ${primary.entryRule}');`
2535
+ ]
2536
+ : []),
2537
+ ...(diagram === undefined
2538
+ ? []
2539
+ : [
2540
+ ' // The diagram follows the switch: two nodes in one file, and in the other its',
2541
+ ' // node and the target it references there, drawn as external.',
2542
+ " const first = await page.locator('#file').inputValue();",
2543
+ ` await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');`,
2544
+ " await expect(page.locator('#diagram .sprotty-node')).toHaveCount(2);",
2545
+ ` await page.locator('#file').selectOption('references.${diagram.extensions[0]}');`,
2546
+ ` await expect(page.locator('#diagram .external')).toHaveText('Second (nodes.${diagram.extensions[0]})');`,
2547
+ " await page.locator('#file').selectOption(first);"
2548
+ ])
2549
+ ];
2550
+ const edit = lsp
2551
+ ? ` await editor.click();
2552
+ await page.keyboard.press('ControlOrMeta+End');
2553
+ await page.keyboard.type('\\nnode Added');
2554
+ await page.locator('#save').click();
2555
+ await expect(page.locator('#status')).toHaveText('saved 1 file(s)');
2556
+
2557
+ await page.reload();
2558
+ await expect(page.locator('#status')).toHaveText('ready');
2559
+ await expect(editor).toContainText('node Added');`
2560
+ : ` // A node from the palette, dropped low and left of centre: the starter nodes
2561
+ // sit in the upper band and the palette in the upper right.
2562
+ const canvas = page.locator('#diagram');
2563
+ const create = async (): Promise<void> => {
2564
+ await page.locator('#diagram .tool-button', { hasText: '${diagram?.nodeRule}' }).click();
2565
+ const size = await canvas.evaluate(element => ({ width: element.clientWidth, height: element.clientHeight }));
2566
+ await canvas.click({ position: { x: size.width * 0.4, y: size.height * 0.85 } });
2567
+ };
2568
+ await create();
2569
+ await expect(nodes).toHaveCount(3);
2570
+ await page.locator('#save').click();
2571
+ await expect(page.locator('#status')).toHaveText('saved the diagram');
2572
+ // A second, left unsaved: the switch saves the diagram it leaves.
2573
+ await create();
2574
+ await expect(nodes).toHaveCount(4);
2575
+ await page.locator('#file').selectOption('references.${diagram?.extensions[0]}');
2576
+ await expect(page.locator('#diagram .external')).toBeVisible();
2577
+
2578
+ await page.reload();
2579
+ await expect(page.locator('#status')).toHaveText('ready');
2580
+ await expect(nodes).toHaveCount(4);`;
2581
+ const guardTest = diagram === undefined
2582
+ ? ''
2583
+ : `
2584
+ test('asks before a reload drops a diagram edit the server has not answered, and saves it with Save at once', async ({ page }) => {
2585
+ const nodes = page.locator('#diagram .sprotty-node');
2586
+ const askGuard = (): Promise<boolean> =>
2587
+ page.evaluate(() => {
2588
+ const event = new Event('beforeunload', { cancelable: true });
2589
+ window.dispatchEvent(event);
2590
+ return event.defaultPrevented;
2591
+ });
2592
+ await page.goto('/');
2593
+ await expect(page.locator('#status')).toHaveText('ready');
2594
+ await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');
2595
+ await expect(nodes).toHaveCount(2);
2596
+
2597
+ const canvas = page.locator('#diagram');
2598
+ await page.locator('#diagram .tool-button', { hasText: '${diagram.nodeRule}' }).click();
2599
+ const size = await canvas.evaluate(element => ({ width: element.clientWidth, height: element.clientHeight }));
2600
+ // Asked and clicked right after the click's own handlers, in the same turn
2601
+ // of the page, so the server's answer cannot have marked anything unsaved.
2602
+ await page.evaluate(() => {
2603
+ window.addEventListener(
2604
+ 'mouseup',
2605
+ () =>
2606
+ queueMicrotask(() => {
2607
+ const event = new Event('beforeunload', { cancelable: true });
2608
+ window.dispatchEvent(event);
2609
+ document.getElementById('save')?.click();
2610
+ Reflect.set(window, 'guardedOnCreate', event.defaultPrevented);
2611
+ }),
2612
+ { once: true }
2613
+ );
2614
+ });
2615
+ await canvas.click({ position: { x: size.width * 0.4, y: size.height * 0.85 } });
2616
+ expect(await page.evaluate(() => Reflect.get(window, 'guardedOnCreate'))).toBe(true);
2617
+ await expect(page.locator('#status')).toHaveText('${lsp ? 'saved 1 file(s)' : 'saved the diagram'}');
2618
+ expect(await askGuard()).toBe(false);
2619
+
2620
+ await page.reload();
2621
+ await expect(page.locator('#status')).toHaveText('ready');
2622
+ await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');
2623
+ await expect(nodes).toHaveCount(3);
2624
+ });
2625
+ `;
2626
+ const locators = [
2627
+ ...(lsp ? [" const editor = page.locator('#editor .view-lines');"] : []),
2628
+ ...(lsp ? [] : [" const nodes = page.locator('#diagram .sprotty-node');"])
2629
+ ];
2630
+ return `// The page loads with every head answering, and an edit saved through the
2631
+ // ${lsp ? 'LSP head' : 'GLSP head'} is still there after a reload; any console error fails that
2632
+ // test. The other asks before a reload drops a diagram edit the server has not
2633
+ // answered yet, and keeps it when Save is clicked at once.
2634
+
2635
+ import { expect, test } from '@playwright/test';
2636
+
2637
+ test('loads every head and keeps a saved ${lsp ? 'edit' : 'diagram edit'} across a reload', async ({ page }) => {
2638
+ const errors: string[] = [];
2639
+ page.on('pageerror', error => errors.push(error.message));
2640
+ page.on('console', message => {
2641
+ if (message.type() === 'error') {
2642
+ errors.push(message.text());
2643
+ }
2644
+ });
2645
+ ${locators.join('\n')}
2646
+
2647
+ await page.goto('/');
2648
+ await expect(page.locator('#status')).toHaveText('ready');
2649
+ ${checks.join('\n')}
2650
+
2651
+ ${edit}
2652
+ expect(errors).toEqual([]);
2653
+ });
2654
+ ${guardTest}`;
2655
+ }
2656
+ /** The browser host's README. */
2657
+ function hostBrowserReadme(composition) {
2658
+ const lsp = composition.heads.includes('lsp');
2659
+ const data = composition.heads.includes('data');
2660
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2661
+ const lines = [
2662
+ `# ${memberPackageName(composition, 'host-browser')}`,
2663
+ '',
2664
+ '__NAME__ in a browser page: every head runs in a web worker, with no backend',
2665
+ `and no Node runtime. The page saves through the ${lsp ? 'LSP head' : 'GLSP head'}, and the worker`,
2666
+ 'keeps each saved file in IndexedDB, laid over `../workspace` on the next',
2667
+ 'load.',
2668
+ '',
2669
+ '```bash',
2670
+ 'npm run build # type-check and bundle into out/',
2671
+ 'npm start # serve the page at the URL it prints, rebundled on every source change',
2672
+ 'npm run test:e2e:install # download the Chromium the smoke test drives, once',
2673
+ 'npm run test:e2e # the smoke test, which serves the page itself',
2674
+ '```',
2675
+ '',
2676
+ '`PORT` moves the page to another port, for `npm start` and the smoke test alike;',
2677
+ 'stop `npm start` before the smoke test, or give one of them another port.',
2678
+ '`npm start` reads `../workspace` once, so restart it after editing a file',
2679
+ 'there.',
2680
+ '',
2681
+ '## Layout',
2682
+ '',
2683
+ '- `index.html` — the page, with a pane for each head that stays hidden until its part fills it',
2684
+ '- `hydranium-mark.svg` — the tab icon',
2685
+ `- \`esbuild.mjs\` — bundles the page${lsp ? ', the worker and Monaco’s worker' : ' and the worker'}, reading \`../workspace\` in as the seed`,
2686
+ '- `src/worker.ts` — the worker: the heads over one store, seeded and persisted',
2687
+ '- `src/page.ts` — starts the worker and runs the part of the page each head serves',
2688
+ '- `src/shown-file.ts` — the file switch above the panes, which every part follows',
2689
+ ...(lsp ? ['- `src/editor.ts` — the LSP part: a Monaco editor and Save'] : []),
2690
+ ...(data ? ['- `src/data-status.ts` — the data part: one document read through the data head'] : []),
2691
+ ...(diagram === undefined
2692
+ ? []
2693
+ : [
2694
+ `- \`src/diagram.ts\` — the GLSP part: the \`${diagram.grammar}\` diagram of the file the page shows, defined in the client package`
2695
+ ]),
2696
+ ...(lsp ? [] : ['- `src/diagram-save.ts` — Save with no editor: the diagram saved through the GLSP head']),
2697
+ '- `src/log.ts` — the status line and the log area',
2698
+ '- `src/workspace.ts` — the workspace root URI both ends name',
2699
+ ...(lsp ? ['- `src/monaco-editor-worker.ts` — Monaco’s own worker, which hosts no head'] : []),
2700
+ '- `src/posix-path-shim.ts` — the `path` function the framework imports, for the bundle',
2701
+ '- `test/smoke.spec.mts` — the page loads, each head answers, and a saved edit survives a reload',
2702
+ ''
2703
+ ];
2704
+ return project(lines.join('\n'), composition);
2705
+ }
2706
+ /** The page with the line under its log view saying what shows there, which the LSP head decides. */
2707
+ function withLogHint(page, lsp) {
2708
+ const hint = lsp
2709
+ ? 'What the server logs over the LSP head, and the errors the page reports.'
2710
+ : "The errors the page reports. The server logs to the worker's console, in the browser's developer tools.";
2711
+ return { ...page, content: page.content.replace('__LOG_HINT__', hint) };
2712
+ }
2713
+ /** The browser host: a page and a worker, bundled by esbuild and served as static files. */
2714
+ function hostBrowserFiles(composition) {
2715
+ const fixed = (file) => projectTemplate(`host-browser/${file}`, composition);
2716
+ const lsp = composition.heads.includes('lsp');
2717
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2718
+ return [
2719
+ { path: 'host-browser/package.json', content: hostBrowserPackageJson(composition) },
2720
+ ignoreFile('host-browser'),
2721
+ { path: 'host-browser/README.md', content: hostBrowserReadme(composition) },
2722
+ withLogHint(fixed('index.html'), lsp),
2723
+ fixed('hydranium-mark.svg'),
2724
+ fixed('esbuild.mjs'),
2725
+ fixed('playwright.config.mts'),
2726
+ fixed('tsconfig.worker.json'),
2727
+ fixed('tsconfig.page.json'),
2728
+ fixed('tsconfig.e2e.json'),
2729
+ { path: 'host-browser/src/worker.ts', content: hostWorkerFile(composition) },
2730
+ { path: 'host-browser/src/page.ts', content: hostPageFile(composition) },
2731
+ fixed('src/shown-file.ts'),
2732
+ ...(lsp ? [fixed('src/editor.ts')] : []),
2733
+ ...(composition.heads.includes('data') ? [fixed('src/data-status.ts')] : []),
2734
+ ...(diagram === undefined ? [] : [grammarTemplate('host-browser/src/diagram.ts', composition, diagram)]),
2735
+ ...(lsp ? [] : [fixed('src/diagram-save.ts')]),
2736
+ fixed('src/log.ts'),
2737
+ fixed('src/workspace.ts'),
2738
+ ...(lsp ? [fixed('src/monaco-editor-worker.ts'), fixed('src/monaco-editor-core-worker.d.ts')] : []),
2739
+ fixed('src/posix-path-shim.ts'),
2740
+ { path: 'host-browser/test/smoke.spec.mts', content: hostSmokeSpec(composition) }
2741
+ ];
2742
+ }
2743
+ /** A JSON value as it sits at `indent` in a manifest npm writes. */
2744
+ function jsonAt(value, indent) {
2745
+ return JSON.stringify(value, null, 2).replace(/\n/g, `\n${indent}`);
2746
+ }
2747
+ /**
2748
+ * The languages and grammars a VS Code extension contributes. Each extension
2749
+ * declares its own, since either may be installed without the other; the
2750
+ * grammars are the server's, copied in by `copy:syntaxes`.
2751
+ */
2752
+ function vscodeLanguageContributions(composition) {
2753
+ return {
2754
+ grammars: composition.grammars.map(grammar => ({
2755
+ language: grammar.languageId,
2756
+ scopeName: `source.${grammar.languageId}`,
2757
+ path: `./syntaxes/${grammar.languageId}.tmLanguage.json`
2758
+ })),
2759
+ languages: composition.grammars.map(grammar => ({
2760
+ id: grammar.languageId,
2761
+ aliases: [grammar.grammar],
2762
+ extensions: grammar.extensions.map(extension => `.${extension}`)
2763
+ }))
2764
+ };
2765
+ }
2766
+ /** VS Code finds the grammars only inside the extension, so the build copies the server's. */
2767
+ const COPY_SYNTAXES_SCRIPT = "require('node:fs').cpSync('../server/syntaxes', 'syntaxes', { recursive: true })";
2768
+ const COPY_SYNTAXES = `node -e \\"${COPY_SYNTAXES_SCRIPT}\\"`;
2769
+ /** `copy:syntaxes`, then again each time the server's `langium:watch` rewrites a grammar. */
2770
+ const WATCH_SYNTAXES = `node -e \\"const copy = () => ${COPY_SYNTAXES_SCRIPT}; copy(); require('node:fs').watch('../server/syntaxes', copy)\\"`;
2771
+ /**
2772
+ * The servers-only extension's `package.json`. Always private, like a host:
2773
+ * it is installed into an application, never as a dependency.
2774
+ *
2775
+ * `onStartupFinished` rather than `onLanguage`, since a Theia backend asks for
2776
+ * a port before any document is open.
2777
+ */
2778
+ function vscodeServersPackageJson(composition) {
2779
+ const dependencies = {
2780
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
2781
+ [memberPackageName(composition, 'server')]: MEMBER_PIN,
2782
+ ...VSCODE_LANGUAGE_CLIENT
2783
+ };
2784
+ if (socketHeads(composition).length > 0) {
2785
+ dependencies['@hydranium/client-vscode'] = frameworkPin(composition);
2786
+ }
2787
+ return `{
2788
+ "name": "${memberPackageName(composition, 'vscode-servers')}",
2789
+ "displayName": "${composition.name} Servers",
2790
+ "version": "0.0.0",
2791
+ "private": true,
2792
+ "description": "Starts the ${composition.name} server${socketHeads(composition).length > 0 ? " and publishes its socket heads' ports as host commands" : ''}, with no editor of its own.",
2793
+ "license": "UNLICENSED",
2794
+ "author": "",
2795
+ "publisher": "${composition.projectId}",
2796
+ "main": "./out/extension.js",
2797
+ "scripts": {
2798
+ "build": "npm run copy:syntaxes && tsc",
2799
+ "clean": "rimraf out syntaxes tsconfig.tsbuildinfo",
2800
+ "copy:syntaxes": "${COPY_SYNTAXES}",
2801
+ ${lintScript(forMember(composition, 'vscode-servers'), 'src')} "watch": "concurrently --kill-others --names syntaxes,tsc \\"npm run watch:syntaxes\\" \\"tsc --watch\\"",
2802
+ "watch:syntaxes": "${WATCH_SYNTAXES}"
2803
+ },
2804
+ "dependencies": {
2805
+ ${sortedBlock(dependencies, ' ')}
2806
+ },
2807
+ "devDependencies": {
2808
+ ${sortedBlock({ '@types/node': '^22.0.0', '@types/vscode': VSCODE_ENGINE, concurrently: '^9.0.0', rimraf: '^5.0.0', typescript: '^7.0.2' }, ' ')}
2809
+ },
2810
+ "contributes": ${jsonAt(vscodeLanguageContributions(composition), ' ')},
2811
+ "activationEvents": [
2812
+ "onStartupFinished"
2813
+ ],
2814
+ "engines": {
2815
+ "vscode": "${VSCODE_ENGINE}"
2816
+ }
2817
+ }
2818
+ `;
2819
+ }
2820
+ /**
2821
+ * The servers-only extension's activation: the shared launch, and with a socket
2822
+ * head the port commands, which only this extension registers.
2823
+ */
2824
+ function vscodeServersExtensionFile(composition) {
2825
+ const upper = screamingSnake(composition.projectId);
2826
+ const heads = socketHeads(composition).map(head => head.key);
2827
+ const protocolSymbols = heads.flatMap(head => [`${upper}_${head}_HOST_COMMAND`, `${upper}_${head}_PORT_COMMAND`]);
2828
+ const imports = heads.length === 0
2829
+ ? ''
2830
+ : `import { registerPortCommands } from '@hydranium/client-vscode/node';
2831
+ ${importList(protocolSymbols, memberPackageName(composition, 'protocol'), columnsFor(composition))}
2832
+ `;
2833
+ const portCommands = heads.length === 0
2834
+ ? ''
2835
+ : `
2836
+
2837
+ // Each socket head's port as a host command, for a host with no language
2838
+ // client of its own. Not in the shared launch: VS Code throws on a second
2839
+ // registration of one id, so the VS Code extension beside this one would fail
2840
+ // to activate. A pass-through: awaiting anything else in it would hang a
2841
+ // Theia backend on a user dismissing a notification.
2842
+ registerPortCommands(context, client, {
2843
+ ${heads.map(head => ` [${upper}_${head}_HOST_COMMAND]: ${upper}_${head}_PORT_COMMAND`).join(',\n')}
2844
+ });`;
2845
+ return `// The servers-only extension: it starts the ${composition.name} server and contributes no
2846
+ // editor, view or command. A Theia app sideloads this one rather than the VS
2847
+ // Code extension, whose diagram editors would give its files a second editor.
2848
+
2849
+ ${imports}import type { ExtensionContext } from 'vscode';
2850
+ import type { LanguageClient } from 'vscode-languageclient/node';
2851
+ import { start${composition.name}LanguageClient } from './language-client.js';
2852
+
2853
+ let client: LanguageClient | undefined;
2854
+
2855
+ export async function activate(context: ExtensionContext): Promise<void> {
2856
+ client = await start${composition.name}LanguageClient(context);${portCommands}
2857
+ }
2858
+
2859
+ export async function deactivate(): Promise<void> {
2860
+ await client?.stop();
2861
+ client = undefined;
2862
+ }
2863
+ `;
2864
+ }
2865
+ /**
2866
+ * The server launch both extensions share: one launch, so VS Code and a Theia
2867
+ * app sideloading the servers extension hand the server the same documents.
2868
+ */
2869
+ function vscodeLanguageClientFile(composition) {
2870
+ return `// Starts the ${composition.name} server for VS Code, and for a Theia app that sideloads
2871
+ // this extension: one launch, so both hand the server the same documents.
2872
+
2873
+ import { ALL_LANGUAGES } from '${memberPackageName(composition, 'protocol')}';
2874
+ import { type ExtensionContext, workspace } from 'vscode';
2875
+ import { LanguageClient, TransportKind } from 'vscode-languageclient/node';
2876
+
2877
+ /** Fork the server, start its language client and return it once started. */
2878
+ export async function start${composition.name}LanguageClient(context: ExtensionContext): Promise<LanguageClient> {
2879
+ // Resolved through the package, so it works from the workspace and from an
2880
+ // installed extension alike. Over IPC, which keeps the server's stdout free.
2881
+ const serverModule = require.resolve('${memberPackageName(composition, 'server')}/lib/main.js');
2882
+ const extensions = ALL_LANGUAGES.flatMap(language => language.fileExtensions).join(',');
2883
+ const client = new LanguageClient(
2884
+ '${composition.projectId}',
2885
+ '${composition.name}',
2886
+ { module: serverModule, transport: TransportKind.ipc },
2887
+ {
2888
+ documentSelector: ALL_LANGUAGES.map(({ languageId }) => ({ scheme: 'file', language: languageId })),
2889
+ // Changes on disk the editor does not hold, such as a file another tool writes.
2890
+ synchronize: { fileEvents: workspace.createFileSystemWatcher(\`**/*{\${extensions}}\`) }
2891
+ }
2892
+ );
2893
+ context.subscriptions.push(client);
2894
+ await client.start();
2895
+
2896
+ return client;
2897
+ }
2898
+ `;
2899
+ }
2900
+ /** The folders of the Theia applications the composition emits, as code spans. */
2901
+ function theiaApplicationPaths(composition) {
2902
+ return composition.hosts.filter(isTheiaHost).map(host => `\`../host-${host}\``);
2903
+ }
2904
+ /** The servers-only extension's README. */
2905
+ function vscodeServersReadme(composition) {
2906
+ const vscode = composition.hosts.includes('vscode');
2907
+ const theiaApps = theiaApplicationPaths(composition);
2908
+ const intro = [
2909
+ 'A VS Code extension that starts the __NAME__ server and contributes no editor, view or command: the languages, their grammars and the server.',
2910
+ `With a socket head, it also answers each head’s port under a host command, which a host without a language client of its own runs${theiaApps.length > 0
2911
+ ? theiaApps.length === 1
2912
+ ? `: the Theia application in ${theiaApps[0]}, which sideloads this extension.`
2913
+ : `: the Theia applications in ${listPhrase(theiaApps)}, which sideload this extension.`
2914
+ : ', such as a Theia app sideloading this extension.'}`,
2915
+ ...(vscode
2916
+ ? [
2917
+ 'The VS Code extension in `../host-vscode` starts the server through the same function.',
2918
+ 'Both work side by side, but each starts its own server and language client, so diagnostics may show twice: install one.'
2919
+ ]
2920
+ : [])
2921
+ ];
2922
+ const lines = [
2923
+ `# ${memberPackageName(composition, 'vscode-servers')}`,
2924
+ '',
2925
+ ...wrapProse(intro.join(' ')),
2926
+ '',
2927
+ '```bash',
2928
+ 'npm run build # copy the server’s grammars and compile into out/; build the server first',
2929
+ 'npm run watch # the same on every change',
2930
+ '```',
2931
+ '',
2932
+ '- `src/extension.ts` — activation, which starts the server and, with a socket head, registers its port commands',
2933
+ `- \`src/language-client.ts\` — the server launch${vscode ? ', shared with `../host-vscode`' : ''}`,
2934
+ ''
2935
+ ];
2936
+ return project(lines.join('\n'), composition);
2937
+ }
2938
+ /** The servers-only extension: the server's launch, without an editor. */
2939
+ function vscodeServersFiles(composition) {
2940
+ return [
2941
+ { path: 'vscode-servers/package.json', content: vscodeServersPackageJson(composition) },
2942
+ ignoreFile('vscode-servers'),
2943
+ { path: 'vscode-servers/README.md', content: vscodeServersReadme(composition) },
2944
+ projectTemplate('vscode-servers/tsconfig.json', composition),
2945
+ { path: 'vscode-servers/src/extension.ts', content: vscodeServersExtensionFile(composition) },
2946
+ { path: 'vscode-servers/src/language-client.ts', content: vscodeLanguageClientFile(composition) }
2947
+ ];
2948
+ }
2949
+ /**
2950
+ * The custom-editor view type of a grammar's diagram, as the editor module
2951
+ * declares it. VS Code keys custom editors by view type alone, across every
2952
+ * installed extension, so it carries the language id, which `init` qualifies
2953
+ * by the project wherever the grammar is named apart from it.
2954
+ */
2955
+ function diagramViewType(grammar) {
2956
+ return `${grammar.languageId}.diagram`;
2957
+ }
2958
+ /**
2959
+ * The VS Code extension's `package.json`. Always private, as every host is.
2960
+ *
2961
+ * A diagram file opens in its diagram by default; `Reopen Editor With` reaches
2962
+ * the text.
2963
+ */
2964
+ function hostVscodePackageJson(composition) {
2965
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
2966
+ const dependencies = {
2967
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
2968
+ ...VSCODE_LANGUAGE_CLIENT
2969
+ };
2970
+ if (diagrams.length > 0) {
2971
+ dependencies[memberPackageName(composition, 'client')] = MEMBER_PIN;
2972
+ dependencies[memberPackageName(composition, 'protocol')] = MEMBER_PIN;
2973
+ Object.assign(dependencies, HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES);
2974
+ for (const framework of HOST_VSCODE_GLSP_FRAMEWORK_DEPENDENCIES) {
2975
+ dependencies[framework] = frameworkPin(composition);
2976
+ }
2977
+ }
2978
+ if (composition.heads.includes('data')) {
2979
+ dependencies[memberPackageName(composition, 'protocol')] = MEMBER_PIN;
2980
+ Object.assign(dependencies, HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES);
2981
+ for (const framework of HOST_VSCODE_DATA_FRAMEWORK_DEPENDENCIES) {
2982
+ dependencies[framework] = frameworkPin(composition);
2983
+ }
2984
+ }
2985
+ const devDependencies = { ...HOST_VSCODE_DEV_DEPENDENCIES, ...(diagrams.length > 0 ? { esbuild: '^0.28.0' } : {}) };
2986
+ const watches = {
2987
+ syntaxes: 'npm run watch:syntaxes',
2988
+ tsc: 'tsc --watch',
2989
+ ...(diagrams.length > 0 ? { webview: 'node esbuild.mjs --watch' } : {})
2990
+ };
2991
+ const watchNames = Object.keys(watches).join(',');
2992
+ const watchCommands = Object.values(watches)
2993
+ .map(command => `\\"${command}\\"`)
2994
+ .join(' ');
2995
+ const contributes = {
2996
+ ...(composition.heads.includes('data')
2997
+ ? { commands: [{ command: `${composition.projectId}.showModel`, title: 'Show Model', category: composition.name }] }
2998
+ : {}),
2999
+ ...(diagrams.length > 0
3000
+ ? {
3001
+ customEditors: diagrams.map(grammar => ({
3002
+ viewType: diagramViewType(grammar),
3003
+ displayName: `${grammar.grammar} Diagram`,
3004
+ selector: grammar.extensions.map(extension => ({ filenamePattern: `*.${extension}` })),
3005
+ priority: 'default'
3006
+ }))
3007
+ }
3008
+ : {}),
3009
+ ...vscodeLanguageContributions(composition)
3010
+ };
3011
+ const typecheck = [...(diagrams.length > 0 ? ['tsconfig.webview.json'] : []), 'tsconfig.e2e.json']
3012
+ .map(project => `tsc --noEmit -p ${project}`)
3013
+ .join(' && ');
3014
+ return `{
3015
+ "name": "${memberPackageName(composition, 'host-vscode')}",
3016
+ "displayName": "${composition.name}",
3017
+ "version": "0.0.0",
3018
+ "private": true,
3019
+ "description": "${composition.name} in VS Code: ${hostVscodeParts(composition)}.",
3020
+ "license": "UNLICENSED",
3021
+ "author": "",
3022
+ "publisher": "${composition.projectId}",
3023
+ "main": "./out/extension.js",
3024
+ "scripts": {
3025
+ "build": "npm run copy:syntaxes && npm run typecheck && tsc${diagrams.length > 0 ? ' && node esbuild.mjs' : ''}",
3026
+ "clean": "rimraf out syntaxes tsconfig.tsbuildinfo test-results playwright-report",
3027
+ "copy:syntaxes": "${COPY_SYNTAXES}",
3028
+ ${lintScript(forMember(composition, 'host-vscode'), 'src test')} "start": "node start.mjs",
3029
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
3030
+ "test:e2e:install": "node --experimental-strip-types test/install-vscode.mts",
3031
+ "typecheck": "${typecheck}",
3032
+ "watch": "concurrently --kill-others --names ${watchNames} ${watchCommands}",
3033
+ "watch:syntaxes": "${WATCH_SYNTAXES}"
3034
+ },
3035
+ "dependencies": {
3036
+ ${sortedBlock(dependencies, ' ')}
3037
+ },
3038
+ "devDependencies": {
3039
+ ${sortedBlock(devDependencies, ' ')}
3040
+ },
3041
+ "contributes": ${jsonAt(contributes, ' ')},
3042
+ "activationEvents": ${jsonAt(composition.grammars.map(grammar => `onLanguage:${grammar.languageId}`), ' ')},
3043
+ "engines": {
3044
+ "vscode": "${VSCODE_ENGINE}"
3045
+ }
3046
+ }
3047
+ `;
3048
+ }
3049
+ /** What the VS Code extension brings, as one phrase; `started` follows the language client. */
3050
+ function hostVscodeParts(composition, started = '') {
3051
+ const parts = [
3052
+ `the language client${started}`,
3053
+ ...(composition.heads.includes('data') ? ['a Show Model command reading a file through the data head'] : []),
3054
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['a custom editor for each diagram'] : [])
3055
+ ];
3056
+ return listPhrase(parts);
3057
+ }
3058
+ /** `parts` as one English list: `a`, `a and b`, `a, b, and c`. */
3059
+ function listPhrase(parts) {
3060
+ return parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(', ')}${parts.length > 2 ? ',' : ''} and ${parts.at(-1)}`;
3061
+ }
3062
+ /**
3063
+ * The VS Code extension's entry: the shared server launch, then the Show Model
3064
+ * command over the data head and a diagram editor per diagram grammar.
3065
+ */
3066
+ function hostVscodeExtensionFile(composition) {
3067
+ const columns = columnsFor(composition);
3068
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3069
+ const data = composition.heads.includes('data');
3070
+ const start = `start${composition.name}LanguageClient`;
3071
+ const servers = `${memberPackageName(composition, 'vscode-servers')}/out/language-client.js`;
3072
+ const upper = screamingSnake(composition.projectId);
3073
+ const editors = diagrams.map(grammar => ({
3074
+ module: `./${grammar.grammarId}-diagram-editor.js`,
3075
+ viewType: `${screamingSnake(grammar.grammarId)}_DIAGRAM_VIEW_TYPE`,
3076
+ provider: `${grammar.grammar}DiagramEditorProvider`,
3077
+ local: `${grammar.grammar.charAt(0).toLowerCase()}${grammar.grammar.slice(1)}Editor`
3078
+ }));
3079
+ const registrations = editors.map(editor => ` const ${editor.local} = new ${editor.provider}(glspConnector, context.extensionUri);
3080
+ context.subscriptions.push(
3081
+ window.registerCustomEditorProvider(${editor.viewType}, ${editor.local}, {
3082
+ // A hidden tab keeps its diagram session rather than repeating the handshake.
3083
+ webviewOptions: { retainContextWhenHidden: true },
3084
+ // Two views of one document would be two GLSP clients racing on one model.
3085
+ supportsMultipleEditorsPerDocument: false
3086
+ })
3087
+ );`);
3088
+ const sockets = data || diagrams.length > 0;
3089
+ const protocolSymbols = [
3090
+ ...(data ? [`${upper}_DATA_SERVER_PORT_COMMAND`] : []),
3091
+ ...(diagrams.length > 0 ? [`${upper}_GLSP_SERVER_PORT_COMMAND`] : []),
3092
+ ...(data ? [`type ${composition.name}Element`] : [])
3093
+ ];
3094
+ const imports = [
3095
+ ...(sockets ? ["import { findPort } from '@hydranium/client-vscode/node';"] : []),
3096
+ ...(data ? ["import { SocketDataPort } from '@hydranium/data-client-vscode/node';"] : []),
3097
+ ...(diagrams.length > 0
3098
+ ? ["import { HydraniumGlspVscodeConnector, HydraniumGlspVscodeServer } from '@hydranium/glsp-client-vscode/node';"]
3099
+ : []),
3100
+ ...(sockets
3101
+ ? [
3102
+ importList([
3103
+ 'ConsoleLogger',
3104
+ ...(data ? ['DataConnectionWithEvents'] : []),
3105
+ ...(diagrams.length > 0 ? ['describeError'] : []),
3106
+ ...(data ? ['renderFrameworkMessage'] : [])
3107
+ ], '@hydranium/protocol', columns)
3108
+ ]
3109
+ : []),
3110
+ ...(sockets ? [importList(protocolSymbols, memberPackageName(composition, 'protocol'), columns)] : []),
3111
+ ...(sockets
3112
+ ? [`import { ${[...(data ? ['commands'] : []), 'type ExtensionContext', 'window'].join(', ')} } from 'vscode';`]
3113
+ : ["import type { ExtensionContext } from 'vscode';"]),
3114
+ "import type { LanguageClient } from 'vscode-languageclient/node';",
3115
+ `import { ${start} } from '${servers}';`,
3116
+ ...editors.map(editor => importList([editor.viewType, editor.provider], editor.module, columns)),
3117
+ ...(data ? ["import { showModelCommand } from './show-model-command.js';"] : [])
3118
+ ];
3119
+ const dataBlock = data
3120
+ ? `
3121
+
3122
+ // The data head, read by the Show Model command. Nothing connects until it runs.
3123
+ const dataPort = new SocketDataPort({
3124
+ findPort: () => findPort(running, ${upper}_DATA_SERVER_PORT_COMMAND),
3125
+ logger: new ConsoleLogger().with('data head'),
3126
+ // A failed read shown to the user, not only logged; the message carries the detail.
3127
+ reportError: (_error, reported) => void window.showErrorMessage(renderFrameworkMessage(reported))
3128
+ });
3129
+ const dataConnection = new DataConnectionWithEvents<${composition.name}Element>(dataPort);
3130
+ context.subscriptions.push(dataConnection, dataPort, commands.registerCommand('${composition.projectId}.showModel', showModelCommand(dataConnection)));`
3131
+ : '';
3132
+ const glspBlock = diagrams.length > 0
3133
+ ? `
3134
+
3135
+ // The GLSP head, and the connector bridging it to every diagram webview. No
3136
+ // \`messenger\` option: the connector's own keeps messages flowing to a hidden tab.
3137
+ const glspServer = new HydraniumGlspVscodeServer({
3138
+ clientId: '${composition.projectId}-glsp',
3139
+ clientName: '${composition.name}',
3140
+ findPort: () => findPort(running, ${upper}_GLSP_SERVER_PORT_COMMAND),
3141
+ logger: new ConsoleLogger().with('GLSP head')
3142
+ });
3143
+ const glspConnector = new HydraniumGlspVscodeConnector({ server: glspServer, logging: false });
3144
+ context.subscriptions.push(glspServer, glspConnector);
3145
+ // Not awaited, so a session that opens no diagram does not wait on the port.
3146
+ // \`start()\` resolves either way; a failure is reported off \`onReady\`.
3147
+ void glspServer.start();
3148
+ void glspServer.onReady.catch((error: unknown) => {
3149
+ void window.showErrorMessage(\`${composition.name} diagram unavailable: \${describeError(error)}\`);
3150
+ });
3151
+ ${registrations.join('\n')}`
3152
+ : '';
3153
+ const opening = wrapComment(`The ${composition.name} VS Code extension: ${hostVscodeParts(composition, ', started the way the servers extension starts it')}.${sockets ? ' Node extension host only: the server is forked and its socket heads reached over TCP.' : ''}`);
3154
+ const activation = sockets
3155
+ ? ` const running = await ${start}(context);
3156
+ client = running;${dataBlock}${glspBlock}`
3157
+ : ` client = await ${start}(context);`;
3158
+ return `${opening}
3159
+
3160
+ ${imports.join('\n')}
3161
+
3162
+ let client: LanguageClient | undefined;
3163
+
3164
+ export async function activate(context: ExtensionContext): Promise<void> {
3165
+ ${activation}
3166
+ }
3167
+
3168
+ export async function deactivate(): Promise<void> {
3169
+ await client?.stop();
3170
+ client = undefined;
3171
+ }
3172
+ `;
3173
+ }
3174
+ /** A smoke test's title: what it checks of each head the composition has. */
3175
+ function hostVscodeSmokeTitle(composition) {
3176
+ return listPhrase([
3177
+ ...(composition.heads.includes('data') ? ['reads the model'] : []),
3178
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['draws the diagram'] : []),
3179
+ 'reports a broken reference'
3180
+ ]);
3181
+ }
3182
+ /**
3183
+ * The smoke test: VS Code opens the starter workspace with the extension
3184
+ * loaded, Show Model names the model with the data head, each diagram file
3185
+ * draws, and the server reports a broken reference.
3186
+ */
3187
+ function hostVscodeSmokeSpec(composition) {
3188
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
3189
+ const file = `nodes.${(diagram ?? composition.grammars[0]).extensions[0]}`;
3190
+ const diagramSteps = diagram
3191
+ ? `
3192
+ // The diagram file opens in its diagram, which draws the two starter nodes.
3193
+ const webview = page.frameLocator('iframe.webview.ready').frameLocator('#active-frame');
3194
+ // In the editor's container: sprotty measures shapes in a hidden copy beside it.
3195
+ await expect(webview.locator('.hydranium-diagram-container .sprotty-node')).toHaveCount(2);
3196
+ // Then as text. The row is clicked, since Enter runs the best fuzzy match,
3197
+ // and its name ends in its keybinding, if it has one.
3198
+ await page.keyboard.press('ControlOrMeta+Shift+P');
3199
+ await page.locator('.quick-input-widget input').fill('>View: Reopen Editor with Text Editor');
3200
+ await page
3201
+ .locator('.quick-input-list')
3202
+ .getByRole('option', { name: /^View: Reopen Editor with Text Editor(,|$)/ })
3203
+ .click();
3204
+ `
3205
+ : '';
3206
+ const primary = diagram ?? composition.grammars[0];
3207
+ const showModelSteps = composition.heads.includes('data')
3208
+ ? ` // The data head reads the open file.
3209
+ await page.keyboard.press('ControlOrMeta+Shift+P');
3210
+ await page.locator('.quick-input-widget input').fill('>${composition.name}: Show Model');
3211
+ await page
3212
+ .locator('.quick-input-list')
3213
+ .getByRole('option', { name: /^${composition.name}: Show Model(,|$)/ })
3214
+ .click();
3215
+ await expect(page.locator('.notification-toast').filter({ hasText: '${file} holds a ${primary.entryRule}' })).toBeVisible();
3216
+ `
3217
+ : '';
3218
+ const opening = wrapComment(`VS Code opens a copy of the starter workspace with this extension loaded, ${listPhrase([
3219
+ ...(composition.heads.includes('data') ? ['the data head reads the file'] : []),
3220
+ ...(diagram ? ['the diagram file draws in its diagram editor'] : []),
3221
+ 'the server reports a reference that resolves to nothing'
3222
+ ])}.`);
3223
+ return `${opening}
3224
+
3225
+ import { _electron, expect, test, type ElectronApplication, type Page } from '@playwright/test';
3226
+ import { downloadAndUnzipVSCode } from '@vscode/test-electron';
3227
+ import { cpSync, mkdtempSync, rmSync } from 'node:fs';
3228
+ import { tmpdir } from 'node:os';
3229
+ import { join } from 'node:path';
3230
+ import { fileURLToPath } from 'node:url';
3231
+ import { VSCODE_CACHE, VSCODE_VERSION } from './vscode-version.mts';
3232
+
3233
+ const extensionRoot = fileURLToPath(new URL('..', import.meta.url));
3234
+
3235
+ test('${hostVscodeSmokeTitle(composition)}', async () => {
3236
+ // A copy, since the server writes its repairs to the folder it opens, and a
3237
+ // fresh profile, since a reused one restores the last run's editors.
3238
+ const scratch = mkdtempSync(join(tmpdir(), '${composition.projectId}-vscode-'));
3239
+ const workspace = join(scratch, 'workspace');
3240
+ cpSync(fileURLToPath(new URL('../../workspace', import.meta.url)), workspace, { recursive: true });
3241
+ let app: ElectronApplication | undefined;
3242
+ try {
3243
+ app = await _electron.launch({
3244
+ executablePath: await downloadAndUnzipVSCode({ version: VSCODE_VERSION, cachePath: VSCODE_CACHE }),
3245
+ args: [
3246
+ '--no-sandbox',
3247
+ '--disable-gpu-sandbox',
3248
+ '--disable-updates',
3249
+ '--skip-welcome',
3250
+ '--skip-release-notes',
3251
+ '--disable-workspace-trust',
3252
+ '--disable-extensions',
3253
+ \`--extensionDevelopmentPath=\${extensionRoot}\`,
3254
+ \`--user-data-dir=\${join(scratch, 'user-data')}\`,
3255
+ \`--extensions-dir=\${join(scratch, 'extensions')}\`,
3256
+ workspace
3257
+ ]
3258
+ });
3259
+ const page = await app.firstWindow();
3260
+ await expect(page.locator('.monaco-workbench')).toBeVisible();
3261
+ await quickOpen(page, '${file}');
3262
+ ${showModelSteps}${diagramSteps}
3263
+ const editor = page.locator('.monaco-editor .view-lines').first();
3264
+ await expect(editor).toContainText('node First');
3265
+ await editor.click();
3266
+ await page.keyboard.press('ControlOrMeta+End');
3267
+ // In one edit: typed key by key, the half-typed reference is reported on the way.
3268
+ await page.keyboard.insertText('\\nnode Broken -> Missing');
3269
+ await expect(page.locator('.monaco-editor .squiggly-error').first()).toBeVisible();
3270
+ } finally {
3271
+ await app?.close();
3272
+ rmSync(scratch, { recursive: true, force: true });
3273
+ }
3274
+ });
3275
+
3276
+ /** Open \`file\` through Quick Open, so it gets the editor a user would. */
3277
+ async function quickOpen(page: Page, file: string): Promise<void> {
3278
+ await page.keyboard.press('ControlOrMeta+P');
3279
+ const input = page.locator('.quick-input-widget input');
3280
+ await input.fill(file);
3281
+ await expect(page.locator('.quick-input-list .monaco-list-row').first()).toContainText(file);
3282
+ await input.press('Enter');
3283
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
3284
+ }
3285
+ `;
3286
+ }
3287
+ /**
3288
+ * `text` broken at spaces into lines of at most 80 columns, the width
3289
+ * `check:docs` holds Markdown to. A link or code span stays whole, and runs
3290
+ * long on a line of its own.
3291
+ */
3292
+ function wrapProse(text, width = 80) {
3293
+ const lines = [];
3294
+ for (const piece of text.match(/!?\[[^\]]*\]\([^)]*\)\S*|`+[^`]*`+\S*|\S+/g) ?? []) {
3295
+ const last = lines.at(-1);
3296
+ if (last !== undefined && last.length + 1 + piece.length <= width) {
3297
+ lines[lines.length - 1] = `${last} ${piece}`;
3298
+ }
3299
+ else {
3300
+ lines.push(piece);
3301
+ }
3302
+ }
3303
+ return lines;
3304
+ }
3305
+ /** `text` as a `//` comment of lines at most 80 columns wide. */
3306
+ function wrapComment(text) {
3307
+ return wrapProse(text, 77)
3308
+ .map(line => `// ${line}`)
3309
+ .join('\n');
3310
+ }
3311
+ /** The VS Code extension's README. */
3312
+ function hostVscodeReadme(composition) {
3313
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3314
+ const data = composition.heads.includes('data');
3315
+ const intro = [
3316
+ diagrams.length > 0
3317
+ ? `${composition.name} in VS Code: the language client, and a custom editor drawing each diagram file.`
3318
+ : `${composition.name} in VS Code: the language client.`,
3319
+ 'The server is started by `../vscode-servers`, whose launch this extension calls, so the two never hand the server different documents.',
3320
+ socketHeads(composition).length > 0
3321
+ ? 'It needs a Node extension host: the server is forked, and its socket heads are reached over TCP.'
3322
+ : 'It needs a Node extension host, since the server is forked.'
3323
+ ];
3324
+ const dataNote = `\`${composition.name}: Show Model\`, in the Command Palette, reads the active file through the data head over a socket from the extension host, and names its root type. A webview reaches the data head too: see the Host in VS Code guide.`;
3325
+ const lines = [
3326
+ `# ${memberPackageName(composition, 'host-vscode')}`,
3327
+ '',
3328
+ ...wrapProse(intro.join(' ')),
3329
+ ...(data ? ['', ...wrapProse(dataNote)] : []),
3330
+ '',
3331
+ '```bash',
3332
+ `npm run build # copy the server’s grammars, type-check and compile${diagrams.length > 0 ? ', then bundle' : ''}`,
3333
+ `npm run watch # copy the grammars and recompile${diagrams.length > 0 ? ' and rebundle' : ''} on every change; Developer: Reload Window picks it up`,
3334
+ 'npm start # VS Code with this extension, on ../workspace; needs `code` on the PATH',
3335
+ 'npm run test:e2e:install # download the VS Code the smoke test drives, once',
3336
+ 'npm run test:e2e # the smoke test; under `xvfb-run -a` on Linux without a display',
3337
+ '```',
3338
+ '',
3339
+ '## Layout',
3340
+ '',
3341
+ `- \`src/extension.ts\` — activation: ${listPhrase([
3342
+ 'the server, through `../vscode-servers`',
3343
+ ...(data ? ['the Show Model command'] : []),
3344
+ ...(diagrams.length > 0 ? ['the diagram editors'] : [])
3345
+ ])}`,
3346
+ ...(data ? ['- `src/show-model-command.ts` — Show Model: the active file, read through the data head'] : []),
3347
+ ...diagrams.flatMap(grammar => [
3348
+ `- \`src/${grammar.grammarId}-diagram-editor.ts\` — the \`${grammar.grammar}\` diagram’s custom editor; its view type is the one \`package.json\` declares`,
3349
+ `- \`src/webview/${grammar.grammarId}-diagram.ts\` — the webview it loads, over the client package’s diagram`
3350
+ ]),
3351
+ ...(diagrams.length > 0
3352
+ ? ['- `src/webview/diagram.css` — the webview’s size and colours', '- `esbuild.mjs` — bundles each webview into `out/webview/`']
3353
+ : []),
3354
+ '- `start.mjs` — `npm start`: VS Code with this extension, on `../workspace`',
3355
+ '- `test/smoke.spec.mts` — VS Code opens the workspace, ' +
3356
+ (composition.heads.includes('data') ? 'Show Model names the model, ' : '') +
3357
+ (diagrams.length > 0 ? 'the diagram draws, ' : '') +
3358
+ 'and the server reports a broken reference',
3359
+ '- `test/vscode-version.mts` — the VS Code release the smoke test runs',
3360
+ ''
3361
+ ];
3362
+ return project(lines.join('\n'), composition);
3363
+ }
3364
+ /** The VS Code extension: the language client and a diagram editor per diagram grammar. */
3365
+ function hostVscodeFiles(composition) {
3366
+ const fixed = (file) => projectTemplate(`host-vscode/${file}`, composition);
3367
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3368
+ return [
3369
+ { path: 'host-vscode/package.json', content: hostVscodePackageJson(composition) },
3370
+ ignoreFile('host-vscode'),
3371
+ { path: 'host-vscode/README.md', content: hostVscodeReadme(composition) },
3372
+ fixed('tsconfig.json'),
3373
+ fixed('tsconfig.e2e.json'),
3374
+ fixed('playwright.config.mts'),
3375
+ fixed('start.mjs'),
3376
+ { path: 'host-vscode/src/extension.ts', content: hostVscodeExtensionFile(composition) },
3377
+ ...(composition.heads.includes('data') ? [fixed('src/show-model-command.ts')] : []),
3378
+ ...(diagrams.length > 0 ? [fixed('tsconfig.webview.json'), fixed('esbuild.mjs'), fixed('src/webview/diagram.css')] : []),
3379
+ ...diagrams.flatMap(grammar => [
3380
+ grammarTemplate('host-vscode/src/__GRAMMAR_ID__-diagram-editor.ts', composition, grammar),
3381
+ grammarTemplate('host-vscode/src/webview/__GRAMMAR_ID__-diagram.ts', composition, grammar)
3382
+ ]),
3383
+ { path: 'host-vscode/test/smoke.spec.mts', content: hostVscodeSmokeSpec(composition) },
3384
+ fixed('test/vscode-version.mts'),
3385
+ fixed('test/install-vscode.mts')
3386
+ ];
3387
+ }
3388
+ /**
3389
+ * The Theia release of every Theia member, the one the framework's own
3390
+ * Theia examples take, so a scaffold builds against what the repo tests: the
3391
+ * Theia community release. Exact, as Theia's members pin each other, so a
3392
+ * workspace root declares it too and GLSP's open Theia peer resolves to it.
3393
+ */
3394
+ const THEIA_VERSION = '1.74.3';
3395
+ /**
3396
+ * What each head adds to the Theia extension; `base` is the connection hardening
3397
+ * and editor sync every one gets. With the third-party entries below, they name
3398
+ * the peers of the framework's Theia packages, so an installer that adds no peers
3399
+ * still finds them.
3400
+ */
3401
+ const THEIA_FRAMEWORK_DEPENDENCIES = {
3402
+ base: ['@hydranium/client-theia', '@hydranium/protocol'],
3403
+ lsp: [],
3404
+ data: ['@hydranium/data-client-theia'],
3405
+ glsp: ['@hydranium/glsp-client', '@hydranium/glsp-client-theia']
3406
+ };
3407
+ const THEIA_THIRD_PARTY_DEPENDENCIES = {
3408
+ base: {
3409
+ '@theia/core': THEIA_VERSION,
3410
+ '@theia/editor': THEIA_VERSION,
3411
+ '@theia/filesystem': THEIA_VERSION,
3412
+ '@theia/output': THEIA_VERSION,
3413
+ inversify: '^6.1.3',
3414
+ 'vscode-jsonrpc': '9.0.0'
3415
+ },
3416
+ lsp: {},
3417
+ data: { '@theia/workspace': THEIA_VERSION },
3418
+ glsp: {
3419
+ '@eclipse-glsp/client': '2.7.0',
3420
+ '@eclipse-glsp/theia-integration': '2.7.0',
3421
+ '@theia/process': THEIA_VERSION,
3422
+ '@theia/workspace': THEIA_VERSION
3423
+ }
3424
+ };
3425
+ /** The Theia extension's third-party pins for `heads`, for its manifest and a workspace root's. */
3426
+ function theiaThirdPartyDependencies(heads) {
3427
+ return ['base', ...heads].flatMap(head => Object.entries(THEIA_THIRD_PARTY_DEPENDENCIES[head]));
3428
+ }
3429
+ /**
3430
+ * The Theia packages the application assembles: the workbench a user expects,
3431
+ * and `plugin-ext` with its VS Code API to sideload the servers extension.
3432
+ */
3433
+ const HOST_THEIA_BROWSER_DEPENDENCIES = [
3434
+ '@theia/core',
3435
+ '@theia/editor',
3436
+ '@theia/filesystem',
3437
+ '@theia/markers',
3438
+ '@theia/messages',
3439
+ '@theia/monaco',
3440
+ '@theia/navigator',
3441
+ '@theia/output',
3442
+ '@theia/plugin-ext',
3443
+ '@theia/plugin-ext-vscode',
3444
+ '@theia/preferences',
3445
+ '@theia/process',
3446
+ '@theia/workspace'
3447
+ ];
3448
+ /** The Theia tooling the application builds with. */
3449
+ const HOST_THEIA_BROWSER_DEV_DEPENDENCIES = ['@theia/cli'];
3450
+ /** Every Theia package the application declares, for a workspace root's pins. */
3451
+ function hostTheiaBrowserTheiaDependencies() {
3452
+ return [...HOST_THEIA_BROWSER_DEPENDENCIES, ...HOST_THEIA_BROWSER_DEV_DEPENDENCIES].map(name => [name, THEIA_VERSION]);
3453
+ }
3454
+ /** The Electron application's Theia packages: the browser application's, and Theia's Electron integration. */
3455
+ const HOST_THEIA_ELECTRON_DEPENDENCIES = [...HOST_THEIA_BROWSER_DEPENDENCIES, '@theia/electron'].sort();
3456
+ /** The Electron release `@theia/electron` peers on, exactly. */
3457
+ const ELECTRON_VERSION = '42.11.16';
3458
+ /** Every package the Electron application pins, for a workspace root's pins. */
3459
+ function hostTheiaElectronPins() {
3460
+ return [
3461
+ ...[...HOST_THEIA_ELECTRON_DEPENDENCIES, ...HOST_THEIA_BROWSER_DEV_DEPENDENCIES].map((name) => [
3462
+ name,
3463
+ THEIA_VERSION
3464
+ ]),
3465
+ ['electron', ELECTRON_VERSION]
3466
+ ];
3467
+ }
3468
+ /** The Theia extension's `theiaExtensions` entries: one per head it forwards, and one per diagram. */
3469
+ function theiaExtensionEntries(composition) {
3470
+ const id = composition.projectId;
3471
+ return [
3472
+ {
3473
+ frontendPreload: `lib/browser/${id}-connection-preload-module`,
3474
+ frontend: `lib/browser/${id}-frontend-module`,
3475
+ backend: `lib/node/${id}-connection-backend-module`
3476
+ },
3477
+ ...(composition.heads.includes('data') ? [{ backend: `lib/node/${id}-data-backend-module` }] : []),
3478
+ ...(composition.heads.includes('glsp') ? [{ backend: `lib/node/${id}-glsp-backend-module` }] : []),
3479
+ ...composition.grammars
3480
+ .filter(grammar => grammar.diagram)
3481
+ .map(grammar => ({ frontend: `lib/browser/${grammar.grammarId}-diagram-frontend-module` }))
3482
+ ];
3483
+ }
3484
+ /** The Theia extension's `package.json`. Private unless `--public`, as the client member is. */
3485
+ function theiaPackageJson(composition) {
3486
+ const dependencies = {
3487
+ // The socket heads' host commands, and the data head's model type.
3488
+ ...(socketHeads(composition).length > 0 ? { [memberPackageName(composition, 'protocol')]: MEMBER_PIN } : {}),
3489
+ ...(composition.heads.includes('glsp') ? { [memberPackageName(composition, 'client')]: MEMBER_PIN } : {}),
3490
+ ...Object.fromEntries(theiaThirdPartyDependencies(composition.heads))
3491
+ };
3492
+ for (const head of ['base', ...composition.heads]) {
3493
+ for (const framework of THEIA_FRAMEWORK_DEPENDENCIES[head]) {
3494
+ dependencies[framework] = frameworkPin(composition);
3495
+ }
3496
+ }
3497
+ return `{
3498
+ "name": "${memberPackageName(composition, 'theia')}",
3499
+ "version": "0.0.0",
3500
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "The ${composition.name} Theia extension: ${theiaParts(composition)}.",
3501
+ "license": "UNLICENSED",
3502
+ "author": "",
3503
+ "files": [
3504
+ "lib",
3505
+ "src",
3506
+ "style"
3507
+ ],
3508
+ "scripts": {
3509
+ "build": "tsc",
3510
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
3511
+ ${lintScript(forMember(composition, 'theia'), 'src')} "watch": "tsc --watch"
3512
+ },
3513
+ "dependencies": {
3514
+ ${sortedBlock(dependencies, ' ')}
3515
+ },
3516
+ "devDependencies": {
3517
+ ${sortedBlock({ '@types/node': '^22.0.0', rimraf: '^5.0.0', typescript: '^7.0.2' }, ' ')}
3518
+ },
3519
+ "engines": {
3520
+ "node": ">=22.13"
3521
+ },
3522
+ "theiaExtensions": ${jsonAt(theiaExtensionEntries(composition), ' ')}
3523
+ }
3524
+ `;
3525
+ }
3526
+ /** What the Theia extension brings, as one phrase. */
3527
+ function theiaParts(composition) {
3528
+ return listPhrase([
3529
+ 'reconnect hardening',
3530
+ ...(composition.heads.includes('data') ? ['a Show Model command reading a file through the data head'] : []),
3531
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['a diagram editor for each diagram'] : [])
3532
+ ]);
3533
+ }
3534
+ /** The extension's one frontend module: the logger, the connection diagnostics and editor sync, and each head's client. */
3535
+ function theiaFrontendModuleFile(composition) {
3536
+ const id = composition.projectId;
3537
+ const name = composition.name;
3538
+ const data = composition.heads.includes('data');
3539
+ const glsp = composition.heads.includes('glsp');
3540
+ const imports = [
3541
+ ...(glsp ? ["import { GLSPClientContribution } from '@eclipse-glsp/theia-integration';"] : []),
3542
+ "import { bindChannelLogger, bindConnectionDiagnostics, bindEditorDiskSync } from '@hydranium/client-theia/browser';",
3543
+ ...(data
3544
+ ? [
3545
+ "import { bindDataConnection } from '@hydranium/data-client-theia/browser';",
3546
+ "import { CommandContribution } from '@theia/core';"
3547
+ ]
3548
+ : []),
3549
+ "import { ContainerModule } from '@theia/core/shared/inversify';",
3550
+ ...(data
3551
+ ? [
3552
+ `import { ${name}DataConnection } from './${id}-data-connection.js';`,
3553
+ `import { ${name}DataPort } from './${id}-data-port.js';`
3554
+ ]
3555
+ : []),
3556
+ ...(glsp ? [`import { ${name}GlspClientContribution } from './${id}-glsp-client-contribution.js';`] : []),
3557
+ ...(data ? [`import { ${name}ShowModelCommand } from './${id}-show-model-command.js';`] : [])
3558
+ ];
3559
+ const dataBlock = data
3560
+ ? `
3561
+
3562
+ // The data head: one connection, opened when the command first runs.
3563
+ bind(${name}DataPort).toSelf().inSingletonScope();
3564
+ bindDataConnection(bind, isBound, ${name}DataConnection);
3565
+ bind(${name}ShowModelCommand).toSelf().inSingletonScope();
3566
+ bind(CommandContribution).toService(${name}ShowModelCommand);`
3567
+ : '';
3568
+ const glspBlock = glsp
3569
+ ? `
3570
+
3571
+ // One GLSP client for every diagram, so each diagram module skips binding its own.
3572
+ bind(${name}GlspClientContribution).toSelf().inSingletonScope();
3573
+ bind(GLSPClientContribution).toService(${name}GlspClientContribution);`
3574
+ : '';
3575
+ return `${wrapComment(`The ${name} Theia extension's frontend: ${listPhrase([
3576
+ 'the connection’s lifecycle in an Output channel',
3577
+ 'a warning when an outage outlasts the offline buffer',
3578
+ 'editor disk sync',
3579
+ ...(data ? ['the data head’s connection and the Show Model command'] : []),
3580
+ ...(glsp ? ['the GLSP client the diagrams share'] : [])
3581
+ ])}.`)}
3582
+
3583
+ ${imports.join('\n')}
3584
+
3585
+ export default new ContainerModule((bind, _unbind, isBound, rebind) => {
3586
+ bindChannelLogger(bind, { channelName: '${name} Connection' });
3587
+ bindConnectionDiagnostics(bind);
3588
+ // Keeps an editor from writing over a file a head saved while it held the same text unsaved.
3589
+ bindEditorDiskSync(bind, isBound, rebind);${dataBlock}${glspBlock}
3590
+ });
3591
+ `;
3592
+ }
3593
+ /** The Theia extension's README. */
3594
+ function theiaReadme(composition) {
3595
+ const id = composition.projectId;
3596
+ const data = composition.heads.includes('data');
3597
+ const glsp = composition.heads.includes('glsp');
3598
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3599
+ const theiaApps = theiaApplicationPaths(composition);
3600
+ const intro = [
3601
+ `The ${composition.name} Theia extension: ${theiaParts(composition)}.`,
3602
+ socketHeads(composition).length > 0
3603
+ ? 'The language client is not here: the application sideloads `../vscode-servers`, which starts the server and answers each socket head’s port under a host command, and the backend modules forward the page’s channels to those ports.'
3604
+ : 'The language client is not here: the application sideloads `../vscode-servers`, which starts the server.',
3605
+ theiaApps.length === 1 ? `The application in ${theiaApps[0]} runs it.` : `The applications in ${listPhrase(theiaApps)} run it.`
3606
+ ];
3607
+ const before = [...(socketHeads(composition).length > 0 ? ['protocol'] : []), ...(glsp ? ['client'] : [])];
3608
+ const lines = [
3609
+ `# ${memberPackageName(composition, 'theia')}`,
3610
+ '',
3611
+ ...wrapProse(intro.join(' ')),
3612
+ '',
3613
+ '```bash',
3614
+ 'npm run build # compile into lib/' +
3615
+ (before.length > 0 ? `; build the ${before.join(' and ')} package${before.length > 1 ? 's' : ''} first` : ''),
3616
+ '```',
3617
+ '',
3618
+ '## Layout',
3619
+ '',
3620
+ `- \`src/browser/${id}-connection-preload-module.ts\` and \`src/node/${id}-connection-backend-module.ts\` — reconnect hardening, sized by the application’s \`connectionBufferBytes\``,
3621
+ `- \`src/browser/${id}-frontend-module.ts\` — the frontend bindings`,
3622
+ ...(data
3623
+ ? [
3624
+ `- \`src/browser/${id}-data-port.ts\` and \`${id}-data-connection.ts\` — the data head’s connection`,
3625
+ `- \`src/browser/${id}-show-model-command.ts\` — \`${composition.name}: Show Model\`, reading the current file through the data head`,
3626
+ `- \`src/node/${id}-data-backend-module.ts\` — forwards the data channel to the data head’s port`
3627
+ ]
3628
+ : []),
3629
+ ...(glsp
3630
+ ? [
3631
+ `- \`src/common/${id}-glsp-contribution.ts\` — the id the GLSP client and its forwarder share`,
3632
+ `- \`src/browser/${id}-glsp-client-contribution.ts\` — the GLSP client every diagram shares`,
3633
+ `- \`src/node/${id}-glsp-backend-module.ts\` — forwards the GLSP channel to the GLSP head’s port`
3634
+ ]
3635
+ : []),
3636
+ ...diagrams.map(grammar => `- \`src/browser/${grammar.grammarId}-diagram-frontend-module.ts\` — the \`${grammar.grammar}\` diagram editor, over the client package’s diagram`),
3637
+ ...(diagrams.length > 0 ? ['- `style/diagram.css` — the diagrams’ colours, from the Theia theme'] : []),
3638
+ ''
3639
+ ];
3640
+ return project(lines.join('\n'), composition);
3641
+ }
3642
+ /** The Theia extension: what a Theia application runs of the language, beside the sideloaded servers extension. */
3643
+ function theiaFiles(composition) {
3644
+ const fixed = (file) => ({
3645
+ path: project(`theia/${file}`, composition),
3646
+ content: project(template(`theia/${file}`), composition)
3647
+ });
3648
+ const id = composition.projectId;
3649
+ const data = composition.heads.includes('data');
3650
+ const glsp = composition.heads.includes('glsp');
3651
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3652
+ return [
3653
+ { path: 'theia/package.json', content: theiaPackageJson(composition) },
3654
+ ignoreFile('theia'),
3655
+ { path: 'theia/README.md', content: theiaReadme(composition) },
3656
+ fixed('tsconfig.json'),
3657
+ fixed('src/browser/__PROJECT_ID__-connection-preload-module.ts'),
3658
+ { path: `theia/src/browser/${id}-frontend-module.ts`, content: theiaFrontendModuleFile(composition) },
3659
+ fixed('src/node/__PROJECT_ID__-connection-backend-module.ts'),
3660
+ ...(data
3661
+ ? [
3662
+ fixed('src/browser/__PROJECT_ID__-data-port.ts'),
3663
+ fixed('src/browser/__PROJECT_ID__-data-connection.ts'),
3664
+ fixed('src/browser/__PROJECT_ID__-show-model-command.ts'),
3665
+ fixed('src/node/__PROJECT_ID__-data-backend-module.ts')
3666
+ ]
3667
+ : []),
3668
+ ...(glsp
3669
+ ? [
3670
+ fixed('src/common/__PROJECT_ID__-glsp-contribution.ts'),
3671
+ fixed('src/browser/__PROJECT_ID__-glsp-client-contribution.ts'),
3672
+ fixed('src/node/__PROJECT_ID__-glsp-backend-module.ts')
3673
+ ]
3674
+ : []),
3675
+ ...diagrams.map(grammar => grammarTemplate('theia/src/browser/__GRAMMAR_ID__-diagram-frontend-module.ts', composition, grammar)),
3676
+ ...(diagrams.length > 0 ? [fixed('style/diagram.css')] : [])
3677
+ ];
3678
+ }
3679
+ /**
3680
+ * The Theia application's `package.json`. Always private, as every host is.
3681
+ *
3682
+ * Theia's default `frontendConnectionTimeout` of 0 ends the session on any
3683
+ * dropped socket, and the page reloads; a minute lets the reconnect hardening
3684
+ * resume it.
3685
+ */
3686
+ function hostTheiaBrowserPackageJson(composition) {
3687
+ const dependencies = {
3688
+ [memberPackageName(composition, 'theia')]: MEMBER_PIN,
3689
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEPENDENCIES.map(name => [name, THEIA_VERSION]))
3690
+ };
3691
+ const devDependencies = {
3692
+ // Built before this application, whose start links it into plugins/.
3693
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
3694
+ '@playwright/test': '^1.55.0',
3695
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEV_DEPENDENCIES.map(name => [name, THEIA_VERSION])),
3696
+ '@types/node': '^22.0.0',
3697
+ rimraf: '^5.0.0',
3698
+ typescript: '^7.0.2'
3699
+ };
3700
+ const theia = {
3701
+ target: 'browser',
3702
+ frontend: {
3703
+ config: {
3704
+ applicationName: composition.name,
3705
+ connectionBufferBytes: 102400,
3706
+ preferences: { 'security.workspace.trust.enabled': false }
3707
+ }
3708
+ },
3709
+ backend: { config: { connectionBufferBytes: 102400, frontendConnectionTimeout: 60000 } }
3710
+ };
3711
+ return `{
3712
+ "name": "${memberPackageName(composition, 'host-theia-browser')}",
3713
+ "version": "0.0.0",
3714
+ "private": true,
3715
+ "description": "${composition.name} in a Theia browser application: the Theia extension, and the servers extension sideloaded for the language client.",
3716
+ "license": "UNLICENSED",
3717
+ "author": "",
3718
+ "scripts": {
3719
+ "build": "theia build --mode development && npm run typecheck",
3720
+ "clean": "rimraf lib src-gen plugins gen-esbuild.browser.mjs gen-esbuild.node.mjs smoke-workspace test-results playwright-report",
3721
+ ${lintScript(forMember(composition, 'host-theia-browser'), 'test')} "start": "node start.mjs",
3722
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
3723
+ "test:e2e:install": "playwright install chromium",
3724
+ "typecheck": "tsc --noEmit -p tsconfig.e2e.json",
3725
+ "watch": "theia build --watch --mode development"
3726
+ },
3727
+ "dependencies": {
3728
+ ${sortedBlock(dependencies, ' ')}
3729
+ },
3730
+ "devDependencies": {
3731
+ ${sortedBlock(devDependencies, ' ')}
3732
+ },
3733
+ "engines": {
3734
+ "node": ">=22.13"
3735
+ },
3736
+ "theia": ${jsonAt(theia, ' ')}
3737
+ }
3738
+ `;
3739
+ }
3740
+ /**
3741
+ * The Theia smoke test: the application opens a copy of the starter
3742
+ * workspace, and each head answers. The steps are the same in both
3743
+ * applications; the browser one's page is Chromium on the server the
3744
+ * configuration starts, the Electron one's the window the test launches.
3745
+ */
3746
+ function theiaSmokeSpec(composition, target) {
3747
+ const data = composition.heads.includes('data');
3748
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
3749
+ const primary = diagram ?? composition.grammars[0];
3750
+ const file = `nodes.${primary.extensions[0]}`;
3751
+ const showModelSteps = data
3752
+ ? `
3753
+ // The data head reads the open file, with focus in the Explorer beside it.
3754
+ await page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' }).click();
3755
+ await expect(page.locator('.theia-FileTree:focus-within')).toHaveCount(1);
3756
+ await runCommand(page, '${composition.name}: Show Model');
3757
+ // \`first()\`: Theia lists a notification in its toast and in the notification centre.
3758
+ await expect(
3759
+ page.locator('.theia-notification-message').filter({ hasText: '${file} holds a ${primary.entryRule}' }).first()
3760
+ ).toBeVisible();
3761
+ `
3762
+ : '';
3763
+ const diagramSteps = diagram
3764
+ ? `
3765
+ // The diagram file opens in its diagram, which draws the two starter nodes.
3766
+ // In the editor's copy: sprotty measures shapes in a hidden one on the page.
3767
+ await expect(page.locator('.sprotty:not(.sprotty-hidden) .sprotty-node')).toHaveCount(2);
3768
+ `
3769
+ : '';
3770
+ const textSteps = diagram
3771
+ ? ` // Then as text, through the Explorer's Open With.
3772
+ await page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' }).click({ button: 'right' });
3773
+ await page.locator('.lm-Menu-item', { hasText: 'Open With...' }).click();
3774
+ await page.locator('.quick-input-list .monaco-list-row', { hasText: 'Text Editor' }).click();
3775
+ `
3776
+ : '';
3777
+ return `${wrapComment(`Theia opens a copy of the starter workspace with this application's extensions, ${listPhrase([
3778
+ ...(diagram ? ['the diagram file draws in its diagram editor'] : []),
3779
+ ...(data ? ['the data head reads the file'] : []),
3780
+ 'the server reports a reference that resolves to nothing'
3781
+ ])}.`)}
3782
+
3783
+ ${target === 'browser' ? "import { expect, test, type Page } from '@playwright/test';\n" : theiaElectronSmokeFixture(composition)}
3784
+ test('${listPhrase([...(diagram ? ['draws the diagram'] : []), ...(data ? ['reads the model'] : []), 'reports a broken reference'])}', async ({ page }) => {
3785
+ ${target === 'browser' ? " await page.goto('/');\n" : ''} // Up once the loading screen is gone; a key pressed before then is lost.
3786
+ await expect(page.locator('.theia-preload')).toHaveCount(0);
3787
+ await page.keyboard.press('ControlOrMeta+Shift+E');
3788
+ await expect(page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' })).toBeVisible();
3789
+ await quickOpen(page, '${file}');
3790
+ ${diagramSteps}${showModelSteps}
3791
+ ${textSteps} const editor = page.locator('.monaco-editor .view-lines').first();
3792
+ await expect(editor).toContainText('node First');
3793
+ await editor.click();
3794
+ await page.keyboard.press('ControlOrMeta+End');
3795
+ // In one edit: typed key by key, the half-typed reference is reported on the way.
3796
+ await page.keyboard.insertText('\\nnode Broken -> Missing');
3797
+ await expect(page.locator('.monaco-editor .squiggly-error').first()).toBeVisible();
3798
+ });
3799
+
3800
+ /** Open \`file\` through Quick Open, so it gets the editor a user would. */
3801
+ async function quickOpen(page: Page, file: string): Promise<void> {
3802
+ await page.keyboard.press('ControlOrMeta+P');
3803
+ const input = page.locator('.quick-input-widget input');
3804
+ await input.fill(file);
3805
+ await expect(page.locator('.quick-input-list .monaco-list-row').first()).toContainText(file);
3806
+ await input.press('Enter');
3807
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
3808
+ }
3809
+ ${data
3810
+ ? `
3811
+ /** Run the command whose palette entry reads \`label\`, checked before Enter, since the match is fuzzy. */
3812
+ async function runCommand(page: Page, label: string): Promise<void> {
3813
+ await page.keyboard.press('F1');
3814
+ const input = page.locator('.quick-input-widget input');
3815
+ await input.fill(\`>\${label}\`);
3816
+ await expect(page.locator('.quick-input-list .monaco-list-row.focused')).toContainText(label);
3817
+ await input.press('Enter');
3818
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
3819
+ }
3820
+ `
3821
+ : ''}`;
3822
+ }
3823
+ /** The Theia application's README. */
3824
+ function hostTheiaBrowserReadme(composition) {
3825
+ const intro = [
3826
+ `${composition.name} in a Theia browser application: the Theia extension in \`../theia\`, and \`../vscode-servers\` sideloaded through \`@theia/plugin-ext\`, which starts the server and its language client.`,
3827
+ 'The backend runs the server, so this is a Node application; Theia serves the page.',
3828
+ ...(composition.grammars.some(grammar => grammar.diagram)
3829
+ ? ['The servers extension contributes no editor, so a diagram file opens in the Theia diagram editor alone.']
3830
+ : [])
3831
+ ];
3832
+ const lines = [
3833
+ `# ${memberPackageName(composition, 'host-theia-browser')}`,
3834
+ '',
3835
+ ...wrapProse(intro.join(' ')),
3836
+ '',
3837
+ '```bash',
3838
+ 'npm run build # bundle and type-check; build the members first',
3839
+ 'npm run watch # rebundle whenever the members’ builds change; reload the page to pick it up',
3840
+ 'npm start # Theia at http://localhost:3000 on ../workspace; THEIA_PORT picks another port',
3841
+ 'npm run test:e2e:install # download the Chromium the smoke test drives, once',
3842
+ 'npm run test:e2e # the smoke test, which starts the application itself',
3843
+ '```',
3844
+ '',
3845
+ ...wrapProse('The `theia` block of `package.json` sets `frontendConnectionTimeout`, without which Theia ends the session on any dropped socket and the page reloads, and `connectionBufferBytes`, the messages kept while the socket is down; the Theia extension’s connection modules read both.'),
3846
+ '',
3847
+ '## Layout',
3848
+ '',
3849
+ '- `esbuild.mjs` — the bundling `theia build` runs. It keeps this file, so it is the place to adjust the bundle',
3850
+ '- `start.mjs` — `npm start`: links `../vscode-servers` into `plugins/`, then starts the backend on `THEIA_PORT`, on a folder given as its argument or `../workspace`',
3851
+ '- `playwright.config.mts` — the smoke tier, on port 4938 or `THEIA_PORT`, on a copy of `../workspace` in `smoke-workspace/`',
3852
+ '- `test/smoke.spec.mts` — Theia opens the workspace and each head answers',
3853
+ ''
3854
+ ];
3855
+ return project(lines.join('\n'), composition);
3856
+ }
3857
+ /** The Theia browser application: the Theia extension and the sideloaded servers extension. */
3858
+ function hostTheiaBrowserFiles(composition) {
3859
+ const fixed = (file) => projectTemplate(`host-theia-browser/${file}`, composition);
3860
+ return [
3861
+ { path: 'host-theia-browser/package.json', content: hostTheiaBrowserPackageJson(composition) },
3862
+ ignoreFile('host-theia-browser'),
3863
+ { path: 'host-theia-browser/README.md', content: hostTheiaBrowserReadme(composition) },
3864
+ fixed('esbuild.mjs'),
3865
+ fixed('start.mjs'),
3866
+ fixed('playwright.config.mts'),
3867
+ fixed('tsconfig.e2e.json'),
3868
+ { path: 'host-theia-browser/test/smoke.spec.mts', content: theiaSmokeSpec(composition, 'browser') }
3869
+ ];
3870
+ }
3871
+ /**
3872
+ * The Electron smoke test's imports and its `page`: the application's window,
3873
+ * launched by the test on a scratch copy of the workspace.
3874
+ */
3875
+ function theiaElectronSmokeFixture(composition) {
3876
+ return `import { expect, test as base, type ElectronApplication, type Page } from '@playwright/test';
3877
+ import { once } from 'node:events';
3878
+ import { cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs';
3879
+ import { tmpdir } from 'node:os';
3880
+ import { join } from 'node:path';
3881
+ import { fileURLToPath, pathToFileURL } from 'node:url';
3882
+
3883
+ /**
3884
+ * The application in Electron, on a copy of the starter workspace, since the
3885
+ * server writes its repairs to the folder it opens, with a profile of its own:
3886
+ * Theia quits at once while another window holds one. Its settings are its own
3887
+ * too, so a run never writes \`~/.theia/settings.json\`.
3888
+ */
3889
+ const test = base.extend<{ page: Page }>({
3890
+ page: async ({ playwright }, use) => {
3891
+ const scratch = mkdtempSync(join(tmpdir(), '${composition.projectId}-theia-electron-'));
3892
+ const workspace = join(scratch, 'workspace');
3893
+ // The servers extension, sideloaded from a plugins folder as \`npm start\` does.
3894
+ const plugins = join(scratch, 'plugins');
3895
+ const link = join(plugins, '${composition.projectId}-vscode-servers');
3896
+ let app: ElectronApplication | undefined;
3897
+ try {
3898
+ cpSync(fileURLToPath(new URL('../../workspace', import.meta.url)), workspace, { recursive: true });
3899
+ mkdirSync(plugins);
3900
+ symlinkSync(fileURLToPath(new URL('../../vscode-servers', import.meta.url)), link, 'junction');
3901
+ // Playwright resolves Electron itself; given its path, Theia opens this
3902
+ // folder instead of the workspace.
3903
+ app = await playwright._electron.launch({
3904
+ args: [
3905
+ fileURLToPath(new URL('..', import.meta.url)),
3906
+ '--no-sandbox',
3907
+ \`--user-data-dir=\${join(scratch, 'user-data')}\`,
3908
+ // In URI form, since Theia reads the argument as a URI.
3909
+ \`--plugins=local-dir:\${pathToFileURL(plugins).pathname}\`,
3910
+ workspace
3911
+ ],
3912
+ env: {
3913
+ ...process.env,
3914
+ THEIA_CONFIG_DIR: join(scratch, 'config'),
3915
+ // Menus drawn in the page, where the test can click them.
3916
+ THEIA_ELECTRON_DISABLE_NATIVE_ELEMENTS: '1'
3917
+ }
3918
+ });
3919
+ await use(await app.firstWindow());
3920
+ } finally {
3921
+ try {
3922
+ // Exited, not closed: closing asks whether to save the edited file. An
3923
+ // app that is already gone is left alone, so the test's own error stands.
3924
+ const child = app?.process();
3925
+ if (app && child?.exitCode === null && child.signalCode === null) {
3926
+ const exited = once(child, 'exit');
3927
+ await app.evaluate(({ app: electron }) => electron.exit(0));
3928
+ await exited;
3929
+ }
3930
+ } finally {
3931
+ // Unlinked first, so the remove never reaches \`../vscode-servers\` through it.
3932
+ rmSync(link, { force: true });
3933
+ rmSync(scratch, { recursive: true, force: true });
3934
+ }
3935
+ }
3936
+ }
3937
+ });
3938
+ `;
3939
+ }
3940
+ /**
3941
+ * The Theia Electron application's `package.json`: the browser application's
3942
+ * `theia` block with the Electron target. Always private, as every host is.
3943
+ */
3944
+ function hostTheiaElectronPackageJson(composition) {
3945
+ const dependencies = {
3946
+ [memberPackageName(composition, 'theia')]: MEMBER_PIN,
3947
+ ...Object.fromEntries(HOST_THEIA_ELECTRON_DEPENDENCIES.map(name => [name, THEIA_VERSION]))
3948
+ };
3949
+ const devDependencies = {
3950
+ // Built before this application, whose start links it into plugins/.
3951
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
3952
+ '@playwright/test': '^1.55.0',
3953
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEV_DEPENDENCIES.map(name => [name, THEIA_VERSION])),
3954
+ '@types/node': '^22.0.0',
3955
+ electron: ELECTRON_VERSION,
3956
+ rimraf: '^5.0.0',
3957
+ typescript: '^7.0.2'
3958
+ };
3959
+ const theia = {
3960
+ target: 'electron',
3961
+ frontend: {
3962
+ config: {
3963
+ applicationName: composition.name,
3964
+ connectionBufferBytes: 102400,
3965
+ preferences: { 'security.workspace.trust.enabled': false }
3966
+ }
3967
+ },
3968
+ backend: { config: { connectionBufferBytes: 102400, frontendConnectionTimeout: 60000 } }
3969
+ };
3970
+ return `{
3971
+ "name": "${memberPackageName(composition, 'host-theia-electron')}",
3972
+ "version": "0.0.0",
3973
+ "private": true,
3974
+ "description": "${composition.name} in a Theia Electron application: the Theia extension, and the servers extension sideloaded for the language client.",
3975
+ "license": "UNLICENSED",
3976
+ "author": "",
3977
+ "main": "lib/backend/electron-main.js",
3978
+ "scripts": {
3979
+ "build": "theia build --mode development && npm run typecheck",
3980
+ "clean": "rimraf lib src-gen plugins gen-esbuild.browser.mjs gen-esbuild.electron.mjs gen-esbuild.node.mjs test-results playwright-report",
3981
+ ${lintScript(forMember(composition, 'host-theia-electron'), 'test')} "start": "node start.mjs",
3982
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
3983
+ "typecheck": "tsc --noEmit -p tsconfig.e2e.json",
3984
+ "watch": "theia build --watch --mode development"
3985
+ },
3986
+ "dependencies": {
3987
+ ${sortedBlock(dependencies, ' ')}
3988
+ },
3989
+ "devDependencies": {
3990
+ ${sortedBlock(devDependencies, ' ')}
3991
+ },
3992
+ "engines": {
3993
+ "node": ">=22.13"
3994
+ },
3995
+ "theia": ${jsonAt(theia, ' ')}
3996
+ }
3997
+ `;
3998
+ }
3999
+ /** The Theia Electron application's README. */
4000
+ function hostTheiaElectronReadme(composition) {
4001
+ const intro = [
4002
+ `${composition.name} in a Theia Electron application: the Theia extension in \`../theia\`, and \`../vscode-servers\` sideloaded through \`@theia/plugin-ext\`, which starts the server and its language client.`,
4003
+ 'Electron runs the window, and a backend process it starts runs the server.',
4004
+ ...(composition.grammars.some(grammar => grammar.diagram)
4005
+ ? ['The servers extension contributes no editor, so a diagram file opens in the Theia diagram editor alone.']
4006
+ : [])
4007
+ ];
4008
+ const lines = [
4009
+ `# ${memberPackageName(composition, 'host-theia-electron')}`,
4010
+ '',
4011
+ ...wrapProse(intro.join(' ')),
4012
+ '',
4013
+ '```bash',
4014
+ 'npm run build # bundle and type-check, and download Electron; build the members first',
4015
+ 'npm run watch # rebundle whenever the members’ builds change; reload the window to pick it up',
4016
+ 'npm start # the application on ../workspace',
4017
+ 'npm run test:e2e # the smoke test, which launches the application itself',
4018
+ '```',
4019
+ '',
4020
+ ...wrapProse('There is no `theia rebuild:electron` step: Theia’s native modules are N-API builds, which load in Electron as `npm install` built them for Node.'),
4021
+ '',
4022
+ ...wrapProse('`npm run watch` reports a `theia-source-map-paths` JSON error as it starts: `esbuild.mjs` starts the browser and electron builds together, and they share `lib/frontend`. Later rebuilds are clean.'),
4023
+ '',
4024
+ '## Layout',
4025
+ '',
4026
+ '- `esbuild.mjs` — the bundling `theia build` runs. It keeps this file, so it is the place to adjust the bundle',
4027
+ '- `start.mjs` — `npm start`: links `../vscode-servers` into `plugins/`, then starts the application on a folder given as its argument or `../workspace`',
4028
+ '- `playwright.config.mts` — the smoke tier',
4029
+ '- `test/smoke.spec.mts` — Electron opens a copy of the workspace with a profile of its own, and each head answers',
4030
+ ''
4031
+ ];
4032
+ return project(lines.join('\n'), composition);
4033
+ }
4034
+ /** The Theia Electron application: the browser application's extensions in a desktop window. */
4035
+ function hostTheiaElectronFiles(composition) {
4036
+ const fixed = (file) => projectTemplate(`host-theia-electron/${file}`, composition);
4037
+ return [
4038
+ { path: 'host-theia-electron/package.json', content: hostTheiaElectronPackageJson(composition) },
4039
+ ignoreFile('host-theia-electron'),
4040
+ { path: 'host-theia-electron/README.md', content: hostTheiaElectronReadme(composition) },
4041
+ fixed('esbuild.mjs'),
4042
+ fixed('start.mjs'),
4043
+ fixed('playwright.config.mts'),
4044
+ fixed('tsconfig.e2e.json'),
4045
+ { path: 'host-theia-electron/test/smoke.spec.mts', content: theiaSmokeSpec(composition, 'electron') }
4046
+ ];
4047
+ }
4048
+ /**
4049
+ * The formatter and linter a standalone root runs. Exact, because a formatter
4050
+ * release that changes its output would fail the project's `format:check`.
4051
+ */
4052
+ const ROOT_STYLE_DEV_DEPENDENCIES = { oxfmt: '0.71.0', oxlint: '1.82.0' };
4053
+ /**
4054
+ * The standalone root's formatter config: the style every template is written
4055
+ * in, at the width the emitted sources wrap at. Generated code is ignored
4056
+ * because each run of its generator rewrites it in that generator's style.
4057
+ */
4058
+ function oxfmtConfig(composition) {
4059
+ return `{
4060
+ "$schema": "./node_modules/oxfmt/configuration_schema.json",
4061
+ "arrowParens": "avoid",
4062
+ "endOfLine": "lf",
4063
+ "ignorePatterns": ["**/generated", "**/generated-hydranium", "**/syntaxes", "**/*.md"],
4064
+ "jsxSingleQuote": true,
4065
+ "printWidth": ${columnsFor(composition)},
4066
+ "singleQuote": true,
4067
+ "sortPackageJson": true,
4068
+ "tabWidth": 3,
4069
+ "trailingComma": "none",
4070
+ "overrides": [
4071
+ {
4072
+ "files": ["*.json", "*.yml", "*.yaml"],
4073
+ "options": {
4074
+ "printWidth": 100,
4075
+ "tabWidth": 2
4076
+ }
4077
+ }
4078
+ ]
4079
+ }
4080
+ `;
4081
+ }
4082
+ /**
4083
+ * A standalone project's root: the members as npm workspaces.
4084
+ *
4085
+ * Always private: it is never published, whatever `--public` makes of the
4086
+ * members. npm runs a script across the members in the order listed here, not
4087
+ * by their dependencies; listing protocol first is safe because its `build`
4088
+ * runs the server's `generate` before compiling.
4089
+ *
4090
+ * It declares the exact pins `--monorepo` prints for a workspace root, for the
4091
+ * same reason: a package ranging over one, such as a framework package's peer,
4092
+ * otherwise takes the top of the tree with the newest match, and each member's
4093
+ * exact copy nests beneath it.
4094
+ *
4095
+ * `watch` keeps every non-host member built; `watch:<host>` adds one host, so
4096
+ * only the bundler of the host being worked on runs.
4097
+ *
4098
+ * `format` and `lint` run at the root over every member, which is why the
4099
+ * members get no `lint` of their own here.
4100
+ */
4101
+ function rootFiles(composition) {
4102
+ const devDependencies = {
4103
+ ...Object.fromEntries(workspaceRootPins(composition)),
4104
+ concurrently: '^9.0.0',
4105
+ ...ROOT_STYLE_DEV_DEPENDENCIES
4106
+ };
4107
+ const members = initMembers(composition.heads, composition.hosts);
4108
+ // Only the server's watch is `tsc -b`, so protocol is built by one process
4109
+ // rather than two writing the same `lib/`; a host's watch joins only in its
4110
+ // own `watch:<host>`.
4111
+ const watched = members.filter(member => member !== 'protocol' && !member.startsWith('host-'));
4112
+ const parallel = (commands) => `concurrently --kill-others --names ${Object.keys(commands).join(',')} ${Object.values(commands)
4113
+ .map(command => `\\"${command}\\"`)
4114
+ .join(' ')}`;
4115
+ const scripts = {
4116
+ build: 'npm run build --workspaces',
4117
+ clean: 'npm run clean --workspaces --if-present',
4118
+ format: 'oxfmt',
4119
+ 'format:check': 'oxfmt --check',
4120
+ lint: 'oxlint --report-unused-disable-directives --max-warnings 0',
4121
+ ...Object.fromEntries(composition.hosts.map(host => [`start:${host}`, `npm --prefix host-${host} start`])),
4122
+ test: 'npm test --workspaces --if-present',
4123
+ watch: parallel(Object.fromEntries(watched.map(member => [member, `npm --prefix ${member} run watch`]))),
4124
+ // The browser host's `start` is its watch: it rebundles the page as it serves it.
4125
+ ...Object.fromEntries(composition.hosts.map(host => [
4126
+ `watch:${host}`,
4127
+ parallel({
4128
+ watch: 'npm run watch',
4129
+ [`host-${host}`]: `npm --prefix host-${host} ${host === 'browser' ? 'start' : 'run watch'}`
4130
+ })
4131
+ ]))
4132
+ };
4133
+ const content = `{
4134
+ "name": "${composition.projectId}-root",
4135
+ "version": "0.0.0",
4136
+ "private": true,
4137
+ "workspaces": [
4138
+ ${members.map(member => ` "${member}"`).join(',\n')}
4139
+ ],
4140
+ "scripts": {
4141
+ ${Object.entries(scripts)
4142
+ .map(([name, command]) => ` "${name}": "${command}"`)
4143
+ .join(',\n')}
4144
+ },
4145
+ "devDependencies": {
4146
+ ${sortedBlock(devDependencies, ' ')}
4147
+ },
4148
+ "engines": {
4149
+ "node": ">=22.13"
4150
+ }
4151
+ }
4152
+ `;
4153
+ return [
4154
+ { path: 'package.json', content },
4155
+ ignoreFile(''),
4156
+ { path: '.editorconfig', content: template('editorconfig') },
4157
+ { path: '.oxfmtrc.json', content: oxfmtConfig(composition) },
4158
+ { path: '.oxlintrc.json', content: template('oxlintrc.json') },
4159
+ { path: '.nvmrc', content: `${SCAFFOLD_NODE_MAJOR}\n` }
4160
+ ];
4161
+ }
4162
+ /**
4163
+ * Every file the scaffold emits, fully rendered, at its path in the project
4164
+ * directory. A workspace member's project gets no root of its own: it joins the
4165
+ * surrounding workspace, whose manifest `init` prints the changes for.
4166
+ */
4167
+ export function buildInitTemplates(composition) {
4168
+ return [
4169
+ ...(composition.packaging.workspace === undefined ? rootFiles(composition) : []),
4170
+ ...protocolFiles(composition),
4171
+ ...serverFiles(composition),
4172
+ ...(composition.heads.includes('glsp') ? clientFiles(composition) : []),
4173
+ ...(emitsVscodeServers(composition) ? vscodeServersFiles(composition) : []),
4174
+ ...(composition.hosts.some(isTheiaHost) ? theiaFiles(composition) : []),
4175
+ ...(composition.hosts.includes('browser') ? hostBrowserFiles(composition) : []),
4176
+ ...(composition.hosts.includes('vscode') ? hostVscodeFiles(composition) : []),
4177
+ ...(composition.hosts.includes('theia-browser') ? hostTheiaBrowserFiles(composition) : []),
4178
+ ...(composition.hosts.includes('theia-electron') ? hostTheiaElectronFiles(composition) : []),
4179
+ ...workspaceFiles(composition)
1934
4180
  ];
1935
4181
  }
1936
4182
  //# sourceMappingURL=init-templates.js.map