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