@akanjs/devkit 3.3.0-rc.4 → 3.3.0-rc.41
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.
- package/CHANGELOG.md +628 -0
- package/DEV_RUNTIME_KNOBS.md +1 -1
- package/README.ko.md +3 -2
- package/README.md +3 -3
- package/akanApp/akanApp.host.test.ts +1 -1
- package/akanApp/akanApp.host.ts +11 -0
- package/akanConfig/akanBin.ts +4 -0
- package/akanConfig/akanConfig.test.ts +66 -7
- package/akanConfig/akanConfig.ts +53 -204
- package/akanConfig/akanWorkers.test.ts +39 -0
- package/akanConfig/akanWorkers.ts +32 -0
- package/akanConfig/desktopServerConfig.ts +96 -0
- package/akanConfig/dockerImage.ts +37 -0
- package/akanConfig/nativeKeys.ts +52 -0
- package/akanConfig/types.ts +1 -0
- package/app/appBin.test.ts +63 -0
- package/app/appBin.ts +50 -0
- package/app/applicationBuildReporter.test.ts +32 -0
- package/app/applicationBuildReporter.ts +4 -0
- package/app/applicationBuildRunner.test.ts +275 -0
- package/app/applicationBuildRunner.ts +133 -6
- package/app/dictionarySizes.ts +91 -0
- package/app/routeFilesReport.test.ts +59 -0
- package/app/routeFilesReport.ts +46 -0
- package/app/routeJsBudget.ts +18 -4
- package/artifact/implicitRootLayout.test.ts +19 -0
- package/artifact/implicitRootLayout.ts +16 -2
- package/artifact/implicitRootLayoutRender.test.tsx +4 -1
- package/artifact/storeBootstrap.test.ts +28 -0
- package/artifact/storeBootstrap.ts +64 -8
- package/biome.base.json +6 -4
- package/codeAgent/agent/CodeAgent.ts +36 -16
- package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
- package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
- package/codeAgent/agent/CodeAgentGate.ts +23 -4
- package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
- package/codeAgent/agent/codeAgent.test.ts +62 -0
- package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
- package/codeAgent/agent/codeAgentContract.test.ts +117 -5
- package/codeAgent/skills/akan-agent/SKILL.md +8 -1
- package/codeAgent/skills/akan-code/SKILL.md +38 -3
- package/codeAgent/skills/akan-deps/SKILL.md +3 -2
- package/codeAgent/skills/akan-err/SKILL.md +13 -8
- package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
- package/codeAgent/skills/akan-module/SKILL.md +2 -2
- package/codeAgent/skills/akan-page/SKILL.md +31 -20
- package/codeAgent/skills/akan-query/SKILL.md +13 -20
- package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
- package/codeAgent/skills/akan-service/SKILL.md +2 -5
- package/codeAgent/skills/akan-transport/SKILL.md +5 -14
- package/codeAgent/skills/akan-ui/SKILL.md +2 -5
- package/context/akanContext.ts +2 -0
- package/docs/apiReference.test.ts +9 -0
- package/docs/apiReference.ts +14 -0
- package/executors/appExecutor.ts +3 -1
- package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
- package/executors/clientRuntimeKeys.fixture.json +393 -0
- package/executors/clientRuntimeKeys.test.ts +1690 -0
- package/executors/executors.test.ts +2 -0
- package/executors/sysExecutor.ts +70 -4
- package/executors/workspaceExecutor.ts +7 -4
- package/frontendBuild/allRoutesBuilder.ts +88 -7
- package/frontendBuild/autoImportSync.ts +3 -2
- package/frontendBuild/buildRouteClient.test.ts +666 -12
- package/frontendBuild/clientBuildTypes.ts +26 -0
- package/frontendBuild/clientEntriesBundler.ts +49 -1
- package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
- package/frontendBuild/clientEntryDiscovery.ts +135 -13
- package/frontendBuild/clientEntryGroups.test.ts +77 -0
- package/frontendBuild/clientEntryGroups.ts +61 -0
- package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
- package/frontendBuild/csrDevModuleCompiler.ts +44 -8
- package/frontendBuild/csrDevPatcher.ts +33 -7
- package/frontendBuild/csrDevTypes.ts +9 -0
- package/frontendBuild/devBarrelImports.test.ts +154 -0
- package/frontendBuild/devBarrelImports.ts +83 -23
- package/frontendBuild/devRegistryBundler.ts +4 -2
- package/frontendBuild/devRouteRuntime.test.ts +492 -0
- package/frontendBuild/devRouteRuntime.ts +167 -0
- package/frontendBuild/dictionaryAssetBuilder.test.ts +324 -0
- package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
- package/frontendBuild/dictionaryConstants.ts +136 -0
- package/frontendBuild/dictionaryPacking.test.ts +142 -0
- package/frontendBuild/dictionaryPacking.ts +135 -0
- package/frontendBuild/dictionaryRoutes.test.ts +251 -0
- package/frontendBuild/dictionaryRoutes.ts +227 -0
- package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
- package/frontendBuild/pagesBundleBuilder.ts +81 -3
- package/frontendBuild/precompressArtifacts.test.ts +22 -0
- package/frontendBuild/precompressArtifacts.ts +22 -8
- package/frontendBuild/registryMetadataFingerprint.ts +3 -3
- package/frontendBuild/renderedEntries.ts +144 -0
- package/frontendBuild/routeClientBuilder.ts +405 -43
- package/frontendBuild/routeHandoffs.test.ts +155 -0
- package/frontendBuild/routeHandoffs.ts +117 -0
- package/frontendBuild/routeModulePreloads.test.ts +32 -0
- package/frontendBuild/routeModulePreloads.ts +20 -11
- package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
- package/frontendBuild/routeRuntimeCheck.ts +248 -0
- package/frontendBuild/routeRuntimePays.test.ts +143 -0
- package/frontendBuild/routeRuntimePays.ts +117 -0
- package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
- package/frontendBuild/rscServerRendererGuard.ts +68 -0
- package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
- package/frontendBuild/ssrDevBundler.test.ts +150 -1
- package/frontendBuild/ssrDevBundler.ts +66 -11
- package/frontendBuild/vendorFileImports.test.ts +254 -0
- package/frontendBuild/vendorFileImports.ts +163 -0
- package/frontendBuild/vendorNarrowing.ts +28 -0
- package/frontendBuild/vendorSpecifiers.ts +2 -0
- package/incrementalBuilder/buildBatch.proc.ts +9 -9
- package/incrementalBuilder/buildBatchProtocol.ts +1 -1
- package/incrementalBuilder/builderBoot.ts +5 -5
- package/incrementalBuilder/builderGraphPayloads.ts +4 -4
- package/incrementalBuilder/builderLanes.ts +2 -2
- package/incrementalBuilder/builderWatch.ts +8 -8
- package/incrementalBuilder/csrRegistry.ts +4 -4
- package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
- package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
- package/incrementalBuilder/ssrRegistry.ts +6 -6
- package/index.ts +1 -1
- package/integration/renderAdmissionSoak.test.ts +99 -0
- package/integration/renderAdmissionSoak.ts +609 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
- package/lint/biomeBase.test.ts +23 -3
- package/lint/biomeCheck.test.ts +145 -0
- package/lint/biomeCheck.ts +131 -0
- package/lint/no-arbitrary-color.grit +5 -0
- package/lint/no-conditional-st-hook.grit +5 -1
- package/lint/no-daisyui-legacy-class.grit +8 -0
- package/lint/no-document-cookie.grit +3 -0
- package/lint/no-inline-color.grit +10 -2
- package/lint/no-oversized-list-limit.grit +2 -0
- package/lint/no-raw-palette-class.grit +7 -0
- package/lint/no-unpublished-form-setter.grit +2 -0
- package/lint/no-web-only-api-outside-webkit.grit +5 -0
- package/lint/no-web-storage.grit +3 -0
- package/lint/withheldEnvFile.ts +17 -0
- package/mobile/desktopBin.ts +2 -2
- package/mobile/desktopServerStage.ts +1 -0
- package/mobile/nativeApp.test.ts +7 -5
- package/mobile/nativeApp.ts +2 -2
- package/mobile/nativeConfig.test.ts +96 -1
- package/mobile/nativeConfig.ts +46 -12
- package/mobile/serverBundleSecrets.ts +43 -0
- package/package.json +15 -169
- package/packageExports.test.ts +38 -24
- package/quality/dictionaryKeys.test.ts +356 -0
- package/quality/dictionaryKeys.ts +488 -0
- package/quality/objectImportReport.test.ts +36 -0
- package/quality/objectImportReport.ts +105 -0
- package/quality/qualityScanner.ts +1 -1
- package/quality/routeRuntimeReport.test.ts +91 -0
- package/quality/routeRuntimeReport.ts +121 -0
- package/quality/runtimeConstantFacts.ts +71 -0
- package/quality/runtimeConstantGraph.ts +123 -0
- package/quality/runtimeConstantReads.ts +116 -0
- package/quality/runtimeImports.test.ts +190 -0
- package/quality/runtimeImports.ts +233 -0
- package/quality/runtimeKeyNames.ts +46 -0
- package/quality/runtimeLexicalScope.ts +132 -0
- package/quality/runtimeMarkerReach.test.ts +84 -0
- package/quality/runtimeMarkerReach.ts +255 -0
- package/quality/runtimeModuleFacts.ts +290 -0
- package/quality/runtimeNameTable.test.ts +172 -0
- package/quality/runtimeNameTable.ts +477 -0
- package/quality/runtimeScopeReport.test.ts +123 -0
- package/quality/runtimeScopeReport.ts +167 -0
- package/quality/runtimeSliceKey.ts +269 -0
- package/quality/runtimeSyntax.ts +133 -0
- package/quality/runtimeTable.fixture.ts +189 -0
- package/quality/runtimeUse.test.ts +737 -0
- package/quality/runtimeUse.ts +696 -0
- package/quality/runtimeUseReadable.test.ts +393 -0
- package/quality/ssrScanner.test.ts +13 -0
- package/quality/ssrScanner.ts +1 -1
- package/quality/translatorBindings.ts +187 -0
- package/test/secretEnvFixture.ts +134 -0
- package/test/testHelpers.ts +11 -0
- package/transforms/barrelAnalyzer.ts +26 -4
- package/transforms/barrelImportsPlugin.ts +121 -32
- package/transforms/exportReach.test.ts +162 -0
- package/transforms/exportReach.ts +308 -0
- package/transforms/frameworkObjects.fixture.tsx +58 -0
- package/transforms/frameworkObjects.test.ts +54 -0
- package/transforms/modelReference.test.ts +196 -0
- package/transforms/modelReference.ts +39 -0
- package/transforms/moduleParts.test.ts +225 -0
- package/transforms/moduleParts.ts +418 -0
- package/transforms/objectImportEdits.ts +150 -0
- package/transforms/objectMemberImports.test.ts +629 -0
- package/transforms/objectMemberImports.ts +571 -0
- package/transforms/objectMemberLookup.ts +150 -0
- package/transforms/objectModule.test.ts +307 -0
- package/transforms/objectModule.ts +482 -0
- package/transforms/objectModuleAnalyzer.ts +104 -0
- package/transforms/partImports.test.ts +76 -0
- package/transforms/partImports.ts +110 -0
- package/transforms/partModules.test.ts +187 -0
- package/transforms/partModules.ts +90 -0
- package/transforms/partPurity.ts +124 -0
- package/transforms/reactIconImports.test.ts +231 -0
- package/transforms/reactIconImports.ts +325 -0
- package/transforms/routeConstants.ts +122 -0
- package/transforms/routeRuntime.test.ts +835 -0
- package/transforms/routeRuntime.ts +703 -0
- package/transforms/routeRuntimeEdits.ts +92 -0
- package/transforms/routeRuntimeGraph.ts +66 -0
- package/transforms/routeRuntimePlan.ts +244 -0
- package/transforms/secretEnvDeclaration.test.ts +208 -0
- package/transforms/secretEnvDeclaration.ts +213 -0
- package/transforms/secretEnvFile.test.ts +117 -0
- package/transforms/secretEnvFile.ts +113 -0
- package/transforms/secretEnvName.test.ts +54 -0
- package/transforms/secretEnvName.ts +29 -0
- package/transforms/secretEnvSource.test.ts +148 -0
- package/transforms/secretEnvSource.ts +166 -0
- package/transforms/serverEnvEvaluationError.ts +11 -0
- package/transforms/serverEnvPlugin.test.ts +2 -1
- package/transforms/serverEnvPlugin.ts +13 -0
- package/transforms/serverEnvProfile.test.ts +115 -2
- package/transforms/serverEnvProfile.ts +117 -40
- package/transforms/serverEnvSecrets.test.ts +292 -0
- package/transforms/signalDescriptors.test.ts +280 -0
- package/transforms/signalDescriptors.ts +227 -0
- package/transforms/thisFreeExports.ts +87 -0
- package/transforms/transforms.test.ts +180 -3
- package/transforms/tsconfigPackageResolver.test.ts +1 -0
- package/tunnel/createTunnel.test.ts +29 -8
- package/tunnel/createTunnel.ts +18 -11
- package/typecheck/projectTypecheck.test.ts +29 -0
- package/typecheck/typeChecker.test.ts +49 -0
- package/typecheck/typeChecker.ts +9 -7
- package/typecheck/withheldDiagnostics.ts +41 -0
- package/util/fileEditor.ts +1 -0
- package/util/selectModel.ts +1 -0
- package/workflow/executor.ts +6 -2
- package/workflow/index.ts +1 -0
- package/workflow/plan.ts +36 -7
- package/workflow/types.ts +1 -1
- package/workflow/uiTarget.ts +50 -0
- package/workspace/getRelatedCnsts.ts +7 -0
- package/workspace/scanInfo.test.ts +39 -0
- package/workspace/scanInfo.ts +48 -5
- package/workspace/workspaceLayout.ts +1 -0
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { realpath } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { tempDirs, writeText } from "../test/testHelpers";
|
|
5
|
+
import { SignalDescriptors } from "./signalDescriptors";
|
|
6
|
+
|
|
7
|
+
const makeTempRoot = tempDirs("akan-devkit-signal-descriptors-");
|
|
8
|
+
|
|
9
|
+
const sigSource = `import { appendFileSync } from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
|
|
12
|
+
appendFileSync(path.join(import.meta.dir, "reads.txt"), "read\\n");
|
|
13
|
+
const serialized = {
|
|
14
|
+
trolley: { endpoint: { pingAt: { type: "query", args: [], returns: { refName: "String" } } } },
|
|
15
|
+
crate: { endpoint: { countOf: { type: "query", args: [], returns: { refName: "Int", nullable: true } } } },
|
|
16
|
+
odd: { endpoint: { at: { type: "query", args: [], returns: { refName: "String", nullable: undefined } } } },
|
|
17
|
+
};
|
|
18
|
+
export const fetch = { ownSerializedSignal: serialized };
|
|
19
|
+
export const getSerializedSignalOf = (name) => (name === "base" ? {} : { [name]: serialized[name] });
|
|
20
|
+
`;
|
|
21
|
+
|
|
22
|
+
const pieceOf = (name: string) => `import { FetchClient } from "akanjs/fetch";
|
|
23
|
+
import * as cnst from "../cnst";
|
|
24
|
+
import { fetch, sig } from "../usePage";
|
|
25
|
+
import { getSerializedSignalOf } from "../sig" with { type: "macro" };
|
|
26
|
+
import type * as signal from "../sig";
|
|
27
|
+
Object.assign(sig, FetchClient.build<typeof signal>(cnst, getSerializedSignalOf("${name}"), { base: fetch }).sig);
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
const writeScope = async (sig = sigSource) => {
|
|
31
|
+
const root = await realpath(await makeTempRoot());
|
|
32
|
+
await writeText(path.join(root, "apps/shop/lib/sig.ts"), sig);
|
|
33
|
+
const pieceDir = path.join(root, "apps/shop/lib/__client");
|
|
34
|
+
return {
|
|
35
|
+
root,
|
|
36
|
+
pieceDir,
|
|
37
|
+
readsOf: () =>
|
|
38
|
+
Bun.file(path.join(root, "apps/shop/lib/reads.txt"))
|
|
39
|
+
.text()
|
|
40
|
+
.catch(() => ""),
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const writeHangingScope = async () => {
|
|
45
|
+
const scope = await writeScope();
|
|
46
|
+
const pidFile = path.join(scope.root, "reader.pid");
|
|
47
|
+
await writeText(
|
|
48
|
+
path.join(scope.root, "apps/shop/lib/sig.ts"),
|
|
49
|
+
`await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nsetInterval(() => undefined, 1_000);\nawait new Promise(() => undefined);\n${sigSource}`,
|
|
50
|
+
);
|
|
51
|
+
return { ...scope, pidFile };
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const alive = (pid: number) => {
|
|
55
|
+
try {
|
|
56
|
+
process.kill(pid, 0);
|
|
57
|
+
return true;
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const goneWithin = async (pid: number, ms: number) => {
|
|
64
|
+
for (const started = Date.now(); Date.now() - started < ms; await Bun.sleep(50)) if (!alive(pid)) return true;
|
|
65
|
+
return !alive(pid);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
describe("SignalDescriptors", () => {
|
|
69
|
+
test("answers each piece with its own descriptors as a literal in place of the macro, reading the signal once", async () => {
|
|
70
|
+
const { root, pieceDir, readsOf } = await writeScope();
|
|
71
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"]);
|
|
72
|
+
const [trolley, crate, base] = await Promise.all(
|
|
73
|
+
["trolley", "crate", "base"].map((name) =>
|
|
74
|
+
descriptors.inline(pieceOf(name), path.join(pieceDir, `${name === "base" ? "_base" : name}.fetch.ts`)),
|
|
75
|
+
),
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
expect(trolley).toBe(
|
|
79
|
+
pieceOf("trolley")
|
|
80
|
+
.replace('import { getSerializedSignalOf } from "../sig" with { type: "macro" };', "")
|
|
81
|
+
.replace(
|
|
82
|
+
'getSerializedSignalOf("trolley")',
|
|
83
|
+
'{"trolley":{"endpoint":{"pingAt":{"type":"query","args":[],"returns":{"refName":"String"}}}}}',
|
|
84
|
+
),
|
|
85
|
+
);
|
|
86
|
+
expect(crate).toContain('{"crate":{"endpoint":{"countOf":');
|
|
87
|
+
expect(base).toContain("FetchClient.build<typeof signal>(cnst, {}, { base: fetch })");
|
|
88
|
+
expect([trolley, crate, base].some((source) => source?.includes('with { type: "macro" }'))).toBe(false);
|
|
89
|
+
expect(await readsOf()).toBe("read\n");
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("leaves the macro to a file it cannot answer exactly: not a piece, two calls, a name the signal lacks, or a value JSON cannot carry", async () => {
|
|
93
|
+
const { root, pieceDir } = await writeScope();
|
|
94
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"]);
|
|
95
|
+
const twoCalls = pieceOf("trolley").replace(
|
|
96
|
+
'getSerializedSignalOf("trolley")',
|
|
97
|
+
'getSerializedSignalOf("trolley"), getSerializedSignalOf("crate")',
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
expect(await descriptors.inline(pieceOf("trolley"), path.join(root, "apps/shop/lib/sigOf.ts"))).toBeNull();
|
|
101
|
+
expect(await descriptors.inline(twoCalls, path.join(pieceDir, "trolley.fetch.ts"))).toBeNull();
|
|
102
|
+
expect(await descriptors.inline(pieceOf("absent"), path.join(pieceDir, "absent.fetch.ts"))).toBeNull();
|
|
103
|
+
expect(await descriptors.inline(pieceOf("odd"), path.join(pieceDir, "odd.fetch.ts"))).toBeNull();
|
|
104
|
+
for (const name of ["valueOf", "__proto__", "constructor"])
|
|
105
|
+
expect(await descriptors.inline(pieceOf(name), path.join(pieceDir, `${name}.fetch.ts`))).toBeNull();
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("says which scope's signals it could not read, leaves only their pieces to the macro and answers the rest", async () => {
|
|
109
|
+
const { root, pieceDir } = await writeScope();
|
|
110
|
+
await writeText(path.join(root, "libs/kit/lib/sig.ts"), 'throw new Error("the signal broke");\n');
|
|
111
|
+
const said: string[] = [];
|
|
112
|
+
const descriptors = new SignalDescriptors(root, ["libs/kit", "apps/shop"], {
|
|
113
|
+
onUnread: (reason) => said.push(reason),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
expect(
|
|
117
|
+
await descriptors.inline(pieceOf("crate"), path.join(root, "libs/kit/lib/__client/crate.fetch.ts")),
|
|
118
|
+
).toBeNull();
|
|
119
|
+
expect(await descriptors.inline(pieceOf("trolley"), path.join(pieceDir, "trolley.fetch.ts"))).toContain(
|
|
120
|
+
'{"trolley":{"endpoint":',
|
|
121
|
+
);
|
|
122
|
+
expect(said).toEqual(["the signals of libs/kit could not be read (the signal broke)"]);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("stops a signal that does not finish loading within its time, names its scope once and leaves no process behind", async () => {
|
|
126
|
+
const { root, pieceDir, pidFile } = await writeHangingScope();
|
|
127
|
+
const said: string[] = [];
|
|
128
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"], {
|
|
129
|
+
onUnread: (reason) => said.push(reason),
|
|
130
|
+
timeoutMs: 500,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const inlined = await Promise.all(
|
|
134
|
+
["trolley", "crate"].map((name) => descriptors.inline(pieceOf(name), path.join(pieceDir, `${name}.fetch.ts`))),
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
expect(inlined).toEqual([null, null]);
|
|
138
|
+
expect(said).toEqual([
|
|
139
|
+
"the signals of apps/shop could not be read (they did not load within 0.5s, so the process reading them was stopped)",
|
|
140
|
+
]);
|
|
141
|
+
expect(await goneWithin(Number(await Bun.file(pidFile).text()), 3_000)).toBe(true);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
for (const ending of ["exits", "is killed"] as const)
|
|
145
|
+
test(`the process reading the signals ends when the build that started it ${ending}`, async () => {
|
|
146
|
+
const { root, pieceDir, pidFile } = await writeHangingScope();
|
|
147
|
+
const build = path.join(root, "build.ts");
|
|
148
|
+
await writeText(
|
|
149
|
+
build,
|
|
150
|
+
[
|
|
151
|
+
`import { SignalDescriptors } from ${JSON.stringify(path.join(import.meta.dir, "signalDescriptors.ts"))};`,
|
|
152
|
+
`void new SignalDescriptors(${JSON.stringify(root)}, ["apps/shop"]).inline(${JSON.stringify(pieceOf("trolley"))}, ${JSON.stringify(path.join(pieceDir, "trolley.fetch.ts"))});`,
|
|
153
|
+
`while (!(await Bun.file(${JSON.stringify(pidFile)}).exists())) await Bun.sleep(50);`,
|
|
154
|
+
ending === "exits" ? "process.exit(0);" : "",
|
|
155
|
+
"",
|
|
156
|
+
].join("\n"),
|
|
157
|
+
);
|
|
158
|
+
const parent = Bun.spawn([process.execPath, build], { cwd: root, stdout: "ignore", stderr: "ignore" });
|
|
159
|
+
try {
|
|
160
|
+
for (let tries = 0; tries < 200 && !(await Bun.file(pidFile).exists()); tries++) await Bun.sleep(50);
|
|
161
|
+
const reader = Number(await Bun.file(pidFile).text());
|
|
162
|
+
if (ending === "is killed") {
|
|
163
|
+
expect(alive(reader)).toBe(true);
|
|
164
|
+
parent.kill("SIGKILL");
|
|
165
|
+
}
|
|
166
|
+
await parent.exited;
|
|
167
|
+
expect(await goneWithin(reader, 5_000)).toBe(true);
|
|
168
|
+
} finally {
|
|
169
|
+
parent.kill("SIGKILL");
|
|
170
|
+
}
|
|
171
|
+
}, 30_000);
|
|
172
|
+
|
|
173
|
+
test("reads the signals in the build's own environment and its define, never a .env file the build did not load", async () => {
|
|
174
|
+
const { root, pieceDir } = await writeScope(
|
|
175
|
+
sigSource.replace(
|
|
176
|
+
'refName: "String" }',
|
|
177
|
+
'refName: "String", mode: process.env.NODE_ENV, sentinel: process.env.AKAN_SIGNAL_SENTINEL ?? "none" }',
|
|
178
|
+
),
|
|
179
|
+
);
|
|
180
|
+
for (const file of [".env.production", ".env.production.local"])
|
|
181
|
+
await writeText(path.join(root, file), "AKAN_SIGNAL_SENTINEL=from-an-env-file\n");
|
|
182
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"]);
|
|
183
|
+
descriptors.plugin.setup({
|
|
184
|
+
config: { define: { "process.env.NODE_ENV": '"production"' } },
|
|
185
|
+
onLoad: () => undefined,
|
|
186
|
+
} as never);
|
|
187
|
+
|
|
188
|
+
const trolley = await descriptors.inline(pieceOf("trolley"), path.join(pieceDir, "trolley.fetch.ts"));
|
|
189
|
+
|
|
190
|
+
expect(trolley).toContain('"mode":"production","sentinel":"none"');
|
|
191
|
+
expect(trolley).not.toContain("from-an-env-file");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
describe("a scope's whole runtime file on a page that also loads pieces", () => {
|
|
195
|
+
const wholeSource = `import { FetchClient } from "akanjs/fetch";
|
|
196
|
+
import * as cnst from "./cnst";
|
|
197
|
+
import { fetch as pageFetch, sig as pageSig } from "./usePage";
|
|
198
|
+
import { getSerializedSignal } from "./sig" with { type: "macro" };
|
|
199
|
+
Object.assign(pageSig, FetchClient.build(cnst, getSerializedSignal(), { base: pageFetch }).sig);
|
|
200
|
+
`;
|
|
201
|
+
const plainSig = sigSource.replace("\n odd: {", "\n spare: {").replace(", nullable: undefined }", " }");
|
|
202
|
+
const writePieces = async (pieceDir: string, names: string[]) =>
|
|
203
|
+
Promise.all(
|
|
204
|
+
names.map(async (name) => {
|
|
205
|
+
const file = path.join(pieceDir, `${name}.fetch.ts`);
|
|
206
|
+
await writeText(file, pieceOf(name));
|
|
207
|
+
return file;
|
|
208
|
+
}),
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
test("leaves out the descriptors of the pieces it is told, imports each piece by a name it uses, and keeps the rest", async () => {
|
|
212
|
+
const { root, pieceDir } = await writeScope(plainSig);
|
|
213
|
+
const [trolley] = await writePieces(pieceDir, ["trolley"]);
|
|
214
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"]);
|
|
215
|
+
|
|
216
|
+
const whole = await descriptors.withoutPieces(wholeSource, path.join(root, "apps/shop/lib/useClient.ts"), [
|
|
217
|
+
trolley ?? "",
|
|
218
|
+
]);
|
|
219
|
+
|
|
220
|
+
expect(whole).toContain(`import { loaded as __akanPiece0 } from ${JSON.stringify(trolley)};`);
|
|
221
|
+
expect(whole).toContain("__akanPiecesFirst(__akanPiece0);");
|
|
222
|
+
expect(whole).toContain('FetchClient.build(cnst, {"crate":');
|
|
223
|
+
expect(whole).toContain('"spare":');
|
|
224
|
+
expect(whole).not.toContain("pingAt");
|
|
225
|
+
expect(whole).not.toContain('type: "macro"');
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test("keeps a signal named `base` that the scope takes from its base, unless the base piece holds it", async () => {
|
|
229
|
+
const query = (name: string) =>
|
|
230
|
+
`{ endpoint: { ${name}: { type: "query", args: [], returns: { refName: "String" } } } }`;
|
|
231
|
+
const libSig = `const serialized = {
|
|
232
|
+
base: ${query("pingBase")},
|
|
233
|
+
agent: ${query("askAgent")},
|
|
234
|
+
trolley: ${query("pingAt")},
|
|
235
|
+
crate: ${query("countOf")},
|
|
236
|
+
};
|
|
237
|
+
export const fetch = { ownSerializedSignal: serialized };
|
|
238
|
+
export const getSerializedSignalOf = (name) =>
|
|
239
|
+
name === "base" ? { base: serialized.base, agent: serialized.agent } : { [name]: serialized[name] };
|
|
240
|
+
`;
|
|
241
|
+
const { root, pieceDir } = await writeScope(libSig);
|
|
242
|
+
const [trolley] = await writePieces(pieceDir, ["trolley"]);
|
|
243
|
+
const basePiece = path.join(pieceDir, "_base.fetch.ts");
|
|
244
|
+
await writeText(basePiece, pieceOf("base"));
|
|
245
|
+
const file = path.join(root, "apps/shop/lib/useClient.ts");
|
|
246
|
+
const occurrencesOf = (source: string | null, text: string) => (source ?? "").split(text).length - 1;
|
|
247
|
+
|
|
248
|
+
const beside = await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [trolley ?? ""]);
|
|
249
|
+
expect(occurrencesOf(beside, "pingBase")).toBe(1);
|
|
250
|
+
expect(occurrencesOf(beside, "askAgent")).toBe(1);
|
|
251
|
+
expect(occurrencesOf(beside, "countOf")).toBe(1);
|
|
252
|
+
expect(occurrencesOf(beside, "pingAt")).toBe(0);
|
|
253
|
+
|
|
254
|
+
const taken = await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [
|
|
255
|
+
basePiece,
|
|
256
|
+
trolley ?? "",
|
|
257
|
+
]);
|
|
258
|
+
expect(occurrencesOf(taken, "pingBase")).toBe(0);
|
|
259
|
+
expect(occurrencesOf(taken, "askAgent")).toBe(0);
|
|
260
|
+
expect(occurrencesOf(taken, "countOf")).toBe(1);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
test("keeps its macro and every descriptor where a name has no literal, or a piece names none", async () => {
|
|
264
|
+
const { root, pieceDir } = await writeScope();
|
|
265
|
+
const [trolley] = await writePieces(pieceDir, ["trolley"]);
|
|
266
|
+
const file = path.join(root, "apps/shop/lib/useClient.ts");
|
|
267
|
+
expect(
|
|
268
|
+
await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [trolley ?? ""]),
|
|
269
|
+
).toBeNull();
|
|
270
|
+
|
|
271
|
+
const plain = await writeScope(plainSig);
|
|
272
|
+
const unnamed = path.join(plain.pieceDir, "_base.fetch.ts");
|
|
273
|
+
await writeText(unnamed, "export const loaded = {};\n");
|
|
274
|
+
const plainFile = path.join(plain.root, "apps/shop/lib/useClient.ts");
|
|
275
|
+
expect(
|
|
276
|
+
await new SignalDescriptors(plain.root, ["apps/shop"]).withoutPieces(wholeSource, plainFile, [unnamed]),
|
|
277
|
+
).toBeNull();
|
|
278
|
+
});
|
|
279
|
+
});
|
|
280
|
+
});
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { BunPlugin } from "bun";
|
|
3
|
+
|
|
4
|
+
type ScopeDescriptors = Record<string, string>;
|
|
5
|
+
|
|
6
|
+
interface ScopeSignals {
|
|
7
|
+
//? Every name the scope's signal holds, with or without a literal.
|
|
8
|
+
names: string[];
|
|
9
|
+
literals: ScopeDescriptors;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface ScopeRead {
|
|
13
|
+
file: string;
|
|
14
|
+
names?: string[];
|
|
15
|
+
read?: ScopeDescriptors;
|
|
16
|
+
failure?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface SignalDescriptorsOptions {
|
|
20
|
+
onUnread?: (reason: string) => void;
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
//? The pieces a scope's `lib/useClient.ts` takes descriptors from, so it holds none of theirs again.
|
|
23
|
+
takenFromPieces?: (absPath: string) => string[] | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
//* Bun runs a macro module again on each bundler thread, so a build of many pieces reads each scope's signal once here.
|
|
27
|
+
export class SignalDescriptors {
|
|
28
|
+
static readonly readTimeoutMs = 60_000;
|
|
29
|
+
static readonly #pieceFile = /[\\/]lib[\\/]__client[\\/][^\\/]+\.fetch\.ts$/;
|
|
30
|
+
static readonly #wholeFile = /[\\/]lib[\\/]useClient\.ts$/;
|
|
31
|
+
static readonly #macroImport = 'import { getSerializedSignalOf } from "../sig" with { type: "macro" };';
|
|
32
|
+
static readonly #macroCall = /\bgetSerializedSignalOf\("([^"\\]+)"\)/g;
|
|
33
|
+
static readonly #wholeImport = 'import { getSerializedSignal } from "./sig" with { type: "macro" };';
|
|
34
|
+
static readonly #wholeCall = "getSerializedSignal()";
|
|
35
|
+
readonly #workspaceRoot: string;
|
|
36
|
+
readonly #sigFiles: string[];
|
|
37
|
+
readonly #onUnread: (reason: string) => void;
|
|
38
|
+
readonly #timeoutMs: number;
|
|
39
|
+
readonly #takenFromPieces: (absPath: string) => string[] | null;
|
|
40
|
+
readonly #reads = new Map<string, Promise<ScopeSignals | null>>();
|
|
41
|
+
#env: Record<string, string> = {};
|
|
42
|
+
|
|
43
|
+
//? In a process of its own: a module imported into this one stays cached after its file changes.
|
|
44
|
+
//? JSON drops undefined, -0, NaN and holes, and a `"__proto__"` key sets a prototype: such a name keeps its macro.
|
|
45
|
+
static #readScript(sigFiles: string[]) {
|
|
46
|
+
return `
|
|
47
|
+
process.on("disconnect", () => process.exit(1));
|
|
48
|
+
const send = (message) => new Promise((resolve) => process.send(message, undefined, undefined, resolve));
|
|
49
|
+
const literalOf = (value) => {
|
|
50
|
+
try {
|
|
51
|
+
const text = JSON.stringify(value);
|
|
52
|
+
return Bun.deepEquals(JSON.parse(text), value, true) && !text.includes('"__proto__":') ? text : undefined;
|
|
53
|
+
} catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
for (const file of ${JSON.stringify(sigFiles)}) {
|
|
58
|
+
try {
|
|
59
|
+
const { fetch, getSerializedSignalOf } = await import(file);
|
|
60
|
+
const names = ["base", ...Object.keys(fetch.ownSerializedSignal)];
|
|
61
|
+
const literals = names.map((name) => [name, literalOf(getSerializedSignalOf(name))]);
|
|
62
|
+
await send({ file, names, read: Object.fromEntries(literals.filter(([, literal]) => literal !== undefined)) });
|
|
63
|
+
} catch (error) {
|
|
64
|
+
await send({ file, failure: String(error?.message ?? error) });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
process.exit(0);
|
|
68
|
+
`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//? A macro module sees the build's `define`, so the process reading the signals gets each `process.env.<KEY>` of it.
|
|
72
|
+
static #envOf(define: Record<string, string> = {}): Record<string, string> {
|
|
73
|
+
return Object.fromEntries(
|
|
74
|
+
Object.entries(define).flatMap(([key, value]) => {
|
|
75
|
+
if (!key.startsWith("process.env.")) return [];
|
|
76
|
+
try {
|
|
77
|
+
const parsed: unknown = JSON.parse(value);
|
|
78
|
+
return typeof parsed === "string" ? [[key.slice("process.env.".length), parsed]] : [];
|
|
79
|
+
} catch {
|
|
80
|
+
return [];
|
|
81
|
+
}
|
|
82
|
+
}),
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
constructor(
|
|
87
|
+
workspaceRoot: string,
|
|
88
|
+
scopes: readonly string[],
|
|
89
|
+
{
|
|
90
|
+
onUnread = () => undefined,
|
|
91
|
+
timeoutMs = SignalDescriptors.readTimeoutMs,
|
|
92
|
+
takenFromPieces = () => null,
|
|
93
|
+
}: SignalDescriptorsOptions = {},
|
|
94
|
+
) {
|
|
95
|
+
this.#takenFromPieces = takenFromPieces;
|
|
96
|
+
this.#workspaceRoot = workspaceRoot;
|
|
97
|
+
this.#sigFiles = scopes.map((scope) => path.join(workspaceRoot, scope, "lib/sig.ts"));
|
|
98
|
+
this.#onUnread = onUnread;
|
|
99
|
+
this.#timeoutMs = timeoutMs;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
get plugin(): BunPlugin {
|
|
103
|
+
return {
|
|
104
|
+
name: "signal-descriptors",
|
|
105
|
+
setup: (build) => {
|
|
106
|
+
this.#env = SignalDescriptors.#envOf(build.config.define);
|
|
107
|
+
build.onLoad({ filter: SignalDescriptors.#pieceFile }, async (args) => {
|
|
108
|
+
const contents = await this.inline(await Bun.file(args.path).text(), args.path);
|
|
109
|
+
return contents === null ? undefined : { contents, loader: "ts" };
|
|
110
|
+
});
|
|
111
|
+
build.onLoad({ filter: SignalDescriptors.#wholeFile }, async (args) => {
|
|
112
|
+
const pieces = this.#takenFromPieces(args.path);
|
|
113
|
+
const contents = pieces && (await this.withoutPieces(await Bun.file(args.path).text(), args.path, pieces));
|
|
114
|
+
return contents ? { contents, loader: "ts" } : undefined;
|
|
115
|
+
});
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async inline(source: string, absPath: string): Promise<string | null> {
|
|
121
|
+
const macroImport = SignalDescriptors.#macroImport;
|
|
122
|
+
const calls = [...source.matchAll(SignalDescriptors.#macroCall)];
|
|
123
|
+
const [call] = calls;
|
|
124
|
+
const name = call?.[1];
|
|
125
|
+
if (!SignalDescriptors.#pieceFile.test(absPath) || !call || !name || calls.length !== 1) return null;
|
|
126
|
+
if (source.split(macroImport).length !== 2) return null;
|
|
127
|
+
const descriptors = (await this.#descriptorsOf(path.resolve(path.dirname(absPath), "../sig.ts")))?.literals;
|
|
128
|
+
const literal = descriptors && Object.hasOwn(descriptors, name) ? descriptors[name] : undefined;
|
|
129
|
+
if (literal === undefined) return null;
|
|
130
|
+
const end = call.index + call[0].length;
|
|
131
|
+
return `${source.slice(0, call.index)}${literal}${source.slice(end)}`.replace(macroImport, "");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
//* A scope's `lib/useClient.ts` with the descriptors of these pieces left out and the pieces imported in their place.
|
|
135
|
+
//* Null where a name cannot be accounted for, so the file keeps its macro and every descriptor.
|
|
136
|
+
async withoutPieces(source: string, absPath: string, pieces: readonly string[]): Promise<string | null> {
|
|
137
|
+
const [macroImport, macroCall] = [SignalDescriptors.#wholeImport, SignalDescriptors.#wholeCall];
|
|
138
|
+
if (source.split(macroImport).length !== 2 || source.split(macroCall).length !== 2) return null;
|
|
139
|
+
const signals = await this.#descriptorsOf(path.resolve(path.dirname(absPath), "sig.ts"));
|
|
140
|
+
if (!signals) return null;
|
|
141
|
+
const { names, literals } = signals;
|
|
142
|
+
if (!names.length || names.some((name) => !Object.hasOwn(literals, name))) return null;
|
|
143
|
+
//? The first name stands for what the scope takes from its base, and a signal of the base may itself be named `base`.
|
|
144
|
+
const [, ...own] = names;
|
|
145
|
+
const fromBase = JSON.parse(literals.base ?? "{}") as Record<string, unknown>;
|
|
146
|
+
const taken = new Set<string>();
|
|
147
|
+
for (const piece of pieces) {
|
|
148
|
+
const calls = [...(await Bun.file(piece).text()).matchAll(SignalDescriptors.#macroCall)];
|
|
149
|
+
const name = calls[0]?.[1];
|
|
150
|
+
if (!name || calls.length !== 1) return null;
|
|
151
|
+
if (name === "base") for (const held of Object.keys(fromBase)) taken.add(held);
|
|
152
|
+
else taken.add(name);
|
|
153
|
+
}
|
|
154
|
+
const kept = [...new Set(own)].filter((name) => !taken.has(name));
|
|
155
|
+
if (kept.includes("base") && !Object.hasOwn(fromBase, "base")) return null;
|
|
156
|
+
const literalOf = (name: string) =>
|
|
157
|
+
name === "base" ? JSON.stringify({ base: fromBase.base }) : (literals[name] ?? "{}");
|
|
158
|
+
const literal = `{${kept
|
|
159
|
+
.map((name) => literalOf(name).slice(1, -1))
|
|
160
|
+
.filter(Boolean)
|
|
161
|
+
.join(",")}}`;
|
|
162
|
+
const loaded = pieces.map((_, index) => `__akanPiece${index}`);
|
|
163
|
+
const imports = [
|
|
164
|
+
'import { loadedAfter as __akanPiecesFirst } from "akanjs/base";',
|
|
165
|
+
...pieces.map((piece, index) => `import { loaded as ${loaded[index]} } from ${JSON.stringify(piece)};`),
|
|
166
|
+
`__akanPiecesFirst(${loaded.join(", ")});`,
|
|
167
|
+
];
|
|
168
|
+
return `${imports.join("\n")}\n${source.replace(macroImport, "").replace(macroCall, () => literal)}`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
#descriptorsOf(sigFile: string): Promise<ScopeSignals | null> {
|
|
172
|
+
const known = this.#reads.get(sigFile);
|
|
173
|
+
if (known) return known;
|
|
174
|
+
const batch = [...new Set([sigFile, ...this.#sigFiles])].filter((file) => !this.#reads.has(file));
|
|
175
|
+
const read = this.#read(batch);
|
|
176
|
+
for (const file of batch)
|
|
177
|
+
this.#reads.set(
|
|
178
|
+
file,
|
|
179
|
+
read.then((byFile) => byFile.get(file) ?? null),
|
|
180
|
+
);
|
|
181
|
+
return this.#reads.get(sigFile) ?? Promise.resolve(null);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
//? `--no-env-file`: the build's `NODE_ENV` define would make Bun load `.env.production` files the build never loaded.
|
|
185
|
+
async #read(sigFiles: string[]): Promise<Map<string, ScopeSignals>> {
|
|
186
|
+
const read = new Map<string, ScopeSignals>();
|
|
187
|
+
const failures = new Map<string, string>();
|
|
188
|
+
const child = Bun.spawn([process.execPath, "--no-env-file", "--eval", SignalDescriptors.#readScript(sigFiles)], {
|
|
189
|
+
cwd: this.#workspaceRoot,
|
|
190
|
+
env: { ...process.env, ...this.#env },
|
|
191
|
+
stdout: "ignore",
|
|
192
|
+
stderr: "ignore",
|
|
193
|
+
serialization: "json",
|
|
194
|
+
ipc: (message: ScopeRead) => {
|
|
195
|
+
if (message.read) read.set(message.file, { names: message.names ?? [], literals: message.read });
|
|
196
|
+
else failures.set(message.file, message.failure ?? "");
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
let timedOut = false;
|
|
200
|
+
const kill = () => child.kill("SIGKILL");
|
|
201
|
+
const timer = setTimeout(() => {
|
|
202
|
+
timedOut = true;
|
|
203
|
+
kill();
|
|
204
|
+
}, this.#timeoutMs);
|
|
205
|
+
process.on("exit", kill);
|
|
206
|
+
const code = await child.exited.finally(() => {
|
|
207
|
+
clearTimeout(timer);
|
|
208
|
+
process.off("exit", kill);
|
|
209
|
+
});
|
|
210
|
+
for (const [file, failure] of failures)
|
|
211
|
+
this.#onUnread(`the signals of ${this.#scopeOf(file)} could not be read (${failure})`);
|
|
212
|
+
const unsent = sigFiles.filter((file) => !read.has(file) && !failures.has(file));
|
|
213
|
+
if (unsent.length > 0) {
|
|
214
|
+
const why = timedOut
|
|
215
|
+
? `they did not load within ${this.#timeoutMs / 1000}s, so the process reading them was stopped`
|
|
216
|
+
: `its process exited with code ${code}`;
|
|
217
|
+
this.#onUnread(
|
|
218
|
+
`the signals of ${unsent.map((file) => this.#scopeOf(file)).join(", ")} could not be read (${why})`,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
return read;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
#scopeOf(sigFile: string) {
|
|
225
|
+
return path.relative(this.#workspaceRoot, path.dirname(path.dirname(sigFile)));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { ObjectModule } from "./objectModule";
|
|
3
|
+
|
|
4
|
+
const OWN_THIS = new Set([
|
|
5
|
+
ts.SyntaxKind.FunctionDeclaration,
|
|
6
|
+
ts.SyntaxKind.FunctionExpression,
|
|
7
|
+
ts.SyntaxKind.MethodDeclaration,
|
|
8
|
+
ts.SyntaxKind.GetAccessor,
|
|
9
|
+
ts.SyntaxKind.SetAccessor,
|
|
10
|
+
ts.SyntaxKind.Constructor,
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
//* The exports a caller may call without the object it reached them through: an arrow function, or a function whose
|
|
14
|
+
//* parameters and body read no `this` outside a nested function that binds its own. Any other export (a call's result,
|
|
15
|
+
//* a re-export, a class, a `let`) may read `this`, so it is never one of them.
|
|
16
|
+
export class ThisFreeExports {
|
|
17
|
+
static read(source: string, file: string): Set<string> {
|
|
18
|
+
const sourceFile = ts.createSourceFile(
|
|
19
|
+
file,
|
|
20
|
+
source,
|
|
21
|
+
ts.ScriptTarget.Latest,
|
|
22
|
+
false,
|
|
23
|
+
ObjectModule.scriptKindOf(file),
|
|
24
|
+
);
|
|
25
|
+
const free = new Map<string, boolean>();
|
|
26
|
+
const exported = new Map<string, string>();
|
|
27
|
+
const names = new Set<string>();
|
|
28
|
+
for (const statement of sourceFile.statements) {
|
|
29
|
+
if (ts.isFunctionDeclaration(statement) && statement.body) {
|
|
30
|
+
const name = statement.name?.text ?? "default";
|
|
31
|
+
free.set(name, !ThisFreeExports.#readsThis(statement));
|
|
32
|
+
if (ThisFreeExports.#hasModifier(statement, ts.SyntaxKind.DefaultKeyword)) exported.set("default", name);
|
|
33
|
+
else if (ThisFreeExports.#hasModifier(statement, ts.SyntaxKind.ExportKeyword)) exported.set(name, name);
|
|
34
|
+
} else if (ts.isVariableStatement(statement)) {
|
|
35
|
+
const constant = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0;
|
|
36
|
+
const isExported = ThisFreeExports.#hasModifier(statement, ts.SyntaxKind.ExportKeyword);
|
|
37
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
38
|
+
if (!ts.isIdentifier(declaration.name)) continue;
|
|
39
|
+
const name = declaration.name.text;
|
|
40
|
+
free.set(name, constant && !!declaration.initializer && ThisFreeExports.#isFree(declaration.initializer));
|
|
41
|
+
if (isExported) exported.set(name, name);
|
|
42
|
+
}
|
|
43
|
+
} else if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && statement.exportClause) {
|
|
44
|
+
if (!ts.isNamedExports(statement.exportClause)) continue;
|
|
45
|
+
for (const element of statement.exportClause.elements)
|
|
46
|
+
exported.set(element.name.text, (element.propertyName ?? element.name).text);
|
|
47
|
+
} else if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
|
|
48
|
+
const value = ThisFreeExports.#unwrap(statement.expression);
|
|
49
|
+
if (ts.isIdentifier(value)) exported.set("default", value.text);
|
|
50
|
+
else if (ThisFreeExports.#isFree(value)) names.add("default");
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
for (const [name, local] of exported) if (free.get(local)) names.add(name);
|
|
54
|
+
return names;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
static #isFree(node: ts.Expression) {
|
|
58
|
+
const value = ThisFreeExports.#unwrap(node);
|
|
59
|
+
if (ts.isArrowFunction(value)) return true;
|
|
60
|
+
return ts.isFunctionExpression(value) && !ThisFreeExports.#readsThis(value);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
static #readsThis(fn: ts.FunctionLikeDeclaration) {
|
|
64
|
+
const visit = (node: ts.Node): boolean => {
|
|
65
|
+
if (node.kind === ts.SyntaxKind.ThisKeyword) return true;
|
|
66
|
+
if (OWN_THIS.has(node.kind)) return false;
|
|
67
|
+
return ts.forEachChild(node, visit) ?? false;
|
|
68
|
+
};
|
|
69
|
+
return [...fn.parameters, ...(fn.body ? [fn.body] : [])].some(visit);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
static #unwrap(node: ts.Expression): ts.Expression {
|
|
73
|
+
let current = node;
|
|
74
|
+
while (
|
|
75
|
+
ts.isParenthesizedExpression(current) ||
|
|
76
|
+
ts.isAsExpression(current) ||
|
|
77
|
+
ts.isSatisfiesExpression(current) ||
|
|
78
|
+
ts.isTypeAssertionExpression(current)
|
|
79
|
+
)
|
|
80
|
+
current = current.expression;
|
|
81
|
+
return current;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
static #hasModifier(node: ts.Node, kind: ts.SyntaxKind) {
|
|
85
|
+
return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === kind);
|
|
86
|
+
}
|
|
87
|
+
}
|