@constructive-io/errors 0.3.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.
Files changed (51) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +139 -0
  3. package/classify.d.ts +10 -0
  4. package/classify.js +20 -0
  5. package/define.d.ts +16 -0
  6. package/define.js +11 -0
  7. package/error.d.ts +32 -0
  8. package/error.js +47 -0
  9. package/esm/classify.d.ts +10 -0
  10. package/esm/classify.js +16 -0
  11. package/esm/define.d.ts +16 -0
  12. package/esm/define.js +8 -0
  13. package/esm/error.d.ts +32 -0
  14. package/esm/error.js +43 -0
  15. package/esm/factory.d.ts +35 -0
  16. package/esm/factory.js +49 -0
  17. package/esm/format.d.ts +24 -0
  18. package/esm/format.js +54 -0
  19. package/esm/generated/registry.generated.d.ts +27 -0
  20. package/esm/generated/registry.generated.js +601 -0
  21. package/esm/index.d.ts +9 -0
  22. package/esm/index.js +9 -0
  23. package/esm/interpolate.d.ts +6 -0
  24. package/esm/interpolate.js +11 -0
  25. package/esm/parse.d.ts +30 -0
  26. package/esm/parse.js +199 -0
  27. package/esm/pg.d.ts +14 -0
  28. package/esm/pg.js +49 -0
  29. package/esm/registry.d.ts +147 -0
  30. package/esm/registry.js +468 -0
  31. package/esm/types.d.ts +81 -0
  32. package/esm/types.js +10 -0
  33. package/factory.d.ts +35 -0
  34. package/factory.js +55 -0
  35. package/format.d.ts +24 -0
  36. package/format.js +59 -0
  37. package/generated/registry.generated.d.ts +27 -0
  38. package/generated/registry.generated.js +604 -0
  39. package/index.d.ts +9 -0
  40. package/index.js +25 -0
  41. package/interpolate.d.ts +6 -0
  42. package/interpolate.js +14 -0
  43. package/package.json +45 -0
  44. package/parse.d.ts +30 -0
  45. package/parse.js +203 -0
  46. package/pg.d.ts +14 -0
  47. package/pg.js +53 -0
  48. package/registry.d.ts +147 -0
  49. package/registry.js +474 -0
  50. package/types.d.ts +81 -0
  51. package/types.js +11 -0
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # @constructive-io/errors
2
+
3
+ Canonical Constructive error system. Zero runtime dependencies — usable by any
4
+ service or client without pulling in pgpm.
5
+
6
+ - **Registry** — the single source of truth mapping each stable `code` to its
7
+ classification (`public` vs `internal`), HTTP hint, and default message.
8
+ - **`parse(anyError)`** — normalize an error from any source (a
9
+ `ConstructiveError`, a node-postgres `DatabaseError`, a GraphQL error or
10
+ `{ errors: [...] }` wrapper, a plain `Error`, or a string) into a canonical
11
+ `{ code, context, class, known }`.
12
+ - **`format(code, context, locale)`** — render a localized, interpolated
13
+ message. `{{var}}` placeholders + registerable per-locale catalogs (i18n).
14
+ - **`errors.*` factory** — type-safe throwable builders derived from the
15
+ registry, e.g. `throw errors.MODULE_NOT_FOUND({ name })`.
16
+ - **`classify(code)`** — `public` or `internal`; unknown codes are `internal`
17
+ (fail safe) so transports never leak unregistered errors.
18
+
19
+ ```ts
20
+ import { parse, format, errors, classify } from '@constructive-io/errors';
21
+
22
+ // Normalize a DB error surfaced through GraphQL
23
+ const parsed = parse(graphqlError);
24
+ if (parsed.class === 'public') {
25
+ showUser(format(parsed.code!, parsed.context, locale));
26
+ }
27
+
28
+ // Throw a structured error
29
+ throw errors.ACCOUNT_EXISTS();
30
+ ```
31
+
32
+ ## Design notes
33
+
34
+ - The machine `code` is deliberately separate from user-facing copy so codes
35
+ are stable and messages are localizable.
36
+ - `parse()` recovers structure from the code's precedence: structured `DETAIL`
37
+ JSON → GraphQL `extensions.code` → a leading ALL_CAPS token in the message
38
+ (legacy DB `RAISE`, incl. `CODE (arg, arg)` positional args) → native
39
+ SQLSTATE constraint mapping.
40
+ - The registry has two layers, merged at lookup time (curated wins):
41
+ - **Generated** (`src/generated/registry.generated.ts`) — every code raised via
42
+ `EXCEPTION`/`THROW` across constructive-db (deploy sources + generated output),
43
+ each with a `public`/`internal` class, HTTP hint, and default message.
44
+ - **Curated** (`src/registry.ts`) — refined, typed-context entries for the codes
45
+ that matter most (public auth/limit copy, native PostgreSQL constraint codes,
46
+ pgpm CLI codes). These override the generated entries.
47
+ - Unregistered codes still `parse()` and are classified `internal` (masked).
48
+
49
+ ## Regenerating the full registry
50
+
51
+ The generated layer is produced from a committed audit snapshot:
52
+
53
+ ```bash
54
+ # 1. re-audit constructive-db (refreshes scripts/db-error-inventory.json)
55
+ CONSTRUCTIVE_DB_DIR=~/repos/constructive-db python3 scripts/audit-db-errors.py
56
+ # 2. regenerate src/generated/registry.generated.ts from the snapshot
57
+ python3 scripts/generate-registry.py
58
+ ```
59
+
60
+ `audit-db-errors.py` scans every `EXCEPTION`/`THROW` across constructive-db deploy
61
+ sources and generated output and writes `scripts/db-error-inventory.json` (the
62
+ committed audit snapshot). `generate-registry.py` reads that snapshot and, when a
63
+ `constructive-io/dashboard` checkout is found (via `DASHBOARD_DIR` or a sibling
64
+ `../dashboard`), seeds public copy from its error catalogs. Re-run both whenever
65
+ constructive-db error codes change. Never hand-edit the generated file.
66
+
67
+ ---
68
+
69
+ ## Education and Tutorials
70
+
71
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
72
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
73
+
74
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
75
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
76
+
77
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
78
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
79
+
80
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
81
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
82
+
83
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
84
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
85
+
86
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
87
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
88
+
89
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
90
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
91
+
92
+ ## Related Constructive Tooling
93
+
94
+ ### 📦 Package Management
95
+
96
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
97
+
98
+ ### 🧪 Testing
99
+
100
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
101
+ * [pglite-test](https://github.com/constructive-io/constructive/tree/main/postgres/pglite-test): **🪶 Drop-in pgsql-test replacement backed by PGlite** — in-process Postgres, no server required, instance-per-suite isolation.
102
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
103
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
104
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
105
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
106
+
107
+ ### 🧠 Parsing & AST
108
+
109
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
110
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
111
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
112
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
113
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
114
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
115
+
116
+ ### 📚 Documentation & Skills
117
+
118
+ * [constructive-skills](https://github.com/constructive-io/constructive-skills): **📖 Platform documentation and AI agent skills** — feature catalog, blueprint reference, SDK guides (i18n, billing, limits, events, uploads, security, entities, search, AI), and deployment guides.
119
+
120
+ Install skills for AI coding agents:
121
+
122
+ ```bash
123
+ # All platform skills (security, blueprints, codegen, billing, etc.)
124
+ npx skills add constructive-io/constructive-skills
125
+
126
+ # Individual repo skills (pgpm, testing, CLI, search, etc.)
127
+ npx skills add https://github.com/constructive-io/constructive --skill pgpm
128
+ npx skills add https://github.com/constructive-io/constructive --skill constructive-testing
129
+ ```
130
+
131
+ ## Credits
132
+
133
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
134
+
135
+ ## Disclaimer
136
+
137
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
138
+
139
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/classify.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { ErrorClass } from './types';
2
+ /**
3
+ * Classify a code as `public` or `internal`.
4
+ *
5
+ * Unknown codes are classified `internal` on purpose: transports mask internal
6
+ * errors, so an unregistered code is never leaked to end users by default.
7
+ */
8
+ export declare function classify(code: string | null | undefined): ErrorClass;
9
+ /** Whether a code is registered and classified `public`. */
10
+ export declare function isPublicCode(code: string | null | undefined): boolean;
package/classify.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.classify = classify;
4
+ exports.isPublicCode = isPublicCode;
5
+ const registry_1 = require("./registry");
6
+ /**
7
+ * Classify a code as `public` or `internal`.
8
+ *
9
+ * Unknown codes are classified `internal` on purpose: transports mask internal
10
+ * errors, so an unregistered code is never leaked to end users by default.
11
+ */
12
+ function classify(code) {
13
+ if (!code)
14
+ return 'internal';
15
+ return (0, registry_1.getDefinition)(code)?.class ?? 'internal';
16
+ }
17
+ /** Whether a code is registered and classified `public`. */
18
+ function isPublicCode(code) {
19
+ return classify(code) === 'public';
20
+ }
package/define.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { EmptyContext, ErrorContext, ErrorDefinition } from './types';
2
+ /**
3
+ * A registry entry plus a phantom type carrier for its context. The
4
+ * contravariant `__context` field lets `ErrorsApi` recover `C` by inference
5
+ * even when `C` appears only in optional positions of {@link ErrorDefinition}.
6
+ * It is type-level only — never set at runtime.
7
+ */
8
+ export type DefinedError<C extends ErrorContext = EmptyContext> = ErrorDefinition<C> & {
9
+ readonly __context: (context: C) => void;
10
+ };
11
+ /**
12
+ * Identity helper that captures each entry's context type for inference while
13
+ * keeping the registry a plain object. `errors.MODULE_NOT_FOUND({ name })` is
14
+ * then type-checked against the declared context.
15
+ */
16
+ export declare function defineError<C extends ErrorContext = EmptyContext>(def: ErrorDefinition<C>): DefinedError<C>;
package/define.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defineError = defineError;
4
+ /**
5
+ * Identity helper that captures each entry's context type for inference while
6
+ * keeping the registry a plain object. `errors.MODULE_NOT_FOUND({ name })` is
7
+ * then type-checked against the declared context.
8
+ */
9
+ function defineError(def) {
10
+ return def;
11
+ }
package/error.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import type { ErrorClass, ErrorContext } from './types';
2
+ export interface ConstructiveErrorArgs {
3
+ code: string;
4
+ message: string;
5
+ errorClass: ErrorClass;
6
+ http: number;
7
+ context?: ErrorContext;
8
+ }
9
+ /**
10
+ * The single canonical error class for Constructive. Carries the machine
11
+ * `code`, its classification, an HTTP hint, and structured `context`.
12
+ *
13
+ * Replaces the previously separate `PgpmError`, `AuthError`, and `DataError`
14
+ * shapes. GraphQL transports should serialize {@link toExtensions}.
15
+ */
16
+ export declare class ConstructiveError extends Error {
17
+ readonly code: string;
18
+ readonly errorClass: ErrorClass;
19
+ readonly http: number;
20
+ readonly context?: ErrorContext;
21
+ constructor(args: ConstructiveErrorArgs);
22
+ /** Whether this error is safe to surface to end users. */
23
+ get isPublic(): boolean;
24
+ /** GraphQL `extensions` payload for this error. */
25
+ toExtensions(): {
26
+ code: string;
27
+ class: ErrorClass;
28
+ http: number;
29
+ context?: ErrorContext;
30
+ };
31
+ toString(): string;
32
+ }
package/error.js ADDED
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConstructiveError = void 0;
4
+ /**
5
+ * The single canonical error class for Constructive. Carries the machine
6
+ * `code`, its classification, an HTTP hint, and structured `context`.
7
+ *
8
+ * Replaces the previously separate `PgpmError`, `AuthError`, and `DataError`
9
+ * shapes. GraphQL transports should serialize {@link toExtensions}.
10
+ */
11
+ class ConstructiveError extends Error {
12
+ code;
13
+ errorClass;
14
+ http;
15
+ context;
16
+ constructor(args) {
17
+ super(args.message);
18
+ this.name = 'ConstructiveError';
19
+ this.code = args.code;
20
+ this.errorClass = args.errorClass;
21
+ this.http = args.http;
22
+ this.context = args.context;
23
+ if (Error.captureStackTrace) {
24
+ Error.captureStackTrace(this, ConstructiveError);
25
+ }
26
+ }
27
+ /** Whether this error is safe to surface to end users. */
28
+ get isPublic() {
29
+ return this.errorClass === 'public';
30
+ }
31
+ /** GraphQL `extensions` payload for this error. */
32
+ toExtensions() {
33
+ const ext = {
34
+ code: this.code,
35
+ class: this.errorClass,
36
+ http: this.http
37
+ };
38
+ if (this.context && Object.keys(this.context).length > 0) {
39
+ ext.context = this.context;
40
+ }
41
+ return ext;
42
+ }
43
+ toString() {
44
+ return `[${this.code}] ${this.message}`;
45
+ }
46
+ }
47
+ exports.ConstructiveError = ConstructiveError;
@@ -0,0 +1,10 @@
1
+ import type { ErrorClass } from './types';
2
+ /**
3
+ * Classify a code as `public` or `internal`.
4
+ *
5
+ * Unknown codes are classified `internal` on purpose: transports mask internal
6
+ * errors, so an unregistered code is never leaked to end users by default.
7
+ */
8
+ export declare function classify(code: string | null | undefined): ErrorClass;
9
+ /** Whether a code is registered and classified `public`. */
10
+ export declare function isPublicCode(code: string | null | undefined): boolean;
@@ -0,0 +1,16 @@
1
+ import { getDefinition } from './registry';
2
+ /**
3
+ * Classify a code as `public` or `internal`.
4
+ *
5
+ * Unknown codes are classified `internal` on purpose: transports mask internal
6
+ * errors, so an unregistered code is never leaked to end users by default.
7
+ */
8
+ export function classify(code) {
9
+ if (!code)
10
+ return 'internal';
11
+ return getDefinition(code)?.class ?? 'internal';
12
+ }
13
+ /** Whether a code is registered and classified `public`. */
14
+ export function isPublicCode(code) {
15
+ return classify(code) === 'public';
16
+ }
@@ -0,0 +1,16 @@
1
+ import type { EmptyContext, ErrorContext, ErrorDefinition } from './types';
2
+ /**
3
+ * A registry entry plus a phantom type carrier for its context. The
4
+ * contravariant `__context` field lets `ErrorsApi` recover `C` by inference
5
+ * even when `C` appears only in optional positions of {@link ErrorDefinition}.
6
+ * It is type-level only — never set at runtime.
7
+ */
8
+ export type DefinedError<C extends ErrorContext = EmptyContext> = ErrorDefinition<C> & {
9
+ readonly __context: (context: C) => void;
10
+ };
11
+ /**
12
+ * Identity helper that captures each entry's context type for inference while
13
+ * keeping the registry a plain object. `errors.MODULE_NOT_FOUND({ name })` is
14
+ * then type-checked against the declared context.
15
+ */
16
+ export declare function defineError<C extends ErrorContext = EmptyContext>(def: ErrorDefinition<C>): DefinedError<C>;
package/esm/define.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Identity helper that captures each entry's context type for inference while
3
+ * keeping the registry a plain object. `errors.MODULE_NOT_FOUND({ name })` is
4
+ * then type-checked against the declared context.
5
+ */
6
+ export function defineError(def) {
7
+ return def;
8
+ }
package/esm/error.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import type { ErrorClass, ErrorContext } from './types';
2
+ export interface ConstructiveErrorArgs {
3
+ code: string;
4
+ message: string;
5
+ errorClass: ErrorClass;
6
+ http: number;
7
+ context?: ErrorContext;
8
+ }
9
+ /**
10
+ * The single canonical error class for Constructive. Carries the machine
11
+ * `code`, its classification, an HTTP hint, and structured `context`.
12
+ *
13
+ * Replaces the previously separate `PgpmError`, `AuthError`, and `DataError`
14
+ * shapes. GraphQL transports should serialize {@link toExtensions}.
15
+ */
16
+ export declare class ConstructiveError extends Error {
17
+ readonly code: string;
18
+ readonly errorClass: ErrorClass;
19
+ readonly http: number;
20
+ readonly context?: ErrorContext;
21
+ constructor(args: ConstructiveErrorArgs);
22
+ /** Whether this error is safe to surface to end users. */
23
+ get isPublic(): boolean;
24
+ /** GraphQL `extensions` payload for this error. */
25
+ toExtensions(): {
26
+ code: string;
27
+ class: ErrorClass;
28
+ http: number;
29
+ context?: ErrorContext;
30
+ };
31
+ toString(): string;
32
+ }
package/esm/error.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The single canonical error class for Constructive. Carries the machine
3
+ * `code`, its classification, an HTTP hint, and structured `context`.
4
+ *
5
+ * Replaces the previously separate `PgpmError`, `AuthError`, and `DataError`
6
+ * shapes. GraphQL transports should serialize {@link toExtensions}.
7
+ */
8
+ export class ConstructiveError extends Error {
9
+ code;
10
+ errorClass;
11
+ http;
12
+ context;
13
+ constructor(args) {
14
+ super(args.message);
15
+ this.name = 'ConstructiveError';
16
+ this.code = args.code;
17
+ this.errorClass = args.errorClass;
18
+ this.http = args.http;
19
+ this.context = args.context;
20
+ if (Error.captureStackTrace) {
21
+ Error.captureStackTrace(this, ConstructiveError);
22
+ }
23
+ }
24
+ /** Whether this error is safe to surface to end users. */
25
+ get isPublic() {
26
+ return this.errorClass === 'public';
27
+ }
28
+ /** GraphQL `extensions` payload for this error. */
29
+ toExtensions() {
30
+ const ext = {
31
+ code: this.code,
32
+ class: this.errorClass,
33
+ http: this.http
34
+ };
35
+ if (this.context && Object.keys(this.context).length > 0) {
36
+ ext.context = this.context;
37
+ }
38
+ return ext;
39
+ }
40
+ toString() {
41
+ return `[${this.code}] ${this.message}`;
42
+ }
43
+ }
@@ -0,0 +1,35 @@
1
+ import { ConstructiveError } from './error';
2
+ import { registry } from './registry';
3
+ import type { ErrorClass, ErrorContext, ErrorDefinition } from './types';
4
+ /**
5
+ * The callable produced for a registry entry. Codes with no context params can
6
+ * be called with no arguments; codes with params require a matching context.
7
+ * The `[keyof C]` tuple wrapper prevents `never` from distributing.
8
+ */
9
+ export type ErrorFactory<C extends ErrorContext> = [keyof C] extends [never] ? (context?: Record<string, never>, overrideMessage?: string) => ConstructiveError : (context: C, overrideMessage?: string) => ConstructiveError;
10
+ export type ErrorsApi<R> = {
11
+ [K in keyof R]: R[K] extends {
12
+ __context: (context: infer C) => void;
13
+ } ? C extends ErrorContext ? ErrorFactory<C> : never : never;
14
+ };
15
+ /** Build a throwable factory for a single definition. */
16
+ export declare function makeErrorFromDefinition<C extends ErrorContext>(def: ErrorDefinition<C>): ErrorFactory<C>;
17
+ /** Build the `errors.*` factory object from a registry. */
18
+ export declare function buildErrors<R extends Record<string, {
19
+ __context: (context: never) => void;
20
+ }>>(reg: R): ErrorsApi<R>;
21
+ /**
22
+ * Low-level factory helper for defining an error inline (the pattern the former
23
+ * pgpm `error-factory` exposed). Prefer registering codes in the registry, but
24
+ * this remains available for ad-hoc / dynamically-coded errors.
25
+ */
26
+ export declare function makeError<C extends ErrorContext>(code: string, messageFn: (context: C) => string, httpCode?: number, errorClass?: ErrorClass): (context: C, overrideMessage?: string) => ConstructiveError;
27
+ /**
28
+ * The canonical `errors.*` factory.
29
+ *
30
+ * Curated codes are strongly typed (`errors.MODULE_NOT_FOUND({ name })`); every
31
+ * other constructive-db code is available via a generic factory through the
32
+ * index signature (`errors.ACCOUNT_EXISTS()`), backed by the generated
33
+ * registry. Curated entries override generated ones on conflict.
34
+ */
35
+ export declare const errors: ErrorsApi<typeof registry> & Record<string, ErrorFactory<ErrorContext>>;
package/esm/factory.js ADDED
@@ -0,0 +1,49 @@
1
+ import { ConstructiveError } from './error';
2
+ import { format } from './format';
3
+ import { generatedRegistry } from './generated/registry.generated';
4
+ import { registry } from './registry';
5
+ /** Build a throwable factory for a single definition. */
6
+ export function makeErrorFromDefinition(def) {
7
+ const factory = (context, overrideMessage) => new ConstructiveError({
8
+ code: def.code,
9
+ message: overrideMessage ?? format(def.code, context ?? {}),
10
+ errorClass: def.class,
11
+ http: def.http,
12
+ context
13
+ });
14
+ return factory;
15
+ }
16
+ /** Build the `errors.*` factory object from a registry. */
17
+ export function buildErrors(reg) {
18
+ const out = {};
19
+ for (const key of Object.keys(reg)) {
20
+ out[key] = makeErrorFromDefinition(reg[key]);
21
+ }
22
+ return out;
23
+ }
24
+ /**
25
+ * Low-level factory helper for defining an error inline (the pattern the former
26
+ * pgpm `error-factory` exposed). Prefer registering codes in the registry, but
27
+ * this remains available for ad-hoc / dynamically-coded errors.
28
+ */
29
+ export function makeError(code, messageFn, httpCode = 500, errorClass = 'internal') {
30
+ return (context, overrideMessage) => new ConstructiveError({
31
+ code,
32
+ message: overrideMessage ?? messageFn(context),
33
+ errorClass,
34
+ http: httpCode,
35
+ context
36
+ });
37
+ }
38
+ /**
39
+ * The canonical `errors.*` factory.
40
+ *
41
+ * Curated codes are strongly typed (`errors.MODULE_NOT_FOUND({ name })`); every
42
+ * other constructive-db code is available via a generic factory through the
43
+ * index signature (`errors.ACCOUNT_EXISTS()`), backed by the generated
44
+ * registry. Curated entries override generated ones on conflict.
45
+ */
46
+ export const errors = buildErrors({
47
+ ...generatedRegistry,
48
+ ...registry
49
+ });
@@ -0,0 +1,24 @@
1
+ import type { ErrorContext } from './types';
2
+ /** A locale catalog maps `code` → message template (with `{{var}}`). */
3
+ export type MessageCatalog = Record<string, string>;
4
+ /**
5
+ * Locale to use when `format` is called without one. This is a plain fallback
6
+ * label, not a special catalog: the untagged default copy lives in the registry
7
+ * itself, so there is no built-in `'en'` catalog to keep in sync.
8
+ */
9
+ export declare const DEFAULT_LOCALE = "en";
10
+ /**
11
+ * Register or extend a locale catalog. Merges with any existing entries for
12
+ * that locale (new entries win), so hosts can override individual codes — pass
13
+ * the default locale to override the base copy.
14
+ */
15
+ export declare function registerCatalog(locale: string, catalog: MessageCatalog): void;
16
+ /**
17
+ * Render a localized message for a code.
18
+ *
19
+ * Resolution order:
20
+ * 1. requested-locale overlay entry (template) → interpolate
21
+ * 2. registry default message (template → interpolate, or function → call)
22
+ * 3. humanized code
23
+ */
24
+ export declare function format(code: string, context?: ErrorContext, locale?: string): string;
package/esm/format.js ADDED
@@ -0,0 +1,54 @@
1
+ import { interpolate } from './interpolate';
2
+ import { getDefinition } from './registry';
3
+ /**
4
+ * Locale to use when `format` is called without one. This is a plain fallback
5
+ * label, not a special catalog: the untagged default copy lives in the registry
6
+ * itself, so there is no built-in `'en'` catalog to keep in sync.
7
+ */
8
+ export const DEFAULT_LOCALE = 'en';
9
+ /**
10
+ * Registered locale overlays. Empty by default — the base/default message for
11
+ * every code is the registry entry, so a locale only needs entries for the
12
+ * codes it actually translates.
13
+ */
14
+ const catalogs = {};
15
+ /**
16
+ * Register or extend a locale catalog. Merges with any existing entries for
17
+ * that locale (new entries win), so hosts can override individual codes — pass
18
+ * the default locale to override the base copy.
19
+ */
20
+ export function registerCatalog(locale, catalog) {
21
+ catalogs[locale] = { ...catalogs[locale], ...catalog };
22
+ }
23
+ /** Humanize a code as a last-resort message, e.g. `LIMIT_REACHED` → `Limit reached`. */
24
+ function humanize(code) {
25
+ const lower = code.toLowerCase().replace(/_/g, ' ');
26
+ return lower.charAt(0).toUpperCase() + lower.slice(1);
27
+ }
28
+ /** The registry's default message for a code (string template or function). */
29
+ function defaultMessage(code, context) {
30
+ const def = getDefinition(code);
31
+ if (def) {
32
+ if (typeof def.message === 'string')
33
+ return interpolate(def.message, context);
34
+ if (typeof def.message === 'function') {
35
+ return def.message(context);
36
+ }
37
+ }
38
+ return humanize(code);
39
+ }
40
+ /**
41
+ * Render a localized message for a code.
42
+ *
43
+ * Resolution order:
44
+ * 1. requested-locale overlay entry (template) → interpolate
45
+ * 2. registry default message (template → interpolate, or function → call)
46
+ * 3. humanized code
47
+ */
48
+ export function format(code, context = {}, locale = DEFAULT_LOCALE) {
49
+ const overlay = catalogs[locale]?.[code];
50
+ if (typeof overlay === 'string') {
51
+ return interpolate(overlay, context);
52
+ }
53
+ return defaultMessage(code, context);
54
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * GENERATED FILE — DO NOT EDIT BY HAND.
3
+ *
4
+ * Source of truth: the constructive-db error audit (289 distinct codes
5
+ * raised via EXCEPTION/THROW across deploy sources + generated output).
6
+ * Regenerate with `python3 scripts/generate-registry.py` (see README.md).
7
+ *
8
+ * Public copy is seeded from the dashboard error catalogs; developer/invariant
9
+ * codes carry their raw message (with %-args rendered as {{argN}}). Curated
10
+ * entries in `registry.ts` override anything here (typed context + refined copy).
11
+ *
12
+ * Counts: 289 total, 82 public, 207 internal.
13
+ */
14
+ import { type DefinedError } from '../define';
15
+ import type { ErrorContext } from '../types';
16
+ export interface GeneratedCodeMeta {
17
+ class: 'public' | 'internal';
18
+ dynamic: boolean;
19
+ /** True when the code is only emitted by DB code generators (no hand source). */
20
+ generatedOnly: boolean;
21
+ }
22
+ /** Every constructive-db error code, keyed by code. */
23
+ export declare const generatedRegistry: Record<string, DefinedError<ErrorContext>>;
24
+ /** Audit metadata for each generated code. */
25
+ export declare const GENERATED_CODE_META: Record<string, GeneratedCodeMeta>;
26
+ /** Total number of codes collected from constructive-db. */
27
+ export declare const GENERATED_CODE_COUNT = 289;