@hydranium/cli 1.0.0-next.42 → 1.0.0-next.420

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 (371) hide show
  1. package/README.md +125 -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 +11 -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 +12 -10
  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/check-skills-args.d.ts +11 -0
  24. package/lib/commands/check-skills-args.d.ts.map +1 -0
  25. package/lib/commands/check-skills-args.js +71 -0
  26. package/lib/commands/check-skills-args.js.map +1 -0
  27. package/lib/commands/client-session.d.ts +17 -0
  28. package/lib/commands/client-session.d.ts.map +1 -0
  29. package/lib/commands/client-session.js +27 -0
  30. package/lib/commands/client-session.js.map +1 -0
  31. package/lib/commands/create-args.d.ts +17 -0
  32. package/lib/commands/create-args.d.ts.map +1 -0
  33. package/lib/commands/create-args.js +53 -0
  34. package/lib/commands/create-args.js.map +1 -0
  35. package/lib/commands/create.d.ts +38 -0
  36. package/lib/commands/create.d.ts.map +1 -0
  37. package/lib/commands/create.js +43 -0
  38. package/lib/commands/create.js.map +1 -0
  39. package/lib/commands/delete-args.d.ts +17 -0
  40. package/lib/commands/delete-args.d.ts.map +1 -0
  41. package/lib/commands/delete-args.js +49 -0
  42. package/lib/commands/delete-args.js.map +1 -0
  43. package/lib/commands/delete.d.ts +30 -0
  44. package/lib/commands/delete.d.ts.map +1 -0
  45. package/lib/commands/delete.js +32 -0
  46. package/lib/commands/delete.js.map +1 -0
  47. package/lib/commands/generate-ast-builder.d.ts +1 -1
  48. package/lib/commands/generate-ast-builder.d.ts.map +1 -1
  49. package/lib/commands/generate-ast-builder.js +2 -11
  50. package/lib/commands/generate-ast-builder.js.map +1 -1
  51. package/lib/commands/generate-languages.d.ts +35 -0
  52. package/lib/commands/generate-languages.d.ts.map +1 -0
  53. package/lib/commands/generate-languages.js +105 -0
  54. package/lib/commands/generate-languages.js.map +1 -0
  55. package/lib/commands/generate-transfer-builder.d.ts +33 -0
  56. package/lib/commands/generate-transfer-builder.d.ts.map +1 -0
  57. package/lib/commands/generate-transfer-builder.js +86 -0
  58. package/lib/commands/generate-transfer-builder.js.map +1 -0
  59. package/lib/commands/generate-transfer-model-args.d.ts.map +1 -1
  60. package/lib/commands/generate-transfer-model-args.js +20 -5
  61. package/lib/commands/generate-transfer-model-args.js.map +1 -1
  62. package/lib/commands/generate-transfer-model-config.d.ts.map +1 -1
  63. package/lib/commands/generate-transfer-model-config.js +8 -3
  64. package/lib/commands/generate-transfer-model-config.js.map +1 -1
  65. package/lib/commands/generate-transfer-model.d.ts +41 -9
  66. package/lib/commands/generate-transfer-model.d.ts.map +1 -1
  67. package/lib/commands/generate-transfer-model.js +225 -68
  68. package/lib/commands/generate-transfer-model.js.map +1 -1
  69. package/lib/commands/generated-module-path.d.ts +16 -0
  70. package/lib/commands/generated-module-path.d.ts.map +1 -0
  71. package/lib/commands/generated-module-path.js +21 -0
  72. package/lib/commands/generated-module-path.js.map +1 -0
  73. package/lib/commands/harness-args.d.ts +46 -43
  74. package/lib/commands/harness-args.d.ts.map +1 -1
  75. package/lib/commands/harness-args.js +170 -29
  76. package/lib/commands/harness-args.js.map +1 -1
  77. package/lib/commands/headless-harness.d.ts +37 -20
  78. package/lib/commands/headless-harness.d.ts.map +1 -1
  79. package/lib/commands/headless-harness.js +71 -19
  80. package/lib/commands/headless-harness.js.map +1 -1
  81. package/lib/commands/init-args.d.ts +5 -18
  82. package/lib/commands/init-args.d.ts.map +1 -1
  83. package/lib/commands/init-args.js +131 -35
  84. package/lib/commands/init-args.js.map +1 -1
  85. package/lib/commands/init-hosts.d.ts +24 -0
  86. package/lib/commands/init-hosts.d.ts.map +1 -0
  87. package/lib/commands/init-hosts.js +37 -0
  88. package/lib/commands/init-hosts.js.map +1 -0
  89. package/lib/commands/init-prompt.d.ts +3 -3
  90. package/lib/commands/init-prompt.d.ts.map +1 -1
  91. package/lib/commands/init-prompt.js +4 -5
  92. package/lib/commands/init-prompt.js.map +1 -1
  93. package/lib/commands/init-skills.d.ts +41 -0
  94. package/lib/commands/init-skills.d.ts.map +1 -0
  95. package/lib/commands/init-skills.js +110 -0
  96. package/lib/commands/init-skills.js.map +1 -0
  97. package/lib/commands/init-templates.d.ts +20 -14
  98. package/lib/commands/init-templates.d.ts.map +1 -1
  99. package/lib/commands/init-templates.js +3107 -759
  100. package/lib/commands/init-templates.js.map +1 -1
  101. package/lib/commands/init-wizard.d.ts +10 -0
  102. package/lib/commands/init-wizard.d.ts.map +1 -1
  103. package/lib/commands/init-wizard.js +76 -31
  104. package/lib/commands/init-wizard.js.map +1 -1
  105. package/lib/commands/init-workspace.d.ts +13 -11
  106. package/lib/commands/init-workspace.d.ts.map +1 -1
  107. package/lib/commands/init-workspace.js +21 -7
  108. package/lib/commands/init-workspace.js.map +1 -1
  109. package/lib/commands/init.d.ts +61 -24
  110. package/lib/commands/init.d.ts.map +1 -1
  111. package/lib/commands/init.js +244 -50
  112. package/lib/commands/init.js.map +1 -1
  113. package/lib/commands/kebab.d.ts +15 -0
  114. package/lib/commands/kebab.d.ts.map +1 -0
  115. package/lib/commands/kebab.js +17 -0
  116. package/lib/commands/kebab.js.map +1 -0
  117. package/lib/commands/lint-grammar-args.d.ts +3 -2
  118. package/lib/commands/lint-grammar-args.d.ts.map +1 -1
  119. package/lib/commands/lint-grammar-args.js +14 -11
  120. package/lib/commands/lint-grammar-args.js.map +1 -1
  121. package/lib/commands/lint-grammar-driver.js +2 -1
  122. package/lib/commands/lint-grammar-driver.js.map +1 -1
  123. package/lib/commands/lint-grammar-report.js.map +1 -1
  124. package/lib/commands/lint-grammar.js +1 -1
  125. package/lib/commands/lint-grammar.js.map +1 -1
  126. package/lib/commands/measure-memory-args.d.ts +3 -2
  127. package/lib/commands/measure-memory-args.d.ts.map +1 -1
  128. package/lib/commands/measure-memory-args.js +26 -14
  129. package/lib/commands/measure-memory-args.js.map +1 -1
  130. package/lib/commands/measure-memory-driver.js +5 -3
  131. package/lib/commands/measure-memory-driver.js.map +1 -1
  132. package/lib/commands/measure-memory.d.ts +1 -1
  133. package/lib/commands/measure-memory.d.ts.map +1 -1
  134. package/lib/commands/measure-memory.js +6 -3
  135. package/lib/commands/measure-memory.js.map +1 -1
  136. package/lib/commands/message-catalogue-args.d.ts +16 -0
  137. package/lib/commands/message-catalogue-args.d.ts.map +1 -0
  138. package/lib/commands/message-catalogue-args.js +53 -0
  139. package/lib/commands/message-catalogue-args.js.map +1 -0
  140. package/lib/commands/message-catalogue.d.ts +21 -0
  141. package/lib/commands/message-catalogue.d.ts.map +1 -0
  142. package/lib/commands/message-catalogue.js +48 -0
  143. package/lib/commands/message-catalogue.js.map +1 -0
  144. package/lib/commands/model-docs-args.d.ts +4 -3
  145. package/lib/commands/model-docs-args.d.ts.map +1 -1
  146. package/lib/commands/model-docs-args.js +13 -11
  147. package/lib/commands/model-docs-args.js.map +1 -1
  148. package/lib/commands/model-docs-driver.js +2 -1
  149. package/lib/commands/model-docs-driver.js.map +1 -1
  150. package/lib/commands/model-docs.js +1 -1
  151. package/lib/commands/model-docs.js.map +1 -1
  152. package/lib/commands/projects-args.d.ts.map +1 -1
  153. package/lib/commands/projects-args.js +5 -5
  154. package/lib/commands/projects-args.js.map +1 -1
  155. package/lib/commands/projects.d.ts +3 -4
  156. package/lib/commands/projects.d.ts.map +1 -1
  157. package/lib/commands/projects.js +2 -2
  158. package/lib/commands/projects.js.map +1 -1
  159. package/lib/commands/query-args.d.ts.map +1 -1
  160. package/lib/commands/query-args.js +6 -5
  161. package/lib/commands/query-args.js.map +1 -1
  162. package/lib/commands/query.d.ts +6 -5
  163. package/lib/commands/query.d.ts.map +1 -1
  164. package/lib/commands/query.js +5 -4
  165. package/lib/commands/query.js.map +1 -1
  166. package/lib/commands/reflect-args.d.ts +3 -2
  167. package/lib/commands/reflect-args.d.ts.map +1 -1
  168. package/lib/commands/reflect-args.js +14 -11
  169. package/lib/commands/reflect-args.js.map +1 -1
  170. package/lib/commands/reflect-driver.js +2 -1
  171. package/lib/commands/reflect-driver.js.map +1 -1
  172. package/lib/commands/reflect-report.js.map +1 -1
  173. package/lib/commands/reflect.js +1 -1
  174. package/lib/commands/reflect.js.map +1 -1
  175. package/lib/commands/save-args.d.ts.map +1 -1
  176. package/lib/commands/save-args.js +7 -4
  177. package/lib/commands/save-args.js.map +1 -1
  178. package/lib/commands/save.d.ts +8 -4
  179. package/lib/commands/save.d.ts.map +1 -1
  180. package/lib/commands/save.js +12 -23
  181. package/lib/commands/save.js.map +1 -1
  182. package/lib/commands/skills.d.ts +22 -0
  183. package/lib/commands/skills.d.ts.map +1 -0
  184. package/lib/commands/skills.js +129 -0
  185. package/lib/commands/skills.js.map +1 -0
  186. package/lib/commands/validate-args.d.ts +3 -2
  187. package/lib/commands/validate-args.d.ts.map +1 -1
  188. package/lib/commands/validate-args.js +14 -11
  189. package/lib/commands/validate-args.js.map +1 -1
  190. package/lib/commands/validate-driver.js +2 -1
  191. package/lib/commands/validate-driver.js.map +1 -1
  192. package/lib/commands/validate-report.js.map +1 -1
  193. package/lib/commands/validate.js +1 -1
  194. package/lib/commands/validate.js.map +1 -1
  195. package/lib/commands/watch-args.d.ts.map +1 -1
  196. package/lib/commands/watch-args.js +6 -4
  197. package/lib/commands/watch-args.js.map +1 -1
  198. package/lib/commands/watch.d.ts +3 -4
  199. package/lib/commands/watch.d.ts.map +1 -1
  200. package/lib/commands/watch.js +5 -2
  201. package/lib/commands/watch.js.map +1 -1
  202. package/lib/driver-heap.d.ts +52 -0
  203. package/lib/driver-heap.d.ts.map +1 -0
  204. package/lib/driver-heap.js +51 -0
  205. package/lib/driver-heap.js.map +1 -0
  206. package/lib/index.d.ts +3 -0
  207. package/lib/index.d.ts.map +1 -1
  208. package/lib/index.js +3 -0
  209. package/lib/index.js.map +1 -1
  210. package/lib/log-level.d.ts +21 -11
  211. package/lib/log-level.d.ts.map +1 -1
  212. package/lib/log-level.js +25 -14
  213. package/lib/log-level.js.map +1 -1
  214. package/lib/spawn-data-server.d.ts +9 -4
  215. package/lib/spawn-data-server.d.ts.map +1 -1
  216. package/lib/spawn-data-server.js +5 -4
  217. package/lib/spawn-data-server.js.map +1 -1
  218. package/lib/stderr-connection-logger.d.ts +12 -0
  219. package/lib/stderr-connection-logger.d.ts.map +1 -0
  220. package/lib/stderr-connection-logger.js +16 -0
  221. package/lib/stderr-connection-logger.js.map +1 -0
  222. package/lib/testing/echo-server.js +9 -1
  223. package/lib/testing/echo-server.js.map +1 -1
  224. package/package.json +99 -41
  225. package/src/cli.ts +11 -2
  226. package/src/commands/analyze-heap-args.ts +1 -2
  227. package/src/commands/analyze-heap.ts +4 -1
  228. package/src/commands/ast-ground-truth-args.ts +16 -13
  229. package/src/commands/ast-ground-truth-driver.ts +4 -2
  230. package/src/commands/ast-ground-truth.ts +1 -1
  231. package/src/commands/check-skills-args.ts +70 -0
  232. package/src/commands/client-session.ts +33 -0
  233. package/src/commands/create-args.ts +68 -0
  234. package/src/commands/create.ts +83 -0
  235. package/src/commands/delete-args.ts +64 -0
  236. package/src/commands/delete.ts +61 -0
  237. package/src/commands/generate-ast-builder.ts +2 -12
  238. package/src/commands/generate-languages.ts +132 -0
  239. package/src/commands/generate-transfer-builder.ts +101 -0
  240. package/src/commands/generate-transfer-model-args.ts +20 -5
  241. package/src/commands/generate-transfer-model-config.ts +8 -3
  242. package/src/commands/generate-transfer-model.ts +297 -66
  243. package/src/commands/generated-module-path.ts +22 -0
  244. package/src/commands/harness-args.ts +163 -33
  245. package/src/commands/headless-harness.ts +89 -28
  246. package/src/commands/init-args.ts +135 -35
  247. package/src/commands/init-hosts.ts +51 -0
  248. package/src/commands/init-prompt.ts +5 -6
  249. package/src/commands/init-skills.ts +129 -0
  250. package/src/commands/init-templates.ts +3300 -785
  251. package/src/commands/init-wizard.ts +97 -32
  252. package/src/commands/init-workspace.ts +31 -16
  253. package/src/commands/init.ts +311 -65
  254. package/src/commands/kebab.ts +17 -0
  255. package/src/commands/lint-grammar-args.ts +18 -14
  256. package/src/commands/lint-grammar-driver.ts +2 -1
  257. package/src/commands/lint-grammar.ts +1 -1
  258. package/src/commands/measure-memory-args.ts +31 -17
  259. package/src/commands/measure-memory-driver.ts +5 -3
  260. package/src/commands/measure-memory.ts +6 -3
  261. package/src/commands/message-catalogue-args.ts +55 -0
  262. package/src/commands/message-catalogue.ts +56 -0
  263. package/src/commands/model-docs-args.ts +17 -14
  264. package/src/commands/model-docs-driver.ts +2 -1
  265. package/src/commands/model-docs.ts +1 -1
  266. package/src/commands/projects-args.ts +5 -4
  267. package/src/commands/projects.ts +4 -6
  268. package/src/commands/query-args.ts +6 -4
  269. package/src/commands/query.ts +9 -9
  270. package/src/commands/reflect-args.ts +18 -14
  271. package/src/commands/reflect-driver.ts +2 -1
  272. package/src/commands/reflect.ts +1 -1
  273. package/src/commands/save-args.ts +7 -3
  274. package/src/commands/save.ts +24 -27
  275. package/src/commands/skills.ts +146 -0
  276. package/src/commands/validate-args.ts +18 -14
  277. package/src/commands/validate-driver.ts +2 -1
  278. package/src/commands/validate.ts +1 -1
  279. package/src/commands/watch-args.ts +6 -3
  280. package/src/commands/watch.ts +7 -6
  281. package/src/driver-heap.ts +65 -0
  282. package/src/index.ts +3 -0
  283. package/src/log-level.ts +42 -14
  284. package/src/spawn-data-server.ts +17 -5
  285. package/src/stderr-connection-logger.ts +18 -0
  286. package/src/testing/echo-server.ts +11 -2
  287. package/templates/client/gitignore +3 -0
  288. package/templates/client/src/__GRAMMAR_ID__-diagram-module.ts +82 -0
  289. package/templates/editorconfig +15 -0
  290. package/templates/gitignore +1 -0
  291. package/templates/host-browser/esbuild.mjs +82 -0
  292. package/templates/host-browser/gitignore +4 -0
  293. package/templates/host-browser/hydranium-mark.svg +40 -0
  294. package/templates/host-browser/index.html +287 -0
  295. package/templates/host-browser/playwright.config.mts +24 -0
  296. package/templates/host-browser/src/data-status.ts +15 -0
  297. package/templates/host-browser/src/diagram-save.ts +60 -0
  298. package/templates/host-browser/src/diagram.ts +121 -0
  299. package/templates/host-browser/src/editor.ts +116 -0
  300. package/templates/host-browser/src/log.ts +14 -0
  301. package/templates/host-browser/src/monaco-editor-core-worker.d.ts +7 -0
  302. package/templates/host-browser/src/monaco-editor-worker.ts +10 -0
  303. package/templates/host-browser/src/posix-path-shim.ts +23 -0
  304. package/templates/host-browser/src/shown-file.ts +61 -0
  305. package/templates/host-browser/src/workspace.ts +5 -0
  306. package/templates/host-browser/tsconfig.e2e.json +16 -0
  307. package/templates/host-browser/tsconfig.page.json +16 -0
  308. package/templates/host-browser/tsconfig.worker.json +16 -0
  309. package/templates/host-theia-browser/esbuild.mjs +24 -0
  310. package/templates/host-theia-browser/gitignore +9 -0
  311. package/templates/host-theia-browser/playwright.config.mts +42 -0
  312. package/templates/host-theia-browser/start.mjs +50 -0
  313. package/templates/host-theia-browser/tsconfig.e2e.json +16 -0
  314. package/templates/host-theia-electron/esbuild.mjs +27 -0
  315. package/templates/host-theia-electron/gitignore +8 -0
  316. package/templates/host-theia-electron/playwright.config.mts +12 -0
  317. package/templates/host-theia-electron/start.mjs +47 -0
  318. package/templates/host-theia-electron/tsconfig.e2e.json +16 -0
  319. package/templates/host-vscode/esbuild.mjs +38 -0
  320. package/templates/host-vscode/gitignore +7 -0
  321. package/templates/host-vscode/playwright.config.mts +14 -0
  322. package/templates/host-vscode/src/__GRAMMAR_ID__-diagram-editor.ts +19 -0
  323. package/templates/host-vscode/src/show-model-command.ts +24 -0
  324. package/templates/host-vscode/src/webview/__GRAMMAR_ID__-diagram.ts +18 -0
  325. package/templates/host-vscode/src/webview/diagram.css +40 -0
  326. package/templates/host-vscode/start.mjs +22 -0
  327. package/templates/host-vscode/test/content-server.cjs +40 -0
  328. package/templates/host-vscode/test/install-vscode.mts +21 -0
  329. package/templates/host-vscode/test/virtual-documents.spec.mts +28 -0
  330. package/templates/host-vscode/test/vscode-version.mts +10 -0
  331. package/templates/host-vscode/tsconfig.e2e.json +17 -0
  332. package/templates/host-vscode/tsconfig.json +19 -0
  333. package/templates/host-vscode/tsconfig.webview.json +17 -0
  334. package/templates/oxlintrc.json +4 -0
  335. package/templates/protocol/gitignore +3 -0
  336. package/templates/protocol/src/__GRAMMAR_ID__-diagram-types.ts +47 -0
  337. package/templates/server/gitignore +6 -0
  338. package/templates/server/src/glsp/__GRAMMAR_ID__/create-node-operation-handler.ts +62 -0
  339. package/templates/server/src/glsp/__GRAMMAR_ID__/delete-operation-handler.ts +63 -0
  340. package/templates/server/src/glsp/__GRAMMAR_ID__/gmodel-factory.ts +144 -0
  341. package/templates/server/src/glsp/__GRAMMAR_ID__/state.ts +18 -0
  342. package/templates/server/src/glsp/__GRAMMAR_ID__/storage.ts +16 -0
  343. package/templates/server/src/glsp/__GRAMMAR_ID__/submission-handler.ts +24 -0
  344. package/templates/server/src/grammar/common.langium +12 -0
  345. package/templates/server/src/language-server/__GRAMMAR_ID__-semantic-tokens.ts +10 -0
  346. package/templates/server/src/language-server/__GRAMMAR_ID__-serializer.ts +53 -0
  347. package/templates/server/src/language-server/__GRAMMAR_ID__-validation.ts +30 -0
  348. package/templates/server/src/language-server/ast.ts +23 -0
  349. package/templates/server/src/node/services.ts +16 -0
  350. package/templates/server/test/__GRAMMAR_ID__-diagram.test.ts +403 -0
  351. package/templates/server/test/__GRAMMAR_ID__-semantic-tokens.test.ts +34 -0
  352. package/templates/server/test/tsconfig.json +4 -0
  353. package/templates/server/tsconfig.test.json +10 -0
  354. package/templates/server/vitest.config.ts +14 -0
  355. package/templates/theia/gitignore +3 -0
  356. package/templates/theia/src/browser/__GRAMMAR_ID__-diagram-frontend-module.ts +65 -0
  357. package/templates/theia/src/browser/__PROJECT_ID__-connection-preload-module.ts +15 -0
  358. package/templates/theia/src/browser/__PROJECT_ID__-data-connection.ts +15 -0
  359. package/templates/theia/src/browser/__PROJECT_ID__-data-port.ts +11 -0
  360. package/templates/theia/src/browser/__PROJECT_ID__-glsp-client-contribution.ts +13 -0
  361. package/templates/theia/src/browser/__PROJECT_ID__-show-model-command.ts +51 -0
  362. package/templates/theia/src/common/__PROJECT_ID__-glsp-contribution.ts +3 -0
  363. package/templates/theia/src/node/__PROJECT_ID__-connection-backend-module.ts +12 -0
  364. package/templates/theia/src/node/__PROJECT_ID__-data-backend-module.ts +15 -0
  365. package/templates/theia/src/node/__PROJECT_ID__-glsp-backend-module.ts +16 -0
  366. package/templates/theia/style/diagram.css +20 -0
  367. package/templates/theia/tsconfig.json +24 -0
  368. package/templates/vscode-servers/gitignore +4 -0
  369. package/templates/vscode-servers/tsconfig.json +19 -0
  370. package/templates/workspace/nodes.__EXTENSION__ +5 -0
  371. 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,46 +309,207 @@ 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: {
230
- langium: '4.3.1',
231
- 'vscode-languageserver': '~10.0.1'
317
+ const HEAD_THIRD_PARTY_DEPENDENCIES: Record<InitHead | 'base', Readonly<Record<string, string>>> = {
318
+ base: {
319
+ langium: '4.4.0',
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.1.2',
324
+ 'vscode-jsonrpc': '9.0.3',
325
+ 'vscode-languageserver-protocol': '3.18.4',
326
+ // The copy that protocol pins; a root without it takes the one Theia pins.
327
+ 'vscode-languageserver-types': '3.18.4'
232
328
  },
329
+ lsp: {},
233
330
  data: {},
234
331
  glsp: {
235
- '@eclipse-glsp/graph': '2.7.0',
236
- '@eclipse-glsp/server': '2.7.0',
237
- // `^6.1.3` and NOT `^6.0.0`: `@eclipse-glsp/server@2.7.0` requires it, and
332
+ '@eclipse-glsp/graph': '2.8.0',
333
+ '@eclipse-glsp/server': '2.8.0',
334
+ // `^6.1.3` and NOT `^6.0.0`: `@eclipse-glsp/server` requires it, and
238
335
  // `^6.0.0` resolved only because the hoisted copy happened to satisfy it.
239
336
  inversify: '^6.1.3',
240
337
  'reflect-metadata': '~0.2.2'
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.8.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.8.0',
356
+ inversify: '^6.1.3'
357
+ };
358
+
359
+ /**
360
+ * What each head adds to the browser host, which bundles the server into its
361
+ * worker and the head's client into its page. `base` is what every page needs.
362
+ *
363
+ * `monaco-editor-core` is exact for the reason `langium` is: Monaco's models
364
+ * live in one copy, and `@hydranium/client-browser` must reach the page's.
365
+ */
366
+ const HOST_BROWSER_FRAMEWORK_DEPENDENCIES: Record<InitHead | 'base', readonly string[]> = {
367
+ base: ['@hydranium/client-browser', '@hydranium/core', '@hydranium/protocol'],
368
+ lsp: [],
369
+ data: ['@hydranium/data-server'],
370
+ glsp: ['@hydranium/glsp-client', '@hydranium/glsp-server']
371
+ };
372
+ const HOST_BROWSER_THIRD_PARTY_DEPENDENCIES: Record<InitHead | 'base', Readonly<Record<string, string>>> = {
373
+ base: { 'vscode-jsonrpc': '9.0.3', 'vscode-languageserver-protocol': '3.18.4' },
374
+ lsp: { 'monaco-editor-core': '0.56.0' },
375
+ data: {},
376
+ glsp: { '@eclipse-glsp/server': '2.8.0', 'reflect-metadata': '~0.2.2' }
377
+ };
378
+
379
+ /** The browser host's tools: the bundler, the smoke tier and the type check. */
380
+ const HOST_BROWSER_DEV_DEPENDENCIES: Readonly<Record<string, string>> = {
381
+ '@playwright/test': '^1.55.0',
382
+ '@types/node': '^22.0.0',
383
+ esbuild: '^0.28.0',
384
+ rimraf: '^5.0.0',
385
+ typescript: '^7.0.2'
386
+ };
387
+
388
+ /** The language client both VS Code extensions start the server with. */
389
+ const VSCODE_LANGUAGE_CLIENT: Readonly<Record<string, string>> = { 'vscode-languageclient': '10.1.2' };
390
+
391
+ /** The VS Code API's types, at the oldest VS Code both extensions run in, which `engines` names too. */
392
+ const VSCODE_ENGINE = '^1.101.0';
393
+
394
+ /**
395
+ * What the GLSP head adds to the VS Code extension: the connector in the
396
+ * extension host and the diagram webview's starter, which bundles the client
397
+ * member.
398
+ */
399
+ const HOST_VSCODE_GLSP_FRAMEWORK_DEPENDENCIES: readonly string[] = [
400
+ '@hydranium/client-vscode',
401
+ '@hydranium/glsp-client',
402
+ '@hydranium/glsp-client-vscode',
403
+ '@hydranium/protocol'
404
+ ];
405
+ const HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES: Readonly<Record<string, string>> = {
406
+ '@eclipse-glsp/client': '2.8.0',
407
+ '@eclipse-glsp/vscode-integration': '2.8.0',
408
+ '@eclipse-glsp/vscode-integration-webview': '2.8.0',
409
+ inversify: '^6.1.3',
410
+ 'vscode-jsonrpc': '9.0.3'
411
+ };
412
+
413
+ /** What the data head adds to the VS Code extension: the Show Model command's socket to it. */
414
+ const HOST_VSCODE_DATA_FRAMEWORK_DEPENDENCIES: readonly string[] = [
415
+ '@hydranium/client-vscode',
416
+ '@hydranium/data-client-vscode',
417
+ '@hydranium/protocol'
418
+ ];
419
+ // Exact, as the server's is: the socket's connection and the framework's must be one copy.
420
+ const HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES: Readonly<Record<string, string>> = { 'vscode-jsonrpc': '9.0.3' };
421
+
422
+ /** The VS Code extension's tools: the smoke tier, the download it runs in, the type check and the watch. */
423
+ const HOST_VSCODE_DEV_DEPENDENCIES: Readonly<Record<string, string>> = {
424
+ '@playwright/test': '^1.55.0',
425
+ '@types/node': '^22.0.0',
426
+ '@types/vscode': VSCODE_ENGINE,
427
+ '@vscode/test-electron': '^3.1.0',
428
+ concurrently: '^9.0.0',
429
+ rimraf: '^5.0.0',
430
+ typescript: '^7.0.2'
431
+ };
432
+
433
+ /**
434
+ * The exact pins of every member the composition emits, for a workspace root
435
+ * to declare too. npm installs a root's own dependencies at the top of the
436
+ * tree, so another member's version of one nests beneath that member instead of
437
+ * taking the place of the copy this package shares with the framework.
438
+ */
439
+ export function workspaceRootPins(composition: InitComposition): ReadonlyArray<readonly [string, string]> {
440
+ const { heads } = composition;
441
+ const members = initMembers(heads, composition.hosts);
442
+ const pins = new Map([
443
+ ...Object.entries(HEAD_THIRD_PARTY_DEPENDENCIES.base),
444
+ ...heads.flatMap(head => [
445
+ ...Object.entries(HEAD_THIRD_PARTY_DEPENDENCIES[head]),
446
+ ...Object.entries(PROTOCOL_THIRD_PARTY_DEPENDENCIES[head])
447
+ ]),
448
+ ...(members.includes('client') ? Object.entries(CLIENT_THIRD_PARTY_DEPENDENCIES) : []),
449
+ ...(members.includes('host-browser')
450
+ ? (['base', ...heads] as const).flatMap(head => Object.entries(HOST_BROWSER_THIRD_PARTY_DEPENDENCIES[head]))
451
+ : []),
452
+ ...(members.includes('vscode-servers') ? Object.entries(VSCODE_LANGUAGE_CLIENT) : []),
453
+ ...(members.includes('host-vscode') && heads.includes('glsp') ? Object.entries(HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES) : []),
454
+ ...(members.includes('host-vscode') && heads.includes('data') ? Object.entries(HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES) : []),
455
+ ...(members.includes('theia') ? theiaThirdPartyDependencies(heads) : []),
456
+ ...(members.includes('host-theia-browser') ? hostTheiaBrowserTheiaDependencies() : []),
457
+ ...(members.includes('host-theia-electron') ? hostTheiaElectronPins() : [])
458
+ ]);
459
+ return [...pins].filter(([, version]) => /^\d+\.\d+\.\d+$/.test(version)).sort(([left], [right]) => left.localeCompare(right));
460
+ }
461
+
462
+ /** 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. */
463
+ function installsVitest41(npmVersion: string | undefined): boolean {
464
+ const [release, prerelease] = (npmVersion ?? '0.0.0').split('-', 2);
465
+ const [major, minor, patch] = release.split('.').map(Number);
466
+ return major > 11 || (major === 11 && (minor > 6 || (minor === 6 && (patch > 0 || prerelease === undefined))));
467
+ }
468
+
469
+ /**
470
+ * Whether the scaffold holds `vitest` below 4.1, whose peer set crashes npm
471
+ * before 11.6 (every npm a Node 22 release bundles) on the first install. Only a
472
+ * workspace root declaring a newer npm lifts it, and only when `init` runs under
473
+ * an npm known to be newer: npm does not enforce `packageManager`.
474
+ */
475
+ function pinsVitest(composition: InitComposition): boolean {
476
+ const workspace = composition.packaging.workspace;
477
+ return !(installsVitest41(workspace?.packageManagerNpm) && installsVitest41(workspace?.npmVersion));
478
+ }
479
+
480
+ /**
481
+ * The version a member pins a sibling member at: exact, at the version every
482
+ * member starts with. npm links a sibling only when the range admits its local
483
+ * version, and otherwise looks for it in the registry, where it was never
484
+ * published.
485
+ */
486
+ const MEMBER_PIN = '0.0.0';
487
+
488
+ /** A dependency block, sorted as npm writes it. */
489
+ function sortedBlock(dependencies: Readonly<Record<string, string>>, indent: string): string {
490
+ return Object.keys(dependencies)
491
+ .sort()
492
+ .map(name => `${indent}"${name}": "${dependencies[name]}"`)
493
+ .join(',\n');
494
+ }
495
+
496
+ /** The server's dependency block: the base and head set's packages and the protocol member. */
245
497
  function dependencyBlock(composition: InitComposition, indent: string): string {
246
- const merged: Record<string, string> = {};
247
- for (const head of composition.heads) {
498
+ const merged: Record<string, string> = { [memberPackageName(composition, 'protocol')]: MEMBER_PIN };
499
+ for (const head of ['base', ...composition.heads] as const) {
248
500
  Object.assign(merged, HEAD_THIRD_PARTY_DEPENDENCIES[head]);
249
501
  for (const framework of HEAD_FRAMEWORK_DEPENDENCIES[head]) {
250
502
  merged[framework] = frameworkPin(composition);
251
503
  }
252
504
  }
253
- return Object.keys(merged)
254
- .sort()
255
- .map(name => `${indent}"${name}": "${merged[name]}"`)
256
- .join(',\n');
505
+ return sortedBlock(merged, indent);
257
506
  }
258
507
 
259
508
  // JSON at two-space indent, not the three the `.ts` templates use: that is the
260
509
  // npm convention, and `npm install` rewrites `package.json` at two spaces
261
510
  // regardless — so three would not survive the adopter's first install.
262
511
  //
263
- // The KEY ORDER is `prettier-plugin-packagejson`'s canonical one, `private`
512
+ // The KEY ORDER is the one Oxfmt's `sortPackageJson` canonicalises to, `private`
264
513
  // before `license` included. Any other order is rewritten by the scaffolded
265
514
  // project's own first `format` run — a diff on a file the adopter never touched
266
515
  // — and it makes a byte-compare against a formatted copy of this emission
@@ -280,6 +529,11 @@ function dependencyBlock(composition: InitComposition, indent: string): string {
280
529
  // from this package's own grammar and can reach a consumer from nowhere else; a
281
530
  // listed path that does not exist yet is inert.
282
531
  //
532
+ // `exports` puts `createServices`, the one module reading the real filesystem,
533
+ // behind `./node`, so the root loads in a browser worker that has no `node:fs`.
534
+ // `./lib/*` and `./package.json` stay reachable for a host that resolves
535
+ // `<server>/lib/main.js` to spawn the server.
536
+ //
283
537
  // `repository` is deliberately NOT emitted while `author` is emitted empty. An
284
538
  // empty `author` is the form `npm init` itself writes and asserts nothing, but
285
539
  // `repository` is CONSUMED — the registry page, `npm repo` and publish
@@ -291,16 +545,9 @@ const PACKAGE_JSON = `{
291
545
  "version": "0.0.0",
292
546
  __PRIVATE__ "description": "__NAME__ language server, built with the Hydranium framework.",
293
547
  "keywords": [
294
- "hydranium",
295
- "langium",
296
- "language-server",
297
- "__PROJECT_ID__"
298
- ],
548
+ __KEYWORDS__ ],
299
549
  "license": "UNLICENSED",
300
550
  "author": "",
301
- "type": "module",
302
- "main": "lib/index.js",
303
- "types": "lib/index.d.ts",
304
551
  "bin": {
305
552
  __BIN__ },
306
553
  "files": [
@@ -308,17 +555,32 @@ __BIN__ },
308
555
  "src",
309
556
  "syntaxes"
310
557
  ],
558
+ "type": "module",
559
+ "main": "lib/index.js",
560
+ "types": "lib/index.d.ts",
561
+ "exports": {
562
+ ".": {
563
+ "types": "./lib/index.d.ts",
564
+ "default": "./lib/index.js"
565
+ },
566
+ "./node": {
567
+ "types": "./lib/node/services.d.ts",
568
+ "default": "./lib/node/services.js"
569
+ },
570
+ "./lib/*": "./lib/*",
571
+ "./package.json": "./package.json"
572
+ },
311
573
  "scripts": {
312
- "build": "npm run generate && tsc",
313
- "clean": "rimraf lib syntaxes src/language-server/generated src/language-server/generated-hydranium tsconfig.tsbuildinfo",
574
+ "build": "npm run generate && tsc -b",
575
+ "clean": "rimraf lib syntaxes src/language-server/generated src/language-server/generated-hydranium test/generated-hydranium tsconfig.tsbuildinfo",
314
576
  "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\\"",
577
+ "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
578
  "langium:generate": "langium generate",
317
579
  "langium:watch": "langium generate --watch",
318
- __LINT__ "start": "node lib/main.js --stdio",
580
+ __LINT__ "start": "node lib/main.js__START_ARGS__",
319
581
  "test": "npm run typecheck:test && vitest run",
320
582
  "typecheck:test": "tsc --noEmit -p tsconfig.test.json",
321
- "watch": "tsc --watch"
583
+ "watch": "concurrently --kill-others --names langium,transfer-model,tsc \\"npm run langium:watch\\" \\"npm run generate:transfer-model -- --watch\\" \\"tsc -b --watch\\""
322
584
  },
323
585
  "dependencies": {
324
586
  __DEPENDENCIES__
@@ -326,28 +588,33 @@ __DEPENDENCIES__
326
588
  "devDependencies": {
327
589
  "@hydranium/cli": "__FRAMEWORK_PIN__",
328
590
  "@types/node": "^22.0.0",
329
- "langium-cli": "4.3.0",
591
+ "concurrently": "^9.0.0",
592
+ "langium-cli": "4.4.0",
330
593
  "rimraf": "^5.0.0",
331
- "typescript": "^5.8.0",
332
- "vitest": "^4.0.0"
594
+ "typescript": "^7.0.2",
595
+ "vitest": "__VITEST__"
333
596
  },
334
597
  "engines": {
335
598
  "node": ">=22.13"
599
+ },
600
+ "hydranium": {
601
+ "services": "./lib/node/services.js"
336
602
  }
337
603
  }
338
604
  `;
339
605
 
340
606
  /**
341
- * How the scaffold names `npm run` when talking about itself.
607
+ * How the scaffold names `npm run` for one member's script.
342
608
  *
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.
609
+ * Always with `--prefix`, from the directory commands are run in: the
610
+ * workspace root for a member, the project root for a standalone project. A
611
+ * bare `npm run` there reaches the ROOT manifest and fails, and the regen hint
612
+ * a generated file prints is read in `protocol/` as well, where the script it
613
+ * names does not exist.
347
614
  */
348
- function npmRun(composition: InitComposition): string {
615
+ function npmRun(composition: InitComposition, member: InitMember): string {
349
616
  const workspace = composition.packaging.workspace;
350
- return workspace === undefined ? 'npm run' : `npm --prefix ${workspace.targetPath} run`;
617
+ return `npm --prefix ${workspace === undefined ? member : `${workspace.targetPath}/${member}`} run`;
351
618
  }
352
619
 
353
620
  /**
@@ -359,7 +626,7 @@ function npmRun(composition: InitComposition): string {
359
626
  * name. Without the second key a scaffolded project has no command line that
360
627
  * reaches its own data head at all.
361
628
  *
362
- * Alphabetical, because `prettier-plugin-packagejson` sorts `bin` and any other
629
+ * Alphabetical, because Oxfmt's `sortPackageJson` sorts `bin` and any other
363
630
  * order is rewritten by the scaffolded project's first `format` run.
364
631
  */
365
632
  function binBlock(composition: InitComposition): string {
@@ -370,21 +637,39 @@ function binBlock(composition: InitComposition): string {
370
637
  return entries.map(([name, target]) => ` "${name}": "${target}"`).join(',\n') + '\n';
371
638
  }
372
639
 
373
- /** `package.json` with the name, the private flag and the dependency block all derived. */
640
+ /**
641
+ * A member's `lint` script line, over `directories`, or nothing.
642
+ *
643
+ * Emitted only where a root lint config says the repo lints. The absence is
644
+ * the dangerous direction: a task runner runs a script only where one is
645
+ * declared, so a package with no `lint` is SKIPPED rather than reported, and
646
+ * that reads as a clean lint. A wrong invocation is one visible line to edit.
647
+ */
648
+ function lintScript(member: InitComposition, directories: string): string {
649
+ const workspace = member.packaging.workspace;
650
+ if (workspace?.oxlintConfig !== undefined) {
651
+ const config = `${'../'.repeat(workspace.targetPath.split('/').length)}${workspace.oxlintConfig}`;
652
+ return ` "lint": "oxlint --report-unused-disable-directives --format stylish --config ${config} ${directories} --max-warnings 0",\n`;
653
+ }
654
+ return workspace?.eslintConfig !== undefined ? ` "lint": "eslint ${directories} --max-warnings 0",\n` : '';
655
+ }
656
+
657
+ /** The server's `package.json`, with the name, the private flag and the dependency block all derived. */
374
658
  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';
659
+ const keywords =
660
+ ['hydranium', 'langium', 'language-server', composition.projectId]
661
+ .sort()
662
+ .map(keyword => ` ${JSON.stringify(keyword)}`)
663
+ .join(',\n') + '\n';
382
664
  return project(PACKAGE_JSON, composition)
383
- .replace('__PACKAGE_NAME__', packageName)
665
+ .replace('__PACKAGE_NAME__', memberPackageName(composition, 'server'))
666
+ .replace('__KEYWORDS__', keywords)
384
667
  .replace('__BIN__', binBlock(composition))
385
- .replace('__LINT__', lint)
668
+ .replace('__LINT__', lintScript(forMember(composition, 'server'), 'src test'))
669
+ .replace('__START_ARGS__', composition.heads.includes('lsp') ? ' --stdio' : ' ../workspace')
670
+ .replace('__VITEST__', pinsVitest(composition) ? '~4.0.18' : '^4.0.0')
386
671
  .replace('__PRIVATE__', composition.packaging.private ? ' "private": true,\n' : '')
387
- .replace('__NPM_RUN__', npmRun(composition))
672
+ .replace('__NPM_RUN__', npmRun(composition, 'server'))
388
673
  .replace('__FRAMEWORK_PIN__', frameworkPin(composition))
389
674
  .replace('__DEPENDENCIES__', dependencyBlock(composition, ' '));
390
675
  }
@@ -452,6 +737,24 @@ const TSCONFIG_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
452
737
  ['types', ['node']]
453
738
  ];
454
739
 
740
+ /** The protocol member's compiler options, pruned against a workspace base like the server's. */
741
+ const PROTOCOL_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
742
+ ['target', 'ES2022'],
743
+ ['lib', ['ES2022']],
744
+ ['module', 'NodeNext'],
745
+ ['moduleResolution', 'NodeNext'],
746
+ ['rootDir', 'src'],
747
+ ['outDir', 'lib'],
748
+ ['strict', true],
749
+ ['skipLibCheck', true],
750
+ ['declaration', true],
751
+ // The server's `tsc -b` builds this project through a reference, which
752
+ // `tsc` refuses unless the referenced project is composite.
753
+ ['composite', true],
754
+ // No ambient Node types: a browser client compiles against this package.
755
+ ['types', []]
756
+ ];
757
+
455
758
  /**
456
759
  * The options that describe where THIS package's own files live. Never pruned,
457
760
  * and emitted first in the workspace case: a base config that supplied them
@@ -460,9 +763,20 @@ const TSCONFIG_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
460
763
  */
461
764
  const PACKAGE_LOCAL_OPTIONS: readonly string[] = ['rootDir', 'outDir'];
462
765
 
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);
766
+ /**
767
+ * The enum-valued options of {@link TSCONFIG_COMPILER_OPTIONS}, whose values
768
+ * `tsc` reads case-insensitively, so `nodenext` and `NodeNext` are one value.
769
+ * An enum-valued option added there belongs here too.
770
+ */
771
+ const CASE_INSENSITIVE_OPTIONS: readonly string[] = ['target', 'lib', 'module', 'moduleResolution'];
772
+
773
+ /** Compare two option values. Sound here because compiler options are scalars and flat arrays. */
774
+ function optionEquals(key: string, left: JsonValue | undefined, right: JsonValue): boolean {
775
+ const normalise = (value: JsonValue | undefined) => {
776
+ const text = JSON.stringify(value);
777
+ return CASE_INSENSITIVE_OPTIONS.includes(key) ? text?.toLowerCase() : text;
778
+ };
779
+ return normalise(left) === normalise(right);
466
780
  }
467
781
 
468
782
  /**
@@ -472,112 +786,57 @@ function jsonEquals(left: JsonValue | undefined, right: JsonValue): boolean {
472
786
  * the same key: inheriting `"module": "CommonJS"` where the scaffold needs
473
787
  * `NodeNext` would break every emitted import, so a differing base value is a
474
788
  * reason to keep the override rather than to trust the parent.
789
+ *
790
+ * `member` is the composition as that member sees it, so `extends` reaches the
791
+ * workspace base from the member's own directory.
475
792
  */
476
- function tsconfigJson(composition: InitComposition): string {
477
- const workspace = composition.packaging.workspace;
793
+ function tsconfigJson(
794
+ member: InitComposition,
795
+ compilerOptions: ReadonlyArray<readonly [string, JsonValue]>,
796
+ include: string,
797
+ references = ''
798
+ ): string {
799
+ const workspace = member.packaging.workspace;
478
800
  const base = workspace?.baseTsconfig === undefined ? undefined : (workspace.baseCompilerOptions ?? {});
479
801
  const options =
480
802
  base === undefined
481
- ? TSCONFIG_COMPILER_OPTIONS
803
+ ? compilerOptions
482
804
  : [
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))
805
+ ...compilerOptions.filter(([key]) => PACKAGE_LOCAL_OPTIONS.includes(key)),
806
+ ...compilerOptions.filter(([key, value]) => !PACKAGE_LOCAL_OPTIONS.includes(key) && !optionEquals(key, base[key], value))
485
807
  ];
486
808
  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"]
809
+ // An array spaced as a formatter writes it, which `JSON.stringify` does not.
810
+ const json = (value: JsonValue): string => (Array.isArray(value) ? `[${value.map(json).join(', ')}]` : JSON.stringify(value));
811
+ const body = options.map(([key, value]) => ` "${key}": ${json(value)}`).join(',\n');
812
+ const referencesLine = references === '' ? '' : `,\n "references": ${references}`;
813
+ return `{\n${extendsLine} "compilerOptions": {\n${body}\n },\n "include": ${include}${referencesLine}\n}\n`;
507
814
  }
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
815
 
534
816
  /**
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
- `;
817
+ * The server's `tsconfig.json`. It references the protocol member, so `tsc -b`
818
+ * compiles protocol first, after `generate` has written its generated modules.
819
+ */
820
+ function serverTsconfigJson(composition: InitComposition): string {
821
+ return tsconfigJson(
822
+ forMember(composition, 'server'),
823
+ TSCONFIG_COMPILER_OPTIONS,
824
+ '["src", "src/**/*.json"]',
825
+ '[{ "path": "../protocol" }]'
826
+ );
827
+ }
561
828
 
562
829
  /**
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.
830
+ * The terminals every grammar needs: the shared fragment's text after its
831
+ * leading comment run, so a lone grammar declares the same set.
567
832
  */
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}`;
833
+ function terminals(): string {
834
+ return template('server/src/grammar/common.langium').replace(/^(\/\/.*\n)*\n/, '');
835
+ }
577
836
 
578
837
  /** One starter grammar. `shared` decides whether it imports the fragment or declares its own terminals. */
579
838
  function grammarFile(shared: boolean): string {
580
- const lexis = shared ? "import './common'\n" : `\n${TERMINALS}`;
839
+ const lexis = shared ? "import './common'\n" : `\n${terminals()}`;
581
840
  return `grammar __GRAMMAR__
