@smonn/ids 0.5.0 → 0.6.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 (42) hide show
  1. package/README.md +400 -18
  2. package/dist/cli.mjs +195 -16
  3. package/dist/cli.mjs.map +1 -1
  4. package/dist/drizzle-CeSni5PB.d.mts +44 -0
  5. package/dist/drizzle-CeSni5PB.d.mts.map +1 -0
  6. package/dist/drizzle.d.mts +2 -0
  7. package/dist/drizzle.mjs +42 -0
  8. package/dist/drizzle.mjs.map +1 -0
  9. package/dist/express.d.mts +92 -0
  10. package/dist/express.d.mts.map +1 -0
  11. package/dist/express.mjs +90 -0
  12. package/dist/express.mjs.map +1 -0
  13. package/dist/hono.d.mts +75 -0
  14. package/dist/hono.d.mts.map +1 -0
  15. package/dist/hono.mjs +63 -0
  16. package/dist/hono.mjs.map +1 -0
  17. package/dist/kysely.d.mts +55 -0
  18. package/dist/kysely.d.mts.map +1 -0
  19. package/dist/kysely.mjs +42 -0
  20. package/dist/kysely.mjs.map +1 -0
  21. package/dist/{opaque-B4ps7Pqk.mjs → opaque-goLnFoo7.mjs} +29 -13
  22. package/dist/opaque-goLnFoo7.mjs.map +1 -0
  23. package/dist/opaque.d.mts +33 -9
  24. package/dist/opaque.d.mts.map +1 -1
  25. package/dist/opaque.mjs +1 -1
  26. package/dist/prisma.d.mts +84 -0
  27. package/dist/prisma.d.mts.map +1 -0
  28. package/dist/prisma.mjs +53 -0
  29. package/dist/prisma.mjs.map +1 -0
  30. package/dist/reverse--n4D2yxu.mjs +87 -0
  31. package/dist/reverse--n4D2yxu.mjs.map +1 -0
  32. package/dist/reverse.d.mts +76 -0
  33. package/dist/reverse.d.mts.map +1 -0
  34. package/dist/reverse.mjs +2 -0
  35. package/dist/wrapped-Dw5mHQhn.mjs +363 -0
  36. package/dist/wrapped-Dw5mHQhn.mjs.map +1 -0
  37. package/dist/wrapped.d.mts +86 -8
  38. package/dist/wrapped.d.mts.map +1 -1
  39. package/dist/wrapped.mjs +1 -335
  40. package/package.json +38 -3
  41. package/dist/opaque-B4ps7Pqk.mjs.map +0 -1
  42. package/dist/wrapped.mjs.map +0 -1
