@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
package/README.md CHANGED
@@ -164,6 +164,102 @@ The `pattern` describes the **canonical form only** — it matches `generate()`
164
164
 
165
165
  `example` is produced by calling `generate()` on each invocation, so it is fresh (non-deterministic) and always matches the returned `pattern`. One consequence: a codec wired with an injected `now` outside the 48-bit range — the same misconfiguration that breaks `generate()` — makes `toJsonSchema()` throw too.
166
166
 
167
+ ### "Validate a route param in Hono"
168
+
169
+ `@smonn/ids/hono` provides `idParam` — a middleware factory that validates a named route param against a codec and exposes the canonical `Id<Brand>` to the handler. Hono is an **optional peer dependency**; install it separately alongside `@smonn/ids`.
170
+
171
+ ```bash
172
+ pnpm add hono
173
+ ```
174
+
175
+ ```ts
176
+ import { idParam } from "@smonn/ids/hono";
177
+ import { createTimestampId } from "@smonn/ids";
178
+
179
+ const usr = createTimestampId("usr");
180
+
181
+ // Default: throws HTTPException → app.onError handles rendering (HTML, JSON, problem+json, …)
182
+ app.get("/users/:id", idParam("id", usr), (c) => {
183
+ const id = c.get("id"); // Id<"usr">, canonical
184
+ // …
185
+ });
186
+
187
+ // Override: consumer fully owns the error response
188
+ app.get(
189
+ "/orgs/:id",
190
+ idParam("id", org, {
191
+ onError: (failure, c) => c.json({ error: failure.reason }, failure.status),
192
+ }),
193
+ handler,
194
+ );
195
+
196
+ // Or a lightweight status remap without a full handler
197
+ app.get("/things/:id", idParam("id", thing, { status: { brand_mismatch: 400 } }), handler);
198
+ ```
199
+
200
+ **Default error-channel behavior:** on failure the adapter throws `HTTPException(status)` — it does **not** write a response body itself. This lets the app's existing `app.onError` handler control content negotiation (HTML, JSON, problem+json, redirect, etc.) exactly as it would for any other error.
201
+
202
+ **`options.onError`:** when provided, the hook owns the response entirely — the adapter neither throws nor writes anything.
203
+
204
+ **`options.status`:** remaps the default HTTP status for a failure reason without requiring a full handler.
205
+
206
+ **400 vs 404 defaults:**
207
+
208
+ - **Brand mismatch (`invalid_prefix`) → `reason: "brand_mismatch"`, status 404.** The resource cannot exist under this route — a `usr_` ID makes no sense on `/orders/:id`.
209
+ - **Malformed or missing ID (`invalid_base32` or `not_string`) → `reason: "malformed"`, status 400.** The ID is absent or unreadable — a bad request, not a missing resource.
210
+
211
+ `idParam` calls `safeParse` at the boundary (lenient: accepts mixed case and Crockford aliases), so the handler always receives a canonical, normalized `Id<Brand>` — never the raw URL string. Works with any codec variant's structural `safeParse`.
212
+
213
+ ### "Validate a route param in Express"
214
+
215
+ `@smonn/ids/express` provides the same `idParam` factory for Express. Express is an **optional peer dependency**; install it separately alongside `@smonn/ids`.
216
+
217
+ ```bash
218
+ pnpm add express
219
+ ```
220
+
221
+ ```ts
222
+ import { idParam, IdParamError } from "@smonn/ids/express";
223
+ import { createTimestampId } from "@smonn/ids";
224
+
225
+ const usr = createTimestampId("usr");
226
+
227
+ // Default: calls next(err) with an IdParamError → app error-handling middleware renders it
228
+ app.get("/users/:id", idParam("id", usr), (req, res) => {
229
+ const id = res.locals.id; // Id<"usr">, canonical
230
+ // …
231
+ });
232
+
233
+ // Error-handling middleware receives the typed error
234
+ app.use((err, req, res, next) => {
235
+ if (err instanceof IdParamError) {
236
+ res.status(err.status).json({ error: err.reason });
237
+ return;
238
+ }
239
+ next(err);
240
+ });
241
+
242
+ // Override: consumer fully owns the error response
243
+ app.get(
244
+ "/orgs/:id",
245
+ idParam("id", org, {
246
+ onError: (failure, req, res) => res.status(failure.status).json({ error: failure.reason }),
247
+ }),
248
+ handler,
249
+ );
250
+
251
+ // Or a lightweight status remap without a full handler
252
+ app.get("/things/:id", idParam("id", thing, { status: { brand_mismatch: 400 } }), handler);
253
+ ```
254
+
255
+ **Default error-channel behavior:** on failure the adapter calls `next(err)` with an `IdParamError` carrying `status` and `reason` — it does **not** write a response body itself. This lets the app's existing error-handling middleware control rendering exactly as it would for any other error.
256
+
257
+ **`options.onError`:** when provided, the hook owns the response entirely — the adapter does not call `next(err)`.
258
+
259
+ **`options.status`:** remaps the default HTTP status for a failure reason without requiring a full handler.
260
+
261
+ The 400 vs 404 defaults are identical to the Hono adapter: `reason: "brand_mismatch"` → 404, `reason: "malformed"` → 400. The canonical `Id<Brand>` is stored in `res.locals` under `paramName` and available to downstream handlers.
262
+
167
263
  ### "Don't leak creation time in IDs that customers can see"
