{"version":3,"file":"hono.mjs","names":[],"sources":["../src/adapters/hono.ts"],"sourcesContent":["import { HTTPException } from \"hono/http-exception\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport {\n  type IdCodec,\n  type IdParamFailure,\n  type IdVerifiableCodec,\n  resolveIdParamFailure,\n  resolveVerifyFailure,\n} from \"./adapter-types.js\";\nimport type { Id } from \"../types.js\";\n\nexport type { IdParamFailure };\n\n/**\n * Typed error thrown into Hono's `app.onError` on validation failure.\n * Inspect `err.reason` and `err.status` in your error handler.\n */\nexport class IdParamError extends HTTPException {\n  readonly reason: \"brand_mismatch\" | \"malformed\";\n\n  constructor(reason: \"brand_mismatch\" | \"malformed\", status: ContentfulStatusCode) {\n    super(status, { message: `ID validation failed: ${reason}` });\n    this.name = \"IdParamError\";\n    this.reason = reason;\n  }\n}\n\n/**\n * Options for `idParam` and `idQuery`. All fields are optional.\n *\n * **Default validation is structural** — `safeParse` checks prefix and base32 form but does not\n * verify any cryptographic tag. For IDs using a codec that satisfies {@link IdVerifiableCodec}\n * (the **Signed Timestamp codec** or **Wrapped key codec**), set `verify: true` to also authenticate the tag.\n */\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?: ContentfulStatusCode; malformed?: ContentfulStatusCode };\n};\n\n/**\n * Extends {@link IdParamOptions} with opt-in HMAC tag verification.\n * Only accepted when the codec satisfies {@link IdVerifiableCodec} (the **Signed Timestamp codec** or **Wrapped key codec**).\n * When `verify` is truthy, the adapter calls `codec.safeVerify(raw)` after structural parse succeeds;\n * a tag mismatch is routed through the existing `\"malformed\"` failure path.\n */\nexport type IdParamVerifyOptions = IdParamOptions & {\n  /** When truthy, calls `codec.safeVerify(raw)` after structural parse and treats a tag failure as `\"malformed\"`. Accepts any boolean so computed flags (`{ verify: cfg.verifyIds }`) compile without casting. */\n  verify?: boolean;\n};\n\nfunction emitFailure(\n  failure: IdParamFailure,\n  options: IdParamOptions | undefined,\n  c: Context,\n): Response | Promise<Response> {\n  if (options?.onError) {\n    return options.onError(failure, c);\n  }\n  throw new IdParamError(failure.reason, failure.status as ContentfulStatusCode);\n}\n\n/**\n * Hono middleware that validates a named route param against a codec via `safeParse`.\n *\n * **Default (no options):** throws `IdParamError` (extends `HTTPException`) carrying both the HTTP\n * status and `reason` so the app's existing `onError` handler can discriminate by reason. The\n * 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, IdParamError } from \"@smonn/ids/hono\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n *\n * // Default: throws IdParamError (extends 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 * // Discriminate by reason in app.onError\n * app.onError((err, c) => {\n *   if (err instanceof IdParamError) {\n *     return c.json({ error: err.reason }, err.status); // err.reason: \"brand_mismatch\" | \"malformed\"\n *   }\n *   return c.json({ error: \"internal\" }, 500);\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: IdVerifiableCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): MiddlewareHandler<{ Variables: Record<ParamKey, Id<Brand>> }>;\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>> }>;\nexport function idParam<ParamKey extends string, Brand extends string>(\n  paramName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamVerifyOptions,\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      return emitFailure(resolveIdParamFailure(result.error, options), options, c);\n    }\n    if (options?.verify) {\n      const verifyResult = await (codec as IdVerifiableCodec<Brand>).safeVerify(raw);\n      if (!verifyResult.ok) {\n        return emitFailure(resolveVerifyFailure(options), options, c);\n      }\n    }\n    c.set(paramName, result.id);\n    return next();\n  };\n}\n\n/**\n * Hono middleware that validates a named query-string param against a codec via `safeParse`.\n *\n * Same failure contract as `idParam` — same `IdParamFailure` shape, same `onError` / `status`\n * options — but reads `c.req.query(queryName)` instead of `c.req.param(queryName)`.\n *\n * **Default (no options):** throws `IdParamError` (extends `HTTPException`) carrying both the HTTP\n * status and `reason` so the app's existing `onError` handler can discriminate by reason. The\n * 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 query param → `reason: \"malformed\"`, default 400**\n *\n * On success, stores the canonical `Id<Brand>` in the Hono context under `queryName`\n * and calls `next()`.\n *\n * @example\n * ```ts\n * import { idQuery, IdParamError } from \"@smonn/ids/hono\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n *\n * // Default: throws IdParamError (extends HTTPException) → app.onError renders it\n * // GET /users?userId=usr_...\n * app.get(\"/users\", idQuery(\"userId\", usr), (c) => {\n *   const userId = c.get(\"userId\"); // Id<\"usr\">, canonical\n * });\n *\n * // Discriminate by reason in app.onError\n * app.onError((err, c) => {\n *   if (err instanceof IdParamError) {\n *     return c.json({ error: err.reason }, err.status); // err.reason: \"brand_mismatch\" | \"malformed\"\n *   }\n *   return c.json({ error: \"internal\" }, 500);\n * });\n *\n * // Override: consumer fully owns the response\n * app.get(\"/search\", idQuery(\"cursor\", usr, {\n *   onError: (failure, c) => c.json({ error: failure.reason }, failure.status),\n * }), handler);\n * ```\n */\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdVerifiableCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): MiddlewareHandler<{ Variables: Record<ParamKey, Id<Brand>> }>;\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamOptions,\n): MiddlewareHandler<{ Variables: Record<ParamKey, Id<Brand>> }>;\nexport function idQuery<ParamKey extends string, Brand extends string>(\n  queryName: ParamKey,\n  codec: IdCodec<Brand>,\n  options?: IdParamVerifyOptions,\n): MiddlewareHandler<{ Variables: Record<ParamKey, Id<Brand>> }> {\n  return async (c, next) => {\n    const raw = c.req.query(queryName);\n    const result = codec.safeParse(raw);\n    if (!result.ok) {\n      return emitFailure(resolveIdParamFailure(result.error, options), options, c);\n    }\n    if (options?.verify) {\n      const verifyResult = await (codec as IdVerifiableCodec<Brand>).safeVerify(raw);\n      if (!verifyResult.ok) {\n        return emitFailure(resolveVerifyFailure(options), options, c);\n      }\n    }\n    c.set(queryName, result.id);\n    return next();\n  };\n}\n"],"mappings":";;;;;;;AAkBA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