@akanjs/devkit 3.3.0-rc.3 → 3.3.0-rc.30

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 (229) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanApp/akanApp.host.ts +11 -0
  7. package/akanConfig/akanBin.ts +4 -0
  8. package/akanConfig/akanConfig.test.ts +66 -7
  9. package/akanConfig/akanConfig.ts +53 -204
  10. package/akanConfig/akanWorkers.test.ts +39 -0
  11. package/akanConfig/akanWorkers.ts +32 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +37 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/akanConfig/types.ts +1 -0
  16. package/app/appBin.test.ts +63 -0
  17. package/app/appBin.ts +50 -0
  18. package/app/applicationBuildReporter.test.ts +32 -0
  19. package/app/applicationBuildReporter.ts +4 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +126 -5
  22. package/app/dictionarySizes.ts +94 -0
  23. package/artifact/implicitRootLayout.test.ts +19 -0
  24. package/artifact/implicitRootLayout.ts +16 -2
  25. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  26. package/artifact/storeBootstrap.test.ts +28 -0
  27. package/artifact/storeBootstrap.ts +60 -8
  28. package/biome.base.json +5 -1
  29. package/codeAgent/agent/CodeAgent.ts +36 -16
  30. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  31. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  32. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  33. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  34. package/codeAgent/agent/codeAgent.test.ts +62 -0
  35. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  36. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  37. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  38. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  39. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  40. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  41. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  42. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  43. package/codeAgent/skills/akan-page/SKILL.md +4 -14
  44. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  45. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  46. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  47. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  48. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  49. package/context/akanContext.ts +2 -0
  50. package/docs/apiReference.test.ts +9 -0
  51. package/docs/apiReference.ts +14 -0
  52. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  53. package/executors/clientRuntimeKeys.fixture.json +393 -0
  54. package/executors/clientRuntimeKeys.test.ts +1591 -0
  55. package/executors/executors.test.ts +2 -0
  56. package/executors/sysExecutor.ts +66 -3
  57. package/executors/workspaceExecutor.ts +7 -4
  58. package/frontendBuild/allRoutesBuilder.ts +72 -3
  59. package/frontendBuild/autoImportSync.ts +3 -2
  60. package/frontendBuild/buildRouteClient.test.ts +515 -12
  61. package/frontendBuild/clientBuildTypes.ts +15 -0
  62. package/frontendBuild/clientEntriesBundler.ts +38 -0
  63. package/frontendBuild/clientEntryDiscovery.test.ts +95 -1
  64. package/frontendBuild/clientEntryDiscovery.ts +88 -7
  65. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  66. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  67. package/frontendBuild/csrDevPatcher.ts +33 -7
  68. package/frontendBuild/csrDevTypes.ts +9 -0
  69. package/frontendBuild/devBarrelImports.test.ts +100 -0
  70. package/frontendBuild/devBarrelImports.ts +82 -23
  71. package/frontendBuild/devRegistryBundler.ts +4 -2
  72. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  73. package/frontendBuild/devRouteRuntime.ts +167 -0
  74. package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
  75. package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
  76. package/frontendBuild/dictionaryConstants.ts +82 -0
  77. package/frontendBuild/dictionaryPacking.test.ts +84 -0
  78. package/frontendBuild/dictionaryPacking.ts +92 -0
  79. package/frontendBuild/dictionaryRoutes.test.ts +186 -0
  80. package/frontendBuild/dictionaryRoutes.ts +225 -0
  81. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  82. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  83. package/frontendBuild/precompressArtifacts.ts +7 -0
  84. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  85. package/frontendBuild/routeClientBuilder.ts +288 -15
  86. package/frontendBuild/routeHandoffs.test.ts +145 -0
  87. package/frontendBuild/routeHandoffs.ts +115 -0
  88. package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
  89. package/frontendBuild/routeRuntimeCheck.ts +241 -0
  90. package/frontendBuild/routeRuntimePays.test.ts +137 -0
  91. package/frontendBuild/routeRuntimePays.ts +117 -0
  92. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  93. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  94. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  95. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  96. package/frontendBuild/ssrDevBundler.ts +66 -11
  97. package/frontendBuild/vendorFileImports.test.ts +254 -0
  98. package/frontendBuild/vendorFileImports.ts +163 -0
  99. package/frontendBuild/vendorNarrowing.ts +28 -0
  100. package/frontendBuild/vendorSpecifiers.ts +2 -0
  101. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  102. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  103. package/incrementalBuilder/builderBoot.ts +5 -5
  104. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  105. package/incrementalBuilder/builderLanes.ts +2 -2
  106. package/incrementalBuilder/builderWatch.ts +8 -8
  107. package/incrementalBuilder/csrRegistry.ts +4 -4
  108. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  109. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  110. package/incrementalBuilder/ssrRegistry.ts +6 -6
  111. package/index.ts +1 -1
  112. package/integration/renderAdmissionSoak.test.ts +99 -0
  113. package/integration/renderAdmissionSoak.ts +609 -0
  114. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  115. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  116. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  117. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  118. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  119. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  120. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  121. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  122. package/lint/biomeCheck.test.ts +145 -0
  123. package/lint/biomeCheck.ts +131 -0
  124. package/lint/no-arbitrary-color.grit +5 -0
  125. package/lint/no-conditional-st-hook.grit +5 -1
  126. package/lint/no-daisyui-legacy-class.grit +8 -0
  127. package/lint/no-document-cookie.grit +3 -0
  128. package/lint/no-inline-color.grit +10 -2
  129. package/lint/no-oversized-list-limit.grit +2 -0
  130. package/lint/no-raw-palette-class.grit +7 -0
  131. package/lint/no-unpublished-form-setter.grit +2 -0
  132. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  133. package/lint/no-web-storage.grit +3 -0
  134. package/lint/withheldEnvFile.ts +17 -0
  135. package/mobile/desktopBin.ts +2 -2
  136. package/mobile/desktopServerStage.ts +1 -0
  137. package/mobile/nativeApp.test.ts +7 -5
  138. package/mobile/nativeApp.ts +2 -2
  139. package/mobile/nativeConfig.test.ts +96 -1
  140. package/mobile/nativeConfig.ts +46 -12
  141. package/mobile/serverBundleSecrets.ts +43 -0
  142. package/package.json +15 -169
  143. package/packageExports.test.ts +38 -24
  144. package/quality/dictionaryKeys.test.ts +173 -0
  145. package/quality/dictionaryKeys.ts +415 -0
  146. package/quality/objectImportReport.test.ts +36 -0
  147. package/quality/objectImportReport.ts +102 -0
  148. package/quality/qualityScanner.ts +1 -1
  149. package/quality/routeRuntimeReport.test.ts +91 -0
  150. package/quality/routeRuntimeReport.ts +121 -0
  151. package/quality/runtimeConstantFacts.ts +71 -0
  152. package/quality/runtimeConstantGraph.ts +123 -0
  153. package/quality/runtimeConstantReads.ts +116 -0
  154. package/quality/runtimeImports.test.ts +190 -0
  155. package/quality/runtimeImports.ts +233 -0
  156. package/quality/runtimeKeyNames.ts +46 -0
  157. package/quality/runtimeLexicalScope.ts +132 -0
  158. package/quality/runtimeMarkerReach.test.ts +84 -0
  159. package/quality/runtimeMarkerReach.ts +255 -0
  160. package/quality/runtimeModuleFacts.ts +290 -0
  161. package/quality/runtimeNameTable.test.ts +172 -0
  162. package/quality/runtimeNameTable.ts +477 -0
  163. package/quality/runtimeScopeReport.test.ts +123 -0
  164. package/quality/runtimeScopeReport.ts +167 -0
  165. package/quality/runtimeSliceKey.ts +269 -0
  166. package/quality/runtimeSyntax.ts +133 -0
  167. package/quality/runtimeTable.fixture.ts +189 -0
  168. package/quality/runtimeUse.test.ts +737 -0
  169. package/quality/runtimeUse.ts +696 -0
  170. package/quality/runtimeUseReadable.test.ts +393 -0
  171. package/quality/ssrScanner.test.ts +13 -0
  172. package/quality/ssrScanner.ts +1 -1
  173. package/test/secretEnvFixture.ts +134 -0
  174. package/test/testHelpers.ts +11 -0
  175. package/transforms/barrelAnalyzer.ts +26 -4
  176. package/transforms/barrelImportsPlugin.ts +82 -14
  177. package/transforms/frameworkObjects.fixture.tsx +58 -0
  178. package/transforms/frameworkObjects.test.ts +54 -0
  179. package/transforms/modelReference.test.ts +196 -0
  180. package/transforms/modelReference.ts +39 -0
  181. package/transforms/objectImportEdits.ts +150 -0
  182. package/transforms/objectMemberImports.test.ts +347 -0
  183. package/transforms/objectMemberImports.ts +537 -0
  184. package/transforms/objectModule.test.ts +237 -0
  185. package/transforms/objectModule.ts +458 -0
  186. package/transforms/objectModuleAnalyzer.ts +104 -0
  187. package/transforms/reactIconImports.test.ts +231 -0
  188. package/transforms/reactIconImports.ts +325 -0
  189. package/transforms/routeConstants.ts +122 -0
  190. package/transforms/routeRuntime.test.ts +835 -0
  191. package/transforms/routeRuntime.ts +703 -0
  192. package/transforms/routeRuntimeEdits.ts +92 -0
  193. package/transforms/routeRuntimeGraph.ts +66 -0
  194. package/transforms/routeRuntimePlan.ts +244 -0
  195. package/transforms/secretEnvDeclaration.test.ts +208 -0
  196. package/transforms/secretEnvDeclaration.ts +213 -0
  197. package/transforms/secretEnvFile.test.ts +117 -0
  198. package/transforms/secretEnvFile.ts +113 -0
  199. package/transforms/secretEnvName.test.ts +54 -0
  200. package/transforms/secretEnvName.ts +29 -0
  201. package/transforms/secretEnvSource.test.ts +148 -0
  202. package/transforms/secretEnvSource.ts +166 -0
  203. package/transforms/serverEnvEvaluationError.ts +11 -0
  204. package/transforms/serverEnvPlugin.test.ts +2 -1
  205. package/transforms/serverEnvPlugin.ts +13 -0
  206. package/transforms/serverEnvProfile.test.ts +115 -2
  207. package/transforms/serverEnvProfile.ts +117 -40
  208. package/transforms/serverEnvSecrets.test.ts +292 -0
  209. package/transforms/signalDescriptors.test.ts +280 -0
  210. package/transforms/signalDescriptors.ts +227 -0
  211. package/transforms/thisFreeExports.ts +87 -0
  212. package/transforms/transforms.test.ts +180 -3
  213. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  214. package/tunnel/createTunnel.test.ts +29 -8
  215. package/tunnel/createTunnel.ts +18 -11
  216. package/typecheck/projectTypecheck.test.ts +29 -0
  217. package/typecheck/typeChecker.test.ts +49 -0
  218. package/typecheck/typeChecker.ts +9 -7
  219. package/typecheck/withheldDiagnostics.ts +41 -0
  220. package/util/fileEditor.ts +1 -0
  221. package/util/selectModel.ts +1 -0
  222. package/workflow/executor.ts +6 -2
  223. package/workflow/index.ts +1 -0
  224. package/workflow/plan.ts +36 -7
  225. package/workflow/types.ts +1 -1
  226. package/workflow/uiTarget.ts +50 -0
  227. package/workspace/getRelatedCnsts.ts +7 -0
  228. package/workspace/scanInfo.ts +1 -1
  229. package/workspace/workspaceLayout.ts +1 -0
