@akanjs/devkit 3.3.0-rc.9 → 3.3.1-rc.0
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/DEV_RUNTIME_KNOBS.md +1 -1
- package/README.ko.md +7 -1
- package/README.md +7 -1
- package/akanApp/akanApp.host.test.ts +3 -1
- package/akanApp/akanApp.host.ts +26 -2
- package/akanApp/akanApp.host.wiring.test.ts +111 -0
- package/akanApp/devHostPolicy.ts +5 -0
- package/akanApp/devMetadataRestart.ts +93 -0
- package/akanApp/devRecycler.test.ts +2 -0
- package/akanApp/devRecycler.ts +9 -0
- package/akanConfig/akanBin.ts +4 -0
- package/akanConfig/akanConfig.test.ts +307 -18
- package/akanConfig/akanConfig.ts +104 -210
- package/akanConfig/akanPreview.test.ts +28 -0
- package/akanConfig/akanPreview.ts +24 -0
- package/akanConfig/akanWorkers.test.ts +73 -0
- package/akanConfig/akanWorkers.ts +61 -0
- package/akanConfig/desktopServerConfig.ts +96 -0
- package/akanConfig/dockerImage.ts +233 -0
- package/akanConfig/index.ts +3 -0
- package/akanConfig/nativeFileSettings.ts +33 -0
- package/akanConfig/types.ts +4 -0
- package/app/appBin.test.ts +63 -0
- package/app/appBin.ts +50 -0
- package/app/applicationBuildReporter.test.ts +51 -1
- package/app/applicationBuildReporter.ts +6 -1
- package/app/applicationBuildRunner.test.ts +438 -7
- package/app/applicationBuildRunner.ts +237 -37
- package/app/clientServerBoundary.test.ts +115 -0
- package/app/clientServerBoundary.ts +89 -0
- package/app/dictionarySizes.test.ts +40 -0
- package/app/dictionarySizes.ts +95 -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 +7 -2
- package/artifact/storeBootstrap.test.ts +28 -0
- package/artifact/storeBootstrap.ts +64 -8
- package/biome.base.json +7 -5
- package/codeAgent/index.ts +1 -34
- package/codeAgent/skills/akan-agent/SKILL.md +2 -2
- package/codeAgent/skills/akan-debug/SKILL.md +11 -5
- package/codeAgent/skills/akan-deps/SKILL.md +10 -3
- 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 +65 -30
- package/codeAgent/skills/akan-query/SKILL.md +13 -20
- package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
- package/codeAgent/skills/akan-service/SKILL.md +21 -20
- package/codeAgent/skills/akan-transport/SKILL.md +5 -14
- package/codeAgent/skills/akan-ui/SKILL.md +16 -21
- package/codeAgent/skills/akan-validate/SKILL.md +8 -2
- package/commandDecorators/command.ts +28 -12
- package/commandDecorators/commandBuilder.ts +8 -1
- package/commandDecorators/commandDecorators.test.ts +70 -3
- package/commandDecorators/helpFormatter.ts +14 -12
- package/context/akanContext.ts +2 -0
- package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
- package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
- package/docs/apiReference.test.ts +25 -0
- package/docs/apiReference.ts +38 -5
- package/docs/declarationReader.ts +30 -0
- package/docs/errorCodeReference.test.ts +26 -0
- package/docs/errorCodeScan.ts +23 -6
- package/executors/appExecutor.ts +26 -12
- package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
- package/executors/clientRuntimeKeys.fixture.json +393 -0
- package/executors/clientRuntimeKeys.test.ts +1692 -0
- package/executors/executor.ts +14 -6
- package/executors/executors.test.ts +155 -1
- package/executors/pkgExecutor.ts +2 -1
- package/executors/sysExecutor.ts +112 -8
- package/executors/workspaceExecutor.ts +7 -4
- package/frontendBuild/allRoutesBuilder.ts +99 -7
- package/frontendBuild/autoImportSync.ts +3 -2
- package/frontendBuild/buildRouteClient.test.ts +684 -6
- package/frontendBuild/clientBuildTypes.ts +26 -0
- package/frontendBuild/clientEntriesBundler.test.ts +79 -0
- package/frontendBuild/clientEntriesBundler.ts +70 -1
- package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
- package/frontendBuild/clientEntryDiscovery.ts +134 -12
- package/frontendBuild/clientEntryGroups.test.ts +77 -0
- package/frontendBuild/clientEntryGroups.ts +61 -0
- package/frontendBuild/csrDevArtifactWriter.ts +2 -2
- package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
- package/frontendBuild/csrDevModuleCompiler.ts +44 -8
- package/frontendBuild/csrDevPatcher.test.ts +4 -5
- package/frontendBuild/csrDevPatcher.ts +37 -11
- package/frontendBuild/csrDevTypes.ts +9 -0
- package/frontendBuild/cssCandidateCache.test.ts +12 -0
- package/frontendBuild/cssCandidateCache.ts +5 -3
- package/frontendBuild/cssCompiler.test.ts +14 -0
- package/frontendBuild/devBarrelImports.test.ts +127 -0
- package/frontendBuild/devBarrelImports.ts +81 -21
- package/frontendBuild/devChangePlanner.ts +0 -1
- package/frontendBuild/devRegistryBundler.ts +4 -2
- package/frontendBuild/devRouteRuntime.test.ts +493 -0
- package/frontendBuild/devRouteRuntime.ts +167 -0
- package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
- package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
- package/frontendBuild/dictionaryConstants.ts +136 -0
- package/frontendBuild/dictionaryOwnParts.ts +88 -0
- package/frontendBuild/dictionaryPackState.ts +131 -0
- package/frontendBuild/dictionaryPacking.test.ts +207 -0
- package/frontendBuild/dictionaryPacking.ts +160 -0
- package/frontendBuild/dictionaryRoutes.test.ts +251 -0
- package/frontendBuild/dictionaryRoutes.ts +227 -0
- package/frontendBuild/frontendBuild.test.ts +5 -3
- package/frontendBuild/hmrWatcher.test.ts +3 -1
- package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
- package/frontendBuild/pagesBundleBuilder.ts +78 -2
- package/frontendBuild/plainStylesheet.test.ts +2 -2
- package/frontendBuild/precompressArtifacts.test.ts +22 -0
- package/frontendBuild/precompressArtifacts.ts +34 -8
- package/frontendBuild/registryMetadataFingerprint.ts +3 -3
- package/frontendBuild/renderedEntries.ts +144 -0
- package/frontendBuild/routeClientBuilder.ts +407 -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/ssrBaseArtifactBuilder.ts +30 -35
- 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.test.ts +47 -3
- package/frontendBuild/vendorNarrowing.ts +38 -2
- package/frontendBuild/vendorSpecifiers.ts +2 -0
- package/frontendBuild/workerChunks.ts +61 -0
- package/guideline/agentAssets.ts +1 -1
- package/incrementalBuilder/buildBatch.proc.ts +27 -1
- package/incrementalBuilder/buildBatchProtocol.ts +1 -0
- package/incrementalBuilder/builderWatch.ts +11 -1
- package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
- package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
- package/incrementalBuilder/pendingMetadata.test.ts +27 -0
- package/incrementalBuilder/pendingMetadata.ts +19 -0
- package/integration/devResourceProbe.ts +14 -0
- package/integration/devStability.integration.test.ts +46 -21
- package/integration/renderAdmissionSoak.test.ts +39 -34
- package/integration/renderAdmissionSoak.ts +6 -0
- package/integration/ssrMemoryProbe.ts +5 -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 +50 -3
- package/lint/biomeBase.ts +1 -1
- package/lint/biomeCheck.test.ts +173 -0
- package/lint/biomeCheck.ts +132 -0
- package/lint/linter.test.ts +16 -11
- 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.test.ts +18 -3
- package/mobile/desktopServerStage.ts +7 -2
- package/mobile/nativeApp.test.ts +13 -5
- package/mobile/nativeApp.ts +9 -4
- package/mobile/nativeConfig.test.ts +27 -7
- package/mobile/nativeConfig.ts +19 -9
- package/mobile/nativePublicEnv.ts +1 -1
- package/mobile/serverBundleSecrets.ts +43 -0
- package/package.json +11 -12
- package/packageExports.test.ts +3 -2
- package/preview/PreviewView.ts +43 -6
- package/preview/previewView.test.ts +31 -0
- package/quality/dictionaryKeys.test.ts +356 -0
- package/quality/dictionaryKeys.ts +488 -0
- package/quality/maintainabilityContract.test.ts +4 -1
- 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 +86 -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/fakeTerminal.ts +45 -0
- package/test/secretEnvFixture.ts +147 -0
- package/test/testHelpers.ts +11 -0
- package/transforms/barrelAnalyzer.ts +24 -2
- 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 +57 -0
- package/transforms/modelReference.test.ts +197 -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 +631 -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 +189 -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 +834 -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 +211 -0
- package/transforms/secretEnvDeclaration.ts +219 -0
- package/transforms/secretEnvFile.test.ts +117 -0
- package/transforms/secretEnvFile.ts +132 -0
- package/transforms/secretEnvName.test.ts +54 -0
- package/transforms/secretEnvName.ts +29 -0
- package/transforms/secretEnvSource.test.ts +152 -0
- package/transforms/secretEnvSource.ts +197 -0
- package/transforms/serverEnvEvaluationError.ts +11 -0
- package/transforms/serverEnvPlugin.test.ts +157 -1
- package/transforms/serverEnvPlugin.ts +123 -19
- package/transforms/serverEnvProfile.test.ts +129 -2
- package/transforms/serverEnvProfile.ts +133 -43
- package/transforms/serverEnvSecrets.test.ts +268 -0
- package/transforms/signalDescriptors.test.ts +280 -0
- package/transforms/signalDescriptors.ts +230 -0
- package/transforms/thisFreeExports.ts +87 -0
- package/transforms/transforms.test.ts +184 -2
- package/transforms/tsconfigPackageResolver.test.ts +1 -0
- package/tunnel/createTunnel.ts +5 -1
- package/tunnel/ssh2Module.test.ts +37 -0
- package/tunnel/ssh2Module.ts +28 -0
- package/tunnel/sshTunnel.ts +4 -2
- package/typecheck/projectTypecheck.test.ts +32 -1
- package/typecheck/projectTypecheck.ts +3 -3
- package/typecheck/typeChecker.test.ts +50 -0
- package/typecheck/typeChecker.ts +14 -8
- package/typecheck/withheldDiagnostics.ts +44 -0
- package/util/devInstallCommand.ts +7 -0
- package/util/jsonFormatter.test.ts +13 -9
- 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/envSeed.test.ts +30 -1
- package/workspace/envSeed.ts +30 -1
- package/workspace/mainCheckout.test.ts +55 -0
- package/workspace/mainCheckout.ts +38 -0
- package/workspace/scanInfo.test.ts +39 -0
- package/workspace/scanInfo.ts +55 -6
- package/workspace/slicePlanner.ts +2 -1
- package/workspace/workspaceLayout.test.ts +22 -1
- package/workspace/workspaceLayout.ts +3 -3
- package/CHANGELOG.md +0 -2904
- package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
- package/codeAgent/agent/AkanCodeServices.ts +0 -122
- package/codeAgent/agent/AkanContextFiles.ts +0 -94
- package/codeAgent/agent/CodeAgent.ts +0 -626
- package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
- package/codeAgent/agent/CodeAgentAsks.ts +0 -66
- package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
- package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
- package/codeAgent/agent/CodeAgentGate.ts +0 -258
- package/codeAgent/agent/CodeAgentProxy.ts +0 -83
- package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
- package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
- package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
- package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
- package/codeAgent/agent/CodeAgentUi.ts +0 -47
- package/codeAgent/agent/CodeMailbox.ts +0 -148
- package/codeAgent/agent/CodeSessionFork.ts +0 -56
- package/codeAgent/agent/CodeSessionIndex.ts +0 -78
- package/codeAgent/agent/SubagentPool.ts +0 -219
- package/codeAgent/agent/WorkspaceTrust.ts +0 -200
- package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
- package/codeAgent/agent/akanCodeModel.ts +0 -47
- package/codeAgent/agent/akanCodeServices.test.ts +0 -54
- package/codeAgent/agent/akanContextFiles.test.ts +0 -116
- package/codeAgent/agent/akanSystemPrompt.ts +0 -50
- package/codeAgent/agent/codeAgent.test.ts +0 -337
- package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
- package/codeAgent/agent/codeAgentContract.test.ts +0 -755
- package/codeAgent/agent/codeAgentHosts.ts +0 -30
- package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
- package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
- package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
- package/codeAgent/agent/codeMailbox.test.ts +0 -76
- package/codeAgent/agent/codeSessionFork.test.ts +0 -58
- package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
- package/codeAgent/agent/consoleToStderr.ts +0 -8
- package/codeAgent/agent/jsonLines.ts +0 -29
- package/codeAgent/agent/stringArg.ts +0 -5
- package/codeAgent/feedback/DevLogFeedback.ts +0 -82
- package/codeAgent/feedback/PreviewFeedback.ts +0 -46
- package/codeAgent/feedback/TurnFeedback.ts +0 -98
- package/codeAgent/feedback/VerifyFeedback.ts +0 -39
- package/codeAgent/tools/AkanCli.ts +0 -51
- package/codeAgent/tools/AkanCodePlugins.ts +0 -142
- package/codeAgent/tools/AkanEditScope.ts +0 -53
- package/codeAgent/tools/AkanEnvKeys.ts +0 -50
- package/codeAgent/tools/AkanToolPack.ts +0 -86
- package/codeAgent/tools/AkanVerifier.ts +0 -30
- package/codeAgent/tools/AskToolPack.ts +0 -99
- package/codeAgent/tools/DeepSeekWeb.ts +0 -127
- package/codeAgent/tools/MailToolPack.ts +0 -76
- package/codeAgent/tools/McpClient.ts +0 -209
- package/codeAgent/tools/McpOAuth.ts +0 -233
- package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
- package/codeAgent/tools/McpServerConfig.ts +0 -131
- package/codeAgent/tools/McpSignIn.ts +0 -158
- package/codeAgent/tools/McpTokenStore.ts +0 -128
- package/codeAgent/tools/McpToolPack.ts +0 -206
- package/codeAgent/tools/SessionToolPack.ts +0 -91
- package/codeAgent/tools/WebToolPack.ts +0 -315
- package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
- package/codeAgent/tools/askToolPack.test.ts +0 -116
- package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
- package/codeAgent/tools/mcpOAuth.test.ts +0 -648
- package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
- package/piDependencyPins.test.ts +0 -45
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { writeText } from "./testHelpers";
|
|
4
|
+
|
|
5
|
+
const environments = ["local", "main"] as const;
|
|
6
|
+
|
|
7
|
+
export const secretEnvSentinels = {
|
|
8
|
+
jwt: "sentinel-jwt-2f0c",
|
|
9
|
+
google: "sentinel-google-91ab",
|
|
10
|
+
bots: ["sentinel-bot-a-44d1", "sentinel-bot-b-55e2"],
|
|
11
|
+
webhook: "https://hooks.example.test/services/sentinel-hook-66f3",
|
|
12
|
+
pem: "-----BEGIN PRIVATE KEY-----\nsentinel-pem-line-one-aa17\nsentinel-pem-line-two-bb28\n-----END PRIVATE KEY-----\n",
|
|
13
|
+
postgres: "postgres://app:sentinel-db-pass-77a4@db.example.test:5432/app",
|
|
14
|
+
storage: "https://minio:sentinel-url-pass-cc39@storage.example.test",
|
|
15
|
+
dollar: ["sentinel-$HOME-", '"quoted"-$', "{USER}-dd40"].join(""),
|
|
16
|
+
apostrophe: "sentinel-it's-$1-ee51",
|
|
17
|
+
libPass: "sentinel-lib-pass-88b5",
|
|
18
|
+
libJwt: "sentinel-lib-jwt-99c6",
|
|
19
|
+
local: "sentinel-local-llm-ff62",
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const secretEnvPlain = { hostname: "app.example.test", clientID: "plain-client-id", region: "ap-northeast-2" };
|
|
23
|
+
|
|
24
|
+
const s = secretEnvSentinels;
|
|
25
|
+
|
|
26
|
+
const mainEnv = (extra = "", head = "") => `${head}import { libEnv } from "./env.server.type";
|
|
27
|
+
|
|
28
|
+
export const env = {
|
|
29
|
+
...libEnv,
|
|
30
|
+
hostname: ${JSON.stringify(secretEnvPlain.hostname)},
|
|
31
|
+
security: {
|
|
32
|
+
jwtSecret: ${JSON.stringify(s.jwt)},
|
|
33
|
+
verifies: [["password"], ["email"]],
|
|
34
|
+
accessTokenSeconds: 900,
|
|
35
|
+
sso: { google: { clientID: ${JSON.stringify(secretEnvPlain.clientID)}, clientSecret: ${JSON.stringify(s.google)} } },
|
|
36
|
+
},
|
|
37
|
+
objectStorage: { region: ${JSON.stringify(secretEnvPlain.region)}, endpoint: ${JSON.stringify(s.storage)} },
|
|
38
|
+
discord: { tokens: ${JSON.stringify(s.bots)}, webhook: ${JSON.stringify(s.webhook)} },
|
|
39
|
+
pushNoti: { firebase: { type: "service_account", private_key: ${JSON.stringify(s.pem)} } },
|
|
40
|
+
message: { apiSecret: ${JSON.stringify(s.dollar)}, senderPassword: ${JSON.stringify(s.apostrophe)} },
|
|
41
|
+
database: { postgres: { url: process.env.DATABASE_URL ?? ${JSON.stringify(s.postgres)} } },${extra}
|
|
42
|
+
} as const;
|
|
43
|
+
`;
|
|
44
|
+
|
|
45
|
+
export interface SecretEnvFixture {
|
|
46
|
+
appDir: string;
|
|
47
|
+
envDir: string;
|
|
48
|
+
libEnvFile: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const writeSecretEnvFixture = async (
|
|
52
|
+
root: string,
|
|
53
|
+
{ app = "demo", mainExtra = "", mainHead = "" } = {},
|
|
54
|
+
): Promise<SecretEnvFixture> => {
|
|
55
|
+
const appDir = path.join(root, "apps", app);
|
|
56
|
+
const envDir = path.join(appDir, "env");
|
|
57
|
+
const libEnvFile = path.join(root, "libs/util/env/env.server.testing.ts");
|
|
58
|
+
await writeText(
|
|
59
|
+
path.join(envDir, "env.server.ts"),
|
|
60
|
+
[
|
|
61
|
+
...environments.map((name) => `import { env as ${name} } from "./env.server.${name}";`),
|
|
62
|
+
`const envConfigs = { ${environments.join(", ")} };`,
|
|
63
|
+
'const currentEnv = process.env.AKAN_PUBLIC_ENV ?? "local";',
|
|
64
|
+
"export const env = envConfigs[currentEnv as keyof typeof envConfigs];",
|
|
65
|
+
"",
|
|
66
|
+
].join("\n"),
|
|
67
|
+
);
|
|
68
|
+
await writeText(
|
|
69
|
+
path.join(envDir, "env.server.type.ts"),
|
|
70
|
+
`import { env as utilOption } from ${JSON.stringify(libEnvFile)};\n\nexport const libEnv = { ...utilOption };\n`,
|
|
71
|
+
);
|
|
72
|
+
await writeText(
|
|
73
|
+
libEnvFile,
|
|
74
|
+
`export const env = {\n hostname: null,\n security: { jwtSecret: ${JSON.stringify(s.libJwt)}, verifies: [["password"]] },\n mailer: { address: "noreply@example.test", auth: { user: "mailer", pass: ${JSON.stringify(s.libPass)} } },\n};\n`,
|
|
75
|
+
);
|
|
76
|
+
await writeText(path.join(envDir, "env.server.main.ts"), mainEnv(mainExtra, mainHead));
|
|
77
|
+
await writeText(
|
|
78
|
+
path.join(envDir, "env.server.local.ts"),
|
|
79
|
+
`export const env = { hostname: "localhost", llm: { apiKey: ${JSON.stringify(s.local)} } };\n`,
|
|
80
|
+
);
|
|
81
|
+
return { appDir, envDir, libEnvFile };
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export const secretEnvFixtureNames = [
|
|
85
|
+
"JWT_SECRET",
|
|
86
|
+
"SECURITY__SSO__GOOGLE__CLIENT_SECRET",
|
|
87
|
+
"MAILER__AUTH__PASS",
|
|
88
|
+
"OBJECT_STORAGE__ENDPOINT",
|
|
89
|
+
"DISCORD__TOKENS",
|
|
90
|
+
"DISCORD__WEBHOOK",
|
|
91
|
+
"PUSH_NOTI__FIREBASE__PRIVATE_KEY",
|
|
92
|
+
"MESSAGE__API_SECRET",
|
|
93
|
+
"MESSAGE__SENDER_PASSWORD",
|
|
94
|
+
"POSTGRES_URL",
|
|
95
|
+
];
|
|
96
|
+
|
|
97
|
+
export const holdsSentinel = (text: string) => text.includes("sentinel-");
|
|
98
|
+
|
|
99
|
+
//? Windows keeps no mode bits: there `icacls` prints one line per entry of the file's access list.
|
|
100
|
+
export const isKeptToUser = async (file: string) => {
|
|
101
|
+
if (process.platform !== "win32") return ((await stat(file)).mode & 0o777) === 0o600;
|
|
102
|
+
const user = Bun.spawnSync(["whoami"]).stdout.toString().trim().toLowerCase();
|
|
103
|
+
const entries = Bun.spawnSync(["icacls", file])
|
|
104
|
+
.stdout.toString()
|
|
105
|
+
.split(/\r?\n/)
|
|
106
|
+
.map((line) => line.replace(file, "").trim().toLowerCase())
|
|
107
|
+
.filter((line) => /:\([a-z,()]+\)$/.test(line));
|
|
108
|
+
return entries.length === 1 && entries[0] === `${user}:(f)`;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
//* What no search of a build's files tells from code: a short password, a passphrase of plain words, a value under
|
|
112
|
+
//* eight characters, and a plain-named key under a secret-named one.
|
|
113
|
+
export const computedSecrets = {
|
|
114
|
+
password: "sentinel-12c",
|
|
115
|
+
passphrase: "sentinel-correct-horse-battery-xyzz",
|
|
116
|
+
short: "s9-k2",
|
|
117
|
+
user: "sentinel-user",
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
//* One string under a secret-named key and a plain one: a long mixed one, a short one, and one under eight characters.
|
|
121
|
+
export const twinSecrets = { long: "sentinel-Twin-7d21-Xq", plain: "sentinel-db", short: "s-pin" };
|
|
122
|
+
|
|
123
|
+
export const twinSecretEnv = [
|
|
124
|
+
"",
|
|
125
|
+
` audit: { password: ${JSON.stringify(twinSecrets.long)}, label: ${JSON.stringify(twinSecrets.long)} },`,
|
|
126
|
+
` cache: { password: ${JSON.stringify(twinSecrets.plain)}, name: ${JSON.stringify(twinSecrets.plain)} },`,
|
|
127
|
+
` door: { secret: ${JSON.stringify(twinSecrets.short)}, hint: ${JSON.stringify(twinSecrets.short)} },`,
|
|
128
|
+
].join("\n");
|
|
129
|
+
|
|
130
|
+
export const computedSecretKeys = ["store.password", "store.passphrase", "otp.secret", "credentials.user"];
|
|
131
|
+
|
|
132
|
+
export const writeComputedSecretFixture = async (root: string, app = "demo"): Promise<SecretEnvFixture> => {
|
|
133
|
+
await writeText(
|
|
134
|
+
path.join(root, "apps", app, "srvkit/keys.ts"),
|
|
135
|
+
`export const keys = ${JSON.stringify({ password: computedSecrets.password, passphrase: computedSecrets.passphrase, user: computedSecrets.user })};\n`,
|
|
136
|
+
);
|
|
137
|
+
return await writeSecretEnvFixture(root, {
|
|
138
|
+
app,
|
|
139
|
+
mainHead: 'import { keys } from "../srvkit/keys";\n',
|
|
140
|
+
mainExtra: [
|
|
141
|
+
"",
|
|
142
|
+
" store: { password: keys.password, passphrase: keys.passphrase },",
|
|
143
|
+
` otp: { secret: ${JSON.stringify(computedSecrets.short.split("-"))}.join("-") },`,
|
|
144
|
+
" credentials: { user: keys.user },",
|
|
145
|
+
].join("\n"),
|
|
146
|
+
});
|
|
147
|
+
};
|
package/test/testHelpers.ts
CHANGED
|
@@ -129,6 +129,17 @@ export const writeJson = async (filePath: string, value: object) => {
|
|
|
129
129
|
await writeText(filePath, `${JSON.stringify(value, null, 2)}\n`);
|
|
130
130
|
};
|
|
131
131
|
|
|
132
|
+
export const printedInOwnProcess = async (script: string, cwd: string): Promise<unknown> => {
|
|
133
|
+
const proc = Bun.spawn([process.execPath, "--eval", script], { cwd, stdout: "pipe", stderr: "pipe" });
|
|
134
|
+
const [code, stdout, stderr] = await Promise.all([
|
|
135
|
+
proc.exited,
|
|
136
|
+
new Response(proc.stdout).text(),
|
|
137
|
+
new Response(proc.stderr).text(),
|
|
138
|
+
]);
|
|
139
|
+
if (code !== 0) throw new Error(`the script exited with code ${code}:\n${stderr}`);
|
|
140
|
+
return JSON.parse(stdout.trim().split("\n").at(-1) ?? "null");
|
|
141
|
+
};
|
|
142
|
+
|
|
132
143
|
export const heldMtimeIndex = () => {
|
|
133
144
|
const primes: PromiseWithResolvers<void>[] = [];
|
|
134
145
|
const scans: PromiseWithResolvers<string[]>[] = [];
|
|
@@ -20,12 +20,16 @@ export interface PackageEntry {
|
|
|
20
20
|
pkgDir: string;
|
|
21
21
|
/** Emit absolute file paths: an installed package's exports name its barrels, never the files behind them. */
|
|
22
22
|
preserveFilePath?: boolean;
|
|
23
|
+
/** The installed package's own folder: its entry may re-export a file beside the entry's folder (`../vendor/x`). */
|
|
24
|
+
rootDir?: string;
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
export interface BarrelAnalyzerOptions {
|
|
26
28
|
resolvePackage: (pkgName: string) => Promise<PackageEntry | null>;
|
|
27
29
|
/** Resolves to an absolute file path on disk. */
|
|
28
30
|
resolveRelative?: (fromFile: string, relSpec: string) => Promise<string | null>;
|
|
31
|
+
/** Maps a name the barrel entry re-exports from a package to that package, when it resolves the same from here. */
|
|
32
|
+
packageRoot?: string;
|
|
29
33
|
}
|
|
30
34
|
|
|
31
35
|
// `Transpiler.scan` gives the export names but not their sources; this regex supplies the name↔source mapping.
|
|
@@ -145,7 +149,11 @@ export class BarrelAnalyzer {
|
|
|
145
149
|
const nsAs = m[2];
|
|
146
150
|
const namedList = m[3];
|
|
147
151
|
const spec = m[5] ?? "";
|
|
148
|
-
if (!isRelative(spec))
|
|
152
|
+
if (!isRelative(spec)) {
|
|
153
|
+
if (namedList !== undefined && absFile === pkg.entryFile && this.#isSamePackage(spec, absFile))
|
|
154
|
+
attribute(namedList, spec);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
149
157
|
|
|
150
158
|
if (star) {
|
|
151
159
|
if (!nsAs) starSpecs.push(spec);
|
|
@@ -210,7 +218,11 @@ export class BarrelAnalyzer {
|
|
|
210
218
|
|
|
211
219
|
#subpathFor(pkg: PackageEntry, absFile: string): string | null {
|
|
212
220
|
const rel = path.relative(pkg.pkgDir, absFile);
|
|
213
|
-
if (!rel ||
|
|
221
|
+
if (!rel || path.isAbsolute(rel)) return null;
|
|
222
|
+
if (rel.startsWith("..")) {
|
|
223
|
+
const inPackage = pkg.preserveFilePath && pkg.rootDir ? path.relative(pkg.rootDir, absFile) : "..";
|
|
224
|
+
if (inPackage.startsWith("..") || path.isAbsolute(inPackage)) return null;
|
|
225
|
+
}
|
|
214
226
|
if (pkg.preserveFilePath) return absFile.split(path.sep).join("/");
|
|
215
227
|
const ext = CANDIDATE_EXTS.find((candidate) => rel.endsWith(candidate));
|
|
216
228
|
const parts = (ext ? rel.slice(0, -ext.length) : rel).split(path.sep);
|
|
@@ -220,6 +232,16 @@ export class BarrelAnalyzer {
|
|
|
220
232
|
return tail === "" ? pkg.pkgName : `${pkg.pkgName}/${tail}`;
|
|
221
233
|
}
|
|
222
234
|
|
|
235
|
+
#isSamePackage(spec: string, absFile: string): boolean {
|
|
236
|
+
const root = this.#opts.packageRoot;
|
|
237
|
+
if (!root) return false;
|
|
238
|
+
try {
|
|
239
|
+
return Bun.resolveSync(spec, path.dirname(absFile)) === Bun.resolveSync(spec, root);
|
|
240
|
+
} catch {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
223
245
|
async #resolveRel(fromFile: string, relSpec: string): Promise<string | null> {
|
|
224
246
|
if (this.#opts.resolveRelative) return this.#opts.resolveRelative(fromFile, relSpec);
|
|
225
247
|
return defaultResolveRelative(fromFile, relSpec);
|
|
@@ -4,7 +4,11 @@ import ts from "typescript";
|
|
|
4
4
|
import { StoreBootstrap } from "../artifact/storeBootstrap";
|
|
5
5
|
import type { App } from "../commandDecorators";
|
|
6
6
|
import { BarrelAnalyzer, type BarrelExportMap, type PackageEntry } from "./barrelAnalyzer";
|
|
7
|
+
import { ModuleParts } from "./moduleParts";
|
|
7
8
|
import { loaderFor, type NamedItem } from "./moduleSyntax";
|
|
9
|
+
import { ObjectMemberImports } from "./objectMemberImports";
|
|
10
|
+
import { PartModules, type PartSource } from "./partModules";
|
|
11
|
+
import type { RouteRuntime } from "./routeRuntime";
|
|
8
12
|
|
|
9
13
|
export interface BarrelImportsPluginOptions {
|
|
10
14
|
/** Absolute paths whose content is returned unchanged (e.g. node_modules). */
|
|
@@ -13,53 +17,101 @@ export interface BarrelImportsPluginOptions {
|
|
|
13
17
|
pipeAfter?: (source: string, args: { path: string }) => string | Promise<string | null> | null;
|
|
14
18
|
/** Barrels the bundle leaves external: a rewritten import would inline the modules the import map already serves. */
|
|
15
19
|
external?: readonly string[];
|
|
16
|
-
/** The barrels to rewrite, instead of the app config's `barrelImports
|
|
20
|
+
/** The barrels to rewrite, instead of the app config's `barrelImports`: a CSR bundle's, which narrows no object or package barrel by member. */
|
|
17
21
|
barrels?: readonly string[];
|
|
22
|
+
/** What `akanjs/ui/modelRuntime` holds instead of its empty source, in a build loading only the page runtime. */
|
|
23
|
+
modelRuntime?: string;
|
|
24
|
+
/** Gives each client module the runtime pieces of the modules it names, in a build loading only the page runtime. */
|
|
25
|
+
routeRuntime?: RouteRuntime | null;
|
|
26
|
+
/** Takes each workspace file apart by export, so a chunk holds the exports asked for; holds the parts read so far. */
|
|
27
|
+
parts?: Map<string, ModuleParts | null>;
|
|
18
28
|
}
|
|
19
29
|
|
|
20
30
|
export const createBarrelImportsPlugin = async (
|
|
21
31
|
app: App,
|
|
22
|
-
{
|
|
32
|
+
{
|
|
33
|
+
skipPath = defaultSkipPath,
|
|
34
|
+
pipeAfter,
|
|
35
|
+
external = [],
|
|
36
|
+
barrels: only,
|
|
37
|
+
modelRuntime,
|
|
38
|
+
routeRuntime,
|
|
39
|
+
parts,
|
|
40
|
+
}: BarrelImportsPluginOptions = {},
|
|
23
41
|
): Promise<BunPlugin> => {
|
|
24
42
|
const barrels = [...new Set(only ?? (await app.getConfig()).barrelImports)].filter(
|
|
25
43
|
(barrel) => barrel && !external.includes(barrel),
|
|
26
44
|
);
|
|
45
|
+
const route = !only;
|
|
46
|
+
const resolvePackage = await createTsconfigPackageResolver(app);
|
|
27
47
|
const analyzer = new BarrelAnalyzer({
|
|
28
|
-
resolvePackage
|
|
48
|
+
resolvePackage,
|
|
49
|
+
...(route ? { packageRoot: app.workspace.workspaceRoot } : {}),
|
|
29
50
|
});
|
|
51
|
+
const resolve = ObjectMemberImports.resolverOf(resolvePackage);
|
|
52
|
+
const objects = route ? new ObjectMemberImports({ resolve, barrels: { names: barrels, analyzer } }) : null;
|
|
53
|
+
|
|
54
|
+
const read = async (realPath: string): Promise<PartSource | null> => {
|
|
55
|
+
const file = Bun.file(realPath);
|
|
56
|
+
//? A build's `files` entry has no copy on disk: Bun loads it itself.
|
|
57
|
+
if (!(await file.exists())) return null;
|
|
58
|
+
if (modelRuntime !== undefined && StoreBootstrap.modelRuntimeFilter.test(realPath))
|
|
59
|
+
return { source: modelRuntime, settled: true };
|
|
60
|
+
const whole = routeRuntime?.redirectOf(realPath);
|
|
61
|
+
if (whole) return { source: whole, settled: true };
|
|
62
|
+
let source = await file.text();
|
|
63
|
+
if (skipPath(realPath)) return { source, settled: true };
|
|
64
|
+
|
|
65
|
+
// Bun's macro evaluator races when a rewritten module holds `with { type: "macro" }` imports while another
|
|
66
|
+
// macro host evaluates (a macro identifier ends up undefined), so macro hosts keep their barrel imports.
|
|
67
|
+
const macroHost = MACRO_ATTR_RE.test(source);
|
|
68
|
+
if (!macroHost) {
|
|
69
|
+
const routed = routeRuntime?.transform(source, realPath);
|
|
70
|
+
if (routed) source = routed.source;
|
|
71
|
+
const rewritten =
|
|
72
|
+
barrels.length > 0
|
|
73
|
+
? await rewriteBarrelImports(source, barrels, analyzer, {
|
|
74
|
+
perModule: routed?.perModule,
|
|
75
|
+
reexports: route,
|
|
76
|
+
})
|
|
77
|
+
: null;
|
|
78
|
+
if (rewritten !== null) source = rewritten;
|
|
79
|
+
const narrowed = await objects?.rewrite(source, realPath);
|
|
80
|
+
if (narrowed?.contents) source = narrowed.contents;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (pipeAfter) {
|
|
84
|
+
const piped = await pipeAfter(source, { path: realPath });
|
|
85
|
+
if (piped !== null) source = piped;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { source, settled: macroHost };
|
|
89
|
+
};
|
|
90
|
+
const partModules =
|
|
91
|
+
parts && route
|
|
92
|
+
? new PartModules({ workspaceRoot: app.workspace.workspaceRoot, resolve, read, cache: parts })
|
|
93
|
+
: null;
|
|
30
94
|
|
|
31
95
|
return {
|
|
32
96
|
name: "barrel-imports",
|
|
33
97
|
setup(build) {
|
|
98
|
+
if (partModules) build.onResolve({ filter: ModuleParts.specifier }, ({ path: asked }) => ({ path: asked }));
|
|
34
99
|
// node_modules/akanjs stays in: framework `"use client"` modules still need RSC stubbing in generated workspaces.
|
|
35
100
|
// The optional `?v=N` tail matches HMR cache-busted paths; it is stripped before reading.
|
|
36
101
|
build.onLoad(
|
|
37
102
|
{
|
|
38
103
|
filter:
|
|
39
|
-
/^(?:(?!.*[\\/]node_modules[\\/]).*|.*[\\/]node_modules[\\/]akanjs[\\/].*)\.(tsx|ts|jsx|js)(\?v=\d+)?$/,
|
|
104
|
+
/^(?:(?!.*[\\/]node_modules[\\/]).*|.*[\\/]node_modules[\\/]akanjs[\\/].*)\.(tsx|ts|jsx|js)(\?v=\d+|\?akan-part=[\w$]+)?$/,
|
|
40
105
|
},
|
|
41
106
|
async (args) => {
|
|
42
107
|
const realPath = args.path.replace(/\?v=\d+$/, "");
|
|
43
|
-
const loader = loaderFor(realPath);
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
let source = await file.text();
|
|
48
|
-
if (skipPath(realPath)) return { contents: source, loader };
|
|
49
|
-
|
|
50
|
-
// Bun's macro evaluator races when a rewritten module holds `with { type: "macro" }` imports while another
|
|
51
|
-
// macro host evaluates (a macro identifier ends up undefined), so macro hosts keep their barrel imports.
|
|
52
|
-
if (!MACRO_ATTR_RE.test(source) && barrels.length > 0) {
|
|
53
|
-
const rewritten = await rewriteBarrelImports(source, barrels, analyzer);
|
|
54
|
-
if (rewritten !== null) source = rewritten;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
if (pipeAfter) {
|
|
58
|
-
const piped = await pipeAfter(source, { path: realPath });
|
|
59
|
-
if (piped !== null) source = piped;
|
|
108
|
+
const loader = loaderFor(PartModules.fileOf(realPath));
|
|
109
|
+
if (partModules) {
|
|
110
|
+
const contents = await partModules.load(realPath);
|
|
111
|
+
return contents === null ? undefined : { contents, loader };
|
|
60
112
|
}
|
|
61
|
-
|
|
62
|
-
return { contents: source, loader };
|
|
113
|
+
const loaded = await read(realPath);
|
|
114
|
+
return loaded ? { contents: loaded.source, loader } : undefined;
|
|
63
115
|
},
|
|
64
116
|
);
|
|
65
117
|
},
|
|
@@ -169,7 +221,7 @@ const resolveNodePackageExport = async (workspaceRoot: string, specifier: string
|
|
|
169
221
|
if (!rel?.startsWith(".")) return null;
|
|
170
222
|
const entryFile = await resolveFileCandidate(path.resolve(pkgDir, rel));
|
|
171
223
|
if (!entryFile) return null;
|
|
172
|
-
return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true };
|
|
224
|
+
return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true, rootDir: pkgDir };
|
|
173
225
|
} catch {
|
|
174
226
|
return null;
|
|
175
227
|
}
|
|
@@ -240,6 +292,10 @@ export interface RewriteBarrelImportsOptions {
|
|
|
240
292
|
specifierOf?: (subpath: string) => string;
|
|
241
293
|
/** Called for each import of a listed barrel with the value names whose rewrite reads its export map. */
|
|
242
294
|
onImport?: (barrel: string, names: string[]) => void;
|
|
295
|
+
/** The file names its runtime per module, so a client barrel stands for the page runtime alone. */
|
|
296
|
+
perModule?: boolean;
|
|
297
|
+
/** Rewrites `export { a, b as c } from "<barrel>"` as it rewrites an import of the same names. */
|
|
298
|
+
reexports?: boolean;
|
|
243
299
|
}
|
|
244
300
|
|
|
245
301
|
export const workspaceBarrels = (barrels: readonly string[]): string[] =>
|
|
@@ -249,11 +305,17 @@ export const rewriteBarrelImports = async (
|
|
|
249
305
|
source: string,
|
|
250
306
|
barrels: string[],
|
|
251
307
|
analyzer: BarrelAnalyzer,
|
|
252
|
-
{
|
|
308
|
+
{
|
|
309
|
+
keepLines = false,
|
|
310
|
+
specifierOf = (subpath: string) => subpath,
|
|
311
|
+
onImport,
|
|
312
|
+
perModule = false,
|
|
313
|
+
reexports = false,
|
|
314
|
+
}: RewriteBarrelImportsOptions = {},
|
|
253
315
|
): Promise<string | null> => {
|
|
254
316
|
// Sound pre-filter before the costly parse: a static import cannot name a specifier absent from the text.
|
|
255
317
|
if (!barrels.some((barrel) => source.includes(barrel))) return null;
|
|
256
|
-
const statements = findImportStatements(source);
|
|
318
|
+
const statements = findImportStatements(source, reexports);
|
|
257
319
|
if (statements.length === 0) return null;
|
|
258
320
|
|
|
259
321
|
// Walk import statements in reverse so replacements don't shift earlier ranges.
|
|
@@ -267,7 +329,7 @@ export const rewriteBarrelImports = async (
|
|
|
267
329
|
if (names.length > 0) onImport?.(stmt.specifier, names);
|
|
268
330
|
const map = await analyzer.analyze(stmt.specifier);
|
|
269
331
|
if (!map || map.size === 0) continue;
|
|
270
|
-
const lines = rewriteSingleStatement(stmt, map, specifierOf);
|
|
332
|
+
const lines = rewriteSingleStatement(stmt, map, specifierOf, perModule);
|
|
271
333
|
if (lines === null) continue;
|
|
272
334
|
const replacement = keepLines
|
|
273
335
|
? `${lines.join(" ")}${"\n".repeat(source.slice(stmt.start, stmt.end).split("\n").length - 1)}`
|
|
@@ -286,13 +348,14 @@ interface ParsedClause {
|
|
|
286
348
|
}
|
|
287
349
|
|
|
288
350
|
interface ImportStatement {
|
|
351
|
+
kind: "import" | "export";
|
|
289
352
|
start: number;
|
|
290
353
|
end: number;
|
|
291
354
|
clause: ParsedClause | null;
|
|
292
355
|
specifier: string;
|
|
293
356
|
}
|
|
294
357
|
|
|
295
|
-
const findImportStatements = (source: string): ImportStatement[] => {
|
|
358
|
+
const findImportStatements = (source: string, reexports: boolean): ImportStatement[] => {
|
|
296
359
|
const statements: ImportStatement[] = [];
|
|
297
360
|
// `setParentNodes: false` holds only while nothing reads `node.parent` and positions use `getStart(sourceFile)`.
|
|
298
361
|
const sourceFile = ts.createSourceFile(
|
|
@@ -303,11 +366,25 @@ const findImportStatements = (source: string): ImportStatement[] => {
|
|
|
303
366
|
ts.ScriptKind.TSX,
|
|
304
367
|
);
|
|
305
368
|
for (const statement of sourceFile.statements) {
|
|
369
|
+
if (reexports && ts.isExportDeclaration(statement)) {
|
|
370
|
+
const exportClause = statement.exportClause;
|
|
371
|
+
if (!statement.moduleSpecifier || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
372
|
+
if (!exportClause || !ts.isNamedExports(exportClause)) continue;
|
|
373
|
+
statements.push({
|
|
374
|
+
kind: "export",
|
|
375
|
+
start: statement.getStart(sourceFile),
|
|
376
|
+
end: statement.end,
|
|
377
|
+
clause: exportClauseOf(statement.isTypeOnly, exportClause),
|
|
378
|
+
specifier: statement.moduleSpecifier.text,
|
|
379
|
+
});
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
306
382
|
if (!ts.isImportDeclaration(statement)) continue;
|
|
307
383
|
if (!ts.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
308
384
|
const importClause = statement.importClause;
|
|
309
385
|
if (!importClause) continue;
|
|
310
386
|
statements.push({
|
|
387
|
+
kind: "import",
|
|
311
388
|
start: statement.getStart(sourceFile),
|
|
312
389
|
end: statement.end,
|
|
313
390
|
clause: clauseOf(importClause),
|
|
@@ -317,6 +394,16 @@ const findImportStatements = (source: string): ImportStatement[] => {
|
|
|
317
394
|
return statements;
|
|
318
395
|
};
|
|
319
396
|
|
|
397
|
+
const exportClauseOf = (typeOnly: boolean, exportClause: ts.NamedExports): ParsedClause | null => {
|
|
398
|
+
const named: NamedItem[] = [];
|
|
399
|
+
for (const element of exportClause.elements) {
|
|
400
|
+
const imported = element.propertyName ?? element.name;
|
|
401
|
+
if (!ts.isIdentifier(imported) || !ts.isIdentifier(element.name)) return null;
|
|
402
|
+
named.push({ imported: imported.text, local: element.name.text, isType: element.isTypeOnly });
|
|
403
|
+
}
|
|
404
|
+
return { named, typeOnly };
|
|
405
|
+
};
|
|
406
|
+
|
|
320
407
|
const clauseOf = (importClause: ts.ImportClause): ParsedClause | null => {
|
|
321
408
|
const parsed: ParsedClause = { typeOnly: importClause.phaseModifier === ts.SyntaxKind.TypeKeyword };
|
|
322
409
|
if (importClause.name) parsed.defaultImport = importClause.name.text;
|
|
@@ -344,6 +431,7 @@ const rewriteSingleStatement = (
|
|
|
344
431
|
stmt: ImportStatement,
|
|
345
432
|
map: BarrelExportMap,
|
|
346
433
|
specifierOf: (subpath: string) => string,
|
|
434
|
+
perModule: boolean,
|
|
347
435
|
): string[] | null => {
|
|
348
436
|
const { clause } = stmt;
|
|
349
437
|
if (!clause) return null;
|
|
@@ -353,6 +441,7 @@ const rewriteSingleStatement = (
|
|
|
353
441
|
if (clause.typeOnly && !clause.defaultImport) return null;
|
|
354
442
|
if (!clause.named?.length) return null;
|
|
355
443
|
|
|
444
|
+
const { kind } = stmt;
|
|
356
445
|
const remaining: NamedItem[] = [];
|
|
357
446
|
const rewrites = new Map<string, NamedItem[]>();
|
|
358
447
|
const namespaceLines: string[] = [];
|
|
@@ -367,7 +456,7 @@ const rewriteSingleStatement = (
|
|
|
367
456
|
continue;
|
|
368
457
|
}
|
|
369
458
|
if (target.namespace) {
|
|
370
|
-
namespaceLines.push(
|
|
459
|
+
namespaceLines.push(`${kind} * as ${item.local} from ${JSON.stringify(specifierOf(target.subpath))};`);
|
|
371
460
|
continue;
|
|
372
461
|
}
|
|
373
462
|
const list = rewrites.get(target.subpath) ?? [];
|
|
@@ -378,7 +467,7 @@ const rewriteSingleStatement = (
|
|
|
378
467
|
if (rewrites.size === 0 && namespaceLines.length === 0) return null;
|
|
379
468
|
|
|
380
469
|
//? An app or lib client barrel's import-time side effects are its client runtime and store, not its module UI.
|
|
381
|
-
const lines = (StoreBootstrap.ofClientBarrel(stmt.specifier, map) ?? []).map(
|
|
470
|
+
const lines = (StoreBootstrap.ofClientBarrel(stmt.specifier, map, valueNamesOf(clause), { perModule }) ?? []).map(
|
|
382
471
|
(specifier) => `import ${JSON.stringify(specifierOf(specifier))};`,
|
|
383
472
|
);
|
|
384
473
|
|
|
@@ -386,11 +475,11 @@ const rewriteSingleStatement = (
|
|
|
386
475
|
const parts: string[] = [];
|
|
387
476
|
if (clause.defaultImport) parts.push(clause.defaultImport);
|
|
388
477
|
if (remaining.length > 0) parts.push(`{ ${remaining.map(serializeNamedItem).join(", ")} }`);
|
|
389
|
-
lines.push(
|
|
478
|
+
lines.push(`${kind} ${parts.join(", ")} from "${stmt.specifier}";`);
|
|
390
479
|
}
|
|
391
480
|
|
|
392
481
|
for (const [subpath, items] of rewrites) {
|
|
393
|
-
lines.push(
|
|
482
|
+
lines.push(`${kind} { ${items.map(serializeNamedItem).join(", ")} } from ${JSON.stringify(specifierOf(subpath))};`);
|
|
394
483
|
}
|
|
395
484
|
lines.push(...namespaceLines);
|
|
396
485
|
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { ExportReach } from "./exportReach";
|
|
3
|
+
|
|
4
|
+
const read = (source: string, file = "View.tsx") => ExportReach.read(source, file) as ExportReach;
|
|
5
|
+
const importsOf = (source: string, name: string) => {
|
|
6
|
+
const reached = read(source).of(name);
|
|
7
|
+
return reached.known ? reached.imports : null;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const view = `
|
|
11
|
+
import { Remove, Edit } from "./Memo.Util";
|
|
12
|
+
import { Chart } from "./Chart";
|
|
13
|
+
import type { Memo } from "./memo.constant";
|
|
14
|
+
import * as Unit from "./Memo.Unit";
|
|
15
|
+
import { format } from "./format";
|
|
16
|
+
|
|
17
|
+
const Title = ({ memo }: { memo: Memo }) => <h1>{format(memo.title)}</h1>;
|
|
18
|
+
|
|
19
|
+
export const General = ({ memo }: { memo: Memo }) => (
|
|
20
|
+
<div>
|
|
21
|
+
<Title memo={memo} />
|
|
22
|
+
<Remove id={memo.id} />
|
|
23
|
+
</div>
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
export function Stats({ memo }: { memo: Memo }) {
|
|
27
|
+
return <Chart value={memo.count} />;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const Card = ({ memo }: { memo: Memo }) => <Unit.Card memo={memo} />;
|
|
31
|
+
export const All = () => Object.values(Unit);
|
|
32
|
+
export interface Props { memo: Memo }
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
describe("ExportReach", () => {
|
|
36
|
+
test("reaches, from one export, the imports its declaration reads and those of the declarations it reads", () => {
|
|
37
|
+
expect(importsOf(view, "General")).toEqual([
|
|
38
|
+
{ specifier: "./Memo.Util", names: ["Remove"] },
|
|
39
|
+
{ specifier: "./format", names: ["format"] },
|
|
40
|
+
]);
|
|
41
|
+
expect(importsOf(view, "Stats")).toEqual([{ specifier: "./Chart", names: ["Chart"] }]);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test("asks a namespace import for the members read from it, and for the whole module once it is handed on", () => {
|
|
45
|
+
expect(importsOf(view, "Card")).toEqual([{ specifier: "./Memo.Unit", names: ["Card"] }]);
|
|
46
|
+
expect(importsOf(view, "All")).toEqual([{ specifier: "./Memo.Unit", names: null }]);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("reaches nothing for a type, and does not follow a name read only in a type", () => {
|
|
50
|
+
expect(importsOf(view, "Props")).toEqual([]);
|
|
51
|
+
expect(
|
|
52
|
+
read(view)
|
|
53
|
+
.whole()
|
|
54
|
+
.map(({ specifier }) => specifier),
|
|
55
|
+
).not.toContain("./memo.constant");
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("answers a name the file does not hold as unknown, with the `export *` targets that may hold it", () => {
|
|
59
|
+
expect(read(view).of("Missing")).toEqual({ known: false, stars: [] });
|
|
60
|
+
expect(read('export * from "./a";\nexport * from "./b";\nexport const X = 1;\n').of("Y")).toEqual({
|
|
61
|
+
known: false,
|
|
62
|
+
stars: ["./a", "./b"],
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("follows an export list, a re-export, a namespace re-export and a default export", () => {
|
|
67
|
+
const source = `
|
|
68
|
+
import Base from "./Base";
|
|
69
|
+
import { Row } from "./Row";
|
|
70
|
+
const List = () => <Row />;
|
|
71
|
+
export { List as Rows };
|
|
72
|
+
export { Cell as GridCell, default as Grid } from "./Grid";
|
|
73
|
+
export * as Icons from "./icons";
|
|
74
|
+
export default function Page() { return <Base />; }
|
|
75
|
+
`;
|
|
76
|
+
expect(importsOf(source, "Rows")).toEqual([{ specifier: "./Row", names: ["Row"] }]);
|
|
77
|
+
expect(importsOf(source, "GridCell")).toEqual([{ specifier: "./Grid", names: ["Cell"] }]);
|
|
78
|
+
expect(importsOf(source, "Grid")).toEqual([{ specifier: "./Grid", names: ["default"] }]);
|
|
79
|
+
expect(importsOf(source, "Icons")).toEqual([{ specifier: "./icons", names: null }]);
|
|
80
|
+
expect(importsOf(source, "default")).toEqual([{ specifier: "./Base", names: ["default"] }]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("reads a member put on a declaration with the declaration, not with every importer", () => {
|
|
84
|
+
const source = `
|
|
85
|
+
import { Header } from "./Header";
|
|
86
|
+
import { Footer } from "./Footer";
|
|
87
|
+
import { Plain } from "./Plain";
|
|
88
|
+
export const Card = () => null;
|
|
89
|
+
Card.Header = Header;
|
|
90
|
+
Object.assign(Card, { Footer });
|
|
91
|
+
export const Other = () => <Plain />;
|
|
92
|
+
`;
|
|
93
|
+
expect(importsOf(source, "Card")).toEqual([
|
|
94
|
+
{ specifier: "./Header", names: ["Header"] },
|
|
95
|
+
{ specifier: "./Footer", names: ["Footer"] },
|
|
96
|
+
]);
|
|
97
|
+
expect(importsOf(source, "Other")).toEqual([{ specifier: "./Plain", names: ["Plain"] }]);
|
|
98
|
+
expect(read(source).always()).toEqual([]);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test("reaches, for every importer, a bare import and what a statement that is no declaration reads", () => {
|
|
102
|
+
const source = `
|
|
103
|
+
import "./polyfill";
|
|
104
|
+
import { register } from "./registry";
|
|
105
|
+
import { Panel } from "./Panel";
|
|
106
|
+
import { Plain } from "./Plain";
|
|
107
|
+
register("panel", Panel);
|
|
108
|
+
export const Other = () => <Plain />;
|
|
109
|
+
`;
|
|
110
|
+
expect(read(source).always()).toEqual([
|
|
111
|
+
{ specifier: "./polyfill", names: null },
|
|
112
|
+
{ specifier: "./registry", names: ["register"] },
|
|
113
|
+
{ specifier: "./Panel", names: ["Panel"] },
|
|
114
|
+
]);
|
|
115
|
+
expect(importsOf(source, "Other")).toEqual([{ specifier: "./Plain", names: ["Plain"] }]);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("reaches a module loaded on demand as a whole, from the export whose declaration loads it", () => {
|
|
119
|
+
const source = `
|
|
120
|
+
import { lazy } from "react";
|
|
121
|
+
const Editor = lazy(() => import("./Editor"));
|
|
122
|
+
export const Rich = () => <Editor />;
|
|
123
|
+
export const Plain = () => null;
|
|
124
|
+
`;
|
|
125
|
+
expect(importsOf(source, "Rich")).toEqual([
|
|
126
|
+
{ specifier: "./Editor", names: null },
|
|
127
|
+
{ specifier: "react", names: ["lazy"] },
|
|
128
|
+
]);
|
|
129
|
+
expect(importsOf(source, "Plain")).toEqual([]);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("counts a property name as no read of an import of that name, and a shadowed name as one", () => {
|
|
133
|
+
const source = `
|
|
134
|
+
import { Card } from "./Card";
|
|
135
|
+
import { Row } from "./Row";
|
|
136
|
+
export const A = (props: { Card: string }) => [props.Card, { Card: 1 }];
|
|
137
|
+
export const B = (Row: string) => Row;
|
|
138
|
+
`;
|
|
139
|
+
expect(importsOf(source, "A")).toEqual([]);
|
|
140
|
+
expect(importsOf(source, "B")).toEqual([{ specifier: "./Row", names: ["Row"] }]);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("the whole module reaches every import a value of it reads, re-exports and `export *` included", () => {
|
|
144
|
+
const source = `
|
|
145
|
+
import { A } from "./a";
|
|
146
|
+
import type { T } from "./t";
|
|
147
|
+
export { B } from "./b";
|
|
148
|
+
export * from "./c";
|
|
149
|
+
export const X = () => <A />;
|
|
150
|
+
`;
|
|
151
|
+
expect(read(source).whole()).toEqual([
|
|
152
|
+
{ specifier: "./a", names: ["A"] },
|
|
153
|
+
{ specifier: "./b", names: ["B"] },
|
|
154
|
+
{ specifier: "./c", names: null },
|
|
155
|
+
]);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("does not read a CommonJS module, whose exports are assigned at run time", () => {
|
|
159
|
+
expect(ExportReach.read('const a = require("./a");\nmodule.exports = { a };\n', "legacy.js")).toBeNull();
|
|
160
|
+
expect(ExportReach.read("export const a = 1;\n", "modern.js")).not.toBeNull();
|
|
161
|
+
});
|
|
162
|
+
});
|