{"version":3,"file":"graphql.mjs","names":[],"sources":["../src/adapters/graphql.ts"],"sourcesContent":["import { GraphQLError, GraphQLScalarType, Kind } from \"graphql\";\nimport type { GraphQLFieldResolver, ValueNode } from \"graphql\";\nimport type { IdCodec, IdVerifiableCodec } from \"./adapter-types.js\";\nimport type { Id } from \"../types.js\";\n\n/** Extension of {@link IdCodec} that also requires `is()` — used by `idScalar` so `serialize` can validate strictly on the trusted outbound path. All concrete codec variants satisfy this. */\ntype GraphQLCodec<Brand extends string> = IdCodec<Brand> & {\n  is(value: unknown): value is Id<Brand>;\n};\n\n/** {@link IdsError} class, {@link isIdsError} type guard, and {@link IdsErrorCode} union — re-exported from `\"@smonn/ids\"` for convenience. */\nexport { IdsError, isIdsError, type IdsErrorCode } from \"../error.js\";\n\n/**\n * Builds a `GraphQLScalarType` for the given codec and brand.\n *\n * - `serialize` — validates strictly via `codec.is()`; throws `GraphQLError` on a non-canonical\n *   value and returns the value **unchanged** (no normalization) on success.\n * - `parseValue` — validates variables via `codec.safeParse`; throws `GraphQLError` on failure.\n *   Accepts mixed-case and Crockford visual aliases; always returns the canonical form.\n * - `parseLiteral` — validates inline `Kind.STRING` literals the same way as `parseValue`; throws\n *   `GraphQLError` for any other AST kind or on a failed `safeParse`.\n *\n * `graphql` must be installed as a peer dependency.\n *\n * @example\n * ```ts\n * import { idScalar } from \"@smonn/ids/graphql\";\n * import { createTimestampId } from \"@smonn/ids\";\n *\n * const usr = createTimestampId(\"usr\");\n * const UserIdScalar = idScalar(usr, { name: \"UserId\", description: \"A branded user ID.\" });\n * ```\n */\nexport function idScalar<Brand extends string>(\n  codec: GraphQLCodec<Brand>,\n  config: { name: string; description?: string },\n): GraphQLScalarType<Id<Brand>, string> {\n  const parse = (value: unknown): Id<Brand> => {\n    const result = codec.safeParse(value);\n    if (!result.ok) {\n      throw new GraphQLError(`invalid ${config.name}`);\n    }\n    return result.id;\n  };\n  return new GraphQLScalarType<Id<Brand>, string>({\n    name: config.name,\n    description: config.description,\n    serialize: (value: unknown): string => {\n      if (!codec.is(value)) {\n        throw new GraphQLError(`invalid ${config.name}`);\n      }\n      return value;\n    },\n    parseValue: parse,\n    parseLiteral: (ast: ValueNode) => {\n      if (ast.kind !== Kind.STRING) {\n        throw new GraphQLError(`${config.name} must be a string literal, got ${ast.kind}`);\n      }\n      return parse(ast.value);\n    },\n  });\n}\n\n/**\n * Wraps a GraphQL field resolver so the named ID arguments are authenticated before the resolver\n * body runs.\n *\n * GraphQL scalar coercers (`parseValue`/`parseLiteral`) are synchronous and cannot await the HMAC\n * check, so `idScalar` cannot verify a Signed Timestamp tag itself. `verifyIdArgs` performs that\n * async verification one layer out, at the resolver. For each `argName → codec` entry it calls\n * `codec.safeVerify(args[argName])`; a forged or tampered tag throws `GraphQLError` **before** the\n * wrapped resolver runs. A `null`/`undefined` arg is skipped (nullable/absent args pass through).\n * Present args are verified in map order and the first failure short-circuits.\n *\n * Both the **Signed Timestamp codec** and the **Wrapped key codec** satisfy\n * {@link IdVerifiableCodec}; passing any other codec is a compile-time type error. Verification\n * covers top-level args only — IDs nested inside input objects are not reached.\n *\n * **Pair with {@link idScalar}.** The wrapper checks the tag but returns `args` unchanged — it does\n * not substitute the canonical `id` from `safeVerify`. Front each verified arg with an `idScalar`\n * built from the same codec so `parseValue`/`parseLiteral` canonicalises the value (case, Crockford\n * aliases) before the resolver runs; on a plain `GraphQLString` arg a non-canonical variant would\n * verify yet reach the resolver un-normalised.\n *\n * **Only listed args are verified, and keys must match the field's argument names exactly.** On the\n * first invocation **for each schema coordinate** (`ParentType.fieldName`) the wrapper resolves\n * the field's declared argument names from `info` and throws a `GraphQLError` if any codec-map key\n * does not match a declared argument — hardening so a typo cannot silently disable verification.\n * Subsequent invocations on the **same coordinate** use the cached result. If the field cannot be\n * found in `parentType.getFields()`, the arg-name guard is skipped for that coordinate — this path\n * is **not** fail-closed for unknown fields — but per-ID `safeVerify` still runs on every\n * invocation regardless.\n *\n * @example\n * ```ts\n * import { verifyIdArgs } from \"@smonn/ids/graphql\";\n *\n * const resolve = verifyIdArgs({ userId: usr }, (_root, args, ctx) => {\n *   // args.userId is an authenticated Id<\"usr\">\n *   return ctx.loadUser(args.userId);\n * });\n * ```\n */\nexport function verifyIdArgs<\n  TSource,\n  TContext,\n  TArgs extends Record<string, unknown> = Record<string, unknown>,\n>(\n  codecs: { [K in keyof TArgs]?: IdVerifiableCodec<string> },\n  resolver: GraphQLFieldResolver<TSource, TContext, TArgs>,\n): GraphQLFieldResolver<TSource, TContext, TArgs> {\n  // Hoist to factory scope — the codec map is fixed at wrap time.\n  const codecEntries = (\n    Object.entries(codecs) as Array<[keyof TArgs & string, IdVerifiableCodec<string> | undefined]>\n  ).filter((e): e is [keyof TArgs & string, IdVerifiableCodec<string>] => e[1] !== undefined);\n\n  const checkedCoordinates = new Set<string>();\n\n  return async (source, args, context, info) => {\n    const coordinate = `${info.parentType.name}.${info.fieldName}`;\n    if (!checkedCoordinates.has(coordinate)) {\n      const field = info.parentType.getFields()[info.fieldName];\n      if (field !== undefined) {\n        const declaredNames = new Set(field.args.map((a) => a.name));\n        for (const [key] of codecEntries) {\n          if (!declaredNames.has(key)) {\n            throw new GraphQLError(\n              `verifyIdArgs: codec-map key \"${key}\" is not a declared argument on \"${info.fieldName}\"`,\n            );\n          }\n        }\n        checkedCoordinates.add(coordinate);\n      }\n    }\n\n    for (const [argName, codec] of codecEntries) {\n      const value = args[argName];\n      if (value == null) {\n        continue;\n      }\n      const result = await codec.safeVerify(value);\n      if (!result.ok) {\n        throw new GraphQLError(`invalid ${argName}`);\n      }\n    }\n    return resolver(source, args, context, info);\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,SACd,OACA,QACsC;CACtC,MAAM,SAAS,UAA8B;EAC3C,MAAM,SAAS,MAAM,UAAU,KAAK;EACpC,IAAI,CAAC,OAAO,IACV,MAAM,IAAI,aAAa,WAAW,OAAO,MAAM;EAEjD,OAAO,OAAO;CAChB;CACA,O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