168
264
 
169
265
  The Timestamp codec exposes the creation timestamp by design — that's what makes `ORDER BY id` work. If that's a leak you can't accept (invoice IDs revealing billing cadence, signup IDs revealing acquisition velocity), use the Opaque Timestamp codec at `@smonn/ids/opaque`. Same `<brand>_<26 chars>` wire shape, but the payload is AES-encrypted under a key you supply.
@@ -171,7 +267,7 @@ The Timestamp codec exposes the creation timestamp by design — that's what mak
171
267
  ```ts
172
268
  import { createOpaqueTimestampId, importOpaqueKey } from "@smonn/ids/opaque";
173
269
 
174
- const key = await importOpaqueKey(new Uint8Array(16)); // 128- or 256-bit raw key
270
+ const key = await importOpaqueKey(new Uint8Array(16)); // returns an OpaqueKey handle
175
271
  const invoices = createOpaqueTimestampId("inv", { key });
176
272
 
177
273
  const id = await invoices.generate(); // "inv_…", timestamp not extractable without the key
@@ -188,6 +284,47 @@ Encryption is AES-CBC with a zero IV. That's deliberately safe here because the
188
284
 
189
285
  To store or transport key material outside the library, `encodeOpaqueKey` / `decodeOpaqueKey` round-trip raw bytes in `hex` or `base64url` — distinct from the Crockford base32 used in ID payloads. The CLI's `keygen` subcommand emits keys in this format (see [CLI](#cli)).
190
286
 
287
+ ### "Newest-first IDs for descending range scans"
288
+
289
+ Most KV stores (DynamoDB, Cloud Datastore, range-scan KV) only support forward lexicographic scans natively — reading the most recent entries first would otherwise require a full reverse scan or a separate sort step. The Reverse Timestamp codec solves this by bitwise-inverting the 48-bit timestamp field before encoding, so newer IDs sort lexicographically before older ones.
290
+
291
+ ```ts
292
+ import { createReverseTimestampId } from "@smonn/ids/reverse";
293
+
294
+ const events = createReverseTimestampId("evt");
295
+
296
+ const id = events.generate(); // "evt_…", sorts newest-first
297
+ events.extractTimestamp(id); // Date — inversion is reversed to recover the original ms
298
+ ```
299
+
300
+ **Range-bound direction is flipped.** Because a newer timestamp maps to a lexicographically smaller ID, a time-range scan over [t_old, t_new] passes the newer timestamp as the lower bound and the older timestamp as the upper bound:
301
+
302
+ ```ts
303
+ const start = new Date("2026-01-01T00:00:00Z"); // older
304
+ const end = new Date("2026-02-01T00:00:00Z"); // newer
305
+
306
+ // Reverse Timestamp: lower bound = newer time, upper bound = older time
307
+ sql`SELECT * FROM events WHERE id BETWEEN ${events.minIdForTime(end)} AND ${events.maxIdForTime(start)}`;
308
+
309
+ // compare: Timestamp codec (ascending) passes start/end in the natural forward direction
310
+ // sql`... WHERE id BETWEEN ${plainEvents.minIdForTime(start)} AND ${plainEvents.maxIdForTime(end)}`
311
+ ```
312
+
313
+ `minIdForTime(t)` is always the lexicographically smallest ID at millisecond `t` (random portion all `0x00`) and `maxIdForTime(t)` is the largest (random portion all `0xff`). Under reversal, a newer `t` produces a smaller `minIdForTime` result, so the bounds are swapped relative to the Timestamp codec — see [ADR-0010](./docs/adr/0010-reverse-timestamp-inversion.md) for the detailed rationale.
314
+
315
+ **Same-millisecond order remains non-deterministic.** The random 10-byte tail is not affected by the timestamp inversion. Two IDs generated in the same millisecond have independent random tails and do not sort deterministically relative to each other — the same caveat as the Timestamp codec (ADR-0002).
316
+
317
+ No key material is required. The inversion is a deterministic byte transform; `generate`, `generateAt`, and `extractTimestamp` are fully synchronous.
318
+
319
+ ## Choosing a codec variant
320
+
321
+ | Codec | Import | Sort direction | Key required | Timestamp extractable | Range query support |
322
+ | ----------------- | -------------------- | ------------------------- | ------------------ | -------------------------- | -------------------------------------------------------------- |
323
+ | Timestamp | `@smonn/ids` | Ascending (oldest-first) | No | Always | `minIdForTime(t_old)` → `maxIdForTime(t_new)` |
324
+ | Reverse Timestamp | `@smonn/ids/reverse` | Descending (newest-first) | No | Always | `minIdForTime(t_new)` → `maxIdForTime(t_old)` (bounds flipped) |
325
+ | Opaque Timestamp | `@smonn/ids/opaque` | None (encrypted) | Yes (AES key) | With key only | None — encrypted payloads do not sort by time |
326
+ | Wrapped key | `@smonn/ids/wrapped` | None | Yes (wrapping key) | N/A — not timestamp-family | None |
327
+
191
328
  ## What this is **not** for
192
329
 
193
330
  - **Internal surrogate primary keys.** If nobody outside your service ever sees the ID, the brand prefix and lenient parsing are dead weight. Use a `bigint` sequence.
@@ -210,14 +347,21 @@ import {
210
347
 
211
348
  import {
212
349
  createOpaqueTimestampId, // (brand: string, opts: OpaqueTimestampOptions) => OpaqueTimestampCodec<Brand>
213
- importOpaqueKey, // (bytes: Uint8Array) => Promise<CryptoKey>
350
+ importOpaqueKey, // (bytes: Uint8Array) => Promise<OpaqueKey>
214
351
  encodeOpaqueKey, // (bytes: Uint8Array, format: OpaqueKeyFormat) => string
215
352
  decodeOpaqueKey, // (encoded: string, format: OpaqueKeyFormat) => Uint8Array
216
353
  type OpaqueTimestampCodec, // returned by createOpaqueTimestampId
217
- type OpaqueTimestampOptions, // { key, now?, rng?, allowDuplicateBrand? } constructor options
354
+ type OpaqueTimestampOptions, // { key: OpaqueKey, now?, rng?, allowDuplicateBrand? } constructor options
355
+ type OpaqueKey, // opaque imported handle for AES key material
218
356
  type OpaqueKeyFormat, // "hex" | "base64url"
219
357
  } from "@smonn/ids/opaque";
220
358
 
359
+ import {
360
+ createReverseTimestampId, // (brand: string, opts?: ReverseTimestampOptions) => ReverseTimestampCodec<Brand>
361
+ type ReverseTimestampCodec, // returned by createReverseTimestampId
362
+ type ReverseTimestampOptions, // { now?, rng?, allowDuplicateBrand? } constructor options
363
+ } from "@smonn/ids/reverse";
364
+
221
365
  import {
222
366
  createWrappedKeyId, // (brand: string, opts: { kind: "u32" | "i32" | "u64" | "i64", keys }) => WrappedKeyCodec<Brand, Kind>
223
367
  importWrappingKey, // (bytes: Uint8Array) => Promise<WrappingKey>
@@ -227,31 +371,269 @@ import {
227
371
  type WrappingKey, // opaque imported handle for wrapping key material
228
372
  type WrappingKeyFormat, // "hex" | "base64url"
229
373
  } from "@smonn/ids/wrapped";
374
+
375
+ import {
376
+ idColumn, // (codec: IdColumnCodec<Brand>) => PgCustomColumnBuilder (Drizzle column)
377
+ type IdColumnCodec, // { safeParse(value: unknown): ParseResult<Brand> }
378
+ } from "@smonn/ids/drizzle";
379
+
380
+ import {
381
+ idField, // (codec: IdColumnCodec<Brand>) => IdTransform<Brand> — read/write transforms for Prisma $extends
382
+ type IdColumnCodec, // { safeParse(value: unknown): ParseResult<Brand> }
383
+ type IdTransform, // { read(value: unknown): Id<Brand>; write(value: Id<Brand>): string }
384
+ } from "@smonn/ids/prisma";
385
+
386
+ import {
387
+ idParam, // (paramName: string, codec, options?) => Hono MiddlewareHandler — throws HTTPException by default; onError/status options override
388
+ type IdParamFailure, // { reason: "brand_mismatch" | "malformed"; status: number }
389
+ type IdParamOptions, // { onError?, status? }
390
+ } from "@smonn/ids/hono";
391
+
392
+ import {
393
+ idParam, // (paramName: string, codec, options?) => Express middleware — calls next(err) with IdParamError by default; onError/status options override
394
+ IdParamError, // Error subclass with .reason and .status — forwarded via next(err) by default
395
+ type IdParamFailure, // { reason: "brand_mismatch" | "malformed"; status: number }
396
+ type IdParamOptions, // { onError?, status? }
397
+ } from "@smonn/ids/express";
230
398
  ```