582
841
  ${shared ? '\n' + lexis : ''}
583
842
  // A minimal starter grammar — replace with your own language. \`__NODE_RULE__\` is
@@ -640,8 +899,12 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
640
899
  };`
641
900
  : `const __NAME__SharedModule: Module<__NAME__SharedServices, PartialLangiumSharedServices> = {};`;
642
901
 
643
- const serializerImports = composition.grammars
644
- .map(grammar => `import { ${grammar.grammar}Serializer } from './${grammar.grammarId}-serializer.js';`)
902
+ const languageImports = composition.grammars
903
+ .flatMap(grammar => [
904
+ `import { ${grammar.grammar}SemanticTokenProvider } from './${grammar.grammarId}-semantic-tokens.js';`,
905
+ `import { ${grammar.grammar}Serializer } from './${grammar.grammarId}-serializer.js';`,
906
+ `import { ${grammar.grammar}ValidationContribution } from './${grammar.grammarId}-validation.js';`
907
+ ])
645
908
  .join('\n');
646
909
 
647
910
  // Each language gets its own adopter module because `Serializer` is a
@@ -650,17 +913,29 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
650
913
  // serializer — and that one throws on a `$type` it has no emitter for.
651
914
  const languageModules = composition.grammars
652
915
  .map(
653
- grammar => `const ${grammar.grammar}LanguageModule: Module<__NAME__Services, PartialLangiumServices & DeepPartial<ServerAddedServices>> = {
916
+ grammar => `const ${grammar.grammar}LanguageModule = (
917
+ options: __NAME__Options
918
+ ): Module<__NAME__Services, PartialLangiumServices & DeepPartial<ServerAddedServices>> => ({
919
+ lsp: {
920
+ SemanticTokenProvider: services => new ${grammar.grammar}SemanticTokenProvider(services, options)
921
+ },
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
  )
659
932
  .join('\n\n');
660
933
 
661
934
  const additionalLanguages = multi
662
935
  ? `,\n additionalLanguages: ${arrayLiteral(
663
- additional.map(grammar => `{ generated: ${grammar.grammar}GeneratedModule, adopter: () => ${grammar.grammar}LanguageModule }`),
936
+ additional.map(
937
+ grammar => `{ generated: ${grammar.grammar}GeneratedModule, adopter: () => ${grammar.grammar}LanguageModule(options) }`
938
+ ),
664
939
  ' ',
665
940
  columns
666
941
  )}`
@@ -674,11 +949,11 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
674
949
 
675
950
  const text = `// DI bootstrap for __NAME__. Composes the framework defaults with adopter
676
951
  // 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.
952
+ // \`createIntegrationServices\`). Each adopter module binds its language's
953
+ // \`Serializer\`, which the framework cannot default because a concrete syntax
954
+ // is grammar knowledge, its semantic tokens and its validation checks. Scope,
955
+ // naming, project management and the build pipeline use the framework defaults;
956
+ // scope computation and AST extensions go in these same modules.
682
957
  //
683
958
  // Note which generated symbol comes from which name: the SHARED module is
684
959
  // \`__NAME__GeneratedSharedModule\` (from \`projectName\`) and there is one of it,
@@ -693,11 +968,20 @@ export const __CONFIG_ROOT_CONST___CONFIGURATION_ROOT = '__PROJECT_ID__';
693
968
  : `
694
969
  //
695
970
  // A second grammar goes in the \`additionalLanguages\` option of
696
- // \`createIntegrationServices\`, generated from this same \`langium-config.json\`.`
971
+ // \`createIntegrationServices\`, generated from this same \`langium-config.json\`.
972
+ // With several languages, bind \`lsp.configurationRoot\` in
973
+ // \`__NAME__SharedModule\`, or the framework warns and takes the first
974
+ // language's id. Type that module's second \`Module\` argument as
975
+ // \`PartialLangiumSharedServices & { lsp: { configurationRoot: string } }\`.`
697
976
  }
698
977
 
699
978
  ${importList(
700
- ['createLspServerLanguageModule', 'createLspServerSharedModule', 'type LspServerAddedServices', 'type LspServerAddedSharedServices'],
979
+ [
980
+ 'createLspServerLanguageModule',
981
+ 'createLspServerSharedModule',
982
+ 'type HydraniumSemanticTokenProviderOptions',
983
+ 'type LspServerAddedSharedServices'
984
+ ],
701
985
  '@hydranium/core/lsp',
702
986
  columns
703
987
  )}
