{"version":3,"file":"core.cjs","names":[],"sources":["../../src/core.ts"],"sourcesContent":["import type { SwaggerTransform, SwaggerTransformObject } from '@fastify/swagger'\nimport type {\n  FastifyPluginAsync,\n  FastifyPluginCallback,\n  FastifyPluginOptions,\n  FastifySchema,\n  FastifySchemaCompiler,\n  FastifySerializerCompiler,\n  FastifyTypeProvider,\n  RawServerBase,\n  RawServerDefault,\n} from 'fastify'\nimport type { $ZodRegistry, output } from 'zod/v4/core'\nimport { $ZodType, globalRegistry, safeEncode, safeParse } from 'zod/v4/core'\nimport { createValidationError, InvalidSchemaError, ResponseSerializationError } from './errors'\nimport {\n  createIORegistriesProvider,\n  generateIORegistries,\n  type SchemaRegistryMeta,\n} from './registry'\nimport { assertIsOpenAPIObject, getJSONSchemaTarget } from './utils'\nimport { type ZodToJsonConfig, zodRegistryToJson, zodSchemaToJson } from './zod-to-json'\n\ntype FreeformRecord = Record<string, any>\n\ntype ContentTypeResponse = {\n  description?: string\n  content: Record<string, { schema: $ZodType }>\n}\n\nconst isContentTypeResponse = (maybeSchema: unknown): maybeSchema is ContentTypeResponse => {\n  return (\n    typeof maybeSchema === 'object' &&\n    maybeSchema !== null &&\n    'content' in maybeSchema &&\n    typeof maybeSchema.content === 'object' &&\n    maybeSchema.content !== null\n  )\n}\n\nconst defaultSkipList = [\n  '/documentation/',\n  '/documentation/initOAuth',\n  '/documentation/json',\n  '/documentation/uiConfig',\n  '/documentation/yaml',\n  '/documentation/*',\n  '/documentation/static/*',\n]\n\nexport interface ZodTypeProvider extends FastifyTypeProvider {\n  validator: this['schema'] extends $ZodType ? output<this['schema']> : unknown\n  serializer: this['schema'] extends $ZodType ? output<this['schema']> : unknown\n}\n\ninterface Schema extends FastifySchema {\n  hide?: boolean\n}\n\ntype CreateJsonSchemaTransformOptions = {\n  skipList?: readonly string[]\n  schemaRegistry?: $ZodRegistry<SchemaRegistryMeta>\n  zodToJsonConfig?: ZodToJsonConfig\n}\n\nexport const createJsonSchemaTransform = ({\n  skipList = defaultSkipList,\n  schemaRegistry = globalRegistry,\n  zodToJsonConfig = {},\n}: CreateJsonSchemaTransformOptions): SwaggerTransform<Schema> => {\n  const getIORegistries = createIORegistriesProvider(schemaRegistry)\n\n  return (document) => {\n    assertIsOpenAPIObject(document)\n\n    const { schema, url } = document\n\n    if (!schema) {\n      return {\n        schema,\n        url,\n      }\n    }\n\n    const { response, headers, querystring, body, params, hide, ...rest } = schema\n\n    const transformed: FreeformRecord = {}\n\n    if (skipList.includes(url) || hide) {\n      transformed.hide = true\n      return { schema: transformed, url }\n    }\n\n    const target = getJSONSchemaTarget(document.openapiObject.openapi)\n    const config = {\n      target,\n      ...zodToJsonConfig,\n    }\n\n    const { inputRegistry, outputRegistry } = getIORegistries()\n\n    const zodSchemas: FreeformRecord = { headers, querystring, body, params }\n\n    for (const prop in zodSchemas) {\n      const zodSchema = zodSchemas[prop]\n      if (zodSchema) {\n        transformed[prop] = zodSchemaToJson(zodSchema, inputRegistry, 'input', config)\n      }\n    }\n\n    if (response) {\n      transformed.response = {}\n\n      for (const prop in response) {\n        const responseSchema = (response as any)[prop]\n\n        if (isContentTypeResponse(responseSchema)) {\n          const responseObj: FreeformRecord = {}\n\n          if (responseSchema.description) {\n            responseObj.description = responseSchema.description\n          }\n\n          responseObj.content = {}\n\n          for (const [contentType, { schema: maybeSchema }] of Object.entries(\n            responseSchema.content,\n          )) {\n            const zodSchema = resolveSchema(maybeSchema)\n            responseObj.content[contentType] = {\n              schema: zodSchemaToJson(zodSchema, outputRegistry, 'output', config),\n            }\n          }\n\n          transformed.response[prop] = responseObj\n          continue\n        }\n\n        const zodSchema = resolveSchema(responseSchema)\n        transformed.response[prop] = zodSchemaToJson(zodSchema, outputRegistry, 'output', config)\n      }\n    }\n\n    for (const prop in rest) {\n      const meta = rest[prop as keyof typeof rest]\n      if (meta) {\n        transformed[prop] = meta\n      }\n    }\n\n    return { schema: transformed, url }\n  }\n}\n\nexport const jsonSchemaTransform: SwaggerTransform<Schema> = createJsonSchemaTransform({})\n\ntype CreateJsonSchemaTransformObjectOptions = {\n  schemaRegistry?: $ZodRegistry<SchemaRegistryMeta>\n  zodToJsonConfig?: ZodToJsonConfig\n}\n\nexport const createJsonSchemaTransformObject =\n  ({\n    schemaRegistry = globalRegistry,\n    zodToJsonConfig = {},\n  }: CreateJsonSchemaTransformObjectOptions): SwaggerTransformObject =>\n  (document) => {\n    assertIsOpenAPIObject(document)\n\n    const target = getJSONSchemaTarget(document.openapiObject.openapi)\n    const config = {\n      target,\n      ...zodToJsonConfig,\n    }\n\n    const { inputRegistry, outputRegistry } = generateIORegistries(schemaRegistry)\n    const inputSchemas = zodRegistryToJson(inputRegistry, 'input', config)\n    const outputSchemas = zodRegistryToJson(outputRegistry, 'output', config)\n\n    return {\n      ...document.openapiObject,\n      components: {\n        ...document.openapiObject.components,\n        schemas: {\n          ...document.openapiObject.components?.schemas,\n          ...inputSchemas,\n          ...outputSchemas,\n        },\n      },\n    } as ReturnType<SwaggerTransformObject>\n  }\n\nexport const jsonSchemaTransformObject: SwaggerTransformObject = createJsonSchemaTransformObject({})\n\nexport const validatorCompiler: FastifySchemaCompiler<$ZodType> =\n  ({ schema }) =>\n  (data) => {\n    const result = safeParse(schema, data)\n    if (result.error) {\n      return { error: createValidationError(result.error) as unknown as Error }\n    }\n\n    return { value: result.data }\n  }\n\nfunction resolveSchema(maybeSchema: $ZodType | { properties: $ZodType }): $ZodType {\n  if (maybeSchema instanceof $ZodType) {\n    return maybeSchema\n  }\n  if ('properties' in maybeSchema && maybeSchema.properties instanceof $ZodType) {\n    return maybeSchema.properties\n  }\n  throw new InvalidSchemaError(JSON.stringify(maybeSchema))\n}\n\ntype ReplacerFunction = (this: any, key: string, value: any) => any\n\nexport type ZodSerializerCompilerOptions = {\n  replacer?: ReplacerFunction\n}\n\nexport const createSerializerCompiler =\n  (\n    options?: ZodSerializerCompilerOptions,\n  ): FastifySerializerCompiler<$ZodType | { properties: $ZodType }> =>\n  ({ schema: maybeSchema, method, url }) => {\n    const schema = resolveSchema(maybeSchema)\n    return (data) => {\n      const result = safeEncode(schema, data)\n      if (result.error) {\n        throw new ResponseSerializationError(method, url, {\n          cause: result.error,\n        })\n      }\n\n      return JSON.stringify(result.data, options?.replacer)\n    }\n  }\n\nexport const serializerCompiler: ReturnType<typeof createSerializerCompiler> =\n  createSerializerCompiler({})\n\n/**\n * FastifyPluginCallbackZod with Zod automatic type inference\n *\n * @example\n * ```typescript\n * import { FastifyPluginCallbackZod } from \"fastify-type-provider-zod\"\n *\n * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {\n *   done()\n * }\n * ```\n */\nexport type FastifyPluginCallbackZod<\n  Options extends FastifyPluginOptions = Record<never, never>,\n  Server extends RawServerBase = RawServerDefault,\n> = FastifyPluginCallback<Options, Server, ZodTypeProvider>\n\n/**\n * FastifyPluginAsyncZod with Zod automatic type inference\n *\n * @example\n * ```typescript\n * import { FastifyPluginAsyncZod } from \"fastify-type-provider-zod\"\n *\n * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {\n * }\n * ```\n */\nexport type FastifyPluginAsyncZod<\n  Options extends FastifyPluginOptions = Record<never, never>,\n  Server extends RawServerBase = RawServerDefault,\n> = FastifyPluginAsync<Options, Server, ZodTypeProvider>\n"],"mappings":";;;;;;AA8BA,IAAM,yBAAyB,gBAA6D;CAC1F,OACE,OAAO,gBAAgB,YACvB,gBAAgB,QAChB,aAAa,eACb,OAAO,YAAY,YAAY,YAC/B,YAAY,YAAY;AAE5B;AAEA,IAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAiBA,IAAa,6BAA6B,EACxC,WAAW,iBACX,iBAAiB,YAAA,gBACjB,kBAAkB,CAAC,QAC6C;CAChE,MAAM,kBAAkB,iBAAA,2BAA2B,cAAc;CAEjE,QAAQ,aAAa;EACnB,cAAA,sBAAsB,QAAQ;EAE9B,MAAM,EAAE,QAAQ,QAAQ;EAExB,IAAI,CAAC,QACH,OAAO;GACL;GACA;EACF;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