@warlock.js/core 4.16.0 → 5.0.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/CHANGELOG.md +13 -0
- package/bin/warlock.js +154 -1
- package/esm/application/application.d.mts +65 -1
- package/esm/application/application.d.mts.map +1 -1
- package/esm/application/application.mjs +62 -0
- package/esm/application/application.mjs.map +1 -1
- package/esm/application/index.d.mts +1 -1
- package/esm/cli/cli-commands.manager.mjs +60 -10
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/commands/dev-server.command.mjs +1 -0
- package/esm/cli/commands/dev-server.command.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/handler-signature.check.mjs +40 -0
- package/esm/cli/commands/doctor/checks/handler-signature.check.mjs.map +1 -0
- package/esm/cli/commands/doctor/checks/index.mjs +4 -2
- package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
- package/esm/commands/cli-command.d.mts +1 -1
- package/esm/commands/cli-command.d.mts.map +1 -1
- package/esm/commands/cli-command.mjs.map +1 -1
- package/esm/commands/types.d.mts +10 -2
- package/esm/commands/types.d.mts.map +1 -1
- package/esm/config/config-handlers.d.mts +1 -2
- package/esm/config/config-handlers.d.mts.map +1 -1
- package/esm/config/config-handlers.mjs +3 -2
- package/esm/config/config-handlers.mjs.map +1 -1
- package/esm/config/locale-configuration.mjs +29 -0
- package/esm/config/locale-configuration.mjs.map +1 -0
- package/esm/connectors/assert-no-reserved-connector-names.d.mts +7 -0
- package/esm/connectors/assert-no-reserved-connector-names.d.mts.map +1 -0
- package/esm/connectors/assert-no-reserved-connector-names.mjs +44 -0
- package/esm/connectors/assert-no-reserved-connector-names.mjs.map +1 -0
- package/esm/connectors/assert-unique-connector-names.d.mts +7 -0
- package/esm/connectors/assert-unique-connector-names.d.mts.map +1 -0
- package/esm/connectors/assert-unique-connector-names.mjs +20 -0
- package/esm/connectors/assert-unique-connector-names.mjs.map +1 -0
- package/esm/connectors/connectors-manager.d.mts +38 -0
- package/esm/connectors/connectors-manager.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.mjs +45 -12
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/describe-server-address.mjs +75 -0
- package/esm/connectors/describe-server-address.mjs.map +1 -0
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +6 -3
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/index.d.mts +4 -1
- package/esm/connectors/index.mjs +4 -1
- package/esm/connectors/register-configured-connectors.d.mts +14 -0
- package/esm/connectors/register-configured-connectors.d.mts.map +1 -0
- package/esm/connectors/register-configured-connectors.mjs +99 -0
- package/esm/connectors/register-configured-connectors.mjs.map +1 -0
- package/esm/connectors/socket-connector.d.mts.map +1 -1
- package/esm/connectors/socket-connector.mjs +4 -1
- package/esm/connectors/socket-connector.mjs.map +1 -1
- package/esm/connectors/types.d.mts +76 -1
- package/esm/connectors/types.d.mts.map +1 -1
- package/esm/connectors/types.mjs.map +1 -1
- package/esm/database/models/database-log/database-log.d.mts +50 -2
- package/esm/database/models/database-log/database-log.d.mts.map +1 -1
- package/esm/database/utils.d.mts +2 -2
- package/esm/database/utils.d.mts.map +1 -1
- package/esm/dev-server/development-server.mjs +1 -0
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/layer-executor.mjs +2 -1
- package/esm/dev-server/layer-executor.mjs.map +1 -1
- package/esm/dev-server/read-config-ast.mjs +48 -0
- package/esm/dev-server/read-config-ast.mjs.map +1 -0
- package/esm/dev-server/run-typings-generation.mjs +18 -0
- package/esm/dev-server/run-typings-generation.mjs.map +1 -0
- package/esm/dev-server/type-generator.mjs +30 -39
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs +169 -1
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/stubs.mjs +93 -1
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/context/request-context.d.mts +14 -3
- package/esm/http/context/request-context.d.mts.map +1 -1
- package/esm/http/context/request-context.mjs +11 -1
- package/esm/http/context/request-context.mjs.map +1 -1
- package/esm/http/context/request-memo.d.mts +21 -0
- package/esm/http/context/request-memo.d.mts.map +1 -0
- package/esm/http/context/request-memo.mjs +48 -0
- package/esm/http/context/request-memo.mjs.map +1 -0
- package/esm/http/database/RequestLog.d.mts +164 -2
- package/esm/http/database/RequestLog.d.mts.map +1 -1
- package/esm/http/index.d.mts +6 -5
- package/esm/http/index.mjs +2 -1
- package/esm/http/middleware/cache-response-middleware.d.mts +2 -2
- package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
- package/esm/http/middleware/cache-response-middleware.mjs +1 -1
- package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
- package/esm/http/middleware/concurrency-limit.middleware.mjs +1 -1
- package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/index.d.mts +1 -1
- package/esm/http/middleware/index.mjs +1 -1
- package/esm/http/middleware/inject-request-context.d.mts +1 -8
- package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +9 -22
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/ip-filter.middleware.mjs +1 -1
- package/esm/http/middleware/ip-filter.middleware.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/max-body-size.middleware.mjs +1 -1
- package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
- package/esm/http/middleware/rate-limit.middleware.mjs +1 -1
- package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/idempotency-key.d.mts +0 -14
- package/esm/http/middleware/utils/idempotency-key.d.mts.map +1 -1
- package/esm/http/middleware/utils/idempotency-key.mjs +19 -1
- package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
- package/esm/http/request.d.mts +119 -30
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +98 -25
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.mjs +1 -1
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/types.d.mts +36 -1
- package/esm/http/types.d.mts.map +1 -1
- package/esm/http/uploaded-file.d.mts +51 -19
- package/esm/http/uploaded-file.d.mts.map +1 -1
- package/esm/http/uploaded-file.mjs +36 -8
- package/esm/http/uploaded-file.mjs.map +1 -1
- package/esm/index.d.mts +17 -9
- package/esm/index.mjs +10 -4
- package/esm/production/build-contributions.mjs +115 -0
- package/esm/production/build-contributions.mjs.map +1 -0
- package/esm/production/production-builder.mjs +97 -2
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/resolve-build-config.d.mts +25 -0
- package/esm/production/resolve-build-config.d.mts.map +1 -0
- package/esm/production/resolve-build-config.mjs +43 -1
- package/esm/production/resolve-build-config.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +1 -1
- package/esm/repositories/adapters/cascade/filter-applicator.mjs +20 -9
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/restful/restful.d.mts +29 -8
- package/esm/restful/restful.d.mts.map +1 -1
- package/esm/restful/restful.mjs +31 -13
- package/esm/restful/restful.mjs.map +1 -1
- package/esm/router/describe-route-for-log.mjs +29 -0
- package/esm/router/describe-route-for-log.mjs.map +1 -0
- package/esm/router/index.d.mts +3 -1
- package/esm/router/index.mjs +2 -0
- package/esm/router/log-request-lifecycle.mjs +38 -0
- package/esm/router/log-request-lifecycle.mjs.map +1 -0
- package/esm/router/positional-handler-diagnostics.d.mts +90 -0
- package/esm/router/positional-handler-diagnostics.d.mts.map +1 -0
- package/esm/router/positional-handler-diagnostics.mjs +247 -0
- package/esm/router/positional-handler-diagnostics.mjs.map +1 -0
- package/esm/router/route-registry.d.mts +34 -0
- package/esm/router/route-registry.d.mts.map +1 -0
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +87 -63
- package/esm/router/router.mjs.map +1 -1
- package/esm/router/types.d.mts +23 -5
- package/esm/router/types.d.mts.map +1 -1
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/storage.mjs +1 -1
- package/esm/storage/storage.mjs.map +1 -1
- package/esm/storage/utils/safe-fetch.d.mts +11 -1
- package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs +51 -4
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/tests/vitest-setup.mjs +1 -1
- package/esm/utils/load-environment.mjs +33 -2
- package/esm/utils/load-environment.mjs.map +1 -1
- package/esm/utils/types.d.mts +4 -0
- package/esm/utils/types.d.mts.map +1 -1
- package/esm/validation/validateAll.mjs +4 -1
- package/esm/validation/validateAll.mjs.map +1 -1
- package/esm/validation/validators/file-validator.d.mts +25 -1
- package/esm/validation/validators/file-validator.d.mts.map +1 -1
- package/esm/warlock-config/index.mjs +1 -1
- package/esm/warlock-config/normalize-build-config.mjs.map +1 -1
- package/esm/warlock-config/types.d.mts +36 -2
- package/esm/warlock-config/types.d.mts.map +1 -1
- package/package.json +15 -12
- package/skills/request-memo/SKILL.md +142 -0
- package/skills/use-request-locals/SKILL.md +144 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
//#region ../core/src/production/build-contributions.ts
|
|
2
|
+
const ErrorWithCause = Error;
|
|
3
|
+
/**
|
|
4
|
+
* The only keys a `build` contribution may carry.
|
|
5
|
+
*
|
|
6
|
+
* The runtime half of the closed-contribution constraint: the
|
|
7
|
+
* type already makes `build: { plugins: [...] }` unrepresentable, but a
|
|
8
|
+
* plain `warlock.config.js`, an `as any`, or a connector compiled against an
|
|
9
|
+
* older core all slip past the type. Rejected rather than ignored — the same
|
|
10
|
+
* posture as the `tsconfig` guard in `resolve-build-config`: dropping the key
|
|
11
|
+
* quietly would leave the author believing their plugin ran.
|
|
12
|
+
*/
|
|
13
|
+
const ALLOWED_CONTRIBUTION_KEYS = ["generate", "emit"];
|
|
14
|
+
/**
|
|
15
|
+
* Reject a contribution object carrying anything but the two hooks.
|
|
16
|
+
*
|
|
17
|
+
* @throws Error naming the connector and the offending key
|
|
18
|
+
*/
|
|
19
|
+
function assertClosedContribution(connector) {
|
|
20
|
+
const contribution = connector.build;
|
|
21
|
+
if (!contribution) return;
|
|
22
|
+
for (const key of Object.keys(contribution)) {
|
|
23
|
+
if (ALLOWED_CONTRIBUTION_KEYS.includes(key)) continue;
|
|
24
|
+
throw new Error(`Connector "${connector.name}" declares an unsupported build contribution key "${key}". A build contribution carries exactly two optional hooks — ${ALLOWED_CONTRIBUTION_KEYS.join(" and ")} — and no data. Anything a hook needs (plugins, pipelines, aliases) must be constructed inside that hook, so it never lands in the connector's static import graph.`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Drain every connector's `generate` hook, in array order, sequentially.
|
|
29
|
+
*
|
|
30
|
+
* Semantics are copied from `Application.runStartupValidators`
|
|
31
|
+
* (`application.ts:304-329`) on purpose: ordered, awaited one at a time, and
|
|
32
|
+
* a throw is rethrown wrapped in an error NAMING the contributor. A
|
|
33
|
+
* contributor failure IS the build failing — that is what makes
|
|
34
|
+
* "green build, no client bundle" unrepresentable rather than merely
|
|
35
|
+
* unlikely.
|
|
36
|
+
*/
|
|
37
|
+
async function runGenerateContributions(connectors, context) {
|
|
38
|
+
const entryImports = [];
|
|
39
|
+
let esbuild = {};
|
|
40
|
+
for (const connector of connectors) {
|
|
41
|
+
assertClosedContribution(connector);
|
|
42
|
+
const generate = connector.build?.generate;
|
|
43
|
+
if (!generate) continue;
|
|
44
|
+
const result = await runHook(connector, "generate", () => generate(context));
|
|
45
|
+
if (!result) continue;
|
|
46
|
+
if (result.entryImports) entryImports.push(...result.entryImports);
|
|
47
|
+
if (result.esbuild) esbuild = mergeEsbuildPatches(esbuild, result.esbuild);
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
entryImports,
|
|
51
|
+
esbuild
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Drain every connector's `emit` hook, in array order, sequentially.
|
|
56
|
+
*
|
|
57
|
+
* Runs after esbuild and before `.warlock/production` is removed, so a hook
|
|
58
|
+
* may still read what `generate` wrote there.
|
|
59
|
+
*/
|
|
60
|
+
async function runEmitContributions(connectors, context) {
|
|
61
|
+
for (const connector of connectors) {
|
|
62
|
+
assertClosedContribution(connector);
|
|
63
|
+
const emit = connector.build?.emit;
|
|
64
|
+
if (!emit) continue;
|
|
65
|
+
await runHook(connector, "emit", () => emit(context));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Merge two contributor patches. Later wins, except:
|
|
70
|
+
*
|
|
71
|
+
* - `define` merges per key — two contributors defining different
|
|
72
|
+
* `import.meta.env.*` entries must both survive; a wholesale replace would
|
|
73
|
+
* drop one silently.
|
|
74
|
+
* - `external` concatenates and dedupes — it is a set of package names, and
|
|
75
|
+
* under `singleBundle` each contributor adds its own optional peers.
|
|
76
|
+
* - `loader` merges per extension, for the same reason as `define`.
|
|
77
|
+
*/
|
|
78
|
+
function mergeEsbuildPatches(base, patch) {
|
|
79
|
+
const merged = {
|
|
80
|
+
...base,
|
|
81
|
+
...patch
|
|
82
|
+
};
|
|
83
|
+
if (base.define || patch.define) merged.define = {
|
|
84
|
+
...base.define,
|
|
85
|
+
...patch.define
|
|
86
|
+
};
|
|
87
|
+
if (base.external || patch.external) merged.external = dedupe([...base.external ?? [], ...patch.external ?? []]);
|
|
88
|
+
if (base.loader || patch.loader) merged.loader = {
|
|
89
|
+
...base.loader,
|
|
90
|
+
...patch.loader
|
|
91
|
+
};
|
|
92
|
+
return merged;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Concatenation order preserved — esbuild does not care, but a stable order
|
|
96
|
+
* keeps build output diffable.
|
|
97
|
+
*/
|
|
98
|
+
function dedupe(values) {
|
|
99
|
+
return [...new Set(values)];
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Run one hook and rename its failure after the connector that owns it.
|
|
103
|
+
*/
|
|
104
|
+
async function runHook(connector, hook, run) {
|
|
105
|
+
try {
|
|
106
|
+
return await run();
|
|
107
|
+
} catch (error) {
|
|
108
|
+
const cause = error instanceof Error ? error.message : String(error);
|
|
109
|
+
throw new ErrorWithCause(`Build contribution "${connector.name}" failed during ${hook}: ${cause}. The build cannot continue — an artifact this connector was responsible for is missing, and shipping the bundle without it would fail at runtime instead.`, { cause: error });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
//#endregion
|
|
114
|
+
export { dedupe, runEmitContributions, runGenerateContributions };
|
|
115
|
+
//# sourceMappingURL=build-contributions.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-contributions.mjs","names":[],"sources":["../../../../../../../core/src/production/build-contributions.ts"],"sourcesContent":["import type {\n Connector,\n ConnectorBuildContext,\n ConnectorEsbuildPatch,\n} from \"../connectors/types\";\n\n/**\n * `Error` with the `cause` option typed. Same shim as\n * `application.ts` — lib.es2022 declares `cause` on `ErrorOptions`, but the\n * package still compiles against an older lib in some consumers.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * The only keys a `build` contribution may carry.\n *\n * The runtime half of the closed-contribution constraint: the\n * type already makes `build: { plugins: [...] }` unrepresentable, but a\n * plain `warlock.config.js`, an `as any`, or a connector compiled against an\n * older core all slip past the type. Rejected rather than ignored — the same\n * posture as the `tsconfig` guard in `resolve-build-config`: dropping the key\n * quietly would leave the author believing their plugin ran.\n */\nconst ALLOWED_CONTRIBUTION_KEYS = [\"generate\", \"emit\"] as const;\n\n/**\n * What the generate pass produced, merged across every contributor.\n */\nexport type GenerateContributionsResult = {\n /** Entry lines in contributor order, appended after `./routes` */\n entryImports: string[];\n /** The contributors' esbuild patches, merged into one */\n esbuild: ConnectorEsbuildPatch;\n};\n\n/**\n * Reject a contribution object carrying anything but the two hooks.\n *\n * @throws Error naming the connector and the offending key\n */\nexport function assertClosedContribution(connector: Connector): void {\n const contribution = connector.build;\n\n if (!contribution) return;\n\n for (const key of Object.keys(contribution)) {\n if ((ALLOWED_CONTRIBUTION_KEYS as readonly string[]).includes(key)) continue;\n\n throw new Error(\n `Connector \"${connector.name}\" declares an unsupported build contribution key \"${key}\". ` +\n `A build contribution carries exactly two optional hooks — ` +\n `${ALLOWED_CONTRIBUTION_KEYS.join(\" and \")} — and no data. ` +\n `Anything a hook needs (plugins, pipelines, aliases) must be constructed inside ` +\n `that hook, so it never lands in the connector's static import graph.`,\n );\n }\n}\n\n/**\n * Drain every connector's `generate` hook, in array order, sequentially.\n *\n * Semantics are copied from `Application.runStartupValidators`\n * (`application.ts:304-329`) on purpose: ordered, awaited one at a time, and\n * a throw is rethrown wrapped in an error NAMING the contributor. A\n * contributor failure IS the build failing — that is what makes\n * \"green build, no client bundle\" unrepresentable rather than merely\n * unlikely.\n */\nexport async function runGenerateContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<GenerateContributionsResult> {\n const entryImports: string[] = [];\n let esbuild: ConnectorEsbuildPatch = {};\n\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const generate = connector.build?.generate;\n\n if (!generate) continue;\n\n const result = await runHook(connector, \"generate\", () => generate(context));\n\n if (!result) continue;\n\n if (result.entryImports) {\n entryImports.push(...result.entryImports);\n }\n\n if (result.esbuild) {\n esbuild = mergeEsbuildPatches(esbuild, result.esbuild);\n }\n }\n\n return { entryImports, esbuild };\n}\n\n/**\n * Drain every connector's `emit` hook, in array order, sequentially.\n *\n * Runs after esbuild and before `.warlock/production` is removed, so a hook\n * may still read what `generate` wrote there.\n */\nexport async function runEmitContributions(\n connectors: readonly Connector[],\n context: ConnectorBuildContext,\n): Promise<void> {\n for (const connector of connectors) {\n assertClosedContribution(connector);\n\n const emit = connector.build?.emit;\n\n if (!emit) continue;\n\n await runHook(connector, \"emit\", () => emit(context));\n }\n}\n\n/**\n * Merge two contributor patches. Later wins, except:\n *\n * - `define` merges per key — two contributors defining different\n * `import.meta.env.*` entries must both survive; a wholesale replace would\n * drop one silently.\n * - `external` concatenates and dedupes — it is a set of package names, and\n * under `singleBundle` each contributor adds its own optional peers.\n * - `loader` merges per extension, for the same reason as `define`.\n */\nexport function mergeEsbuildPatches(\n base: ConnectorEsbuildPatch,\n patch: ConnectorEsbuildPatch,\n): ConnectorEsbuildPatch {\n const merged: ConnectorEsbuildPatch = { ...base, ...patch };\n\n if (base.define || patch.define) {\n merged.define = { ...base.define, ...patch.define };\n }\n\n if (base.external || patch.external) {\n merged.external = dedupe([...(base.external ?? []), ...(patch.external ?? [])]);\n }\n\n if (base.loader || patch.loader) {\n merged.loader = { ...base.loader, ...patch.loader };\n }\n\n return merged;\n}\n\n/**\n * Concatenation order preserved — esbuild does not care, but a stable order\n * keeps build output diffable.\n */\nexport function dedupe(values: string[]): string[] {\n return [...new Set(values)];\n}\n\n/**\n * Run one hook and rename its failure after the connector that owns it.\n */\nasync function runHook<Result>(\n connector: Connector,\n hook: \"generate\" | \"emit\",\n run: () => Result | Promise<Result>,\n): Promise<Result> {\n try {\n return await run();\n } catch (error) {\n const cause = error instanceof Error ? error.message : String(error);\n\n throw new ErrorWithCause(\n `Build contribution \"${connector.name}\" failed during ${hook}: ${cause}. ` +\n `The build cannot continue — an artifact this connector was responsible for ` +\n `is missing, and shipping the bundle without it would fail at runtime instead.`,\n { cause: error },\n );\n }\n}\n"],"mappings":";AAaA,MAAM,iBAAiB;;;;;;;;;;;AAYvB,MAAM,4BAA4B,CAAC,YAAY,MAAM;;;;;;AAiBrD,SAAgB,yBAAyB,WAA4B;CACnE,MAAM,eAAe,UAAU;CAE/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GAAG,KAAK;EAAQ,GAAG,MAAM;CAAO;CAGpD,OAAO;AACT;;;;;AAMA,SAAgB,OAAO,QAA4B;CACjD,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;;;;AAKA,eAAe,QACb,WACA,MACA,KACiB;CACjB,IAAI;EACF,OAAO,MAAM,IAAI;CACnB,SAAS,OAAO;EACd,MAAM,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAEnE,MAAM,IAAI,eACR,uBAAuB,UAAU,KAAK,kBAAkB,KAAK,IAAI,MAAM,6JAGvE,EAAE,OAAO,MAAM,CACjB;CACF;AACF"}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { appPath, rootPath, warlockPath } from "../utils/paths.mjs";
|
|
2
2
|
import "../utils/index.mjs";
|
|
3
|
+
import { assertNoReservedConnectorNames } from "../connectors/assert-no-reserved-connector-names.mjs";
|
|
4
|
+
import { assertUniqueConnectorNames } from "../connectors/assert-unique-connector-names.mjs";
|
|
5
|
+
import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
|
|
3
6
|
import { tsconfigManager } from "../dev-server/tsconfig-manager.mjs";
|
|
4
7
|
import { assertGeneratedImportsAreDeclared } from "./assert-generated-imports.mjs";
|
|
8
|
+
import { dedupe, runEmitContributions, runGenerateContributions } from "./build-contributions.mjs";
|
|
5
9
|
import { nativeNodeModulesPlugin } from "./esbuild-plugins.mjs";
|
|
6
10
|
import { resolveBuildConfig } from "./resolve-build-config.mjs";
|
|
7
11
|
import path from "path";
|
|
@@ -51,6 +55,16 @@ function mergeBanner(userBanner, shim) {
|
|
|
51
55
|
};
|
|
52
56
|
}
|
|
53
57
|
/**
|
|
58
|
+
* Prefix every generated file uses to reach the app root.
|
|
59
|
+
*
|
|
60
|
+
* Generated sources are written into `.warlock/production/`, two levels below
|
|
61
|
+
* the app root, so `../../` lands back on it — the same hop already spelled
|
|
62
|
+
* out in the `../../src/app/…` and `../../src/config/…` imports the module and
|
|
63
|
+
* config-loader generators emit. Named once so a generator that needs a new
|
|
64
|
+
* app-root file (`warlock.config`) cannot pick a different depth.
|
|
65
|
+
*/
|
|
66
|
+
const APP_ROOT_FROM_PRODUCTION_DIR = "../../";
|
|
67
|
+
/**
|
|
54
68
|
* Production Builder
|
|
55
69
|
* Generates production-ready files and bundles them for deployment
|
|
56
70
|
* Build options are loaded from warlock.config.ts
|
|
@@ -58,6 +72,8 @@ function mergeBanner(userBanner, shim) {
|
|
|
58
72
|
var ProductionBuilder = class {
|
|
59
73
|
constructor() {
|
|
60
74
|
this.productionDir = warlockPath("production");
|
|
75
|
+
this.connectors = [];
|
|
76
|
+
this.contributedEsbuild = {};
|
|
61
77
|
this.generatedFiles = {
|
|
62
78
|
locales: false,
|
|
63
79
|
events: false,
|
|
@@ -74,7 +90,9 @@ var ProductionBuilder = class {
|
|
|
74
90
|
await this.generateCombinedFiles();
|
|
75
91
|
await this.generateEntryPoint();
|
|
76
92
|
await this.assertGeneratedImports();
|
|
93
|
+
if (await this.runGenerateContributions()) await this.assertGeneratedImports();
|
|
77
94
|
await this.bundle();
|
|
95
|
+
await runEmitContributions(this.connectors, this.buildContext());
|
|
78
96
|
await removeDirectoryAsync(this.productionDir);
|
|
79
97
|
console.log(colors.green("Build complete!"));
|
|
80
98
|
console.log(`Start production server by running ${colors.cyan("warlock start")}`);
|
|
@@ -84,9 +102,50 @@ var ProductionBuilder = class {
|
|
|
84
102
|
*/
|
|
85
103
|
async initializeOptions() {
|
|
86
104
|
this.options = resolveBuildConfig();
|
|
105
|
+
const connectors = warlockConfigManager.get("connectors") ?? [];
|
|
106
|
+
assertUniqueConnectorNames([...connectors]);
|
|
107
|
+
assertNoReservedConnectorNames([...connectors]);
|
|
108
|
+
this.connectors = connectors;
|
|
87
109
|
await ensureDirectoryAsync(this.productionDir);
|
|
88
110
|
}
|
|
89
111
|
/**
|
|
112
|
+
* The context handed to every build contribution.
|
|
113
|
+
*/
|
|
114
|
+
buildContext() {
|
|
115
|
+
return {
|
|
116
|
+
productionDir: this.productionDir,
|
|
117
|
+
appRoot: rootPath(),
|
|
118
|
+
options: this.options
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Drain the `generate` hooks and fold what they returned back into the
|
|
123
|
+
* build.
|
|
124
|
+
*
|
|
125
|
+
* The entry point is REGENERATED here rather than generated later. The
|
|
126
|
+
* contribution slot is fixed — after `assertGeneratedImports` (so nothing
|
|
127
|
+
* bundles that the app could not resolve) and before `bundle` — while
|
|
128
|
+
* `generateEntryPoint` must stay at step 3, because `app.ts` is itself
|
|
129
|
+
* generated code the assertion has to see; moving it past the assertion
|
|
130
|
+
* would silently drop the entry from that check. Rewriting one small file
|
|
131
|
+
* is cheaper than losing either guarantee, and the write is pure
|
|
132
|
+
* (`generatedFiles` + these imports), so doing it twice is not a
|
|
133
|
+
* correctness risk.
|
|
134
|
+
*
|
|
135
|
+
* @returns whether any connector ran a `generate` hook — the caller uses it
|
|
136
|
+
* to decide if the import assertion is worth a second pass. Keyed on the
|
|
137
|
+
* hook EXISTING, not on what it returned: a hook that returns nothing may
|
|
138
|
+
* still have written files into `productionDir`, and those are exactly the
|
|
139
|
+
* files the second pass is there to read.
|
|
140
|
+
*/
|
|
141
|
+
async runGenerateContributions() {
|
|
142
|
+
const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));
|
|
143
|
+
const { entryImports, esbuild } = await runGenerateContributions(this.connectors, this.buildContext());
|
|
144
|
+
this.contributedEsbuild = esbuild;
|
|
145
|
+
if (entryImports.length > 0) await this.generateEntryPoint(entryImports);
|
|
146
|
+
return contributed;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
90
149
|
* Generate all combined files
|
|
91
150
|
*/
|
|
92
151
|
async generateCombinedFiles() {
|
|
@@ -249,9 +308,13 @@ bootstrap();
|
|
|
249
308
|
}
|
|
250
309
|
/**
|
|
251
310
|
* Generate the main entry point (app.ts)
|
|
311
|
+
*
|
|
312
|
+
* @param contributedImports lines from connector `generate` hooks, appended
|
|
313
|
+
* to section 4 after `./routes`
|
|
252
314
|
*/
|
|
253
|
-
async generateEntryPoint() {
|
|
315
|
+
async generateEntryPoint(contributedImports = []) {
|
|
254
316
|
console.log(colors.yellow(" Generating entry point..."));
|
|
317
|
+
const expectedNames = this.connectors.map((connector) => JSON.stringify(connector.name)).join(", ");
|
|
255
318
|
const imports = [
|
|
256
319
|
"// 1. Bootstrap (loads .env, initializes framework)",
|
|
257
320
|
"import \"./bootstrap\";",
|
|
@@ -259,6 +322,19 @@ bootstrap();
|
|
|
259
322
|
"// 2. Load configs",
|
|
260
323
|
"import \"./config-loader\";",
|
|
261
324
|
"",
|
|
325
|
+
"// 2.5 Register connectors declared in warlock.config (the same array this",
|
|
326
|
+
"// build read its contributions from, so built-for and boots-with match).",
|
|
327
|
+
"// The config is imported STATICALLY so esbuild bakes it into the bundle",
|
|
328
|
+
"// and the array is handed over explicitly — an artifact has no",
|
|
329
|
+
"// warlock.config.ts beside it to read at runtime, and a registration",
|
|
330
|
+
"// that quietly found nothing to register is the exact drift this",
|
|
331
|
+
"// section exists to prevent.",
|
|
332
|
+
"// `expectedNames` is the list this build resolved, in order — boot",
|
|
333
|
+
"// refuses to start when the config hands over a different set or order.",
|
|
334
|
+
"import { registerConfiguredConnectors } from \"@warlock.js/core\";",
|
|
335
|
+
`import warlockConfig from "${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config";`,
|
|
336
|
+
`registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,
|
|
337
|
+
"",
|
|
262
338
|
"// 3. Start early-phase connectors (database, cache, logger, ...)",
|
|
263
339
|
"// so data sources, cache, etc. are ready before app code runs",
|
|
264
340
|
"import { Application, connectorsManager, ConnectorLifecyclePhase } from \"@warlock.js/core\";",
|
|
@@ -269,7 +345,9 @@ bootstrap();
|
|
|
269
345
|
if (this.generatedFiles.locales) imports.push("await import(\"./locales\");");
|
|
270
346
|
if (this.generatedFiles.main) imports.push("await import(\"./main\");");
|
|
271
347
|
if (this.generatedFiles.routes) imports.push("await import(\"./routes\");");
|
|
272
|
-
imports.push(
|
|
348
|
+
imports.push(...contributedImports);
|
|
349
|
+
imports.push("", "// 5. Run startup validators registered via Application.onValidateBoot(...)", "await Application.runStartupValidators();");
|
|
350
|
+
imports.push("", "// 6. Start late-phase connectors (http, socket) — routes and", "// listeners registered by app code are now ready to bind", "await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);", "", "// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire", "Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });", "connectorsManager.shutdownOnProcessKill();");
|
|
273
351
|
const content = imports.join("\n") + "\n";
|
|
274
352
|
await putFileAsync(path.join(this.productionDir, "app.ts"), content);
|
|
275
353
|
}
|
|
@@ -294,6 +372,19 @@ bootstrap();
|
|
|
294
372
|
const alias = this.buildAliasMapFromTsconfig();
|
|
295
373
|
const isEsm = (this.options.format ?? "esm") === "esm";
|
|
296
374
|
const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : void 0);
|
|
375
|
+
const { define: contributedDefine, external: contributedExternal, loader: contributedLoader, ...contributedOptions } = this.contributedEsbuild;
|
|
376
|
+
const userDefine = this.options.define;
|
|
377
|
+
const userExternal = this.options.external;
|
|
378
|
+
const userLoader = this.options.loader;
|
|
379
|
+
const define = contributedDefine || userDefine ? {
|
|
380
|
+
...contributedDefine,
|
|
381
|
+
...userDefine
|
|
382
|
+
} : void 0;
|
|
383
|
+
const loader = contributedLoader || userLoader ? {
|
|
384
|
+
...contributedLoader,
|
|
385
|
+
...userLoader
|
|
386
|
+
} : void 0;
|
|
387
|
+
const external = contributedExternal || userExternal ? dedupe([...contributedExternal ?? [], ...userExternal ?? []]) : void 0;
|
|
297
388
|
if (singleBundle) console.log(colors.magenta(" Single-bundle mode — one JS file" + (esmShim && isEsm ? " with the ESM interop shim" : "") + ". Native .node addons are still emitted alongside it."));
|
|
298
389
|
try {
|
|
299
390
|
await esbuild.build({
|
|
@@ -310,7 +401,11 @@ bootstrap();
|
|
|
310
401
|
entryNames: entryName,
|
|
311
402
|
alias,
|
|
312
403
|
plugins: [nativeNodeModulesPlugin],
|
|
404
|
+
...contributedOptions,
|
|
313
405
|
...this.options,
|
|
406
|
+
...define ? { define } : {},
|
|
407
|
+
...external ? { external } : {},
|
|
408
|
+
...loader ? { loader } : {},
|
|
314
409
|
...banner ? { banner } : {}
|
|
315
410
|
});
|
|
316
411
|
} catch (e) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n ensureDirectoryAsync,\r\n fileExistsAsync,\r\n getFileAsync,\r\n getJsonFileAsync,\r\n putFileAsync,\r\n removeDirectoryAsync,\r\n} from \"@warlock.js/fs\";\r\nimport esbuild from \"esbuild\";\r\nimport glob from \"fast-glob\";\r\nimport path from \"path\";\r\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, rootPath, warlockPath } from \"../utils\";\r\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\r\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\r\nimport { toCamelCase, toKebabCase } from \"@mongez/reinforcements\";\r\n\r\n/**\r\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\r\n *\r\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\r\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\r\n * esbuild substitutes a stub that throws — **after the build has reported\r\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\r\n * firing, and it is the defect this shim removes.\r\n *\r\n * `__dirname` matters as much as `require`: without it a dependency resolving\r\n * an asset path silently gets `undefined` and fails later, further from the\r\n * cause.\r\n *\r\n * Written as one line because esbuild inserts a banner verbatim above the\r\n * bundle and a multi-line string here would shift every mapped line.\r\n */\r\nconst ESM_INTEROP_SHIM =\r\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\r\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\r\n \"import{dirname as __wlDirname}from'node:path';\" +\r\n \"const require=__wlCreateRequire(import.meta.url);\" +\r\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\r\n \"const __dirname=__wlDirname(__filename);\";\r\n\r\n/**\r\n * Combine the framework's banner with the user's, keeping both.\r\n *\r\n * esbuild's `banner` is an object keyed by output type, and every merge in the\r\n * path to it — the config merge and the options spread — REPLACES that object\r\n * rather than merging it. So whichever is applied second silently deletes the\r\n * other. This is the only place the two can coexist.\r\n *\r\n * The shim goes first: it defines `require`, which a user banner may use.\r\n *\r\n * @param userBanner banner from `warlock.config.ts`, if any\r\n * @param shim the interop shim, or undefined when it does not apply\r\n */\r\nfunction mergeBanner(\r\n userBanner: Record<string, string> | undefined,\r\n shim: string | undefined,\r\n): Record<string, string> | undefined {\r\n if (!shim) return userBanner;\r\n\r\n const userJs = userBanner?.js;\r\n\r\n return {\r\n ...userBanner,\r\n js: userJs ? `${shim}${userJs}` : shim,\r\n };\r\n}\r\n\r\n/**\r\n * Production Builder\r\n * Generates production-ready files and bundles them for deployment\r\n * Build options are loaded from warlock.config.ts\r\n */\r\nexport class ProductionBuilder {\r\n private options!: ResolvedBuildConfig;\r\n private readonly productionDir = warlockPath(\"production\");\r\n\r\n /**\r\n * Main build entry point\r\n */\r\n public async build(): Promise<void> {\r\n console.log(colors.cyan(\"Building for production...\\n\"));\r\n\r\n // Step 1: Initialize options from config\r\n await this.initializeOptions();\r\n\r\n // Step 2: Generate combined files\r\n await this.generateCombinedFiles();\r\n\r\n // Step 3: Generate entry point\r\n await this.generateEntryPoint();\r\n\r\n // Step 4: Refuse to bundle code the app could not resolve at runtime\r\n await this.assertGeneratedImports();\r\n\r\n // Step 5: Bundle with esbuild\r\n await this.bundle();\r\n\r\n // Step 6: Remove production folder\r\n await removeDirectoryAsync(this.productionDir);\r\n\r\n console.log(colors.green(\"Build complete!\"));\r\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\r\n }\r\n\r\n /**\r\n * Initialize options from warlock.config.ts\r\n */\r\n private async initializeOptions(): Promise<void> {\r\n this.options = resolveBuildConfig();\r\n\r\n // Ensure production directory exists\r\n await ensureDirectoryAsync(this.productionDir);\r\n }\r\n\r\n /**\r\n * Track which special files were generated\r\n */\r\n private generatedFiles = {\r\n locales: false,\r\n events: false,\r\n main: false,\r\n routes: false,\r\n };\r\n\r\n /**\r\n * Generate all combined files\r\n */\r\n private async generateCombinedFiles(): Promise<void> {\r\n console.log(colors.yellow(\" Generating production files...\"));\r\n\r\n // Generate bootstrap.ts file\r\n await this.generateBootstrap();\r\n\r\n // Generate config loader\r\n await this.generateConfigLoader();\r\n\r\n // Generate special files and track which ones have content\r\n const [locales, events, main, routes] = await Promise.all([\r\n this.generateLocales(),\r\n this.generateEvents(),\r\n this.generateMain(),\r\n this.generateRoutes(),\r\n ]);\r\n\r\n this.generatedFiles = { locales, events, main, routes };\r\n }\r\n\r\n /**\r\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\r\n */\r\n private async generateBootstrap(): Promise<void> {\r\n let content = `import { bootstrap, Application } from \"@warlock.js/core\";\r\n\r\n// Set production environment\r\nApplication.setRuntimeStrategy(\"production\");\r\nApplication.setEnvironment(\"production\");\r\n\r\n// Bootstrap the application\r\nbootstrap();\r\n`;\r\n if (await fileExistsAsync(appPath(\"bootstrap.ts\"))) {\r\n content += \"import './../../src/app/bootstrap';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\r\n }\r\n\r\n /**\r\n * Fail the build when generated code imports a package the app does not\r\n * declare.\r\n *\r\n * The bundler is configured `packages: \"external\"`, so every bare specifier\r\n * written above survives verbatim into an artifact that resolves against the\r\n * **consuming app's** node_modules. A framework-internal dependency imported\r\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\r\n * which is how a production app shipped that could not boot. Rewriting the\r\n * offending import fixes today's bundle; this check is what stops the next\r\n * change to the generator from quietly reintroducing it.\r\n */\r\n private async assertGeneratedImports(): Promise<void> {\r\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\r\n cwd: this.productionDir,\r\n absolute: false,\r\n });\r\n\r\n const [files, appPackage] = await Promise.all([\r\n Promise.all(\r\n generatedPaths.map(async (file) => ({\r\n file,\r\n content: await getFileAsync(path.join(this.productionDir, file)),\r\n })),\r\n ),\r\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\r\n ]);\r\n\r\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\r\n }\r\n\r\n /**\r\n * Glob for module files matching a pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModule(fileName: string): Promise<string[]> {\r\n const pattern = `**/${fileName}.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n // Convert to relative paths from .warlock/production/ to src/app/\r\n // e.g., \"users/main\" -> \"../../src/app/users/main\"\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Glob for files in a specific directory pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModuleDirectory(directory: string): Promise<string[]> {\r\n const pattern = `**/${directory}/*.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Generate config-loader.ts\r\n */\r\n private async generateConfigLoader(): Promise<void> {\r\n const configDirectory = path.join(process.cwd(), \"src/config\");\r\n\r\n const files = await glob(\"*.{ts,tsx}\", {\r\n cwd: configDirectory,\r\n absolute: false,\r\n });\r\n\r\n const configNames = files.map((f) => f.replace(/\\.(ts|tsx)$/, \"\"));\r\n\r\n // Only `@warlock.js/core` — the one package the app itself declares. See\r\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\r\n // dependency, so a bare import of it resolved by luck under npm/yarn\r\n // hoisting and died under pnpm's strict layout.\r\n const imports: string[] = [\r\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\r\n ];\r\n const configImports: string[] = [];\r\n const configSetCalls: string[] = [];\r\n const executors: string[] = [];\r\n\r\n for (const configName of configNames) {\r\n const properConfigName = toCamelCase(configName);\r\n const varName = `${properConfigName}Config`;\r\n configImports.push(`import ${varName} from \"../../src/config/${configName}\";`);\r\n configSetCalls.push(`setConfig(\"${properConfigName}\", ${varName});`);\r\n executors.push(`await configSpecialHandlers.execute(\"${properConfigName}\", ${varName});`);\r\n }\r\n\r\n let content = [\r\n ...imports,\r\n \"\",\r\n \"// Config imports\",\r\n ...configImports,\r\n \"\",\r\n \"// Register configs\",\r\n ...configSetCalls,\r\n \"\",\r\n \"// Special handlers\",\r\n ...executors,\r\n \"\",\r\n ].join(\"\\n\");\r\n\r\n if (await fileExistsAsync(appPath(\"prestart.ts\"))) {\r\n content += \"import './../../src/app/prestart';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\r\n }\r\n\r\n /**\r\n * Generate locales.ts (only if there are locale files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateLocales(): Promise<boolean> {\r\n const files = await this.globModule(\"utils/locales\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"locales.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate events.ts (only if there are event files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateEvents(): Promise<boolean> {\r\n const files = await this.globModuleDirectory(\"events\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"events.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate main.ts (only if there are main files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateMain(): Promise<boolean> {\r\n const files = await this.globModule(\"main\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"main.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate routes.ts (only if there are route files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateRoutes(): Promise<boolean> {\r\n const files = await this.globModule(\"routes\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"routes.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate a file with imports from all given files\r\n */\r\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\r\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, outputFile), content);\r\n }\r\n\r\n /**\r\n * Generate the main entry point (app.ts)\r\n */\r\n private async generateEntryPoint(): Promise<void> {\r\n console.log(colors.yellow(\" Generating entry point...\"));\r\n\r\n // Build imports based on which files were generated\r\n const imports: string[] = [\r\n \"// 1. Bootstrap (loads .env, initializes framework)\",\r\n 'import \"./bootstrap\";',\r\n \"\",\r\n \"// 2. Load configs\",\r\n 'import \"./config-loader\";',\r\n \"\",\r\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\r\n \"// so data sources, cache, etc. are ready before app code runs\",\r\n 'import { Application, connectorsManager, ConnectorLifecyclePhase } from \"@warlock.js/core\";',\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\r\n ];\r\n\r\n // App code uses dynamic `await import(...)` so each module's side\r\n // effects fire at THIS point in execution. Static imports would be\r\n // hoisted to module-instantiation time (before the early-phase await\r\n // resolves), which is exactly the bug this split is meant to fix.\r\n //\r\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\r\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\r\n // it at the await, not at instantiation. It does NOT come from\r\n // `splitting: true`, which only decides one-file-vs-chunks. This\r\n // previously said splitting was required; it is not, and `singleBundle`\r\n // (splitting: false) preserves the ordering.\r\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\r\n\r\n if (this.generatedFiles.events) {\r\n imports.push('await import(\"./events\");');\r\n }\r\n if (this.generatedFiles.locales) {\r\n imports.push('await import(\"./locales\");');\r\n }\r\n if (this.generatedFiles.main) {\r\n imports.push('await import(\"./main\");');\r\n }\r\n if (this.generatedFiles.routes) {\r\n imports.push('await import(\"./routes\");');\r\n }\r\n\r\n // Start late-phase connectors after app code registers routes/listeners\r\n imports.push(\r\n \"\",\r\n \"// 5. Start late-phase connectors (http, socket) — routes and\",\r\n \"// listeners registered by app code are now ready to bind\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\r\n \"\",\r\n \"// 6. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\r\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\r\n \"connectorsManager.shutdownOnProcessKill();\",\r\n );\r\n\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\r\n }\r\n\r\n /**\r\n * Bundle with esbuild\r\n */\r\n private async bundle(): Promise<void> {\r\n console.log(colors.magenta(\" Bundling with esbuild...\"));\r\n\r\n const entryPoint = path.join(this.productionDir, \"app.ts\");\r\n const outDir = this.options.outdir!;\r\n const outFileName = this.options.outFile!;\r\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\r\n const entryName = path.basename(outFileName, path.extname(outFileName));\r\n\r\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\r\n // unknown keys, and the user options are spread into its call verbatim.\r\n const singleBundle = this.options.singleBundle === true;\r\n const esmShim = this.options.esmShim !== false;\r\n // Read before deleting: the merged banner is applied AFTER the user\r\n // spread, so a user banner must not be lost to it or clobber the shim.\r\n const userBanner = this.options.banner;\r\n\r\n delete this.options.outFile;\r\n delete this.options.entryPath;\r\n delete this.options.singleBundle;\r\n delete this.options.esmShim;\r\n delete this.options.banner;\r\n\r\n await ensureDirectoryAsync(outDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\r\n\r\n // The user can override `format`, so gate the shim on the EFFECTIVE\r\n // format rather than on the default below. A CJS build already has\r\n // `require` and friends; injecting them there would be a redefinition.\r\n const isEsm = (this.options.format ?? \"esm\") === \"esm\";\r\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\r\n\r\n if (singleBundle) {\r\n console.log(\r\n colors.magenta(\r\n \" Single-bundle mode — one JS file\" +\r\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\r\n \". Native .node addons are still emitted alongside it.\",\r\n ),\r\n );\r\n }\r\n\r\n\r\n try {\r\n \r\n await esbuild.build({\r\n platform: \"node\",\r\n entryPoints: [entryPoint],\r\n bundle: true,\r\n // Both are DEFAULTS the user can override — they sit before the\r\n // `...this.options` spread deliberately. `singleBundle` moves them,\r\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\r\n //\r\n // Phase ordering does not depend on `splitting`: it comes from the\r\n // generated app.ts using dynamic `await import(...)` (see\r\n // generateAppEntry above), which esbuild defers to the call site in\r\n // either mode. Splitting only decides one file vs chunks.\r\n splitting: !singleBundle,\r\n packages: singleBundle ? \"bundle\" : \"external\",\r\n minify: this.options!.minify,\r\n sourcemap: this.options!.sourcemap === true ? \"linked\" : this.options!.sourcemap,\r\n format: \"esm\",\r\n // Targeting a concrete Node version (not \"esnext\") so esbuild\r\n // transpiles TC39 stage 3 decorators into helpers — Node does not\r\n // implement them natively yet.\r\n target: [\"node22\"],\r\n outdir: outDir,\r\n entryNames: entryName,\r\n alias,\r\n plugins: [nativeNodeModulesPlugin],\r\n ...(this.options as any),\r\n // AFTER the spread, and intentionally so: `banner` is an object, and\r\n // both the config merge and this spread REPLACE it wholesale rather\r\n // than merging. Left as a default above, any user banner would delete\r\n // the shim; left to the spread, the shim would delete theirs. The\r\n // merge is the only form that keeps both.\r\n ...(banner ? { banner } : {}),\r\n });\r\n } catch (e) {\r\n console.log(e);\r\n throw e;\r\n }\r\n }\r\n\r\n /**\r\n * Build an alias map from tsconfig `paths` so esbuild resolves local\r\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\r\n * folders during bundling. Without this, `packages: \"external\"` would\r\n * leave those bare specifiers as raw imports and Node would fail to\r\n * resolve them at runtime (they aren't installed in node_modules).\r\n *\r\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\r\n * option doesn't support glob-style mappings.\r\n */\r\n private buildAliasMapFromTsconfig(): Record<string, string> {\r\n tsconfigManager.init();\r\n\r\n const alias: Record<string, string> = {};\r\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\r\n\r\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\r\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\r\n continue;\r\n }\r\n\r\n alias[from] = path.resolve(baseUrl, to[0]);\r\n }\r\n\r\n return alias;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,MACoC;CACpC,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,SAAS,YAAY;CAE3B,OAAO;EACL,GAAG;EACH,IAAI,SAAS,GAAG,OAAO,WAAW;CACpC;AACF;;;;;;AAOA,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;wBA2ChC;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;CA3CA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA8B,CAAC;EAGvD,MAAM,KAAK,kBAAkB;EAG7B,MAAM,KAAK,sBAAsB;EAGjC,MAAM,KAAK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SAAS,GAAG;GACV,QAAQ,IAAI,CAAC;GACb,MAAM;EACR;CACF;;;;;;;;;;;CAYA,AAAQ,4BAAoD;EAC1D,gBAAgB,KAAK;EAErB,MAAM,QAAgC,CAAC;EACvC,MAAM,UAAU,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;EAEnE,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,gBAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,GAAG,EAAE;EAC3C;EAEA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n ensureDirectoryAsync,\r\n fileExistsAsync,\r\n getFileAsync,\r\n getJsonFileAsync,\r\n putFileAsync,\r\n removeDirectoryAsync,\r\n} from \"@warlock.js/fs\";\r\nimport esbuild from \"esbuild\";\r\nimport glob from \"fast-glob\";\r\nimport path from \"path\";\r\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\r\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\r\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\r\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, rootPath, warlockPath } from \"../utils\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\r\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\r\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\r\nimport { toCamelCase, toKebabCase } from \"@mongez/reinforcements\";\r\n\r\n/**\r\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\r\n *\r\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\r\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\r\n * esbuild substitutes a stub that throws — **after the build has reported\r\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\r\n * firing, and it is the defect this shim removes.\r\n *\r\n * `__dirname` matters as much as `require`: without it a dependency resolving\r\n * an asset path silently gets `undefined` and fails later, further from the\r\n * cause.\r\n *\r\n * Written as one line because esbuild inserts a banner verbatim above the\r\n * bundle and a multi-line string here would shift every mapped line.\r\n */\r\nconst ESM_INTEROP_SHIM =\r\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\r\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\r\n \"import{dirname as __wlDirname}from'node:path';\" +\r\n \"const require=__wlCreateRequire(import.meta.url);\" +\r\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\r\n \"const __dirname=__wlDirname(__filename);\";\r\n\r\n/**\r\n * Combine the framework's banner with the user's, keeping both.\r\n *\r\n * esbuild's `banner` is an object keyed by output type, and every merge in the\r\n * path to it — the config merge and the options spread — REPLACES that object\r\n * rather than merging it. So whichever is applied second silently deletes the\r\n * other. This is the only place the two can coexist.\r\n *\r\n * The shim goes first: it defines `require`, which a user banner may use.\r\n *\r\n * @param userBanner banner from `warlock.config.ts`, if any\r\n * @param shim the interop shim, or undefined when it does not apply\r\n */\r\nfunction mergeBanner(\r\n userBanner: Record<string, string> | undefined,\r\n shim: string | undefined,\r\n): Record<string, string> | undefined {\r\n if (!shim) return userBanner;\r\n\r\n const userJs = userBanner?.js;\r\n\r\n return {\r\n ...userBanner,\r\n js: userJs ? `${shim}${userJs}` : shim,\r\n };\r\n}\r\n\r\n/**\r\n * Prefix every generated file uses to reach the app root.\r\n *\r\n * Generated sources are written into `.warlock/production/`, two levels below\r\n * the app root, so `../../` lands back on it — the same hop already spelled\r\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\r\n * config-loader generators emit. Named once so a generator that needs a new\r\n * app-root file (`warlock.config`) cannot pick a different depth.\r\n */\r\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\r\n\r\n/**\r\n * Production Builder\r\n * Generates production-ready files and bundles them for deployment\r\n * Build options are loaded from warlock.config.ts\r\n */\r\nexport class ProductionBuilder {\r\n private options!: ResolvedBuildConfig;\r\n private readonly productionDir = warlockPath(\"production\");\r\n\r\n /**\r\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\r\n * never calls `boot()`/`start()` on them; it only\r\n * drains their `build` contributions.\r\n */\r\n private connectors: readonly Connector[] = [];\r\n\r\n /**\r\n * The contributors' merged esbuild patch, produced by the `generate` pass\r\n * and consumed by {@link bundle}.\r\n */\r\n private contributedEsbuild: ConnectorEsbuildPatch = {};\r\n\r\n /**\r\n * Main build entry point\r\n */\r\n public async build(): Promise<void> {\r\n console.log(colors.cyan(\"Building for production...\\n\"));\r\n\r\n // Step 1: Initialize options from config\r\n await this.initializeOptions();\r\n\r\n // Step 2: Generate combined files\r\n await this.generateCombinedFiles();\r\n\r\n // Step 3: Generate entry point\r\n await this.generateEntryPoint();\r\n\r\n // Step 4: Refuse to bundle code the app could not resolve at runtime\r\n await this.assertGeneratedImports();\r\n\r\n // Step 4.5: Drain the connectors' `generate` contributions\r\n const contributed = await this.runGenerateContributions();\r\n\r\n // Step 4.6: Re-assert over what the contributors just wrote.\r\n //\r\n // Step 4 only saw core's own generated files; a contributor writes its\r\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\r\n // specifier in it reaches the bundle unchecked. Under\r\n // `packages: \"external\"` that specifier survives verbatim into the\r\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\r\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\r\n // and re-reading the production dir is pure cost in the common case.\r\n if (contributed) {\r\n await this.assertGeneratedImports();\r\n }\r\n\r\n // Step 5: Bundle with esbuild\r\n await this.bundle();\r\n\r\n // Step 5.5: Drain the connectors' `emit` contributions — after the\r\n // bundle, and BEFORE step 6 deletes the directory they may still read.\r\n await runEmitContributions(this.connectors, this.buildContext());\r\n\r\n // Step 6: Remove production folder\r\n await removeDirectoryAsync(this.productionDir);\r\n\r\n console.log(colors.green(\"Build complete!\"));\r\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\r\n }\r\n\r\n /**\r\n * Initialize options from warlock.config.ts\r\n */\r\n private async initializeOptions(): Promise<void> {\r\n this.options = resolveBuildConfig();\r\n // Same config object `resolveBuildConfig` just read — `warlock build`\r\n // preloads warlock.config.ts, so no additional load happens here.\r\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\r\n\r\n // Checked here, where the array is first read, so nothing downstream has\r\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\r\n // a name listed twice would write its files and merge its esbuild options\r\n // twice into an artifact the runtime then boots that name only once from.\r\n // A build that half-applied a connector and reported success is worse than\r\n // one that never started.\r\n assertUniqueConnectorNames([...connectors]);\r\n\r\n // And here rather than only at boot, for the same reason: a name a built-in\r\n // already owns is skipped by the runtime, so an artifact built from it\r\n // carries the custom connector's generated files and esbuild patches while\r\n // the server boots the built-in instead. Refusing it at boot alone would\r\n // mean the build had already emitted that artifact — the failure has to\r\n // land on the developer running `warlock build`, not on whoever starts the\r\n // server. Same assertion the registration half calls, over the same names.\r\n assertNoReservedConnectorNames([...connectors]);\r\n\r\n this.connectors = connectors;\r\n\r\n // Ensure production directory exists\r\n await ensureDirectoryAsync(this.productionDir);\r\n }\r\n\r\n /**\r\n * The context handed to every build contribution.\r\n */\r\n private buildContext(): ConnectorBuildContext {\r\n return {\r\n productionDir: this.productionDir,\r\n appRoot: rootPath(),\r\n options: this.options,\r\n };\r\n }\r\n\r\n /**\r\n * Drain the `generate` hooks and fold what they returned back into the\r\n * build.\r\n *\r\n * The entry point is REGENERATED here rather than generated later. The\r\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\r\n * bundles that the app could not resolve) and before `bundle` — while\r\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\r\n * generated code the assertion has to see; moving it past the assertion\r\n * would silently drop the entry from that check. Rewriting one small file\r\n * is cheaper than losing either guarantee, and the write is pure\r\n * (`generatedFiles` + these imports), so doing it twice is not a\r\n * correctness risk.\r\n *\r\n * @returns whether any connector ran a `generate` hook — the caller uses it\r\n * to decide if the import assertion is worth a second pass. Keyed on the\r\n * hook EXISTING, not on what it returned: a hook that returns nothing may\r\n * still have written files into `productionDir`, and those are exactly the\r\n * files the second pass is there to read.\r\n */\r\n private async runGenerateContributions(): Promise<boolean> {\r\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\r\n\r\n const { entryImports, esbuild } = await runGenerateContributions(\r\n this.connectors,\r\n this.buildContext(),\r\n );\r\n\r\n this.contributedEsbuild = esbuild;\r\n\r\n if (entryImports.length > 0) {\r\n await this.generateEntryPoint(entryImports);\r\n }\r\n\r\n return contributed;\r\n }\r\n\r\n /**\r\n * Track which special files were generated\r\n */\r\n private generatedFiles = {\r\n locales: false,\r\n events: false,\r\n main: false,\r\n routes: false,\r\n };\r\n\r\n /**\r\n * Generate all combined files\r\n */\r\n private async generateCombinedFiles(): Promise<void> {\r\n console.log(colors.yellow(\" Generating production files...\"));\r\n\r\n // Generate bootstrap.ts file\r\n await this.generateBootstrap();\r\n\r\n // Generate config loader\r\n await this.generateConfigLoader();\r\n\r\n // Generate special files and track which ones have content\r\n const [locales, events, main, routes] = await Promise.all([\r\n this.generateLocales(),\r\n this.generateEvents(),\r\n this.generateMain(),\r\n this.generateRoutes(),\r\n ]);\r\n\r\n this.generatedFiles = { locales, events, main, routes };\r\n }\r\n\r\n /**\r\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\r\n */\r\n private async generateBootstrap(): Promise<void> {\r\n let content = `import { bootstrap, Application } from \"@warlock.js/core\";\r\n\r\n// Set production environment\r\nApplication.setRuntimeStrategy(\"production\");\r\nApplication.setEnvironment(\"production\");\r\n\r\n// Bootstrap the application\r\nbootstrap();\r\n`;\r\n if (await fileExistsAsync(appPath(\"bootstrap.ts\"))) {\r\n content += \"import './../../src/app/bootstrap';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\r\n }\r\n\r\n /**\r\n * Fail the build when generated code imports a package the app does not\r\n * declare.\r\n *\r\n * The bundler is configured `packages: \"external\"`, so every bare specifier\r\n * written above survives verbatim into an artifact that resolves against the\r\n * **consuming app's** node_modules. A framework-internal dependency imported\r\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\r\n * which is how a production app shipped that could not boot. Rewriting the\r\n * offending import fixes today's bundle; this check is what stops the next\r\n * change to the generator from quietly reintroducing it.\r\n */\r\n private async assertGeneratedImports(): Promise<void> {\r\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\r\n cwd: this.productionDir,\r\n absolute: false,\r\n });\r\n\r\n const [files, appPackage] = await Promise.all([\r\n Promise.all(\r\n generatedPaths.map(async (file) => ({\r\n file,\r\n content: await getFileAsync(path.join(this.productionDir, file)),\r\n })),\r\n ),\r\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\r\n ]);\r\n\r\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\r\n }\r\n\r\n /**\r\n * Glob for module files matching a pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModule(fileName: string): Promise<string[]> {\r\n const pattern = `**/${fileName}.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n // Convert to relative paths from .warlock/production/ to src/app/\r\n // e.g., \"users/main\" -> \"../../src/app/users/main\"\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Glob for files in a specific directory pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModuleDirectory(directory: string): Promise<string[]> {\r\n const pattern = `**/${directory}/*.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Generate config-loader.ts\r\n */\r\n private async generateConfigLoader(): Promise<void> {\r\n const configDirectory = path.join(process.cwd(), \"src/config\");\r\n\r\n const files = await glob(\"*.{ts,tsx}\", {\r\n cwd: configDirectory,\r\n absolute: false,\r\n });\r\n\r\n const configNames = files.map((f) => f.replace(/\\.(ts|tsx)$/, \"\"));\r\n\r\n // Only `@warlock.js/core` — the one package the app itself declares. See\r\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\r\n // dependency, so a bare import of it resolved by luck under npm/yarn\r\n // hoisting and died under pnpm's strict layout.\r\n const imports: string[] = [\r\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\r\n ];\r\n const configImports: string[] = [];\r\n const configSetCalls: string[] = [];\r\n const executors: string[] = [];\r\n\r\n for (const configName of configNames) {\r\n const properConfigName = toCamelCase(configName);\r\n const varName = `${properConfigName}Config`;\r\n configImports.push(`import ${varName} from \"../../src/config/${configName}\";`);\r\n configSetCalls.push(`setConfig(\"${properConfigName}\", ${varName});`);\r\n executors.push(`await configSpecialHandlers.execute(\"${properConfigName}\", ${varName});`);\r\n }\r\n\r\n let content = [\r\n ...imports,\r\n \"\",\r\n \"// Config imports\",\r\n ...configImports,\r\n \"\",\r\n \"// Register configs\",\r\n ...configSetCalls,\r\n \"\",\r\n \"// Special handlers\",\r\n ...executors,\r\n \"\",\r\n ].join(\"\\n\");\r\n\r\n if (await fileExistsAsync(appPath(\"prestart.ts\"))) {\r\n content += \"import './../../src/app/prestart';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\r\n }\r\n\r\n /**\r\n * Generate locales.ts (only if there are locale files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateLocales(): Promise<boolean> {\r\n const files = await this.globModule(\"utils/locales\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"locales.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate events.ts (only if there are event files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateEvents(): Promise<boolean> {\r\n const files = await this.globModuleDirectory(\"events\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"events.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate main.ts (only if there are main files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateMain(): Promise<boolean> {\r\n const files = await this.globModule(\"main\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"main.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate routes.ts (only if there are route files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateRoutes(): Promise<boolean> {\r\n const files = await this.globModule(\"routes\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"routes.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate a file with imports from all given files\r\n */\r\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\r\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, outputFile), content);\r\n }\r\n\r\n /**\r\n * Generate the main entry point (app.ts)\r\n *\r\n * @param contributedImports lines from connector `generate` hooks, appended\r\n * to section 4 after `./routes`\r\n */\r\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\r\n console.log(colors.yellow(\" Generating entry point...\"));\r\n\r\n // The names this build resolved, baked in as a literal. The entry imports\r\n // the config source, and that source is re-evaluated at startup — an\r\n // env-conditional `connectors` array can hand the boot a different list\r\n // than the one drained here. A literal is the only part of the array that\r\n // survives into the artifact unchanged, so it is what the boot compares\r\n // against.\r\n const expectedNames = this.connectors\r\n .map((connector) => JSON.stringify(connector.name))\r\n .join(\", \");\r\n\r\n // Build imports based on which files were generated\r\n const imports: string[] = [\r\n \"// 1. Bootstrap (loads .env, initializes framework)\",\r\n 'import \"./bootstrap\";',\r\n \"\",\r\n \"// 2. Load configs\",\r\n 'import \"./config-loader\";',\r\n \"\",\r\n // Registration has to sit between the config being available and the\r\n // first phase starting: the connectors listed in `connectors` are the\r\n // same ones this build drained contributions from, so the bundle boots\r\n // exactly what it was built for. Register any later and an early-phase\r\n // connector would miss its own start.\r\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\r\n \"// build read its contributions from, so built-for and boots-with match).\",\r\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\r\n \"// and the array is handed over explicitly — an artifact has no\",\r\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\r\n \"// that quietly found nothing to register is the exact drift this\",\r\n \"// section exists to prevent.\",\r\n \"// `expectedNames` is the list this build resolved, in order — boot\",\r\n \"// refuses to start when the config hands over a different set or order.\",\r\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\r\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\r\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\r\n \"\",\r\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\r\n \"// so data sources, cache, etc. are ready before app code runs\",\r\n 'import { Application, connectorsManager, ConnectorLifecyclePhase } from \"@warlock.js/core\";',\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\r\n ];\r\n\r\n // App code uses dynamic `await import(...)` so each module's side\r\n // effects fire at THIS point in execution. Static imports would be\r\n // hoisted to module-instantiation time (before the early-phase await\r\n // resolves), which is exactly the bug this split is meant to fix.\r\n //\r\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\r\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\r\n // it at the await, not at instantiation. It does NOT come from\r\n // `splitting: true`, which only decides one-file-vs-chunks. This\r\n // previously said splitting was required; it is not, and `singleBundle`\r\n // (splitting: false) preserves the ordering.\r\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\r\n\r\n if (this.generatedFiles.events) {\r\n imports.push('await import(\"./events\");');\r\n }\r\n if (this.generatedFiles.locales) {\r\n imports.push('await import(\"./locales\");');\r\n }\r\n if (this.generatedFiles.main) {\r\n imports.push('await import(\"./main\");');\r\n }\r\n if (this.generatedFiles.routes) {\r\n imports.push('await import(\"./routes\");');\r\n }\r\n\r\n // Contributor imports come AFTER `./routes`, never before: a connector\r\n // that registers pages needs the routes app code already collected —\r\n // the same ordering dev uses (routes first, then the connector installs\r\n // on top of them). Emitted verbatim; the contributor writes the whole\r\n // statement (e.g. `await import(\"./pages\");`).\r\n imports.push(...contributedImports);\r\n\r\n // A rejecting validator (Application.onValidateBoot) must abort boot\r\n // before late-phase connectors bind a port.\r\n imports.push(\r\n \"\",\r\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\r\n \"await Application.runStartupValidators();\",\r\n );\r\n\r\n // Start late-phase connectors after app code registers routes/listeners\r\n imports.push(\r\n \"\",\r\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\r\n \"// listeners registered by app code are now ready to bind\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\r\n \"\",\r\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\r\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\r\n \"connectorsManager.shutdownOnProcessKill();\",\r\n );\r\n\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\r\n }\r\n\r\n /**\r\n * Bundle with esbuild\r\n */\r\n private async bundle(): Promise<void> {\r\n console.log(colors.magenta(\" Bundling with esbuild...\"));\r\n\r\n const entryPoint = path.join(this.productionDir, \"app.ts\");\r\n const outDir = this.options.outdir!;\r\n const outFileName = this.options.outFile!;\r\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\r\n const entryName = path.basename(outFileName, path.extname(outFileName));\r\n\r\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\r\n // unknown keys, and the user options are spread into its call verbatim.\r\n const singleBundle = this.options.singleBundle === true;\r\n const esmShim = this.options.esmShim !== false;\r\n // Read before deleting: the merged banner is applied AFTER the user\r\n // spread, so a user banner must not be lost to it or clobber the shim.\r\n const userBanner = this.options.banner;\r\n\r\n delete this.options.outFile;\r\n delete this.options.entryPath;\r\n delete this.options.singleBundle;\r\n delete this.options.esmShim;\r\n delete this.options.banner;\r\n\r\n await ensureDirectoryAsync(outDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\r\n\r\n // The user can override `format`, so gate the shim on the EFFECTIVE\r\n // format rather than on the default below. A CJS build already has\r\n // `require` and friends; injecting them there would be a redefinition.\r\n const isEsm = (this.options.format ?? \"esm\") === \"esm\";\r\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\r\n\r\n // Contributor patch, split into the part that can ride the spread order\r\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\r\n // BEFORE the user spread below, which gives the ruled precedence for\r\n // free: builder defaults < contributor < user config.\r\n //\r\n // `define`, `external` and `loader` are pulled out because a spread\r\n // REPLACES them wholesale — the same trap `banner` documents. Two\r\n // contributors' env defines, a contributor's optional peers plus the\r\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\r\n // must both survive, so they are merged by key/by set and re-applied\r\n // after the spread with the user still winning per key.\r\n const {\r\n define: contributedDefine,\r\n external: contributedExternal,\r\n loader: contributedLoader,\r\n ...contributedOptions\r\n } = this.contributedEsbuild;\r\n\r\n const userDefine: Record<string, string> | undefined = this.options.define;\r\n const userExternal: string[] | undefined = this.options.external;\r\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = this.options.loader;\r\n\r\n const define =\r\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\r\n\r\n const loader =\r\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\r\n\r\n const external =\r\n contributedExternal || userExternal\r\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\r\n : undefined;\r\n\r\n if (singleBundle) {\r\n console.log(\r\n colors.magenta(\r\n \" Single-bundle mode — one JS file\" +\r\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\r\n \". Native .node addons are still emitted alongside it.\",\r\n ),\r\n );\r\n }\r\n\r\n\r\n try {\r\n \r\n await esbuild.build({\r\n platform: \"node\",\r\n entryPoints: [entryPoint],\r\n bundle: true,\r\n // Both are DEFAULTS the user can override — they sit before the\r\n // `...this.options` spread deliberately. `singleBundle` moves them,\r\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\r\n //\r\n // Phase ordering does not depend on `splitting`: it comes from the\r\n // generated app.ts using dynamic `await import(...)` (see\r\n // generateAppEntry above), which esbuild defers to the call site in\r\n // either mode. Splitting only decides one file vs chunks.\r\n splitting: !singleBundle,\r\n packages: singleBundle ? \"bundle\" : \"external\",\r\n minify: this.options!.minify,\r\n sourcemap: this.options!.sourcemap === true ? \"linked\" : this.options!.sourcemap,\r\n format: \"esm\",\r\n // Targeting a concrete Node version (not \"esnext\") so esbuild\r\n // transpiles TC39 stage 3 decorators into helpers — Node does not\r\n // implement them natively yet.\r\n target: [\"node22\"],\r\n outdir: outDir,\r\n entryNames: entryName,\r\n alias,\r\n plugins: [nativeNodeModulesPlugin],\r\n // Between the defaults and the user spread — the ruled precedence.\r\n ...contributedOptions,\r\n ...(this.options as any),\r\n // AFTER the spread for the same reason `banner` is: a spread replaces\r\n // these objects instead of merging them, so the merged values are\r\n // re-applied here. The user still wins — they were merged in last.\r\n ...(define ? { define } : {}),\r\n ...(external ? { external } : {}),\r\n ...(loader ? { loader } : {}),\r\n // AFTER the spread, and intentionally so: `banner` is an object, and\r\n // both the config merge and this spread REPLACE it wholesale rather\r\n // than merging. Left as a default above, any user banner would delete\r\n // the shim; left to the spread, the shim would delete theirs. The\r\n // merge is the only form that keeps both.\r\n ...(banner ? { banner } : {}),\r\n });\r\n } catch (e) {\r\n console.log(e);\r\n throw e;\r\n }\r\n }\r\n\r\n /**\r\n * Build an alias map from tsconfig `paths` so esbuild resolves local\r\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\r\n * folders during bundling. Without this, `packages: \"external\"` would\r\n * leave those bare specifiers as raw imports and Node would fail to\r\n * resolve them at runtime (they aren't installed in node_modules).\r\n *\r\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\r\n * option doesn't support glob-style mappings.\r\n */\r\n private buildAliasMapFromTsconfig(): Record<string, string> {\r\n tsconfigManager.init();\r\n\r\n const alias: Record<string, string> = {};\r\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\r\n\r\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\r\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\r\n continue;\r\n }\r\n\r\n alias[from] = path.resolve(baseUrl, to[0]);\r\n }\r\n\r\n return alias;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,MACoC;CACpC,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,SAAS,YAAY;CAE3B,OAAO;EACL,GAAG;EACH,IAAI,SAAS,GAAG,OAAO,WAAW;CACpC;AACF;;;;;;;;;;AAWA,MAAM,+BAA+B;;;;;;AAOrC,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;oBAOd,CAAC;4BAMQ,CAAC;wBAqI5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;CArIA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA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B,WAAW,KAAK,QAAS,cAAc,OAAO,WAAW,KAAK,QAAS;IACvE,QAAQ;IAIR,QAAQ,CAAC,QAAQ;IACjB,QAAQ;IACR,YAAY;IACZ;IACA,SAAS,CAAC,uBAAuB;IAEjC,GAAG;IACH,GAAI,KAAK;IAIT,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAC3B,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAC/B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAM3B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAC7B,CAAC;EACD,SAAS,GAAG;GACV,QAAQ,IAAI,CAAC;GACb,MAAM;EACR;CACF;;;;;;;;;;;CAYA,AAAQ,4BAAoD;EAC1D,gBAAgB,KAAK;EAErB,MAAM,QAAgC,CAAC;EACvC,MAAM,UAAU,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;EAEnE,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,gBAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,GAAG,EAAE;EAC3C;EAEA,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { WarlockConfig } from "../warlock-config/types.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../core/src/production/resolve-build-config.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Keys the builder deletes before handing the options to esbuild — ours
|
|
6
|
+
* (`singleBundle`, `esmShim`), which esbuild would reject as unknown, and
|
|
7
|
+
* `banner`, which is re-merged and re-applied after the user spread.
|
|
8
|
+
*
|
|
9
|
+
* They are optional here for a concrete reason: `Required<…>` makes `delete`
|
|
10
|
+
* a type error (TS2790). Naming exactly these three says which keys are
|
|
11
|
+
* removable, rather than casting at each `delete` — a cast there would also
|
|
12
|
+
* hide a genuine mistake.
|
|
13
|
+
*
|
|
14
|
+
* `outFile` and `entryPath` stay REQUIRED even though the builder deletes
|
|
15
|
+
* them too. They are always present after resolution and callers depend on
|
|
16
|
+
* that; widening them to `string | undefined` pushed the lie downstream into
|
|
17
|
+
* `start-production.command.ts`, which then could not trust its own config.
|
|
18
|
+
*/
|
|
19
|
+
type BuilderStrippedKeys = "singleBundle" | "esmShim" | "banner";
|
|
20
|
+
type ResolvedBuildConfig = Required<Omit<NonNullable<WarlockConfig["build"]>, "outDirectory" | BuilderStrippedKeys>> & Partial<Pick<NonNullable<WarlockConfig["build"]>, BuilderStrippedKeys>> & {
|
|
21
|
+
/** Absolute path to the bundled entry file (`{outdir}/{outFile}`) */entryPath: string;
|
|
22
|
+
};
|
|
23
|
+
//#endregion
|
|
24
|
+
export { ResolvedBuildConfig };
|
|
25
|
+
//# sourceMappingURL=resolve-build-config.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-build-config.d.mts","names":[],"sources":["../../../../../../../core/src/production/resolve-build-config.ts"],"mappings":";;;;;AAG6D;;;;AAkBrC;AAExB;;;;;;;;KAFK,mBAAA;AAAA,KAEO,mBAAA,GAAsB,QAAA,CAChC,IAAA,CAAK,WAAA,CAAY,aAAA,6BAA0C,mBAAA,KAE3D,OAAA,CAAQ,IAAA,CAAK,WAAA,CAAY,aAAA,YAAyB,mBAAA;EAAA,qEAEhD,SAAA;AAAA"}
|
|
@@ -1,10 +1,51 @@
|
|
|
1
|
+
import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
|
|
1
2
|
import { defaultWarlockConfigurations } from "../warlock-config/default-configurations.mjs";
|
|
2
3
|
import { normalizeBuildConfig } from "../warlock-config/normalize-build-config.mjs";
|
|
3
|
-
import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
|
|
4
4
|
import path from "path";
|
|
5
5
|
|
|
6
6
|
//#region ../core/src/production/resolve-build-config.ts
|
|
7
7
|
/**
|
|
8
|
+
* esbuild options the build config may not carry, and why.
|
|
9
|
+
*
|
|
10
|
+
* Both apply the named compiler options to EVERY file in the bundle, not just
|
|
11
|
+
* the app's own sources — workspace packages compiled under their own tsconfig
|
|
12
|
+
* are silently recompiled under the app's. An app-level
|
|
13
|
+
* `verbatimModuleSyntax: true` reaching package sources that never opted into
|
|
14
|
+
* it strips the imports their decorators rely on, and the build succeeds only
|
|
15
|
+
* to die at import time with `Class extends value undefined`.
|
|
16
|
+
*/
|
|
17
|
+
const FORBIDDEN_BUILD_OPTIONS = {
|
|
18
|
+
tsconfig: "points esbuild at a tsconfig file",
|
|
19
|
+
tsconfigRaw: "inlines compiler options"
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Raised when the build config carries an esbuild option the framework owns.
|
|
23
|
+
*
|
|
24
|
+
* The typed config already omits these keys; this catches the forms the type
|
|
25
|
+
* cannot see — an `as any` cast, or a plain `warlock.config.js`. Rejected
|
|
26
|
+
* rather than deleted: dropping the key quietly would leave the author
|
|
27
|
+
* believing a setting applied when it never did.
|
|
28
|
+
*/
|
|
29
|
+
var ForbiddenBuildOptionError = class extends Error {
|
|
30
|
+
constructor(option) {
|
|
31
|
+
super([
|
|
32
|
+
`build.${option} is not a supported warlock build option.`,
|
|
33
|
+
"",
|
|
34
|
+
`Setting it ${FORBIDDEN_BUILD_OPTIONS[option]} for every file in the bundle,`,
|
|
35
|
+
"including workspace packages that were compiled under their own tsconfig.",
|
|
36
|
+
"Options such as `verbatimModuleSyntax` then apply to sources that never",
|
|
37
|
+
"opted into them, and the build succeeds but crashes at import time with",
|
|
38
|
+
"`Class extends value undefined`.",
|
|
39
|
+
"",
|
|
40
|
+
`Remove \`${option}\` from the \`build\` block of your warlock config. The builder`,
|
|
41
|
+
"already reads the app's tsconfig for the parts it needs (path aliases); to",
|
|
42
|
+
"change how your own sources compile, edit that tsconfig.json instead."
|
|
43
|
+
].join("\n"));
|
|
44
|
+
this.option = option;
|
|
45
|
+
this.name = "ForbiddenBuildOptionError";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
8
49
|
* Resolve the build config with framework defaults applied.
|
|
9
50
|
*
|
|
10
51
|
* Both the production builder and `warlock start` call this so they
|
|
@@ -14,6 +55,7 @@ import path from "path";
|
|
|
14
55
|
*/
|
|
15
56
|
function resolveBuildConfig() {
|
|
16
57
|
const userBuild = normalizeBuildConfig(warlockConfigManager.get("build") ?? {});
|
|
58
|
+
for (const option of Object.keys(FORBIDDEN_BUILD_OPTIONS)) if (option in userBuild) throw new ForbiddenBuildOptionError(option);
|
|
17
59
|
const merged = {
|
|
18
60
|
...defaultWarlockConfigurations.build,
|
|
19
61
|
...userBuild
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-build-config.mjs","names":[],"sources":["../../../../../../../core/src/production/resolve-build-config.ts"],"sourcesContent":["import path from \"path\";\nimport { defaultWarlockConfigurations } from \"../warlock-config/default-configurations\";\nimport { normalizeBuildConfig } from \"../warlock-config/normalize-build-config\";\nimport type { WarlockConfig } from \"../warlock-config/types\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n/**\n * Keys the builder deletes before handing the options to esbuild — ours\n * (`singleBundle`, `esmShim`), which esbuild would reject as unknown, and\n * `banner`, which is re-merged and re-applied after the user spread.\n *\n * They are optional here for a concrete reason: `Required<…>` makes `delete`\n * a type error (TS2790). Naming exactly these three says which keys are\n * removable, rather than casting at each `delete` — a cast there would also\n * hide a genuine mistake.\n *\n * `outFile` and `entryPath` stay REQUIRED even though the builder deletes\n * them too. They are always present after resolution and callers depend on\n * that; widening them to `string | undefined` pushed the lie downstream into\n * `start-production.command.ts`, which then could not trust its own config.\n */\ntype BuilderStrippedKeys = \"singleBundle\" | \"esmShim\" | \"banner\";\n\nexport type ResolvedBuildConfig = Required<\n Omit<NonNullable<WarlockConfig[\"build\"]>, \"outDirectory\" | BuilderStrippedKeys>\n> &\n Partial<Pick<NonNullable<WarlockConfig[\"build\"]>, BuilderStrippedKeys>> & {\n /** Absolute path to the bundled entry file (`{outdir}/{outFile}`) */\n entryPath: string;\n };\n\n/**\n * Resolve the build config with framework defaults applied.\n *\n * Both the production builder and `warlock start` call this so they\n * agree on where the bundle lives — previously each had its own local\n * fallbacks and they drifted (`.warlock/production` vs `dist`),\n * letting `build` and `start` look at different paths.\n */\nexport function resolveBuildConfig(): ResolvedBuildConfig {\n // Normalised here rather than only in `defineConfig` because a project may\n // export a plain config object that never went through it.\n const userBuild = normalizeBuildConfig(warlockConfigManager.get(\"build\") ?? {});\n const defaults = defaultWarlockConfigurations.build!;\n const merged = { ...defaults, ...userBuild } as ResolvedBuildConfig;\n\n return {\n ...merged,\n entryPath: path.resolve(merged.outdir, merged.outFile),\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"resolve-build-config.mjs","names":[],"sources":["../../../../../../../core/src/production/resolve-build-config.ts"],"sourcesContent":["import path from \"path\";\nimport { defaultWarlockConfigurations } from \"../warlock-config/default-configurations\";\nimport { normalizeBuildConfig } from \"../warlock-config/normalize-build-config\";\nimport type { WarlockConfig } from \"../warlock-config/types\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n/**\n * Keys the builder deletes before handing the options to esbuild — ours\n * (`singleBundle`, `esmShim`), which esbuild would reject as unknown, and\n * `banner`, which is re-merged and re-applied after the user spread.\n *\n * They are optional here for a concrete reason: `Required<…>` makes `delete`\n * a type error (TS2790). Naming exactly these three says which keys are\n * removable, rather than casting at each `delete` — a cast there would also\n * hide a genuine mistake.\n *\n * `outFile` and `entryPath` stay REQUIRED even though the builder deletes\n * them too. They are always present after resolution and callers depend on\n * that; widening them to `string | undefined` pushed the lie downstream into\n * `start-production.command.ts`, which then could not trust its own config.\n */\ntype BuilderStrippedKeys = \"singleBundle\" | \"esmShim\" | \"banner\";\n\nexport type ResolvedBuildConfig = Required<\n Omit<NonNullable<WarlockConfig[\"build\"]>, \"outDirectory\" | BuilderStrippedKeys>\n> &\n Partial<Pick<NonNullable<WarlockConfig[\"build\"]>, BuilderStrippedKeys>> & {\n /** Absolute path to the bundled entry file (`{outdir}/{outFile}`) */\n entryPath: string;\n };\n\n/**\n * esbuild options the build config may not carry, and why.\n *\n * Both apply the named compiler options to EVERY file in the bundle, not just\n * the app's own sources — workspace packages compiled under their own tsconfig\n * are silently recompiled under the app's. An app-level\n * `verbatimModuleSyntax: true` reaching package sources that never opted into\n * it strips the imports their decorators rely on, and the build succeeds only\n * to die at import time with `Class extends value undefined`.\n */\nconst FORBIDDEN_BUILD_OPTIONS = {\n tsconfig: \"points esbuild at a tsconfig file\",\n tsconfigRaw: \"inlines compiler options\",\n} as const;\n\n/**\n * Raised when the build config carries an esbuild option the framework owns.\n *\n * The typed config already omits these keys; this catches the forms the type\n * cannot see — an `as any` cast, or a plain `warlock.config.js`. Rejected\n * rather than deleted: dropping the key quietly would leave the author\n * believing a setting applied when it never did.\n */\nexport class ForbiddenBuildOptionError extends Error {\n public constructor(public readonly option: keyof typeof FORBIDDEN_BUILD_OPTIONS) {\n super(\n [\n `build.${option} is not a supported warlock build option.`,\n \"\",\n `Setting it ${FORBIDDEN_BUILD_OPTIONS[option]} for every file in the bundle,`,\n \"including workspace packages that were compiled under their own tsconfig.\",\n \"Options such as `verbatimModuleSyntax` then apply to sources that never\",\n \"opted into them, and the build succeeds but crashes at import time with\",\n \"`Class extends value undefined`.\",\n \"\",\n `Remove \\`${option}\\` from the \\`build\\` block of your warlock config. The builder`,\n \"already reads the app's tsconfig for the parts it needs (path aliases); to\",\n \"change how your own sources compile, edit that tsconfig.json instead.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"ForbiddenBuildOptionError\";\n }\n}\n\n/**\n * Resolve the build config with framework defaults applied.\n *\n * Both the production builder and `warlock start` call this so they\n * agree on where the bundle lives — previously each had its own local\n * fallbacks and they drifted (`.warlock/production` vs `dist`),\n * letting `build` and `start` look at different paths.\n */\nexport function resolveBuildConfig(): ResolvedBuildConfig {\n // Normalised here rather than only in `defineConfig` because a project may\n // export a plain config object that never went through it.\n const userBuild = normalizeBuildConfig(warlockConfigManager.get(\"build\") ?? {});\n\n // Before the merge, so the option cannot reach the esbuild spread in\n // production-builder — which overrides framework defaults with user config.\n for (const option of Object.keys(FORBIDDEN_BUILD_OPTIONS) as Array<\n keyof typeof FORBIDDEN_BUILD_OPTIONS\n >) {\n if (option in userBuild) {\n throw new ForbiddenBuildOptionError(option);\n }\n }\n\n const defaults = defaultWarlockConfigurations.build!;\n const merged = { ...defaults, ...userBuild } as ResolvedBuildConfig;\n\n return {\n ...merged,\n entryPath: path.resolve(merged.outdir, merged.outFile),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,MAAM,0BAA0B;CAC9B,UAAU;CACV,aAAa;AACf;;;;;;;;;AAUA,IAAa,4BAAb,cAA+C,MAAM;CACnD,AAAO,YAAY,AAAgB,QAA8C;EAC/E,MACE;GACE,SAAS,OAAO;GAChB;GACA,cAAc,wBAAwB,QAAQ;GAC9C;GACA;GACA;GACA;GACA;GACA,YAAY,OAAO;GACnB;GACA;EACF,CAAC,CAAC,KAAK,IAAI,CACb;EAfiC;EAiBjC,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,SAAgB,qBAA0C;CAGxD,MAAM,YAAY,qBAAqB,qBAAqB,IAAI,OAAO,KAAK,CAAC,CAAC;CAI9E,KAAK,MAAM,UAAU,OAAO,KAAK,uBAAuB,GAGtD,IAAI,UAAU,WACZ,MAAM,IAAI,0BAA0B,MAAM;CAK9C,MAAM,SAAS;EAAE,GADA,6BAA6B;EAChB,GAAG;CAAU;CAE3C,OAAO;EACL,GAAG;EACH,WAAW,KAAK,QAAQ,OAAO,QAAQ,OAAO,OAAO;CACvD;AACF"}
|