@warlock.js/core 5.28.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 +13 -0
- 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/index.d.mts +3 -1
- package/esm/index.mjs +2 -1
- 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/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 +22 -3
- 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/router/response-schema-types.mjs +2 -0
- package/esm/router/response-schema-types.mjs.map +1 -1
- package/llms-full.txt +241 -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 +5 -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,19 @@ 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
|
+
|
|
9
22
|
## 5.28.0 - 2026-10-01
|
|
10
23
|
|
|
11
24
|
### Added
|
|
@@ -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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,UAAU,U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,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,WAAW,QAAQ;AAClC;;;;;;;;AASA,IAAa,oBAAb,M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, Serialized, SerializedWire } from "./http/serial
|
|
|
68
68
|
import { LocalizedObject, getLocalized } from "./utils/get-localized.mjs";
|
|
69
69
|
import { ResourceFieldBuilder } from "./resource/resource-field-builder.mjs";
|
|
70
70
|
import { Resource, ResourceConstructor, ResourceContract } from "./resource/resource.mjs";
|
|
71
|
+
import { NULLABLE_RESOURCE, NullableResource, NullableResourceTarget, isNullableResource, nullable } from "./resource/nullable-resource.mjs";
|
|
71
72
|
import { BaseCastOutput, CastOutput, FieldOutput, ResourceArraySchema, ResourceCastType, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, ResponseBodyOutput, ResponseBodyValue, ResponseSchema, ResponseSchemaOutput } from "./resource/types.mjs";
|
|
72
73
|
import { GroupedRoutesOptions, HttpContext, Middleware, MiddlewareResponse, NamedApiRoute, NamedApiRoutesOptions, PartialPick, RequestControllerContract, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestMethod, ResourceMethod, RestfulMiddleware, Route, RouteOptions, RouteResource, RouterGroupCallback, RouterStacks } from "./router/types.mjs";
|
|
73
74
|
import { PositionalHandlerSuspect, clearPositionalHandlerSuspects, describePositionalHandlerSuspect, forgetPositionalHandlerSuspects, inspectHandlerSignature, listPositionalHandlerSuspects, looksLikePositionalHandler, reportPositionalHandlerSuspects } from "./router/positional-handler-diagnostics.mjs";
|
|
@@ -115,6 +116,7 @@ import { SocketConnector } from "./connectors/socket-connector.mjs";
|
|
|
115
116
|
import { StorageConnector } from "./connectors/storage.connector.mjs";
|
|
116
117
|
import { CLICommandAction, CLICommandOption, CLICommandOptions, CLICommandPreload, CLICommandSource, CommandActionData, ResolvedCLICommandOption } from "./commands/types.mjs";
|
|
117
118
|
import { CLICommand, command } from "./commands/cli-command.mjs";
|
|
119
|
+
import { DevelopmentAppModuleEntry, DevelopmentAppModules } from "./container/development-app-modules.mjs";
|
|
118
120
|
import { DevelopmentModelModuleEntry, DevelopmentModelModuleState, DevelopmentModelModules } from "./container/development-model-modules.mjs";
|
|
119
121
|
import { ContainerTypes, container } from "./container/index.mjs";
|
|
120
122
|
import { DatabaseLogModel } from "./database/models/database-log/database-log.mjs";
|
|
@@ -189,7 +191,7 @@ import { WarlockConfigManager, isUnknownTsExtensionError, warlockConfigManager }
|
|
|
189
191
|
import { env } from "@mongez/dotenv";
|
|
190
192
|
import { colors } from "@mongez/copper";
|
|
191
193
|
export * from "@mongez/localization";
|
|
192
|
-
export { $registerUseCase, $unregisterUseCase, APP_ROLES, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppRole, Application, AuthDescriptor, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseCastOutput, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, CastOutput, ChunkCallback, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConfigKey, ConfigKeyRegistry, ConfigName, ConfigRegistry, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, DevelopmentPostmanResult, EncryptionConfigurations, EncryptionPasswordConfigurations, Environment, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FieldOutput, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, HttpReadyReport, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidCspDirectiveError, type IpFilterOptions, ListOptions, LocalDriver, LocalStorageDriverOptions, LocaleDictionaryEntries, LocaleDictionaryError, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, Middleware, MiddlewareResponse, MimeTypes, ModelResourceRegistry, NamedApiRoute, NamedApiRoutesOptions, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, OPENAPI_JSON_SCHEMA_DIALECT, OpenApiBuildResult, OpenApiComponents, OpenApiContext, OpenApiDocument, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, OpenApiRouteInput, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiValidationResponseConfig, POSTMAN_COLLECTION_SCHEMA, PaginationMode, PaginationResult, ParsedLocaleDictionary, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestMethod, RequestTranslator, type ResolvedCLICommandOption, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyOutput, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSchema, ResponseSchemaOutput, ResponseStatus, ResponseStreamController, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SafeFetchOptions, SafeFetchResult, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WarningSink, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetRolesCacheForTests, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
|
|
194
|
+
export { $registerUseCase, $unregisterUseCase, APP_ROLES, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppRole, Application, AuthDescriptor, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseCastOutput, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, CastOutput, ChunkCallback, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConfigKey, ConfigKeyRegistry, ConfigName, ConfigRegistry, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentAppModuleEntry, type DevelopmentAppModules, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, DevelopmentPostmanResult, EncryptionConfigurations, EncryptionPasswordConfigurations, Environment, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FieldOutput, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, HttpReadyReport, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidCspDirectiveError, type IpFilterOptions, ListOptions, LocalDriver, LocalStorageDriverOptions, LocaleDictionaryEntries, LocaleDictionaryError, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, Middleware, MiddlewareResponse, MimeTypes, ModelResourceRegistry, NULLABLE_RESOURCE, NamedApiRoute, NamedApiRoutesOptions, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, NullableResource, NullableResourceTarget, OPENAPI_JSON_SCHEMA_DIALECT, OpenApiBuildResult, OpenApiComponents, OpenApiContext, OpenApiDocument, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, OpenApiRouteInput, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiValidationResponseConfig, POSTMAN_COLLECTION_SCHEMA, PaginationMode, PaginationResult, ParsedLocaleDictionary, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestMethod, RequestTranslator, type ResolvedCLICommandOption, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyOutput, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSchema, ResponseSchemaOutput, ResponseStatus, ResponseStreamController, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SafeFetchOptions, SafeFetchResult, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WarningSink, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isBootSignal, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetRolesCacheForTests, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
|
|
193
195
|
import "./config/types.mjs";
|
|
194
196
|
import "./http/request.mjs";
|
|
195
197
|
import "./http/serialized.mjs";
|
package/esm/index.mjs
CHANGED
|
@@ -153,6 +153,7 @@ import "./localization/index.mjs";
|
|
|
153
153
|
import { exampleFromSchema } from "./openapi/postman/example-from-schema.mjs";
|
|
154
154
|
import { DEFAULT_POSTMAN_BASE_URL, POSTMAN_COLLECTION_SCHEMA, openApiToPostmanCollection } from "./openapi/postman/openapi-to-postman-collection.mjs";
|
|
155
155
|
import { getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, registerDevelopmentOpenApiProvider } from "./openapi/development-openapi-provider.mjs";
|
|
156
|
+
import { NULLABLE_RESOURCE, isNullableResource, nullable } from "./resource/nullable-resource.mjs";
|
|
156
157
|
import { OPENAPI_JSON_SCHEMA_DIALECT, buildOpenApiDocument } from "./openapi/build-openapi-document.mjs";
|
|
157
158
|
import "./openapi/index.mjs";
|
|
158
159
|
import { CascadeQueryBuilder } from "./repositories/adapters/cascade/cascade-query-builder.mjs";
|
|
@@ -183,4 +184,4 @@ import { colors } from "@mongez/copper";
|
|
|
183
184
|
|
|
184
185
|
export * from "@mongez/localization"
|
|
185
186
|
|
|
186
|
-
export { $registerUseCase, $unregisterUseCase, APP_ROLES, AccessConnector, AiConnector, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, BenchmarkProfiler, BenchmarkSnapshots, CLICommand, CacheConnector, CascadeAdapter, CascadeQueryBuilder, CloudDriver, ConfigSpecialHandlers, ConflictError, ConnectorLifecyclePhase, ConnectorPriority, ConnectorsManager, ConsoleChannel, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, ImageVariantsConfigError, InvalidCspDirectiveError, LocalDriver, LocaleDictionaryError, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MimeTypes, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, OPENAPI_JSON_SCHEMA_DIALECT, POSTMAN_COLLECTION_SCHEMA, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteRegistry, Router, S3Driver, ScopedStorage, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageCapabilityError, StorageConnector, StorageError, StorageFile, StorageNotInitializedError, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetRolesCacheForTests, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
|
|
187
|
+
export { $registerUseCase, $unregisterUseCase, APP_ROLES, AccessConnector, AiConnector, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, BenchmarkProfiler, BenchmarkSnapshots, CLICommand, CacheConnector, CascadeAdapter, CascadeQueryBuilder, CloudDriver, ConfigSpecialHandlers, ConflictError, ConnectorLifecyclePhase, ConnectorPriority, ConnectorsManager, ConsoleChannel, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, ImageVariantsConfigError, InvalidCspDirectiveError, LocalDriver, LocaleDictionaryError, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MimeTypes, NULLABLE_RESOURCE, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, OPENAPI_JSON_SCHEMA_DIALECT, POSTMAN_COLLECTION_SCHEMA, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteRegistry, Router, S3Driver, ScopedStorage, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageCapabilityError, StorageConnector, StorageError, StorageFile, StorageNotInitializedError, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isBootSignal, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetRolesCacheForTests, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
|
|
@@ -15,7 +15,12 @@ declare class LocaleDictionaryError extends Error {
|
|
|
15
15
|
declare function parseLocaleDictionary(input: {
|
|
16
16
|
sourceFile: string;
|
|
17
17
|
source: string;
|
|
18
|
-
|
|
18
|
+
/**
|
|
19
|
+
* The group used when the file declares no `$group`. A function is called
|
|
20
|
+
* only in that case, so a namespace that cannot be derived (e.g. from a
|
|
21
|
+
* folder name) never fails a file that names its own `$group`.
|
|
22
|
+
*/
|
|
23
|
+
defaultNamespace: string | (() => string);
|
|
19
24
|
localeCodes?: readonly string[];
|
|
20
25
|
}): ParsedLocaleDictionary;
|
|
21
26
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-locale-dictionary.d.mts","names":[],"sources":["../../../../../../../core/src/localization/parse-locale-dictionary.ts"],"mappings":";KAAY,uBAAA,GAA0B,MAAM,SAAS,MAAA;AAAA,KAEzC,sBAAA;EACV,UAAA;EACA,KAAA;EACA,OAAA,EAAS,uBAAuB;AAAA;AAHlC;AAAA,cAca,qBAAA,SAA8B,KAAK;EAAA,SAE5B,UAAA;EAAA,SACA,GAAA;cADA,UAAA,UACA,GAAA,UAChB,MAAA;AAAA;;
|
|
1
|
+
{"version":3,"file":"parse-locale-dictionary.d.mts","names":[],"sources":["../../../../../../../core/src/localization/parse-locale-dictionary.ts"],"mappings":";KAAY,uBAAA,GAA0B,MAAM,SAAS,MAAA;AAAA,KAEzC,sBAAA;EACV,UAAA;EACA,KAAA;EACA,OAAA,EAAS,uBAAuB;AAAA;AAHlC;AAAA,cAca,qBAAA,SAA8B,KAAK;EAAA,SAE5B,UAAA;EAAA,SACA,GAAA;cADA,UAAA,UACA,GAAA,UAChB,MAAA;AAAA;;iBAsOY,qBAAA,CAAsB,KAAA;EACpC,UAAA;EACA,MAAA;EA5OW;;;;;EAkPX,gBAAA;EACA,WAAA;AAAA,IACE,sBAAsB"}
|
|
@@ -153,6 +153,10 @@ function explicitGroup(sourceFile, value) {
|
|
|
153
153
|
}
|
|
154
154
|
return value;
|
|
155
155
|
}
|
|
156
|
+
function defaultGroup(sourceFile, defaultNamespace) {
|
|
157
|
+
const namespace = typeof defaultNamespace === "function" ? defaultNamespace() : defaultNamespace;
|
|
158
|
+
return namespace === "" ? "" : explicitGroup(sourceFile, namespace);
|
|
159
|
+
}
|
|
156
160
|
function isObject(value) {
|
|
157
161
|
return value instanceof Map;
|
|
158
162
|
}
|
|
@@ -198,7 +202,7 @@ function parseLocaleDictionary(input) {
|
|
|
198
202
|
if (!isObject(parsed)) fail(sourceFile, "$", "root JSON value must be an object");
|
|
199
203
|
const groupValue = parsed.get("$group");
|
|
200
204
|
if (groupValue !== void 0 && typeof groupValue !== "string") fail(sourceFile, "$group", "'$group' must be a string");
|
|
201
|
-
const group = groupValue === void 0 ?
|
|
205
|
+
const group = groupValue === void 0 ? defaultGroup(sourceFile, defaultNamespace) : explicitGroup(sourceFile, groupValue);
|
|
202
206
|
const entries = Object.create(null);
|
|
203
207
|
const rootEntries = new Map(parsed);
|
|
204
208
|
rootEntries.delete("$group");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-locale-dictionary.mjs","names":[],"sources":["../../../../../../../core/src/localization/parse-locale-dictionary.ts"],"sourcesContent":["export type LocaleDictionaryEntries = Record<string, Record<string, string>>;\n\nexport type ParsedLocaleDictionary = {\n sourceFile: string;\n group: string;\n entries: LocaleDictionaryEntries;\n};\n\ntype JsonValue = string | number | boolean | null | JsonObject | JsonValue[];\ntype JsonObject = Map<string, JsonValue>;\n\nconst SEGMENT = /^[A-Za-z_][A-Za-z0-9_-]*$/;\nconst LOCALE_CODE = /^[A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*$/;\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\n/** A source error that always names both the locale file and the offending JSON key. */\nexport class LocaleDictionaryError extends Error {\n public constructor(\n public readonly sourceFile: string,\n public readonly key: string,\n detail: string,\n ) {\n super(`Cannot parse route locales in \"${sourceFile}\" at \"${key}\": ${detail}.`);\n this.name = \"LocaleDictionaryError\";\n }\n}\n\nfunction fail(sourceFile: string, key: string, detail: string): never {\n throw new LocaleDictionaryError(sourceFile, key, detail);\n}\n\n/** A deliberately small JSON parser: unlike JSON.parse, it preserves duplicate property names. */\nclass StrictJsonParser {\n private offset = 0;\n\n public constructor(\n private readonly sourceFile: string,\n private readonly source: string,\n ) {}\n\n public parse(): JsonValue {\n if (this.source.charCodeAt(0) === 0xfeff) this.offset = 1;\n const value = this.value(\"$\");\n this.whitespace();\n if (this.offset !== this.source.length) this.invalid(\"$\", \"unexpected trailing JSON\");\n return value;\n }\n\n private value(key: string): JsonValue {\n this.whitespace();\n const character = this.source[this.offset];\n if (character === \"{\") return this.object(key);\n if (character === \"[\") return this.array(key);\n if (character === '\"') return this.string(key);\n if (this.source.startsWith(\"true\", this.offset)) return this.literal(\"true\", true);\n if (this.source.startsWith(\"false\", this.offset)) return this.literal(\"false\", false);\n if (this.source.startsWith(\"null\", this.offset)) return this.literal(\"null\", null);\n if (character === \"-\" || (character !== undefined && /[0-9]/.test(character)))\n return this.number(key);\n this.invalid(key, \"invalid JSON value\");\n }\n\n private object(key: string): JsonObject {\n this.offset++;\n this.whitespace();\n const object = new Map<string, JsonValue>();\n if (this.source[this.offset] === \"}\") {\n this.offset++;\n return object;\n }\n while (true) {\n this.whitespace();\n if (this.source[this.offset] !== '\"') this.invalid(key, \"object keys must be JSON strings\");\n const property = this.string(key);\n const propertyKey = `${key}.${property}`;\n if (object.has(property)) this.invalid(propertyKey, \"duplicate JSON property\");\n this.whitespace();\n if (this.source[this.offset] !== \":\")\n this.invalid(propertyKey, \"expected ':' after object key\");\n this.offset++;\n object.set(property, this.value(propertyKey));\n this.whitespace();\n const separator = this.source[this.offset];\n if (separator === \"}\") {\n this.offset++;\n return object;\n }\n if (separator !== \",\") this.invalid(key, \"expected ',' or '}' in object\");\n this.offset++;\n }\n }\n\n private array(key: string): JsonValue[] {\n this.offset++;\n this.whitespace();\n const values: JsonValue[] = [];\n if (this.source[this.offset] === \"]\") {\n this.offset++;\n return values;\n }\n while (true) {\n values.push(this.value(key));\n this.whitespace();\n const separator = this.source[this.offset];\n if (separator === \"]\") {\n this.offset++;\n return values;\n }\n if (separator !== \",\") this.invalid(key, \"expected ',' or ']' in array\");\n this.offset++;\n }\n }\n\n private string(key: string): string {\n const start = this.offset++;\n let escaped = false;\n while (this.offset < this.source.length) {\n const character = this.source[this.offset++];\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (character === '\"') {\n try {\n return JSON.parse(this.source.slice(start, this.offset)) as string;\n } catch {\n this.invalid(key, \"invalid JSON string\");\n }\n }\n if (character !== undefined && character.charCodeAt(0) < 0x20)\n this.invalid(key, \"unescaped control character in JSON string\");\n }\n this.invalid(key, \"unterminated JSON string\");\n }\n\n private number(key: string): number {\n const match = /-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;\n match.lastIndex = this.offset;\n const token = match.exec(this.source)?.[0];\n if (token === undefined) this.invalid(key, \"invalid JSON number\");\n this.offset += token.length;\n return Number(token);\n }\n\n private literal<T extends boolean | null>(written: string, value: T): T {\n this.offset += written.length;\n return value;\n }\n\n private whitespace(): void {\n while (this.offset < this.source.length) {\n const character = this.source[this.offset];\n if (character === undefined || !\" \\t\\n\\r\".includes(character)) return;\n this.offset++;\n }\n }\n\n private invalid(key: string, detail: string): never {\n fail(this.sourceFile, key, detail);\n }\n}\n\nfunction assertNamespaceSegment(sourceFile: string, segment: string, key: string): void {\n if (!SEGMENT.test(segment)) fail(sourceFile, key, \"segments must match [A-Za-z_][A-Za-z0-9_-]*\");\n if (FORBIDDEN_SEGMENTS.has(segment)) fail(sourceFile, key, \"segments cannot be reserved\");\n}\n\nfunction assertSegment(sourceFile: string, segment: string, key: string): void {\n if (segment.includes(\".\")) fail(sourceFile, key, \"JSON keys cannot contain '.'\");\n assertNamespaceSegment(sourceFile, segment, key);\n}\n\nfunction explicitGroup(sourceFile: string, value: string): string {\n if (value === \"\") fail(sourceFile, \"$group\", \"'$group' cannot be empty\");\n for (const segment of value.split(\".\")) {\n if (segment === \"\") fail(sourceFile, \"$group\", \"'$group' cannot contain empty segments\");\n assertNamespaceSegment(sourceFile, segment, \"$group\");\n }\n return value;\n}\n\nfunction isObject(value: JsonValue): value is JsonObject {\n return value instanceof Map;\n}\n\nfunction readLeaf(\n sourceFile: string,\n key: string,\n value: JsonObject,\n localeCodes: readonly string[] | undefined,\n): Record<string, string> {\n const locales = localeCodes === undefined ? undefined : new Set(localeCodes);\n const entry: Record<string, string> = Object.create(null) as Record<string, string>;\n for (const [locale, translation] of value) {\n if (!LOCALE_CODE.test(locale)) fail(sourceFile, `${key}.${locale}`, \"invalid locale code\");\n if (typeof translation !== \"string\")\n fail(sourceFile, `${key}.${locale}`, \"locale values must be strings\");\n if (locales !== undefined && !locales.has(locale))\n fail(sourceFile, `${key}.${locale}`, \"unknown locale code\");\n entry[locale] = translation;\n }\n if (localeCodes !== undefined)\n for (const locale of localeCodes)\n if (!(locale in entry)) fail(sourceFile, key, `missing locale code \"${locale}\"`);\n return entry;\n}\n\nfunction collectEntries(\n sourceFile: string,\n object: JsonObject,\n group: string,\n localeCodes: readonly string[] | undefined,\n entries: LocaleDictionaryEntries,\n nested: boolean,\n): void {\n if (nested && object.size === 0) fail(sourceFile, group, \"nested objects cannot be empty\");\n for (const [segment, value] of object) {\n const key = group === \"\" ? segment : `${group}.${segment}`;\n if (segment === \"$group\") fail(sourceFile, key, \"'$group' is only allowed at the root\");\n assertSegment(sourceFile, segment, key);\n if (!isObject(value)) fail(sourceFile, key, \"entries must be locale objects or nested objects\");\n if (value.has(\"$group\"))\n fail(sourceFile, `${key}.$group`, \"'$group' is only allowed at the root\");\n const values = [...value.values()];\n const hasString = values.some((item) => typeof item === \"string\");\n const allObjects = values.every(isObject);\n if (hasString) {\n if (!values.every((item) => typeof item === \"string\"))\n fail(sourceFile, key, \"cannot mix locale values with nested entries\");\n entries[key] = readLeaf(sourceFile, key, value, localeCodes);\n continue;\n }\n if (!allObjects) fail(sourceFile, key, \"cannot mix locale values with nested entries\");\n if (localeCodes !== undefined && [...value.keys()].some((child) => localeCodes.includes(child)))\n fail(sourceFile, key, \"cannot mix locale codes with nested entries\");\n collectEntries(sourceFile, value, key, localeCodes, entries, true);\n }\n}\n\n/** Parses one locale dictionary source without reading the filesystem or loading application code. */\nexport function parseLocaleDictionary(input: {\n sourceFile: string;\n source: string;\n defaultNamespace: string;\n localeCodes?: readonly string[];\n}): ParsedLocaleDictionary {\n const { sourceFile, source, defaultNamespace, localeCodes } = input;\n const parsed = new StrictJsonParser(sourceFile, source).parse();\n if (!isObject(parsed)) fail(sourceFile, \"$\", \"root JSON value must be an object\");\n const groupValue = parsed.get(\"$group\");\n if (groupValue !== undefined && typeof groupValue !== \"string\")\n fail(sourceFile, \"$group\", \"'$group' must be a string\");\n const group =\n groupValue === undefined\n ? defaultNamespace === \"\"\n ? \"\"\n : explicitGroup(sourceFile, defaultNamespace)\n : explicitGroup(sourceFile, groupValue);\n const entries: LocaleDictionaryEntries = Object.create(null) as LocaleDictionaryEntries;\n const rootEntries = new Map(parsed);\n rootEntries.delete(\"$group\");\n collectEntries(sourceFile, rootEntries, group, localeCodes, entries, false);\n return { sourceFile, group, entries };\n}\n"],"mappings":";AAWA,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,qBAAqB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAa,CAAC;;AAG5E,IAAa,wBAAb,cAA2C,MAAM;CAC/C,AAAO,YACL,AAAgB,YAChB,AAAgB,KAChB,QACA;EACA,MAAM,kCAAkC,WAAW,QAAQ,IAAI,KAAK,OAAO,EAAE;EAJ7D;EACA;EAIhB,KAAK,OAAO;CACd;AACF;AAEA,SAAS,KAAK,YAAoB,KAAa,QAAuB;CACpE,MAAM,IAAI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a,OAAO,MAAM,QAAQ;EACxC,IAAI,WAAW;GACb,IAAI,CAAC,OAAO,OAAO,SAAS,OAAO,SAAS,QAAQ,GAClD,KAAK,YAAY,KAAK,8CAA8C;GACtE,QAAQ,OAAO,SAAS,YAAY,KAAK,OAAO,WAAW;GAC3D;EACF;EACA,IAAI,CAAC,YAAY,KAAK,YAAY,KAAK,8CAA8C;EACrF,IAAI,gBAAgB,UAAa,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,UAAU,YAAY,SAAS,KAAK,CAAC,GAC5F,KAAK,YAAY,KAAK,6CAA6C;EACrE,eAAe,YAAY,OAAO,KAAK,aAAa,SAAS,IAAI;CACnE;AACF;;AAGA,SAAgB,sBAAsB,OAKX;CACzB,MAAM,EAAE,YAAY,QAAQ,kBAAkB,gBAAgB;CAC9D,MAAM,SAAS,IAAI,iBAAiB,YAAY,MAAM,CAAC,CAAC,MAAM;CAC9D,IAAI,CAAC,SAAS,MAAM,GAAG,KAAK,YAAY,KAAK,mCAAmC;CAChF,MAAM,aAAa,OAAO,IAAI,QAAQ;CACtC,IAAI,eAAe,UAAa,OAAO,eAAe,UACpD,KAAK,YAAY,UAAU,2BAA2B;CACxD,MAAM,QACJ,eAAe,SACX,qBAAqB,KACnB,KACA,cAAc,YAAY,gBAAgB,IAC5C,cAAc,YAAY,UAAU;CAC1C,MAAM,UAAmC,OAAO,OAAO,IAAI;CAC3D,MAAM,cAAc,IAAI,IAAI,MAAM;CAClC,YAAY,OAAO,QAAQ;CAC3B,eAAe,YAAY,aAAa,OAAO,aAAa,SAAS,KAAK;CAC1E,OAAO;EAAE;EAAY;EAAO;CAAQ;AACtC"}
|
|
1
|
+
{"version":3,"file":"parse-locale-dictionary.mjs","names":[],"sources":["../../../../../../../core/src/localization/parse-locale-dictionary.ts"],"sourcesContent":["export type LocaleDictionaryEntries = Record<string, Record<string, string>>;\n\nexport type ParsedLocaleDictionary = {\n sourceFile: string;\n group: string;\n entries: LocaleDictionaryEntries;\n};\n\ntype JsonValue = string | number | boolean | null | JsonObject | JsonValue[];\ntype JsonObject = Map<string, JsonValue>;\n\nconst SEGMENT = /^[A-Za-z_][A-Za-z0-9_-]*$/;\nconst LOCALE_CODE = /^[A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*$/;\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\n/** A source error that always names both the locale file and the offending JSON key. */\nexport class LocaleDictionaryError extends Error {\n public constructor(\n public readonly sourceFile: string,\n public readonly key: string,\n detail: string,\n ) {\n super(`Cannot parse route locales in \"${sourceFile}\" at \"${key}\": ${detail}.`);\n this.name = \"LocaleDictionaryError\";\n }\n}\n\nfunction fail(sourceFile: string, key: string, detail: string): never {\n throw new LocaleDictionaryError(sourceFile, key, detail);\n}\n\n/** A deliberately small JSON parser: unlike JSON.parse, it preserves duplicate property names. */\nclass StrictJsonParser {\n private offset = 0;\n\n public constructor(\n private readonly sourceFile: string,\n private readonly source: string,\n ) {}\n\n public parse(): JsonValue {\n if (this.source.charCodeAt(0) === 0xfeff) this.offset = 1;\n const value = this.value(\"$\");\n this.whitespace();\n if (this.offset !== this.source.length) this.invalid(\"$\", \"unexpected trailing JSON\");\n return value;\n }\n\n private value(key: string): JsonValue {\n this.whitespace();\n const character = this.source[this.offset];\n if (character === \"{\") return this.object(key);\n if (character === \"[\") return this.array(key);\n if (character === '\"') return this.string(key);\n if (this.source.startsWith(\"true\", this.offset)) return this.literal(\"true\", true);\n if (this.source.startsWith(\"false\", this.offset)) return this.literal(\"false\", false);\n if (this.source.startsWith(\"null\", this.offset)) return this.literal(\"null\", null);\n if (character === \"-\" || (character !== undefined && /[0-9]/.test(character)))\n return this.number(key);\n this.invalid(key, \"invalid JSON value\");\n }\n\n private object(key: string): JsonObject {\n this.offset++;\n this.whitespace();\n const object = new Map<string, JsonValue>();\n if (this.source[this.offset] === \"}\") {\n this.offset++;\n return object;\n }\n while (true) {\n this.whitespace();\n if (this.source[this.offset] !== '\"') this.invalid(key, \"object keys must be JSON strings\");\n const property = this.string(key);\n const propertyKey = `${key}.${property}`;\n if (object.has(property)) this.invalid(propertyKey, \"duplicate JSON property\");\n this.whitespace();\n if (this.source[this.offset] !== \":\")\n this.invalid(propertyKey, \"expected ':' after object key\");\n this.offset++;\n object.set(property, this.value(propertyKey));\n this.whitespace();\n const separator = this.source[this.offset];\n if (separator === \"}\") {\n this.offset++;\n return object;\n }\n if (separator !== \",\") this.invalid(key, \"expected ',' or '}' in object\");\n this.offset++;\n }\n }\n\n private array(key: string): JsonValue[] {\n this.offset++;\n this.whitespace();\n const values: JsonValue[] = [];\n if (this.source[this.offset] === \"]\") {\n this.offset++;\n return values;\n }\n while (true) {\n values.push(this.value(key));\n this.whitespace();\n const separator = this.source[this.offset];\n if (separator === \"]\") {\n this.offset++;\n return values;\n }\n if (separator !== \",\") this.invalid(key, \"expected ',' or ']' in array\");\n this.offset++;\n }\n }\n\n private string(key: string): string {\n const start = this.offset++;\n let escaped = false;\n while (this.offset < this.source.length) {\n const character = this.source[this.offset++];\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (character === '\"') {\n try {\n return JSON.parse(this.source.slice(start, this.offset)) as string;\n } catch {\n this.invalid(key, \"invalid JSON string\");\n }\n }\n if (character !== undefined && character.charCodeAt(0) < 0x20)\n this.invalid(key, \"unescaped control character in JSON string\");\n }\n this.invalid(key, \"unterminated JSON string\");\n }\n\n private number(key: string): number {\n const match = /-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;\n match.lastIndex = this.offset;\n const token = match.exec(this.source)?.[0];\n if (token === undefined) this.invalid(key, \"invalid JSON number\");\n this.offset += token.length;\n return Number(token);\n }\n\n private literal<T extends boolean | null>(written: string, value: T): T {\n this.offset += written.length;\n return value;\n }\n\n private whitespace(): void {\n while (this.offset < this.source.length) {\n const character = this.source[this.offset];\n if (character === undefined || !\" \\t\\n\\r\".includes(character)) return;\n this.offset++;\n }\n }\n\n private invalid(key: string, detail: string): never {\n fail(this.sourceFile, key, detail);\n }\n}\n\nfunction assertNamespaceSegment(sourceFile: string, segment: string, key: string): void {\n if (!SEGMENT.test(segment)) fail(sourceFile, key, \"segments must match [A-Za-z_][A-Za-z0-9_-]*\");\n if (FORBIDDEN_SEGMENTS.has(segment)) fail(sourceFile, key, \"segments cannot be reserved\");\n}\n\nfunction assertSegment(sourceFile: string, segment: string, key: string): void {\n if (segment.includes(\".\")) fail(sourceFile, key, \"JSON keys cannot contain '.'\");\n assertNamespaceSegment(sourceFile, segment, key);\n}\n\nfunction explicitGroup(sourceFile: string, value: string): string {\n if (value === \"\") fail(sourceFile, \"$group\", \"'$group' cannot be empty\");\n for (const segment of value.split(\".\")) {\n if (segment === \"\") fail(sourceFile, \"$group\", \"'$group' cannot contain empty segments\");\n assertNamespaceSegment(sourceFile, segment, \"$group\");\n }\n return value;\n}\n\nfunction defaultGroup(sourceFile: string, defaultNamespace: string | (() => string)): string {\n const namespace = typeof defaultNamespace === \"function\" ? defaultNamespace() : defaultNamespace;\n\n return namespace === \"\" ? \"\" : explicitGroup(sourceFile, namespace);\n}\n\nfunction isObject(value: JsonValue): value is JsonObject {\n return value instanceof Map;\n}\n\nfunction readLeaf(\n sourceFile: string,\n key: string,\n value: JsonObject,\n localeCodes: readonly string[] | undefined,\n): Record<string, string> {\n const locales = localeCodes === undefined ? undefined : new Set(localeCodes);\n const entry: Record<string, string> = Object.create(null) as Record<string, string>;\n for (const [locale, translation] of value) {\n if (!LOCALE_CODE.test(locale)) fail(sourceFile, `${key}.${locale}`, \"invalid locale code\");\n if (typeof translation !== \"string\")\n fail(sourceFile, `${key}.${locale}`, \"locale values must be strings\");\n if (locales !== undefined && !locales.has(locale))\n fail(sourceFile, `${key}.${locale}`, \"unknown locale code\");\n entry[locale] = translation;\n }\n if (localeCodes !== undefined)\n for (const locale of localeCodes)\n if (!(locale in entry)) fail(sourceFile, key, `missing locale code \"${locale}\"`);\n return entry;\n}\n\nfunction collectEntries(\n sourceFile: string,\n object: JsonObject,\n group: string,\n localeCodes: readonly string[] | undefined,\n entries: LocaleDictionaryEntries,\n nested: boolean,\n): void {\n if (nested && object.size === 0) fail(sourceFile, group, \"nested objects cannot be empty\");\n for (const [segment, value] of object) {\n const key = group === \"\" ? segment : `${group}.${segment}`;\n if (segment === \"$group\") fail(sourceFile, key, \"'$group' is only allowed at the root\");\n assertSegment(sourceFile, segment, key);\n if (!isObject(value)) fail(sourceFile, key, \"entries must be locale objects or nested objects\");\n if (value.has(\"$group\"))\n fail(sourceFile, `${key}.$group`, \"'$group' is only allowed at the root\");\n const values = [...value.values()];\n const hasString = values.some((item) => typeof item === \"string\");\n const allObjects = values.every(isObject);\n if (hasString) {\n if (!values.every((item) => typeof item === \"string\"))\n fail(sourceFile, key, \"cannot mix locale values with nested entries\");\n entries[key] = readLeaf(sourceFile, key, value, localeCodes);\n continue;\n }\n if (!allObjects) fail(sourceFile, key, \"cannot mix locale values with nested entries\");\n if (localeCodes !== undefined && [...value.keys()].some((child) => localeCodes.includes(child)))\n fail(sourceFile, key, \"cannot mix locale codes with nested entries\");\n collectEntries(sourceFile, value, key, localeCodes, entries, true);\n }\n}\n\n/** Parses one locale dictionary source without reading the filesystem or loading application code. */\nexport function parseLocaleDictionary(input: {\n sourceFile: string;\n source: string;\n /**\n * The group used when the file declares no `$group`. A function is called\n * only in that case, so a namespace that cannot be derived (e.g. from a\n * folder name) never fails a file that names its own `$group`.\n */\n defaultNamespace: string | (() => string);\n localeCodes?: readonly string[];\n}): ParsedLocaleDictionary {\n const { sourceFile, source, defaultNamespace, localeCodes } = input;\n const parsed = new StrictJsonParser(sourceFile, source).parse();\n if (!isObject(parsed)) fail(sourceFile, \"$\", \"root JSON value must be an object\");\n const groupValue = parsed.get(\"$group\");\n if (groupValue !== undefined && typeof groupValue !== \"string\")\n fail(sourceFile, \"$group\", \"'$group' must be a string\");\n const group =\n groupValue === undefined\n ? defaultGroup(sourceFile, defaultNamespace)\n : explicitGroup(sourceFile, groupValue);\n const entries: LocaleDictionaryEntries = Object.create(null) as LocaleDictionaryEntries;\n const rootEntries = new Map(parsed);\n rootEntries.delete(\"$group\");\n collectEntries(sourceFile, rootEntries, group, localeCodes, entries, false);\n return { sourceFile, group, entries };\n}\n"],"mappings":";AAWA,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,qBAAqB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAa,CAAC;;AAG5E,IAAa,wBAAb,cAA2C,MAAM;CAC/C,AAAO,YACL,AAAgB,YAChB,AAAgB,KAChB,QACA;EACA,MAAM,kCAAkC,WAAW,QAAQ,IAAI,KAAK,OAAO,EAAE;EAJ7D;EACA;EAIhB,KAAK,OAAO;CACd;AACF;AAEA,SAAS,KAAK,YAAoB,KAAa,QAAuB;CACpE,MAAM,IAAI,sBAAsB,YAAY,KAAK,MAAM;AACzD;;AAGA,IAAM,mBAAN,MAAuB;CAGrB,AAAO,YACL,AAAiB,YACjB,AAAiB,QACjB;EAFiB;EACA;gBAJF;CAKd;CAEH,AAAO,QAAmB;EACxB,IAAI,KAAK,OAAO,WAAW,CAAC,MAAM,OAAQ,KAAK,SAAS;EACxD,MAAM,QAAQ,KAAK,MAAM,GAAG;EAC5B,KAAK,WAAW;EAChB,IAAI,KAAK,WAAW,KAAK,OAAO,QAAQ,KAAK,QAAQ,KAAK,0BAA0B;EACpF,OAAO;CACT;CAEA,AAAQ,MAAM,KAAwB;EACpC,KAAK,WAAW;EAChB,MAAM,YAAY,KAAK,OAAO,KAAK;EACnC,IAAI,cAAc,KAAK,OAAO,KAAK,OAAO,GAAG;EAC7C,IAAI,cAAc,KAAK,OAAO,KAAK,MAAM,GAAG;EAC5C,IAAI,cAAc,MAAK,OAAO,KAAK,OAAO,GAAG;EAC7C,IAAI,KAAK,OAAO,WAAW,QAAQ,KAAK,MAAM,GAAG,OAAO,KAAK,QAAQ,QAAQ,I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SAAS,IAAI,iBAAiB,YAAY,MAAM,CAAC,CAAC,MAAM;CAC9D,IAAI,CAAC,SAAS,MAAM,GAAG,KAAK,YAAY,KAAK,mCAAmC;CAChF,MAAM,aAAa,OAAO,IAAI,QAAQ;CACtC,IAAI,eAAe,UAAa,OAAO,eAAe,UACpD,KAAK,YAAY,UAAU,2BAA2B;CACxD,MAAM,QACJ,eAAe,SACX,aAAa,YAAY,gBAAgB,IACzC,cAAc,YAAY,UAAU;CAC1C,MAAM,UAAmC,OAAO,OAAO,IAAI;CAC3D,MAAM,cAAc,IAAI,IAAI,MAAM;CAClC,YAAY,OAAO,QAAQ;CAC3B,eAAe,YAAY,aAAa,OAAO,aAAa,SAAS,KAAK;CAC1E,OAAO;EAAE;EAAY;EAAO;CAAQ;AACtC"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isNullableResource } from "../resource/nullable-resource.mjs";
|
|
2
|
+
|
|
1
3
|
//#region ../core/src/openapi/response-schemas.ts
|
|
2
4
|
const STATUS_TEXT = {
|
|
3
5
|
"200": "Successful response",
|
|
@@ -30,11 +32,12 @@ function describeStatus(status) {
|
|
|
30
32
|
}
|
|
31
33
|
/**
|
|
32
34
|
* JSON Schema of one response body value: a cast string, a resource class, `[Resource]`
|
|
33
|
-
* (array of it) or a nested plain object of those. Anything else (a resolver function, a
|
|
35
|
+
* (array of it), `nullable(Resource)` (the resource or null) or a nested plain object of those. Anything else (a resolver function, a
|
|
34
36
|
* builder) is `{}` plus a warning.
|
|
35
37
|
*/
|
|
36
38
|
function bodyValueSchema(value, path, registry, warn) {
|
|
37
39
|
if (typeof value === "string") return registry.cast(value, path, warn);
|
|
40
|
+
if (isNullableResource(value)) return { oneOf: [bodyValueSchema(value.resource, path, registry, warn), { type: "null" }] };
|
|
38
41
|
if (typeof value === "function") {
|
|
39
42
|
if (registry.isResourceClass(value)) return registry.resourceRef(value);
|
|
40
43
|
warn(`${path}: a function that is not a resource class has no static shape and is documented as {}.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response-schemas.mjs","names":[],"sources":["../../../../../../../core/src/openapi/response-schemas.ts"],"sourcesContent":["import type { SchemaRegistry } from \"./schema-registry\";\nimport type { OpenApiResponse, OpenApiSchema, WarningSink } from \"./types\";\n\nconst STATUS_TEXT: Record<string, string> = {\n \"200\": \"Successful response\",\n \"201\": \"Created\",\n \"202\": \"Accepted\",\n \"204\": \"No content\",\n \"301\": \"Moved permanently\",\n \"302\": \"Found\",\n \"304\": \"Not modified\",\n \"400\": \"Bad request\",\n \"401\": \"Unauthorized\",\n \"403\": \"Forbidden\",\n \"404\": \"Not found\",\n \"405\": \"Method not allowed\",\n \"409\": \"Conflict\",\n \"410\": \"Gone\",\n \"422\": \"Validation failed\",\n \"429\": \"Too many requests\",\n \"500\": \"Internal server error\",\n \"503\": \"Service unavailable\",\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Human description of a status code for the required `description` of a response.\n */\nexport function describeStatus(status: string): string {\n return STATUS_TEXT[status] ?? `Status ${status}`;\n}\n\n/**\n * JSON Schema of one response body value: a cast string, a resource class, `[Resource]`\n * (array of it) or a nested plain object of those. Anything else (a resolver function, a\n * builder) is `{}` plus a warning.\n */\nfunction bodyValueSchema(value: unknown, path: string, registry: SchemaRegistry, warn: WarningSink): OpenApiSchema {\n if (typeof value === \"string\") {\n return registry.cast(value, path, warn);\n }\n\n if (typeof value === \"function\") {\n if (registry.isResourceClass(value)) {\n return registry.resourceRef(value);\n }\n\n warn(`${path}: a function that is not a resource class has no static shape and is documented as {}.`);\n\n return {};\n }\n\n if (Array.isArray(value)) {\n return { type: \"array\", items: bodyValueSchema(value[0], `${path}[]`, registry, warn) };\n }\n\n if (isRecord(value)) {\n return objectSchema(value, path, registry, warn);\n }\n\n warn(`${path}: unsupported response value is documented as {}.`);\n\n return {};\n}\n\nfunction objectSchema(\n body: Record<string, unknown>,\n path: string,\n registry: SchemaRegistry,\n warn: WarningSink,\n): OpenApiSchema {\n const properties: Record<string, OpenApiSchema> = {};\n\n for (const [key, member] of Object.entries(body)) {\n properties[key] = bodyValueSchema(member, `${path}.${key}`, registry, warn);\n }\n\n return { type: \"object\", properties, required: Object.keys(properties) };\n}\n\n/**\n * Map a handler's `responseSchema` to OpenAPI responses, one per declared status code.\n *\n * `routeLabel` prefixes warnings (for example `POST /login`). A status without a usable\n * `body` becomes a description-only response.\n */\nexport function buildDeclaredResponses(\n responseSchema: unknown,\n registry: SchemaRegistry,\n warn: WarningSink,\n): Record<string, OpenApiResponse> {\n const responses: Record<string, OpenApiResponse> = {};\n\n if (!isRecord(responseSchema)) {\n return responses;\n }\n\n for (const [status, entry] of Object.entries(responseSchema)) {\n const body = isRecord(entry) ? entry.body : undefined;\n\n if (!isRecord(body)) {\n responses[status] = { description: describeStatus(status) };\n\n continue;\n }\n\n responses[status] = {\n description: describeStatus(status),\n content: {\n \"application/json\": { schema: objectSchema(body, `response ${status}`, registry, warn) },\n },\n };\n }\n\n return responses;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"response-schemas.mjs","names":[],"sources":["../../../../../../../core/src/openapi/response-schemas.ts"],"sourcesContent":["import { isNullableResource } from \"../resource/nullable-resource\";\nimport type { SchemaRegistry } from \"./schema-registry\";\nimport type { OpenApiResponse, OpenApiSchema, WarningSink } from \"./types\";\n\nconst STATUS_TEXT: Record<string, string> = {\n \"200\": \"Successful response\",\n \"201\": \"Created\",\n \"202\": \"Accepted\",\n \"204\": \"No content\",\n \"301\": \"Moved permanently\",\n \"302\": \"Found\",\n \"304\": \"Not modified\",\n \"400\": \"Bad request\",\n \"401\": \"Unauthorized\",\n \"403\": \"Forbidden\",\n \"404\": \"Not found\",\n \"405\": \"Method not allowed\",\n \"409\": \"Conflict\",\n \"410\": \"Gone\",\n \"422\": \"Validation failed\",\n \"429\": \"Too many requests\",\n \"500\": \"Internal server error\",\n \"503\": \"Service unavailable\",\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Human description of a status code for the required `description` of a response.\n */\nexport function describeStatus(status: string): string {\n return STATUS_TEXT[status] ?? `Status ${status}`;\n}\n\n/**\n * JSON Schema of one response body value: a cast string, a resource class, `[Resource]`\n * (array of it), `nullable(Resource)` (the resource or null) or a nested plain object of those. Anything else (a resolver function, a\n * builder) is `{}` plus a warning.\n */\nfunction bodyValueSchema(value: unknown, path: string, registry: SchemaRegistry, warn: WarningSink): OpenApiSchema {\n if (typeof value === \"string\") {\n return registry.cast(value, path, warn);\n }\n\n if (isNullableResource(value)) {\n return { oneOf: [bodyValueSchema(value.resource, path, registry, warn), { type: \"null\" }] };\n }\n\n if (typeof value === \"function\") {\n if (registry.isResourceClass(value)) {\n return registry.resourceRef(value);\n }\n\n warn(`${path}: a function that is not a resource class has no static shape and is documented as {}.`);\n\n return {};\n }\n\n if (Array.isArray(value)) {\n return { type: \"array\", items: bodyValueSchema(value[0], `${path}[]`, registry, warn) };\n }\n\n if (isRecord(value)) {\n return objectSchema(value, path, registry, warn);\n }\n\n warn(`${path}: unsupported response value is documented as {}.`);\n\n return {};\n}\n\nfunction objectSchema(\n body: Record<string, unknown>,\n path: string,\n registry: SchemaRegistry,\n warn: WarningSink,\n): OpenApiSchema {\n const properties: Record<string, OpenApiSchema> = {};\n\n for (const [key, member] of Object.entries(body)) {\n properties[key] = bodyValueSchema(member, `${path}.${key}`, registry, warn);\n }\n\n return { type: \"object\", properties, required: Object.keys(properties) };\n}\n\n/**\n * Map a handler's `responseSchema` to OpenAPI responses, one per declared status code.\n *\n * `routeLabel` prefixes warnings (for example `POST /login`). A status without a usable\n * `body` becomes a description-only response.\n */\nexport function buildDeclaredResponses(\n responseSchema: unknown,\n registry: SchemaRegistry,\n warn: WarningSink,\n): Record<string, OpenApiResponse> {\n const responses: Record<string, OpenApiResponse> = {};\n\n if (!isRecord(responseSchema)) {\n return responses;\n }\n\n for (const [status, entry] of Object.entries(responseSchema)) {\n const body = isRecord(entry) ? entry.body : undefined;\n\n if (!isRecord(body)) {\n responses[status] = { description: describeStatus(status) };\n\n continue;\n }\n\n responses[status] = {\n description: describeStatus(status),\n content: {\n \"application/json\": { schema: objectSchema(body, `response ${status}`, registry, warn) },\n },\n };\n }\n\n return responses;\n}\n"],"mappings":";;;AAIA,MAAM,cAAsC;CAC1C,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;AACT;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;AAKA,SAAgB,eAAe,QAAwB;CACrD,OAAO,YAAY,WAAW,UAAU;AAC1C;;;;;;AAOA,SAAS,gBAAgB,OAAgB,MAAc,UAA0B,MAAkC;CACjH,IAAI,OAAO,UAAU,UACnB,OAAO,SAAS,KAAK,OAAO,MAAM,IAAI;CAGxC,IAAI,mBAAmB,KAAK,GAC1B,OAAO,EAAE,OAAO,CAAC,gBAAgB,MAAM,UAAU,MAAM,UAAU,IAAI,GAAG,EAAE,MAAM,OAAO,CAAC,EAAE;CAG5F,IAAI,OAAO,UAAU,YAAY;EAC/B,IAAI,SAAS,gBAAgB,KAAK,GAChC,OAAO,SAAS,YAAY,KAAK;EAGnC,KAAK,GAAG,KAAK,uFAAuF;EAEpG,OAAO,CAAC;CACV;CAEA,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO;EAAE,MAAM;EAAS,OAAO,gBAAgB,MAAM,IAAI,GAAG,KAAK,KAAK,UAAU,IAAI;CAAE;CAGxF,IAAI,SAAS,KAAK,GAChB,OAAO,aAAa,OAAO,MAAM,UAAU,IAAI;CAGj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