231
399
 
232
- `@smonn/ids/wrapped` ships the Wrapped key codec for `u32`, `i32`, `u64`, and `i64` lookup keys. `wrap(lookupKey)` emits a public ID, `unwrap(id)` verifies and recovers the lookup key, and `safeUnwrap(input)` structurally parses then reports parse or verification failure without throwing. The 32-bit kinds use `number`; the 64-bit kinds use `bigint`.
400
+ `@smonn/ids/wrapped` ships the Wrapped key codec for `u32`, `i32`, `u64`, and `i64` lookup keys. `wrap(lookupKey)` returns a public ID; `unwrap(id)` verifies the payload and returns the lookup key; `safeUnwrap(input)` is the non-throwing path for untrusted input.
401
+
402
+ **Integer kinds and value types.** The 32-bit kinds (`u32`, `i32`) use safe JavaScript `number` values in their fixed-width ranges. The 64-bit kinds (`u64`, `i64`) always use `bigint` — even when the magnitude would fit in a `number` — to prevent silent truncation or sign erasure.
233
403
 
234
404
  ```ts
405
+ import { createWrappedKeyId, importWrappingKey } from "@smonn/ids/wrapped";
406
+
235
407
  const key = await importWrappingKey(new Uint8Array(32));
236
- const invoices = createWrappedKeyId("inv", { kind: "u64", keys: [key] });
237
408
 
238
- const id = await invoices.wrap(42n); // "inv_..."
239
- const lookupKey = await invoices.unwrap(id); // 42n
409
+ // u32: number, range [0, 4294967295]
410
+ const u32Ids = createWrappedKeyId("inv", { kind: "u32", keys: [key] });
411
+ const u32Id = await u32Ids.wrap(42); // number → Id<"inv">
412
+ const u32Key = await u32Ids.unwrap(u32Id); // → 42 (number)
413
+
414
+ // i32: number, range [-2147483648, 2147483647]
415
+ const i32Ids = createWrappedKeyId("rec", { kind: "i32", keys: [key] });
416
+ const i32Id = await i32Ids.wrap(-7); // number → Id<"rec">
417
+ const i32Key = await i32Ids.unwrap(i32Id); // → -7 (number)
418
+
419
+ // u64: bigint, range [0n, 18446744073709551615n]
420
+ const u64Ids = createWrappedKeyId("ord", { kind: "u64", keys: [key] });
421
+ const u64Id = await u64Ids.wrap(42n); // bigint → Id<"ord">
422
+ const u64Key = await u64Ids.unwrap(u64Id); // → 42n (bigint)
423
+
424
+ // i64: bigint, range [-9223372036854775808n, 9223372036854775807n]
425
+ const i64Ids = createWrappedKeyId("evt", { kind: "i64", keys: [key] });
426
+ const i64Id = await i64Ids.wrap(-1n); // bigint → Id<"evt">
427
+ const i64Key = await i64Ids.unwrap(i64Id); // → -1n (bigint)
428
+ ```
429
+
430
+ **Keyring rotation.** Pass a non-empty ordered list of wrapping keys at construction. The first entry is the _current_ key — the only one `wrap` uses. `unwrap` trials every entry in order until the verification tag matches, so IDs wrapped under any listed key are still unwrappable. Removing an entry from the list revokes all IDs wrapped under it.
431
+
432
+ ```ts
433
+ const oldKey = await importWrappingKey(rawOldSecret);
434
+ const newKey = await importWrappingKey(rawNewSecret);
435
+
436
+ // Before rotation: only oldKey in the ring
437
+ const legacy = createWrappedKeyId("inv", { kind: "u32", keys: [oldKey] });
438
+ const id = await legacy.wrap(7);
439
+
440
+ // After rotation: newKey is current; oldKey is still accepted on unwrap
441
+ const rotated = createWrappedKeyId("inv", { kind: "u32", keys: [newKey, oldKey] });
442
+ await rotated.unwrap(id); // succeeds — tried oldKey and matched
443
+ await rotated.wrap(7); // uses newKey → different public ID
444
+ ```
445
+
446
+ **Equality leakage.** The Wrapped key codec is deterministic: the same lookup key wrapped under the same wrapping key always yields the same public ID. An observer without operator material can tell that two identical public IDs wrap the same lookup key, but cannot recover the lookup key or wrapping key from the ID alone. This is an accepted trade-off for fitting an 8-byte integer lane and an 8-byte verification tag into the 16-byte payload. UUID-sized values (128 bits) are out of scope for this compact branch — there is no room for them alongside the verification tag.
447
+
448
+ **Fail-closed verification.** `is`, `parse`, and `safeParse` are structural — they check only the prefix and base32 payload shape, with no key material required. Cryptographic verification only happens in `unwrap` and `safeUnwrap`.
449
+
450
+ - `unwrap(id)` takes a trusted `Id<Brand>` and **throws** if payload verification fails. Use it when the ID is already known to be structurally valid (e.g. freshly loaded from your database).
451
+ - `safeUnwrap(input)` accepts untrusted input, structurally parses first, then verifies — without throwing. It returns one of:
452
+
453
+ ```ts
454
+ // Success
455
+ {
456
+ ok: true;
457
+ id: Id<Brand>;
458
+ lookupKey: number | bigint;
459
+ }
460
+
461
+ // Structural parse failure (wrong brand, invalid base32, etc.)
462
+ {
463
+ ok: false;
464
+ error: "not_string" | "invalid_prefix" | "invalid_base32";
465
+ }
466
+
467
+ // Payload verified but tag mismatch (tampered, wrong keyring, or revoked key)
468
+ {
469
+ ok: false;
470
+ error: "verification_failed";
471
+ }
472
+ ```
473
+
474
+ Use `safeUnwrap` at API boundaries where the input is untrusted:
475
+
476
+ ```ts
477
+ const result = await invoices.safeUnwrap(req.body.invoiceId);
478
+
479
+ if (!result.ok) {
480
+ if (result.error === "verification_failed") return 403; // tampered or wrong key
481
+ return 400; // malformed ID
482
+ }
483
+
484
+ const { id, lookupKey } = result; // Id<"inv">, number
240
485
  ```