@@ -0,0 +1,92 @@
1
+ import { i as ParseResult, t as Id } from "./types-g7CiQDyE.mjs";
2
+ import { NextFunction, Request, Response } from "express";
3
+
4
+ //#region src/express.d.ts
5
+ type IdCodec<Brand extends string> = {
6
+ safeParse(value: unknown): ParseResult<Brand>;
7
+ };
8
+ /** Discriminated failure value passed to `onError` and emitted to Express error pipeline via `next(err)`. */
9
+ type IdParamFailure = {
10
+ readonly reason: "brand_mismatch";
11
+ readonly status: number;
12
+ } | {
13
+ readonly reason: "malformed";
14
+ readonly status: number;
15
+ };
16
+ /**
17
+ * Typed error forwarded to Express's error pipeline (`next(err)`) on validation failure.
18
+ * Inspect `err.reason` and `err.status` in error-handling middleware.
19
+ */
20
+ declare class IdParamError extends Error {
21
+ readonly status: number;
22
+ readonly reason: "brand_mismatch" | "malformed";
23
+ constructor(reason: "brand_mismatch" | "malformed", status: number);
24
+ }
25
+ /** Options for `idParam`. All fields are optional. */
26
+ type IdParamOptions = {
27
+ /**
28
+ * Called instead of forwarding to `next(err)` when provided. The hook owns the response
29
+ * entirely — the adapter does not call `next(err)` itself.
30
+ */
31
+ onError?: (failure: IdParamFailure, req: Request, res: Response, next: NextFunction) => void;
32
+ /**
33
+ * Remap the default HTTP status for a failure reason without a full handler.
34
+ * e.g. `{ brand_mismatch: 400 }` treats both failure kinds as 400.
35
+ */
36
+ status?: {
37
+ brand_mismatch?: number;
38
+ malformed?: number;
39
+ };
40
+ };
41
+ /**
42
+ * Express middleware that validates a named route param against a codec via `safeParse`.
43
+ *
44
+ * **Default (no options):** calls `next(err)` with an `IdParamError` carrying `status` and `reason`,
45
+ * so the app's existing error-handling middleware controls rendering. The adapter does not write
46
+ * a response body itself.
47
+ *
48
+ * **`options.onError`:** when provided, the hook owns the response entirely — the adapter does
49
+ * not call `next(err)`.
50
+ *
51
+ * **`options.status`:** remaps the default HTTP status for a reason without a full handler.
52
+ *
53
+ * - **Brand mismatch (`invalid_prefix`) → `reason: "brand_mismatch"`, default 404**
54
+ * - **Malformed or missing ID → `reason: "malformed"`, default 400**
55
+ *
56
+ * On success, stores the canonical `Id<Brand>` in `res.locals` under `paramName`
57
+ * and calls `next()`.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * import { idParam, IdParamError } from "@smonn/ids/express";
62
+ * import { createTimestampId } from "@smonn/ids";
63
+ *
64
+ * const usr = createTimestampId("usr");
65
+ *
66
+ * // Default: forwards error to app error-handling middleware
67
+ * app.get("/users/:id", idParam("id", usr), (req, res) => {
68
+ * const id = res.locals.id; // Id<"usr">, canonical
69
+ * });
70
+ *
71
+ * // Error-handling middleware receives the typed error
72
+ * app.use((err, req, res, next) => {
73
+ * if (err instanceof IdParamError) {
74
+ * res.status(err.status).json({ error: err.reason });
75
+ * return;
76
+ * }
77
+ * next(err);
78
+ * });
79
+ *
80
+ * // Override: consumer fully owns the response
81
+ * app.get("/orgs/:id", idParam("id", org, {
82
+ * onError: (failure, req, res) => res.status(failure.status).json({ error: failure.reason }),
83
+ * }), handler);
84
+ *
85
+ * // Or a lightweight status remap without a full handler
86
+ * app.get("/things/:id", idParam("id", thing, { status: { brand_mismatch: 400 } }), handler);
87
+ * ```
88
+ */
89
+ declare function idParam<ParamKey extends string, Brand extends string>(paramName: ParamKey, codec: IdCodec<Brand>, options?: IdParamOptions): (req: Request, res: Response<unknown, Record<ParamKey, Id<Brand>>>, next: NextFunction) => void;
90
+ //#endregion
91
+ export { IdParamError, IdParamFailure, IdParamOptions, idParam };
92
+ //# sourceMappingURL=express.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"express.d.mts","names":[],"sources":["../src/express.ts"],"mappings":";;;;KAGK,OAAA;EACH,SAAA,CAAU,KAAA,YAAiB,WAAA,CAAY,KAAA;AAAA;;KAI7B,cAAA;EAAA,SACG,MAAA;EAAA,SAAmC,MAAA;AAAA;EAAA,SACnC,MAAA;EAAA,SAA8B,MAAA;AAAA;;AANJ;AAIzC;;cAQa,YAAA,SAAqB,KAAA;EAAA,SACvB,MAAA;EAAA,SACA,MAAA;EAET,WAAA,CAAY,MAAA,kCAAwC,MAAA;AAAA;;KAS1C,cAAA;EAnBiC;AAM7C;;;EAkBE,OAAA,IAAW,OAAA,EAAS,cAAA,EAAgB,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,YAAA;;;;;EAKvE,MAAA;IAAW,cAAA;IAAyB,SAAA;EAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;AAAA;AAmDtC;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,OAAA,gDACd,SAAA,EAAW,QAAA,EACX,KAAA,EAAO,OAAA,CAAQ,KAAA,GACf,OAAA,GAAU,cAAA,IACR,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,QAAA,UAAkB,MAAA,CAAO,QAAA,EAAU,EAAA,CAAG,KAAA,KAAU,IAAA,EAAM,YAAA"}
@@ -0,0 +1,90 @@
1
+ //#region src/express.ts
2
+ /**
3
+ * Typed error forwarded to Express's error pipeline (`next(err)`) on validation failure.
4
+ * Inspect `err.reason` and `err.status` in error-handling middleware.
5
+ */
6
+ var IdParamError = class extends Error {
7
+ status;
8
+ reason;
9
+ constructor(reason, status) {
10
+ super(`ID validation failed: ${reason}`);
11
+ this.name = "IdParamError";
12
+ this.reason = reason;
13
+ this.status = status;
14
+ }
15
+ };
16
+ /**
17
+ * Express middleware that validates a named route param against a codec via `safeParse`.
18
+ *
19
+ * **Default (no options):** calls `next(err)` with an `IdParamError` carrying `status` and `reason`,
20
+ * so the app's existing error-handling middleware controls rendering. The adapter does not write
21
+ * a response body itself.
22
+ *
23
+ * **`options.onError`:** when provided, the hook owns the response entirely — the adapter does
24
+ * not call `next(err)`.
25
+ *
26
+ * **`options.status`:** remaps the default HTTP status for a reason without a full handler.
27
+ *
28
+ * - **Brand mismatch (`invalid_prefix`) → `reason: "brand_mismatch"`, default 404**
29
+ * - **Malformed or missing ID → `reason: "malformed"`, default 400**
30
+ *
31
+ * On success, stores the canonical `Id<Brand>` in `res.locals` under `paramName`
32
+ * and calls `next()`.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import { idParam, IdParamError } from "@smonn/ids/express";
37
+ * import { createTimestampId } from "@smonn/ids";
38
+ *
39
+ * const usr = createTimestampId("usr");
40
+ *
41
+ * // Default: forwards error to app error-handling middleware
42
+ * app.get("/users/:id", idParam("id", usr), (req, res) => {
43
+ * const id = res.locals.id; // Id<"usr">, canonical
44
+ * });
45
+ *
46
+ * // Error-handling middleware receives the typed error
47
+ * app.use((err, req, res, next) => {
48
+ * if (err instanceof IdParamError) {
49
+ * res.status(err.status).json({ error: err.reason });
50
+ * return;
51
+ * }
52
+ * next(err);
53
+ * });
54
+ *
55
+ * // Override: consumer fully owns the response
56
+ * app.get("/orgs/:id", idParam("id", org, {
57
+ * onError: (failure, req, res) => res.status(failure.status).json({ error: failure.reason }),
58
+ * }), handler);
59
+ *
60
+ * // Or a lightweight status remap without a full handler
61
+ * app.get("/things/:id", idParam("id", thing, { status: { brand_mismatch: 400 } }), handler);
62
+ * ```
63
+ */
64
+ function idParam(paramName, codec, options) {
65
+ return (req, res, next) => {
66
+ const raw = req.params[paramName];
67
+ const result = codec.safeParse(raw);
68
+ if (!result.ok) {
69
+ const reason = result.error === "invalid_prefix" ? "brand_mismatch" : "malformed";
70
+ const defaultStatus = reason === "brand_mismatch" ? 404 : 400;
71
+ const status = options?.status?.[reason] ?? defaultStatus;
72
+ const failure = {
73
+ reason,
74
+ status
75
+ };
76
+ if (options?.onError) {
77
+ options.onError(failure, req, res, next);
78
+ return;
79
+ }
80
+ next(new IdParamError(reason, status));
81
+ return;
82
+ }
83
+ res.locals[paramName] = result.id;
84
+ next();
85
+ };
86
+ }
87
+ //#endregion
88
+ export { IdParamError, idParam };
89
+
90
+ //# sourceMappingURL=express.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"express.mjs","names":[],"sources":["../src/express.ts"],"sourcesContent":["import type { NextFunction, Request, Response } from \"express\";\nimport type { Id, ParseResult } from \"./types.js\";\n\ntype IdCodec<Brand extends string> = {\n safeParse(value: unknown): ParseResult<Brand>;\n};\n\n/** Discriminated failure value passed to `onError` and emitted to Express error pipeline via `next(err)`. */\nexport type IdParamFailure =\n | { readonly reason: \"brand_mismatch\"; readonly status: number }\n | { readonly reason: \"malformed\"; readonly status: number };\n\n/**\n * Typed error forwarded to Express's error pipeline (`next(err)`) on validation failure.\n * Inspect `err.reason` and `err.status` in error-handling middleware.\n */\nexport class IdParamError extends Error {\n readonly status: number;\n readonly reason: \"brand_mismatch\" | \"malformed\";\n\n constructor(reason: \"brand_mismatch\" | \"malformed\", status: number) {\n super(`ID validation failed: ${reason}`);\n this.name = \"IdParamError\";\n this.reason = reason;\n this.status = status;\n }\n}\n\n/** Options for `idParam`. All fields are optional. */\nexport type IdParamOptions = {\n /**\n * Called instead of forwarding to `next(err)` when provided. The hook owns the response\n * entirely — the adapter does not call `next(err)` itself.\n */\n onError?: (failure: IdParamFailure, req: Request, res: Response, next: NextFunction) => void;\n /**\n * Remap the default HTTP status for a failure reason without a full handler.\n * e.g. `{ brand_mismatch: 400 }` treats both failure kinds as 400.\n */\n status?: { brand_mismatch?: number; malformed?: number };\n};\n\n/**\n * Express middleware that validates a named route param against a codec via `safeParse`.\n *\n * **Default (no options):** calls `next(err)` with an `IdParamError` carrying `status` and `reason`,\n * so the app's existing error-handling middleware controls rendering. The adapter does not write\n * a response body itself.\n *\n * **`options.onError`:** when provided, the hook owns the response entirely — the adapter does\n * not call `next(err)`.\n *\n * **`options.status`:** remaps the default HTTP status for a reason without a full handler.\n *\n * - **Brand mismatch (`invalid_prefix`) → `reason: \"brand_mismatch\"`, default 404**\n * - **Malformed or missing ID → `reason: \"malformed\"`, default 400**\n *\n * On success, stores the canonical `Id<Brand>` in `res.locals` under `paramName`\n * and calls `next()`.\n *\n * @example\n * ```ts\n * import { idParam, IdParamError } from \"@smonn/ids/express\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n *\n * // Default: forwards error to app error-handling middleware\n * app.get(\"/users/:id\", idParam(\"id\", usr), (req, res) => {\n * const id = res.locals.id; // Id<\"usr\">, canonical\n * });\n *\n * // Error-handling middleware receives the typed error\n * app.use((err, req, res, next) => {\n * if (err instanceof IdParamError) {\n * res.status(err.status).json({ error: err.reason });\n * return;\n * }\n * next(err);\n * });\n *\n * // Override: consumer fully owns the response\n * app.get(\"/orgs/:id\", idParam(\"id\", org, {\n * onError: (failure, req, res) => res.status(failure.status).json({ error: failure.reason }),\n * }), handler);\n *\n * // Or a lightweight status remap without a full handler\n * app.get(\"/things/:id\", idParam(\"id\", thing, { status: { brand_mismatch: 400 } }), handler);\n * ```\n */\nexport function idParam<ParamKey extends string, Brand extends string>(\n paramName: ParamKey,\n codec: IdCodec<Brand>,\n options?: IdParamOptions,\n): (req: Request, res: Response<unknown, Record<ParamKey, Id<Brand>>>, next: NextFunction) => void {\n return (req, res, next): void => {\n const raw = req.params[paramName];\n const result = codec.safeParse(raw);\n if (!result.ok) {\n const reason =\n result.error === \"invalid_prefix\" ? (\"brand_mismatch\" as const) : (\"malformed\" as const);\n const defaultStatus = reason === \"brand_mismatch\" ? 404 : 400;\n const status = options?.status?.[reason] ?? defaultStatus;\n const failure: IdParamFailure = { reason, status };\n if (options?.onError) {\n options.onError(failure, req, res, next);\n return;\n }\n next(new IdParamError(reason, status));\n return;\n }\n (res.locals as Record<string, unknown>)[paramName] = result.id;\n next();\n };\n}\n"],"mappings":";;;;;AAgBA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CAEA,YAAY,QAAwC,QAAgB;EAClE,MAAM,yBAAyB,QAAQ;EACvC,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,QACd,WACA,OACA,SACiG;CACjG,QAAQ,KAAK,KAAK,SAAe;EAC/B,MAAM,MAAM,IAAI,OAAO;EACvB,MAAM,SAAS,MAAM,UAAU,GAAG;EAClC,IAAI,CAAC,OAAO,IAAI;GACd,MAAM,SACJ,OAAO,UAAU,mBAAoB,mBAA8B;GACrE,MAAM,gBAAgB,WAAW,mBAAmB,MAAM;GAC1D,MAAM,SAAS,SAAS,SAAS,WAAW;GAC5C,MAAM,UAA0B;IAAE;IAAQ;GAAO;GACjD,IAAI,SAAS,SAAS;IACpB,QAAQ,QAAQ,SAAS,KAAK,KAAK,IAAI;IACvC;GACF;GACA,KAAK,IAAI,aAAa,QAAQ,MAAM,CAAC;GACrC;EACF;EACA,IAAK,OAAmC,aAAa,OAAO;EAC5D,KAAK;CACP;AACF"}
@@ -0,0 +1,75 @@
1
+ import { i as ParseResult, t as Id } from "./types-g7CiQDyE.mjs";
2
+ import { Context, MiddlewareHandler } from "hono";
3
+
4
+ //#region src/hono.d.ts
5
+ type IdCodec<Brand extends string> = {
6
+ safeParse(value: unknown): ParseResult<Brand>;
7
+ };
8
+ /** Discriminated failure value passed to `onError` and emitted to `app.onError` via HTTPException. */
9
+ type IdParamFailure = {
10
+ readonly reason: "brand_mismatch";
11
+ readonly status: number;
12
+ } | {
13
+ readonly reason: "malformed";
14
+ readonly status: number;
15
+ };
16
+ /** Options for `idParam`. All fields are optional. */
17
+ type IdParamOptions = {
18
+ /**
19
+ * Called instead of throwing when provided. The hook owns the response entirely —
20
+ * the adapter neither throws nor writes a body.
21
+ */
22
+ onError?: (failure: IdParamFailure, c: Context) => Response | Promise<Response>;
23
+ /**
24
+ * Remap the default HTTP status for a failure reason without a full handler.
25
+ * e.g. `{ brand_mismatch: 400 }` treats both failure kinds as 400.
26
+ */
27
+ status?: {
28
+ brand_mismatch?: number;
29
+ malformed?: number;
30
+ };
31
+ };
32
+ /**
33
+ * Hono middleware that validates a named route param against a codec via `safeParse`.
34
+ *
35
+ * **Default (no options):** throws `HTTPException(status)` so the app's existing `onError` handler
36
+ * controls rendering and content negotiation. The adapter does not write a response body itself.
37
+ *
38
+ * **`options.onError`:** when provided, the hook owns the response entirely — the adapter neither
39
+ * throws nor writes a response.
40
+ *
41
+ * **`options.status`:** remaps the default HTTP status for a reason without a full handler.
42
+ *
43
+ * - **Brand mismatch (`invalid_prefix`) → `reason: "brand_mismatch"`, default 404**
44
+ * - **Malformed or missing ID → `reason: "malformed"`, default 400**
45
+ *
46
+ * On success, stores the canonical `Id<Brand>` in the Hono context under `paramName`
47
+ * and calls `next()`.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * import { idParam } from "@smonn/ids/hono";
52
+ * import { createTimestampId } from "@smonn/ids";
53
+ *
54
+ * const usr = createTimestampId("usr");
55
+ *
56
+ * // Default: throws HTTPException → app.onError renders it
57
+ * app.get("/users/:id", idParam("id", usr), (c) => {
58
+ * const id = c.get("id"); // Id<"usr">, canonical
59
+ * });
60
+ *
61
+ * // Override: consumer fully owns the response
62
+ * app.get("/orgs/:id", idParam("id", org, {
63
+ * onError: (failure, c) => c.json({ error: failure.reason }, failure.status),
64
+ * }), handler);
65
+ *
66
+ * // Or a lightweight status remap without a full handler
67
+ * app.get("/things/:id", idParam("id", thing, { status: { brand_mismatch: 400 } }), handler);
68
+ * ```
69
+ */
70
+ declare function idParam<ParamKey extends string, Brand extends string>(paramName: ParamKey, codec: IdCodec<Brand>, options?: IdParamOptions): MiddlewareHandler<{
71
+ Variables: Record<ParamKey, Id<Brand>>;
72
+ }>;
73
+ //#endregion
74
+ export { IdParamFailure, IdParamOptions, idParam };
75
+ //# sourceMappingURL=hono.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hono.d.mts","names":[],"sources":["../src/hono.ts"],"mappings":";;;;KAIK,OAAA;EACH,SAAA,CAAU,KAAA,YAAiB,WAAA,CAAY,KAAA;AAAA;;KAI7B,cAAA;EAAA,SACG,MAAA;EAAA,SAAmC,MAAA;AAAA;EAAA,SACnC,MAAA;EAAA,SAA8B,MAAA;AAAA;;KAGjC,cAAA;EALZ;;;;EAUE,OAAA,IAAW,OAAA,EAAS,cAAA,EAAgB,CAAA,EAAG,OAAA,KAAY,QAAA,GAAW,OAAA,CAAQ,QAAA;;;;;EAKtE,MAAA;IAAW,cAAA;IAAyB,SAAA;EAAA;AAAA;;;;;;;;;;;;;;;;;;;AAAA;AAyCtC;;;;;;;;;;;;;;;;;;;iBAAgB,OAAA,gDACd,SAAA,EAAW,QAAA,EACX,KAAA,EAAO,OAAA,CAAQ,KAAA,GACf,OAAA,GAAU,cAAA,GACT,iBAAA;EAAoB,SAAA,EAAW,MAAA,CAAO,QAAA,EAAU,EAAA,CAAG,KAAA;AAAA"}
package/dist/hono.mjs ADDED
@@ -0,0 +1,63 @@
1
+ import { HTTPException } from "hono/http-exception";
2
+ //#region src/hono.ts
3
+ /**
4
+ * Hono middleware that validates a named route param against a codec via `safeParse`.
5
+ *
6
+ * **Default (no options):** throws `HTTPException(status)` so the app's existing `onError` handler
7
+ * controls rendering and content negotiation. The adapter does not write a response body itself.
8
+ *
9
+ * **`options.onError`:** when provided, the hook owns the response entirely — the adapter neither
10
+ * throws nor writes a response.
11
+ *
12
+ * **`options.status`:** remaps the default HTTP status for a reason without a full handler.
13
+ *
14
+ * - **Brand mismatch (`invalid_prefix`) → `reason: "brand_mismatch"`, default 404**
15
+ * - **Malformed or missing ID → `reason: "malformed"`, default 400**
16
+ *
17
+ * On success, stores the canonical `Id<Brand>` in the Hono context under `paramName`
18
+ * and calls `next()`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { idParam } from "@smonn/ids/hono";
23
+ * import { createTimestampId } from "@smonn/ids";
24
+ *
25
+ * const usr = createTimestampId("usr");
26
+ *
27
+ * // Default: throws HTTPException → app.onError renders it
28
+ * app.get("/users/:id", idParam("id", usr), (c) => {
29
+ * const id = c.get("id"); // Id<"usr">, canonical
30
+ * });
31
+ *
32
+ * // Override: consumer fully owns the response
33
+ * app.get("/orgs/:id", idParam("id", org, {
34
+ * onError: (failure, c) => c.json({ error: failure.reason }, failure.status),
35
+ * }), handler);
36
+ *
37
+ * // Or a lightweight status remap without a full handler
38
+ * app.get("/things/:id", idParam("id", thing, { status: { brand_mismatch: 400 } }), handler);
39
+ * ```
40
+ */
41
+ function idParam(paramName, codec, options) {
42
+ return async (c, next) => {
43
+ const raw = c.req.param(paramName);
44
+ const result = codec.safeParse(raw);
45
+ if (!result.ok) {
46
+ const reason = result.error === "invalid_prefix" ? "brand_mismatch" : "malformed";
47
+ const defaultStatus = reason === "brand_mismatch" ? 404 : 400;
48
+ const status = options?.status?.[reason] ?? defaultStatus;
49
+ const failure = {
50
+ reason,
51
+ status
52
+ };
53
+ if (options?.onError) return options.onError(failure, c);
54
+ throw new HTTPException(status);
55
+ }
56
+ c.set(paramName, result.id);
57
+ await next();
58
+ };
59
+ }
60
+ //#endregion
61
+ export { idParam };
62
+
63
+ //# sourceMappingURL=hono.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hono.mjs","names":[],"sources":["../src/hono.ts"],"sourcesContent":["import { HTTPException } from \"hono/http-exception\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport type { Id, ParseResult } from \"./types.js\";\n\ntype IdCodec<Brand extends string> = {\n safeParse(value: unknown): ParseResult<Brand>;\n};\n\n/** Discriminated failure value passed to `onError` and emitted to `app.onError` via HTTPException. */\nexport type IdParamFailure =\n | { readonly reason: \"brand_mismatch\"; readonly status: number }\n | { readonly reason: \"malformed\"; readonly status: number };\n\n/** Options for `idParam`. All fields are optional. */\nexport type IdParamOptions = {\n /**\n * Called instead of throwing when provided. The hook owns the response entirely —\n * the adapter neither throws nor writes a body.\n */\n onError?: (failure: IdParamFailure, c: Context) => Response | Promise<Response>;\n /**\n * Remap the default HTTP status for a failure reason without a full handler.\n * e.g. `{ brand_mismatch: 400 }` treats both failure kinds as 400.\n */\n status?: { brand_mismatch?: number; malformed?: number };\n};\n\n/**\n * Hono middleware that validates a named route param against a codec via `safeParse`.\n *\n * **Default (no options):** throws `HTTPException(status)` so the app's existing `onError` handler\n * controls rendering and content negotiation. The adapter does not write a response body itself.\n *\n * **`options.onError`:** when provided, the hook owns the response entirely — the adapter neither\n * throws nor writes a response.\n *\n * **`options.status`:** remaps the default HTTP status for a reason without a full handler.\n *\n * - **Brand mismatch (`invalid_prefix`) → `reason: \"brand_mismatch\"`, default 404**\n * - **Malformed or missing ID → `reason: \"malformed\"`, default 400**\n *\n * On success, stores the canonical `Id<Brand>` in the Hono context under `paramName`\n * and calls `next()`.\n *\n * @example\n * ```ts\n * import { idParam } from \"@smonn/ids/hono\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n *\n * // Default: throws HTTPException → app.onError renders it\n * app.get(\"/users/:id\", idParam(\"id\", usr), (c) => {\n * const id = c.get(\"id\"); // Id<\"usr\">, canonical\n * });\n *\n * // Override: consumer fully owns the response\n * app.get(\"/orgs/:id\", idParam(\"id\", org, {\n * onError: (failure, c) => c.json({ error: failure.reason }, failure.status),\n * }), handler);\n *\n * // Or a lightweight status remap without a full handler\n * app.get(\"/things/:id\", idParam(\"id\", thing, { status: { brand_mismatch: 400 } }), handler);\n * ```\n */\nexport function idParam<ParamKey extends string, Brand extends string>(\n paramName: ParamKey,\n codec: IdCodec<Brand>,\n options?: IdParamOptions,\n): MiddlewareHandler<{ Variables: Record<ParamKey, Id<Brand>> }> {\n return async (c, next) => {\n const raw = c.req.param(paramName);\n const result = codec.safeParse(raw);\n if (!result.ok) {\n const reason =\n result.error === \"invalid_prefix\" ? (\"brand_mismatch\" as const) : (\"malformed\" as const);\n const defaultStatus = reason === \"brand_mismatch\" ? 404 : 400;\n const status = options?.status?.[reason] ?? defaultStatus;\n const failure: IdParamFailure = { reason, status };\n if (options?.onError) {\n return options.onError(failure, c);\n }\n throw new HTTPException(status as ConstructorParameters<typeof HTTPException>[0]);\n }\n c.set(paramName, result.id);\n await next();\n return;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAgB,QACd,WACA,OACA,SAC+D;CAC/D,OAAO,OAAO,GAAG,SAAS;EACxB,MAAM,MAAM,EAAE,IAAI,MAAM,SAAS;EACjC,MAAM,SAAS,MAAM,UAAU,GAAG;EAClC,IAAI,CAAC,OAAO,IAAI;GACd,MAAM,SACJ,OAAO,UAAU,mBAAoB,mBAA8B;GACrE,MAAM,gBAAgB,WAAW,mBAAmB,MAAM;GAC1D,MAAM,SAAS,SAAS,SAAS,WAAW;GAC5C,MAAM,UAA0B;IAAE;IAAQ;GAAO;GACjD,IAAI,SAAS,SACX,OAAO,QAAQ,QAAQ,SAAS,CAAC;GAEnC,MAAM,IAAI,cAAc,MAAwD;EAClF;EACA,EAAE,IAAI,WAAW,OAAO,EAAE;EAC1B,MAAM,KAAK;CAEb;AACF"}
@@ -0,0 +1,55 @@
1
+ import { t as Id } from "./types-g7CiQDyE.mjs";
2
+ import { t as IdColumnCodec } from "./drizzle-CeSni5PB.mjs";
3
+ import { ColumnType } from "kysely";
4
+
5
+ //#region src/kysely.d.ts
6
+ /**
7
+ * Kysely column type mapping for `Id<Brand>`.
8
+ *
9
+ * Use this in your Kysely `Database` interface to type a column as `Id<Brand>` at
10
+ * the TypeScript level. Pair it with `idColumn(codec)` for runtime read/write
11
+ * transformation.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import type { IdColumnType } from "@smonn/ids/kysely";
16
+ * import type { Id } from "@smonn/ids";
17
+ *
18
+ * interface Database {
19
+ * users: { id: IdColumnType<"usr"> };
20
+ * }
21
+ * ```
22
+ */
23
+ type IdColumnType<Brand extends string> = ColumnType<Id<Brand>, Id<Brand>, Id<Brand>>;
24
+ /**
25
+ * Kysely column adapter bound to a codec.
26
+ *
27
+ * Returns an object with `fromDriver` / `toDriver` helpers that mirror the read/write
28
+ * contract of the Drizzle adapter — same error message, same strictness (safeParse on
29
+ * read, identity on write).
30
+ *
31
+ * **Write path:** passes the `Id<Brand>` directly to the driver — it is already
32
+ * the canonical string form.
33
+ *
34
+ * **Read path:** normalises the raw DB string via `codec.safeParse()`. Throws if
35
+ * the value does not parse as a valid `Id<Brand>`.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { idColumn } from "@smonn/ids/kysely";
40
+ * import { createTimestampId } from "@smonn/ids";
41
+ *
42
+ * const usr = createTimestampId("usr");
43
+ * const usrCol = idColumn(usr);
44
+ *
45
+ * // In a query result handler:
46
+ * const id = usrCol.fromDriver(row.id);
47
+ * ```
48
+ */
49
+ declare function idColumn<Brand extends string>(codec: IdColumnCodec<Brand>): {
50
+ toDriver(value: Id<Brand>): string;
51
+ fromDriver(value: string): Id<Brand>;
52
+ };
53
+ //#endregion
54
+ export { type IdColumnCodec, IdColumnType, idColumn };
55
+ //# sourceMappingURL=kysely.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kysely.d.mts","names":[],"sources":["../src/kysely.ts"],"mappings":";;;;;;AAuBA;;;;;;;;;;;;;;;;KAAY,YAAA,yBAAqC,UAAA,CAAW,EAAA,CAAG,KAAA,GAAQ,EAAA,CAAG,KAAA,GAAQ,EAAA,CAAG,KAAA;;;;;AAAA;AA2BrF;;;;;;;;;;;;;;;;;;;;iBAAgB,QAAA,uBACd,KAAA,EAAO,aAAA,CAAc,KAAA;EAErB,QAAA,CAAS,KAAA,EAAO,EAAA,CAAG,KAAA;EACnB,UAAA,CAAW,KAAA,WAAgB,EAAA,CAAG,KAAA;AAAA"}
@@ -0,0 +1,42 @@
1
+ //#region src/kysely.ts
2
+ /**
3
+ * Kysely column adapter bound to a codec.
4
+ *
5
+ * Returns an object with `fromDriver` / `toDriver` helpers that mirror the read/write
6
+ * contract of the Drizzle adapter — same error message, same strictness (safeParse on
7
+ * read, identity on write).
8
+ *
9
+ * **Write path:** passes the `Id<Brand>` directly to the driver — it is already
10
+ * the canonical string form.
11
+ *
12
+ * **Read path:** normalises the raw DB string via `codec.safeParse()`. Throws if
13
+ * the value does not parse as a valid `Id<Brand>`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { idColumn } from "@smonn/ids/kysely";
18
+ * import { createTimestampId } from "@smonn/ids";
19
+ *
20
+ * const usr = createTimestampId("usr");
21
+ * const usrCol = idColumn(usr);
22
+ *
23
+ * // In a query result handler:
24
+ * const id = usrCol.fromDriver(row.id);
25
+ * ```
26
+ */
27
+ function idColumn(codec) {
28
+ return {
29
+ toDriver(value) {
30
+ return value;
31
+ },
32
+ fromDriver(value) {
33
+ const result = codec.safeParse(value);
34
+ if (!result.ok) throw new Error(`[ids] invalid ID from database: ${result.error}`);
35
+ return result.id;
36
+ }
37
+ };
38
+ }
39
+ //#endregion
40
+ export { idColumn };
41
+
42
+ //# sourceMappingURL=kysely.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kysely.mjs","names":[],"sources":["../src/kysely.ts"],"sourcesContent":["import type { ColumnType } from \"kysely\";\nimport type { IdColumnCodec } from \"./drizzle.js\";\nimport type { Id } from \"./types.js\";\n\nexport type { IdColumnCodec } from \"./drizzle.js\";\n\n/**\n * Kysely column type mapping for `Id<Brand>`.\n *\n * Use this in your Kysely `Database` interface to type a column as `Id<Brand>` at\n * the TypeScript level. Pair it with `idColumn(codec)` for runtime read/write\n * transformation.\n *\n * @example\n * ```ts\n * import type { IdColumnType } from \"@smonn/ids/kysely\";\n * import type { Id } from \"@smonn/ids\";\n *\n * interface Database {\n * users: { id: IdColumnType<\"usr\"> };\n * }\n * ```\n */\nexport type IdColumnType<Brand extends string> = ColumnType<Id<Brand>, Id<Brand>, Id<Brand>>;\n\n/**\n * Kysely column adapter bound to a codec.\n *\n * Returns an object with `fromDriver` / `toDriver` helpers that mirror the read/write\n * contract of the Drizzle adapter — same error message, same strictness (safeParse on\n * read, identity on write).\n *\n * **Write path:** passes the `Id<Brand>` directly to the driver — it is already\n * the canonical string form.\n *\n * **Read path:** normalises the raw DB string via `codec.safeParse()`. Throws if\n * the value does not parse as a valid `Id<Brand>`.\n *\n * @example\n * ```ts\n * import { idColumn } from \"@smonn/ids/kysely\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n * const usrCol = idColumn(usr);\n *\n * // In a query result handler:\n * const id = usrCol.fromDriver(row.id);\n * ```\n */\nexport function idColumn<Brand extends string>(\n codec: IdColumnCodec<Brand>,\n): {\n toDriver(value: Id<Brand>): string;\n fromDriver(value: string): Id<Brand>;\n} {\n return {\n toDriver(value: Id<Brand>): string {\n return value;\n },\n fromDriver(value: string): Id<Brand> {\n const result = codec.safeParse(value);\n if (!result.ok) {\n throw new Error(`[ids] invalid ID from database: ${result.error}`);\n }\n return result.id;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,SACd,OAIA;CACA,OAAO;EACL,SAAS,OAA0B;GACjC,OAAO;EACT;EACA,WAAW,OAA0B;GACnC,MAAM,SAAS,MAAM,UAAU,KAAK;GACpC,IAAI,CAAC,OAAO,IACV,MAAM,IAAI,MAAM,mCAAmC,OAAO,OAAO;GAEnE,OAAO,OAAO;EAChB;CACF;AACF"}
@@ -59,6 +59,29 @@ const validAesKeyByteLengths = new Set([
59
59
  24,
60
60
  32
61
61
  ]);
