{"version":3,"file":"reverse-Bi20KovA.mjs","names":[],"sources":["../src/codecs/reverse/layout.ts","../src/codecs/reverse/index.ts"],"sourcesContent":["import type { Id, Prefix } from \"../../types.js\";\nimport { payloadBytesFromId, toWireId } from \"../../wire/envelope.js\";\nimport { payloadByteLength } from \"../../wire/invariants.js\";\nimport { timestampByteLength, writeTimestamp } from \"../../wire/timestamp-bytes.js\";\n\nconst randomByteLength: number = payloadByteLength - timestampByteLength;\n\n/** Inverts the first `timestampByteLength` bytes of `buffer` in place. */\nfunction invertTimestampBytes(buffer: Uint8Array): void {\n  for (let i = 0; i < timestampByteLength; i++) {\n    buffer[i] = ~buffer[i]! & 0xff;\n  }\n}\n\n/** Writes inverted timestamp bytes, then fills random portion. */\nfunction buildReversePayload(\n  ms: number,\n  rng: (target: Uint8Array) => void,\n  buffer: Uint8Array,\n  randomView: Uint8Array,\n): void {\n  writeTimestamp(ms, buffer);\n  invertTimestampBytes(buffer);\n  rng(randomView);\n}\n\n/** Writes inverted timestamp bytes, then fills random portion with a sentinel. */\nfunction buildReverseSentinelPayload(\n  ms: number,\n  fill: number,\n  buffer: Uint8Array,\n  randomView: Uint8Array,\n): void {\n  writeTimestamp(ms, buffer);\n  invertTimestampBytes(buffer);\n  randomView.fill(fill);\n}\n\n/** Decodes the original timestamp by inverting the first 6 payload bytes.\n * Stays inline: combines inversion and big-endian accumulation in one pass\n * so no temporary buffer is needed; factoring further would add allocation. */\nfunction extractReverseTimestampFromId<Brand extends string>(\n  prefix: Prefix<Brand>,\n  id: Id<Brand>,\n): Date {\n  const bytes = payloadBytesFromId(prefix, id);\n  let ms = 0;\n  for (let i = 0; i < timestampByteLength; i++) {\n    ms = ms * 256 + (~bytes[i]! & 0xff);\n  }\n  return new Date(ms);\n}\n\n/** Layout ops binder for the Reverse Timestamp variant. */\nexport function createReverseTimestampLayoutOps<Brand extends string>(\n  prefix: Prefix<Brand>,\n  rng: (target: Uint8Array) => void,\n): {\n  generateAt(ms: number): Id<Brand>;\n  extractTimestamp(id: Id<Brand>): Date;\n  minIdForTime(ms: number): Id<Brand>;\n  maxIdForTime(ms: number): Id<Brand>;\n} {\n  const buffer = new Uint8Array(payloadByteLength);\n  const randomView = new Uint8Array(buffer.buffer, timestampByteLength, randomByteLength);\n\n  return {\n    generateAt: (ms: number): Id<Brand> => {\n      buildReversePayload(ms, rng, buffer, randomView);\n      return toWireId(prefix, buffer);\n    },\n    extractTimestamp: (id: Id<Brand>): Date => extractReverseTimestampFromId(prefix, id),\n    minIdForTime: (ms: number): Id<Brand> => {\n      buildReverseSentinelPayload(ms, 0x00, buffer, randomView);\n      return toWireId(prefix, buffer);\n    },\n    maxIdForTime: (ms: number): Id<Brand> => {\n      buildReverseSentinelPayload(ms, 0xff, buffer, randomView);\n      return toWireId(prefix, buffer);\n    },\n  };\n}\n","import { validateBrand } from \"../_kernel/brand.js\";\nimport { createReverseTimestampLayoutOps } from \"./layout.js\";\nimport { registerBrand } from \"../_kernel/registry.js\";\nimport { fastTenByteRng } from \"../_kernel/rng.js\";\nimport type {\n  Id,\n  JsonSchema,\n  ParseResult,\n  Prefix,\n  StandardSchemaProps,\n  ValidBrand,\n} from \"../../types.js\";\nimport { wireMethods } from \"../../wire/codec-shell.js\";\n\n/**\n * Configuration options for a Reverse Timestamp codec instance.\n */\nexport type ReverseTimestampOptions = {\n  /** Returns the current timestamp in milliseconds. Defaults to `Date.now`. */\n  now?: () => number;\n  /** Writes the 10-byte random tail into `target`. Defaults to a `crypto.randomUUID` harvest fast path (same as the Timestamp codec). */\n  rng?: (target: Uint8Array) => void;\n  /** If true, silences the duplicate-brand warning in non-production environments. */\n  allowDuplicateBrand?: boolean;\n};\n\ntype ResolvedReverseTimestampOptions = Required<Pick<ReverseTimestampOptions, \"now\" | \"rng\">> &\n  Pick<ReverseTimestampOptions, \"allowDuplicateBrand\">;\n\n/**\n * A brand-scoped codec for generating and validating Reverse Timestamp IDs.\n *\n * Wire format: `{brand}_` plus 26 lowercase Crockford base32 characters encoding a\n * 16-byte payload (6-byte bitwise-inverted ms timestamp + 10 random bytes). IDs sort\n * by creation time in **descending** (newest-first) order.\n *\n * Range queries across a time interval [t_old, t_new] should scan from\n * `minIdForTime(t_new)` to `maxIdForTime(t_old)` — the reversed sort order means\n * newer timestamps produce lexicographically smaller IDs.\n *\n * Constructed via `createReverseTimestampId(brand)` from `@smonn/ids/reverse`.\n */\nexport type ReverseTimestampCodec<Brand extends string> = {\n  /** Produces a new canonical ID using the codec's `now` and `rng`. */\n  generate(): Id<Brand>;\n  /** Produces a new canonical ID with timestamp bytes from `date` and a fresh random tail. Throws on invalid dates. */\n  generateAt(date: Date): 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   * Decodes the creation `Date` from an `Id<Brand>` by inverting the timestamp bytes.\n   * Trusts the type — use `safeParse()` at boundaries first.\n   *\n   * Best-effort: inverts and decodes the timestamp bytes in the payload without any\n   * additional verification. An ID that bypassed `safeParse()` (e.g. via a type\n   * assertion) may return a plausible-looking but incorrect `Date`.\n   */\n  extractTimestamp(id: Id<Brand>): Date;\n  /**\n   * Lexicographically smallest ID for any ID generated at `date` (random portion `0x00`).\n   * Because timestamps are inverted, a newer `date` yields a lexicographically smaller result —\n   * use `minIdForTime(t_new)` as the lower bound when scanning [t_old, t_new].\n   * Throws on invalid dates.\n   */\n  minIdForTime(date: Date): Id<Brand>;\n  /**\n   * Lexicographically largest ID for any ID generated at `date` (random portion `0xff`).\n   * Because timestamps are inverted, an older `date` yields a lexicographically larger result —\n   * use `maxIdForTime(t_old)` as the upper bound when scanning [t_old, t_new].\n   * Throws on invalid dates.\n   */\n  maxIdForTime(date: Date): Id<Brand>;\n  /**\n   * JSON Schema for the canonical wire form. The `pattern` matches the canonical stored\n   * form only and is deliberately stricter than `parse()`/`safeParse()`, which accept\n   * uppercase letters and Crockford aliases (`o`/`i`/`l`) before normalising. See ADR-0003.\n   */\n  toJsonSchema(): JsonSchema;\n  /** Standard Schema validate entry point. */\n  readonly \"~standard\": StandardSchemaProps<Brand>;\n  /**\n   * Converts a trusted `Id<Brand>` to an RFC 9562 canonical (lowercase, hyphenated)\n   * UUID string by reinterpreting the 16-byte payload verbatim. Total — cannot fail.\n   * Returns a plain `string` (brand is shed). See ADR-0024.\n   */\n  toUUID(id: Id<Brand>): string;\n  /**\n   * Parses a UUID string into an `Id<Brand>`. Accepts case-insensitive `8-4-4-4-12`\n   * hyphenated form only. Throws `IdsError` with `code: \"invalid_id\"` on bad input.\n   * See ADR-0024.\n   */\n  fromUUID(value: string): Id<Brand>;\n  /**\n   * Non-throwing UUID parse. Returns `{ ok: true, id }` or\n   * `{ ok: false, error: \"not_string\" | \"invalid_uuid\" }`. See ADR-0024.\n   */\n  safeFromUUID(value: unknown): ParseResult<Brand>;\n};\n\nconst defaultReverseTimestampOptions: ResolvedReverseTimestampOptions = {\n  now: Date.now,\n  // crypto.randomUUID harvest fast path (~7× faster than crypto.getRandomValues);\n  // see fastTenByteRng. The Timestamp codec uses the identical default.\n  rng: fastTenByteRng,\n};\n\n/**\n * Creates a Reverse Timestamp codec for `brand` (three lowercase a–z characters).\n *\n * IDs sort newest-first: the 48-bit timestamp field is bitwise-inverted before encoding,\n * so lexicographic ID order equals descending creation-time order. `extractTimestamp`\n * inverts back to recover the original millisecond.\n *\n * @param brand - Entity type brand validated once at construction.\n * @param opts - Optional `now`, `rng`, and `allowDuplicateBrand` overrides.\n * @example\n * ```ts\n * const posts = createReverseTimestampId(\"pst\");\n *\n * const id = posts.generate();            // Id<\"pst\">  (newest-first sort)\n * posts.extractTimestamp(id);             // Date\n * ```\n */\nexport function createReverseTimestampId<Brand extends string>(\n  brand: Brand & ValidBrand<Brand>,\n  opts: ReverseTimestampOptions = {},\n): ReverseTimestampCodec<Brand> {\n  validateBrand(brand);\n  registerBrand(brand, opts.allowDuplicateBrand);\n\n  const options = {\n    now: opts.now ?? defaultReverseTimestampOptions.now,\n    rng: opts.rng ?? defaultReverseTimestampOptions.rng,\n  } satisfies ResolvedReverseTimestampOptions;\n\n  const prefix: Prefix<Brand> = `${brand}_`;\n  const wire = wireMethods(prefix);\n  const layout = createReverseTimestampLayoutOps(prefix, options.rng);\n\n  return {\n    generate: () => layout.generateAt(options.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    minIdForTime: (date: Date) => layout.minIdForTime(date.getTime()),\n    maxIdForTime: (date: Date) => layout.maxIdForTime(date.getTime()),\n    toJsonSchema: wire.toJsonSchema,\n    \"~standard\": wire[\"~standard\"],\n    toUUID: wire.toUUID,\n    fromUUID: wire.fromUUID,\n    safeFromUUID: wire.safeFromUUID,\n  };\n}\n"],"mappings":";;;AAKA,MAAM,mBAAA;;AAGN,SAAS,qBAAqB,QAA0B;CACtD,KAAK,IAAI,IAAI,GAAG,IAAA,GAAyB,KACvC,OAAO,KAAK,CAAC,OAAO,KAAM;AAE9B;;AAGA,SAAS,oBACP,IACA,KACA,QACA,YACM;CACN,eAAe,IAAI,MAAM;CACzB,qBAAqB,MAAM;CAC3B,IAAI,UAAU;AAChB;;AAGA,SAAS,4BACP,IACA,MACA,QACA,YACM;CACN,eAAe,IAAI,MAAM;CACzB,qBAAqB,MAAM;CAC3B,WAAW,KAAK,IAAI;AACtB;;;;AAKA,SAAS,8BACP,QACA,IACM;CACN,MAAM,QAAQ,mBAAmB,QAAQ,EAAE;CAC3C,IAAI,KAAK;CACT,KAAK,IAAI,IAAI,GAAG,IAAA,GAAyB,KACvC,KAAK,KAAK,O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