241
486
 
242
487
  ### Codec methods
243
488
 
244
- | Method | `TimestampCodec<Brand>` | `OpaqueTimestampCodec<Brand>` | Description |
245
- | ---------------------- | ----------------------- | ----------------------------- | ----------------------------------------------------------------------------- |
246
- | `generate()` | sync | async | Produce a fresh ID |
247
- | `generateAt(date)` | sync | async | Produce a fresh ID with timestamp bytes from `date` (for backfills) |
248
- | `is(value)` | sync | sync | Strict type guard: `true` only for already-canonical strings |
249
- | `parse(value)` | sync | sync | Lenient: normalise to canonical, or throw |
250
- | `safeParse(value)` | sync | sync | Lenient: normalise to canonical, or return `{ ok: false, error }` |
251
- | `extractTimestamp(id)` | sync | async | Decode the creation `Date` from an `Id<Brand>` (trusts the type) |
252
- | `minIdForTime(date)` | sync | | Tight lower bound for any ID generated at `date` (for range queries) |
253
- | `maxIdForTime(date)` | sync | | Tight upper bound for any ID generated at `date` (for range queries) |
254
- | `toJsonSchema()` | sync | sync | JSON Schema (`type`/`pattern`/`description`/`example`) for the canonical form |
489
+ | Method | `TimestampCodec<Brand>` | `ReverseTimestampCodec<Brand>` | `OpaqueTimestampCodec<Brand>` | `WrappedKeyCodec<Brand, Kind>` | Description |
490
+ | ---------------------- | ----------------------- | ------------------------------ | ----------------------------- | ------------------------------ | ----------------------------------------------------------------------------- |
491
+ | `generate()` | sync | sync | async | — | Produce a fresh ID |
492
+ | `generateAt(date)` | sync | sync | async | — | Produce a fresh ID with timestamp bytes from `date` (for backfills) |
493
+ | `wrap(lookupKey)` | | — | — | async | Wrap a lookup key into a public ID using the current wrapping key |
494
+ | `unwrap(id)` | | — | — | async | Verify and recover the lookup key; throws on verification failure |
495
+ | `safeUnwrap(input)` | | — | — | async | Non-throwing: structurally parse then verify; returns parse or verify error |
496
+ | `is(value)` | sync | sync | sync | sync | Strict type guard: `true` only for already-canonical strings |
497
+ | `parse(value)` | sync | sync | sync | sync | Lenient: normalise to canonical, or throw |
498
+ | `safeParse(value)` | sync | sync | sync | sync | Lenient: normalise to canonical, or return `{ ok: false, error }` |
499
+ | `extractTimestamp(id)` | sync | sync | async | — | Decode the creation `Date` from an `Id<Brand>` (trusts the type) |
500
+ | `minIdForTime(date)` | sync | sync † | — | — | Tight lower bound for any ID generated at `date` (for range queries) |
501
+ | `maxIdForTime(date)` | sync | sync † | — | — | Tight upper bound for any ID generated at `date` (for range queries) |
502
+ | `toJsonSchema()` | sync | sync | sync | sync | JSON Schema (`type`/`pattern`/`description`/`example`) for the canonical form |
503
+
504
+ † Under the Reverse Timestamp codec, a newer timestamp maps to a lexicographically smaller ID — pass `minIdForTime(t_new)` as the lower bound and `maxIdForTime(t_old)` as the upper bound for a [t_old, t_new] scan.
505
+
506
+ ## ORM adapters
507
+
508
+ ### Drizzle (`@smonn/ids/drizzle`)
509
+
510
+ `@smonn/ids/drizzle` is a subpath export that provides a Drizzle custom column type bound to a codec. It requires `drizzle-orm` as a peer dependency — installing `@smonn/ids` alone does not require Drizzle.
511
+
512
+ ```bash
513
+ pnpm add drizzle-orm
514
+ ```
515
+
516
+ ```ts
517
+ import { pgTable } from "drizzle-orm/pg-core";
518
+ import { idColumn } from "@smonn/ids/drizzle";
519
+ import { createTimestampId } from "@smonn/ids";
520
+
521
+ const usr = createTimestampId("usr");
522
+
523
+ export const users = pgTable("users", {
524
+ id: idColumn(usr).primaryKey(),
525
+ });
526
+ // users.id is typed as Id<"usr"> end-to-end
527
+ ```
528
+
529
+ `idColumn(codec)` works with any codec variant — `TimestampCodec`, `OpaqueTimestampCodec`, and `WrappedKeyCodec` all satisfy the required interface.
530
+
531
+ **Write path:** `Id<Brand>` is already canonical, so it is passed to the driver unchanged.
532
+
533
+ **Read path:** values from the database are normalised via `codec.safeParse()` rather than the strict `is()` check. Data at rest should already be canonical per [ADR-0003](./docs/adr/0003-canonical-strict-is.md), but `safeParse` is a safe boundary in case stale non-canonical values exist. An unrecognised value throws at read time so corrupt data surfaces immediately rather than silently.
534
+
535
+ ```ts
536
+ import {
537
+ idColumn, // (codec: IdColumnCodec<Brand>) => PgCustomColumnBuilder
538
+ type IdColumnCodec, // { safeParse(value: unknown): ParseResult<Brand> }
539
+ } from "@smonn/ids/drizzle";
540
+ ```
541
+
542
+ ### Kysely (`@smonn/ids/kysely`)
543
+
544
+ `@smonn/ids/kysely` is a subpath export that provides a Kysely column adapter bound to a codec. It requires `kysely` as a peer dependency — installing `@smonn/ids` alone does not require Kysely.
545
+
546
+ ```bash
547
+ pnpm add kysely
548
+ ```
549
+
550
+ ```ts
551
+ import { idColumn, type IdColumnType } from "@smonn/ids/kysely";
552
+ import { createTimestampId } from "@smonn/ids";
553
+
554
+ const usr = createTimestampId("usr");
555
+ const usrCol = idColumn(usr);
556
+
557
+ // Use IdColumnType in your Database interface:
558
+ interface Database {
559
+ users: { id: IdColumnType<"usr"> };
560
+ }
561
+
562
+ // Kysely has no runtime transformer — fromDriver/toDriver do NOT fire automatically.
563
+ // You must call fromDriver() manually on every read result.
564
+ // The `as unknown as string` cast is required because TypeScript already sees
565
+ // row.id as Id<"usr"> (from the Database interface), even though the raw DB
566
+ // value is a plain string at runtime.
567
+ const row = await db.selectFrom("users").selectAll().executeTakeFirstOrThrow();
568
+ const id = usrCol.fromDriver(row.id as unknown as string);
569
+ ```
570
+
571
+ `idColumn(codec)` works with any codec variant — `TimestampCodec`, `OpaqueTimestampCodec`, and `WrappedKeyCodec` all satisfy the required interface.
572
+
573
+ **Write path:** `Id<Brand>` is already canonical, so `toDriver` passes it to the driver unchanged.
574
+
575
+ **Read path:** `fromDriver` normalises the raw DB string via `codec.safeParse()`. An unrecognised value throws at read time so corrupt data surfaces immediately rather than silently.
576
+
577
+ ```ts
578
+ import {
579
+ idColumn, // (codec: IdColumnCodec<Brand>) => { toDriver, fromDriver }
580
+ type IdColumnCodec, // { safeParse(value: unknown): ParseResult<Brand> }
581
+ type IdColumnType, // ColumnType<Id<Brand>, Id<Brand>, Id<Brand>>
582
+ } from "@smonn/ids/kysely";
583
+ ```
584
+
585
+ ### Prisma (`@smonn/ids/prisma`)
586
+
587
+ `@smonn/ids/prisma` is a subpath export that provides a read/write transform pair for integrating `Id<Brand>` with Prisma's `$extends` extension model. It requires `@prisma/client` as a peer dependency — installing `@smonn/ids` alone does not require Prisma.
588
+
589
+ ```bash
590
+ pnpm add @prisma/client
591
+ ```
592
+
593
+ ```ts
594
+ import { idField } from "@smonn/ids/prisma";
595
+ import { createTimestampId } from "@smonn/ids";
596
+ import type { Id } from "@smonn/ids";
597
+
598
+ const usr = createTimestampId("usr");
599
+ const userIdField = idField(usr);
600
+
601
+ const xprisma = prisma.$extends({
602
+ result: {
603
+ user: {
604
+ id: {
605
+ needs: { id: true },
606
+ compute(user) {
607
+ // Cast required — see Prisma caveat below
608
+ return userIdField.read(user.id) as Id<"usr">;
609
+ },
610
+ },
611
+ },
612
+ },
613
+ });
614
+
615
+ // Write path: Id<Brand> is already canonical — pass it directly
616
+ await xprisma.user.create({ data: { id: userIdField.write(usr.generate()), name: "Alice" } });
617
+
618
+ // Read path: validated and typed as Id<"usr"> (with cast)
619
+ const user = await xprisma.user.findFirstOrThrow();
620
+ ```
621
+
622
+ `idField(codec)` works with any codec variant — `TimestampCodec`, `OpaqueTimestampCodec`, `ReverseTimestampCodec`, and `WrappedKeyCodec` all satisfy the required interface.
623
+
624
+ **Write path:** `Id<Brand>` is already canonical, so `write` is an identity function — it returns the string unchanged.
625
+
626
+ **Read path:** values from the database are normalised via `codec.safeParse()` rather than the strict `is()` check. Data at rest should already be canonical per [ADR-0003](./docs/adr/0003-canonical-strict-is.md), but `safeParse` is a safe boundary in case stale non-canonical values exist. An unrecognised value throws at read time so corrupt data surfaces immediately rather than silently.
627
+
628
+ **Prisma casting caveat:** Prisma's `$extends` result component can add typed computed accessors to model instances, but cannot retroactively re-type an existing schema field at the Prisma Client level. The `read` function asserts `Id<Brand>` at the TypeScript level, but Prisma's generated types for the model field will not reflect this branding. Callers will need an explicit `as Id<"brand">` cast at consumption sites. This is a Prisma type-system constraint, not a library limitation — see the JSDoc on `idField` for the canonical example.
629
+
630
+ ```ts
631
+ import {
632
+ idField, // (codec: IdColumnCodec<Brand>) => IdTransform<Brand>
633
+ type IdColumnCodec, // { safeParse(value: unknown): ParseResult<Brand> }
634
+ type IdTransform, // { read(value: unknown): Id<Brand>; write(value: Id<Brand>): string }
635
+ } from "@smonn/ids/prisma";
636
+ ```
255
637
 
256
638
  ## CLI
257
639