62
+ const opaqueKeyInternals = /* @__PURE__ */ new WeakMap();
63
+ /**
64
+ * Imports raw AES key bytes into an {@link OpaqueKey} handle for the Opaque
65
+ * Timestamp codec.
66
+ *
67
+ * Accepts 16, 24, or 32 bytes (AES-128 / AES-192 / AES-256 strength).
68
+ * To store or transport key material, use {@link encodeOpaqueKey} /
69
+ * {@link decodeOpaqueKey} (`"hex"` or `"base64url"` — not Crockford base32).
70
+ *
71
+ * @param bytes - 16, 24, or 32 raw key bytes.
72
+ */
73
+ async function importOpaqueKey(bytes) {
74
+ assertValidAesKeyByteLength(bytes.length);
75
+ const cryptoKey = await crypto.subtle.importKey("raw", bytes, "AES-CBC", false, ["encrypt", "decrypt"]);
76
+ const key = Object.freeze({});
77
+ opaqueKeyInternals.set(key, cryptoKey);
78
+ return key;
79
+ }
80
+ function getOpaqueKeyCryptoKey(key) {
81
+ const cryptoKey = opaqueKeyInternals.get(key);
82
+ if (cryptoKey === void 0) throw new Error("invalid opaque key");
83
+ return cryptoKey;
84
+ }
62
85
  /**
63
86
  * Encodes raw AES key bytes for storage in env vars or secret managers.
64
87
  *
@@ -111,28 +134,21 @@ function defaultRng(target) {
111
134
  crypto.getRandomValues(target);
112
135
  }
113
136
  /**
114
- * Imports a raw AES key for use with the Opaque Timestamp codec.
115
- *
116
- * @param bytes - Raw key bytes (16, 24, or 32 bytes for AES-128/192/256).
117
- */
118
- function importOpaqueKey(bytes) {
119
- return crypto.subtle.importKey("raw", bytes, "AES-CBC", false, ["encrypt", "decrypt"]);
120
- }
121
- /**
122
137
  * Creates an Opaque Timestamp codec for `brand` (three lowercase a–z characters).
123
138
  *
124
139
  * @param brand - Entity type brand validated once at construction.
125
- * @param opts - Required `key` plus optional `now`, `rng`, and `allowDuplicateBrand` overrides.
140
+ * @param opts - Required `key` (an {@link OpaqueKey} from {@link importOpaqueKey}) plus
141
+ * optional `now`, `rng`, and `allowDuplicateBrand` overrides.
126
142
  */