@@ -705,22 +989,21 @@ import { createIntegrationServices, type ServerAddedServices, type ServerModuleC
705
989
  import { type DeepPartial, EmptyFileSystem, type Module } from '@hydranium/langium';
706
990
  import { type LangiumServices, type PartialLangiumServices, type PartialLangiumSharedServices } from '@hydranium/langium/lsp';
707
991
  ${importList(generatedImports, './generated/module.js', columns)}
708
- ${serializerImports}
992
+ ${languageImports}
709
993
 
710
994
  export type __NAME__SharedServices = ServerSharedServices & LspServerAddedSharedServices;
711
995
  export type __NAME__Services = LangiumServices &
712
- ServerAddedServices &
713
- LspServerAddedServices & {
996
+ ServerAddedServices & {
714
997
  shared: __NAME__SharedServices;
715
998
  };
716
999
 
717
1000
  /** What a host or a test may vary about this composition. */
718
- export interface __NAME__Options {
1001
+ export interface __NAME__Options extends HydraniumSemanticTokenProviderOptions {
719
1002
  /**
720
1003
  * Shared modules layered in after the framework's own bindings.
721
1004
  *
722
1005
  * The framework constructs most shared services with no options —
723
- * \`DocumentBuilder: services => new HydraniumDocumentBuilder(services)\` — so
1006
+ * \`DocumentBuilder: services => new DefaultHydraniumDocumentBuilder(services)\` — so
724
1007
  * rebinding the slot is the only way to boot one configured differently, and
725
1008
  * a factory that hard-codes its composition leaves a test nowhere to do it.
726
1009
  * That is what this is for: pass a module binding \`workspace.DocumentBuilder\`
@@ -756,7 +1039,7 @@ ${returnType}
756
1039
  },
757
1040
  languageModules: {
758
1041
  generated: ${primary.grammar}GeneratedModule,
759
- adopter: () => ${primary.grammar}LanguageModule,
1042
+ adopter: () => ${primary.grammar}LanguageModule(options),
760
1043
  extra: [createLspServerLanguageModule(fullContext)]
761
1044
  }${additionalLanguages}
762
1045
  });
@@ -766,185 +1049,135 @@ ${returnType}
766
1049
  return project(text, composition);
767
1050
  }
768
1051
 
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 });
1052
+ /** One exported constant of the protocol member's `head-ports.ts`. */
1053
+ interface HeadPortConstant {
1054
+ readonly name: string;
1055
+ readonly value: string;
1056
+ readonly doc: string;
780
1057
  }
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
1058
 
808
1059
  /**
809
- * The starter serializer — the concrete-syntax emitter for ONE grammar.
1060
+ * How a host finds each socket head's port, in emission order: an LSP request
1061
+ * when the LSP head publishes the ports, else the environment variable
1062
+ * `main.ts` reads a port from.
810
1063
  *
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
- }
1064
+ * Keyed by the PROJECT rather than by a language: one server of each kind per
1065
+ * process serves every registered grammar, so a language-derived name would tie
1066
+ * a project-level endpoint to whichever grammar was scaffolded first.
1067
+ */
1068
+ function headPortConstants(composition: InitComposition): HeadPortConstant[] {
1069
+ const upper = screamingSnake(composition.projectId);
1070
+ const lsp = composition.heads.includes('lsp');
1071
+ return socketHeads(composition).map(head =>
1072
+ lsp
1073
+ ? {
1074
+ name: `${upper}_${head.key}_PORT_COMMAND`,
1075
+ value: `${composition.projectId}/${head.path}/port`,
1076
+ doc: `LSP request the host queries to discover the ${head.label} socket port.`
1077
+ }
1078
+ : {
1079
+ name: `${upper}_${head.key}_PORT_ENV`,
1080
+ value: `${upper}_${head.key}_PORT`,
1081
+ doc: `Environment variable naming the ${head.label} socket port when no \`--${head.path}-port\` flag does.`
1082
+ }
1083
+ );
1084
+ }
851
1085
 
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
- }
1086
+ /** The socket heads of the composition, as `head-ports.ts` names them. */
1087
+ function socketHeads(composition: InitComposition) {
1088
+ return [
1089
+ ...(composition.heads.includes('data')
1090
+ ? [{ key: 'DATA_SERVER', path: 'data-server', command: 'dataServer', label: 'data-server' }]
1091
+ : []),
1092
+ ...(composition.heads.includes('glsp') ? [{ key: 'GLSP_SERVER', path: 'glsp-server', command: 'glsp', label: 'GLSP' }] : [])
1093
+ ];
1094
+ }
856
1095
 
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
- }
1096
+ /** Whether the composition emits the servers-only extension, which VS Code starts the server through and a Theia app sideloads. */
1097
+ function emitsVscodeServers(composition: InitComposition): boolean {
1098
+ return initMembers(composition.heads, composition.hosts).includes('vscode-servers');
868
1099
  }
869
- `;
870
1100
 
871
1101
  /**
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.
1102
+ * The host commands the servers extension answers each socket head's port
1103
+ * under, for a host without a language client of its own.
876
1104
  */
877
- function portCommandNames(composition: InitComposition): string[] {
1105
+ function hostCommandConstants(composition: InitComposition): HeadPortConstant[] {
1106
+ if (!emitsVscodeServers(composition)) {
1107
+ return [];
1108
+ }
878
1109
  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
- ];
1110
+ return socketHeads(composition).map(head => ({
1111
+ name: `${upper}_${head.key}_HOST_COMMAND`,
1112
+ value: `${composition.projectId}.port.${head.command}`,
1113
+ doc: `Host command the servers extension answers with the ${head.label} socket port.`
1114
+ }));
883
1115
  }
884
1116
 
885
1117
  /**
886
- * The socket heads' discovery commands, as an importable module.
1118
+ * The socket heads' port commands or variables, in the protocol member.
887
1119
  *
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.
1120
+ * A host shell has to name the same string the server reads, and reaches it
1121
+ * here without depending on the server. A host that retypes the literal
1122
+ * instead gets no error when it drifts: the framework's port poll defaults to
1123
+ * `findPortAttempts = -1`, so a wrong command retries forever rather than
1124
+ * failing, and a wrong variable is never read.
894
1125
  */
895
1126
  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' : ''}.
1127
+ const constants = [...headPortConstants(composition), ...hostCommandConstants(composition)];
1128
+ const blocks = constants.map(constant => `/** ${constant.doc} */\nexport const ${constant.name} = '${constant.value}';`);
1129
+ const socketHeadCount = socketHeads(composition).length;
1130
+ const heads = `socket head${socketHeadCount > 1 ? 's' : ''}`;
1131
+ const opening = composition.heads.includes('lsp')
1132
+ ? `// The LSP requests a host queries to discover this server's ${heads}.`
1133
+ : `// The environment variables that name the ports of this server's ${heads}.`;
1134
+ const usage = composition.heads.includes('lsp')
1135
+ ? `// The server publishes them and a host shell has to name the same string to
1136
+ // reach the head; both import them from here. A shell that retypes the literal
1137
+ // gets no error when it drifts: the framework's port poll retries indefinitely
1138
+ // by default.`
1139
+ : `// The server reads them and a process that starts it sets them; both import
1140
+ // them from here. A variable retyped with a typo is never read, and the head
1141
+ // then listens on whichever port is free.`;
1142
+ const hostCommands = emitsVscodeServers(composition)
1143
+ ? `
912
1144
  //
913
- // Both are keyed by the PROJECT, not the language: one server of each kind per
1145
+ // The host commands are the same ports for a host with no language client,
1146
+ // such as a Theia app sideloading the servers extension: it runs the command
1147
+ // and the extension sends the request.`
1148
+ : '';
1149
+ return `${opening}
1150
+ //
1151
+ // ${socketHeadCount > 1 ? 'Both are' : 'It is'} keyed by the PROJECT, not the language: one server of each kind per
914
1152
  // process serves every registered grammar, so a language-derived name would tie
915
1153
  // a project-level endpoint to whichever grammar was scaffolded first.
916
1154
  //
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.
1155
+ ${usage}${hostCommands}
922
1156
 
923
1157
  ${blocks.join('\n\n')}
924
1158
  `;
925
1159
  }
926
1160
 
927
- const INDEX = `// Public surface of the __NAME__ language server: the DI factory, the generated
928
- // AST, and the headless \`createServices\` entry.
1161
+ /**
1162
+ * The server's root entry: the DI factory, the generated AST and each diagram
1163
+ * module, all loadable in a browser worker.
1164
+ */
1165
+ function indexFile(composition: InitComposition): string {
1166
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
1167
+ const diagramPhrase = diagrams.length === 0 ? '' : diagrams.length === 1 ? ', plus the diagram module' : ', plus the diagram modules';
1168
+ const text = `// Public surface of the __NAME__ language server: the DI factory and the
1169
+ // generated AST${diagramPhrase}.
929
1170
  //
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\`.
1171
+ // Everything here loads in a browser worker as well as in Node, so a host can
1172
+ // compose the language wherever it runs it. \`createServices\`, which reads the
1173
+ // real filesystem, is the package's \`./node\` entry instead. The entry points
1174
+ // under \`src/\` are not re-exported either: each opens a transport at module
1175
+ // scope, so importing one starts a server, which is why they are \`bin\` targets.
933
1176
 
934
1177
  export * from './language-server/__PROJECT_ID__-module.js';
935
1178
  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;
1179
+ ${diagrams.map(grammar => `export * from './glsp/${grammar.grammarId}/diagram-module.js';\n`).join('')}`;
1180
+ return project(text, composition);
948
1181
  }
949
1182
 
950
1183
  /**
@@ -972,12 +1205,14 @@ const SHEBANG = '#!/usr/bin/env node\n';
972
1205
  */
973
1206
  function mainFile(composition: InitComposition): string {
974
1207
  const columns = columnsFor(composition);
975
- const roots = [...composition.grammars.map(grammar => grammar.entryRule)].sort();
1208
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
976
1209
  const upper = screamingSnake(composition.projectId);
1210
+ const lsp = composition.heads.includes('lsp');
977
1211
  const data = composition.heads.includes('data');
978
1212
  const glsp = composition.heads.includes('glsp');
979
1213
  const diagrams = composition.grammars.filter(grammar => grammar.diagram);
980
1214
  const plural = roots.length > 1 ? 's' : '';
1215
+ const portFlags = [...(data ? ['--data-server-port'] : []), ...(glsp ? ['--glsp-server-port'] : [])];
981
1216
 
982
1217
  const headNames = composition.heads.map(head =>
983
1218
  head === 'lsp' ? 'the Langium LSP head' : head === 'data' ? 'a socket data-server (model server) head' : 'a GLSP head'
@@ -991,7 +1226,7 @@ function mainFile(composition: InitComposition): string {
991
1226
  // `reflect-metadata` must be imported before anything that reads a
992
1227
  // decorator's emitted metadata, which inversify does at module scope.
993
1228
  const reflectImport = glsp ? "import 'reflect-metadata';\n" : '';
994
- const coreNodeSymbols = ['NodeFileSystem', ...(data ? ['publishPortOnLspConnection', 'startSocketServer'] : [])];
1229
+ const coreNodeSymbols = ['NodeFileSystem', ...(data ? [...(lsp ? ['publishPortOnLspConnection'] : []), 'startSocketServer'] : [])];
995
1230
  const glspImports = glsp
996
1231
  ? `import { ServerModule } from '@eclipse-glsp/server/node.js';
997
1232
  import { GlspClientLogger, HydraniumGlspAppModule } from '@hydranium/glsp-server';
@@ -1008,46 +1243,59 @@ import { startGlspServer } from '@hydranium/glsp-server/node';
1008
1243
  // \`TransferElement\` structurally, so naming the AST type here compiles fine and
1009
1244
  // silently tells every typed client that a reference is a resolvable object
1010
1245
  // rather than a name.
1011
- ${importList(roots, './language-server/generated-hydranium/transfer-model.js', columns, true)}
1246
+ ${importList(roots, memberPackageName(composition, 'protocol'), columns, true)}
1012
1247
  `
1013
1248
  : '';
1014
1249
 
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
- ? `
1250
+ // The names live in the protocol member, not here: a host shell has to name
1251
+ // the same string to reach the head, and this file is an executable entry,
1252
+ // so nothing can import from it.
1253
+ const portNames = headPortConstants(composition).map(constant => constant.name);
1254
+ const portImports = portNames.length ? importList(portNames, memberPackageName(composition, 'protocol'), columns) + '\n' : '';
1255
+
1256
+ const dataBlock = !data
1257
+ ? ''
1258
+ : !lsp
1259
+ ? `
1260
+ // Data-server head: each accepted client gets its own DataServer.
1261
+ const dataServer = startSocketServer(
1262
+ { shared, workspace, port: portFrom('data-server-port', ${upper}_DATA_SERVER_PORT_ENV), logTag: 'ModelServer', logger: shared.Logger },
1263
+ dataConnection => {
1264
+ new DataServer<${roots.join(' | ')}>(dataConnection, shared);
1265
+ return { dispose: () => undefined };
1266
+ }
1267
+ );
1268
+ `
1269
+ : `
1024
1270
  // Data-server head alongside LSP: binds an ephemeral port, published over the LSP
1025
1271
  // connection for the host to discover. Each accepted client gets its own DataServer.
1026
1272
  //
1027
1273
  // Neither the bind nor the publish may be swallowed: either failure leaves the LSP
1028
1274
  // head serving text edits while every data client waits on a port command that was
1029
1275
  // 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 => {
1276
+ const dataServer = startSocketServer({ shared, port: 0, logTag: 'ModelServer', logger: shared.Logger }, dataConnection => {
1031
1277
  new DataServer<${roots.join(' | ')}>(dataConnection, shared);
1032
1278
  return { dispose: () => undefined };
1033
1279
  });
1034
1280
  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
- })
1281
+ .then(
1282
+ () => {
1283
+ const { port } = dataServer;
1284
+ if (port === undefined) {
1285
+ // \`started\` resolves only once the address is resolved, so this is
1286
+ // unreachable; a non-null assertion in its place would publish
1287
+ // \`undefined\`, which the host cannot tell from an unreachable port.
1288
+ throw new Error('the data head started without a resolved port');
1289
+ }
1290
+ publishPortOnLspConnection(shared.lsp.Connection, ${upper}_DATA_SERVER_PORT_COMMAND, port);
1291
+ },
1292
+ // The launcher logged its own bind failure; the rejection is control flow.
1293
+ () => undefined
1294
+ )
1045
1295
  .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}\`);
1296
+ shared.Logger.error(\`[ModelServer] Could not publish the data-server port: \${describeErrorWithStack(error)}\`);
1048
1297
  });
1049
- `
1050
- : '';
1298
+ `;
1051
1299
 
1052
1300
  const glspBlock = glsp
1053
1301
  ? `
@@ -1056,94 +1304,159 @@ dataServer.started
1056
1304
  // grammar a request concerns, so nothing per-language belongs there — each
1057
1305
  // diagram module declares its own language instead.
1058
1306
  //
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.
1307
+ ${
1308
+ lsp
1309
+ ? `// GLSP framework logs route through the LSP connection rather than stdout, which
1310
+ // IS the LSP transport in stdio mode; writing there corrupts the protocol stream.`
1311
+ : `// GLSP framework logs route through the framework's logger to stderr. GLSP's
1312
+ // own startup line goes to stdout, beside the ports line below.`
1313
+ }
1061
1314
  const glspServer = startGlspServer({
1062
1315
  // The GLSP log threshold lives on the logger, not beside it: the framework
1063
1316
  // replaces GLSP's own \`Logger\` binding, so a launcher-level \`logLevel\` would
1064
1317
  // 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;
1318
+ // \`HYDRANIUM_LOG_LEVEL\` ${lsp ? 'and the LSP log-level setting govern' : 'governs'} GLSP output too;
1066
1319
  // pass \`logLevel\` only to make GLSP quieter than the rest of the server.
1067
1320
  createLogger: caller => new GlspClientLogger(shared, { component: caller }),
1068
1321
  serverModule: new ServerModule()${diagrams.map(grammar => `.configureDiagramModule(new ${grammar.grammar}DiagramModule())`).join('')},
1069
1322
  appModules: [new HydraniumGlspAppModule({ shared })],
1070
- lspConnection: shared.lsp.Connection,
1071
- portCommand: ${upper}_GLSP_PORT_COMMAND
1323
+ ${
1324
+ lsp
1325
+ ? ` lspConnection: shared.lsp.Connection,
1326
+ portCommand: ${upper}_GLSP_SERVER_PORT_COMMAND`
1327
+ : ` workspace,
1328
+ port: portFrom('glsp-server-port', ${upper}_GLSP_SERVER_PORT_ENV),
1329
+ logger: shared.Logger`
1330
+ }
1072
1331
  });
1073
- void glspServer;
1074
- `
1332
+ ${lsp ? 'void glspServer;\n' : ''}`
1075
1333
  : '';