@@ -1,4 +1,5 @@
1
1
  import { describe, expect, test } from "bun:test";
2
+ import { existsSync } from "node:fs";
2
3
  import { mkdir, readdir, writeFile } from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import type { App } from "../commandDecorators";
@@ -23,6 +24,117 @@ const makeApp = async (dictSource?: string) => {
23
24
 
24
25
  const dictSourceOf = (dictionary: object) => `export const getAllDictionary = () => (${JSON.stringify(dictionary)});\n`;
25
26
 
27
+ const workspaceRoot = path.resolve(import.meta.dir, "../../../..");
28
+ const i18n = { defaultLocale: "en", locales: ["en", "ko"] };
29
+
30
+ interface LocaleBuild {
31
+ whole: Record<string, Record<string, unknown>>;
32
+ page: Record<string, Record<string, unknown>>;
33
+ api: Record<string, Record<string, unknown>>;
34
+ parts: unknown;
35
+ apiUrl: string;
36
+ server: unknown;
37
+ }
38
+
39
+ //? In a process of its own: a sample app's `dict.ts` resolves `@libs/*` by the tsconfig its process read first.
40
+ const buildBothWays = async (cwdPath: string, outDir: string): Promise<Record<string, LocaleBuild>> => {
41
+ const script = `
42
+ import path from "node:path";
43
+ import { DictionaryAssetBuilder } from ${JSON.stringify(path.join(import.meta.dir, "dictionaryAssetBuilder.ts"))};
44
+ import { WebArtifact } from ${JSON.stringify(path.join(workspaceRoot, "pkgs/akanjs/server/webArtifact.ts"))};
45
+ import { TranslatorState } from ${JSON.stringify(path.join(workspaceRoot, "pkgs/akanjs/client/translatorState.ts"))};
46
+ const app = { cwdPath: ${JSON.stringify(cwdPath)}, verbose: () => undefined };
47
+ const i18n = ${JSON.stringify(i18n)};
48
+ const wholeDir = ${JSON.stringify(path.join(outDir, "whole"))};
49
+ const splitDir = ${JSON.stringify(path.join(outDir, "split"))};
50
+ const whole = await new DictionaryAssetBuilder(app, wholeDir).build(i18n);
51
+ const split = await new DictionaryAssetBuilder(app, splitDir).build(i18n, { splitApi: true });
52
+ await WebArtifact.seedDictionaries({ dictAssets: split }, splitDir);
53
+ const result = {};
54
+ for (const lang of i18n.locales) {
55
+ const page = await import(path.join(splitDir, split[lang].relPath));
56
+ result[lang] = {
57
+ whole: (await import(path.join(wholeDir, whole[lang].relPath))).default,
58
+ page: page.default,
59
+ parts: page.parts,
60
+ api: (await import(path.join(splitDir, split[lang].parts.api.relPath))).default,
61
+ apiUrl: split[lang].parts.api.url,
62
+ server: TranslatorState.get().langDictionaryMap.get(lang),
63
+ };
64
+ }
65
+ console.log(JSON.stringify(result));
66
+ `;
67
+ const proc = Bun.spawn([process.execPath, "-e", script], {
68
+ cwd: workspaceRoot,
69
+ env: {
70
+ ...process.env,
71
+ AKAN_PUBLIC_REPO_NAME: "repo",
72
+ AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
73
+ AKAN_PUBLIC_ENV: "local",
74
+ },
75
+ stdout: "pipe",
76
+ stderr: "pipe",
77
+ });
78
+ const [code, stdout, stderr] = await Promise.all([
79
+ proc.exited,
80
+ new Response(proc.stdout).text(),
81
+ new Response(proc.stderr).text(),
82
+ ]);
83
+ if (code !== 0) throw new Error(`the dictionary did not build:\n${stderr}`);
84
+ return JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") as Record<string, LocaleBuild>;
85
+ };
86
+
87
+ const isNode = (value: unknown): value is Record<string, unknown> =>
88
+ typeof value === "object" && value !== null && !Array.isArray(value);
89
+ const mergeOf = (target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown> =>
90
+ Object.fromEntries(
91
+ [...new Set([...Object.keys(target), ...Object.keys(source)])].map((key) => {
92
+ const [own, added] = [target[key], source[key]];
93
+ return [key, isNode(own) && isNode(added) ? mergeOf(own, added) : (added ?? own)];
94
+ }),
95
+ );
96
+ const signalEntriesOf = (dictionary: Record<string, Record<string, unknown>>) =>
97
+ Object.values(dictionary).flatMap((node) => (isNode(node.signal) ? Object.values(node.signal) : []));
98
+
99
+ const expectSplitOf = (build: LocaleBuild) => {
100
+ expect(mergeOf(build.page, build.api)).toEqual(build.whole);
101
+ expect(build.server).toEqual(build.whole);
102
+ expect(build.parts).toEqual({ api: build.apiUrl });
103
+ const pageEntries = signalEntriesOf(build.page).filter(isNode);
104
+ expect(pageEntries.length).toBeGreaterThan(0);
105
+ expect(pageEntries.filter((entry) => "desc" in entry || "arg" in entry)).toEqual([]);
106
+ expect(Object.values(build.api).every((node) => Object.keys(node).join() === "signal")).toBe(true);
107
+ const apiEntries = signalEntriesOf(build.api).filter(isNode);
108
+ expect(apiEntries.length).toBeGreaterThan(0);
109
+ expect(apiEntries.filter((entry) => Object.keys(entry).some((key) => key !== "desc" && key !== "arg"))).toEqual([]);
110
+ };
111
+
112
+ const libAndAppDictSource = (dictionaryIndex: string) => `
113
+ import { makeDictionary, makeTrans, registerServiceTrans, serviceDictionary } from ${JSON.stringify(dictionaryIndex)};
114
+ const libShop = serviceDictionary(["en", "ko"])
115
+ .endpoint((fn) => ({
116
+ order: fn(["Order", "주문"])
117
+ .desc(["Places an order", "주문한다"])
118
+ .arg((t) => ({ itemId: t(["Item", "상품"]).desc(["The item to order", "주문할 상품"]) })),
119
+ refund: fn(["Refund", "환불"]).desc(["Refunds an order", "주문을 환불한다"]),
120
+ }))
121
+ .translate({ title: ["Shop", "상점"] });
122
+ const libCart = serviceDictionary(["en"]).endpoint((fn) => ({
123
+ addItem: fn(["Add Item"]).desc(["Adds an item to the cart"]).arg((t) => ({ itemId: t(["Item"]) })),
124
+ }));
125
+ const appShop = serviceDictionary(["en", "ko"])
126
+ .endpoint((fn) => ({
127
+ order: fn(["Order now", "바로 주문"])
128
+ .desc(["Places an order at once", "바로 주문한다"])
129
+ .arg((t) => ({ coupon: t(["Coupon", "쿠폰"]).desc(["A coupon code", "쿠폰 코드"]) })),
130
+ track: fn(["Track", "배송 조회"]),
131
+ }))
132
+ .translate({ title: ["My shop", "내 상점"] });
133
+ const lib = makeDictionary({ shop: registerServiceTrans(libShop), cart: registerServiceTrans(libCart) });
134
+ export const dictionary = makeDictionary(lib, { shop: registerServiceTrans(appShop) });
135
+ export const { getAllDictionary } = makeTrans(dictionary);
136
+ `;
137
+
26
138
  describe("DictionaryAssetBuilder", () => {
27
139
  test("writes one module per locale, the default locale's text filled into the gaps", async () => {
28
140
  const { app, artifactDir } = await makeApp(dictSourceOf(allDictionary));
@@ -68,6 +180,210 @@ describe("DictionaryAssetBuilder", () => {
68
180
  );
69
181
  });
70
182
 
183
+ test("writes a locale's file as it always did when the API descriptions are not split out", async () => {
184
+ const { app, artifactDir } = await makeApp(dictSourceOf(allDictionary));
185
+ const assets = await new DictionaryAssetBuilder(app, artifactDir).build({ defaultLocale: "en", locales: ["en"] });
186
+
187
+ expect(assets.en.parts).toBeUndefined();
188
+ expect(await Bun.file(path.join(artifactDir, assets.en.relPath)).text()).toBe(
189
+ `export const lang = "en";\nexport default JSON.parse(${JSON.stringify(JSON.stringify(allDictionary.en))});\n`,
190
+ );
191
+ });
192
+
193
+ test("moves each endpoint's description and arguments to a file of their own, leaving its label", async () => {
194
+ const dictionary = {
195
+ en: {
196
+ memo: {
197
+ t: "Memo",
198
+ title: { t: "Title", desc: { t: "A field's own description stays" } },
199
+ signal: {
200
+ createMemo: { t: "Create Memo", desc: { t: "Creates a memo" }, arg: { data: { t: "Data" } } },
201
+ removeMemo: { t: "Remove Memo" },
202
+ },
203
+ },
204
+ util: { t: "Util" },
205
+ },
206
+ };
207
+ const { app, artifactDir } = await makeApp(dictSourceOf(dictionary));
208
+ const assets = await new DictionaryAssetBuilder(app, artifactDir).build(
209
+ { defaultLocale: "en", locales: ["en"] },
210
+ { splitApi: true },
211
+ );
212
+
213
+ const api = assets.en.parts?.api;
214
+ expect(api?.url).toMatch(/^\/_akan\/dict\/en-api-[a-z0-9]+\.js$/);
215
+ const page = (await import(path.join(artifactDir, assets.en.relPath))) as { default: object; parts: object };
216
+ expect(page.parts).toEqual({ api: api?.url });
217
+ expect(page.default).toEqual({
218
+ memo: {
219
+ t: "Memo",
220
+ title: { t: "Title", desc: { t: "A field's own description stays" } },
221
+ signal: { createMemo: { t: "Create Memo" }, removeMemo: { t: "Remove Memo" } },
222
+ },
223
+ util: { t: "Util" },
224
+ });
225
+ expect((await import(path.join(artifactDir, api?.relPath ?? ""))).default).toEqual({
226
+ memo: { signal: { createMemo: { desc: { t: "Creates a memo" }, arg: { data: { t: "Data" } } } } },
227
+ });
228
+ });
229
+
230
+ test("writes the whole file when the split leaves nothing to move", async () => {
231
+ const { app, artifactDir } = await makeApp(dictSourceOf(allDictionary));
232
+ const assets = await new DictionaryAssetBuilder(app, artifactDir).build(i18n, { splitApi: true });
233
+
234
+ expect(assets.en.parts).toBeUndefined();
235
+ expect((await readdir(path.join(artifactDir, "dict"))).length).toBe(2);
236
+ });
237
+
238
+ test("splits a lib's and an app's description of the same module into files that merge back to the whole", async () => {
239
+ const { app } = await makeApp(libAndAppDictSource(path.join(workspaceRoot, "pkgs/akanjs/dictionary/index.ts")));
240
+ const builds = await buildBothWays(app.cwdPath, await tempRoot());
241
+
242
+ expect(Object.keys(builds)).toEqual(["en", "ko"]);
243
+ for (const build of Object.values(builds)) expectSplitOf(build);
244
+ expect(builds.ko.whole.cart).toEqual(builds.en.whole.cart);
245
+ expect(builds.ko.page.shop).toEqual({
246
+ error: {},
247
+ signal: { order: { t: "바로 주문" }, track: { t: "배송 조회" } },
248
+ title: { t: "내 상점" },
249
+ });
250
+ }, 30_000);
251
+
252
+ //? `lib/dict.ts` is written by `akan sync`, which the package test job of CI does not run.
253
+ for (const name of ["minimal", "akan"])
254
+ test.skipIf(!existsSync(path.join(workspaceRoot, "apps", name, "lib/dict.ts")))(
255
+ `splits apps/${name}'s dictionary into files that merge back to the whole`,
256
+ async () => {
257
+ const builds = await buildBothWays(path.join(workspaceRoot, "apps", name), await tempRoot());
258
+
259
+ expect(Object.keys(builds)).toEqual(["en", "ko"]);
260
+ for (const build of Object.values(builds)) expectSplitOf(build);
261
+ },
262
+ 60_000,
263
+ );
264
+
265
+ describe("for the routes it is handed", () => {
266
+ const routedDictionary = {
267
+ en: {
268
+ base: { t: "Base", ok: { t: "OK" } },
269
+ memo: { t: "Memo", signal: { getMemo: { t: "Get Memo", desc: { t: "Reads a memo" } } } },
270
+ user: { t: "User" },
271
+ util: { t: "Util" },
272
+ },
273
+ ko: { base: { t: "기본" }, memo: { t: "메모" } },
274
+ };
275
+ const routes = new Map([
276
+ ["/:lang/memo", ["base", "memo"]],
277
+ ["/:lang/user", ["base", "user", "unknownGroup"]],
278
+ ]);
279
+ interface PartModule {
280
+ default: Record<string, unknown>;
281
+ groups: string[];
282
+ table: string;
283
+ parts?: object;
284
+ }
285
+ const importOf = async <Module>(artifactDir: string, url: string) =>
286
+ (await import(path.join(artifactDir, url.replace(/^\/_akan\//, "")))) as Module;
287
+
288
+ test("writes the files each route loads, and the table naming each group's file, for every locale", async () => {
289
+ const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
290
+ const built = await new DictionaryAssetBuilder(app, artifactDir).buildAll(i18n, { splitApi: true, routes });
291
+
292
+ expect(Object.keys(built.routes ?? {})).toEqual(["/:lang/memo", "/:lang/user"]);
293
+ for (const lang of i18n.locales) {
294
+ const asset = built.assets[lang];
295
+ const routeParts = asset?.routeParts;
296
+ if (!asset || !routeParts) throw new Error(`no route files for ${lang}`);
297
+ const table = await importOf<{ files: string[]; default: Record<string, number> }>(
298
+ artifactDir,
299
+ routeParts.table.url,
300
+ );
301
+ expect(table.files).toEqual(routeParts.files.map(({ url }) => url));
302
+ const page = await importOf<PartModule>(artifactDir, asset.url);
303
+ expect(page.table).toBe(routeParts.table.url);
304
+ for (const [routeId, shown] of routes) {
305
+ const merged: Record<string, unknown> = {};
306
+ for (const idx of built.routes?.[routeId] ?? []) {
307
+ const part = await importOf<PartModule>(artifactDir, table.files[idx] ?? "");
308
+ expect(part.table).toBe(routeParts.table.url);
309
+ expect(part.parts).toEqual(page.parts);
310
+ for (const group of part.groups) expect(table.default[group]).toBe(idx);
311
+ Object.assign(merged, part.default);
312
+ }
313
+ for (const group of shown.filter((group) => group in page.default))
314
+ expect(merged[group]).toEqual(page.default[group]);
315
+ expect(merged.util).toBeUndefined();
316
+ }
317
+ expect(Object.keys(table.default).sort()).toEqual(["base", "memo", "user", "util"]);
318
+ expect(built.routes?.["/:lang/memo"]).not.toContain(table.default.util);
319
+ expect(built.routes?.["/:lang/user"]).not.toContain(table.default.util);
320
+ }
321
+ });
322
+
323
+ test("writes the one page file unchanged when no route is handed", async () => {
324
+ const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
325
+ const plain = await new DictionaryAssetBuilder(app, path.join(artifactDir, "plain")).buildAll(i18n, {
326
+ splitApi: true,
327
+ });
328
+ const routed = await new DictionaryAssetBuilder(app, path.join(artifactDir, "routed")).buildAll(i18n, {
329
+ splitApi: true,
330
+ routes: new Map(),
331
+ });
332
+
333
+ expect(routed).toEqual(plain);
334
+ expect(plain.routes).toBeUndefined();
335
+ expect(plain.assets.en.routeParts).toBeUndefined();
336
+ expect((await readdir(path.join(artifactDir, "plain/dict"))).length).toBe(4);
337
+ const api = await importOf<{ part?: string }>(
338
+ path.join(artifactDir, "plain"),
339
+ plain.assets.ko.parts?.api?.url ?? "",
340
+ );
341
+ expect(api.part).toBeUndefined();
342
+ });
343
+
344
+ test("adds the API description file to a route whose components show those texts, in a build and in development", async () => {
345
+ const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
346
+ const { apiGroup } = DictionaryAssetBuilder;
347
+ const withApi = new Map([...routes, ["/:lang/memo/api", ["base", "memo", apiGroup]]]);
348
+ const built = await new DictionaryAssetBuilder(app, path.join(artifactDir, "build")).buildAll(i18n, {
349
+ splitApi: true,
350
+ routes: withApi,
351
+ });
352
+ const dev = await new DictionaryAssetBuilder(app, path.join(artifactDir, "dev")).buildAll(i18n, {
353
+ splitApi: true,
354
+ everyGroupAlone: true,
355
+ });
356
+
357
+ for (const { assets } of [built, dev])
358
+ for (const lang of i18n.locales) expect(assets[lang].routeParts?.files.at(-1)).toEqual(assets[lang].parts?.api);
359
+ const apiIdx = (built.assets.en.routeParts?.files.length ?? 0) - 1;
360
+ expect(built.routes?.["/:lang/memo/api"]).toEqual([...(built.routes?.["/:lang/memo"] ?? []), apiIdx]);
361
+ expect(built.routes?.["/:lang/memo"]).not.toContain(apiIdx);
362
+ expect(dev.groups?.[apiGroup]).toBe((dev.assets.en.routeParts?.files.length ?? 0) - 1);
363
+ const api = await importOf<{ part: string; default: object }>(
364
+ path.join(artifactDir, "build"),
365
+ built.assets.ko.parts?.api?.url ?? "",
366
+ );
367
+ expect(api.part).toBe(DictionaryAssetBuilder.apiPart);
368
+ expect(api.default).toEqual({ memo: { signal: { getMemo: { desc: { t: "Reads a memo" } } } } });
369
+ });
370
+
371
+ test("development writes one file per group and the index of each, as each route's groups are read when it builds", async () => {
372
+ const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
373
+ const built = await new DictionaryAssetBuilder(app, artifactDir).buildAll(i18n, { everyGroupAlone: true });
374
+
375
+ expect(built.routes).toBeUndefined();
376
+ expect(built.groups).toEqual({ base: 0, memo: 1, user: 2, util: 3 });
377
+ const files = built.assets.ko?.routeParts?.files ?? [];
378
+ expect(files).toHaveLength(4);
379
+ for (const [group, idx] of Object.entries(built.groups ?? {})) {
380
+ const part = await importOf<PartModule>(artifactDir, files[idx]?.url ?? "");
381
+ expect(part.groups).toEqual([group]);
382
+ expect(Object.keys(part.default)).toEqual([group]);
383
+ }
384
+ });
385
+ });
386
+
71
387
  test("writes nothing for an app without a dictionary", async () => {
72
388
  const { app, artifactDir } = await makeApp();
73
389
  expect(await new DictionaryAssetBuilder(app, artifactDir).build({ defaultLocale: "en", locales: ["en"] })).toEqual(
@@ -1,11 +1,38 @@
1
1
  import path from "node:path";
2
- import { type AllDictionary, Translator } from "akanjs/client";
2
+ import { type AllDictionary, type Dictionary, Translator } from "akanjs/client";
3
3
  import type { AkanI18nConfig } from "akanjs/common";
4
4
  import type { DictAsset } from "akanjs/server";
5
5
  import type { App } from "../commandDecorators";
6
+ import { DictionaryPacking } from "./dictionaryPacking";
7
+
8
+ export interface DictionaryAssetBuildOptions {
9
+ /** Each locale's API descriptions go to a file of their own, loaded where shown. */
10
+ splitApi?: boolean;
11
+ /** The groups each route can show; a route left out loads the whole page file. */
12
+ routes?: ReadonlyMap<string, readonly string[]>;
13
+ /** Development: one file per group, as each route's groups are read when it builds. */
14
+ everyGroupAlone?: boolean;
15
+ }
16
+
17
+ export interface DictionaryAssets {
18
+ assets: Record<string, DictAsset>;
19
+ /** The `routeParts.files` each route loads, by index, the same for every locale. */
20
+ routes?: Record<string, number[]>;
21
+ /** With `everyGroupAlone`: the `routeParts.files` index of each group. */
22
+ groups?: Record<string, number>;
23
+ }
24
+
25
+ interface LocalePages {
26
+ lang: string;
27
+ page: Dictionary;
28
+ api: Dictionary;
29
+ }
6
30
 
7
31
  export class DictionaryAssetBuilder {
8
32
  static readonly urlPrefix = "/_akan/dict";
33
+ static readonly apiPart = "api";
34
+ //? How a route's groups name the API description file: no module's group is spelled so.
35
+ static readonly apiGroup = "@api";
9
36
  readonly #app: App;
10
37
  readonly #absArtifactDir: string;
11
38
 
@@ -14,16 +41,58 @@ export class DictionaryAssetBuilder {
14
41
  this.#absArtifactDir = absArtifactDir;
15
42
  }
16
43
 
17
- async build(i18n: AkanI18nConfig): Promise<Record<string, DictAsset>> {
44
+ async build(i18n: AkanI18nConfig, options: DictionaryAssetBuildOptions = {}): Promise<Record<string, DictAsset>> {
45
+ return (await this.buildAll(i18n, options)).assets;
46
+ }
47
+
48
+ async buildAll(
49
+ i18n: AkanI18nConfig,
50
+ { splitApi = false, routes, everyGroupAlone = false }: DictionaryAssetBuildOptions = {},
51
+ ): Promise<DictionaryAssets> {
18
52
  const allDictionary = await this.#loadAllDictionary();
19
- if (!allDictionary) return {};
20
- const assets = await Promise.all(
21
- i18n.locales.map((lang) =>
22
- this.#write(lang, Translator.fillFromDefault(allDictionary, lang, i18n.defaultLocale)),
23
- ),
24
- );
25
- this.#app.verbose(`[base-artifact] dictionaries -> ${assets.map(([, asset]) => asset.relPath).join(", ")}`);
26
- return Object.fromEntries(assets);
53
+ if (!allDictionary) return { assets: {} };
54
+ const locales: LocalePages[] = i18n.locales.map((lang) => {
55
+ const dictionary = Translator.fillFromDefault(allDictionary, lang, i18n.defaultLocale);
56
+ return { lang, ...(splitApi ? DictionaryAssetBuilder.splitApi(dictionary) : { page: dictionary, api: {} }) };
57
+ });
58
+ const groups = [...new Set(locales.flatMap(({ page }) => Object.keys(page)))].sort();
59
+ const pack = routes?.size
60
+ ? DictionaryAssetBuilder.#pack(routes, locales, i18n.defaultLocale, groups)
61
+ : everyGroupAlone
62
+ ? { parts: groups.map((group) => [group]), partsByRoute: {} }
63
+ : null;
64
+ const assets = await Promise.all(locales.map((locale) => this.#writeLocale(locale, pack?.parts)));
65
+ const files = assets.flatMap(([, asset]) => [
66
+ asset,
67
+ ...Object.values(asset.parts ?? {}),
68
+ ...(asset.routeParts ? [asset.routeParts.table, ...asset.routeParts.files] : []),
69
+ ]);
70
+ this.#app.verbose(`[base-artifact] dictionaries -> ${files.map((asset) => asset.relPath).join(", ")}`);
71
+ if (!pack?.parts.length) return { assets: Object.fromEntries(assets) };
72
+ const { apiPart, apiGroup } = DictionaryAssetBuilder;
73
+ const apiFile = assets.every(([, asset]) => asset.parts?.[apiPart]) ? pack.parts.length : null;
74
+ if (!everyGroupAlone || routes?.size) {
75
+ const withApi = (routeId: string, files: number[]) =>
76
+ apiFile !== null && routes?.get(routeId)?.includes(apiGroup) ? [...files, apiFile] : files;
77
+ const routed = Object.entries(pack.partsByRoute).map(([routeId, files]) => [routeId, withApi(routeId, files)]);
78
+ return { assets: Object.fromEntries(assets), routes: Object.fromEntries(routed) };
79
+ }
80
+ const groupFiles = Object.fromEntries(groups.map((group, idx) => [group, idx]));
81
+ return {
82
+ assets: Object.fromEntries(assets),
83
+ groups: apiFile === null ? groupFiles : { ...groupFiles, [apiGroup]: apiFile },
84
+ };
85
+ }
86
+
87
+ //? Sized on the default locale, whose texts every other locale's fill from: the same files hold the same groups.
88
+ static #pack(
89
+ routes: ReadonlyMap<string, readonly string[]>,
90
+ locales: LocalePages[],
91
+ defaultLocale: string,
92
+ groups: string[],
93
+ ) {
94
+ const sizing = (locales.find(({ lang }) => lang === defaultLocale) ?? locales[0])?.page ?? {};
95
+ return DictionaryPacking.pack(routes, (group) => JSON.stringify(sizing[group] ?? {}).length, groups);
27
96
  }
28
97
 
29
98
  //? The same module the root layout's macro evaluates in this process, so the asset and the RSC worker's copy agree.
@@ -34,16 +103,83 @@ export class DictionaryAssetBuilder {
34
103
  return getAllDictionary ? getAllDictionary() : null;
35
104
  }
36
105
 
37
- async #write(lang: string, dictionary: object): Promise<readonly [string, DictAsset]> {
38
- const source = DictionaryAssetBuilder.source(lang, dictionary);
39
- const name = `${lang}-${Bun.hash(source).toString(36)}.js`;
106
+ async #writeLocale({ lang, page, api }: LocalePages, packed?: string[][]): Promise<readonly [string, DictAsset]> {
107
+ const { source, apiPart } = DictionaryAssetBuilder;
108
+ const apiSource = source(lang, api, undefined, packed?.length ? { part: apiPart } : {});
109
+ const apiAsset = Object.keys(api).length ? await this.#write(`${lang}-api`, apiSource) : null;
110
+ const parts = apiAsset ? { [apiPart]: apiAsset.url } : undefined;
111
+ const withParts = apiAsset ? { parts: { [apiPart]: apiAsset } } : {};
112
+ if (!packed?.length) return [lang, { ...(await this.#write(lang, source(lang, page, parts))), ...withParts }];
113
+ //? Named for what decides every file it lists, not for their names: each part names the table it belongs to.
114
+ const tableName = `${lang}-groups-${Bun.hash(JSON.stringify([page, packed, parts ?? null])).toString(36)}.js`;
115
+ const table = `${DictionaryAssetBuilder.urlPrefix}/${tableName}`;
116
+ const groupFiles = await Promise.all(
117
+ packed.map((groups, idx) => {
118
+ const held = Object.fromEntries(groups.flatMap((group) => (page[group] ? [[group, page[group]]] : [])));
119
+ return this.#write(`${lang}-${idx}`, source(lang, held, parts, { table, groups }));
120
+ }),
121
+ );
122
+ const files = apiAsset ? [...groupFiles, apiAsset] : groupFiles;
123
+ const groupIndex = Object.fromEntries(packed.flatMap((groups, idx) => groups.map((group) => [group, idx])));
124
+ const tableSource = `export const lang = ${JSON.stringify(lang)};\nexport const files = ${JSON.stringify(files.map(({ url }) => url))};\nexport default ${JSON.stringify(groupIndex)};\n`;
125
+ const tableAsset = await this.#write(lang, tableSource, tableName);
126
+ const whole = await this.#write(lang, source(lang, page, parts, { table }));
127
+ return [lang, { ...whole, ...withParts, routeParts: { table: tableAsset, files } }];
128
+ }
129
+
130
+ async #write(stem: string, source: string, fileName?: string): Promise<DictAsset> {
131
+ const name = fileName ?? `${stem}-${Bun.hash(source).toString(36)}.js`;
40
132
  const relPath = `dict/${name}`;
41
133
  await Bun.write(path.join(this.#absArtifactDir, relPath), source);
42
- return [lang, { url: `${DictionaryAssetBuilder.urlPrefix}/${name}`, relPath }] as const;
134
+ return { url: `${DictionaryAssetBuilder.urlPrefix}/${name}`, relPath };
135
+ }
136
+
137
+ //? An endpoint's own label stays with the page: apps show `l("<model>.signal.<endpoint>")` as a button's text.
138
+ static splitApi(dictionary: Dictionary): { page: Dictionary; api: Dictionary } {
139
+ const page: Dictionary = {};
140
+ const api: Dictionary = {};
141
+ for (const [refName, node] of Object.entries(dictionary)) {
142
+ const signal = node.signal;
143
+ if (!DictionaryAssetBuilder.#isNode(signal)) {
144
+ page[refName] = node;
145
+ continue;
146
+ }
147
+ const pageSignal: Record<string, unknown> = {};
148
+ const apiSignal: Record<string, unknown> = {};
149
+ for (const [key, entry] of Object.entries(signal)) {
150
+ if (!DictionaryAssetBuilder.#isNode(entry)) {
151
+ pageSignal[key] = entry;
152
+ continue;
153
+ }
154
+ const { desc, arg, ...label } = entry;
155
+ pageSignal[key] = label;
156
+ if (desc !== undefined || arg !== undefined)
157
+ apiSignal[key] = { ...(desc === undefined ? {} : { desc }), ...(arg === undefined ? {} : { arg }) };
158
+ }
159
+ page[refName] = { ...node, signal: pageSignal };
160
+ if (Object.keys(apiSignal).length) api[refName] = { signal: apiSignal };
161
+ }
162
+ return { page, api };
163
+ }
164
+
165
+ static #isNode(value: unknown): value is Record<string, unknown> {
166
+ return typeof value === "object" && value !== null && !Array.isArray(value);
43
167
  }
44
168
 
45
169
  //? A string for JSON.parse, not an object literal: engines parse the JSON grammar faster than a JS expression.
46
- static source(lang: string, dictionary: object): string {
47
- return `export const lang = ${JSON.stringify(lang)};\nexport default JSON.parse(${JSON.stringify(JSON.stringify(dictionary))});\n`;
170
+ static source(
171
+ lang: string,
172
+ dictionary: object,
173
+ parts?: Record<string, string>,
174
+ { table, groups, part }: { table?: string; groups?: string[]; part?: string } = {},
175
+ ): string {
176
+ const lines = [
177
+ `export const lang = ${JSON.stringify(lang)};\n`,
178
+ parts ? `export const parts = ${JSON.stringify(parts)};\n` : "",
179
+ table ? `export const table = ${JSON.stringify(table)};\n` : "",
180
+ groups ? `export const groups = ${JSON.stringify(groups)};\n` : "",
181
+ part ? `export const part = ${JSON.stringify(part)};\n` : "",
182
+ ];
183
+ return `${lines.join("")}export default JSON.parse(${JSON.stringify(JSON.stringify(dictionary))});\n`;
48
184
  }
49
185
  }
@@ -0,0 +1,82 @@
1
+ import path from "node:path";
2
+ import { createAst, createFactReader } from "@akanjs/language";
3
+ import { Glob } from "bun";
4
+ import ts from "typescript";
5
+
6
+ type GroupKind = "model" | "service" | "scalar" | "enum";
7
+
8
+ const constantFile = /(?:^|\/)lib\/(?:(__scalar)\/)?(_?)([A-Za-z0-9]+)\/\3\.constant\.ts$/;
9
+ const enumClass = /class\s+([A-Za-z0-9_$]+)\s+extends\s+enumOf\(\s*["'`]([A-Za-z0-9_$]+)["'`]/g;
10
+
11
+ //* The dictionary groups a model's texts reach: a framework view, list or form labels the model's fields, the enums
12
+ //* and scalars they hold, and the models they refer to (a relation shows the other model's name).
13
+ export class DictionaryConstants {
14
+ static readonly #reader = createFactReader(ts, createAst(ts));
15
+ readonly #groupOfClass = new Map<string, Set<string>>();
16
+ readonly #kindOf = new Map<string, GroupKind>();
17
+ readonly #typesOf = new Map<string, Set<string>>();
18
+ readonly #reach = new Map<string, string[]>();
19
+
20
+ static async read(workspaceRoot: string, scopes: string[]): Promise<DictionaryConstants> {
21
+ const constants = new DictionaryConstants();
22
+ for (const scope of scopes)
23
+ for await (const rel of new Glob("lib/**/*.constant.ts").scan({ cwd: path.join(workspaceRoot, scope) })) {
24
+ const file = path.join(workspaceRoot, scope, rel);
25
+ constants.add(`${scope}/${rel}`, await Bun.file(file).text());
26
+ }
27
+ return constants;
28
+ }
29
+
30
+ add(fileName: string, text: string) {
31
+ const [, scalar, underscore, group] = fileName.match(constantFile) ?? [];
32
+ if (!group) return;
33
+ this.#kindOf.set(group, scalar ? "scalar" : underscore ? "service" : "model");
34
+ const sourceFile = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
35
+ const types = this.#typesOf.get(group) ?? new Set<string>();
36
+ for (const constant of DictionaryConstants.#reader.read(sourceFile, null).constants) {
37
+ this.#classTo(constant.name, group);
38
+ for (const field of constant.fields) if (field.type) types.add(field.type);
39
+ }
40
+ this.#typesOf.set(group, types);
41
+ for (const [, name, ref] of text.matchAll(enumClass))
42
+ if (name && ref) {
43
+ this.#classTo(name, ref);
44
+ this.#kindOf.set(ref, "enum");
45
+ }
46
+ }
47
+
48
+ #classTo(name: string, group: string) {
49
+ this.#groupOfClass.set(name, (this.#groupOfClass.get(name) ?? new Set()).add(group));
50
+ }
51
+
52
+ groupsOfClass(name: string): string[] {
53
+ return [...(this.#groupOfClass.get(name) ?? [])];
54
+ }
55
+
56
+ //? A relation is followed one step: the other model's name and its own enums and scalars, not its relations.
57
+ reachOf(group: string): string[] {
58
+ const known = this.#reach.get(group);
59
+ if (known) return known;
60
+ const reached = new Set<string>([group]);
61
+ this.#holds(group, reached, true);
62
+ const result = [...reached].sort();
63
+ this.#reach.set(group, result);
64
+ return result;
65
+ }
66
+
67
+ #holds(group: string, reached: Set<string>, followRelations: boolean) {
68
+ for (const type of this.#typesOf.get(group) ?? [])
69
+ for (const held of this.groupsOfClass(type)) {
70
+ if (reached.has(held)) continue;
71
+ const kind = this.#kindOf.get(held);
72
+ if (kind === "model" || kind === "service") {
73
+ if (!followRelations) continue;
74
+ reached.add(held);
75
+ this.#holds(held, reached, false);
76
+ } else {
77
+ reached.add(held);
78
+ this.#holds(held, reached, followRelations);
79
+ }
80
+ }
81
+ }
82
+ }