127
143
  function createOpaqueTimestampId(brand, opts) {
128
144
  validateBrand(brand);
129
145
  registerBrand(brand, opts.allowDuplicateBrand);
130
- const key = opts.key;
146
+ const cryptoKey = getOpaqueKeyCryptoKey(opts.key);
131
147
  const now = opts.now ?? Date.now;
132
148
  const rng = opts.rng ?? defaultRng;
133
149
  const prefix = `${brand}_`;
134
150
  const wire = wireMethods(prefix);
135
- const layout = createOpaqueLayoutOps(prefix, key, rng);
151
+ const layout = createOpaqueLayoutOps(prefix, cryptoKey, rng);
136
152
  return {
137
153
  generate: () => layout.generateAt(now()),
138
154
  generateAt: (date) => layout.generateAt(date.getTime()),
@@ -145,6 +161,6 @@ function createOpaqueTimestampId(brand, opts) {
145
161
  };
146
162
  }
147
163
  //#endregion
148
- export { encodeOpaqueKey as i, importOpaqueKey as n, decodeOpaqueKey as r, createOpaqueTimestampId as t };
164
+ export { importOpaqueKey as i, decodeOpaqueKey as n, encodeOpaqueKey as r, createOpaqueTimestampId as t };
149
165
 
150
- //# sourceMappingURL=opaque-B4ps7Pqk.mjs.map
166
+ //# sourceMappingURL=opaque-goLnFoo7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opaque-goLnFoo7.mjs","names":[],"sources":["../src/layouts/opaque.ts","../src/opaque-key.ts","../src/opaque.ts"],"sourcesContent":["import type { Id, Prefix } from \"../types.js\";\nimport { payloadBytesFromId, toWireId } from \"../wire/envelope.js\";\nimport { payloadBase32Length, payloadByteLength } from \"../wire/invariants.js\";\nimport { readTimestampMs, timestampByteLength, writeTimestamp } from \"../wire/timestamp-bytes.js\";\n\nconst zeroIv = new Uint8Array(payloadByteLength);\nconst pkcsPad = 0x10;\n\nfunction buildPlaintext(ms: number, rng: (target: Uint8Array) => void): Uint8Array {\n const plaintext = new Uint8Array(payloadByteLength);\n writeTimestamp(ms, plaintext);\n rng(plaintext.subarray(timestampByteLength, payloadByteLength));\n return plaintext;\n}\n\nasync function encryptPayload(key: CryptoKey, plaintext: Uint8Array): Promise<Uint8Array> {\n const encrypted = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: \"AES-CBC\", iv: zeroIv },\n key,\n plaintext as Uint8Array<ArrayBuffer>,\n ),\n );\n return encrypted.subarray(0, payloadByteLength);\n}\n\n// AES-CBC strip-and-reconstruct decrypt (ADR-0004). The wire carries only C1\n// (16 bytes); C2 = AES_K(P2 XOR C1) where P2 is the PKCS#7 pad block (0x10×16).\n// Recompute C2 via CBC encrypt of (P2 XOR C1) with IV=0, then decrypt C1‖C2.\nasync function decryptPayload(key: CryptoKey, c1: Uint8Array): Promise<Uint8Array> {\n const c2Input = new Uint8Array(payloadByteLength);\n for (let i = 0; i < payloadByteLength; i++) c2Input[i] = pkcsPad ^ c1[i]!;\n const c2Encrypted = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: \"AES-CBC\", iv: zeroIv },\n key,\n c2Input as Uint8Array<ArrayBuffer>,\n ),\n );\n const ciphertext = new Uint8Array(payloadByteLength * 2);\n ciphertext.set(c1, 0);\n ciphertext.set(c2Encrypted.subarray(0, payloadByteLength), payloadByteLength);\n return new Uint8Array(\n await crypto.subtle.decrypt(\n { name: \"AES-CBC\", iv: zeroIv },\n key,\n ciphertext as Uint8Array<ArrayBuffer>,\n ),\n );\n}\n\nasync function extractTimestampFromId<Brand extends string>(\n prefix: Prefix<Brand>,\n key: CryptoKey,\n id: Id<Brand>,\n): Promise<Date> {\n const plaintext = await decryptPayload(key, payloadBytesFromId(prefix, id));\n return new Date(readTimestampMs(plaintext));\n}\n\n/** Produces a canonical encrypted wire ID. Per-call plaintext/ciphertext buffers —\n * subtle dominates this path; reuse would be safe but not worth pinning to spec detail. */\nasync function generateWireId<Brand extends string>(\n prefix: Prefix<Brand>,\n key: CryptoKey,\n rng: (target: Uint8Array) => void,\n ms: number,\n): Promise<Id<Brand>> {\n const plaintext = buildPlaintext(ms, rng);\n const encrypted = await encryptPayload(key, plaintext);\n return toWireId(prefix, encrypted);\n}\n\n/** Structural placeholder for JSON Schema (encrypt is async). */\nfunction schemaExample<Brand extends string>(prefix: Prefix<Brand>): string {\n return prefix + \"0\".repeat(payloadBase32Length);\n}\n\n/** Layout ops binder for the Opaque Timestamp variant. `extractTimestampFromId` is module-private; the binder exposes `extractTimestamp` for the codec constructor. */\nexport function createOpaqueLayoutOps<Brand extends string>(\n prefix: Prefix<Brand>,\n key: CryptoKey,\n rng: (target: Uint8Array) => void,\n) {\n return {\n generateAt: (ms: number): Promise<Id<Brand>> => generateWireId(prefix, key, rng, ms),\n extractTimestamp: (id: Id<Brand>): Promise<Date> => extractTimestampFromId(prefix, key, id),\n exampleWireId: (): Id<Brand> => schemaExample(prefix) as Id<Brand>,\n };\n}\n","import { decodeBase64Url, decodeHex, encodeBase64Url, encodeHex } from \"./bytes.js\";\n\n/** Wire encoding for opaque AES key material (not Crockford base32). */\nexport type OpaqueKeyFormat = \"hex\" | \"base64url\";\n\nconst validAesKeyByteLengths = new Set([16, 24, 32]);\n\ndeclare const opaqueKeyBrand: unique symbol;\n\n/**\n * Opaque imported handle for one AES key used by the Opaque Timestamp codec.\n *\n * Holds the underlying `CryptoKey` internally; callers never access it directly.\n * Obtain handles via {@link importOpaqueKey} and pass them to\n * `createOpaqueTimestampId` as the `key` option.\n *\n * Distinct from the `WrappingKey` used by `@smonn/ids/wrapped` — one raw\n * secret must not silently serve both codecs without an explicit import.\n */\nexport type OpaqueKey = {\n readonly [opaqueKeyBrand]: \"OpaqueKey\";\n};\n\nconst opaqueKeyInternals = new WeakMap<OpaqueKey, CryptoKey>();\n\n/**\n * Imports raw AES key bytes into an {@link OpaqueKey} handle for the Opaque\n * Timestamp codec.\n *\n * Accepts 16, 24, or 32 bytes (AES-128 / AES-192 / AES-256 strength).\n * To store or transport key material, use {@link encodeOpaqueKey} /\n * {@link decodeOpaqueKey} (`\"hex\"` or `\"base64url\"` — not Crockford base32).\n *\n * @param bytes - 16, 24, or 32 raw key bytes.\n */\nexport async function importOpaqueKey(bytes: Uint8Array): Promise<OpaqueKey> {\n assertValidAesKeyByteLength(bytes.length);\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n bytes as Uint8Array<ArrayBuffer>,\n \"AES-CBC\",\n false,\n [\"encrypt\", \"decrypt\"],\n );\n const key = Object.freeze({}) as OpaqueKey;\n opaqueKeyInternals.set(key, cryptoKey);\n return key;\n}\n\nexport function getOpaqueKeyCryptoKey(key: OpaqueKey): CryptoKey {\n const cryptoKey = opaqueKeyInternals.get(key);\n if (cryptoKey === undefined) {\n throw new Error(\"invalid opaque key\");\n }\n return cryptoKey;\n}\n\n/**\n * Encodes raw AES key bytes for storage in env vars or secret managers.\n *\n * @param bytes - 16, 24, or 32 raw key bytes (AES-128/192/256).\n * @param format - `hex` (lowercase) or `base64url`.\n */\nexport function encodeOpaqueKey(bytes: Uint8Array, format: OpaqueKeyFormat): string {\n assertOpaqueKeyFormat(format);\n assertValidAesKeyByteLength(bytes.length);\n if (format === \"hex\") return encodeHex(bytes);\n return encodeBase64Url(bytes);\n}\n\n/**\n * Decodes key material emitted by `encodeOpaqueKey` (or `ids keygen`) back to raw bytes.\n *\n * @param encoded - Hex or base64url string.\n * @param format - Must match how the string was encoded.\n */\nexport function decodeOpaqueKey(encoded: string, format: OpaqueKeyFormat): Uint8Array {\n assertOpaqueKeyFormat(format);\n let bytes: Uint8Array;\n if (format === \"hex\") {\n if (encoded.length === 0 || encoded.length % 2 !== 0) {\n throw new Error(\"invalid hex key: length must be a positive even number of characters\");\n }\n if (!/^[0-9a-fA-F]+$/.test(encoded)) {\n throw new Error(\"invalid hex key: expected [0-9a-fA-F] only\");\n }\n bytes = decodeHex(encoded);\n } else {\n try {\n bytes = decodeBase64Url(encoded);\n } catch {\n throw new Error(\"invalid base64url key\");\n }\n }\n assertValidAesKeyByteLength(bytes.length);\n return bytes;\n}\n\nfunction assertValidAesKeyByteLength(byteLength: number): void {\n if (!validAesKeyByteLengths.has(byteLength)) {\n throw new Error(`invalid AES key length: expected 16, 24, or 32 bytes, got ${byteLength}`);\n }\n}\n\nfunction assertOpaqueKeyFormat(format: unknown): asserts format is OpaqueKeyFormat {\n if (format !== \"hex\" && format !== \"base64url\") {\n throw new Error(\n `invalid opaque key format: expected hex or base64url, got '${formatForError(format)}'`,\n );\n }\n}\n\nfunction formatForError(value: unknown): string {\n try {\n return String(value);\n } catch {\n return \"[unprintable]\";\n }\n}\n","import { validateBrand } from \"./brand.js\";\nimport { createOpaqueLayoutOps } from \"./layouts/opaque.js\";\nimport { getOpaqueKeyCryptoKey, type OpaqueKey } from \"./opaque-key.js\";\nimport { registerBrand } from \"./registry.js\";\nimport type { Id, JsonSchema, ParseResult, Prefix, StandardSchemaProps } from \"./types.js\";\nimport { wireMethods } from \"./wire/codec-shell.js\";\n\nexport {\n decodeOpaqueKey,\n encodeOpaqueKey,\n importOpaqueKey,\n type OpaqueKey,\n type OpaqueKeyFormat,\n} from \"./opaque-key.js\";\n\n/**\n * Configuration options for an Opaque Timestamp codec instance.\n */\nexport type OpaqueTimestampOptions = {\n /**\n * {@link OpaqueKey} handle for AES-CBC encryption and decryption.\n * Obtain via {@link importOpaqueKey}.\n */\n key: OpaqueKey;\n /** Returns the current timestamp in milliseconds. Defaults to `Date.now`. */\n now?: () => number;\n /** Writes random bytes into `target` for ID generation. Defaults to `crypto.getRandomValues`. */\n rng?: (target: Uint8Array) => void;\n /** If true, silences the duplicate-brand warning in non-production environments. */\n allowDuplicateBrand?: boolean;\n};\n\n/**\n * A brand-scoped codec for generating and validating Opaque Timestamp IDs.\n *\n * Same wire shape as the Timestamp codec (`{brand}_` + 26 base32 chars) but the\n * payload is AES-CBC encrypted. `generate`, `generateAt`, and `extractTimestamp`\n * are async; parsing methods are sync. No `minIdForTime` / `maxIdForTime` —\n * encrypted payloads do not sort by creation time.\n */\nexport type OpaqueTimestampCodec<Brand extends string> = {\n /** Produces a new canonical encrypted ID using the codec's `now` and `rng`. */\n generate(): Promise<Id<Brand>>;\n /** Produces a new canonical encrypted ID with timestamp bytes from `date`. Throws on invalid dates. */\n generateAt(date: Date): Promise<Id<Brand>>;\n /**\n * Strict type guard: `true` only for already-canonical strings for this brand.\n * For untrusted input, use `safeParse()` or `parse()` instead. See ADR-0003.\n */\n is(value: unknown): value is Id<Brand>;\n /**\n * Lenient parse: normalises case and Crockford aliases, returns canonical `Id<Brand>`, or throws.\n */\n parse(value: unknown): Id<Brand>;\n /**\n * Lenient parse without throwing: normalises to canonical form, or returns `{ ok: false, error }`.\n */\n safeParse(value: unknown): ParseResult<Brand>;\n /**\n * Decrypts and decodes the creation `Date` from an `Id<Brand>`. Trusts the type — use `safeParse()` at boundaries first. See ADR-0002.\n */\n extractTimestamp(id: Id<Brand>): Promise<Date>;\n /** JSON Schema for the canonical wire form (`example` is a structural placeholder). */\n toJsonSchema(): JsonSchema;\n /** Standard Schema validate entry point. */\n readonly \"~standard\": StandardSchemaProps<Brand>;\n};\n\nfunction defaultRng(target: Uint8Array): void {\n crypto.getRandomValues(target as Uint8Array<ArrayBuffer>);\n}\n\n/**\n * Creates an Opaque Timestamp codec for `brand` (three lowercase a–z characters).\n *\n * @param brand - Entity type brand validated once at construction.\n * @param opts - Required `key` (an {@link OpaqueKey} from {@link importOpaqueKey}) plus\n * optional `now`, `rng`, and `allowDuplicateBrand` overrides.\n */\nexport function createOpaqueTimestampId<Brand extends string>(\n brand: Brand,\n opts: OpaqueTimestampOptions,\n): OpaqueTimestampCodec<Brand> {\n validateBrand(brand);\n registerBrand(brand, opts.allowDuplicateBrand);\n\n const cryptoKey = getOpaqueKeyCryptoKey(opts.key);\n const now = opts.now ?? Date.now;\n const rng = opts.rng ?? defaultRng;\n const prefix: Prefix<Brand> = `${brand}_`;\n const wire = wireMethods(prefix);\n const layout = createOpaqueLayoutOps(prefix, cryptoKey, rng);\n\n return {\n generate: () => layout.generateAt(now()),\n generateAt: (date: Date) => layout.generateAt(date.getTime()),\n is: wire.is,\n parse: wire.parse,\n safeParse: wire.safeParse,\n extractTimestamp: layout.extractTimestamp,\n toJsonSchema: () => wire.toJsonSchema(brand, layout.exampleWireId()),\n \"~standard\": wire[\"~standard\"],\n };\n}\n"],"mappings":";;;;AAKA,MAAM,SAAS,IAAI,WAAA,EAA4B;AAC/C,MAAM,UAAU;AAEhB,SAAS,eAAe,IAAY,KAA+C;CACjF,MAAM,YAAY,IAAI,WAAA,EAA4B;CAClD,eAAe,IAAI,SAAS;CAC5B,IAAI,UAAU,SAAA,GAAA,EAA+C,CAAC;CAC9D,OAAO;AACT;AAEA,eAAe,eAAe,KAAgB,WAA4C;CAQxF,OAAO,IAPe,WACpB,MAAM,OAAO,OAAO,QAClB;EAAE,MAAM;EAAW,IAAI;CAAO,GAC9B,KACA,SACF,CAEa,CAAC,CAAC,SAAS,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OAAO,gBAAgB,MAAiC;AAC1D;;;;;;;;AASA,SAAgB,wBACd,OACA,MAC6B;CAC7B,cAAc,KAAK;CACnB,cAAc,OAAO,KAAK,mBAAmB;CAE7C,MAAM,YAAY,sBAAsB,KAAK,GAAG;CAChD,MAAM,MAAM,KAAK,OAAO,KAAK;CAC7B,MAAM,MAAM,KAAK,OAAO;CACxB,MAAM,SAAwB,GAAG,MAAM;CACvC,MAAM,OAAO,YAAY,MAAM;CAC/B,MAAM,SAAS,sBAAsB,QAAQ,WAAW,GAAG;CAE3D,OAAO;EACL,gBAAgB,OAAO,WAAW,IAAI,CAAC;EACvC,aAAa,SAAe,OAAO,WAAW,KAAK,QAAQ,CAAC;EAC5D,IAAI,KAAK;EACT,OAAO,KAAK;EACZ,WAAW,KAAK;EAChB,kBAAkB,OAAO;EACzB,oBAAoB,KAAK,aAAa,OAAO,OAAO,cAAc,CAAC;EACnE,aAAa,KAAK;CACpB;AACF"}
package/dist/opaque.d.mts CHANGED
@@ -3,6 +3,31 @@ import { a as StandardSchemaProps, i as ParseResult, n as JsonSchema, t as Id }
3
3
  //#region src/opaque-key.d.ts
4
4
  /** Wire encoding for opaque AES key material (not Crockford base32). */
5
5
  type OpaqueKeyFormat = "hex" | "base64url";
6
+ declare const opaqueKeyBrand: unique symbol;
7
+ /**
8
+ * Opaque imported handle for one AES key used by the Opaque Timestamp codec.
9
+ *
10
+ * Holds the underlying `CryptoKey` internally; callers never access it directly.
11
+ * Obtain handles via {@link importOpaqueKey} and pass them to
12
+ * `createOpaqueTimestampId` as the `key` option.
13
+ *
14
+ * Distinct from the `WrappingKey` used by `@smonn/ids/wrapped` — one raw
15
+ * secret must not silently serve both codecs without an explicit import.
16
+ */
17
+ type OpaqueKey = {
18
+ readonly [opaqueKeyBrand]: "OpaqueKey";
19
+ };
20
+ /**
21
+ * Imports raw AES key bytes into an {@link OpaqueKey} handle for the Opaque
22
+ * Timestamp codec.
23
+ *
24
+ * Accepts 16, 24, or 32 bytes (AES-128 / AES-192 / AES-256 strength).
25
+ * To store or transport key material, use {@link encodeOpaqueKey} /
26
+ * {@link decodeOpaqueKey} (`"hex"` or `"base64url"` — not Crockford base32).
27
+ *
28
+ * @param bytes - 16, 24, or 32 raw key bytes.
29
+ */
30
+ declare function importOpaqueKey(bytes: Uint8Array): Promise<OpaqueKey>;
6
31
  /**
7
32
  * Encodes raw AES key bytes for storage in env vars or secret managers.
8
33
  *
@@ -23,7 +48,11 @@ declare function decodeOpaqueKey(encoded: string, format: OpaqueKeyFormat): Uint
23
48
  * Configuration options for an Opaque Timestamp codec instance.
24
49
  */
25
50
  type OpaqueTimestampOptions = {
26
- /** AES-CBC key used for encryption and decryption. */key: CryptoKey; /** Returns the current timestamp in milliseconds. Defaults to `Date.now`. */
51
+ /**
52
+ * {@link OpaqueKey} handle for AES-CBC encryption and decryption.
53
+ * Obtain via {@link importOpaqueKey}.
54
+ */
55
+ key: OpaqueKey; /** Returns the current timestamp in milliseconds. Defaults to `Date.now`. */
27
56
  now?: () => number; /** Writes random bytes into `target` for ID generation. Defaults to `crypto.getRandomValues`. */
28
57
  rng?: (target: Uint8Array) => void; /** If true, silences the duplicate-brand warning in non-production environments. */
29
58
  allowDuplicateBrand?: boolean;
@@ -60,18 +89,13 @@ type OpaqueTimestampCodec<Brand extends string> = {
60
89
  readonly "~standard": StandardSchemaProps<Brand>;
61
90
  };
62
91
  /**
63
- * Imports a raw AES key for use with the Opaque Timestamp codec.
64
- *
65
- * @param bytes - Raw key bytes (16, 24, or 32 bytes for AES-128/192/256).
66
- */
67
- declare function importOpaqueKey(bytes: Uint8Array): Promise<CryptoKey>;
68
- /**
69
92
  * Creates an Opaque Timestamp codec for `brand` (three lowercase a–z characters).
70
93
  *
71
94
  * @param brand - Entity type brand validated once at construction.
72
- * @param opts - Required `key` plus optional `now`, `rng`, and `allowDuplicateBrand` overrides.
95
+ * @param opts - Required `key` (an {@link OpaqueKey} from {@link importOpaqueKey}) plus
96
+ * optional `now`, `rng`, and `allowDuplicateBrand` overrides.
73
97
  */
74
98
  declare function createOpaqueTimestampId<Brand extends string>(brand: Brand, opts: OpaqueTimestampOptions): OpaqueTimestampCodec<Brand>;
75
99
  //#endregion
76
- export { type OpaqueKeyFormat, OpaqueTimestampCodec, OpaqueTimestampOptions, createOpaqueTimestampId, decodeOpaqueKey, encodeOpaqueKey, importOpaqueKey };
100
+ export { type OpaqueKey, type OpaqueKeyFormat, OpaqueTimestampCodec, OpaqueTimestampOptions, createOpaqueTimestampId, decodeOpaqueKey, encodeOpaqueKey, importOpaqueKey };
77
101
  //# sourceMappingURL=opaque.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"opaque.d.mts","names":[],"sources":["../src/opaque-key.ts","../src/opaque.ts"],"mappings":";;;;KAGY,eAAA;;AAAZ;;;;AAAY;iBAUI,eAAA,CAAgB,KAAA,EAAO,UAAA,EAAY,MAAA,EAAQ,eAAA;;;;;;;iBAa3C,eAAA,CAAgB,OAAA,UAAiB,MAAA,EAAQ,eAAA,GAAkB,UAAA;;;;AAvB3E;;KCQY,sBAAA;EDRA,sDCUV,GAAA,EAAK,SAAA,EDAP;ECEE,GAAA;EAEA,GAAA,IAAO,MAAA,EAAQ,UAAA;EAEf,mBAAA;AAAA;;;ADNyD;AAa3D;;;;;KCIY,oBAAA;iFAEV,QAAA,IAAY,OAAA,CAAQ,EAAA,CAAG,KAAA,IDNkD;ECQzE,UAAA,CAAW,IAAA,EAAM,IAAA,GAAO,OAAA,CAAQ,EAAA,CAAG,KAAA;;;;AAvBrC;EA4BE,EAAA,CAAG,KAAA,YAAiB,KAAA,IAAS,EAAA,CAAG,KAAA;;;;EAIhC,KAAA,CAAM,KAAA,YAAiB,EAAA,CAAG,KAAA;;;;EAI1B,SAAA,CAAU,KAAA,YAAiB,WAAA,CAAY,KAAA;;;AA5BvC;EAgCA,gBAAA,CAAiB,EAAA,EAAI,EAAA,CAAG,KAAA,IAAS,OAAA,CAAQ,IAAA,GArB/B;EAuBV,YAAA,IAA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