@warlock.js/core 5.27.0 → 5.29.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 +24 -0
- package/esm/cli/commands/openapi-generator.action.mjs +1 -1
- package/esm/cli/commands/openapi-generator.action.mjs.map +1 -1
- package/esm/cli/commands/postman-generator.action.mjs +47 -0
- package/esm/cli/commands/postman-generator.action.mjs.map +1 -0
- package/esm/cli/commands/postman-generator.command.mjs +43 -0
- package/esm/cli/commands/postman-generator.command.mjs.map +1 -0
- package/esm/cli/framework-cli-commands.mjs +2 -0
- package/esm/cli/framework-cli-commands.mjs.map +1 -1
- package/esm/container/development-app-modules.d.mts +31 -0
- package/esm/container/development-app-modules.d.mts.map +1 -0
- package/esm/container/index.d.mts +2 -0
- package/esm/container/index.d.mts.map +1 -1
- package/esm/container/index.mjs.map +1 -1
- package/esm/dev-server/app-module-registry.mjs +52 -0
- package/esm/dev-server/app-module-registry.mjs.map +1 -0
- package/esm/dev-server/files-orchestrator.mjs +13 -2
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +29 -3
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/request.d.mts +2 -2
- package/esm/http/request.d.mts.map +1 -1
- package/esm/index.d.mts +7 -2
- package/esm/index.mjs +5 -2
- package/esm/localization/parse-locale-dictionary.d.mts +6 -1
- package/esm/localization/parse-locale-dictionary.d.mts.map +1 -1
- package/esm/localization/parse-locale-dictionary.mjs +5 -1
- package/esm/localization/parse-locale-dictionary.mjs.map +1 -1
- package/esm/openapi/development-openapi-provider.d.mts +12 -1
- package/esm/openapi/development-openapi-provider.d.mts.map +1 -1
- package/esm/openapi/development-openapi-provider.mjs +15 -1
- package/esm/openapi/development-openapi-provider.mjs.map +1 -1
- package/esm/openapi/index.d.mts +5 -2
- package/esm/openapi/index.mjs +3 -1
- package/esm/openapi/postman/build-request-body.mjs +86 -0
- package/esm/openapi/postman/build-request-body.mjs.map +1 -0
- package/esm/openapi/postman/build-request-url.mjs +85 -0
- package/esm/openapi/postman/build-request-url.mjs.map +1 -0
- package/esm/openapi/postman/build-saved-responses.mjs +60 -0
- package/esm/openapi/postman/build-saved-responses.mjs.map +1 -0
- package/esm/openapi/postman/example-from-schema.d.mts +17 -0
- package/esm/openapi/postman/example-from-schema.d.mts.map +1 -0
- package/esm/openapi/postman/example-from-schema.mjs +92 -0
- package/esm/openapi/postman/example-from-schema.mjs.map +1 -0
- package/esm/openapi/postman/http-status-text.mjs +31 -0
- package/esm/openapi/postman/http-status-text.mjs.map +1 -0
- package/esm/openapi/postman/index.d.mts +3 -0
- package/esm/openapi/postman/openapi-to-postman-collection.d.mts +22 -0
- package/esm/openapi/postman/openapi-to-postman-collection.d.mts.map +1 -0
- package/esm/openapi/postman/openapi-to-postman-collection.mjs +109 -0
- package/esm/openapi/postman/openapi-to-postman-collection.mjs.map +1 -0
- package/esm/openapi/postman/postman-types.d.mts +119 -0
- package/esm/openapi/postman/postman-types.d.mts.map +1 -0
- package/esm/openapi/postman/resolve-operation-auth.mjs +51 -0
- package/esm/openapi/postman/resolve-operation-auth.mjs.map +1 -0
- package/esm/openapi/postman/schema-refs.d.mts +7 -0
- package/esm/openapi/postman/schema-refs.d.mts.map +1 -0
- package/esm/openapi/postman/schema-refs.mjs +41 -0
- package/esm/openapi/postman/schema-refs.mjs.map +1 -0
- package/esm/openapi/postman/uuid-v5.mjs +29 -0
- package/esm/openapi/postman/uuid-v5.mjs.map +1 -0
- package/esm/openapi/response-schemas.mjs +4 -1
- package/esm/openapi/response-schemas.mjs.map +1 -1
- package/esm/openapi/schema-registry.mjs +6 -0
- package/esm/openapi/schema-registry.mjs.map +1 -1
- package/esm/resource/index.d.mts +1 -0
- package/esm/resource/index.mjs +1 -0
- package/esm/resource/nullable-resource.d.mts +44 -0
- package/esm/resource/nullable-resource.d.mts.map +1 -0
- package/esm/resource/nullable-resource.mjs +38 -0
- package/esm/resource/nullable-resource.mjs.map +1 -0
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs +24 -7
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/resource/types.d.mts +10 -5
- package/esm/resource/types.d.mts.map +1 -1
- package/esm/restful/restful.d.mts +5 -5
- package/esm/restful/restful.d.mts.map +1 -1
- package/esm/router/response-schema-types.mjs +2 -0
- package/esm/router/response-schema-types.mjs.map +1 -1
- package/llms-full.txt +269 -241
- package/llms.txt +42 -42
- package/package.json +12 -12
- package/skills/README.md +39 -39
- package/skills/add-connector/SKILL.md +4 -4
- package/skills/benchmark-code/SKILL.md +3 -3
- package/skills/build-restful/SKILL.md +5 -5
- package/skills/build-url/SKILL.md +7 -7
- package/skills/configure-app/SKILL.md +7 -7
- package/skills/create-controller/SKILL.md +8 -8
- package/skills/create-module/SKILL.md +9 -9
- package/skills/define-resource/SKILL.md +4 -4
- package/skills/encrypt-data/SKILL.md +7 -7
- package/skills/generate-openapi/SKILL.md +33 -5
- package/skills/hash-password/SKILL.md +8 -8
- package/skills/health-checks/SKILL.md +6 -6
- package/skills/lower-stage3-decorators/SKILL.md +4 -4
- package/skills/process-image/SKILL.md +5 -5
- package/skills/register-route/SKILL.md +6 -6
- package/skills/request-memo/SKILL.md +4 -4
- package/skills/request-tracing/SKILL.md +6 -6
- package/skills/resolve-path/SKILL.md +6 -6
- package/skills/retry-operation/SKILL.md +4 -4
- package/skills/run-app/SKILL.md +11 -11
- package/skills/send-mail/SKILL.md +3 -3
- package/skills/send-response/SKILL.md +6 -6
- package/skills/store-file/SKILL.md +4 -4
- package/skills/test-http/SKILL.md +5 -5
- package/skills/test-service/SKILL.md +5 -5
- package/skills/update-packages/SKILL.md +6 -6
- package/skills/upload-file/SKILL.md +7 -7
- package/skills/use-app-context/SKILL.md +7 -7
- package/skills/use-localization/SKILL.md +6 -6
- package/skills/use-middleware/SKILL.md +6 -6
- package/skills/use-model-transformers/SKILL.md +6 -6
- package/skills/use-repository/SKILL.md +7 -7
- package/skills/use-request-locals/SKILL.md +4 -4
- package/skills/validate-input/SKILL.md +7 -7
- package/skills/warlock-conventions/SKILL.md +6 -6
- package/skills/warlock-doctor/SKILL.md +5 -5
- package/skills/warlock-routes/SKILL.md +6 -6
- package/skills/wire-socket/SKILL.md +4 -4
- package/skills/write-cli-command/SKILL.md +6 -6
- package/skills/write-middleware/SKILL.md +8 -8
- package/skills/write-seeder/SKILL.md +5 -5
- package/skills/write-use-case/SKILL.md +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,30 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
6
6
|
|
|
7
7
|
> ⚠ **Versioning: `@warlock.js/*` does not follow SemVer strictly — breaking changes may ship in a minor.** This is a deliberate decision, not an oversight: the framework is pre-adoption and the cost of a major per behaviour fix currently outweighs the benefit. **Pin an exact version or a tilde range (`~4.13.0`) if you need to opt into changes rather than receive them.** Every breaking change is marked **BREAKING** in its entry and summarised in an _Upgrading_ section at the top of the release. **This policy will change once the framework has consumers beyond its author.**
|
|
8
8
|
|
|
9
|
+
## 5.29.0 - 2026-10-01
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **`nullable(Resource)`**: a resource that may be `null`, accepted as a `defineResource` field and in `responseSchema` bodies. A field outputs `null` (not omitted) for null/undefined input; `ResourceOutput`/`ResponseBodyOutput` type it as `Output | null`; OpenAPI documents it as `oneOf [resource, null]`; route types emit `… | null` (FORMAI).
|
|
14
|
+
- **`[Resource]` list fields in `defineResource`**: each item is mapped through the resource, `[]` stays `[]`, and the output type is an array (the same syntax `responseSchema` already accepts). Plain `Resource` fields behave as before (FORMAI).
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- Cast strings inside an `arrayOf({...})` item schema (`"number"`, `"string?"`, `"date"`, `"string[]"`) were silently dropped from the resource output; they are now cast like top-level fields, matching the output type.
|
|
19
|
+
- `parseLocaleDictionary()` accepts `defaultNamespace` as a function, called only when the file declares no `$group`, so a folder that cannot name a namespace never fails a file with an explicit `$group`.
|
|
20
|
+
- `warlock dev` publishes each `src/app` file it reloads (`{ url, generation }`, after the loader hook confirms the bump) through the `development.appModules` container key, so `@warlock.js/web` can load the same module instance in page loaders.
|
|
21
|
+
|
|
22
|
+
## 5.28.0 - 2026-10-01
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- **`warlock generate.postman`** writes a Postman Collection v2.1.0 (`storage/postman/collection.json`, or `--out`) derived from the same OpenAPI document as `generate.openapi` (options: `--title`, `--server`, `--include-pages`), so the two can never disagree. Each tag is a folder, each operation a request with an example body generated from its schema (JSON as raw, multipart as form-data), saved responses for every declared status, `{{baseUrl}}` and `{{token}}` collection variables, collection-level bearer auth for `authMiddleware()` routes and `noauth` on public ones. `openApiToPostmanCollection(document, options?)` is exported (pure, deterministic `_postman_id`), and `getDevelopmentPostmanCollection()` returns the collection for the running dev process.
|
|
27
|
+
|
|
28
|
+
### Fixed
|
|
29
|
+
|
|
30
|
+
- Expected client errors no longer fill logs with stack traces: a thrown error that resolves to a 4xx (an `HttpError` such as `ConflictError` or `ResourceNotFoundError`, or a `DatabaseWriterValidationError` configured below 500 via `http.modelValidationErrorStatus`) is logged once at `warn` as `Name: message (status)`, without the stack. 5xx and unknown errors are logged at `error` with the stack, as before.
|
|
31
|
+
- A nested-resource field whose input is an empty list now outputs `[]`; it used to drop the key. `null`/`undefined` still omit it.
|
|
32
|
+
|
|
9
33
|
## 5.27.0 - 2026-10-01
|
|
10
34
|
|
|
11
35
|
### Added
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi-generator.action.mjs","names":[],"sources":["../../../../../../../../core/src/cli/commands/openapi-generator.action.ts"],"sourcesContent":["import { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { colors } from \"@mongez/copper\";\nimport type { CommandActionData } from \"../../commands/types\";\nimport { collectOpenApiDocument } from \"../../openapi/collect-openapi-document\";\nimport { resolveBuildConfig } from \"../../production/resolve-build-config\";\nimport { rootPath } from \"../../utils/paths\";\n\n/** Where the document goes unless `--out` says otherwise. */\nexport const DEFAULT_OPENAPI_OUTPUT = \"storage/openapi/openapi.json\";\n\ntype OptionValue = CommandActionData[\"options\"][string];\n\
|
|
1
|
+
{"version":3,"file":"openapi-generator.action.mjs","names":[],"sources":["../../../../../../../../core/src/cli/commands/openapi-generator.action.ts"],"sourcesContent":["import { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { colors } from \"@mongez/copper\";\nimport type { CommandActionData } from \"../../commands/types\";\nimport { collectOpenApiDocument } from \"../../openapi/collect-openapi-document\";\nimport { resolveBuildConfig } from \"../../production/resolve-build-config\";\nimport { rootPath } from \"../../utils/paths\";\n\n/** Where the document goes unless `--out` says otherwise. */\nexport const DEFAULT_OPENAPI_OUTPUT = \"storage/openapi/openapi.json\";\n\ntype OptionValue = CommandActionData[\"options\"][string];\n\nexport function stringOption(value: OptionValue | undefined): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n}\n\n/**\n * Action behind `warlock generate.openapi`.\n *\n * Builds the OpenAPI 3.1 document in a fresh registration child (no connectors are booted),\n * writes it as pretty JSON to `--out` (default `storage/openapi/openapi.json`) and prints the\n * per-route gaps it found as warnings. A child failure is fatal and rejects; gaps never are.\n */\nexport async function generateOpenApiAction({ options }: CommandActionData): Promise<void> {\n const cwd = rootPath();\n const output = path.resolve(cwd, stringOption(options.out) ?? DEFAULT_OPENAPI_OUTPUT);\n\n const { document, warnings } = await collectOpenApiDocument({\n cwd,\n timeoutMs: resolveBuildConfig().routeRegistrationTimeoutMs,\n title: stringOption(options.title),\n server: stringOption(options.server),\n includePages: options.includePages === true,\n });\n\n await mkdir(path.dirname(output), { recursive: true });\n await writeFile(output, `${JSON.stringify(document, null, 2)}\\n`, \"utf8\");\n\n const operations = Object.values(document.paths).reduce(\n (total, item) => total + Object.keys(item).length,\n 0,\n );\n\n console.log(\n colors.greenBright(\n `OpenAPI ${document.openapi} written to ${output} (${Object.keys(document.paths).length} paths, ${operations} operations).`,\n ),\n );\n\n if (warnings.length > 0) {\n console.warn(colors.yellowBright(`\\n${warnings.length} warning${warnings.length === 1 ? \"\" : \"s\"}:`));\n\n for (const warning of warnings) {\n console.warn(` - ${warning}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,yBAAyB;AAItC,SAAgB,aAAa,OAAoD;CAC/E,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS,IAAI,MAAM,KAAK,IAAI;AAC/E;;;;;;;;AASA,eAAsB,sBAAsB,EAAE,WAA6C;CACzF,MAAM,MAAM,SAAS;CACrB,MAAM,SAAS,KAAK,QAAQ,KAAK,aAAa,QAAQ,GAAG,mCAA2B;CAEpF,MAAM,EAAE,UAAU,aAAa,MAAM,uBAAuB;EAC1D;EACA,WAAW,mBAAmB,CAAC,CAAC;EAChC,OAAO,aAAa,QAAQ,KAAK;EACjC,QAAQ,aAAa,QAAQ,MAAM;EACnC,cAAc,QAAQ,iBAAiB;CACzC,CAAC;CAED,MAAM,MAAM,KAAK,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;CACrD,MAAM,UAAU,QAAQ,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE,KAAK,MAAM;CAExE,MAAM,aAAa,OAAO,OAAO,SAAS,KAAK,CAAC,CAAC,QAC9C,OAAO,SAAS,QAAQ,OAAO,KAAK,IAAI,CAAC,CAAC,QAC3C,CACF;CAEA,QAAQ,IACN,OAAO,YACL,WAAW,SAAS,QAAQ,cAAc,OAAO,IAAI,OAAO,KAAK,SAAS,KAAK,CAAC,CAAC,OAAO,UAAU,WAAW,cAC/G,CACF;CAEA,IAAI,SAAS,SAAS,GAAG;EACvB,QAAQ,KAAK,OAAO,aAAa,KAAK,SAAS,OAAO,UAAU,SAAS,WAAW,IAAI,KAAK,IAAI,EAAE,CAAC;EAEpG,KAAK,MAAM,WAAW,UACpB,QAAQ,KAAK,OAAO,SAAS;CAEjC;AACF"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { rootPath } from "../../utils/paths.mjs";
|
|
2
|
+
import { openApiToPostmanCollection } from "../../openapi/postman/openapi-to-postman-collection.mjs";
|
|
3
|
+
import { resolveBuildConfig } from "../../production/resolve-build-config.mjs";
|
|
4
|
+
import { collectOpenApiDocument } from "../../openapi/collect-openapi-document.mjs";
|
|
5
|
+
import { stringOption } from "./openapi-generator.action.mjs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { colors } from "@mongez/copper";
|
|
8
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
9
|
+
|
|
10
|
+
//#region ../core/src/cli/commands/postman-generator.action.ts
|
|
11
|
+
/** Where the collection goes unless `--out` says otherwise. */
|
|
12
|
+
const DEFAULT_POSTMAN_OUTPUT = "storage/postman/collection.json";
|
|
13
|
+
function countRequests(items) {
|
|
14
|
+
return items.reduce((total, item) => total + ("item" in item ? countRequests(item.item) : 1), 0);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Action behind `warlock generate.postman`.
|
|
18
|
+
*
|
|
19
|
+
* Gets the OpenAPI document exactly as `generate.openapi` does (same registration child, same
|
|
20
|
+
* options), converts it to a Postman Collection v2.1.0 in this process and writes it as
|
|
21
|
+
* pretty JSON to `--out` (default `storage/postman/collection.json`). The per-route gaps the
|
|
22
|
+
* document builder found are printed as warnings. A child failure is fatal and rejects.
|
|
23
|
+
*/
|
|
24
|
+
async function generatePostmanAction({ options }) {
|
|
25
|
+
const cwd = rootPath();
|
|
26
|
+
const output = path.resolve(cwd, stringOption(options.out) ?? "storage/postman/collection.json");
|
|
27
|
+
const { document, warnings } = await collectOpenApiDocument({
|
|
28
|
+
cwd,
|
|
29
|
+
timeoutMs: resolveBuildConfig().routeRegistrationTimeoutMs,
|
|
30
|
+
title: stringOption(options.title),
|
|
31
|
+
server: stringOption(options.server),
|
|
32
|
+
includePages: options.includePages === true
|
|
33
|
+
});
|
|
34
|
+
const collection = openApiToPostmanCollection(document);
|
|
35
|
+
await mkdir(path.dirname(output), { recursive: true });
|
|
36
|
+
await writeFile(output, `${JSON.stringify(collection, null, 2)}\n`, "utf8");
|
|
37
|
+
const folders = collection.item.filter((item) => "item" in item).length;
|
|
38
|
+
console.log(colors.greenBright(`Postman collection written to ${output} (${folders} folder${folders === 1 ? "" : "s"}, ${countRequests(collection.item)} requests). Import it in Postman and set the {{token}} variable.`));
|
|
39
|
+
if (warnings.length > 0) {
|
|
40
|
+
console.warn(colors.yellowBright(`\n${warnings.length} warning${warnings.length === 1 ? "" : "s"}:`));
|
|
41
|
+
for (const warning of warnings) console.warn(` - ${warning}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
export { generatePostmanAction };
|
|
47
|
+
//# sourceMappingURL=postman-generator.action.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postman-generator.action.mjs","names":[],"sources":["../../../../../../../../core/src/cli/commands/postman-generator.action.ts"],"sourcesContent":["import { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { colors } from \"@mongez/copper\";\nimport type { CommandActionData } from \"../../commands/types\";\nimport { collectOpenApiDocument } from \"../../openapi/collect-openapi-document\";\nimport { openApiToPostmanCollection } from \"../../openapi/postman/openapi-to-postman-collection\";\nimport type { PostmanItem } from \"../../openapi/postman/postman-types\";\nimport { resolveBuildConfig } from \"../../production/resolve-build-config\";\nimport { rootPath } from \"../../utils/paths\";\nimport { stringOption } from \"./openapi-generator.action\";\n\n/** Where the collection goes unless `--out` says otherwise. */\nexport const DEFAULT_POSTMAN_OUTPUT = \"storage/postman/collection.json\";\n\nfunction countRequests(items: readonly PostmanItem[]): number {\n return items.reduce((total, item) => total + (\"item\" in item ? countRequests(item.item) : 1), 0);\n}\n\n/**\n * Action behind `warlock generate.postman`.\n *\n * Gets the OpenAPI document exactly as `generate.openapi` does (same registration child, same\n * options), converts it to a Postman Collection v2.1.0 in this process and writes it as\n * pretty JSON to `--out` (default `storage/postman/collection.json`). The per-route gaps the\n * document builder found are printed as warnings. A child failure is fatal and rejects.\n */\nexport async function generatePostmanAction({ options }: CommandActionData): Promise<void> {\n const cwd = rootPath();\n const output = path.resolve(cwd, stringOption(options.out) ?? DEFAULT_POSTMAN_OUTPUT);\n\n const { document, warnings } = await collectOpenApiDocument({\n cwd,\n timeoutMs: resolveBuildConfig().routeRegistrationTimeoutMs,\n title: stringOption(options.title),\n server: stringOption(options.server),\n includePages: options.includePages === true,\n });\n\n const collection = openApiToPostmanCollection(document);\n\n await mkdir(path.dirname(output), { recursive: true });\n await writeFile(output, `${JSON.stringify(collection, null, 2)}\\n`, \"utf8\");\n\n const folders = collection.item.filter((item) => \"item\" in item).length;\n\n console.log(\n colors.greenBright(\n `Postman collection written to ${output} (${folders} folder${folders === 1 ? \"\" : \"s\"}, ${countRequests(collection.item)} requests). Import it in Postman and set the {{token}} variable.`,\n ),\n );\n\n if (warnings.length > 0) {\n console.warn(colors.yellowBright(`\\n${warnings.length} warning${warnings.length === 1 ? \"\" : \"s\"}:`));\n\n for (const warning of warnings) {\n console.warn(` - ${warning}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAa,yBAAyB;AAEtC,SAAS,cAAc,OAAuC;CAC5D,OAAO,MAAM,QAAQ,OAAO,SAAS,SAAS,UAAU,OAAO,cAAc,KAAK,IAAI,IAAI,IAAI,CAAC;AACjG;;;;;;;;;AAUA,eAAsB,sBAAsB,EAAE,WAA6C;CACzF,MAAM,MAAM,SAAS;CACrB,MAAM,SAAS,KAAK,QAAQ,KAAK,aAAa,QAAQ,GAAG,sCAA2B;CAEpF,MAAM,EAAE,UAAU,aAAa,MAAM,uBAAuB;EAC1D;EACA,WAAW,mBAAmB,CAAC,CAAC;EAChC,OAAO,aAAa,QAAQ,KAAK;EACjC,QAAQ,aAAa,QAAQ,MAAM;EACnC,cAAc,QAAQ,iBAAiB;CACzC,CAAC;CAED,MAAM,aAAa,2BAA2B,QAAQ;CAEtD,MAAM,MAAM,KAAK,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;CACrD,MAAM,UAAU,QAAQ,GAAG,KAAK,UAAU,YAAY,MAAM,CAAC,EAAE,KAAK,MAAM;CAE1E,MAAM,UAAU,WAAW,KAAK,QAAQ,SAAS,UAAU,IAAI,CAAC,CAAC;CAEjE,QAAQ,IACN,OAAO,YACL,iCAAiC,OAAO,IAAI,QAAQ,SAAS,YAAY,IAAI,KAAK,IAAI,IAAI,cAAc,WAAW,IAAI,EAAE,iEAC3H,CACF;CAEA,IAAI,SAAS,SAAS,GAAG;EACvB,QAAQ,KAAK,OAAO,aAAa,KAAK,SAAS,OAAO,UAAU,SAAS,WAAW,IAAI,KAAK,IAAI,EAAE,CAAC;EAEpG,KAAK,MAAM,WAAW,UACpB,QAAQ,KAAK,OAAO,SAAS;CAEjC;AACF"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { command } from "../../commands/cli-command.mjs";
|
|
2
|
+
import { generatePostmanAction } from "./postman-generator.action.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../core/src/cli/commands/postman-generator.command.ts
|
|
5
|
+
/**
|
|
6
|
+
* `warlock generate.postman` — write a Postman Collection v2.1.0 derived from the same
|
|
7
|
+
* OpenAPI document `generate.openapi` produces, so the two never disagree.
|
|
8
|
+
*
|
|
9
|
+
* Routes are read in the same isolated child process `warlock build` uses; the conversion
|
|
10
|
+
* itself is pure and runs in the CLI process.
|
|
11
|
+
*/
|
|
12
|
+
const postmanGeneratorCommand = command({
|
|
13
|
+
name: "generate.postman",
|
|
14
|
+
description: "Generate a Postman collection (storage/postman/collection.json) from the routes",
|
|
15
|
+
action: generatePostmanAction,
|
|
16
|
+
preload: { warlockConfig: true },
|
|
17
|
+
options: [
|
|
18
|
+
{
|
|
19
|
+
text: "--out, -o",
|
|
20
|
+
description: "Output file, relative to the project root (default storage/postman/collection.json)",
|
|
21
|
+
type: "string"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
text: "--title",
|
|
25
|
+
description: "Collection name (default: the name in package.json)",
|
|
26
|
+
type: "string"
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
text: "--server",
|
|
30
|
+
description: "Value of {{baseUrl}} (default: built from the http config)",
|
|
31
|
+
type: "string"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
text: "--include-pages",
|
|
35
|
+
description: "Also include page (SSR) routes",
|
|
36
|
+
type: "boolean"
|
|
37
|
+
}
|
|
38
|
+
]
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
42
|
+
export { postmanGeneratorCommand };
|
|
43
|
+
//# sourceMappingURL=postman-generator.command.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postman-generator.command.mjs","names":[],"sources":["../../../../../../../../core/src/cli/commands/postman-generator.command.ts"],"sourcesContent":["import { command } from \"../../commands/cli-command\";\nimport { generatePostmanAction } from \"./postman-generator.action\";\n\n/**\n * `warlock generate.postman` — write a Postman Collection v2.1.0 derived from the same\n * OpenAPI document `generate.openapi` produces, so the two never disagree.\n *\n * Routes are read in the same isolated child process `warlock build` uses; the conversion\n * itself is pure and runs in the CLI process.\n */\nexport const postmanGeneratorCommand = command({\n name: \"generate.postman\",\n description: \"Generate a Postman collection (storage/postman/collection.json) from the routes\",\n action: generatePostmanAction,\n preload: {\n warlockConfig: true,\n },\n options: [\n {\n text: \"--out, -o\",\n description: \"Output file, relative to the project root (default storage/postman/collection.json)\",\n type: \"string\",\n },\n {\n text: \"--title\",\n description: \"Collection name (default: the name in package.json)\",\n type: \"string\",\n },\n {\n text: \"--server\",\n description: \"Value of {{baseUrl}} (default: built from the http config)\",\n type: \"string\",\n },\n {\n text: \"--include-pages\",\n description: \"Also include page (SSR) routes\",\n type: \"boolean\",\n },\n ],\n});\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,0BAA0B,QAAQ;CAC7C,MAAM;CACN,aAAa;CACb,QAAQ;CACR,SAAS,EACP,eAAe,KACjB;CACA,SAAS;EACP;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;CACF;AACF,CAAC"}
|
|
@@ -7,6 +7,7 @@ import { dropTablesCommand } from "./commands/drop-tables.command.mjs";
|
|
|
7
7
|
import { generateCommand, generateControllerCommand, generateMigrationCommand, generateModelCommand, generateModuleCommand, generateRepositoryCommand, generateResourceCommand, generateServiceCommand, generateUseCaseCommand } from "./commands/generate/generate.command.mjs";
|
|
8
8
|
import { migrateCommand } from "./commands/migrate.command.mjs";
|
|
9
9
|
import { openApiGeneratorCommand } from "./commands/openapi-generator.command.mjs";
|
|
10
|
+
import { postmanGeneratorCommand } from "./commands/postman-generator.command.mjs";
|
|
10
11
|
import { routesCommand, routesDiffCommand } from "./commands/routes.command.mjs";
|
|
11
12
|
import { seedCommand } from "./commands/seed.command.mjs";
|
|
12
13
|
import { startProductionCommand } from "./commands/start-production.command.mjs";
|
|
@@ -19,6 +20,7 @@ const frameworkCommands = [
|
|
|
19
20
|
devServerCommand,
|
|
20
21
|
typingsGeneratorCommand,
|
|
21
22
|
openApiGeneratorCommand,
|
|
23
|
+
postmanGeneratorCommand,
|
|
22
24
|
doctorCommand,
|
|
23
25
|
routesCommand,
|
|
24
26
|
routesDiffCommand,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-cli-commands.mjs","names":[],"sources":["../../../../../../../core/src/cli/framework-cli-commands.ts"],"sourcesContent":["import { addCommand } from \"./commands/add.command\";\nimport { buildCommand } from \"./commands/build.command\";\nimport { createDatabaseCommand } from \"./commands/create-database.command\";\nimport { devServerCommand } from \"./commands/dev-server.command\";\nimport { doctorCommand } from \"./commands/doctor.command\";\nimport { dropTablesCommand } from \"./commands/drop-tables.command\";\nimport {\n generateCommand,\n generateControllerCommand,\n generateMigrationCommand,\n generateModelCommand,\n generateModuleCommand,\n generateRepositoryCommand,\n generateResourceCommand,\n generateServiceCommand,\n generateUseCaseCommand,\n} from \"./commands/generate/generate.command\";\nimport { migrateCommand } from \"./commands/migrate.command\";\nimport { openApiGeneratorCommand } from \"./commands/openapi-generator.command\";\nimport { routesCommand, routesDiffCommand } from \"./commands/routes.command\";\nimport { seedCommand } from \"./commands/seed.command\";\nimport { startProductionCommand } from \"./commands/start-production.command\";\nimport { storagePutCommand } from \"./commands/storage-put.command\";\nimport { typingsGeneratorCommand } from \"./commands/typings-generator.command\";\nimport { updateCommand } from \"./commands/update.command\";\n\nexport const frameworkCommands = [\n // development commands\n devServerCommand,\n typingsGeneratorCommand,\n openApiGeneratorCommand,\n\n // diagnostics commands\n doctorCommand,\n routesCommand,\n routesDiffCommand,\n\n // production commands\n buildCommand,\n startProductionCommand,\n\n // database commands\n migrateCommand,\n seedCommand,\n createDatabaseCommand,\n dropTablesCommand,\n\n // generation/installation commands\n addCommand,\n updateCommand,\n\n // scaffolding commands\n generateCommand,\n generateModuleCommand,\n generateControllerCommand,\n generateServiceCommand,\n generateUseCaseCommand,\n generateModelCommand,\n generateRepositoryCommand,\n generateResourceCommand,\n generateMigrationCommand,\n\n // storage commands\n storagePutCommand,\n];\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"framework-cli-commands.mjs","names":[],"sources":["../../../../../../../core/src/cli/framework-cli-commands.ts"],"sourcesContent":["import { addCommand } from \"./commands/add.command\";\nimport { buildCommand } from \"./commands/build.command\";\nimport { createDatabaseCommand } from \"./commands/create-database.command\";\nimport { devServerCommand } from \"./commands/dev-server.command\";\nimport { doctorCommand } from \"./commands/doctor.command\";\nimport { dropTablesCommand } from \"./commands/drop-tables.command\";\nimport {\n generateCommand,\n generateControllerCommand,\n generateMigrationCommand,\n generateModelCommand,\n generateModuleCommand,\n generateRepositoryCommand,\n generateResourceCommand,\n generateServiceCommand,\n generateUseCaseCommand,\n} from \"./commands/generate/generate.command\";\nimport { migrateCommand } from \"./commands/migrate.command\";\nimport { openApiGeneratorCommand } from \"./commands/openapi-generator.command\";\nimport { postmanGeneratorCommand } from \"./commands/postman-generator.command\";\nimport { routesCommand, routesDiffCommand } from \"./commands/routes.command\";\nimport { seedCommand } from \"./commands/seed.command\";\nimport { startProductionCommand } from \"./commands/start-production.command\";\nimport { storagePutCommand } from \"./commands/storage-put.command\";\nimport { typingsGeneratorCommand } from \"./commands/typings-generator.command\";\nimport { updateCommand } from \"./commands/update.command\";\n\nexport const frameworkCommands = [\n // development commands\n devServerCommand,\n typingsGeneratorCommand,\n openApiGeneratorCommand,\n postmanGeneratorCommand,\n\n // diagnostics commands\n doctorCommand,\n routesCommand,\n routesDiffCommand,\n\n // production commands\n buildCommand,\n startProductionCommand,\n\n // database commands\n migrateCommand,\n seedCommand,\n createDatabaseCommand,\n dropTablesCommand,\n\n // generation/installation commands\n addCommand,\n updateCommand,\n\n // scaffolding commands\n generateCommand,\n generateModuleCommand,\n generateControllerCommand,\n generateServiceCommand,\n generateUseCaseCommand,\n generateModelCommand,\n generateRepositoryCommand,\n generateResourceCommand,\n generateMigrationCommand,\n\n // storage commands\n storagePutCommand,\n];\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,MAAa,oBAAoB;CAE/B;CACA;CACA;CACA;CAGA;CACA;CACA;CAGA;CACA;CAGA;CACA;CACA;CACA;CAGA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;AACF"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//#region ../core/src/container/development-app-modules.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* A read-only view of the `src/` files the development server has re-versioned,
|
|
4
|
+
* for adapters (the web connector's Vite SSR graph) that must import those
|
|
5
|
+
* files through the SAME native URL core's ESM loader hook uses, instead of
|
|
6
|
+
* evaluating a second copy of them.
|
|
7
|
+
*
|
|
8
|
+
* Like {@link DevelopmentModelModules}, this is a container-only internal
|
|
9
|
+
* contract: it is not a package-root dev-server export and it exposes no module
|
|
10
|
+
* namespace.
|
|
11
|
+
*/
|
|
12
|
+
type DevelopmentAppModuleEntry = Readonly<{
|
|
13
|
+
/** The file's plain `file://` URL (no query), as `ModuleLoader` imports it. */url: string;
|
|
14
|
+
/**
|
|
15
|
+
* How many times core has bumped this file. It is the SAME counter the loader
|
|
16
|
+
* hook thread keeps (`version-registry.ts`), so `${url}?v=${generation}` is
|
|
17
|
+
* exactly the URL the loader hook resolves the file to.
|
|
18
|
+
*
|
|
19
|
+
* An entry is only ever published AFTER the hook thread has acknowledged the
|
|
20
|
+
* bump, so reading this value and importing that URL cannot return the
|
|
21
|
+
* previous instance.
|
|
22
|
+
*/
|
|
23
|
+
generation: number;
|
|
24
|
+
}>;
|
|
25
|
+
type DevelopmentAppModules = {
|
|
26
|
+
/** `undefined` when the file was never bumped: its generation is 0. */get(absolutePath: string): DevelopmentAppModuleEntry | undefined; /** Called once per bumped file, after the hook thread flushed the bump. */
|
|
27
|
+
subscribe(listener: (entry: DevelopmentAppModuleEntry) => void): () => void;
|
|
28
|
+
};
|
|
29
|
+
//#endregion
|
|
30
|
+
export { DevelopmentAppModuleEntry, DevelopmentAppModules };
|
|
31
|
+
//# sourceMappingURL=development-app-modules.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"development-app-modules.d.mts","names":[],"sources":["../../../../../../../core/src/container/development-app-modules.ts"],"mappings":";;AAUA;;;;;;;;AAYY;KAZA,yBAAA,GAA4B,QAAQ;EAef,+EAb/B,GAAA;EAiBqD;;;;;;;;;EAPrD,UAAA;AAAA;AAAA,KAGU,qBAAA;yEAEV,GAAA,CAAI,YAAA,WAAuB,yBAAA;EAE3B,SAAA,CAAU,QAAA,GAAW,KAAA,EAAO,yBAAyB;AAAA"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Router } from "../router/router.mjs";
|
|
2
|
+
import { DevelopmentAppModuleEntry, DevelopmentAppModules } from "./development-app-modules.mjs";
|
|
2
3
|
import { DevelopmentModelModuleEntry, DevelopmentModelModuleState, DevelopmentModelModules } from "./development-model-modules.mjs";
|
|
3
4
|
import { DataSource } from "@warlock.js/cascade";
|
|
4
5
|
import { FastifyInstance } from "fastify";
|
|
@@ -15,6 +16,7 @@ type ContainerTypes = {
|
|
|
15
16
|
socket: Server;
|
|
16
17
|
"database.source": DataSource;
|
|
17
18
|
"development.modelModules": DevelopmentModelModules;
|
|
19
|
+
"development.appModules": DevelopmentAppModules;
|
|
18
20
|
};
|
|
19
21
|
type ContainerKeys = keyof ContainerTypes | (string & {});
|
|
20
22
|
declare class Container {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"mappings":";;;;;;;;;AA6BA;;KAAY,cAAA;EACV,MAAA,EAAQ,MAAA;EACR,aAAA,EAAe,eAAA;EACf,cAAA;EACA,MAAA,EAAQ,MAAA;EACR,iBAAA,EAAmB,UAAA;EACnB,0BAAA,EAA4B,uBAAA;EAC5B,wBAAA,EAA0B,qBAAA;AAAA;AAAA,KAGvB,aAAA,SAAsB,cAAc;AAAA,cAEnC,SAAA;EAVJ;;;EAcO,GAAA,iBAAoB,cAAA,EAAgB,GAAA,EAAK,CAAA,EAAG,KAAA,EAAO,cAAA,CAAe,CAAA;EAClE,GAAA,UAAa,GAAA,UAAa,KAAA,EAAO,CAAA;EAZxC;;;;;;;AAE+C;AAC/C;;;EAyBO,GAAA,iBAAoB,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAC5D,GAAA,UAAa,GAAA,WAAc,CAAA;EAtB9B;;;EAmCG,GAAA,CAAI,GAAA,EAAK,aAAA;EA/BgC;;;;;;;;;EA4CzC,MAAA,iBAAuB,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAC/D,MAAA,UAAgB,GAAA,WAAc,CAAA;EADc;;;EAS5C,SAAA,iBAA0B,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAClE,SAAA,UAAmB,GAAA,WAAc,CAAA;EADc;;;EAS/C,MAAA,CAAO,GAAA;AAAA;AAAA,cAKH,SAAA,EAAS,SAAkB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"sourcesContent":["import { type DataSource } from \"@warlock.js/cascade\";\nimport { type FastifyInstance } from \"fastify\";\nimport { type Server } from \"socket.io\";\nimport { ContainerKeyMissingError } from \"../errors/container-key-missing-error\";\nimport { type Router } from \"../router\";\nimport {\n getRegisteredContainerInstances,\n registerContainerInstance,\n} from \"./container-instance-registry\";\nimport type { DevelopmentModelModules } from \"./development-model-modules\";\n\nexport type {\n DevelopmentModelModuleEntry,\n DevelopmentModelModules,\n DevelopmentModelModuleState,\n} from \"./development-model-modules\";\n\nconst containerMap: Map<string, any> = new Map();\n\nregisterContainerInstance();\n\n/**\n * Known container types for better IDE support\n */\nexport type ContainerTypes = {\n router: Router;\n \"http.server\": FastifyInstance;\n \"http.baseUrl\": string;\n socket: Server;\n \"database.source\": DataSource;\n \"development.modelModules\": DevelopmentModelModules;\n};\n\ntype ContainerKeys = keyof ContainerTypes | (string & {});\n\nclass Container {\n /**\n * Set a value in the container\n */\n public set<K extends keyof ContainerTypes>(key: K, value: ContainerTypes[K]): void;\n public set<T = any>(key: string, value: T): void;\n public set(key: any, value: any) {\n containerMap.set(key, value);\n }\n\n /**\n * Get a value from the container, or throw if `key` is not registered.\n *\n * Behaves exactly like an ordinary \"not registered\" error when only one\n * copy of this module is loaded. When {@link getRegisteredContainerInstances}\n * shows more than one, the thrown error additionally names that count, so\n * a duplicate-instance dev-path miss is never indistinguishable from a\n * genuine missing registration.\n *\n * Use {@link tryGet} instead when the value is genuinely optional.\n */\n public get<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public get<T = any>(key: string): T;\n public get(key: any): any {\n if (!containerMap.has(key)) {\n const instanceCount = getRegisteredContainerInstances().length;\n throw new ContainerKeyMissingError(key, instanceCount, [...containerMap.keys()]);\n }\n\n return containerMap.get(key);\n }\n\n /**\n * Check if a key exists in the container\n */\n public has(key: ContainerKeys) {\n return containerMap.has(key);\n }\n\n /**\n * Get a value from the container, or `undefined` if `key` is not\n * registered.\n *\n * Use this only for genuinely optional dependencies — where the caller\n * has its own fallback for an absent value. For every other read, prefer\n * {@link get}: a hole in the container should fail loudly, not hand back\n * `undefined` typed as the real value.\n */\n public tryGet<K extends keyof ContainerTypes>(key: K): ContainerTypes[K] | undefined;\n public tryGet<T = any>(key: string): T | undefined;\n public tryGet(key: any): any {\n return containerMap.get(key);\n }\n\n /**\n * @deprecated `get` now throws for a missing key; use {@link get}.\n */\n public getOrFail<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public getOrFail<T = any>(key: string): T;\n public getOrFail(key: any): any {\n return this.get(key);\n }\n\n /**\n * Delete a key from the container\n */\n public delete(key: string) {\n containerMap.delete(key);\n }\n}\n\nexport const container = new Container();\n"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"sourcesContent":["import { type DataSource } from \"@warlock.js/cascade\";\nimport { type FastifyInstance } from \"fastify\";\nimport { type Server } from \"socket.io\";\nimport { ContainerKeyMissingError } from \"../errors/container-key-missing-error\";\nimport { type Router } from \"../router\";\nimport {\n getRegisteredContainerInstances,\n registerContainerInstance,\n} from \"./container-instance-registry\";\nimport type { DevelopmentAppModules } from \"./development-app-modules\";\nimport type { DevelopmentModelModules } from \"./development-model-modules\";\n\nexport type {\n DevelopmentAppModuleEntry,\n DevelopmentAppModules,\n} from \"./development-app-modules\";\nexport type {\n DevelopmentModelModuleEntry,\n DevelopmentModelModules,\n DevelopmentModelModuleState,\n} from \"./development-model-modules\";\n\nconst containerMap: Map<string, any> = new Map();\n\nregisterContainerInstance();\n\n/**\n * Known container types for better IDE support\n */\nexport type ContainerTypes = {\n router: Router;\n \"http.server\": FastifyInstance;\n \"http.baseUrl\": string;\n socket: Server;\n \"database.source\": DataSource;\n \"development.modelModules\": DevelopmentModelModules;\n \"development.appModules\": DevelopmentAppModules;\n};\n\ntype ContainerKeys = keyof ContainerTypes | (string & {});\n\nclass Container {\n /**\n * Set a value in the container\n */\n public set<K extends keyof ContainerTypes>(key: K, value: ContainerTypes[K]): void;\n public set<T = any>(key: string, value: T): void;\n public set(key: any, value: any) {\n containerMap.set(key, value);\n }\n\n /**\n * Get a value from the container, or throw if `key` is not registered.\n *\n * Behaves exactly like an ordinary \"not registered\" error when only one\n * copy of this module is loaded. When {@link getRegisteredContainerInstances}\n * shows more than one, the thrown error additionally names that count, so\n * a duplicate-instance dev-path miss is never indistinguishable from a\n * genuine missing registration.\n *\n * Use {@link tryGet} instead when the value is genuinely optional.\n */\n public get<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public get<T = any>(key: string): T;\n public get(key: any): any {\n if (!containerMap.has(key)) {\n const instanceCount = getRegisteredContainerInstances().length;\n throw new ContainerKeyMissingError(key, instanceCount, [...containerMap.keys()]);\n }\n\n return containerMap.get(key);\n }\n\n /**\n * Check if a key exists in the container\n */\n public has(key: ContainerKeys) {\n return containerMap.has(key);\n }\n\n /**\n * Get a value from the container, or `undefined` if `key` is not\n * registered.\n *\n * Use this only for genuinely optional dependencies — where the caller\n * has its own fallback for an absent value. For every other read, prefer\n * {@link get}: a hole in the container should fail loudly, not hand back\n * `undefined` typed as the real value.\n */\n public tryGet<K extends keyof ContainerTypes>(key: K): ContainerTypes[K] | undefined;\n public tryGet<T = any>(key: string): T | undefined;\n public tryGet(key: any): any {\n return containerMap.get(key);\n }\n\n /**\n * @deprecated `get` now throws for a missing key; use {@link get}.\n */\n public getOrFail<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public getOrFail<T = any>(key: string): T;\n public getOrFail(key: any): any {\n return this.get(key);\n }\n\n /**\n * Delete a key from the container\n */\n public delete(key: string) {\n containerMap.delete(key);\n }\n}\n\nexport const container = new Container();\n"],"mappings":";;;;AAsBA,MAAM,+BAAiC,IAAI,IAAI;AAE/C,0BAA0B;AAiB1B,IAAM,YAAN,MAAgB;CAMd,AAAO,IAAI,KAAU,OAAY;EAC/B,aAAa,IAAI,KAAK,KAAK;CAC7B;CAeA,AAAO,IAAI,KAAe;EACxB,IAAI,CAAC,aAAa,IAAI,GAAG,GAAG;GAC1B,MAAM,gBAAgB,gCAAgC,CAAC,CAAC;GACxD,MAAM,IAAI,yBAAyB,KAAK,eAAe,CAAC,GAAG,aAAa,KAAK,CAAC,CAAC;EACjF;EAEA,OAAO,aAAa,IAAI,GAAG;CAC7B;;;;CAKA,AAAO,IAAI,KAAoB;EAC7B,OAAO,aAAa,IAAI,GAAG;CAC7B;CAaA,AAAO,OAAO,KAAe;EAC3B,OAAO,aAAa,IAAI,GAAG;CAC7B;CAOA,AAAO,UAAU,KAAe;EAC9B,OAAO,KAAK,IAAI,GAAG;CACrB;;;;CAKA,AAAO,OAAO,KAAa;EACzB,aAAa,OAAO,GAAG;CACzB;AACF;AAEA,MAAa,YAAY,IAAI,UAAU"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { container } from "../container/index.mjs";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
|
|
4
|
+
//#region ../core/src/dev-server/app-module-registry.ts
|
|
5
|
+
/**
|
|
6
|
+
* The SAME key normalization the loader hook thread uses for its version map
|
|
7
|
+
* (`loader/version-registry.ts`). It is what keeps `generation` equal to the
|
|
8
|
+
* hook's version for a path: both sides count bumps per this key.
|
|
9
|
+
*/
|
|
10
|
+
function normalizeKey(absolutePath) {
|
|
11
|
+
return absolutePath.replace(/\\/g, "/").toLowerCase();
|
|
12
|
+
}
|
|
13
|
+
/** Internal writer for the container's read-only development app-module carrier. */
|
|
14
|
+
var DevelopmentAppModuleRegistry = class {
|
|
15
|
+
constructor() {
|
|
16
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
17
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
18
|
+
}
|
|
19
|
+
get(absolutePath) {
|
|
20
|
+
return this.entries.get(normalizeKey(absolutePath));
|
|
21
|
+
}
|
|
22
|
+
subscribe(listener) {
|
|
23
|
+
this.listeners.add(listener);
|
|
24
|
+
return () => this.listeners.delete(listener);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Record that the hook thread has processed one more bump of this file.
|
|
28
|
+
* Call only after the hook thread acknowledged it (`flushVersionBumps`).
|
|
29
|
+
*/
|
|
30
|
+
bump(absolutePath) {
|
|
31
|
+
const key = normalizeKey(absolutePath);
|
|
32
|
+
const entry = {
|
|
33
|
+
url: pathToFileURL(absolutePath).href,
|
|
34
|
+
generation: (this.entries.get(key)?.generation ?? 0) + 1
|
|
35
|
+
};
|
|
36
|
+
this.entries.set(key, entry);
|
|
37
|
+
for (const listener of this.listeners) try {
|
|
38
|
+
listener(entry);
|
|
39
|
+
} catch {}
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
function getDevelopmentAppModuleRegistry() {
|
|
43
|
+
const existing = container.tryGet("development.appModules");
|
|
44
|
+
if (existing instanceof DevelopmentAppModuleRegistry) return existing;
|
|
45
|
+
const registry = new DevelopmentAppModuleRegistry();
|
|
46
|
+
container.set("development.appModules", registry);
|
|
47
|
+
return registry;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
export { getDevelopmentAppModuleRegistry };
|
|
52
|
+
//# sourceMappingURL=app-module-registry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-module-registry.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/app-module-registry.ts"],"sourcesContent":["import { pathToFileURL } from \"node:url\";\nimport { container } from \"../container\";\nimport type {\n DevelopmentAppModuleEntry,\n DevelopmentAppModules,\n} from \"../container/development-app-modules\";\n\n/**\n * The SAME key normalization the loader hook thread uses for its version map\n * (`loader/version-registry.ts`). It is what keeps `generation` equal to the\n * hook's version for a path: both sides count bumps per this key.\n */\nfunction normalizeKey(absolutePath: string): string {\n return absolutePath.replace(/\\\\/g, \"/\").toLowerCase();\n}\n\n/** Internal writer for the container's read-only development app-module carrier. */\nexport class DevelopmentAppModuleRegistry implements DevelopmentAppModules {\n private readonly entries = new Map<string, DevelopmentAppModuleEntry>();\n private readonly listeners = new Set<(entry: DevelopmentAppModuleEntry) => void>();\n\n public get(absolutePath: string): DevelopmentAppModuleEntry | undefined {\n return this.entries.get(normalizeKey(absolutePath));\n }\n\n public subscribe(listener: (entry: DevelopmentAppModuleEntry) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Record that the hook thread has processed one more bump of this file.\n * Call only after the hook thread acknowledged it (`flushVersionBumps`).\n */\n public bump(absolutePath: string): void {\n const key = normalizeKey(absolutePath);\n const entry: DevelopmentAppModuleEntry = {\n url: pathToFileURL(absolutePath).href,\n generation: (this.entries.get(key)?.generation ?? 0) + 1,\n };\n\n this.entries.set(key, entry);\n\n for (const listener of this.listeners) {\n try {\n listener(entry);\n } catch {\n // A subscriber's invalidation failure must never abort the reload batch.\n }\n }\n }\n}\n\nexport function getDevelopmentAppModuleRegistry(): DevelopmentAppModuleRegistry {\n const existing = container.tryGet(\"development.appModules\");\n\n if (existing instanceof DevelopmentAppModuleRegistry) return existing;\n\n const registry = new DevelopmentAppModuleRegistry();\n container.set(\"development.appModules\", registry);\n return registry;\n}\n"],"mappings":";;;;;;;;;AAYA,SAAS,aAAa,cAA8B;CAClD,OAAO,aAAa,QAAQ,OAAO,GAAG,CAAC,CAAC,YAAY;AACtD;;AAGA,IAAa,+BAAb,MAA2E;;iCAC9C,IAAI,IAAuC;mCACzC,IAAI,IAAgD;;CAEjF,AAAO,IAAI,cAA6D;EACtE,OAAO,KAAK,QAAQ,IAAI,aAAa,YAAY,CAAC;CACpD;CAEA,AAAO,UAAU,UAAkE;EACjF,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;;;;;CAMA,AAAO,KAAK,cAA4B;EACtC,MAAM,MAAM,aAAa,YAAY;EACrC,MAAM,QAAmC;GACvC,KAAK,cAAc,YAAY,CAAC,CAAC;GACjC,aAAa,KAAK,QAAQ,IAAI,GAAG,CAAC,EAAE,cAAc,KAAK;EACzD;EAEA,KAAK,QAAQ,IAAI,KAAK,KAAK;EAE3B,KAAK,MAAM,YAAY,KAAK,WAC1B,IAAI;GACF,SAAS,KAAK;EAChB,QAAQ,CAER;CAEJ;AACF;AAEA,SAAgB,kCAAgE;CAC9E,MAAM,WAAW,UAAU,OAAO,wBAAwB;CAE1D,IAAI,oBAAoB,8BAA8B,OAAO;CAE7D,MAAM,WAAW,IAAI,6BAA6B;CAClD,UAAU,IAAI,0BAA0B,QAAQ;CAChD,OAAO;AACT"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Path } from "../utils/normalized-path.mjs";
|
|
2
2
|
import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
|
|
3
|
+
import { getDevelopmentAppModuleRegistry } from "./app-module-registry.mjs";
|
|
3
4
|
import { DependencyGraph } from "./dependency-graph.mjs";
|
|
4
5
|
import { devLogDim, devLogSuccess } from "./dev-logger.mjs";
|
|
5
6
|
import "./flags.mjs";
|
|
@@ -57,7 +58,9 @@ var FilesOrchestrator = class {
|
|
|
57
58
|
this.moduleLoader = new ModuleLoader(this.specialFilesCollector);
|
|
58
59
|
this.loaderPort = null;
|
|
59
60
|
this.pendingFlushes = [];
|
|
61
|
+
this.pendingBumpedPaths = [];
|
|
60
62
|
this.isInitialized = false;
|
|
63
|
+
getDevelopmentAppModuleRegistry();
|
|
61
64
|
this.fileOperations = new FileOperations(this.files, this.dependencyGraph, this.manifest, this.specialFilesCollector);
|
|
62
65
|
this.eventHandler = new FileEventHandler(this.fileOperations, this.manifest, this.dependencyGraph, this.files);
|
|
63
66
|
}
|
|
@@ -103,10 +106,12 @@ var FilesOrchestrator = class {
|
|
|
103
106
|
* a fresh `?v=N` URL → Node cache miss → fresh content.
|
|
104
107
|
*/
|
|
105
108
|
bumpVersion(absolutePath) {
|
|
106
|
-
this.loaderPort
|
|
109
|
+
if (!this.loaderPort) return;
|
|
110
|
+
this.loaderPort.postMessage({
|
|
107
111
|
type: "bump",
|
|
108
112
|
absolutePath
|
|
109
113
|
});
|
|
114
|
+
this.pendingBumpedPaths.push(absolutePath);
|
|
110
115
|
}
|
|
111
116
|
/**
|
|
112
117
|
* Wait until the hook worker has processed every pending bump.
|
|
@@ -117,8 +122,14 @@ var FilesOrchestrator = class {
|
|
|
117
122
|
*/
|
|
118
123
|
flushVersionBumps() {
|
|
119
124
|
if (!this.loaderPort) return Promise.resolve();
|
|
125
|
+
const bumpedPaths = this.pendingBumpedPaths;
|
|
126
|
+
this.pendingBumpedPaths = [];
|
|
120
127
|
return new Promise((resolve) => {
|
|
121
|
-
this.pendingFlushes.push(
|
|
128
|
+
this.pendingFlushes.push(() => {
|
|
129
|
+
const appModules = getDevelopmentAppModuleRegistry();
|
|
130
|
+
for (const absolutePath of bumpedPaths) appModules.bump(absolutePath);
|
|
131
|
+
resolve();
|
|
132
|
+
});
|
|
122
133
|
this.loaderPort.postMessage({ type: "sync" });
|
|
123
134
|
});
|
|
124
135
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"files-orchestrator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/files-orchestrator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { init } from \"es-module-lexer\";\nimport { fileURLToPath } from \"node:url\";\nimport type { MessagePort } from \"node:worker_threads\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { DependencyGraph } from \"./dependency-graph\";\nimport { devLogDim, devLogSuccess } from \"./dev-logger\";\nimport { FileEventHandler } from \"./file-event-handler\";\nimport { FileManager } from \"./file-manager\";\nimport { FileOperations } from \"./file-operations\";\nimport { FilesWatcher, createIgnoredMatcher } from \"./files-watcher\";\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\nimport { EslintHealthChecker } from \"./health-checker/checkers/eslint-health-checker\";\nimport { TypescriptHealthChecker } from \"./health-checker/checkers/typescript-health-checker\";\nimport type { FileHealthCheckerContract } from \"./health-checker/file-health-checker.contract\";\nimport { FilesHealthcareManager } from \"./health-checker/files-healthcare.manager\";\nimport { buildTranspileInit } from \"./loader/build-transpile-init.js\";\nimport { registerLoader } from \"./loader/register-loader.js\";\nimport { ManifestManager } from \"./manifest-manager\";\nimport { ModuleLoader } from \"./module-loader\";\nimport { packageJsonManager } from \"./package-json-manager\";\nimport { Path } from \"../utils/normalized-path\";\nimport { SpecialFilesCollector } from \"./special-files-collector\";\nimport { tsconfigManager } from \"./tsconfig-manager\";\nimport { ensureWarlockDirectory, getFilesFromDirectory } from \"./utils\";\n\n/**\n * Register a cleanup callback that fires before the current module is\n * unloaded by HMR. Stack-inspects the caller so user code doesn't need to\n * thread the FileManager through.\n */\nexport function onCleanup(callback: () => any) {\n if (globalThis.__currentModuleFile) {\n globalThis.__currentModuleFile.addCleanup(callback);\n return;\n }\n\n const stack = new Error().stack;\n const callerLine = stack?.split(\"\\n\")[2];\n const match = callerLine?.match(/\\((.+?):\\d+:\\d+\\)/) || callerLine?.match(/at (.+?):\\d+:\\d+/);\n const rawCaller = match?.[1];\n\n // Loaded modules report `file:///…?v=N`; turn that back into a plain path.\n const callerFile = rawCaller?.startsWith(\"file://\")\n ? fileURLToPath(rawCaller.replace(/\\?.*$/, \"\"))\n : rawCaller;\n\n if (!callerFile) return;\n const fileManager = filesOrchestrator.files.get(Path.toRelative(callerFile));\n fileManager?.addCleanup(callback);\n}\n\n/**\n * Top-level coordinator for the dev server's file system.\n *\n * Owns: file discovery, the dependency graph, the manifest, the special-files\n * index, the file watcher, and the lifecycle of the ESM loader hook (which\n * provides cache-busting via `?v=N` version tokens).\n */\nexport class FilesOrchestrator {\n public readonly filesWatcher = new FilesWatcher();\n public readonly files = new Map<string, FileManager>();\n private readonly manifest = new ManifestManager(this.files);\n private readonly dependencyGraph = new DependencyGraph();\n private readonly healthCheckerManager = new FilesHealthcareManager(this.files);\n public readonly specialFilesCollector = new SpecialFilesCollector();\n public readonly moduleLoader = new ModuleLoader(this.specialFilesCollector);\n public readonly fileOperations: FileOperations;\n private readonly eventHandler: FileEventHandler;\n\n /** Main-thread end of the MessageChannel to the loader hook worker. */\n private loaderPort: MessagePort | null = null;\n\n /** Resolve callbacks for pending `flushVersionBumps()` calls. */\n private readonly pendingFlushes: Array<() => void> = [];\n\n public isInitialized = false;\n\n public constructor() {\n this.fileOperations = new FileOperations(\n this.files,\n this.dependencyGraph,\n this.manifest,\n this.specialFilesCollector,\n );\n\n this.eventHandler = new FileEventHandler(\n this.fileOperations,\n this.manifest,\n this.dependencyGraph,\n this.files,\n );\n }\n\n public async add(relativePath: string): Promise<FileManager> {\n return this.fileOperations.addFile(relativePath);\n }\n\n public async load<T>(relativePath: string, type = \"other\") {\n // Guarantee the ESM loader hook is registered before we import anything.\n // `load()` is the dynamic-import entrypoint, so it is the one place that\n // must satisfy `init()`'s documented precondition (\"Must be called before\n // any user src/ module is dynamically imported\") on its own — it cannot\n // assume a caller ran `init()` first.\n //\n // The CLI command-resolution path proves why: `cliCommandsLoader.load()`\n // imports a project command module during command *lookup* (before the\n // command's own `execute()` runs), whereas `loadPreloaders()` only calls\n // `init()` from *inside* `execute()`. So a `warlock <command>` whose\n // command file imports an `app/*` alias or a `.ts` sibling was imported\n // with no hook registered and died on `ERR_MODULE_NOT_FOUND` (f9d8f99f).\n //\n // `init()` is idempotent (guarded by `isInitialized`), so this is a no-op\n // on the dev-server path, which already calls it explicitly at startup.\n await this.init();\n\n const fileManager = await this.add(relativePath);\n return this.moduleLoader.loadModule<T>(fileManager, fileManager.type || type);\n }\n\n public getDependencyGraph(): DependencyGraph {\n return this.dependencyGraph;\n }\n\n public getInvalidationChain(file: string): string[] {\n return this.dependencyGraph.getInvalidationChain(file);\n }\n\n public getFiles(): Map<string, FileManager> {\n return this.files;\n }\n\n public getHealthCheckerManager(): FilesHealthcareManager {\n return this.healthCheckerManager;\n }\n\n /**\n * Initialise managers and register the ESM loader hook. Must be called\n * before any user `src/` module is dynamically imported.\n */\n public async init() {\n if (this.isInitialized) return;\n this.isInitialized = true;\n\n await init;\n await Promise.all([tsconfigManager.init(), packageJsonManager.init()]);\n\n // The loader hook writes itself into .warlock/, so ensure the dir exists.\n await ensureWarlockDirectory();\n\n const devServerConfig = await warlockConfigManager.lazyGet(\"devServer\");\n const transpileInit = buildTranspileInit(\n tsconfigManager.tsconfig?.compilerOptions,\n devServerConfig?.transpileCacheDebug === true,\n );\n\n this.loaderPort = await registerLoader(transpileInit);\n\n this.loaderPort.on(\"message\", (msg: { type: string }) => {\n if (msg.type === \"sync-ack\") {\n this.pendingFlushes.shift()?.();\n }\n });\n }\n\n /**\n * Tell the hook worker a file changed. The next `import()` of it will get\n * a fresh `?v=N` URL → Node cache miss → fresh content.\n */\n public bumpVersion(absolutePath: string): void {\n this.loaderPort?.postMessage({ type: \"bump\", absolutePath });\n }\n\n /**\n * Wait until the hook worker has processed every pending bump.\n *\n * `postMessage` is async — without this, a follow-up `import()` may\n * resolve before the worker increments the counter and Node will return\n * the cached old module.\n */\n public flushVersionBumps(): Promise<void> {\n if (!this.loaderPort) return Promise.resolve();\n\n return new Promise<void>((resolve) => {\n this.pendingFlushes.push(resolve);\n this.loaderPort!.postMessage({ type: \"sync\" });\n });\n }\n\n /**\n * Discover files on disk, reconcile against the manifest, build the dep\n * graph, and persist the new manifest. Idempotent.\n */\n public async initializeAll() {\n const [filesInFilesystem, manifestExists] = await Promise.all([\n this.getAllFilesFromFilesystem(),\n this.manifest.init(),\n ]);\n\n if (!manifestExists) {\n await this.processFiles(filesInFilesystem);\n } else {\n await this.reconcileFiles(filesInFilesystem);\n }\n\n this.dependencyGraph.build(this.files);\n this.fileOperations.updateFileDependents();\n this.fileOperations.syncFilesToManifest();\n await this.manifest.save();\n }\n\n public async checkHealth(files: { added: string[]; changed: string[]; deleted: string[] }) {\n const filesToCheck = [...files.added, ...files.changed]\n .map((file) => this.files.get(Path.toRelative(file)))\n .filter((file): file is FileManager => !!file);\n\n const filesToDelete = files.deleted\n .map((file) => this.files.get(Path.toRelative(file)))\n .filter((file): file is FileManager => !!file);\n\n await this.healthCheckerManager.onFileChanges(filesToCheck);\n this.healthCheckerManager.removeFiles(filesToDelete);\n this.healthCheckerManager.checkFiles(filesToCheck);\n }\n\n public async startCheckingHealth(healthCheckers?: FileHealthCheckerContract[]): Promise<void> {\n devLogDim(\"Started File Health Checks in the background.\");\n\n const checkers = healthCheckers ?? [new TypescriptHealthChecker(), new EslintHealthChecker()];\n await this.healthCheckerManager.setHealthCheckers(checkers).initialize();\n await this.healthCheckerManager.validateAllFiles();\n }\n\n /**\n * Glob the src directory, returning relative paths.\n */\n public async getAllFilesFromFilesystem(): Promise<string[]> {\n const absolutePaths = await getFilesFromDirectory();\n return absolutePaths.map((absPath) => Path.toRelative(absPath));\n }\n\n /**\n * Process every file from scratch — used when no manifest exists.\n */\n private async processFiles(filePaths: string[]) {\n devLogDim(`processing ${filePaths.length} files...`);\n await runInBatches(filePaths, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\n const fileManager = new FileManager(\n Path.toAbsolute(relativePath),\n this.files,\n this.fileOperations,\n );\n this.files.set(relativePath, fileManager);\n await fileManager.process();\n });\n devLogSuccess(`processed ${filePaths.length} files`);\n }\n\n private async reconcileFiles(filesInFilesystem: string[]) {\n const filesInManifest = new Set(this.manifest.getAllFilePaths());\n const filesInFilesystemSet = new Set(filesInFilesystem);\n\n const newFiles = filesInFilesystem.filter((f) => !filesInManifest.has(f));\n const deletedFiles = Array.from(filesInManifest).filter((f) => !filesInFilesystemSet.has(f));\n const existingFiles = filesInFilesystem.filter((f) => filesInManifest.has(f));\n\n if (newFiles.length > 0 || deletedFiles.length > 0) {\n devLogDim(\n `reconciling: ${colors.green(newFiles.length)} new, ${colors.red(deletedFiles.length)} deleted, ${colors.blue(existingFiles.length)} existing`,\n );\n }\n\n await this.processFiles(newFiles);\n\n for (const relativePath of deletedFiles) {\n this.manifest.removeFile(relativePath);\n this.files.delete(relativePath);\n }\n\n await runInBatches(existingFiles, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\n const fileManager = new FileManager(\n Path.toAbsolute(relativePath),\n this.files,\n this.fileOperations,\n );\n this.files.set(relativePath, fileManager);\n await fileManager.init(this.manifest.getFile(relativePath));\n });\n }\n\n public async watchFiles() {\n devLogSuccess(\"watching for file changes (not serving yet)\");\n\n this.filesWatcher.onFileChange((p, settleMs) => this.eventHandler.handleFileChange(p, settleMs));\n this.filesWatcher.onFileAdd((p, settleMs) => this.eventHandler.handleFileAdd(p, settleMs));\n this.filesWatcher.onFileDelete((p, settleMs) => this.eventHandler.handleFileDelete(p, settleMs));\n\n const watchConfig = warlockConfigManager.get(\"devServer\")?.watch;\n if (watchConfig?.include?.length) {\n this.eventHandler.setIncludeMatcher(createIgnoredMatcher(watchConfig.include));\n }\n\n await this.filesWatcher.watch(watchConfig);\n }\n}\n\nasync function runInBatches<T>(\n items: T[],\n size: number,\n fn: (item: T) => Promise<unknown>,\n): Promise<void> {\n if (items.length === 0) return;\n for (let i = 0; i < items.length; i += size) {\n await Promise.all(items.slice(i, i + size).map(fn));\n }\n}\n\nexport const filesOrchestrator = new FilesOrchestrator();\n"],"mappings":";;;;;;;;;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MAAM,WAAW,GAAG;CACxB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MACrC,MAAM,QAAQ,IAAI,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAEtD;AAEA,MAAa,oBAAoB,IAAI,kBAAkB"}
|
|
1
|
+
{"version":3,"file":"files-orchestrator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/files-orchestrator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { init } from \"es-module-lexer\";\nimport { fileURLToPath } from \"node:url\";\nimport type { MessagePort } from \"node:worker_threads\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { getDevelopmentAppModuleRegistry } from \"./app-module-registry\";\nimport { DependencyGraph } from \"./dependency-graph\";\nimport { devLogDim, devLogSuccess } from \"./dev-logger\";\nimport { FileEventHandler } from \"./file-event-handler\";\nimport { FileManager } from \"./file-manager\";\nimport { FileOperations } from \"./file-operations\";\nimport { FilesWatcher, createIgnoredMatcher } from \"./files-watcher\";\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\nimport { EslintHealthChecker } from \"./health-checker/checkers/eslint-health-checker\";\nimport { TypescriptHealthChecker } from \"./health-checker/checkers/typescript-health-checker\";\nimport type { FileHealthCheckerContract } from \"./health-checker/file-health-checker.contract\";\nimport { FilesHealthcareManager } from \"./health-checker/files-healthcare.manager\";\nimport { buildTranspileInit } from \"./loader/build-transpile-init.js\";\nimport { registerLoader } from \"./loader/register-loader.js\";\nimport { ManifestManager } from \"./manifest-manager\";\nimport { ModuleLoader } from \"./module-loader\";\nimport { packageJsonManager } from \"./package-json-manager\";\nimport { Path } from \"../utils/normalized-path\";\nimport { SpecialFilesCollector } from \"./special-files-collector\";\nimport { tsconfigManager } from \"./tsconfig-manager\";\nimport { ensureWarlockDirectory, getFilesFromDirectory } from \"./utils\";\n\n/**\n * Register a cleanup callback that fires before the current module is\n * unloaded by HMR. Stack-inspects the caller so user code doesn't need to\n * thread the FileManager through.\n */\nexport function onCleanup(callback: () => any) {\n if (globalThis.__currentModuleFile) {\n globalThis.__currentModuleFile.addCleanup(callback);\n return;\n }\n\n const stack = new Error().stack;\n const callerLine = stack?.split(\"\\n\")[2];\n const match = callerLine?.match(/\\((.+?):\\d+:\\d+\\)/) || callerLine?.match(/at (.+?):\\d+:\\d+/);\n const rawCaller = match?.[1];\n\n // Loaded modules report `file:///…?v=N`; turn that back into a plain path.\n const callerFile = rawCaller?.startsWith(\"file://\")\n ? fileURLToPath(rawCaller.replace(/\\?.*$/, \"\"))\n : rawCaller;\n\n if (!callerFile) return;\n const fileManager = filesOrchestrator.files.get(Path.toRelative(callerFile));\n fileManager?.addCleanup(callback);\n}\n\n/**\n * Top-level coordinator for the dev server's file system.\n *\n * Owns: file discovery, the dependency graph, the manifest, the special-files\n * index, the file watcher, and the lifecycle of the ESM loader hook (which\n * provides cache-busting via `?v=N` version tokens).\n */\nexport class FilesOrchestrator {\n public readonly filesWatcher = new FilesWatcher();\n public readonly files = new Map<string, FileManager>();\n private readonly manifest = new ManifestManager(this.files);\n private readonly dependencyGraph = new DependencyGraph();\n private readonly healthCheckerManager = new FilesHealthcareManager(this.files);\n public readonly specialFilesCollector = new SpecialFilesCollector();\n public readonly moduleLoader = new ModuleLoader(this.specialFilesCollector);\n public readonly fileOperations: FileOperations;\n private readonly eventHandler: FileEventHandler;\n\n /** Main-thread end of the MessageChannel to the loader hook worker. */\n private loaderPort: MessagePort | null = null;\n\n /** Resolve callbacks for pending `flushVersionBumps()` calls. */\n private readonly pendingFlushes: Array<() => void> = [];\n\n /**\n * Files bumped since the last `flushVersionBumps()`. They are published to\n * the development app-module carrier only once the hook thread acknowledged\n * the bump, so a subscriber that imports the published URL cannot get the\n * previous instance.\n */\n private pendingBumpedPaths: string[] = [];\n\n public isInitialized = false;\n\n public constructor() {\n // Web creates its Vite bridge after this orchestrator exists; create the\n // carrier now so it can subscribe before the first bump happens.\n getDevelopmentAppModuleRegistry();\n\n this.fileOperations = new FileOperations(\n this.files,\n this.dependencyGraph,\n this.manifest,\n this.specialFilesCollector,\n );\n\n this.eventHandler = new FileEventHandler(\n this.fileOperations,\n this.manifest,\n this.dependencyGraph,\n this.files,\n );\n }\n\n public async add(relativePath: string): Promise<FileManager> {\n return this.fileOperations.addFile(relativePath);\n }\n\n public async load<T>(relativePath: string, type = \"other\") {\n // Guarantee the ESM loader hook is registered before we import anything.\n // `load()` is the dynamic-import entrypoint, so it is the one place that\n // must satisfy `init()`'s documented precondition (\"Must be called before\n // any user src/ module is dynamically imported\") on its own — it cannot\n // assume a caller ran `init()` first.\n //\n // The CLI command-resolution path proves why: `cliCommandsLoader.load()`\n // imports a project command module during command *lookup* (before the\n // command's own `execute()` runs), whereas `loadPreloaders()` only calls\n // `init()` from *inside* `execute()`. So a `warlock <command>` whose\n // command file imports an `app/*` alias or a `.ts` sibling was imported\n // with no hook registered and died on `ERR_MODULE_NOT_FOUND` (f9d8f99f).\n //\n // `init()` is idempotent (guarded by `isInitialized`), so this is a no-op\n // on the dev-server path, which already calls it explicitly at startup.\n await this.init();\n\n const fileManager = await this.add(relativePath);\n return this.moduleLoader.loadModule<T>(fileManager, fileManager.type || type);\n }\n\n public getDependencyGraph(): DependencyGraph {\n return this.dependencyGraph;\n }\n\n public getInvalidationChain(file: string): string[] {\n return this.dependencyGraph.getInvalidationChain(file);\n }\n\n public getFiles(): Map<string, FileManager> {\n return this.files;\n }\n\n public getHealthCheckerManager(): FilesHealthcareManager {\n return this.healthCheckerManager;\n }\n\n /**\n * Initialise managers and register the ESM loader hook. Must be called\n * before any user `src/` module is dynamically imported.\n */\n public async init() {\n if (this.isInitialized) return;\n this.isInitialized = true;\n\n await init;\n await Promise.all([tsconfigManager.init(), packageJsonManager.init()]);\n\n // The loader hook writes itself into .warlock/, so ensure the dir exists.\n await ensureWarlockDirectory();\n\n const devServerConfig = await warlockConfigManager.lazyGet(\"devServer\");\n const transpileInit = buildTranspileInit(\n tsconfigManager.tsconfig?.compilerOptions,\n devServerConfig?.transpileCacheDebug === true,\n );\n\n this.loaderPort = await registerLoader(transpileInit);\n\n this.loaderPort.on(\"message\", (msg: { type: string }) => {\n if (msg.type === \"sync-ack\") {\n this.pendingFlushes.shift()?.();\n }\n });\n }\n\n /**\n * Tell the hook worker a file changed. The next `import()` of it will get\n * a fresh `?v=N` URL → Node cache miss → fresh content.\n */\n public bumpVersion(absolutePath: string): void {\n if (!this.loaderPort) return;\n\n this.loaderPort.postMessage({ type: \"bump\", absolutePath });\n this.pendingBumpedPaths.push(absolutePath);\n }\n\n /**\n * Wait until the hook worker has processed every pending bump.\n *\n * `postMessage` is async — without this, a follow-up `import()` may\n * resolve before the worker increments the counter and Node will return\n * the cached old module.\n */\n public flushVersionBumps(): Promise<void> {\n if (!this.loaderPort) return Promise.resolve();\n\n // Everything posted before this `sync` message is processed by the hook\n // thread before it answers, so exactly this batch is safe to publish on ack.\n const bumpedPaths = this.pendingBumpedPaths;\n this.pendingBumpedPaths = [];\n\n return new Promise<void>((resolve) => {\n this.pendingFlushes.push(() => {\n const appModules = getDevelopmentAppModuleRegistry();\n\n for (const absolutePath of bumpedPaths) appModules.bump(absolutePath);\n\n resolve();\n });\n this.loaderPort!.postMessage({ type: \"sync\" });\n });\n }\n\n /**\n * Discover files on disk, reconcile against the manifest, build the dep\n * graph, and persist the new manifest. Idempotent.\n */\n public async initializeAll() {\n const [filesInFilesystem, manifestExists] = await Promise.all([\n this.getAllFilesFromFilesystem(),\n this.manifest.init(),\n ]);\n\n if (!manifestExists) {\n await this.processFiles(filesInFilesystem);\n } else {\n await this.reconcileFiles(filesInFilesystem);\n }\n\n this.dependencyGraph.build(this.files);\n this.fileOperations.updateFileDependents();\n this.fileOperations.syncFilesToManifest();\n await this.manifest.save();\n }\n\n public async checkHealth(files: { added: string[]; changed: string[]; deleted: string[] }) {\n const filesToCheck = [...files.added, ...files.changed]\n .map((file) => this.files.get(Path.toRelative(file)))\n .filter((file): file is FileManager => !!file);\n\n const filesToDelete = files.deleted\n .map((file) => this.files.get(Path.toRelative(file)))\n .filter((file): file is FileManager => !!file);\n\n await this.healthCheckerManager.onFileChanges(filesToCheck);\n this.healthCheckerManager.removeFiles(filesToDelete);\n this.healthCheckerManager.checkFiles(filesToCheck);\n }\n\n public async startCheckingHealth(healthCheckers?: FileHealthCheckerContract[]): Promise<void> {\n devLogDim(\"Started File Health Checks in the background.\");\n\n const checkers = healthCheckers ?? [new TypescriptHealthChecker(), new EslintHealthChecker()];\n await this.healthCheckerManager.setHealthCheckers(checkers).initialize();\n await this.healthCheckerManager.validateAllFiles();\n }\n\n /**\n * Glob the src directory, returning relative paths.\n */\n public async getAllFilesFromFilesystem(): Promise<string[]> {\n const absolutePaths = await getFilesFromDirectory();\n return absolutePaths.map((absPath) => Path.toRelative(absPath));\n }\n\n /**\n * Process every file from scratch — used when no manifest exists.\n */\n private async processFiles(filePaths: string[]) {\n devLogDim(`processing ${filePaths.length} files...`);\n await runInBatches(filePaths, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\n const fileManager = new FileManager(\n Path.toAbsolute(relativePath),\n this.files,\n this.fileOperations,\n );\n this.files.set(relativePath, fileManager);\n await fileManager.process();\n });\n devLogSuccess(`processed ${filePaths.length} files`);\n }\n\n private async reconcileFiles(filesInFilesystem: string[]) {\n const filesInManifest = new Set(this.manifest.getAllFilePaths());\n const filesInFilesystemSet = new Set(filesInFilesystem);\n\n const newFiles = filesInFilesystem.filter((f) => !filesInManifest.has(f));\n const deletedFiles = Array.from(filesInManifest).filter((f) => !filesInFilesystemSet.has(f));\n const existingFiles = filesInFilesystem.filter((f) => filesInManifest.has(f));\n\n if (newFiles.length > 0 || deletedFiles.length > 0) {\n devLogDim(\n `reconciling: ${colors.green(newFiles.length)} new, ${colors.red(deletedFiles.length)} deleted, ${colors.blue(existingFiles.length)} existing`,\n );\n }\n\n await this.processFiles(newFiles);\n\n for (const relativePath of deletedFiles) {\n this.manifest.removeFile(relativePath);\n this.files.delete(relativePath);\n }\n\n await runInBatches(existingFiles, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\n const fileManager = new FileManager(\n Path.toAbsolute(relativePath),\n this.files,\n this.fileOperations,\n );\n this.files.set(relativePath, fileManager);\n await fileManager.init(this.manifest.getFile(relativePath));\n });\n }\n\n public async watchFiles() {\n devLogSuccess(\"watching for file changes (not serving yet)\");\n\n this.filesWatcher.onFileChange((p, settleMs) => this.eventHandler.handleFileChange(p, settleMs));\n this.filesWatcher.onFileAdd((p, settleMs) => this.eventHandler.handleFileAdd(p, settleMs));\n this.filesWatcher.onFileDelete((p, settleMs) => this.eventHandler.handleFileDelete(p, settleMs));\n\n const watchConfig = warlockConfigManager.get(\"devServer\")?.watch;\n if (watchConfig?.include?.length) {\n this.eventHandler.setIncludeMatcher(createIgnoredMatcher(watchConfig.include));\n }\n\n await this.filesWatcher.watch(watchConfig);\n }\n}\n\nasync function runInBatches<T>(\n items: T[],\n size: number,\n fn: (item: T) => Promise<unknown>,\n): Promise<void> {\n if (items.length === 0) return;\n for (let i = 0; i < items.length; i += size) {\n await Promise.all(items.slice(i, i + size).map(fn));\n }\n}\n\nexport const filesOrchestrator = new FilesOrchestrator();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,UAAU,UAAqB;CAC7C,IAAI,WAAW,qBAAqB;EAClC,WAAW,oBAAoB,WAAW,QAAQ;EAClD;CACF;CAGA,MAAM,8BADQ,IAAI,MAAM,EAAC,CAAC,OACA,MAAM,IAAI,CAAC,CAAC;CAEtC,MAAM,aADQ,YAAY,MAAM,mBAAmB,KAAK,YAAY,MAAM,kBAAkB,EACrE,GAAG;CAG1B,MAAM,aAAa,WAAW,WAAW,SAAS,IAC9C,cAAc,UAAU,QAAQ,SAAS,EAAE,CAAC,IAC5C;CAEJ,IAAI,CAAC,YAAY;CAEjB,AADoB,kBAAkB,MAAM,IAAI,KAAK,WAAW,UAAU,CAChE,CAAC,EAAE,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1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;AA8CA;;;iBAAgB,kBAAA,CACd,OAAA,EAAS,OAAA,OACT,QAAA,EAAU,QAAA,GACT,OAAA,CAAQ,gBAAA;;;;
|
|
1
|
+
{"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;AA8CA;;;iBAAgB,kBAAA,CACd,OAAA,EAAS,OAAA,OACT,QAAA,EAAU,QAAA,GACT,OAAA,CAAQ,gBAAA;;;;iBAqNK,CAAA,CAAE,OAAA,UAAiB,YAAA,GAAe,MAAM"}
|
|
@@ -69,12 +69,38 @@ function createRequestStore(request, response) {
|
|
|
69
69
|
request.trigger("executedAction", request.route);
|
|
70
70
|
return output;
|
|
71
71
|
} catch (error) {
|
|
72
|
-
|
|
72
|
+
logRequestError(error, request);
|
|
73
73
|
return handleRequestError(error, response, request);
|
|
74
74
|
}
|
|
75
75
|
});
|
|
76
76
|
}
|
|
77
77
|
/**
|
|
78
|
+
* The HTTP status an error will be answered with, or `undefined` when it is not
|
|
79
|
+
* one of the known HTTP-answerable shapes (those fall through to the opaque 500).
|
|
80
|
+
*
|
|
81
|
+
* Single source for `handleRequestError` and the request logger, so the rule
|
|
82
|
+
* that decides the response status is the same rule that decides the log level.
|
|
83
|
+
* @internal
|
|
84
|
+
*/
|
|
85
|
+
function resolveRequestErrorStatus(error) {
|
|
86
|
+
if (error instanceof HttpError) return error.status;
|
|
87
|
+
if (error instanceof DatabaseWriterValidationError) return config.get("http.modelValidationErrorStatus", 500);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Log a request error at the right severity. An error answered with a 4xx is an
|
|
91
|
+
* expected client error (a thrown 404/409/422): one `warn` line, no stack.
|
|
92
|
+
* Everything else (5xx, unknown errors) keeps the error-level entry with its stack.
|
|
93
|
+
* @internal
|
|
94
|
+
*/
|
|
95
|
+
function logRequestError(error, request) {
|
|
96
|
+
const status = resolveRequestErrorStatus(error);
|
|
97
|
+
if (status !== void 0 && status < 500 && error instanceof Error) {
|
|
98
|
+
request.log(`${error.name}: ${error.message} (${status})`, "warn");
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
request.log(error, "error");
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
78
104
|
* Unconditional floor for an unhandled request error (canon 8d3c13a8): route it
|
|
79
105
|
* through the logger, and when no logger channel is configured (nothing would
|
|
80
106
|
* record it) fall back to `console.error` so the only copy is never lost.
|
|
@@ -98,11 +124,11 @@ function handleRequestError(error, response, request) {
|
|
|
98
124
|
return response.setStatusCode(error.status).send(payload);
|
|
99
125
|
}
|
|
100
126
|
if (error instanceof DatabaseWriterValidationError) {
|
|
101
|
-
|
|
127
|
+
const status = resolveRequestErrorStatus(error);
|
|
128
|
+
if (status >= 500) log.error("http", "model-write-validation-error", error, {
|
|
102
129
|
requestId: request.id,
|
|
103
130
|
errors: error.errors
|
|
104
131
|
});
|
|
105
|
-
const status = config.get("http.modelValidationErrorStatus", 500);
|
|
106
132
|
if (status < 500) return response.setStatusCode(status).send({ errors: error.errors });
|
|
107
133
|
return response.setStatusCode(status).send({ error: "Internal server error." });
|
|
108
134
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-request-context.mjs","names":["requestContextInstance"],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"sourcesContent":["/**\n * Request Context Middleware\n *\n * Creates a unified context for each request using the ContextManager.\n * All framework contexts (request, storage, database) are available throughout the request lifecycle.\n */\nimport { trans } from \"@mongez/localization\";\nimport { type GenericObject } from \"@mongez/reinforcements\";\nimport { DatabaseWriterValidationError } from \"@warlock.js/cascade\";\nimport { contextManager } from \"@warlock.js/context\";\nimport { log } from \"@warlock.js/logger\";\nimport config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\nimport { runDefaultCsrfGuard } from \"../csrf-default-guard\";\nimport { HttpError } from \"../errors\";\nimport { type Request } from \"../request\";\nimport { type Response } from \"../response\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../tracing\";\nimport { type ReturnedResponse } from \"./../types\";\n\n// Contexts are now registered in core/context/init-contexts.ts via initializeContexts()\n\n/**\n * Echo `request.id` back as a response header so the FE / proxies / log\n * aggregators can correlate by the same value the server logs against.\n *\n * Reads the header name from `http.requestId.header` (default `X-Request-Id`).\n * Skip when `http.requestId.enabled` is explicitly false.\n */\nfunction stampRequestIdHeader(request: Request, response: Response) {\n const requestIdConfig = config.get(\"http.requestId\", {} as Record<string, any>);\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = requestIdConfig.header || \"X-Request-Id\";\n\n response.header(headerName, request.id);\n}\n\n/**\n * Create request store and execute middleware + handler\n *\n * Runs all registered contexts together using ContextManager.\n */\nexport function createRequestStore(\n request: Request<any>,\n response: Response,\n): Promise<ReturnedResponse> {\n stampRequestIdHeader(request, response);\n\n // Stamped this early — before any middleware or handler runs — so the\n // header carries the SAME nonce the web layer later reads off\n // `request.nonce` for its `<script>` tags: `request.nonce` caches on first\n // read, and this is deliberately the first read. A no-op when the app\n // hasn't opted into `http.csp` (see `csp.ts`).\n applyCspHeader(request, response);\n\n // Build all context stores using the immutable API\n // Each context defines its own store initialization via buildStore()\n const httpContextStore = contextManager.buildStores({ request, response });\n\n // Run all contexts together!\n return contextManager.runAll(httpContextStore, async () => {\n try {\n // Default CSRF-Origin guard (SECURITY, card 8a752ab2) — the earliest\n // seam common to every request, BEFORE the route's own middleware\n // (`request.runMiddleware()` below) and before any app handler, so it\n // applies even to a route that never attaches\n // `authMiddleware(\"cookie:*\")`. See `../csrf-default-guard.ts` for the\n // full scope rule and `{ csrf: false }` exemption.\n const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {\n log.error(\n \"http\",\n \"csrf-default-guard\",\n new Error(`Default CSRF Origin guard refused request: ${reason}`),\n );\n });\n\n if (csrfGuardResponse) {\n return csrfGuardResponse as ReturnedResponse;\n }\n\n // Run middleware chain\n const result = await request.runMiddleware();\n\n if (result) {\n return result as ReturnedResponse;\n }\n\n // Execute route handler\n request.trigger(\"executingAction\", request.route);\n\n const handler = request.getHandler();\n\n request.log(\"Executing Handler\", \"info\");\n\n const tracingEnabled = isTracingEnabled();\n const handlerStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await handler({ request, response });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"handler\",\n durationMs: performance.now() - handlerStartedAt,\n });\n }\n\n request.log(\"Handler Executed Successfully\", \"success\");\n\n request.trigger(\"executedAction\", request.route);\n\n return output as ReturnedResponse;\n } catch (error) {\n request.log(error, \"error\");\n return handleRequestError(error, response, request);\n }\n });\n}\n\n/**\n * Unconditional floor for an unhandled request error (canon 8d3c13a8): route it\n * through the logger, and when no logger channel is configured (nothing would\n * record it) fall back to `console.error` so the only copy is never lost.\n * @internal\n */\nfunction reportUnhandledRequestError(error: unknown, request: Request<any>) {\n log.error(\"http\", \"unhandled-request-error\", error, { requestId: request.id });\n\n if (log.channels.length === 0) {\n console.error(`[http] unhandled-request-error (requestId: ${request.id})`, error);\n }\n}\n\n/**\n * Handle request errors\n * @internal\n */\nfunction handleRequestError(\n error: unknown,\n response: Response,\n request: Request<any>,\n): ReturnedResponse {\n // Availability floor, not a cache-policy nit: `handleRequestError` is the\n // single funnel every unhandled error in every Warlock app passes through\n // (`createRequestStore`'s catch above), and none of the branches below set\n // a `Cache-Control` header. Without this, an error response — a 500 as\n // much as a 401/403/404 carrying per-request/-user state — can be stored\n // by a shared cache or CDN and replayed to other requests/users long after\n // the condition that caused it is gone: a cached 500 becomes an outage\n // that outlives its cause; a cached 401/403 becomes a leak across users.\n // Set once, here, before any branch runs — not per branch — because the\n // branches below do not partition by status. `ResourceNotFoundError`,\n // `UnAuthorizedError`, `ForbiddenError`, `BadRequestError` and `ServerError`\n // all extend `HttpError`, so the `HttpError` branch answers for every one of\n // them, and a raw `HttpError` can carry any caller-chosen status, 4xx or 5xx.\n // Gating the floor on the eventual status would mean re-deriving that status\n // per branch — one rule meeting one form while others reach the same output.\n // Applying it once, unconditionally, is both simpler and safer.\n response.header(\"Cache-Control\", \"private, no-store\");\n\n if (error instanceof HttpError) {\n // 5xx HttpErrors (e.g. `ServerError`) are server faults: send them to the\n // logger channels too, tagged with the request id.\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n\n const payload: GenericObject = {\n error: error.message,\n };\n if (error.payload) {\n payload.payload = error.payload;\n }\n\n if (environment() === \"development\") {\n payload.stack = error.stack;\n }\n\n return response.setStatusCode(error.status).send(payload);\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n log.error(\"http\", \"model-write-validation-error\", error, {\n requestId: request.id,\n errors: error.errors,\n });\n\n const status = config.get(\"http.modelValidationErrorStatus\", 500);\n\n // A 4xx status means the app treats this as the client's fault, so the\n // field errors are useful to it; a 5xx stays opaque.\n if (status < 500) {\n return response.setStatusCode(status).send({\n errors: error.errors,\n });\n }\n\n return response.setStatusCode(status).send({\n error: \"Internal server error.\",\n });\n }\n\n // Last resort: the error matched none of the known shapes above, so the\n // client gets a deliberately opaque message. Without this line the error\n // itself is discarded here — no stack, no message, nothing in any log — and\n // an unrecognised failure becomes indistinguishable from a working server\n // returning 500. Never swallow the only copy of an error (`65e476ee`).\n reportUnhandledRequestError(error, request);\n\n return response.serverError({\n error: \"Internal server error.\",\n });\n}\n\n/**\n * Translate a keyword (uses request context for locale)\n */\nexport function t(keyword: string, placeholders?: Record<string, unknown>): string {\n return (\n requestContextInstance.getRequest()?.trans(keyword, placeholders) ||\n trans(keyword, placeholders)\n );\n}\n\n// `fromRequest` was removed in v5. It cached computed values as dynamic\n// properties on the Request instance, which only compiled because of the\n// `[key: string]: any` index signature that v5 deletes (eed20184). Use\n// `requestMemo(key, fn)` from `../context/request-memo` instead — same\n// per-request lifetime, single-flight, and it never touches the Request object.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,qBAAqB,SAAkB,UAAoB;CAClE,MAAM,kBAAkB,OAAO,IAAI,kBAAkB,CAAC,CAAwB;CAE9E,IAAI,gBAAgB,YAAY,OAAO;CAEvC,MAAM,aAAa,gBAAgB,UAAU;CAE7C,SAAS,OAAO,YAAY,QAAQ,EAAE;AACxC;;;;;;AAOA,SAAgB,mBACd,SACA,UAC2B;CAC3B,qBAAqB,SAAS,QAAQ;CAOtC,eAAe,SAAS,QAAQ;CAIhC,MAAM,mBAAmB,eAAe,YAAY;EAAE;EAAS;CAAS,CAAC;CAGzE,OAAO,eAAe,OAAO,kBAAkB,YAAY;EACzD,IAAI;GAOF,MAAM,oBAAoB,MAAM,oBAAoB,SAAS,UAAU,IAAI,WAAW;IACpF,IAAI,MACF,QACA,sCACA,IAAI,MAAM,8CAA8C,QAAQ,CAClE;GACF,CAAC;GAED,IAAI,mBACF,OAAO;GAIT,MAAM,SAAS,MAAM,QAAQ,cAAc;GAE3C,IAAI,QACF,OAAO;GAIT,QAAQ,QAAQ,mBAAmB,QAAQ,KAAK;GAEhD,MAAM,UAAU,QAAQ,WAAW;GAEnC,QAAQ,IAAI,qBAAqB,MAAM;GAEvC,MAAM,iBAAiB,iBAAiB;GACxC,MAAM,mBAAmB,iBAAiB,YAAY,IAAI,IAAI;GAE9D,MAAM,SAAS,MAAM,QAAQ;IAAE;IAAS;GAAS,CAAC;GAElD,IAAI,gBACF,cAAc,oBAAoB,OAAO,GAAG;IAC1C,MAAM;IACN,YAAY,YAAY,IAAI,IAAI;GAClC,CAAC;GAGH,QAAQ,IAAI,iCAAiC,SAAS;GAEtD,QAAQ,QAAQ,kBAAkB,QAAQ,KAAK;GAE/C,OAAO;EACT,SAAS,OAAO;GACd,QAAQ,IAAI,OAAO,OAAO;GAC1B,OAAO,mBAA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.mjs","names":["requestContextInstance"],"sources":["../../../../../../../../core/src/http/middleware/inject-request-context.ts"],"sourcesContent":["/**\n * Request Context Middleware\n *\n * Creates a unified context for each request using the ContextManager.\n * All framework contexts (request, storage, database) are available throughout the request lifecycle.\n */\nimport { trans } from \"@mongez/localization\";\nimport { type GenericObject } from \"@mongez/reinforcements\";\nimport { DatabaseWriterValidationError } from \"@warlock.js/cascade\";\nimport { contextManager } from \"@warlock.js/context\";\nimport { log } from \"@warlock.js/logger\";\nimport config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\nimport { runDefaultCsrfGuard } from \"../csrf-default-guard\";\nimport { HttpError } from \"../errors\";\nimport { type Request } from \"../request\";\nimport { type Response } from \"../response\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../tracing\";\nimport { type ReturnedResponse } from \"./../types\";\n\n// Contexts are now registered in core/context/init-contexts.ts via initializeContexts()\n\n/**\n * Echo `request.id` back as a response header so the FE / proxies / log\n * aggregators can correlate by the same value the server logs against.\n *\n * Reads the header name from `http.requestId.header` (default `X-Request-Id`).\n * Skip when `http.requestId.enabled` is explicitly false.\n */\nfunction stampRequestIdHeader(request: Request, response: Response) {\n const requestIdConfig = config.get(\"http.requestId\", {} as Record<string, any>);\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = requestIdConfig.header || \"X-Request-Id\";\n\n response.header(headerName, request.id);\n}\n\n/**\n * Create request store and execute middleware + handler\n *\n * Runs all registered contexts together using ContextManager.\n */\nexport function createRequestStore(\n request: Request<any>,\n response: Response,\n): Promise<ReturnedResponse> {\n stampRequestIdHeader(request, response);\n\n // Stamped this early — before any middleware or handler runs — so the\n // header carries the SAME nonce the web layer later reads off\n // `request.nonce` for its `<script>` tags: `request.nonce` caches on first\n // read, and this is deliberately the first read. A no-op when the app\n // hasn't opted into `http.csp` (see `csp.ts`).\n applyCspHeader(request, response);\n\n // Build all context stores using the immutable API\n // Each context defines its own store initialization via buildStore()\n const httpContextStore = contextManager.buildStores({ request, response });\n\n // Run all contexts together!\n return contextManager.runAll(httpContextStore, async () => {\n try {\n // Default CSRF-Origin guard (SECURITY, card 8a752ab2) — the earliest\n // seam common to every request, BEFORE the route's own middleware\n // (`request.runMiddleware()` below) and before any app handler, so it\n // applies even to a route that never attaches\n // `authMiddleware(\"cookie:*\")`. See `../csrf-default-guard.ts` for the\n // full scope rule and `{ csrf: false }` exemption.\n const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {\n log.error(\n \"http\",\n \"csrf-default-guard\",\n new Error(`Default CSRF Origin guard refused request: ${reason}`),\n );\n });\n\n if (csrfGuardResponse) {\n return csrfGuardResponse as ReturnedResponse;\n }\n\n // Run middleware chain\n const result = await request.runMiddleware();\n\n if (result) {\n return result as ReturnedResponse;\n }\n\n // Execute route handler\n request.trigger(\"executingAction\", request.route);\n\n const handler = request.getHandler();\n\n request.log(\"Executing Handler\", \"info\");\n\n const tracingEnabled = isTracingEnabled();\n const handlerStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await handler({ request, response });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"handler\",\n durationMs: performance.now() - handlerStartedAt,\n });\n }\n\n request.log(\"Handler Executed Successfully\", \"success\");\n\n request.trigger(\"executedAction\", request.route);\n\n return output as ReturnedResponse;\n } catch (error) {\n logRequestError(error, request);\n return handleRequestError(error, response, request);\n }\n });\n}\n\n/**\n * The HTTP status an error will be answered with, or `undefined` when it is not\n * one of the known HTTP-answerable shapes (those fall through to the opaque 500).\n *\n * Single source for `handleRequestError` and the request logger, so the rule\n * that decides the response status is the same rule that decides the log level.\n * @internal\n */\nfunction resolveRequestErrorStatus(error: unknown): number | undefined {\n if (error instanceof HttpError) {\n return error.status;\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n return config.get(\"http.modelValidationErrorStatus\", 500);\n }\n\n return undefined;\n}\n\n/**\n * Log a request error at the right severity. An error answered with a 4xx is an\n * expected client error (a thrown 404/409/422): one `warn` line, no stack.\n * Everything else (5xx, unknown errors) keeps the error-level entry with its stack.\n * @internal\n */\nfunction logRequestError(error: unknown, request: Request<any>) {\n const status = resolveRequestErrorStatus(error);\n\n if (status !== undefined && status < 500 && error instanceof Error) {\n request.log(`${error.name}: ${error.message} (${status})`, \"warn\");\n\n return;\n }\n\n request.log(error, \"error\");\n}\n\n/**\n * Unconditional floor for an unhandled request error (canon 8d3c13a8): route it\n * through the logger, and when no logger channel is configured (nothing would\n * record it) fall back to `console.error` so the only copy is never lost.\n * @internal\n */\nfunction reportUnhandledRequestError(error: unknown, request: Request<any>) {\n log.error(\"http\", \"unhandled-request-error\", error, { requestId: request.id });\n\n if (log.channels.length === 0) {\n console.error(`[http] unhandled-request-error (requestId: ${request.id})`, error);\n }\n}\n\n/**\n * Handle request errors\n * @internal\n */\nfunction handleRequestError(\n error: unknown,\n response: Response,\n request: Request<any>,\n): ReturnedResponse {\n // Availability floor, not a cache-policy nit: `handleRequestError` is the\n // single funnel every unhandled error in every Warlock app passes through\n // (`createRequestStore`'s catch above), and none of the branches below set\n // a `Cache-Control` header. Without this, an error response — a 500 as\n // much as a 401/403/404 carrying per-request/-user state — can be stored\n // by a shared cache or CDN and replayed to other requests/users long after\n // the condition that caused it is gone: a cached 500 becomes an outage\n // that outlives its cause; a cached 401/403 becomes a leak across users.\n // Set once, here, before any branch runs — not per branch — because the\n // branches below do not partition by status. `ResourceNotFoundError`,\n // `UnAuthorizedError`, `ForbiddenError`, `BadRequestError` and `ServerError`\n // all extend `HttpError`, so the `HttpError` branch answers for every one of\n // them, and a raw `HttpError` can carry any caller-chosen status, 4xx or 5xx.\n // Gating the floor on the eventual status would mean re-deriving that status\n // per branch — one rule meeting one form while others reach the same output.\n // Applying it once, unconditionally, is both simpler and safer.\n response.header(\"Cache-Control\", \"private, no-store\");\n\n if (error instanceof HttpError) {\n // 5xx HttpErrors (e.g. `ServerError`) are server faults: send them to the\n // logger channels too, tagged with the request id.\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n\n const payload: GenericObject = {\n error: error.message,\n };\n if (error.payload) {\n payload.payload = error.payload;\n }\n\n if (environment() === \"development\") {\n payload.stack = error.stack;\n }\n\n return response.setStatusCode(error.status).send(payload);\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n const status = resolveRequestErrorStatus(error) as number;\n\n // A 4xx is an expected client error, already logged as a one-line warn by\n // `logRequestError`; only a 5xx gets the error-level entry with its stack.\n if (status >= 500) {\n log.error(\"http\", \"model-write-validation-error\", error, {\n requestId: request.id,\n errors: error.errors,\n });\n }\n\n // A 4xx status means the app treats this as the client's fault, so the\n // field errors are useful to it; a 5xx stays opaque.\n if (status < 500) {\n return response.setStatusCode(status).send({\n errors: error.errors,\n });\n }\n\n return response.setStatusCode(status).send({\n error: \"Internal server error.\",\n });\n }\n\n // Last resort: the error matched none of the known shapes above, so the\n // client gets a deliberately opaque message. Without this line the error\n // itself is discarded here — no stack, no message, nothing in any log — and\n // an unrecognised failure becomes indistinguishable from a working server\n // returning 500. Never swallow the only copy of an error (`65e476ee`).\n reportUnhandledRequestError(error, request);\n\n return response.serverError({\n error: \"Internal server error.\",\n });\n}\n\n/**\n * Translate a keyword (uses request context for locale)\n */\nexport function t(keyword: string, placeholders?: Record<string, unknown>): string {\n return (\n requestContextInstance.getRequest()?.trans(keyword, placeholders) ||\n trans(keyword, placeholders)\n );\n}\n\n// `fromRequest` was removed in v5. It cached computed values as dynamic\n// properties on the Request instance, which only compiled because of the\n// `[key: string]: any` index signature that v5 deletes (eed20184). Use\n// `requestMemo(key, fn)` from `../context/request-memo` instead — same\n// per-request lifetime, single-flight, and it never touches the Request object.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,qBAAqB,SAAkB,UAAoB;CAClE,MAAM,kBAAkB,OAAO,IAAI,kBAAkB,CAAC,CAAwB;CAE9E,IAAI,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