1076
1334
 
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
1335
+ const lspImports = `// The framework's entry point, NOT Langium's \`@hydranium/langium/lsp\` one. It is
1095
1336
  // signature-compatible and delegates straight through; what it adds first is
1096
1337
  // \`assertLspHeadComposed\`, which fails the start if the LSP head's SHARED module
1097
1338
  // was never composed. Reaching for Langium's is the natural mistake and it is
1098
1339
  // silent: the server boots, links and completes, while echo suppression, the
1099
1340
  // didChangeContent debounce and the last-client-close rebuild are all inert.
1100
- import { startLanguageServer } from '@hydranium/core/lsp';
1341
+ import { startLanguageServer, withHydraniumLspFeatures } from '@hydranium/core/lsp';
1101
1342
  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);
1343
+ `;
1344
+
1345
+ const lspStart = `
1346
+ const connection = createConnection(withHydraniumLspFeatures(ProposedFeatures.all));
1105
1347
  const { shared } = create__NAME__Services({ connection, ...NodeFileSystem });
1106
1348
  startLanguageServer(shared);
1107
- ${dataBlock}${glspBlock}`;
1108
- return project(text, composition);
1109
- }
1349
+ `;
1110
1350
 
1111
- /**
1112
- * The second executable entry: the data head alone, on stdio.
1113
- *
1114
- * 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.
1122
- *
1123
- * A separate process rather than a flag on `main.ts`: only one protocol can own
1124
- * stdio, so the two entries are mutually exclusive by construction.
1125
- */
1126
- function dataServerMainFile(composition: InitComposition): string {
1127
- const columns = columnsFor(composition);
1128
- const roots = [...composition.grammars.map(grammar => grammar.entryRule)].sort();
1129
- const plural = roots.length > 1 ? 's' : '';
1351
+ // No LSP client names the workspace or asks for the ports here, so the
1352
+ // command line does, and the ports go to stdout once every head listens.
1353
+ const servers = [...(data ? ['dataServer'] : []), ...(glsp ? ['glspServer'] : [])];
1354
+ const socketStart = `
1355
+ const { values, positionals } = parseArgs({
1356
+ options: { ${portFlags.map(flag => `'${flag.slice(2)}': { type: 'string' }`).join(', ')} },
1357
+ allowPositionals: true
1358
+ });
1359
+ // The workspace root: the first argument, else the process cwd.
1360
+ const workspace = positionals[0] ?? process.cwd();
1361
+
1362
+ /** A head's port: its flag, else its environment variable, else 0 for any free port. */
1363
+ function portFrom(flag: keyof typeof values, variable: string): number {
1364
+ const text = values[flag] ?? process.env[variable] ?? '0';
1365
+ const port = Number(text);
1366
+ // Decimal digits only: \`Number\` also reads '' as 0 and takes '1e3' or '0x10'.
1367
+ if (!/^\\d+$/.test(text) || port > 65_535) {
1368
+ throw new Error(\`--\${flag} or \${variable} is '\${text}', not a port\`);
1369
+ }
1370
+ return port;
1371
+ }
1372
+
1373
+ const { shared } = create__NAME__Services({ ...NodeFileSystem });
1374
+ `;
1375
+ const portsLine = `
1376
+ // One JSON line on stdout once every head listens, for the process that started
1377
+ // this one to read the ports from: the one line that starts with \`{\`. Each
1378
+ // head brings the workspace up before it listens; a head that fails to start
1379
+ // has logged why and ends the process, which would otherwise serve without it.
1380
+ ${servers.length === 1 ? `${servers[0]}.started` : `Promise.all([${servers.map(server => `${server}.started`).join(', ')}])`}.then(
1381
+ () => process.stdout.write(\`\${JSON.stringify({ ${servers.map(server => `${server}: ${server}.port`).join(', ')} })}\\n\`),
1382
+ () => process.exit(1)
1383
+ );
1384
+ `;
1385
+
1386
+ const invocation = lsp
1387
+ ? `// Invocation: \`node lib/main.js --stdio\`, or the package's \`__PROJECT_ID__\` bin
1388
+ // script.`
1389
+ : `// Invocation: \`node lib/main.js [<workspace-path>] ${portFlags.map(flag => `[${flag} <port>]`).join(' ')}\`,
1390
+ // or the package's \`__PROJECT_ID__\` bin script. Each port falls back to its
1391
+ // environment variable, then to any free port.`;
1392
+ const dataNote = !data
1393
+ ? ''
1394
+ : lsp
1395
+ ? `
1396
+ //
1397
+ // NOT the entry the data-server subcommands of \`hydranium-cli\` speak to: stdio
1398
+ // here carries LSP, and the data head is a socket whose port is published over
1399
+ // the LSP connection. Those subcommands spawn \`data-server-main.js\`.`
1400
+ : `
1401
+ //
1402
+ // NOT the entry the data-server subcommands of \`hydranium-cli\` speak to: they
1403
+ // drive the data protocol over a child's stdio, and the data head here is a
1404
+ // socket. Those subcommands spawn \`data-server-main.js\`.`;
1405
+
1406
+ const text = `${SHEBANG}// Standalone entry point: starts ${headSummary} in the same
1407
+ // process, so every head shares one model store.
1408
+ ${invocation}${dataNote}
1409
+ //
1410
+ // Everything here runs at module scope, so this file is an executable rather
1411
+ // than a library entry — import \`./index.js\` instead to compose the language.
1412
+
1413
+ ${reflectImport}${glspImports}${importList(coreNodeSymbols, '@hydranium/core/node', columns)}
1414
+ ${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';
1415
+ ${portImports === '' ? '' : '\n' + portImports}${lsp ? lspStart : socketStart}${dataBlock}${glspBlock}${lsp ? '' : portsLine}`;
1416
+ return project(text, composition);
1417
+ }
1418
+
1419
+ /**
1420
+ * The second executable entry: the data head alone, on stdio.
1421
+ *
1422
+ * Emitted with the `data` head because it is the ONLY command line that reaches
1423
+ * that head from outside the editor. `main.ts` serves the data head on a
1424
+ * socket, so a client driving the data protocol over a spawned child's
1425
+ * stdin/stdout cannot reach it — which is every data-server subcommand of
1426
+ * `hydranium-cli`. Without this file a scaffolded project has no `--server`
1427
+ * value, and the closest guess, `main.ts`, fails as an unrecognised method or
1428
+ * an unknown flag rather than as a missing head.
1429
+ *
1430
+ * A separate process rather than a flag on `main.ts`: only one protocol can own
1431
+ * stdio, so the two entries are mutually exclusive by construction.
1432
+ */
1433
+ function dataServerMainFile(composition: InitComposition): string {
1434
+ const columns = columnsFor(composition);
1435
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
1436
+ const plural = roots.length > 1 ? 's' : '';
1130
1437
 
1131
1438
  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.
1439
+ // the process. This is the transport \`hydranium-cli\` speaks — its data-server
1440
+ // subcommands spawn a server command and drive JSON-RPC over its stdin/stdout —
1441
+ // so it is what makes those subcommands usable against this language.
1136
1442
  //
1137
1443
  // Invocation: \`node lib/data-server-main.js [<workspace-path>]\`, or the
1138
1444
  // package's \`__PROJECT_ID__-data-server\` bin script. The workspace path defaults to
1139
1445
  // the process cwd, which is what the CLI's \`--cwd\` sets on the child.
1140
1446
  //
1141
- // Contrast with \`main.ts\`, the editor entry: there the LSP head owns stdio and
1447
+ ${
1448
+ composition.heads.includes('lsp')
1449
+ ? `// Contrast with \`main.ts\`, the editor entry: there the LSP head owns stdio and
1142
1450
  // the data head is a socket published over the LSP connection. Here there is no
1143
1451
  // LSP connection at all, so the workspace initialization an
1144
1452
  // \`initialize\`/\`initialized\` pair would otherwise drive has to happen here —
1145
1453
  // which is why this entry uses \`startStdioServer\` rather than wiring a
1146
- // connection directly.
1454
+ // connection directly.`
1455
+ : `// Contrast with \`main.ts\`, where the data head is a socket whose port it
1456
+ // prints. Here it owns stdio, and as there, no LSP connection drives the
1457
+ // workspace initialization, so \`startStdioServer\` brings the workspace up
1458
+ // before it listens.`
1459
+ }
1147
1460
  //
1148
1461
  // Everything here runs at module scope, so this file is an executable rather
1149
1462
  // than a library entry — import \`./index.js\` instead to compose the language.
@@ -1151,7 +1464,7 @@ function dataServerMainFile(composition: InitComposition): string {
1151
1464
  ${importList(['NodeFileSystem', 'startStdioServer'], '@hydranium/core/node', columns)}
1152
1465
  import { DataServer } from '@hydranium/data-server';
1153
1466
  // 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)}
1467
+ ${importList(roots, memberPackageName(composition, 'protocol'), columns, true)}
1155
1468
  import { create__NAME__Services } from './language-server/__PROJECT_ID__-module.js';
1156
1469
 
1157
1470
  const { shared } = create__NAME__Services({ ...NodeFileSystem });
@@ -1200,7 +1513,7 @@ function servicesTest(composition: InitComposition): string {
1200
1513
  // is missing from the composition.
1201
1514
 
1202
1515
  import { describe, expect, it } from 'vitest';
1203
- import { createServices } from '../src/services.js';
1516
+ import { createServices } from '../src/node/services.js';
1204
1517
 
1205
1518
  describe('__NAME__ services', () => {
1206
1519
  it('composes the DI tree and registers ${title}', () => {
@@ -1242,13 +1555,9 @@ const SERIALIZATION_SUITE = `describe('__GRAMMAR__ serialization', () => {
1242
1555
 
1243
1556
  it('emits the same text from a transfer model, whose references are plain strings', async () => {
1244
1557
  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
- };
1558
+ const model = transferNode(Transfer__ENTRY_RULE__, {
1559
+ nodes: __TRANSFER_NODES__
1560
+ });
1252
1561
 
1253
1562
  expect(await __GRAMMAR__.serializer.Serializer.serializeTransfer(model)).toBe(source);
1254
1563
  });
@@ -1267,11 +1576,24 @@ const SERIALIZATION_SUITE = `describe('__GRAMMAR__ serialization', () => {
1267
1576
  function serializationTest(composition: InitComposition): string {
1268
1577
  const columns = columnsFor(composition);
1269
1578
  const astTypes = composition.grammars.map(grammar => grammar.entryRule);
1270
- const transferTypes = composition.grammars.map(grammar => `${grammar.entryRule} as Transfer${grammar.entryRule}`);
1579
+ const transferConstants = composition.grammars.flatMap(grammar => [
1580
+ `${grammar.entryRule} as Transfer${grammar.entryRule}`,
1581
+ grammar.nodeRule
1582
+ ]);
1583
+ const suite = (grammar: InitGrammarNames): string => {
1584
+ const nodes = [
1585
+ `transferNode(${grammar.nodeRule}, { name: 'first', target: 'second' })`,
1586
+ `transferNode(${grammar.nodeRule}, { name: 'second' })`
1587
+ ];
1588
+ const single = `[${nodes.join(', ')}]`;
1589
+ const literal =
1590
+ ` nodes: ${single}`.length <= columns ? single : `[\n${nodes.map(node => ` ${node}`).join(',\n')}\n ]`;
1591
+ return render(SERIALIZATION_SUITE, composition, grammar).replace('__TRANSFER_NODES__', literal);
1592
+ };
1271
1593
  const text = `// Round-trips each grammar through its serializer: parse the source, serialize
1272
1594
  // 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.
1595
+ // is the assertion that keeps a client session's \`update\` / \`save\` writing
1596
+ // files the language server can read back.
1275
1597
  //
1276
1598
  // The transfer case is the one that catches the mistake worth catching.
1277
1599
  // \`ModelService.modelToText\` short-circuits only a RAW STRING, so a typed model
@@ -1281,10 +1603,11 @@ function serializationTest(composition: InitComposition): string {
1281
1603
  import { parseHelper } from '@hydranium/core/testing';
1282
1604
  import { describe, expect, it } from 'vitest';
1283
1605
  ${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';
1606
+ ${importList(transferConstants, memberPackageName(composition, 'protocol'), columns)}
1607
+ import { createServices } from '../src/node/services.js';
1608
+ import { transferNode } from './generated-hydranium/transfer-builder.js';
1286
1609
 
1287
- ${composition.grammars.map(grammar => render(SERIALIZATION_SUITE, composition, grammar)).join('\n\n')}
1610
+ ${composition.grammars.map(suite).join('\n\n')}
1288
1611
  `;
1289
1612
  return text;
1290
1613
  }
@@ -1364,14 +1687,9 @@ const LINKING_SUITE = `describe('__GRAMMAR__ linking', () => {
1364
1687
  });`;
1365
1688
 
1366
1689
  /**
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.
1690
+ * The validation tier: the linker's diagnostic for a dangling reference, the
1691
+ * tier a new adopter breaks third, and the scaffold's one check, a warning on
1692
+ * a repeated name.
1375
1693
  */
1376
1694
  const VALIDATING_SUITE = `describe('__GRAMMAR__ validation', () => {
1377
1695
  it('reports nothing for a well-formed document', async () => {
@@ -1398,6 +1716,21 @@ const VALIDATING_SUITE = `describe('__GRAMMAR__ validation', () => {
1398
1716
  expect(diagnostics[0].severity).toBe(DiagnosticSeverity.Error);
1399
1717
  expect(diagnostics[0].message).toContain('absent');
1400
1718
  });
1719
+
1720
+ it('warns on each node named like one before it', async () => {
1721
+ const { shared, __GRAMMAR__ } = createServices();
1722
+
1723
+ const document = await parseHelper<__ENTRY_RULE__>(__GRAMMAR__)('node first\\nnode second\\nnode first', {
1724
+ documentUri: 'file:///duplicate.__EXTENSION__'
1725
+ });
1726
+ await shared.workspace.DocumentBuilder.build([document], { validation: true });
1727
+
1728
+ const diagnostics = document.diagnostics ?? [];
1729
+ expect(diagnostics).toHaveLength(1);
1730
+ expect(diagnostics[0].severity).toBe(DiagnosticSeverity.Warning);
1731
+ expect(diagnostics[0].message).toBe("A node named 'first' is already declared.");
1732
+ expect(diagnostics[0].range.start.line).toBe(2);
1733
+ });
1401
1734
  });`;
1402
1735
 
1403
1736
  /** Assemble one grammar-derived test file: a fixed preamble plus one suite per grammar. */
@@ -1409,7 +1742,7 @@ function grammarTest(composition: InitComposition, header: string, imports: read
1409
1742
  import { parseHelper } from '@hydranium/core/testing';
1410
1743
  import { describe, expect, it } from 'vitest';
1411
1744
  ${imports.join('\n')}${imports.length ? '\n' : ''}${importList(astTypes, '../src/language-server/ast.js', columns, true)}
1412
- import { createServices } from '../src/services.js';
1745
+ import { createServices } from '../src/node/services.js';
1413
1746
 
1414
1747
  ${composition.grammars.map(grammar => render(suite, composition, grammar)).join('\n\n')}
1415
1748
  `;
@@ -1430,16 +1763,16 @@ const LINKING_HEADER = `// Tier two: does my cross-reference resolve.
1430
1763
 
1431
1764
  const VALIDATING_HEADER = `// Tier three: does a broken model get reported.
1432
1765
  //
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.`;
1766
+ // A dangling reference is the FRAMEWORK's own linker diagnostic; a repeated
1767
+ // name is reported by the scaffold's own validation check. Bind a further
1768
+ // check in your language module and assert it here alongside these.`;
1437
1769
 
1438
1770
  /** The README, assembled from lines to avoid escaping the Markdown code fences. */
1439
1771
  function readme(composition: InitComposition): string {
1440
1772
  const multi = composition.grammars.length > 1;
1441
1773
  const data = composition.heads.includes('data');
1442
1774
  const primaryExtension = composition.grammars[0].extensions[0];
1775
+ const diagramCount = composition.grammars.filter(grammar => grammar.diagram).length;
1443
1776
  const grammarBullets = composition.grammars.map(
1444
1777
  grammar => `- \`src/grammar/${grammar.grammarId}.langium\` — the \`${grammar.grammar}\` grammar (.${grammar.extensions.join(', .')})`
1445
1778
  );
@@ -1450,24 +1783,11 @@ function readme(composition: InitComposition): string {
1450
1783
  '',
1451
1784
  '## Getting started',
1452
1785
  '',
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
- : []),
1467
1786
  '```bash',
1468
1787
  'npm install',
1469
1788
  'npm run langium:generate # generate the AST from the grammar',
1470
1789
  'npm run build # generate + compile to lib/',
1790
+ 'npm run watch # regenerate and recompile on every grammar or source change',
1471
1791
  'npm test # typecheck the tests, then run them',
1472
1792
  '```',
1473
1793
  '',
@@ -1478,25 +1798,26 @@ function readme(composition: InitComposition): string {
1478
1798
  // nowhere else.
1479
1799
  '```bash',
1480
1800
  '# Grammar / AST reflection',
1481
- 'npx hydranium-cli reflect --services ./lib/services.js',
1801
+ 'npx hydranium-cli reflect',
1482
1802
  '',
1483
1803
  '# Grammar-convention lint (CI gate)',
1484
- 'npx hydranium-cli lint-grammar --services ./lib/services.js',
1804
+ 'npx hydranium-cli lint-grammar',
1485
1805
  '',
1486
1806
  '# Validate a workspace of model files (non-zero exit on errors)',
1487
- 'npx hydranium-cli validate --services ./lib/services.js <workspace-dir>',
1807
+ 'npx hydranium-cli validate ../workspace',
1488
1808
  ...(data
1489
1809
  ? [
1490
1810
  '',
1491
1811
  '# Data-head operations. `--server` is a command line the CLI spawns and then',
1492
1812
  "# 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".',
1813
+ ...(composition.heads.includes('lsp')
1814
+ ? ['# `data-server-main.js` — `main.js` gives stdio to LSP and answers these', '# methods with "Unhandled method".']
1815
+ : ['# `data-server-main.js` — `main.js` serves the data head on a socket.']),
1495
1816
  '#',
1496
1817
  '# The workspace goes to the ENTRY, not to `--cwd`: `--cwd` re-roots the child,',
1497
1818
  '# 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>`
1819
+ 'npx hydranium-cli projects --server "node ./lib/data-server-main.js ../workspace"',
1820
+ `npx hydranium-cli query --server "node ./lib/data-server-main.js ../workspace" --uri <file:// URI of ../workspace/nodes.${primaryExtension}>`
1500
1821
  ]
1501
1822
  : []),
1502
1823
  '```',
@@ -1506,12 +1827,13 @@ function readme(composition: InitComposition): string {
1506
1827
  ...grammarBullets,
1507
1828
  ...(multi ? ['- `src/grammar/common.langium` — shared terminals, imported by each grammar (not a language)'] : []),
1508
1829
  '- `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',
1830
+ ...composition.grammars.flatMap(grammar => [
1831
+ `- \`src/language-server/${grammar.grammarId}-serializer.ts\` — emits \`${grammar.grammar}\` back to text (the framework defaults this to a throw)`,
1832
+ `- \`src/language-server/${grammar.grammarId}-semantic-tokens.ts\` — colours declarations and references; the browser enables keywords and comments too`,
1833
+ `- \`src/language-server/${grammar.grammarId}-validation.ts\` — the \`${grammar.grammar}\` checks: a warning on a repeated name`
1834
+ ]),
1835
+ "- `src/node/services.ts` — zero-arg `createServices()` for the headless CLI, the package's `./node` entry",
1836
+ `- \`src/index.ts\` — the package root, loadable in a browser worker: DI factory + generated AST${diagramCount === 0 ? '' : diagramCount === 1 ? ' + diagram module' : ' + diagram modules'}`,
1515
1837
  `- \`src/main.ts\` — starts ${composition.heads.join(' + ')}, the \`__PROJECT_ID__\` bin entry`,
1516
1838
  ...(data
1517
1839
  ? [
@@ -1523,8 +1845,9 @@ function readme(composition: InitComposition): string {
1523
1845
  .filter(grammar => grammar.diagram)
1524
1846
  .map(
1525
1847
  grammar =>
1526
- `- \`src/glsp/${grammar.grammarId}/\` — the \`${grammar.grammar}\` diagram: type ids, state, storage, submission handler, GModel factory, configuration, create-node handler, DI module`
1848
+ `- \`src/glsp/${grammar.grammarId}/\` — the \`${grammar.grammar}\` diagram: state, storage, submission handler, GModel factory, configuration, create-node handler, DI module`
1527
1849
  ),
1850
+ `- \`../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
1851
  '- `test/services.test.ts` — the DI tree composes; grows as your language does',
1529
1852
  '- `test/parsing.test.ts` / `linking.test.ts` / `validating.test.ts` — the three tiers a new language breaks first',
1530
1853
  '- `test/serialization.test.ts` — each grammar round-trips through its serializer',
@@ -1577,6 +1900,21 @@ function readme(composition: InitComposition): string {
1577
1900
  'atomic set and depends on a single physical copy, so a floating range can',
1578
1901
  'silently resolve a second one.',
1579
1902
  '',
1903
+ '`vscode-languageserver` is pinned to `10.1.2`, and',
1904
+ '`vscode-languageserver-protocol` and `vscode-jsonrpc` to the `3.18.4` and',
1905
+ '`9.0.3` it pins, so Langium, the LSP connection and the framework share one',
1906
+ 'copy of each. With two, an error a Langium handler returns, such as a request',
1907
+ 'for a document the server does not have, reaches the client as a result, and a',
1908
+ 'framework error your own LSP handler throws loses its code.',
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,109 @@ 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__-semantic-tokens.ts', composition, grammar),
2199
+ grammarTemplate('server/test/__GRAMMAR_ID__-semantic-tokens.test.ts', composition, grammar),
2200
+ grammarTemplate('server/src/language-server/__GRAMMAR_ID__-validation.ts', composition, grammar)
2201
+ ]),
2202
+ { path: 'server/src/index.ts', content: indexFile(composition) },
2203
+ projectTemplate('server/src/node/services.ts', composition),
2204
+ { path: 'server/src/main.ts', content: mainFile(composition) },
2205
+ ...(composition.heads.includes('data') ? [{ path: 'server/src/data-server-main.ts', content: dataServerMainFile(composition) }] : []),
2053
2206
  ...diagramFiles,
2054
- { path: 'test/services.test.ts', content: servicesTest(composition) },
2055
- { path: 'test/parsing.test.ts', content: grammarTest(composition, PARSING_HEADER, [], PARSING_SUITE) },
2207
+ { path: 'server/test/services.test.ts', content: servicesTest(composition) },
2208
+ { path: 'server/test/parsing.test.ts', content: grammarTest(composition, PARSING_HEADER, [], PARSING_SUITE) },
2056
2209
  {
2057
- path: 'test/linking.test.ts',
2210
+ path: 'server/test/linking.test.ts',
2058
2211
  content: grammarTest(composition, LINKING_HEADER, ["import { AstUtils } from '@hydranium/langium';"], LINKING_SUITE)
2059
2212
  },
2060
2213
  {
2061
- path: 'test/validating.test.ts',
2214
+ path: 'server/test/validating.test.ts',
2062
2215
  content: grammarTest(
2063
2216
  composition,
2064
2217
  VALIDATING_HEADER,
@@ -2066,6 +2219,2368 @@ export function buildInitTemplates(composition: InitComposition): InitFile[] {
2066
2219
  VALIDATING_SUITE
2067
2220
  )
2068
2221
  },
2069
- { path: 'test/serialization.test.ts', content: serializationTest(composition) }
2222
+ { path: 'server/test/serialization.test.ts', content: serializationTest(composition) }
2223
+ ];
2224
+ }
2225
+
2226
+ /**
2227
+ * The protocol member's `package.json`.
2228
+ *
2229
+ * Its `build` runs the server's `generate` first, because the server writes
2230
+ * this package's `generated-hydranium/` modules from the grammar: a runner that
2231
+ * builds in dependency order reaches this package before the server, and would
2232
+ * otherwise compile modules that do not exist yet. A full build therefore
2233
+ * generates twice; the second pass rewrites nothing.
2234
+ */
2235
+ function protocolPackageJson(composition: InitComposition): string {
2236
+ const member = forMember(composition, 'protocol');
2237
+ const dependencies: Record<string, string> = {};
2238
+ for (const head of composition.heads) {
2239
+ Object.assign(dependencies, PROTOCOL_THIRD_PARTY_DEPENDENCIES[head]);
2240
+ }
2241
+ const dependencyLines =
2242
+ Object.keys(dependencies).length === 0 ? '' : ` "dependencies": {\n${sortedBlock(dependencies, ' ')}\n },\n`;
2243
+ return `{
2244
+ "name": "${memberPackageName(composition, 'protocol')}",
2245
+ "version": "0.0.0",
2246
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "What the ${composition.name} language server and its clients share: language ids, wire types and diagram ids.",
2247
+ "license": "UNLICENSED",
2248
+ "author": "",
2249
+ "files": [
2250
+ "lib",
2251
+ "src"
2252
+ ],
2253
+ "type": "module",
2254
+ "main": "lib/index.js",
2255
+ "types": "lib/index.d.ts",
2256
+ "scripts": {
2257
+ "build": "npm --prefix ../server run generate && tsc -b",
2258
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
2259
+ ${lintScript(member, 'src')} "watch": "tsc -b --watch"
2260
+ },
2261
+ ${dependencyLines} "devDependencies": {
2262
+ "rimraf": "^5.0.0",
2263
+ "typescript": "^7.0.2"
2264
+ },
2265
+ "engines": {
2266
+ "node": ">=22.13"
2267
+ }
2268
+ }
2269
+ `;
2270
+ }
2271
+
2272
+ /** The protocol member's root entry, one re-export per module. */
2273
+ function protocolIndexFile(composition: InitComposition): string {
2274
+ const modules = [
2275
+ './generated-hydranium/languages.js',
2276
+ './generated-hydranium/transfer-model.js',
2277
+ ...(headPortConstants(composition).length ? ['./head-ports.js'] : []),
2278
+ ...composition.grammars.filter(grammar => grammar.diagram).map(grammar => `./${grammar.grammarId}-diagram-types.js`)
2279
+ ];
2280
+ const text = `// What the __NAME__ server and its clients both import. A client depends on
2281
+ // this package instead of the server, so it never installs Langium to reach a
2282
+ // constant or a wire type.
2283
+ //
2284
+ // The server's \`generate\` writes \`generated-hydranium/\` from the grammar;
2285
+ // commit those modules with the grammar change that produced them. An interface
2286
+ // narrowed here hides the generated constant of the same name; re-export that
2287
+ // constant beside it, and declare the type map under its own name with the
2288
+ // narrowed entry, or the builder and the GLSP state keep the generated one.
2289
+
2290
+ ${modules.map(module => `export * from '${module}';`).join('\n')}
2291
+ `;
2292
+ return project(text, composition);
2293
+ }
2294
+
2295
+ /** The protocol member's README. */
2296
+ function protocolReadme(composition: InitComposition): string {
2297
+ const lines = [
2298
+ `# ${memberPackageName(composition, 'protocol')}`,
2299
+ '',
2300
+ 'What the __NAME__ language server and its clients both import, so a client',
2301
+ 'never depends on the server or installs Langium.',
2302
+ '',
2303
+ '- `src/generated-hydranium/languages.ts` — each language id and its file extensions',
2304
+ '- `src/generated-hydranium/transfer-model.ts` — the wire types of the model, references as plain strings',
2305
+ ...(headPortConstants(composition).length === 0
2306
+ ? []
2307
+ : composition.heads.includes('lsp')
2308
+ ? ['- `src/head-ports.ts` — the LSP requests a host sends to find the socket heads']
2309
+ : ["- `src/head-ports.ts` — the environment variables naming the socket heads' ports"]),
2310
+ ...composition.grammars
2311
+ .filter(grammar => grammar.diagram)
2312
+ .map(grammar => `- \`src/${grammar.grammarId}-diagram-types.ts\` — the \`${grammar.grammar}\` diagram's type ids`),
2313
+ '',
2314
+ "The server's `npm run generate` writes `src/generated-hydranium/` from the",
2315
+ 'grammar, and `npm run build` here runs it first. Commit the generated',
2316
+ 'modules with the grammar change that produced them.',
2317
+ ''
2318
+ ];
2319
+ return project(lines.join('\n'), composition);
2320
+ }
2321
+
2322
+ /** The protocol member: everything the server and its clients both import. */
2323
+ function protocolFiles(composition: InitComposition): InitFile[] {
2324
+ return [
2325
+ { path: 'protocol/package.json', content: protocolPackageJson(composition) },
2326
+ { path: 'protocol/tsconfig.json', content: tsconfigJson(forMember(composition, 'protocol'), PROTOCOL_COMPILER_OPTIONS, '["src"]') },
2327
+ ignoreFile('protocol'),
2328
+ { path: 'protocol/README.md', content: protocolReadme(composition) },
2329
+ { path: 'protocol/src/index.ts', content: protocolIndexFile(composition) },
2330
+ ...(headPortConstants(composition).length ? [{ path: 'protocol/src/head-ports.ts', content: headPortsFile(composition) }] : []),
2331
+ ...composition.grammars
2332
+ .filter(grammar => grammar.diagram)
2333
+ .map(grammar => grammarTemplate('protocol/src/__GRAMMAR_ID__-diagram-types.ts', composition, grammar))
2334
+ ];
2335
+ }
2336
+
2337
+ /**
2338
+ * The starter model files every host and the CLI open, two per language: one
2339
+ * declaring nodes, one referencing a node in the other file.
2340
+ *
2341
+ * Named by extension alone, since `init` refuses two grammars sharing one.
2342
+ */
2343
+ function workspaceFiles(composition: InitComposition): InitFile[] {
2344
+ return composition.grammars.flatMap(grammar => [
2345
+ grammarTemplate('workspace/nodes.__EXTENSION__', composition, grammar),
2346
+ grammarTemplate('workspace/references.__EXTENSION__', composition, grammar)
2347
+ ]);
2348
+ }
2349
+
2350
+ /** The client member's compiler options: the protocol's, with the DOM its diagram renders into. */
2351
+ const CLIENT_COMPILER_OPTIONS: ReadonlyArray<readonly [string, JsonValue]> = [
2352
+ ['target', 'ES2022'],
2353
+ ['lib', ['ES2022', 'DOM']],
2354
+ ['module', 'NodeNext'],
2355
+ ['moduleResolution', 'NodeNext'],
2356
+ ['rootDir', 'src'],
2357
+ ['outDir', 'lib'],
2358
+ ['strict', true],
2359
+ ['skipLibCheck', true],
2360
+ ['declaration', true],
2361
+ // For inversify's `@injectable`, which a GLSP view needs to be bound.
2362
+ ['experimentalDecorators', true],
2363
+ ['types', []],
2364
+ // A base that sets it fails every `import` in this CommonJS member.
2365
+ ['verbatimModuleSyntax', false]
2366
+ ];
2367
+
2368
+ /**
2369
+ * The client member's `package.json`.
2370
+ *
2371
+ * CommonJS, unlike its siblings, as GLSP's client is: inversify ships an ES
2372
+ * build and a CommonJS one, so an ES module here would load the first while
2373
+ * GLSP's client loads the second, giving a page two containers' worth of
2374
+ * classes. Node from 22.12 and `tsc` under `nodenext` both let it require the
2375
+ * ES protocol member.
2376
+ */
2377
+ function clientPackageJson(composition: InitComposition): string {
2378
+ const dependencies: Record<string, string> = {
2379
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
2380
+ ...CLIENT_THIRD_PARTY_DEPENDENCIES
2381
+ };
2382
+ for (const framework of CLIENT_FRAMEWORK_DEPENDENCIES) {
2383
+ dependencies[framework] = frameworkPin(composition);
2384
+ }
2385
+ return `{
2386
+ "name": "${memberPackageName(composition, 'client')}",
2387
+ "version": "0.0.0",
2388
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "The host-neutral client side of the ${composition.name} language: what every host of it mounts.",
2389
+ "license": "UNLICENSED",
2390
+ "author": "",
2391
+ "files": [
2392
+ "lib",
2393
+ "src"
2394
+ ],
2395
+ "main": "lib/index.js",
2396
+ "types": "lib/index.d.ts",
2397
+ "scripts": {
2398
+ "build": "tsc -b",
2399
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
2400
+ ${lintScript(forMember(composition, 'client'), 'src')} "watch": "tsc --watch"
2401
+ },
2402
+ "dependencies": {
2403
+ ${sortedBlock(dependencies, ' ')}
2404
+ },
2405
+ "devDependencies": {
2406
+ "rimraf": "^5.0.0",
2407
+ "typescript": "^7.0.2"
2408
+ },
2409
+ "engines": {
2410
+ "node": ">=22.13"
2411
+ }
2412
+ }
2413
+ `;
2414
+ }
2415
+
2416
+ /** The client member's README. */
2417
+ function clientReadme(composition: InitComposition): string {
2418
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
2419
+ const lines = [
2420
+ `# ${memberPackageName(composition, 'client')}`,
2421
+ '',
2422
+ 'The host-neutral client side of the __NAME__ language: what every host of it',
2423
+ 'mounts, whatever that host is. It reads the element ids from the protocol',
2424
+ 'package and never depends on the server.',
2425
+ '',
2426
+ ...diagrams.map(
2427
+ grammar =>
2428
+ `- \`src/${grammar.grammarId}-diagram-module.ts\` — the \`${grammar.grammar}\` diagram: a registration per element type, its container module, and \`initialize${grammar.grammar}DiagramContainer\``
2429
+ ),
2430
+ '- `src/index.ts` — the package root, re-exporting each module',
2431
+ '',
2432
+ 'A host builds a diagram container with the initializer, passing its own',
2433
+ 'modules: they go first and the diagram definition last, since GLSP gives an',
2434
+ 'element type to whichever module registered it last.',
2435
+ ''
2436
+ ];
2437
+ return project(lines.join('\n'), composition);
2438
+ }
2439
+
2440
+ /** The client member's root entry, one re-export per diagram module. */
2441
+ function clientIndexFile(composition: InitComposition): string {
2442
+ const modules = composition.grammars.filter(grammar => grammar.diagram).map(grammar => `./${grammar.grammarId}-diagram-module.js`);
2443
+ return `// What every host of the ${composition.name} language mounts.
2444
+
2445
+ ${modules.map(module => `export * from '${module}';`).join('\n')}
2446
+ `;
2447
+ }
2448
+
2449
+ /**
2450
+ * The client member: the host-neutral client side of the language, emitted
2451
+ * when there is a diagram to define. Each host mounts it rather than defining
2452
+ * the diagram again.
2453
+ */
2454
+ function clientFiles(composition: InitComposition): InitFile[] {
2455
+ return [
2456
+ { path: 'client/package.json', content: clientPackageJson(composition) },
2457
+ {
2458
+ path: 'client/tsconfig.json',
2459
+ content: tsconfigJson(forMember(composition, 'client'), CLIENT_COMPILER_OPTIONS, '["src"]', '[{ "path": "../protocol" }]')
2460
+ },
2461
+ ignoreFile('client'),
2462
+ { path: 'client/README.md', content: clientReadme(composition) },
2463
+ { path: 'client/src/index.ts', content: clientIndexFile(composition) },
2464
+ ...composition.grammars
2465
+ .filter(grammar => grammar.diagram)
2466
+ .map(grammar => grammarTemplate('client/src/__GRAMMAR_ID__-diagram-module.ts', composition, grammar))
2467
+ ];
2468
+ }
2469
+
2470
+ /**
2471
+ * The browser host's `package.json`. Always private: it is an application,
2472
+ * which nothing installs as a dependency.
2473
+ */
2474
+ function hostBrowserPackageJson(composition: InitComposition): string {
2475
+ const dependencies: Record<string, string> = {
2476
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
2477
+ [memberPackageName(composition, 'server')]: MEMBER_PIN,
2478
+ ...(composition.heads.includes('glsp') ? { [memberPackageName(composition, 'client')]: MEMBER_PIN } : {}),
2479
+ // A page with no editor saves through the diagram's own action dispatcher.
2480
+ ...(composition.heads.includes('lsp') ? {} : { '@eclipse-glsp/client': CLIENT_THIRD_PARTY_DEPENDENCIES['@eclipse-glsp/client'] })
2481
+ };
2482
+ for (const head of ['base', ...composition.heads] as const) {
2483
+ Object.assign(dependencies, HOST_BROWSER_THIRD_PARTY_DEPENDENCIES[head]);
2484
+ for (const framework of HOST_BROWSER_FRAMEWORK_DEPENDENCIES[head]) {
2485
+ dependencies[framework] = frameworkPin(composition);
2486
+ }
2487
+ }
2488
+ return `{
2489
+ "name": "${memberPackageName(composition, 'host-browser')}",
2490
+ "version": "0.0.0",
2491
+ "private": true,
2492
+ "description": "${composition.name} in a browser page, with every head in a web worker and no backend.",
2493
+ "license": "UNLICENSED",
2494
+ "author": "",
2495
+ "type": "module",
2496
+ "scripts": {
2497
+ "build": "npm run typecheck && node esbuild.mjs",
2498
+ "clean": "rimraf out test-results playwright-report",
2499
+ ${lintScript(forMember(composition, 'host-browser'), 'src test')} "start": "node esbuild.mjs --serve",
2500
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
2501
+ "test:e2e:install": "playwright install chromium",
2502
+ "typecheck": "tsc --noEmit -p tsconfig.worker.json && tsc --noEmit -p tsconfig.page.json && tsc --noEmit -p tsconfig.e2e.json"
2503
+ },
2504
+ "dependencies": {
2505
+ ${sortedBlock(dependencies, ' ')}
2506
+ },
2507
+ "devDependencies": {
2508
+ ${sortedBlock(HOST_BROWSER_DEV_DEPENDENCIES, ' ')}
2509
+ },
2510
+ "engines": {
2511
+ "node": ">=22.13"
2512
+ }
2513
+ }
2514
+ `;
2515
+ }
2516
+
2517
+ /** The workspace URI of a grammar's first starter file, as a template literal over `WORKSPACE_ROOT_URI`. */
2518
+ function starterUri(grammar: InitGrammarNames): string {
2519
+ return `\`\${WORKSPACE_ROOT_URI}/nodes.${grammar.extensions[0]}\``;
2520
+ }
2521
+
2522
+ /**
2523
+ * The worker hosting the heads: every head over the one store, with the
2524
+ * workspace seeded from `../workspace` and saved files kept in IndexedDB.
2525
+ */
2526
+ function hostWorkerFile(composition: InitComposition): string {
2527
+ const columns = columnsFor(composition);
2528
+ const lsp = composition.heads.includes('lsp');
2529
+ const data = composition.heads.includes('data');
2530
+ const glsp = composition.heads.includes('glsp');
2531
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
2532
+ const roots = composition.grammars.map(grammar => grammar.entryRule).sort();
2533
+ const serverSymbols = [`create${composition.name}Services`, ...diagrams.map(grammar => `${grammar.grammar}DiagramModule`)].sort(
2534
+ (left, right) => left.localeCompare(right)
2535
+ );
2536
+
2537
+ const imports = [
2538
+ ...(glsp
2539
+ ? [
2540
+ '// First, before any class carrying a decorator loads: GLSP reads the metadata',
2541
+ '// its decorators emit as each class is defined.',
2542
+ "import 'reflect-metadata';",
2543
+ "import { ServerModule } from '@eclipse-glsp/server/browser.js';"
2544
+ ]
2545
+ : []),
2546
+ "import { persistentFileSystem } from '@hydranium/core';",
2547
+ importList(
2548
+ ['hostHeadsInWorker', 'IndexedDbFileSystemStore', ...(lsp ? ['startLanguageServerInWorker'] : [])],
2549
+ '@hydranium/core/browser',
2550
+ columns
2551
+ ),
2552
+ ...(data
2553
+ ? [
2554
+ "import { DataServer } from '@hydranium/data-server';",
2555
+ "import { startDataServerInWorker } from '@hydranium/data-server/browser';"
2556
+ ]
2557
+ : []),
2558
+ ...(glsp
2559
+ ? [
2560
+ "import { GlspClientLogger, HydraniumGlspAppModule } from '@hydranium/glsp-server';",
2561
+ "import { startGlspServerInWorker } from '@hydranium/glsp-server/browser';"
2562
+ ]
2563
+ : []),
2564
+ ...(data ? [importList(roots, memberPackageName(composition, 'protocol'), columns, true)] : []),
2565
+ importList(serverSymbols, memberPackageName(composition, 'server'), columns),
2566
+ "import { WORKSPACE_ROOT_URI } from './workspace.js';"
2567
+ ];
2568
+
2569
+ const services = `const shared = create${composition.name}Services({ ...fileSystem }).shared;`;
2570
+ const lspCall = `startLanguageServerInWorker(ports.lsp, connection => create${composition.name}Services({ connection, ...fileSystem }, { highlightKeywords: true, highlightComments: true }).shared);`;
2571
+ const startServices = !lsp
2572
+ ? services
2573
+ : ` const shared = ${lspCall}`.length <= columns
2574
+ ? `const shared = ${lspCall}`
2575
+ : `const shared = startLanguageServerInWorker(
2576
+ ports.lsp,
2577
+ connection => create${composition.name}Services({ connection, ...fileSystem }, { highlightKeywords: true, highlightComments: true }).shared
2578
+ );`;
2579
+ const dataServer = `connection => new DataServer<${roots.join(' | ')}>(connection, shared)`;
2580
+ const dataCall = `startDataServerInWorker(ports.data, shared, ${dataServer});`;
2581
+ const dataHead = data
2582
+ ? `
2583
+ // The data head serves from the ${lsp ? "LSP head's" : "services'"} store, on its own port.
2584
+ ${
2585
+ ` ${dataCall}`.length <= columns
2586
+ ? dataCall
2587
+ : `startDataServerInWorker(
2588
+ ports.data,
2589
+ shared,
2590
+ ${dataServer}
2591
+ );`
2592
+ }`
2593
+ : '';
2594
+ const glspHead = glsp
2595
+ ? `
2596
+ const glsp = startGlspServerInWorker({
2597
+ context: ports.glsp,
2598
+ createLogger: caller => new GlspClientLogger(shared, { component: caller }),
2599
+ serverModule: new ServerModule()${diagrams.map(grammar => `.configureDiagramModule(new ${grammar.grammar}DiagramModule())`).join('')},
2600
+ appModules: [new HydraniumGlspAppModule({ shared })]
2601
+ });
2602
+ // The GLSP head reports a failed start through \`started\`, which the
2603
+ // ready message waits for.
2604
+ return { shared, started: [glsp.started] };`
2605
+ : `
2606
+ return shared;`;
2607
+
2608
+ const text = `// The worker hosting the heads: every head over one store, in the browser and
2609
+ // with no backend. The page reaches each head over a \`MessagePort\` of its own.
2610
+
2611
+ ${imports.join('\n')}
2612
+
2613
+ /** The files of \`../workspace\`, read by \`esbuild.mjs\` and keyed by their path below the root. */
2614
+ declare const __WORKSPACE_SEED__: Record<string, string>;
2615
+ /** This project's directory, hashed by \`esbuild.mjs\`, so that no other project on the origin opens its store. */
2616
+ declare const __DIRECTORY_KEY__: string;
2617
+
2618
+ // A saved file is kept in IndexedDB and laid over the seed on the next load;
2619
+ // the heads start once the stored files are restored.
2620
+ const store = new IndexedDbFileSystemStore(\`__PROJECT_ID__-workspace-\${__DIRECTORY_KEY__}\`);
2621
+
2622
+ hostHeadsInWorker(
2623
+ persistentFileSystem({ store, seed: __WORKSPACE_SEED__, rootUri: WORKSPACE_ROOT_URI }),
2624
+ (ports, fileSystem) => {
2625
+ ${lsp ? '// The LSP head composes the services, as the Node entry does around stdio.\n ' : ''}${startServices}${dataHead}${glspHead}
2626
+ },
2627
+ ${
2628
+ lsp
2629
+ ? '// The ready message then carries the workspace files the page opens.'
2630
+ : '// With no LSP head the workspace comes up from this root, and the ready\n // message then carries its files.'
2631
+ }
2632
+ { rootUri: WORKSPACE_ROOT_URI }
2633
+ );
2634
+ `;
2635
+ return project(text, composition);
2636
+ }
2637
+
2638
+ /**
2639
+ * The page, and the one place deciding which head's part of it runs: each
2640
+ * part is a module of its own, and this calls the ones the heads serve.
2641
+ */
2642
+ function hostPageFile(composition: InitComposition): string {
2643
+ const lsp = composition.heads.includes('lsp');
2644
+ const data = composition.heads.includes('data');
2645
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2646
+ // A host takes lsp or glsp, and glsp marks a diagram grammar, so without lsp there is one.
2647
+ const diagramLanguage = lsp || diagram === undefined ? undefined : `${screamingSnake(diagram.grammarId)}_LANGUAGE`;
2648
+ const shownLanguage = diagramLanguage ?? 'ALL_LANGUAGES';
2649
+ const parts = [
2650
+ // Every part follows the file the page shows, so the switch comes first. With
2651
+ // no editor it lists only the diagram's files, the only ones the page shows.
2652
+ {
2653
+ module: './shown-file.js',
2654
+ imports: 'startShownFile',
2655
+ call: `const shownFile = await startShownFile(heads, ${diagramLanguage === undefined ? shownLanguage : `[${diagramLanguage}]`});`
2656
+ },
2657
+ // Save is armed with the editor, so it works before the other panes load;
2658
+ // with a diagram it waits for the edits of the one shown, once mounted.
2659
+ ...(lsp
2660
+ ? [
2661
+ {
2662
+ module: './editor.js',
2663
+ imports: 'armEditorSave, startEditor',
2664
+ call: [
2665
+ 'const editor = await startEditor(heads, shownFile);',
2666
+ ...(diagram === undefined
2667
+ ? ['armEditorSave(editor);']
2668
+ : [
2669
+ 'let shownDiagram: Awaited<ReturnType<typeof mountDiagram>> | undefined = undefined;',
2670
+ 'armEditorSave(editor, () => settleDiagramEdits(shownDiagram?.()));'
2671
+ ])
2672
+ ].join('\n ')
2673
+ }
2674
+ ]
2675
+ : []),
2676
+ ...(data
2677
+ ? [
2678
+ {
2679
+ module: './data-status.js',
2680
+ imports: 'showDataStatus',
2681
+ call: `await showDataStatus(heads.data, ${starterUri(composition.grammars[0])});`
2682
+ }
2683
+ ]
2684
+ : []),
2685
+ ...(diagram === undefined
2686
+ ? []
2687
+ : [
2688
+ {
2689
+ module: './diagram.js',
2690
+ imports: lsp ? 'mountDiagram, settleDiagramEdits' : 'mountDiagram',
2691
+ call: `${lsp ? 'shownDiagram' : 'const shownDiagram'} = await mountDiagram(heads.glsp, shownFile, logger, ${lsp ? 'settleDiagramEdits' : 'saveBeforeLeaving'});`
2692
+ }
2693
+ ]),
2694
+ // Without the editor, the diagram is what the page saves through.
2695
+ ...(lsp ? [] : [{ module: './diagram-save.js', imports: 'armDiagramSave, saveBeforeLeaving', call: 'armDiagramSave(shownDiagram);' }])
2696
+ ];
2697
+ const imports = [
2698
+ ...parts.map(part => `import { ${part.imports} } from '${part.module}';`),
2699
+ "import { appendLog, setStatus } from './log.js';",
2700
+ ...(data ? ["import { WORKSPACE_ROOT_URI } from './workspace.js';"] : [])
2701
+ ].sort((left, right) => left.slice(left.indexOf("'")).localeCompare(right.slice(right.indexOf("'"))));
2702
+
2703
+ return `// The page: it starts the worker, hands each head a channel of its own, and
2704
+ // fills the pane of each head the server runs, one after the other.
2705
+
2706
+ import { connectWorkerHeads } from '@hydranium/client-browser';
2707
+ import { ConsoleLogger, describeError } from '@hydranium/protocol';
2708
+ import { ${shownLanguage} } from '${memberPackageName(composition, 'protocol')}';
2709
+ ${imports.join('\n')}
2710
+
2711
+ /** Where the worker bundle is served, substituted by \`esbuild.mjs\`. */
2712
+ declare const __WORKER_BUNDLE_URL__: string;
2713
+
2714
+ async function main(): Promise<void> {
2715
+ // The page's end of each head's connection logs to the browser console.
2716
+ const logger = new ConsoleLogger();
2717
+ const heads = connectWorkerHeads(new Worker(__WORKER_BUNDLE_URL__), { logger });
2718
+ heads.onWorkerError(report => appendLog(\`worker error during \${report.phase}: \${report.message}\`));
2719
+ setStatus('starting…');
2720
+ ${parts.map(part => ` ${part.call}`).join('\n')}
2721
+ setStatus('ready');
2722
+ }
2723
+
2724
+ main().catch((error: unknown) => setStatus(\`failed: \${describeError(error)}\`));
2725
+ `;
2726
+ }
2727
+
2728
+ /**
2729
+ * The smoke test: what each head shows on the page, and an edit that survives
2730
+ * a reload, typed in the editor or, with no LSP head, made in the diagram. With
2731
+ * a diagram, also a diagram edit the reload guard and Save catch before the
2732
+ * server has answered it.
2733
+ */
2734
+ function hostSmokeSpec(composition: InitComposition): string {
2735
+ const lsp = composition.heads.includes('lsp');
2736
+ const data = composition.heads.includes('data');
2737
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2738
+ const primary = composition.grammars[0];
2739
+ const checks = [
2740
+ ...(lsp ? [" await expect(editor).toContainText('node First');"] : []),
2741
+ ...(data
2742
+ ? [
2743
+ ' // The data head reads the document out of the same store.',
2744
+ ` await expect(page.locator('#data-status')).toHaveText('data head: nodes.${primary.extensions[0]} holds a ${primary.entryRule}');`
2745
+ ]
2746
+ : []),
2747
+ ...(diagram === undefined
2748
+ ? []
2749
+ : [
2750
+ ' // The diagram follows the switch: two nodes in one file, and in the other its',
2751
+ ' // node and the target it references there, drawn as external.',
2752
+ " const first = await page.locator('#file').inputValue();",
2753
+ ` await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');`,
2754
+ " await expect(page.locator('#diagram .sprotty-node')).toHaveCount(2);",
2755
+ ` await page.locator('#file').selectOption('references.${diagram.extensions[0]}');`,
2756
+ ` await expect(page.locator('#diagram .external')).toHaveText('Second (nodes.${diagram.extensions[0]})');`,
2757
+ " await page.locator('#file').selectOption(first);"
2758
+ ])
2759
+ ];
2760
+ const edit = lsp
2761
+ ? ` await editor.click();
2762
+ await page.keyboard.press('ControlOrMeta+End');
2763
+ await page.keyboard.type('\\nnode Added');
2764
+ await page.locator('#save').click();
2765
+ await expect(page.locator('#status')).toHaveText('saved 1 file(s)');
2766
+
2767
+ await page.reload();
2768
+ await expect(page.locator('#status')).toHaveText('ready');
2769
+ await expect(editor).toContainText('node Added');`
2770
+ : ` // A node from the palette, dropped low and left of centre: the starter nodes
2771
+ // sit in the upper band and the palette in the upper right.
2772
+ const canvas = page.locator('#diagram');
2773
+ const create = async (): Promise<void> => {
2774
+ await page.locator('#diagram .tool-button', { hasText: '${diagram?.nodeRule}' }).click();
2775
+ const size = await canvas.evaluate(element => ({ width: element.clientWidth, height: element.clientHeight }));
2776
+ await canvas.click({ position: { x: size.width * 0.4, y: size.height * 0.85 } });
2777
+ };
2778
+ await create();
2779
+ await expect(nodes).toHaveCount(3);
2780
+ await page.locator('#save').click();
2781
+ await expect(page.locator('#status')).toHaveText('saved the diagram');
2782
+ // A second, left unsaved: the switch saves the diagram it leaves.
2783
+ await create();
2784
+ await expect(nodes).toHaveCount(4);
2785
+ await page.locator('#file').selectOption('references.${diagram?.extensions[0]}');
2786
+ await expect(page.locator('#diagram .external')).toBeVisible();
2787
+
2788
+ await page.reload();
2789
+ await expect(page.locator('#status')).toHaveText('ready');
2790
+ await expect(nodes).toHaveCount(4);`;
2791
+ const guardTest =
2792
+ diagram === undefined
2793
+ ? ''
2794
+ : `
2795
+ test('asks before a reload drops a diagram edit the server has not answered, and saves it with Save at once', async ({ page }) => {
2796
+ const nodes = page.locator('#diagram .sprotty-node');
2797
+ const askGuard = (): Promise<boolean> =>
2798
+ page.evaluate(() => {
2799
+ const event = new Event('beforeunload', { cancelable: true });
2800
+ window.dispatchEvent(event);
2801
+ return event.defaultPrevented;
2802
+ });
2803
+ await page.goto('/');
2804
+ await expect(page.locator('#status')).toHaveText('ready');
2805
+ await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');
2806
+ await expect(nodes).toHaveCount(2);
2807
+
2808
+ const canvas = page.locator('#diagram');
2809
+ await page.locator('#diagram .tool-button', { hasText: '${diagram.nodeRule}' }).click();
2810
+ const size = await canvas.evaluate(element => ({ width: element.clientWidth, height: element.clientHeight }));
2811
+ // Asked and clicked right after the click's own handlers, in the same turn
2812
+ // of the page, so the server's answer cannot have marked anything unsaved.
2813
+ await page.evaluate(() => {
2814
+ window.addEventListener(
2815
+ 'mouseup',
2816
+ () =>
2817
+ queueMicrotask(() => {
2818
+ const event = new Event('beforeunload', { cancelable: true });
2819
+ window.dispatchEvent(event);
2820
+ document.getElementById('save')?.click();
2821
+ Reflect.set(window, 'guardedOnCreate', event.defaultPrevented);
2822
+ }),
2823
+ { once: true }
2824
+ );
2825
+ });
2826
+ await canvas.click({ position: { x: size.width * 0.4, y: size.height * 0.85 } });
2827
+ expect(await page.evaluate(() => Reflect.get(window, 'guardedOnCreate'))).toBe(true);
2828
+ await expect(page.locator('#status')).toHaveText('${lsp ? 'saved 1 file(s)' : 'saved the diagram'}');
2829
+ expect(await askGuard()).toBe(false);
2830
+
2831
+ await page.reload();
2832
+ await expect(page.locator('#status')).toHaveText('ready');
2833
+ await page.locator('#file').selectOption('nodes.${diagram.extensions[0]}');
2834
+ await expect(nodes).toHaveCount(3);
2835
+ });
2836
+ `;
2837
+ const locators = [
2838
+ ...(lsp ? [" const editor = page.locator('#editor .view-lines');"] : []),
2839
+ ...(lsp ? [] : [" const nodes = page.locator('#diagram .sprotty-node');"])
2840
+ ];
2841
+ return `// The page loads with every head answering, and an edit saved through the
2842
+ // ${lsp ? 'LSP head' : 'GLSP head'} is still there after a reload; any console error fails that
2843
+ // test. The other asks before a reload drops a diagram edit the server has not
2844
+ // answered yet, and keeps it when Save is clicked at once.
2845
+
2846
+ import { expect, test } from '@playwright/test';
2847
+
2848
+ test('loads every head and keeps a saved ${lsp ? 'edit' : 'diagram edit'} across a reload', async ({ page }) => {
2849
+ const errors: string[] = [];
2850
+ page.on('pageerror', error => errors.push(error.message));
2851
+ page.on('console', message => {
2852
+ if (message.type() === 'error') {
2853
+ errors.push(message.text());
2854
+ }
2855
+ });
2856
+ ${locators.join('\n')}
2857
+
2858
+ await page.goto('/');
2859
+ await expect(page.locator('#status')).toHaveText('ready');
2860
+ ${checks.join('\n')}
2861
+
2862
+ ${edit}
2863
+ expect(errors).toEqual([]);
2864
+ });
2865
+ ${guardTest}${
2866
+ lsp
2867
+ ? `
2868
+ test('colours declarations, references, keywords and comments', async ({ page }) => {
2869
+ await page.goto('/');
2870
+ await expect(page.locator('#status')).toHaveText('ready');
2871
+ const editor = page.locator('#editor .view-lines');
2872
+ const second = editor.locator('span').filter({ hasText: /^Second$/ });
2873
+ const keyword = editor
2874
+ .locator('span')
2875
+ .filter({ hasText: /^node$/ })
2876
+ .first();
2877
+ for (const extension of [${composition.grammars.map(grammar => `'${grammar.extensions[0]}'`).join(', ')}]) {
2878
+ await page.locator('#file').selectOption(\`nodes.\${extension}\`);
2879
+ await expect(editor.locator('span').filter({ hasText: /^First$/ })).toHaveCSS('color', 'rgb(36, 122, 147)');
2880
+ await expect(second).toHaveCount(2);
2881
+ for (const target of await second.all()) {
2882
+ await expect(target).toHaveCSS('color', 'rgb(36, 122, 147)');
2883
+ }
2884
+ await expect(keyword).toHaveCSS('color', 'rgb(0, 0, 255)');
2885
+ await expect(editor.locator('.view-line > span > span').filter({ hasText: /A.second.node/ })).toHaveCSS('color', 'rgb(0, 128, 0)');
2886
+ await page.locator('#file').selectOption(\`references.\${extension}\`);
2887
+ await expect(editor.locator('span').filter({ hasText: /^Third$/ })).toHaveCSS('color', 'rgb(36, 122, 147)');
2888
+ await expect(second).toHaveCSS('color', 'rgb(36, 122, 147)');
2889
+ }
2890
+ });
2891
+ `
2892
+ : ''
2893
+ }`;
2894
+ }
2895
+
2896
+ /** The browser host's README. */
2897
+ function hostBrowserReadme(composition: InitComposition): string {
2898
+ const lsp = composition.heads.includes('lsp');
2899
+ const data = composition.heads.includes('data');
2900
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2901
+ const lines = [
2902
+ `# ${memberPackageName(composition, 'host-browser')}`,
2903
+ '',
2904
+ '__NAME__ in a browser page: every head runs in a web worker, with no backend',
2905
+ `and no Node runtime. The page saves through the ${lsp ? 'LSP head' : 'GLSP head'}, and the worker`,
2906
+ 'keeps each saved file in IndexedDB, laid over `../workspace` on the next',
2907
+ 'load.',
2908
+ '',
2909
+ '```bash',
2910
+ 'npm run build # type-check and bundle into out/',
2911
+ 'npm start # serve the page at the URL it prints, rebundled on every source change',
2912
+ 'npm run test:e2e:install # download the Chromium the smoke test drives, once',
2913
+ 'npm run test:e2e # the smoke test, which serves the page itself',
2914
+ '```',
2915
+ '',
2916
+ '`PORT` moves the page to another port, for `npm start` and the smoke test alike;',
2917
+ 'stop `npm start` before the smoke test, or give one of them another port.',
2918
+ '`npm start` reads `../workspace` once, so restart it after editing a file',
2919
+ 'there.',
2920
+ '',
2921
+ '## Layout',
2922
+ '',
2923
+ '- `index.html` — the page, with a pane for each head that stays hidden until its part fills it',
2924
+ '- `hydranium-mark.svg` — the tab icon',
2925
+ `- \`esbuild.mjs\` — bundles the page${lsp ? ', the worker and Monaco’s worker' : ' and the worker'}, reading \`../workspace\` in as the seed`,
2926
+ '- `src/worker.ts` — the worker: the heads over one store, seeded and persisted',
2927
+ '- `src/page.ts` — starts the worker and runs the part of the page each head serves',
2928
+ '- `src/shown-file.ts` — the file switch above the panes, which every part follows',
2929
+ ...(lsp ? ['- `src/editor.ts` — the LSP part: a Monaco editor and Save'] : []),
2930
+ ...(data ? ['- `src/data-status.ts` — the data part: one document read through the data head'] : []),
2931
+ ...(diagram === undefined
2932
+ ? []
2933
+ : [
2934
+ `- \`src/diagram.ts\` — the GLSP part: the \`${diagram.grammar}\` diagram of the file the page shows, defined in the client package`
2935
+ ]),
2936
+ ...(lsp ? [] : ['- `src/diagram-save.ts` — Save with no editor: the diagram saved through the GLSP head']),
2937
+ '- `src/log.ts` — the status line and the log area',
2938
+ '- `src/workspace.ts` — the workspace root URI both ends name',
2939
+ ...(lsp ? ['- `src/monaco-editor-worker.ts` — Monaco’s own worker, which hosts no head'] : []),
2940
+ '- `src/posix-path-shim.ts` — the `path` function the framework imports, for the bundle',
2941
+ '- `test/smoke.spec.mts` — the page loads, each head answers, and a saved edit survives a reload',
2942
+ ''
2943
+ ];
2944
+ return project(lines.join('\n'), composition);
2945
+ }
2946
+
2947
+ /** The page with the line under its log view saying what shows there, which the LSP head decides. */
2948
+ function withLogHint(page: InitFile, lsp: boolean): InitFile {
2949
+ const hint = lsp
2950
+ ? 'What the server logs over the LSP head, and the errors the page reports.'
2951
+ : "The errors the page reports. The server logs to the worker's console, in the browser's developer tools.";
2952
+ return { ...page, content: page.content.replace('__LOG_HINT__', hint) };
2953
+ }
2954
+
2955
+ /** The browser host: a page and a worker, bundled by esbuild and served as static files. */
2956
+ function hostBrowserFiles(composition: InitComposition): InitFile[] {
2957
+ const fixed = (file: string): InitFile => projectTemplate(`host-browser/${file}`, composition);
2958
+ const lsp = composition.heads.includes('lsp');
2959
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
2960
+ return [
2961
+ { path: 'host-browser/package.json', content: hostBrowserPackageJson(composition) },
2962
+ ignoreFile('host-browser'),
2963
+ { path: 'host-browser/README.md', content: hostBrowserReadme(composition) },
2964
+ withLogHint(fixed('index.html'), lsp),
2965
+ fixed('hydranium-mark.svg'),
2966
+ fixed('esbuild.mjs'),
2967
+ fixed('playwright.config.mts'),
2968
+ fixed('tsconfig.worker.json'),
2969
+ fixed('tsconfig.page.json'),
2970
+ fixed('tsconfig.e2e.json'),
2971
+ { path: 'host-browser/src/worker.ts', content: hostWorkerFile(composition) },
2972
+ { path: 'host-browser/src/page.ts', content: hostPageFile(composition) },
2973
+ fixed('src/shown-file.ts'),
2974
+ ...(lsp ? [fixed('src/editor.ts')] : []),
2975
+ ...(composition.heads.includes('data') ? [fixed('src/data-status.ts')] : []),
2976
+ ...(diagram === undefined ? [] : [grammarTemplate('host-browser/src/diagram.ts', composition, diagram)]),
2977
+ ...(lsp ? [] : [fixed('src/diagram-save.ts')]),
2978
+ fixed('src/log.ts'),
2979
+ fixed('src/workspace.ts'),
2980
+ ...(lsp ? [fixed('src/monaco-editor-worker.ts'), fixed('src/monaco-editor-core-worker.d.ts')] : []),
2981
+ fixed('src/posix-path-shim.ts'),
2982
+ { path: 'host-browser/test/smoke.spec.mts', content: hostSmokeSpec(composition) }
2983
+ ];
2984
+ }
2985
+
2986
+ /** A JSON value as it sits at `indent` in a manifest npm writes. */
2987
+ function jsonAt(value: unknown, indent: string): string {
2988
+ return JSON.stringify(value, null, 2).replace(/\n/g, `\n${indent}`);
2989
+ }
2990
+
2991
+ /**
2992
+ * The languages and grammars a VS Code extension contributes. Each extension
2993
+ * declares its own, since either may be installed without the other; the
2994
+ * grammars are the server's, copied in by `copy:syntaxes`.
2995
+ */
2996
+ function vscodeLanguageContributions(composition: InitComposition): Record<string, unknown> {
2997
+ return {
2998
+ grammars: composition.grammars.map(grammar => ({
2999
+ language: grammar.languageId,
3000
+ scopeName: `source.${grammar.languageId}`,
3001
+ path: `./syntaxes/${grammar.languageId}.tmLanguage.json`
3002
+ })),
3003
+ languages: composition.grammars.map(grammar => ({
3004
+ id: grammar.languageId,
3005
+ aliases: [grammar.grammar],
3006
+ extensions: grammar.extensions.map(extension => `.${extension}`)
3007
+ }))
3008
+ };
3009
+ }
3010
+
3011
+ /** VS Code finds the grammars only inside the extension, so the build copies the server's. */
3012
+ const COPY_SYNTAXES_SCRIPT = "require('node:fs').cpSync('../server/syntaxes', 'syntaxes', { recursive: true })";
3013
+ const COPY_SYNTAXES = `node -e \\"${COPY_SYNTAXES_SCRIPT}\\"`;
3014
+
3015
+ /** `copy:syntaxes`, then again each time the server's `langium:watch` rewrites a grammar. */
3016
+ const WATCH_SYNTAXES = `node -e \\"const copy = () => ${COPY_SYNTAXES_SCRIPT}; copy(); require('node:fs').watch('../server/syntaxes', copy)\\"`;
3017
+
3018
+ /**
3019
+ * The servers-only extension's `package.json`. Always private, like a host:
3020
+ * it is installed into an application, never as a dependency.
3021
+ *
3022
+ * `onStartupFinished` rather than `onLanguage`, since a Theia backend asks for
3023
+ * a port before any document is open.
3024
+ */
3025
+ function vscodeServersPackageJson(composition: InitComposition): string {
3026
+ const dependencies: Record<string, string> = {
3027
+ [memberPackageName(composition, 'protocol')]: MEMBER_PIN,
3028
+ [memberPackageName(composition, 'server')]: MEMBER_PIN,
3029
+ ...VSCODE_LANGUAGE_CLIENT,
3030
+ '@hydranium/client-vscode': frameworkPin(composition)
3031
+ };
3032
+ return `{
3033
+ "name": "${memberPackageName(composition, 'vscode-servers')}",
3034
+ "displayName": "${composition.name} Servers",
3035
+ "version": "0.0.0",
3036
+ "private": true,
3037
+ "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.",
3038
+ "license": "UNLICENSED",
3039
+ "author": "",
3040
+ "publisher": "${composition.projectId}",
3041
+ "main": "./out/extension.js",
3042
+ "scripts": {
3043
+ "build": "npm run copy:syntaxes && tsc",
3044
+ "clean": "rimraf out syntaxes tsconfig.tsbuildinfo",
3045
+ "copy:syntaxes": "${COPY_SYNTAXES}",
3046
+ ${lintScript(forMember(composition, 'vscode-servers'), 'src')} "watch": "concurrently --kill-others --names syntaxes,tsc \\"npm run watch:syntaxes\\" \\"tsc --watch\\"",
3047
+ "watch:syntaxes": "${WATCH_SYNTAXES}"
3048
+ },
3049
+ "dependencies": {
3050
+ ${sortedBlock(dependencies, ' ')}
3051
+ },
3052
+ "devDependencies": {
3053
+ ${sortedBlock({ '@types/node': '^22.0.0', '@types/vscode': VSCODE_ENGINE, concurrently: '^9.0.0', rimraf: '^5.0.0', typescript: '^7.0.2' }, ' ')}
3054
+ },
3055
+ "contributes": ${jsonAt(vscodeLanguageContributions(composition), ' ')},
3056
+ "activationEvents": [
3057
+ "onStartupFinished"
3058
+ ],
3059
+ "engines": {
3060
+ "vscode": "${VSCODE_ENGINE}"
3061
+ }
3062
+ }
3063
+ `;
3064
+ }
3065
+
3066
+ /**
3067
+ * The servers-only extension's activation: the shared launch, and with a socket
3068
+ * head the port commands, which only this extension registers.
3069
+ */
3070
+ function vscodeServersExtensionFile(composition: InitComposition): string {
3071
+ const upper = screamingSnake(composition.projectId);
3072
+ const heads = socketHeads(composition).map(head => head.key);
3073
+ const protocolSymbols = heads.flatMap(head => [`${upper}_${head}_HOST_COMMAND`, `${upper}_${head}_PORT_COMMAND`]);
3074
+ const imports =
3075
+ heads.length === 0
3076
+ ? ''
3077
+ : `import { registerPortCommands } from '@hydranium/client-vscode/node';
3078
+ ${importList(protocolSymbols, memberPackageName(composition, 'protocol'), columnsFor(composition))}
3079
+ `;
3080
+ const portCommands =
3081
+ heads.length === 0
3082
+ ? ''
3083
+ : `
3084
+
3085
+ // Each socket head's port as a host command, for a host with no language
3086
+ // client of its own. Not in the shared launch: VS Code throws on a second
3087
+ // registration of one id, so the VS Code extension beside this one would fail
3088
+ // to activate. A pass-through: awaiting anything else in it would hang a
3089
+ // Theia backend on a user dismissing a notification.
3090
+ registerPortCommands(context, client, {
3091
+ ${heads.map(head => ` [${upper}_${head}_HOST_COMMAND]: ${upper}_${head}_PORT_COMMAND`).join(',\n')}
3092
+ });`;
3093
+ return `// The servers-only extension: it starts the ${composition.name} server and contributes no
3094
+ // editor, view or command. A Theia app sideloads this one rather than the VS
3095
+ // Code extension, whose diagram editors would give its files a second editor.
3096
+
3097
+ ${imports}import type { ExtensionContext } from 'vscode';
3098
+ import type { LanguageClient } from 'vscode-languageclient/node';
3099
+ import { start${composition.name}LanguageClient } from './language-client.js';
3100
+
3101
+ let client: LanguageClient | undefined;
3102
+
3103
+ export async function activate(context: ExtensionContext): Promise<void> {
3104
+ client = await start${composition.name}LanguageClient(context);${portCommands}
3105
+ }
3106
+
3107
+ export async function deactivate(): Promise<void> {
3108
+ await client?.stop();
3109
+ client = undefined;
3110
+ }
3111
+ `;
3112
+ }
3113
+
3114
+ /**
3115
+ * The server launch both extensions share: one launch, so VS Code and a Theia
3116
+ * app sideloading the servers extension hand the server the same documents.
3117
+ */
3118
+ function vscodeLanguageClientFile(composition: InitComposition): string {
3119
+ return `// Starts the ${composition.name} server for VS Code, and for a Theia app that sideloads
3120
+ // this extension: one launch, so both hand the server the same documents.
3121
+
3122
+ import { textDocumentContentMiddleware, textDocumentSyncMiddleware } from '@hydranium/client-vscode/node';
3123
+ import { ALL_LANGUAGES } from '${memberPackageName(composition, 'protocol')}';
3124
+ import { type ExtensionContext, workspace } from 'vscode';
3125
+ import { LanguageClient, type ServerOptions, TransportKind } from 'vscode-languageclient/node';
3126
+
3127
+ /** Fork the server, start its language client and return it once started. */
3128
+ export async function start${composition.name}LanguageClient(context: ExtensionContext, serverOptions?: ServerOptions): Promise<LanguageClient> {
3129
+ // Resolved through the package, so it works from the workspace and from an
3130
+ // installed extension alike. Over IPC, which keeps the server's stdout free.
3131
+ const serverModule = require.resolve('${memberPackageName(composition, 'server')}/lib/main.js');
3132
+ const extensions = ALL_LANGUAGES.flatMap(language => language.fileExtensions).join(',');
3133
+ const client: LanguageClient = new LanguageClient(
3134
+ '${composition.projectId}',
3135
+ '${composition.name}',
3136
+ serverOptions ?? { module: serverModule, transport: TransportKind.ipc },
3137
+ {
3138
+ documentSelector: ALL_LANGUAGES.flatMap(({ languageId }) => [
3139
+ { scheme: 'file', language: languageId },
3140
+ { scheme: 'virtual', language: languageId }
3141
+ ]),
3142
+ // Changes on disk the editor does not hold, such as a file another tool writes.
3143
+ synchronize: { fileEvents: workspace.createFileSystemWatcher(\`**/*{\${extensions}}\`) },
3144
+ // The text of a document only the server holds, such as a built-in library.
3145
+ middleware: {
3146
+ ...textDocumentContentMiddleware(() => client),
3147
+ ...textDocumentSyncMiddleware(() => client)
3148
+ }
3149
+ }
3150
+ );
3151
+ context.subscriptions.push(client);
3152
+ await client.start();
3153
+
3154
+ return client;
3155
+ }
3156
+ `;
3157
+ }
3158
+
3159
+ /** The generated launcher exercised in a real extension host against a content server. */
3160
+ function hostVscodeVirtualTest(composition: InitComposition): string {
3161
+ return `const assert = require('node:assert/strict');
3162
+ const path = require('node:path');
3163
+ const fs = require('node:fs');
3164
+ const os = require('node:os');
3165
+ const { TransportKind } = require('vscode-languageclient/node');
3166
+ const vscode = require('vscode');
3167
+ const { start${composition.name}LanguageClient } = require('${memberPackageName(composition, 'vscode-servers')}/out/language-client.js');
3168
+
3169
+ module.exports.run = async () => {
3170
+ const subscriptions = [];
3171
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'content-host-'));
3172
+ const client = await start${composition.name}LanguageClient(
3173
+ { subscriptions },
3174
+ {
3175
+ module: path.join(__dirname, 'content-server.cjs'),
3176
+ transport: TransportKind.ipc
3177
+ }
3178
+ );
3179
+ try {
3180
+ const file = path.join(scratch, 'file.${composition.grammars[0].extensions[0]}');
3181
+ fs.writeFileSync(file, 'node Local');
3182
+ await vscode.window.showTextDocument(vscode.Uri.file(file));
3183
+ const uri = vscode.Uri.parse('virtual:fixture/library.${composition.grammars[0].extensions[0]}');
3184
+ const editor = await vscode.window.showTextDocument(uri);
3185
+ const position = new vscode.Position(0, 5);
3186
+ const hover = await vscode.commands.executeCommand('vscode.executeHoverProvider', uri, position);
3187
+ assert.ok(
3188
+ hover.some(value => value.contents.some(content => content.value === 'fixture hover')),
3189
+ 'virtual hover'
3190
+ );
3191
+ const tokens = await vscode.commands.executeCommand('vscode.provideDocumentSemanticTokens', uri);
3192
+ assert.ok(tokens?.data.length, 'virtual semantic tokens');
3193
+ const definitions = await vscode.commands.executeCommand('vscode.executeDefinitionProvider', uri, position);
3194
+ assert.ok(definitions.length, 'virtual definition');
3195
+ const before = editor.document.getText();
3196
+ await editor.edit(builder => builder.insert(position, 'changed'));
3197
+ assert.equal(editor.document.getText(), before);
3198
+ await vscode.languages.setTextDocumentLanguage(editor.document, 'plaintext');
3199
+ const received = await client.sendRequest('fixture/sync');
3200
+ assert.ok(
3201
+ received.some(event => event.method === 'textDocument/didOpen' && event.uri.startsWith('file:')),
3202
+ 'file sync reaches the server'
3203
+ );
3204
+ assert.deepEqual(
3205
+ received.filter(event => event.uri.startsWith('virtual:')),
3206
+ [],
3207
+ 'no virtual document synchronization reaches the server'
3208
+ );
3209
+ } finally {
3210
+ await client.stop();
3211
+ for (const subscription of subscriptions) subscription.dispose();
3212
+ fs.rmSync(scratch, { recursive: true, force: true });
3213
+ }
3214
+ };
3215
+ `;
3216
+ }
3217
+
3218
+ /** The folders of the Theia applications the composition emits, as code spans. */
3219
+ function theiaApplicationPaths(composition: InitComposition): string[] {
3220
+ return composition.hosts.filter(isTheiaHost).map(host => `\`../host-${host}\``);
3221
+ }
3222
+
3223
+ /** The servers-only extension's README. */
3224
+ function vscodeServersReadme(composition: InitComposition): string {
3225
+ const vscode = composition.hosts.includes('vscode');
3226
+ const theiaApps = theiaApplicationPaths(composition);
3227
+ const intro = [
3228
+ 'A VS Code extension that starts the __NAME__ server and contributes no editor, view or command: the languages, their grammars and the server.',
3229
+ `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${
3230
+ theiaApps.length > 0
3231
+ ? theiaApps.length === 1
3232
+ ? `: the Theia application in ${theiaApps[0]}, which sideloads this extension.`
3233
+ : `: the Theia applications in ${listPhrase(theiaApps)}, which sideload this extension.`
3234
+ : ', such as a Theia app sideloading this extension.'
3235
+ }`,
3236
+ ...(vscode
3237
+ ? [
3238
+ 'The VS Code extension in `../host-vscode` starts the server through the same function.',
3239
+ 'Both work side by side, but each starts its own server and language client, so diagnostics may show twice: install one.'
3240
+ ]
3241
+ : [])
3242
+ ];
3243
+ const lines = [
3244
+ `# ${memberPackageName(composition, 'vscode-servers')}`,
3245
+ '',
3246
+ ...wrapProse(intro.join(' ')),
3247
+ '',
3248
+ '```bash',
3249
+ 'npm run build # copy the server’s grammars and compile into out/; build the server first',
3250
+ 'npm run watch # the same on every change',
3251
+ '```',
3252
+ '',
3253
+ '- `src/extension.ts` — activation, which starts the server and, with a socket head, registers its port commands',
3254
+ `- \`src/language-client.ts\` — the server launch${vscode ? ', shared with `../host-vscode`' : ''}`,
3255
+ ''
3256
+ ];
3257
+ return project(lines.join('\n'), composition);
3258
+ }
3259
+
3260
+ /** The servers-only extension: the server's launch, without an editor. */
3261
+ function vscodeServersFiles(composition: InitComposition): InitFile[] {
3262
+ return [
3263
+ { path: 'vscode-servers/package.json', content: vscodeServersPackageJson(composition) },
3264
+ ignoreFile('vscode-servers'),
3265
+ { path: 'vscode-servers/README.md', content: vscodeServersReadme(composition) },
3266
+ projectTemplate('vscode-servers/tsconfig.json', composition),
3267
+ { path: 'vscode-servers/src/extension.ts', content: vscodeServersExtensionFile(composition) },
3268
+ { path: 'vscode-servers/src/language-client.ts', content: vscodeLanguageClientFile(composition) }
3269
+ ];
3270
+ }
3271
+
3272
+ /**
3273
+ * The custom-editor view type of a grammar's diagram, as the editor module
3274
+ * declares it. VS Code keys custom editors by view type alone, across every
3275
+ * installed extension, so it carries the language id, which `init` qualifies
3276
+ * by the project wherever the grammar is named apart from it.
3277
+ */
3278
+ function diagramViewType(grammar: InitGrammarNames): string {
3279
+ return `${grammar.languageId}.diagram`;
3280
+ }
3281
+
3282
+ /**
3283
+ * The VS Code extension's `package.json`. Always private, as every host is.
3284
+ *
3285
+ * A diagram file opens in its diagram by default; `Reopen Editor With` reaches
3286
+ * the text.
3287
+ */
3288
+ function hostVscodePackageJson(composition: InitComposition): string {
3289
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3290
+ const dependencies: Record<string, string> = {
3291
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
3292
+ ...VSCODE_LANGUAGE_CLIENT
3293
+ };
3294
+ if (diagrams.length > 0) {
3295
+ dependencies[memberPackageName(composition, 'client')] = MEMBER_PIN;
3296
+ dependencies[memberPackageName(composition, 'protocol')] = MEMBER_PIN;
3297
+ Object.assign(dependencies, HOST_VSCODE_GLSP_THIRD_PARTY_DEPENDENCIES);
3298
+ for (const framework of HOST_VSCODE_GLSP_FRAMEWORK_DEPENDENCIES) {
3299
+ dependencies[framework] = frameworkPin(composition);
3300
+ }
3301
+ }
3302
+ if (composition.heads.includes('data')) {
3303
+ dependencies[memberPackageName(composition, 'protocol')] = MEMBER_PIN;
3304
+ Object.assign(dependencies, HOST_VSCODE_DATA_THIRD_PARTY_DEPENDENCIES);
3305
+ for (const framework of HOST_VSCODE_DATA_FRAMEWORK_DEPENDENCIES) {
3306
+ dependencies[framework] = frameworkPin(composition);
3307
+ }
3308
+ }
3309
+ const devDependencies = { ...HOST_VSCODE_DEV_DEPENDENCIES, ...(diagrams.length > 0 ? { esbuild: '^0.28.0' } : {}) };
3310
+ const watches: Record<string, string> = {
3311
+ syntaxes: 'npm run watch:syntaxes',
3312
+ tsc: 'tsc --watch',
3313
+ ...(diagrams.length > 0 ? { webview: 'node esbuild.mjs --watch' } : {})
3314
+ };
3315
+ const watchNames = Object.keys(watches).join(',');
3316
+ const watchCommands = Object.values(watches)
3317
+ .map(command => `\\"${command}\\"`)
3318
+ .join(' ');
3319
+ const contributes = {
3320
+ ...(composition.heads.includes('data')
3321
+ ? { commands: [{ command: `${composition.projectId}.showModel`, title: 'Show Model', category: composition.name }] }
3322
+ : {}),
3323
+ ...(diagrams.length > 0
3324
+ ? {
3325
+ customEditors: diagrams.map(grammar => ({
3326
+ viewType: diagramViewType(grammar),
3327
+ displayName: `${grammar.grammar} Diagram`,
3328
+ selector: grammar.extensions.map(extension => ({ filenamePattern: `*.${extension}` })),
3329
+ priority: 'default'
3330
+ }))
3331
+ }
3332
+ : {}),
3333
+ ...vscodeLanguageContributions(composition)
3334
+ };
3335
+ const typecheck = [...(diagrams.length > 0 ? ['tsconfig.webview.json'] : []), 'tsconfig.e2e.json']
3336
+ .map(project => `tsc --noEmit -p ${project}`)
3337
+ .join(' && ');
3338
+ return `{
3339
+ "name": "${memberPackageName(composition, 'host-vscode')}",
3340
+ "displayName": "${composition.name}",
3341
+ "version": "0.0.0",
3342
+ "private": true,
3343
+ "description": "${composition.name} in VS Code: ${hostVscodeParts(composition)}.",
3344
+ "license": "UNLICENSED",
3345
+ "author": "",
3346
+ "publisher": "${composition.projectId}",
3347
+ "main": "./out/extension.js",
3348
+ "scripts": {
3349
+ "build": "npm run copy:syntaxes && npm run typecheck && tsc${diagrams.length > 0 ? ' && node esbuild.mjs' : ''}",
3350
+ "clean": "rimraf out syntaxes tsconfig.tsbuildinfo test-results playwright-report",
3351
+ "copy:syntaxes": "${COPY_SYNTAXES}",
3352
+ ${lintScript(forMember(composition, 'host-vscode'), 'src test')} "start": "node start.mjs",
3353
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
3354
+ "test:e2e:install": "node --experimental-strip-types test/install-vscode.mts",
3355
+ "typecheck": "${typecheck}",
3356
+ "watch": "concurrently --kill-others --names ${watchNames} ${watchCommands}",
3357
+ "watch:syntaxes": "${WATCH_SYNTAXES}"
3358
+ },
3359
+ "dependencies": {
3360
+ ${sortedBlock(dependencies, ' ')}
3361
+ },
3362
+ "devDependencies": {
3363
+ ${sortedBlock(devDependencies, ' ')}
3364
+ },
3365
+ "contributes": ${jsonAt(contributes, ' ')},
3366
+ "activationEvents": ${jsonAt(
3367
+ composition.grammars.map(grammar => `onLanguage:${grammar.languageId}`),
3368
+ ' '
3369
+ )},
3370
+ "engines": {
3371
+ "vscode": "${VSCODE_ENGINE}"
3372
+ }
3373
+ }
3374
+ `;
3375
+ }
3376
+
3377
+ /** What the VS Code extension brings, as one phrase; `started` follows the language client. */
3378
+ function hostVscodeParts(composition: InitComposition, started = ''): string {
3379
+ const parts = [
3380
+ `the language client${started}`,
3381
+ ...(composition.heads.includes('data') ? ['a Show Model command reading a file through the data head'] : []),
3382
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['a custom editor for each diagram'] : [])
3383
+ ];
3384
+ return listPhrase(parts);
3385
+ }
3386
+
3387
+ /** `parts` as one English list: `a`, `a and b`, `a, b, and c`. */
3388
+ function listPhrase(parts: readonly string[]): string {
3389
+ return parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(', ')}${parts.length > 2 ? ',' : ''} and ${parts.at(-1)}`;
3390
+ }
3391
+
3392
+ /**
3393
+ * The VS Code extension's entry: the shared server launch, then the Show Model
3394
+ * command over the data head and a diagram editor per diagram grammar.
3395
+ */
3396
+ function hostVscodeExtensionFile(composition: InitComposition): string {
3397
+ const columns = columnsFor(composition);
3398
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3399
+ const data = composition.heads.includes('data');
3400
+ const start = `start${composition.name}LanguageClient`;
3401
+ const servers = `${memberPackageName(composition, 'vscode-servers')}/out/language-client.js`;
3402
+ const upper = screamingSnake(composition.projectId);
3403
+ const editors = diagrams.map(grammar => ({
3404
+ module: `./${grammar.grammarId}-diagram-editor.js`,
3405
+ viewType: `${screamingSnake(grammar.grammarId)}_DIAGRAM_VIEW_TYPE`,
3406
+ provider: `${grammar.grammar}DiagramEditorProvider`,
3407
+ local: `${grammar.grammar.charAt(0).toLowerCase()}${grammar.grammar.slice(1)}Editor`
3408
+ }));
3409
+ const registrations = editors.map(
3410
+ editor => ` const ${editor.local} = new ${editor.provider}(glspConnector, context.extensionUri);
3411
+ context.subscriptions.push(
3412
+ window.registerCustomEditorProvider(${editor.viewType}, ${editor.local}, {
3413
+ // A hidden tab keeps its diagram session rather than repeating the handshake.
3414
+ webviewOptions: { retainContextWhenHidden: true },
3415
+ // Two views of one document would be two GLSP clients racing on one model.
3416
+ supportsMultipleEditorsPerDocument: false
3417
+ })
3418
+ );`
3419
+ );
3420
+ const sockets = data || diagrams.length > 0;
3421
+ const protocolSymbols = [
3422
+ ...(data ? [`${upper}_DATA_SERVER_PORT_COMMAND`] : []),
3423
+ ...(diagrams.length > 0 ? [`${upper}_GLSP_SERVER_PORT_COMMAND`] : []),
3424
+ ...(data ? [`type ${composition.name}Element`] : [])
3425
+ ];
3426
+ const imports = [
3427
+ ...(sockets ? ["import { findPort } from '@hydranium/client-vscode/node';"] : []),
3428
+ ...(data ? ["import { SocketDataPort } from '@hydranium/data-client-vscode/node';"] : []),
3429
+ ...(diagrams.length > 0
3430
+ ? ["import { HydraniumGlspVscodeConnector, HydraniumGlspVscodeServer } from '@hydranium/glsp-client-vscode/node';"]
3431
+ : []),
3432
+ ...(sockets
3433
+ ? [
3434
+ importList(
3435
+ [
3436
+ 'ConsoleLogger',
3437
+ ...(data ? ['DataConnectionWithEvents'] : []),
3438
+ ...(diagrams.length > 0 ? ['describeError'] : []),
3439
+ ...(data ? ['renderFrameworkMessage'] : [])
3440
+ ],
3441
+ '@hydranium/protocol',
3442
+ columns
3443
+ )
3444
+ ]
3445
+ : []),
3446
+ ...(sockets ? [importList(protocolSymbols, memberPackageName(composition, 'protocol'), columns)] : []),
3447
+ ...(sockets
3448
+ ? [`import { ${[...(data ? ['commands'] : []), 'type ExtensionContext', 'window'].join(', ')} } from 'vscode';`]
3449
+ : ["import type { ExtensionContext } from 'vscode';"]),
3450
+ "import type { LanguageClient } from 'vscode-languageclient/node';",
3451
+ `import { ${start} } from '${servers}';`,
3452
+ ...editors.map(editor => importList([editor.viewType, editor.provider], editor.module, columns)),
3453
+ ...(data ? ["import { showModelCommand } from './show-model-command.js';"] : [])
3454
+ ];
3455
+ const dataBlock = data
3456
+ ? `
3457
+
3458
+ // The data head, read by the Show Model command. Nothing connects until it runs.
3459
+ const dataPort = new SocketDataPort({
3460
+ findPort: () => findPort(running, ${upper}_DATA_SERVER_PORT_COMMAND),
3461
+ logger: new ConsoleLogger().with('data head'),
3462
+ // A failed read shown to the user, not only logged; the message carries the detail.
3463
+ reportError: (_error, reported) => void window.showErrorMessage(renderFrameworkMessage(reported))
3464
+ });
3465
+ const dataConnection = new DataConnectionWithEvents<${composition.name}Element>(dataPort);
3466
+ context.subscriptions.push(dataConnection, dataPort, commands.registerCommand('${composition.projectId}.showModel', showModelCommand(dataConnection)));`
3467
+ : '';
3468
+ const glspBlock =
3469
+ diagrams.length > 0
3470
+ ? `
3471
+
3472
+ // The GLSP head, and the connector bridging it to every diagram webview. No
3473
+ // \`messenger\` option: the connector's own keeps messages flowing to a hidden tab.
3474
+ const glspServer = new HydraniumGlspVscodeServer({
3475
+ clientId: '${composition.projectId}-glsp',
3476
+ clientName: '${composition.name}',
3477
+ findPort: () => findPort(running, ${upper}_GLSP_SERVER_PORT_COMMAND),
3478
+ logger: new ConsoleLogger().with('GLSP head')
3479
+ });
3480
+ const glspConnector = new HydraniumGlspVscodeConnector({ server: glspServer, logging: false });
3481
+ context.subscriptions.push(glspServer, glspConnector);
3482
+ // Not awaited, so a session that opens no diagram does not wait on the port.
3483
+ // \`start()\` resolves either way; a failure is reported off \`onReady\`.
3484
+ void glspServer.start();
3485
+ void glspServer.onReady.catch((error: unknown) => {
3486
+ void window.showErrorMessage(\`${composition.name} diagram unavailable: \${describeError(error)}\`);
3487
+ });
3488
+ ${registrations.join('\n')}`
3489
+ : '';
3490
+ const opening = wrapComment(
3491
+ `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.' : ''}`
3492
+ );
3493
+ const activation = sockets
3494
+ ? ` const running = await ${start}(context);
3495
+ client = running;${dataBlock}${glspBlock}`
3496
+ : ` client = await ${start}(context);`;
3497
+ return `${opening}
3498
+
3499
+ ${imports.join('\n')}
3500
+
3501
+ let client: LanguageClient | undefined;
3502
+
3503
+ export async function activate(context: ExtensionContext): Promise<void> {
3504
+ ${activation}
3505
+ }
3506
+
3507
+ export async function deactivate(): Promise<void> {
3508
+ await client?.stop();
3509
+ client = undefined;
3510
+ }
3511
+ `;
3512
+ }
3513
+
3514
+ /** A smoke test's title: what it checks of each head the composition has. */
3515
+ function hostVscodeSmokeTitle(composition: InitComposition): string {
3516
+ return listPhrase([
3517
+ ...(composition.heads.includes('data') ? ['reads the model'] : []),
3518
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['draws the diagram'] : []),
3519
+ 'reports a broken reference'
3520
+ ]);
3521
+ }
3522
+
3523
+ /**
3524
+ * The smoke test: VS Code opens the starter workspace with the extension
3525
+ * loaded, Show Model names the model with the data head, each diagram file
3526
+ * draws, and the server reports a broken reference.
3527
+ */
3528
+ function hostVscodeSmokeSpec(composition: InitComposition): string {
3529
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
3530
+ const file = `nodes.${(diagram ?? composition.grammars[0]).extensions[0]}`;
3531
+ const diagramSteps = diagram
3532
+ ? `
3533
+ // The diagram file opens in its diagram, which draws the two starter nodes.
3534
+ const webview = page.frameLocator('iframe.webview.ready').frameLocator('#active-frame');
3535
+ // In the editor's container: sprotty measures shapes in a hidden copy beside it.
3536
+ await expect(webview.locator('.hydranium-diagram-container .sprotty-node')).toHaveCount(2);
3537
+ // Then as text. The row is clicked, since Enter runs the best fuzzy match,
3538
+ // and its name ends in its keybinding, if it has one.
3539
+ await page.keyboard.press('ControlOrMeta+Shift+P');
3540
+ await page.locator('.quick-input-widget input').fill('>View: Reopen Editor with Text Editor');
3541
+ await page
3542
+ .locator('.quick-input-list')
3543
+ .getByRole('option', { name: /^View: Reopen Editor with Text Editor(,|$)/ })
3544
+ .click();
3545
+ `
3546
+ : '';
3547
+ const primary = diagram ?? composition.grammars[0];
3548
+ const showModelSteps = composition.heads.includes('data')
3549
+ ? ` // The data head reads the open file.
3550
+ await page.keyboard.press('ControlOrMeta+Shift+P');
3551
+ await page.locator('.quick-input-widget input').fill('>${composition.name}: Show Model');
3552
+ await page
3553
+ .locator('.quick-input-list')
3554
+ .getByRole('option', { name: /^${composition.name}: Show Model(,|$)/ })
3555
+ .click();
3556
+ await expect(page.locator('.notification-toast').filter({ hasText: '${file} holds a ${primary.entryRule}' })).toBeVisible();
3557
+ `
3558
+ : '';
3559
+ const opening = wrapComment(
3560
+ `VS Code opens a copy of the starter workspace with this extension loaded, ${listPhrase([
3561
+ ...(composition.heads.includes('data') ? ['the data head reads the file'] : []),
3562
+ ...(diagram ? ['the diagram file draws in its diagram editor'] : []),
3563
+ 'the server reports a reference that resolves to nothing'
3564
+ ])}.`
3565
+ );
3566
+ return `${opening}
3567
+
3568
+ import { _electron, expect, test, type ElectronApplication, type Page } from '@playwright/test';
3569
+ import { downloadAndUnzipVSCode } from '@vscode/test-electron';
3570
+ import { cpSync, mkdtempSync, rmSync } from 'node:fs';
3571
+ import { tmpdir } from 'node:os';
3572
+ import { join } from 'node:path';
3573
+ import { fileURLToPath } from 'node:url';
3574
+ import { VSCODE_CACHE, VSCODE_VERSION } from './vscode-version.mts';
3575
+
3576
+ const extensionRoot = fileURLToPath(new URL('..', import.meta.url));
3577
+
3578
+ test('${hostVscodeSmokeTitle(composition)}', async () => {
3579
+ // A copy, since the server writes its repairs to the folder it opens, and a
3580
+ // fresh profile, since a reused one restores the last run's editors.
3581
+ const scratch = mkdtempSync(join(tmpdir(), '${composition.projectId}-vscode-'));
3582
+ const workspace = join(scratch, 'workspace');
3583
+ cpSync(fileURLToPath(new URL('../../workspace', import.meta.url)), workspace, { recursive: true });
3584
+ let app: ElectronApplication | undefined;
3585
+ try {
3586
+ app = await _electron.launch({
3587
+ executablePath: await downloadAndUnzipVSCode({ version: VSCODE_VERSION, cachePath: VSCODE_CACHE }),
3588
+ args: [
3589
+ '--no-sandbox',
3590
+ '--disable-gpu-sandbox',
3591
+ '--disable-updates',
3592
+ '--skip-welcome',
3593
+ '--skip-release-notes',
3594
+ '--disable-workspace-trust',
3595
+ '--disable-extensions',
3596
+ \`--extensionDevelopmentPath=\${extensionRoot}\`,
3597
+ \`--user-data-dir=\${join(scratch, 'user-data')}\`,
3598
+ \`--extensions-dir=\${join(scratch, 'extensions')}\`,
3599
+ workspace
3600
+ ]
3601
+ });
3602
+ const page = await app.firstWindow();
3603
+ await expect(page.locator('.monaco-workbench')).toBeVisible();
3604
+ await quickOpen(page, '${file}');
3605
+ ${showModelSteps}${diagramSteps}
3606
+ const editor = page.locator('.monaco-editor .view-lines').first();
3607
+ await expect(editor).toContainText('node First');
3608
+ await editor.click();
3609
+ await page.keyboard.press('ControlOrMeta+End');
3610
+ // In one edit: typed key by key, the half-typed reference is reported on the way.
3611
+ await page.keyboard.insertText('\\nnode Broken -> Missing');
3612
+ await expect(page.locator('.monaco-editor .squiggly-error').first()).toBeVisible();
3613
+ } finally {
3614
+ await app?.close();
3615
+ rmSync(scratch, { recursive: true, force: true });
3616
+ }
3617
+ });
3618
+
3619
+ /** Open \`file\` through Quick Open, so it gets the editor a user would. */
3620
+ async function quickOpen(page: Page, file: string): Promise<void> {
3621
+ await page.keyboard.press('ControlOrMeta+P');
3622
+ const input = page.locator('.quick-input-widget input');
3623
+ await input.fill(file);
3624
+ await expect(page.locator('.quick-input-list .monaco-list-row').first()).toContainText(file);
3625
+ await input.press('Enter');
3626
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
3627
+ }
3628
+ `;
3629
+ }
3630
+
3631
+ /**
3632
+ * `text` broken at spaces into lines of at most 80 columns, the width
3633
+ * `check:docs` holds Markdown to. A link or code span stays whole, and runs
3634
+ * long on a line of its own.
3635
+ */
3636
+ function wrapProse(text: string, width = 80): string[] {
3637
+ const lines: string[] = [];
3638
+ for (const piece of text.match(/!?\[[^\]]*\]\([^)]*\)\S*|`+[^`]*`+\S*|\S+/g) ?? []) {
3639
+ const last = lines.at(-1);
3640
+ if (last !== undefined && last.length + 1 + piece.length <= width) {
3641
+ lines[lines.length - 1] = `${last} ${piece}`;
3642
+ } else {
3643
+ lines.push(piece);
3644
+ }
3645
+ }
3646
+ return lines;
3647
+ }
3648
+
3649
+ /** `text` as a `//` comment of lines at most 80 columns wide. */
3650
+ function wrapComment(text: string): string {
3651
+ return wrapProse(text, 77)
3652
+ .map(line => `// ${line}`)
3653
+ .join('\n');
3654
+ }
3655
+
3656
+ /** The VS Code extension's README. */
3657
+ function hostVscodeReadme(composition: InitComposition): string {
3658
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3659
+ const data = composition.heads.includes('data');
3660
+ const intro = [
3661
+ diagrams.length > 0
3662
+ ? `${composition.name} in VS Code: the language client, and a custom editor drawing each diagram file.`
3663
+ : `${composition.name} in VS Code: the language client.`,
3664
+ 'The server is started by `../vscode-servers`, whose launch this extension calls, so the two never hand the server different documents.',
3665
+ socketHeads(composition).length > 0
3666
+ ? 'It needs a Node extension host: the server is forked, and its socket heads are reached over TCP.'
3667
+ : 'It needs a Node extension host, since the server is forked.'
3668
+ ];
3669
+ 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.`;
3670
+ const lines = [
3671
+ `# ${memberPackageName(composition, 'host-vscode')}`,
3672
+ '',
3673
+ ...wrapProse(intro.join(' ')),
3674
+ ...(data ? ['', ...wrapProse(dataNote)] : []),
3675
+ '',
3676
+ '```bash',
3677
+ `npm run build # copy the server’s grammars, type-check and compile${diagrams.length > 0 ? ', then bundle' : ''}`,
3678
+ `npm run watch # copy the grammars and recompile${diagrams.length > 0 ? ' and rebundle' : ''} on every change; Developer: Reload Window picks it up`,
3679
+ 'npm start # VS Code with this extension, on ../workspace; needs `code` on the PATH',
3680
+ 'npm run test:e2e:install # download the VS Code the smoke test drives, once',
3681
+ 'npm run test:e2e # the smoke test; under `xvfb-run -a` on Linux without a display',
3682
+ '```',
3683
+ '',
3684
+ '## Layout',
3685
+ '',
3686
+ `- \`src/extension.ts\` — activation: ${listPhrase([
3687
+ 'the server, through `../vscode-servers`',
3688
+ ...(data ? ['the Show Model command'] : []),
3689
+ ...(diagrams.length > 0 ? ['the diagram editors'] : [])
3690
+ ])}`,
3691
+ ...(data ? ['- `src/show-model-command.ts` — Show Model: the active file, read through the data head'] : []),
3692
+ ...diagrams.flatMap(grammar => [
3693
+ `- \`src/${grammar.grammarId}-diagram-editor.ts\` — the \`${grammar.grammar}\` diagram’s custom editor; its view type is the one \`package.json\` declares`,
3694
+ `- \`src/webview/${grammar.grammarId}-diagram.ts\` — the webview it loads, over the client package’s diagram`
3695
+ ]),
3696
+ ...(diagrams.length > 0
3697
+ ? ['- `src/webview/diagram.css` — the webview’s size and colours', '- `esbuild.mjs` — bundles each webview into `out/webview/`']
3698
+ : []),
3699
+ '- `start.mjs` — `npm start`: VS Code with this extension, on `../workspace`',
3700
+ '- `test/smoke.spec.mts` — VS Code opens the workspace, ' +
3701
+ (composition.heads.includes('data') ? 'Show Model names the model, ' : '') +
3702
+ (diagrams.length > 0 ? 'the diagram draws, ' : '') +
3703
+ 'and the server reports a broken reference',
3704
+ '- `test/virtual-documents.spec.mts` — the generated launcher serves a',
3705
+ ' content document in the extension host without sending its text back',
3706
+ '- `test/virtual-documents.cjs` and `test/content-server.cjs` — the host',
3707
+ ' assertions and the content-owning LSP fixture they drive',
3708
+ '- `test/vscode-version.mts` — the VS Code release the smoke tests run',
3709
+ ''
3710
+ ];
3711
+ return project(lines.join('\n'), composition);
3712
+ }
3713
+
3714
+ /** The VS Code extension: the language client and a diagram editor per diagram grammar. */
3715
+ function hostVscodeFiles(composition: InitComposition): InitFile[] {
3716
+ const fixed = (file: string): InitFile => projectTemplate(`host-vscode/${file}`, composition);
3717
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3718
+ return [
3719
+ { path: 'host-vscode/package.json', content: hostVscodePackageJson(composition) },
3720
+ ignoreFile('host-vscode'),
3721
+ { path: 'host-vscode/README.md', content: hostVscodeReadme(composition) },
3722
+ fixed('tsconfig.json'),
3723
+ fixed('tsconfig.e2e.json'),
3724
+ fixed('playwright.config.mts'),
3725
+ fixed('start.mjs'),
3726
+ { path: 'host-vscode/src/extension.ts', content: hostVscodeExtensionFile(composition) },
3727
+ ...(composition.heads.includes('data') ? [fixed('src/show-model-command.ts')] : []),
3728
+ ...(diagrams.length > 0 ? [fixed('tsconfig.webview.json'), fixed('esbuild.mjs'), fixed('src/webview/diagram.css')] : []),
3729
+ ...diagrams.flatMap(grammar => [
3730
+ grammarTemplate('host-vscode/src/__GRAMMAR_ID__-diagram-editor.ts', composition, grammar),
3731
+ grammarTemplate('host-vscode/src/webview/__GRAMMAR_ID__-diagram.ts', composition, grammar)
3732
+ ]),
3733
+ { path: 'host-vscode/test/smoke.spec.mts', content: hostVscodeSmokeSpec(composition) },
3734
+ fixed('test/vscode-version.mts'),
3735
+ fixed('test/install-vscode.mts'),
3736
+ { path: 'host-vscode/test/virtual-documents.cjs', content: hostVscodeVirtualTest(composition) },
3737
+ fixed('test/content-server.cjs'),
3738
+ fixed('test/virtual-documents.spec.mts')
3739
+ ];
3740
+ }
3741
+
3742
+ /**
3743
+ * The Theia release of every Theia member, the one the framework's own
3744
+ * Theia examples take, so a scaffold builds against what the repo tests: the
3745
+ * Theia community release. Exact, as Theia's members pin each other, so a
3746
+ * workspace root declares it too and GLSP's open Theia peer resolves to it.
3747
+ */
3748
+ const THEIA_VERSION = '1.74.3';
3749
+
3750
+ /**
3751
+ * What each head adds to the Theia extension; `base` is the connection hardening
3752
+ * and editor sync every one gets. With the third-party entries below, they name
3753
+ * the peers of the framework's Theia packages, so an installer that adds no peers
3754
+ * still finds them.
3755
+ */
3756
+ const THEIA_FRAMEWORK_DEPENDENCIES: Record<InitHead | 'base', readonly string[]> = {
3757
+ base: ['@hydranium/client-theia', '@hydranium/protocol'],
3758
+ lsp: [],
3759
+ data: ['@hydranium/data-client-theia'],
3760
+ glsp: ['@hydranium/glsp-client', '@hydranium/glsp-client-theia']
3761
+ };
3762
+ const THEIA_THIRD_PARTY_DEPENDENCIES: Record<InitHead | 'base', Readonly<Record<string, string>>> = {
3763
+ base: {
3764
+ '@theia/core': THEIA_VERSION,
3765
+ '@theia/editor': THEIA_VERSION,
3766
+ '@theia/filesystem': THEIA_VERSION,
3767
+ '@theia/output': THEIA_VERSION,
3768
+ inversify: '^6.1.3',
3769
+ 'vscode-jsonrpc': '9.0.3'
3770
+ },
3771
+ lsp: {},
3772
+ data: { '@theia/workspace': THEIA_VERSION },
3773
+ glsp: {
3774
+ '@eclipse-glsp/client': '2.8.0',
3775
+ '@eclipse-glsp/theia-integration': '2.8.0',
3776
+ '@theia/process': THEIA_VERSION,
3777
+ '@theia/workspace': THEIA_VERSION
3778
+ }
3779
+ };
3780
+
3781
+ /** The Theia extension's third-party pins for `heads`, for its manifest and a workspace root's. */
3782
+ function theiaThirdPartyDependencies(heads: readonly InitHead[]): Array<[string, string]> {
3783
+ return (['base', ...heads] as const).flatMap(head => Object.entries(THEIA_THIRD_PARTY_DEPENDENCIES[head]));
3784
+ }
3785
+
3786
+ /**
3787
+ * The Theia packages the application assembles: the workbench a user expects,
3788
+ * and `plugin-ext` with its VS Code API to sideload the servers extension.
3789
+ */
3790
+ const HOST_THEIA_BROWSER_DEPENDENCIES: readonly string[] = [
3791
+ '@theia/core',
3792
+ '@theia/editor',
3793
+ '@theia/filesystem',
3794
+ '@theia/markers',
3795
+ '@theia/messages',
3796
+ '@theia/monaco',
3797
+ '@theia/navigator',
3798
+ '@theia/output',
3799
+ '@theia/plugin-ext',
3800
+ '@theia/plugin-ext-vscode',
3801
+ '@theia/preferences',
3802
+ '@theia/process',
3803
+ '@theia/workspace'
3804
+ ];
3805
+
3806
+ /** The Theia tooling the application builds with. */
3807
+ const HOST_THEIA_BROWSER_DEV_DEPENDENCIES: readonly string[] = ['@theia/cli'];
3808
+
3809
+ /** Every Theia package the application declares, for a workspace root's pins. */
3810
+ function hostTheiaBrowserTheiaDependencies(): Array<[string, string]> {
3811
+ return [...HOST_THEIA_BROWSER_DEPENDENCIES, ...HOST_THEIA_BROWSER_DEV_DEPENDENCIES].map(name => [name, THEIA_VERSION]);
3812
+ }
3813
+
3814
+ /** The Electron application's Theia packages: the browser application's, and Theia's Electron integration. */
3815
+ const HOST_THEIA_ELECTRON_DEPENDENCIES: readonly string[] = [...HOST_THEIA_BROWSER_DEPENDENCIES, '@theia/electron'].sort();
3816
+
3817
+ /** The Electron release `@theia/electron` peers on, exactly. */
3818
+ const ELECTRON_VERSION = '42.11.16';
3819
+
3820
+ /** Every package the Electron application pins, for a workspace root's pins. */
3821
+ function hostTheiaElectronPins(): Array<[string, string]> {
3822
+ return [
3823
+ ...[...HOST_THEIA_ELECTRON_DEPENDENCIES, ...HOST_THEIA_BROWSER_DEV_DEPENDENCIES].map((name): [string, string] => [
3824
+ name,
3825
+ THEIA_VERSION
3826
+ ]),
3827
+ ['electron', ELECTRON_VERSION]
3828
+ ];
3829
+ }
3830
+
3831
+ /** The Theia extension's `theiaExtensions` entries: one per head it forwards, and one per diagram. */
3832
+ function theiaExtensionEntries(composition: InitComposition): Array<Record<string, string>> {
3833
+ const id = composition.projectId;
3834
+ return [
3835
+ {
3836
+ frontendPreload: `lib/browser/${id}-connection-preload-module`,
3837
+ frontend: `lib/browser/${id}-frontend-module`,
3838
+ backend: `lib/node/${id}-connection-backend-module`
3839
+ },
3840
+ ...(composition.heads.includes('data') ? [{ backend: `lib/node/${id}-data-backend-module` }] : []),
3841
+ ...(composition.heads.includes('glsp') ? [{ backend: `lib/node/${id}-glsp-backend-module` }] : []),
3842
+ ...composition.grammars
3843
+ .filter(grammar => grammar.diagram)
3844
+ .map(grammar => ({ frontend: `lib/browser/${grammar.grammarId}-diagram-frontend-module` }))
3845
+ ];
3846
+ }
3847
+
3848
+ /** The Theia extension's `package.json`. Private unless `--public`, as the client member is. */
3849
+ function theiaPackageJson(composition: InitComposition): string {
3850
+ const dependencies: Record<string, string> = {
3851
+ // The socket heads' host commands, and the data head's model type.
3852
+ ...(socketHeads(composition).length > 0 ? { [memberPackageName(composition, 'protocol')]: MEMBER_PIN } : {}),
3853
+ ...(composition.heads.includes('glsp') ? { [memberPackageName(composition, 'client')]: MEMBER_PIN } : {}),
3854
+ ...Object.fromEntries(theiaThirdPartyDependencies(composition.heads))
3855
+ };
3856
+ for (const head of ['base', ...composition.heads] as const) {
3857
+ for (const framework of THEIA_FRAMEWORK_DEPENDENCIES[head]) {
3858
+ dependencies[framework] = frameworkPin(composition);
3859
+ }
3860
+ }
3861
+ return `{
3862
+ "name": "${memberPackageName(composition, 'theia')}",
3863
+ "version": "0.0.0",
3864
+ ${composition.packaging.private ? ' "private": true,\n' : ''} "description": "The ${composition.name} Theia extension: ${theiaParts(composition)}.",
3865
+ "license": "UNLICENSED",
3866
+ "author": "",
3867
+ "files": [
3868
+ "lib",
3869
+ "src",
3870
+ "style"
3871
+ ],
3872
+ "scripts": {
3873
+ "build": "tsc",
3874
+ "clean": "rimraf lib tsconfig.tsbuildinfo",
3875
+ ${lintScript(forMember(composition, 'theia'), 'src')} "watch": "tsc --watch"
3876
+ },
3877
+ "dependencies": {
3878
+ ${sortedBlock(dependencies, ' ')}
3879
+ },
3880
+ "devDependencies": {
3881
+ ${sortedBlock({ '@types/node': '^22.0.0', rimraf: '^5.0.0', typescript: '^7.0.2' }, ' ')}
3882
+ },
3883
+ "engines": {
3884
+ "node": ">=22.13"
3885
+ },
3886
+ "theiaExtensions": ${jsonAt(theiaExtensionEntries(composition), ' ')}
3887
+ }
3888
+ `;
3889
+ }
3890
+
3891
+ /** What the Theia extension brings, as one phrase. */
3892
+ function theiaParts(composition: InitComposition): string {
3893
+ return listPhrase([
3894
+ 'reconnect hardening',
3895
+ ...(composition.heads.includes('data') ? ['a Show Model command reading a file through the data head'] : []),
3896
+ ...(composition.grammars.some(grammar => grammar.diagram) ? ['a diagram editor for each diagram'] : [])
3897
+ ]);
3898
+ }
3899
+
3900
+ /** The extension's one frontend module: the logger, the connection diagnostics and editor sync, and each head's client. */
3901
+ function theiaFrontendModuleFile(composition: InitComposition): string {
3902
+ const id = composition.projectId;
3903
+ const name = composition.name;
3904
+ const data = composition.heads.includes('data');
3905
+ const glsp = composition.heads.includes('glsp');
3906
+ const imports = [
3907
+ ...(glsp ? ["import { GLSPClientContribution } from '@eclipse-glsp/theia-integration';"] : []),
3908
+ importList(
3909
+ ['bindChannelLogger', 'bindConnectionDiagnostics', 'bindEditorDiskSync', 'bindReadOnlyContentResources'],
3910
+ '@hydranium/client-theia/browser',
3911
+ columnsFor(composition)
3912
+ ),
3913
+ ...(data
3914
+ ? [
3915
+ "import { bindDataConnection } from '@hydranium/data-client-theia/browser';",
3916
+ "import { CommandContribution } from '@theia/core';"
3917
+ ]
3918
+ : []),
3919
+ "import { ContainerModule } from '@theia/core/shared/inversify';",
3920
+ ...(data
3921
+ ? [
3922
+ `import { ${name}DataConnection } from './${id}-data-connection.js';`,
3923
+ `import { ${name}DataPort } from './${id}-data-port.js';`
3924
+ ]
3925
+ : []),
3926
+ ...(glsp ? [`import { ${name}GlspClientContribution } from './${id}-glsp-client-contribution.js';`] : []),
3927
+ ...(data ? [`import { ${name}ShowModelCommand } from './${id}-show-model-command.js';`] : [])
3928
+ ];
3929
+ const dataBlock = data
3930
+ ? `
3931
+
3932
+ // The data head: one connection, opened when the command first runs.
3933
+ bind(${name}DataPort).toSelf().inSingletonScope();
3934
+ bindDataConnection(bind, isBound, ${name}DataConnection);
3935
+ bind(${name}ShowModelCommand).toSelf().inSingletonScope();
3936
+ bind(CommandContribution).toService(${name}ShowModelCommand);`
3937
+ : '';
3938
+ const glspBlock = glsp
3939
+ ? `
3940
+
3941
+ // One GLSP client for every diagram, so each diagram module skips binding its own.
3942
+ bind(${name}GlspClientContribution).toSelf().inSingletonScope();
3943
+ bind(GLSPClientContribution).toService(${name}GlspClientContribution);`
3944
+ : '';
3945
+ return `${wrapComment(
3946
+ `The ${name} Theia extension's frontend: ${listPhrase([
3947
+ 'the connection’s lifecycle in an Output channel',
3948
+ 'a warning when an outage outlasts the offline buffer',
3949
+ 'editor disk sync',
3950
+ ...(data ? ['the data head’s connection and the Show Model command'] : []),
3951
+ ...(glsp ? ['the GLSP client the diagrams share'] : [])
3952
+ ])}.`
3953
+ )}
3954
+
3955
+ ${imports.join('\n')}
3956
+
3957
+ export default new ContainerModule((bind, _unbind, isBound, rebind) => {
3958
+ bindChannelLogger(bind, { channelName: '${name} Connection' });
3959
+ bindConnectionDiagnostics(bind);
3960
+ // Keeps an editor from writing over a file a head saved while it held the same text unsaved.
3961
+ bindEditorDiskSync(bind, isBound, rebind);
3962
+ bindReadOnlyContentResources(rebind);${dataBlock}${glspBlock}
3963
+ });
3964
+ `;
3965
+ }
3966
+
3967
+ /** The Theia extension's README. */
3968
+ function theiaReadme(composition: InitComposition): string {
3969
+ const id = composition.projectId;
3970
+ const data = composition.heads.includes('data');
3971
+ const glsp = composition.heads.includes('glsp');
3972
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
3973
+ const theiaApps = theiaApplicationPaths(composition);
3974
+ const intro = [
3975
+ `The ${composition.name} Theia extension: ${theiaParts(composition)}.`,
3976
+ socketHeads(composition).length > 0
3977
+ ? '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.'
3978
+ : 'The language client is not here: the application sideloads `../vscode-servers`, which starts the server.',
3979
+ theiaApps.length === 1 ? `The application in ${theiaApps[0]} runs it.` : `The applications in ${listPhrase(theiaApps)} run it.`
3980
+ ];
3981
+ const before = [...(socketHeads(composition).length > 0 ? ['protocol'] : []), ...(glsp ? ['client'] : [])];
3982
+ const lines = [
3983
+ `# ${memberPackageName(composition, 'theia')}`,
3984
+ '',
3985
+ ...wrapProse(intro.join(' ')),
3986
+ '',
3987
+ '```bash',
3988
+ 'npm run build # compile into lib/' +
3989
+ (before.length > 0 ? `; build the ${before.join(' and ')} package${before.length > 1 ? 's' : ''} first` : ''),
3990
+ '```',
3991
+ '',
3992
+ '## Layout',
3993
+ '',
3994
+ `- \`src/browser/${id}-connection-preload-module.ts\` and \`src/node/${id}-connection-backend-module.ts\` — reconnect hardening, sized by the application’s \`connectionBufferBytes\``,
3995
+ `- \`src/browser/${id}-frontend-module.ts\` — the frontend bindings`,
3996
+ ...(data
3997
+ ? [
3998
+ `- \`src/browser/${id}-data-port.ts\` and \`${id}-data-connection.ts\` — the data head’s connection`,
3999
+ `- \`src/browser/${id}-show-model-command.ts\` — \`${composition.name}: Show Model\`, reading the current file through the data head`,
4000
+ `- \`src/node/${id}-data-backend-module.ts\` — forwards the data channel to the data head’s port`
4001
+ ]
4002
+ : []),
4003
+ ...(glsp
4004
+ ? [
4005
+ `- \`src/common/${id}-glsp-contribution.ts\` — the id the GLSP client and its forwarder share`,
4006
+ `- \`src/browser/${id}-glsp-client-contribution.ts\` — the GLSP client every diagram shares`,
4007
+ `- \`src/node/${id}-glsp-backend-module.ts\` — forwards the GLSP channel to the GLSP head’s port`
4008
+ ]
4009
+ : []),
4010
+ ...diagrams.map(
4011
+ grammar =>
4012
+ `- \`src/browser/${grammar.grammarId}-diagram-frontend-module.ts\` — the \`${grammar.grammar}\` diagram editor, over the client package’s diagram`
4013
+ ),
4014
+ ...(diagrams.length > 0 ? ['- `style/diagram.css` — the diagrams’ colours, from the Theia theme'] : []),
4015
+ ''
4016
+ ];
4017
+ return project(lines.join('\n'), composition);
4018
+ }
4019
+
4020
+ /** The Theia extension: what a Theia application runs of the language, beside the sideloaded servers extension. */
4021
+ function theiaFiles(composition: InitComposition): InitFile[] {
4022
+ const fixed = (file: string): InitFile => ({
4023
+ path: project(`theia/${file}`, composition),
4024
+ content: project(template(`theia/${file}`), composition)
4025
+ });
4026
+ const id = composition.projectId;
4027
+ const data = composition.heads.includes('data');
4028
+ const glsp = composition.heads.includes('glsp');
4029
+ const diagrams = composition.grammars.filter(grammar => grammar.diagram);
4030
+ return [
4031
+ { path: 'theia/package.json', content: theiaPackageJson(composition) },
4032
+ ignoreFile('theia'),
4033
+ { path: 'theia/README.md', content: theiaReadme(composition) },
4034
+ fixed('tsconfig.json'),
4035
+ fixed('src/browser/__PROJECT_ID__-connection-preload-module.ts'),
4036
+ { path: `theia/src/browser/${id}-frontend-module.ts`, content: theiaFrontendModuleFile(composition) },
4037
+ fixed('src/node/__PROJECT_ID__-connection-backend-module.ts'),
4038
+ ...(data
4039
+ ? [
4040
+ fixed('src/browser/__PROJECT_ID__-data-port.ts'),
4041
+ fixed('src/browser/__PROJECT_ID__-data-connection.ts'),
4042
+ fixed('src/browser/__PROJECT_ID__-show-model-command.ts'),
4043
+ fixed('src/node/__PROJECT_ID__-data-backend-module.ts')
4044
+ ]
4045
+ : []),
4046
+ ...(glsp
4047
+ ? [
4048
+ fixed('src/common/__PROJECT_ID__-glsp-contribution.ts'),
4049
+ fixed('src/browser/__PROJECT_ID__-glsp-client-contribution.ts'),
4050
+ fixed('src/node/__PROJECT_ID__-glsp-backend-module.ts')
4051
+ ]
4052
+ : []),
4053
+ ...diagrams.map(grammar => grammarTemplate('theia/src/browser/__GRAMMAR_ID__-diagram-frontend-module.ts', composition, grammar)),
4054
+ ...(diagrams.length > 0 ? [fixed('style/diagram.css')] : [])
4055
+ ];
4056
+ }
4057
+
4058
+ /**
4059
+ * The Theia application's `package.json`. Always private, as every host is.
4060
+ *
4061
+ * Theia's default `frontendConnectionTimeout` of 0 ends the session on any
4062
+ * dropped socket, and the page reloads; a minute lets the reconnect hardening
4063
+ * resume it.
4064
+ */
4065
+ function hostTheiaBrowserPackageJson(composition: InitComposition): string {
4066
+ const dependencies: Record<string, string> = {
4067
+ [memberPackageName(composition, 'theia')]: MEMBER_PIN,
4068
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEPENDENCIES.map(name => [name, THEIA_VERSION]))
4069
+ };
4070
+ const devDependencies: Record<string, string> = {
4071
+ // Built before this application, whose start links it into plugins/.
4072
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
4073
+ '@playwright/test': '^1.55.0',
4074
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEV_DEPENDENCIES.map(name => [name, THEIA_VERSION])),
4075
+ '@types/node': '^22.0.0',
4076
+ rimraf: '^5.0.0',
4077
+ typescript: '^7.0.2'
4078
+ };
4079
+ const theia = {
4080
+ target: 'browser',
4081
+ frontend: {
4082
+ config: {
4083
+ applicationName: composition.name,
4084
+ connectionBufferBytes: 102400,
4085
+ preferences: { 'security.workspace.trust.enabled': false }
4086
+ }
4087
+ },
4088
+ backend: { config: { connectionBufferBytes: 102400, frontendConnectionTimeout: 60000 } }
4089
+ };
4090
+ return `{
4091
+ "name": "${memberPackageName(composition, 'host-theia-browser')}",
4092
+ "version": "0.0.0",
4093
+ "private": true,
4094
+ "description": "${composition.name} in a Theia browser application: the Theia extension, and the servers extension sideloaded for the language client.",
4095
+ "license": "UNLICENSED",
4096
+ "author": "",
4097
+ "scripts": {
4098
+ "build": "theia build --mode development && npm run typecheck",
4099
+ "clean": "rimraf lib src-gen plugins gen-esbuild.browser.mjs gen-esbuild.node.mjs smoke-workspace test-results playwright-report",
4100
+ ${lintScript(forMember(composition, 'host-theia-browser'), 'test')} "start": "node start.mjs",
4101
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
4102
+ "test:e2e:install": "playwright install chromium",
4103
+ "typecheck": "tsc --noEmit -p tsconfig.e2e.json",
4104
+ "watch": "theia build --watch --mode development"
4105
+ },
4106
+ "dependencies": {
4107
+ ${sortedBlock(dependencies, ' ')}
4108
+ },
4109
+ "devDependencies": {
4110
+ ${sortedBlock(devDependencies, ' ')}
4111
+ },
4112
+ "engines": {
4113
+ "node": ">=22.13"
4114
+ },
4115
+ "theia": ${jsonAt(theia, ' ')}
4116
+ }
4117
+ `;
4118
+ }
4119
+
4120
+ /**
4121
+ * The Theia smoke test: the application opens a copy of the starter
4122
+ * workspace, and each head answers. The steps are the same in both
4123
+ * applications; the browser one's page is Chromium on the server the
4124
+ * configuration starts, the Electron one's the window the test launches.
4125
+ */
4126
+ function theiaSmokeSpec(composition: InitComposition, target: 'browser' | 'electron'): string {
4127
+ const data = composition.heads.includes('data');
4128
+ const diagram = composition.grammars.find(grammar => grammar.diagram);
4129
+ const primary = diagram ?? composition.grammars[0];
4130
+ const file = `nodes.${primary.extensions[0]}`;
4131
+ const showModelSteps = data
4132
+ ? `
4133
+ // The data head reads the open file, with focus in the Explorer beside it.
4134
+ await page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' }).click();
4135
+ await expect(page.locator('.theia-FileTree:focus-within')).toHaveCount(1);
4136
+ await runCommand(page, '${composition.name}: Show Model');
4137
+ // \`first()\`: Theia lists a notification in its toast and in the notification centre.
4138
+ await expect(
4139
+ page.locator('.theia-notification-message').filter({ hasText: '${file} holds a ${primary.entryRule}' }).first()
4140
+ ).toBeVisible();
4141
+ `
4142
+ : '';
4143
+ const diagramSteps = diagram
4144
+ ? `
4145
+ // The diagram file opens in its diagram, which draws the two starter nodes.
4146
+ // In the editor's copy: sprotty measures shapes in a hidden one on the page.
4147
+ await expect(page.locator('.sprotty:not(.sprotty-hidden) .sprotty-node')).toHaveCount(2);
4148
+ `
4149
+ : '';
4150
+ const textSteps = diagram
4151
+ ? ` // Then as text, through the Explorer's Open With.
4152
+ await page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' }).click({ button: 'right' });
4153
+ await page.locator('.lm-Menu-item', { hasText: 'Open With...' }).click();
4154
+ await page.locator('.quick-input-list .monaco-list-row', { hasText: 'Text Editor' }).click();
4155
+ `
4156
+ : '';
4157
+ return `${wrapComment(
4158
+ `Theia opens a copy of the starter workspace with this application's extensions, ${listPhrase([
4159
+ ...(diagram ? ['the diagram file draws in its diagram editor'] : []),
4160
+ ...(data ? ['the data head reads the file'] : []),
4161
+ 'the server reports a reference that resolves to nothing'
4162
+ ])}.`
4163
+ )}
4164
+
4165
+ ${target === 'browser' ? "import { expect, test, type Page } from '@playwright/test';\n" : theiaElectronSmokeFixture(composition)}
4166
+ test('${listPhrase([...(diagram ? ['draws the diagram'] : []), ...(data ? ['reads the model'] : []), 'reports a broken reference'])}', async ({ page }) => {
4167
+ ${target === 'browser' ? " await page.goto('/');\n" : ''} // Up once the loading screen is gone; a key pressed before then is lost.
4168
+ await expect(page.locator('.theia-preload')).toHaveCount(0);
4169
+ await page.keyboard.press('ControlOrMeta+Shift+E');
4170
+ await expect(page.locator('.theia-FileTree .theia-TreeNode', { hasText: '${file}' })).toBeVisible();
4171
+ await quickOpen(page, '${file}');
4172
+ ${diagramSteps}${showModelSteps}
4173
+ ${textSteps} const editor = page.locator('.monaco-editor .view-lines').first();
4174
+ await expect(editor).toContainText('node First');
4175
+ await editor.click();
4176
+ await page.keyboard.press('ControlOrMeta+End');
4177
+ // In one edit: typed key by key, the half-typed reference is reported on the way.
4178
+ await page.keyboard.insertText('\\nnode Broken -> Missing');
4179
+ await expect(page.locator('.monaco-editor .squiggly-error').first()).toBeVisible();
4180
+ });
4181
+
4182
+ /** Open \`file\` through Quick Open, so it gets the editor a user would. */
4183
+ async function quickOpen(page: Page, file: string): Promise<void> {
4184
+ await page.keyboard.press('ControlOrMeta+P');
4185
+ const input = page.locator('.quick-input-widget input');
4186
+ await input.fill(file);
4187
+ await expect(page.locator('.quick-input-list .monaco-list-row').first()).toContainText(file);
4188
+ await input.press('Enter');
4189
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
4190
+ }
4191
+ ${
4192
+ data
4193
+ ? `
4194
+ /** Run the command whose palette entry reads \`label\`, checked before Enter, since the match is fuzzy. */
4195
+ async function runCommand(page: Page, label: string): Promise<void> {
4196
+ await page.keyboard.press('F1');
4197
+ const input = page.locator('.quick-input-widget input');
4198
+ await input.fill(\`>\${label}\`);
4199
+ await expect(page.locator('.quick-input-list .monaco-list-row.focused')).toContainText(label);
4200
+ await input.press('Enter');
4201
+ await expect(page.locator('.quick-input-widget')).toBeHidden();
4202
+ }
4203
+ `
4204
+ : ''
4205
+ }`;
4206
+ }
4207
+
4208
+ /** The Theia application's README. */
4209
+ function hostTheiaBrowserReadme(composition: InitComposition): string {
4210
+ const intro = [
4211
+ `${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.`,
4212
+ 'The backend runs the server, so this is a Node application; Theia serves the page.',
4213
+ ...(composition.grammars.some(grammar => grammar.diagram)
4214
+ ? ['The servers extension contributes no editor, so a diagram file opens in the Theia diagram editor alone.']
4215
+ : [])
4216
+ ];
4217
+ const lines = [
4218
+ `# ${memberPackageName(composition, 'host-theia-browser')}`,
4219
+ '',
4220
+ ...wrapProse(intro.join(' ')),
4221
+ '',
4222
+ '```bash',
4223
+ 'npm run build # bundle and type-check; build the members first',
4224
+ 'npm run watch # rebundle whenever the members’ builds change; reload the page to pick it up',
4225
+ 'npm start # Theia at http://localhost:3000 on ../workspace; THEIA_PORT picks another port',
4226
+ 'npm run test:e2e:install # download the Chromium the smoke test drives, once',
4227
+ 'npm run test:e2e # the smoke test, which starts the application itself',
4228
+ '```',
4229
+ '',
4230
+ ...wrapProse(
4231
+ '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.'
4232
+ ),
4233
+ '',
4234
+ '## Layout',
4235
+ '',
4236
+ '- `esbuild.mjs` — the bundling `theia build` runs. It keeps this file, so it is the place to adjust the bundle',
4237
+ '- `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`',
4238
+ '- `playwright.config.mts` — the smoke tier, on port 4938 or `THEIA_PORT`, on a copy of `../workspace` in `smoke-workspace/`',
4239
+ '- `test/smoke.spec.mts` — Theia opens the workspace and each head answers',
4240
+ ''
4241
+ ];
4242
+ return project(lines.join('\n'), composition);
4243
+ }
4244
+
4245
+ /** The Theia browser application: the Theia extension and the sideloaded servers extension. */
4246
+ function hostTheiaBrowserFiles(composition: InitComposition): InitFile[] {
4247
+ const fixed = (file: string): InitFile => projectTemplate(`host-theia-browser/${file}`, composition);
4248
+ return [
4249
+ { path: 'host-theia-browser/package.json', content: hostTheiaBrowserPackageJson(composition) },
4250
+ ignoreFile('host-theia-browser'),
4251
+ { path: 'host-theia-browser/README.md', content: hostTheiaBrowserReadme(composition) },
4252
+ fixed('esbuild.mjs'),
4253
+ fixed('start.mjs'),
4254
+ fixed('playwright.config.mts'),
4255
+ fixed('tsconfig.e2e.json'),
4256
+ { path: 'host-theia-browser/test/smoke.spec.mts', content: theiaSmokeSpec(composition, 'browser') }
4257
+ ];
4258
+ }
4259
+
4260
+ /**
4261
+ * The Electron smoke test's imports and its `page`: the application's window,
4262
+ * launched by the test on a scratch copy of the workspace.
4263
+ */
4264
+ function theiaElectronSmokeFixture(composition: InitComposition): string {
4265
+ return `import { expect, test as base, type ElectronApplication, type Page } from '@playwright/test';
4266
+ import { once } from 'node:events';
4267
+ import { cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs';
4268
+ import { tmpdir } from 'node:os';
4269
+ import { join } from 'node:path';
4270
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4271
+
4272
+ /**
4273
+ * The application in Electron, on a copy of the starter workspace, since the
4274
+ * server writes its repairs to the folder it opens, with a profile of its own:
4275
+ * Theia quits at once while another window holds one. Its settings are its own
4276
+ * too, so a run never writes \`~/.theia/settings.json\`.
4277
+ */
4278
+ const test = base.extend<{ page: Page }>({
4279
+ page: async ({ playwright }, use) => {
4280
+ const scratch = mkdtempSync(join(tmpdir(), '${composition.projectId}-theia-electron-'));
4281
+ const workspace = join(scratch, 'workspace');
4282
+ // The servers extension, sideloaded from a plugins folder as \`npm start\` does.
4283
+ const plugins = join(scratch, 'plugins');
4284
+ const link = join(plugins, '${composition.projectId}-vscode-servers');
4285
+ let app: ElectronApplication | undefined;
4286
+ try {
4287
+ cpSync(fileURLToPath(new URL('../../workspace', import.meta.url)), workspace, { recursive: true });
4288
+ mkdirSync(plugins);
4289
+ symlinkSync(fileURLToPath(new URL('../../vscode-servers', import.meta.url)), link, 'junction');
4290
+ // Playwright resolves Electron itself; given its path, Theia opens this
4291
+ // folder instead of the workspace.
4292
+ app = await playwright._electron.launch({
4293
+ args: [
4294
+ fileURLToPath(new URL('..', import.meta.url)),
4295
+ '--no-sandbox',
4296
+ \`--user-data-dir=\${join(scratch, 'user-data')}\`,
4297
+ // In URI form, since Theia reads the argument as a URI.
4298
+ \`--plugins=local-dir:\${pathToFileURL(plugins).pathname}\`,
4299
+ workspace
4300
+ ],
4301
+ env: {
4302
+ ...process.env,
4303
+ THEIA_CONFIG_DIR: join(scratch, 'config'),
4304
+ // Menus drawn in the page, where the test can click them.
4305
+ THEIA_ELECTRON_DISABLE_NATIVE_ELEMENTS: '1'
4306
+ }
4307
+ });
4308
+ await use(await app.firstWindow());
4309
+ } finally {
4310
+ try {
4311
+ // Exited, not closed: closing asks whether to save the edited file. An
4312
+ // app that is already gone is left alone, so the test's own error stands.
4313
+ const child = app?.process();
4314
+ if (app && child?.exitCode === null && child.signalCode === null) {
4315
+ const exited = once(child, 'exit');
4316
+ await app.evaluate(({ app: electron }) => electron.exit(0));
4317
+ await exited;
4318
+ }
4319
+ } finally {
4320
+ // Unlinked first, so the remove never reaches \`../vscode-servers\` through it.
4321
+ rmSync(link, { force: true });
4322
+ rmSync(scratch, { recursive: true, force: true });
4323
+ }
4324
+ }
4325
+ }
4326
+ });
4327
+ `;
4328
+ }
4329
+
4330
+ /**
4331
+ * The Theia Electron application's `package.json`: the browser application's
4332
+ * `theia` block with the Electron target. Always private, as every host is.
4333
+ */
4334
+ function hostTheiaElectronPackageJson(composition: InitComposition): string {
4335
+ const dependencies: Record<string, string> = {
4336
+ [memberPackageName(composition, 'theia')]: MEMBER_PIN,
4337
+ ...Object.fromEntries(HOST_THEIA_ELECTRON_DEPENDENCIES.map(name => [name, THEIA_VERSION]))
4338
+ };
4339
+ const devDependencies: Record<string, string> = {
4340
+ // Built before this application, whose start links it into plugins/.
4341
+ [memberPackageName(composition, 'vscode-servers')]: MEMBER_PIN,
4342
+ '@playwright/test': '^1.55.0',
4343
+ ...Object.fromEntries(HOST_THEIA_BROWSER_DEV_DEPENDENCIES.map(name => [name, THEIA_VERSION])),
4344
+ '@types/node': '^22.0.0',
4345
+ electron: ELECTRON_VERSION,
4346
+ rimraf: '^5.0.0',
4347
+ typescript: '^7.0.2'
4348
+ };
4349
+ const theia = {
4350
+ target: 'electron',
4351
+ frontend: {
4352
+ config: {
4353
+ applicationName: composition.name,
4354
+ connectionBufferBytes: 102400,
4355
+ preferences: { 'security.workspace.trust.enabled': false }
4356
+ }
4357
+ },
4358
+ backend: { config: { connectionBufferBytes: 102400, frontendConnectionTimeout: 60000 } }
4359
+ };
4360
+ return `{
4361
+ "name": "${memberPackageName(composition, 'host-theia-electron')}",
4362
+ "version": "0.0.0",
4363
+ "private": true,
4364
+ "description": "${composition.name} in a Theia Electron application: the Theia extension, and the servers extension sideloaded for the language client.",
4365
+ "license": "UNLICENSED",
4366
+ "author": "",
4367
+ "main": "lib/backend/electron-main.js",
4368
+ "scripts": {
4369
+ "build": "theia build --mode development && npm run typecheck",
4370
+ "clean": "rimraf lib src-gen plugins gen-esbuild.browser.mjs gen-esbuild.electron.mjs gen-esbuild.node.mjs test-results playwright-report",
4371
+ ${lintScript(forMember(composition, 'host-theia-electron'), 'test')} "start": "node start.mjs",
4372
+ "test:e2e": "playwright test --tsconfig tsconfig.e2e.json",
4373
+ "typecheck": "tsc --noEmit -p tsconfig.e2e.json",
4374
+ "watch": "theia build --watch --mode development"
4375
+ },
4376
+ "dependencies": {
4377
+ ${sortedBlock(dependencies, ' ')}
4378
+ },
4379
+ "devDependencies": {
4380
+ ${sortedBlock(devDependencies, ' ')}
4381
+ },
4382
+ "engines": {
4383
+ "node": ">=22.13"
4384
+ },
4385
+ "theia": ${jsonAt(theia, ' ')}
4386
+ }
4387
+ `;
4388
+ }
4389
+
4390
+ /** The Theia Electron application's README. */
4391
+ function hostTheiaElectronReadme(composition: InitComposition): string {
4392
+ const intro = [
4393
+ `${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.`,
4394
+ 'Electron runs the window, and a backend process it starts runs the server.',
4395
+ ...(composition.grammars.some(grammar => grammar.diagram)
4396
+ ? ['The servers extension contributes no editor, so a diagram file opens in the Theia diagram editor alone.']
4397
+ : [])
4398
+ ];
4399
+ const lines = [
4400
+ `# ${memberPackageName(composition, 'host-theia-electron')}`,
4401
+ '',
4402
+ ...wrapProse(intro.join(' ')),
4403
+ '',
4404
+ '```bash',
4405
+ 'npm run build # bundle and type-check, and download Electron; build the members first',
4406
+ 'npm run watch # rebundle whenever the members’ builds change; reload the window to pick it up',
4407
+ 'npm start # the application on ../workspace',
4408
+ 'npm run test:e2e # the smoke test, which launches the application itself',
4409
+ '```',
4410
+ '',
4411
+ ...wrapProse(
4412
+ '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.'
4413
+ ),
4414
+ '',
4415
+ ...wrapProse(
4416
+ '`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.'
4417
+ ),
4418
+ '',
4419
+ '## Layout',
4420
+ '',
4421
+ '- `esbuild.mjs` — the bundling `theia build` runs. It keeps this file, so it is the place to adjust the bundle',
4422
+ '- `start.mjs` — `npm start`: links `../vscode-servers` into `plugins/`, then starts the application on a folder given as its argument or `../workspace`',
4423
+ '- `playwright.config.mts` — the smoke tier',
4424
+ '- `test/smoke.spec.mts` — Electron opens a copy of the workspace with a profile of its own, and each head answers',
4425
+ ''
4426
+ ];
4427
+ return project(lines.join('\n'), composition);
4428
+ }
4429
+
4430
+ /** The Theia Electron application: the browser application's extensions in a desktop window. */
4431
+ function hostTheiaElectronFiles(composition: InitComposition): InitFile[] {
4432
+ const fixed = (file: string): InitFile => projectTemplate(`host-theia-electron/${file}`, composition);
4433
+ return [
4434
+ { path: 'host-theia-electron/package.json', content: hostTheiaElectronPackageJson(composition) },
4435
+ ignoreFile('host-theia-electron'),
4436
+ { path: 'host-theia-electron/README.md', content: hostTheiaElectronReadme(composition) },
4437
+ fixed('esbuild.mjs'),
4438
+ fixed('start.mjs'),
4439
+ fixed('playwright.config.mts'),
4440
+ fixed('tsconfig.e2e.json'),
4441
+ { path: 'host-theia-electron/test/smoke.spec.mts', content: theiaSmokeSpec(composition, 'electron') }
4442
+ ];
4443
+ }
4444
+
4445
+ /**
4446
+ * The formatter and linter a standalone root runs. Exact, because a formatter
4447
+ * release that changes its output would fail the project's `format:check`.
4448
+ */
4449
+ const ROOT_STYLE_DEV_DEPENDENCIES: Readonly<Record<string, string>> = { oxfmt: '0.71.0', oxlint: '1.82.0' };
4450
+
4451
+ /**
4452
+ * The standalone root's formatter config: the style every template is written
4453
+ * in, at the width the emitted sources wrap at. Generated code is ignored
4454
+ * because each run of its generator rewrites it in that generator's style.
4455
+ */
4456
+ function oxfmtConfig(composition: InitComposition): string {
4457
+ return `{
4458
+ "$schema": "./node_modules/oxfmt/configuration_schema.json",
4459
+ "arrowParens": "avoid",
4460
+ "endOfLine": "lf",
4461
+ "ignorePatterns": ["**/generated", "**/generated-hydranium", "**/syntaxes", "**/*.md"],
4462
+ "jsxSingleQuote": true,
4463
+ "printWidth": ${columnsFor(composition)},
4464
+ "singleQuote": true,
4465
+ "sortPackageJson": true,
4466
+ "tabWidth": 3,
4467
+ "trailingComma": "none",
4468
+ "overrides": [
4469
+ {
4470
+ "files": ["*.json", "*.yml", "*.yaml"],
4471
+ "options": {
4472
+ "printWidth": 100,
4473
+ "tabWidth": 2
4474
+ }
4475
+ }
4476
+ ]
4477
+ }
4478
+ `;
4479
+ }
4480
+
4481
+ /**
4482
+ * A standalone project's root: the members as npm workspaces.
4483
+ *
4484
+ * Always private: it is never published, whatever `--public` makes of the
4485
+ * members. npm runs a script across the members in the order listed here, not
4486
+ * by their dependencies; listing protocol first is safe because its `build`
4487
+ * runs the server's `generate` before compiling.
4488
+ *
4489
+ * It declares the exact pins `--monorepo` prints for a workspace root, for the
4490
+ * same reason: a package ranging over one, such as a framework package's peer,
4491
+ * otherwise takes the top of the tree with the newest match, and each member's
4492
+ * exact copy nests beneath it.
4493
+ *
4494
+ * `watch` keeps every non-host member built; `watch:<host>` adds one host, so
4495
+ * only the bundler of the host being worked on runs.
4496
+ *
4497
+ * `format` and `lint` run at the root over every member, which is why the
4498
+ * members get no `lint` of their own here.
4499
+ */
4500
+ function rootFiles(composition: InitComposition): InitFile[] {
4501
+ const devDependencies = {
4502
+ ...Object.fromEntries(workspaceRootPins(composition)),
4503
+ concurrently: '^9.0.0',
4504
+ ...ROOT_STYLE_DEV_DEPENDENCIES
4505
+ };
4506
+ const members = initMembers(composition.heads, composition.hosts);
4507
+ // Only the server's watch is `tsc -b`, so protocol is built by one process
4508
+ // rather than two writing the same `lib/`; a host's watch joins only in its
4509
+ // own `watch:<host>`.
4510
+ const watched = members.filter(member => member !== 'protocol' && !member.startsWith('host-'));
4511
+ const parallel = (commands: Readonly<Record<string, string>>): string =>
4512
+ `concurrently --kill-others --names ${Object.keys(commands).join(',')} ${Object.values(commands)
4513
+ .map(command => `\\"${command}\\"`)
4514
+ .join(' ')}`;
4515
+ const scripts: Record<string, string> = {
4516
+ build: 'npm run build --workspaces',
4517
+ clean: 'npm run clean --workspaces --if-present',
4518
+ format: 'oxfmt',
4519
+ 'format:check': 'oxfmt --check',
4520
+ lint: 'oxlint --report-unused-disable-directives --max-warnings 0',
4521
+ ...Object.fromEntries(composition.hosts.map(host => [`start:${host}`, `npm --prefix host-${host} start`])),
4522
+ test: 'npm test --workspaces --if-present',
4523
+ watch: parallel(Object.fromEntries(watched.map(member => [member, `npm --prefix ${member} run watch`]))),
4524
+ // The browser host's `start` is its watch: it rebundles the page as it serves it.
4525
+ ...Object.fromEntries(
4526
+ composition.hosts.map(host => [
4527
+ `watch:${host}`,
4528
+ parallel({
4529
+ watch: 'npm run watch',
4530
+ [`host-${host}`]: `npm --prefix host-${host} ${host === 'browser' ? 'start' : 'run watch'}`
4531
+ })
4532
+ ])
4533
+ )
4534
+ };
4535
+ const content = `{
4536
+ "name": "${composition.projectId}-root",
4537
+ "version": "0.0.0",
4538
+ "private": true,
4539
+ "workspaces": [
4540
+ ${members.map(member => ` "${member}"`).join(',\n')}
4541
+ ],
4542
+ "scripts": {
4543
+ ${Object.entries(scripts)
4544
+ .map(([name, command]) => ` "${name}": "${command}"`)
4545
+ .join(',\n')}
4546
+ },
4547
+ "devDependencies": {
4548
+ ${sortedBlock(devDependencies, ' ')}
4549
+ },
4550
+ "engines": {
4551
+ "node": ">=22.13"
4552
+ },
4553
+ "hydranium": {
4554
+ "services": "./server/lib/node/services.js"
4555
+ }
4556
+ }
4557
+ `;
4558
+ return [
4559
+ { path: 'package.json', content },
4560
+ ignoreFile(''),
4561
+ { path: '.editorconfig', content: template('editorconfig') },
4562
+ { path: '.oxfmtrc.json', content: oxfmtConfig(composition) },
4563
+ { path: '.oxlintrc.json', content: template('oxlintrc.json') }
4564
+ ];
4565
+ }
4566
+
4567
+ /**
4568
+ * Every file the scaffold emits, fully rendered, at its path in the project
4569
+ * directory. A workspace member's project gets no root of its own: it joins the
4570
+ * surrounding workspace, whose manifest `init` prints the changes for.
4571
+ */
4572
+ export function buildInitTemplates(composition: InitComposition): InitFile[] {
4573
+ return [
4574
+ ...(composition.packaging.workspace === undefined ? rootFiles(composition) : []),
4575
+ ...protocolFiles(composition),
4576
+ ...serverFiles(composition),
4577
+ ...(composition.heads.includes('glsp') ? clientFiles(composition) : []),
4578
+ ...(emitsVscodeServers(composition) ? vscodeServersFiles(composition) : []),
4579
+ ...(composition.hosts.some(isTheiaHost) ? theiaFiles(composition) : []),
4580
+ ...(composition.hosts.includes('browser') ? hostBrowserFiles(composition) : []),
4581
+ ...(composition.hosts.includes('vscode') ? hostVscodeFiles(composition) : []),
4582
+ ...(composition.hosts.includes('theia-browser') ? hostTheiaBrowserFiles(composition) : []),
4583
+ ...(composition.hosts.includes('theia-electron') ? hostTheiaElectronFiles(composition) : []),
4584
+ ...workspaceFiles(composition)
2070
4585
  ];
2071
4586
  }