{"version":3,"file":"OpenAIImageGenerator.mjs","names":[],"sources":["../src/OpenAIImageGenerator.ts"],"sourcesContent":["import { Context, Effect, Layer, type Redacted, Result, Schema, Stream } from \"effect\"\nimport { HttpClient, HttpClientRequest, type HttpClientResponse } from \"effect/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport type {\n  GeneratedImage,\n  ImageBase64Source,\n  ImageBytesSource,\n  ImageMimeType,\n} from \"@effect-uai/core/Image\"\nimport { imageBase64, imageUrl, pixelsOf } from \"@effect-uai/core/Image\"\nimport type {\n  CommonImageEditRequest,\n  CommonImageGenerateRequest,\n  CommonStreamImageEditRequest,\n  CommonStreamImageRequest,\n  ImageGeneratorService,\n  ImageResponse,\n  ImageUsage,\n} from \"@effect-uai/core/ImageGenerator\"\nimport { ImageGenerator, ImageStreamEvent, ImageStreaming } from \"@effect-uai/core/ImageGenerator\"\nimport * as SSE from \"@effect-uai/core/SSE\"\nimport { bodyMultipart, httpStatusError, imageToBlob, transportFailure } from \"./codec.js\"\nimport type { OpenAIImageModel } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Wire knobs shared by `/images/generations` and `/images/edits`. */\ntype OpenAIImageKnobs = {\n  /**\n   * Exact `\"WxH\"` or `\"auto\"`. Takes precedence over `aspectRatio` and\n   * `resolution`, which are then warn-dropped.\n   */\n  readonly size?: string\n  readonly quality?: \"low\" | \"medium\" | \"high\" | \"auto\"\n  /** `\"transparent\"` requires a png or webp `outputFormat`. */\n  readonly background?: \"transparent\" | \"opaque\" | \"auto\"\n  readonly outputFormat?: \"png\" | \"jpeg\" | \"webp\"\n  /** 0..100, jpeg and webp only. */\n  readonly outputCompression?: number\n  readonly moderation?: \"low\" | \"auto\"\n}\n\nexport type OpenAIImageGenerateRequest = Omit<CommonImageGenerateRequest, \"model\"> & {\n  readonly model: OpenAIImageModel\n} & OpenAIImageKnobs\n\n/**\n * Reference images for an edit. Narrowed off `ImageSource`: the endpoint's\n * multipart body uploads bytes, so a `url` variant has no wire\n * representation here and is a compile-time error rather than a 400.\n * Fetch it yourself and pass the bytes.\n */\nexport type OpenAIImageRef = ImageBase64Source | ImageBytesSource\n\nexport type OpenAIImageEditRequest = Omit<CommonImageEditRequest, \"model\" | \"images\"> & {\n  readonly model: OpenAIImageModel\n  readonly images: ReadonlyArray<OpenAIImageRef>\n} & OpenAIImageKnobs & {\n    /** PNG with an alpha channel, same dimensions as `images[0]`, which it applies to. */\n    readonly mask?: OpenAIImageRef\n  }\n\nexport type OpenAIStreamImageRequest = Omit<CommonStreamImageRequest, \"model\"> & {\n  readonly model: OpenAIImageModel\n} & OpenAIImageKnobs\n\nexport type OpenAIStreamImageEditRequest = OpenAIImageEditRequest & {\n  readonly partialImages: 1 | 2 | 3\n}\n\nexport type OpenAIImageGeneratorService = {\n  readonly generate: (\n    request: OpenAIImageGenerateRequest,\n  ) => Effect.Effect<ImageResponse, AiError.AiError>\n  readonly edit: (request: OpenAIImageEditRequest) => Effect.Effect<ImageResponse, AiError.AiError>\n  readonly streamGeneration: (\n    request: OpenAIStreamImageRequest,\n  ) => Stream.Stream<ImageStreamEvent, AiError.AiError>\n  readonly streamEdit: (\n    request: OpenAIStreamImageEditRequest,\n  ) => Stream.Stream<ImageStreamEvent, AiError.AiError>\n}\n\n/**\n * Provider-typed service tag. Yield this for exact pixel sizes, quality\n * tiers, transparency, and masks; yield the generic `ImageGenerator` tag\n * for provider-portable code. Both are registered by `layer`.\n */\nexport class OpenAIImageGenerator extends Context.Service<\n  OpenAIImageGenerator,\n  OpenAIImageGeneratorService\n>()(\"@betalyra/effect-uai/providers/openai/OpenAIImageGenerator\") {}\n\nexport type Config = {\n  readonly apiKey: Redacted.Redacted\n  readonly baseUrl?: string\n  readonly region?: OpenAiRegion\n}\n\n// ---------------------------------------------------------------------------\n// Codec - size\n//\n// The portable request carries a ratio and a tier; this endpoint wants\n// `\"WxH\"`. Whether the derived pair is in range for the model is the\n// server's call: per-model limits churn and we do not table them.\n// ---------------------------------------------------------------------------\n\n/**\n * Derive `\"WxH\"` from the portable ratio and tier. `undefined` means\n * \"send no size\" and let the endpoint pick.\n */\nexport const sizeOf = (\n  request: Pick<OpenAIImageGenerateRequest, \"size\" | \"aspectRatio\" | \"resolution\">,\n): Effect.Effect<string | undefined, AiError.AiError> =>\n  Effect.gen(function* () {\n    if (request.size !== undefined) {\n      // Explicit pixels win, but the shape the caller also asked for is one\n      // they will not get: say so rather than drop it silently.\n      const overridden = `\\`size: \"${request.size}\"\\` sets the dimensions directly.`\n      yield* Capabilities.warnDroppedWhen(request.aspectRatio, {\n        provider: \"openai\",\n        capability: \"aspectRatio\",\n        field: \"aspectRatio\",\n        reason: overridden,\n      })\n      yield* Capabilities.warnDroppedWhen(request.resolution, {\n        provider: \"openai\",\n        capability: \"resolution\",\n        field: \"resolution\",\n        reason: overridden,\n      })\n      return request.size\n    }\n    return yield* Result.match(pixelsOf(request), {\n      onSuccess: (pixels) =>\n        Effect.succeed(pixels === undefined ? undefined : `${pixels.width}x${pixels.height}`),\n      onFailure: (reason) =>\n        Effect.fail(\n          new AiError.InvalidRequest({\n            provider: \"openai\",\n            param: \"aspectRatio\",\n            raw: `${reason} The Images API takes \"WxH\"; set \\`size\\` directly to bypass the derivation.`,\n          }),\n        ),\n    })\n  })\n\n// ---------------------------------------------------------------------------\n// Codec - request bodies\n// ---------------------------------------------------------------------------\n\nexport type WireBody = {\n  readonly prompt: string\n  readonly model: string\n  readonly n?: number\n  readonly size?: string\n  readonly quality?: string\n  readonly background?: string\n  readonly output_format?: string\n  readonly output_compression?: number\n  readonly moderation?: string\n  readonly stream?: boolean\n  readonly partial_images?: number\n}\n\n// Out-of-range values (`n` above 10, compression above 100, an impossible\n// `size`) go out as given: the endpoint adjudicates and its 400 is\n// translated, so no range table lives here.\nconst knobFields = (\n  request: OpenAIImageKnobs & { readonly n?: number },\n  size: string | undefined,\n) => ({\n  ...(request.n !== undefined && { n: request.n }),\n  ...(size !== undefined && { size }),\n  ...(request.quality !== undefined && { quality: request.quality }),\n  ...(request.background !== undefined && { background: request.background }),\n  ...(request.outputFormat !== undefined && { output_format: request.outputFormat }),\n  ...(request.outputCompression !== undefined && { output_compression: request.outputCompression }),\n  ...(request.moderation !== undefined && { moderation: request.moderation }),\n})\n\nexport const generateBody = (\n  request: OpenAIImageGenerateRequest,\n): Effect.Effect<WireBody, AiError.AiError> =>\n  Effect.map(sizeOf(request), (size) => ({\n    prompt: request.prompt,\n    model: request.model,\n    ...knobFields(request, size),\n  }))\n\nconst EXTENSION_BY_MIME: Record<string, string> = {\n  \"image/png\": \"png\",\n  \"image/jpeg\": \"jpg\",\n  \"image/webp\": \"webp\",\n}\n\n/** The endpoint reads the format off the filename, not the content type. */\nconst fileName = (blob: Blob, index: number): string =>\n  `image-${index}.${EXTENSION_BY_MIME[blob.type] ?? \"png\"}`\n\n/**\n * Multipart edit body. The endpoint also documents a JSON variant taking\n * `images[]` as URL or data-URL references, but it is not universally\n * served: Azure-backed routes validate against this schema and reject the\n * JSON one with \"Missing required parameter: 'image'\". Multipart works\n * everywhere, so it is the only variant sent.\n *\n * References upload as repeated `image[]` parts, so they must be inline\n * bytes; a URL source fails `InvalidRequest`.\n */\nexport const editForm = (\n  request: OpenAIImageEditRequest,\n): Effect.Effect<FormData, AiError.AiError> =>\n  Effect.gen(function* () {\n    const size = yield* sizeOf(request)\n    const blobs = yield* Effect.forEach(request.images, imageToBlob)\n    const form = new FormData()\n    form.set(\"prompt\", request.prompt)\n    form.set(\"model\", request.model)\n    // The endpoint's required field is `image`, a single file. Only the\n    // multi-reference form uses the repeated `image[]`, and a server that\n    // implements just the single-file schema rejects `image[]` outright.\n    const field = blobs.length > 1 ? \"image[]\" : \"image\"\n    blobs.forEach((blob, index) => form.append(field, blob, fileName(blob, index)))\n    if (request.mask !== undefined) {\n      const mask = yield* imageToBlob(request.mask)\n      form.set(\"mask\", mask, fileName(mask, 0))\n    }\n    Object.entries(knobFields(request, size)).forEach(([key, value]) =>\n      form.set(key, String(value)),\n    )\n    return form\n  })\n\n/** The edit form plus the two streaming fields, which multipart sends as strings. */\nexport const streamEditForm = (\n  request: OpenAIStreamImageEditRequest,\n): Effect.Effect<FormData, AiError.AiError> =>\n  Effect.map(editForm(request), (form) => {\n    form.set(\"stream\", \"true\")\n    form.set(\"partial_images\", String(request.partialImages))\n    return form\n  })\n\nexport const streamBody = (\n  request: OpenAIStreamImageRequest,\n): Effect.Effect<WireBody, AiError.AiError> =>\n  Effect.map(generateBody(request), (body) => ({\n    ...body,\n    stream: true,\n    partial_images: request.partialImages,\n  }))\n\n// ---------------------------------------------------------------------------\n// Codec - response\n// ---------------------------------------------------------------------------\n\nconst WireUsage = Schema.Struct({\n  input_tokens: Schema.optional(Schema.Number),\n  output_tokens: Schema.optional(Schema.Number),\n  total_tokens: Schema.optional(Schema.Number),\n})\ntype WireUsage = typeof WireUsage.Type\n\n// `created`, `usage`, `url`, and `revised_prompt` stay optional so the\n// narrower payloads served by OpenAI-compatible gateways decode too.\nconst WireImagesResponse = Schema.Struct({\n  created: Schema.optional(Schema.Number),\n  data: Schema.Array(\n    Schema.Struct({\n      b64_json: Schema.optional(Schema.String),\n      url: Schema.optional(Schema.String),\n      revised_prompt: Schema.optional(Schema.String),\n    }),\n  ),\n  output_format: Schema.optional(Schema.String),\n  usage: Schema.optional(WireUsage),\n})\ntype WireImagesResponse = typeof WireImagesResponse.Type\n\nexport const decodeImagesResponse = Schema.decodeUnknownEffect(WireImagesResponse)\n\nconst MIME_BY_FORMAT: Record<string, ImageMimeType> = {\n  png: \"image/png\",\n  jpeg: \"image/jpeg\",\n  webp: \"image/webp\",\n}\n\n/** The response echoes the realized format; the request's is the fallback. */\nconst mimeOf = (\n  wireFormat: string | undefined,\n  requested: OpenAIImageKnobs[\"outputFormat\"],\n): ImageMimeType => MIME_BY_FORMAT[wireFormat ?? requested ?? \"png\"] ?? \"image/png\"\n\nconst usageOf = (usage: WireUsage | undefined): ImageUsage => ({\n  ...(usage?.input_tokens !== undefined && { inputTokens: usage.input_tokens }),\n  ...(usage?.output_tokens !== undefined && { outputTokens: usage.output_tokens }),\n  ...(usage?.total_tokens !== undefined && { totalTokens: usage.total_tokens }),\n})\n\n// GPT image models always return base64; `url` is decoded for gateways that\n// hand back a link instead. No watermark: OpenAI documents none.\nconst imageOf = (\n  entry: WireImagesResponse[\"data\"][number],\n  mime: ImageMimeType,\n): GeneratedImage | undefined =>\n  entry.b64_json !== undefined\n    ? { image: imageBase64(entry.b64_json, mime) }\n    : entry.url !== undefined\n      ? { image: imageUrl(entry.url, mime) }\n      : undefined\n\nexport const toResponse = (\n  wire: WireImagesResponse,\n  requested: OpenAIImageKnobs[\"outputFormat\"],\n): Effect.Effect<ImageResponse, AiError.AiError> => {\n  const mime = mimeOf(wire.output_format, requested)\n  const images = wire.data.flatMap((entry) => {\n    const image = imageOf(entry, mime)\n    return image === undefined ? [] : [image]\n  })\n  return images.length === 0\n    ? Effect.fail(\n        new AiError.GenerationFailed({\n          provider: \"openai\",\n          message: \"OpenAI returned no image data.\",\n          raw: wire,\n        }),\n      )\n    : Effect.succeed({ images, usage: usageOf(wire.usage) })\n}\n\n// ---------------------------------------------------------------------------\n// Codec - errors\n// ---------------------------------------------------------------------------\n\nconst WireError = Schema.Struct({\n  error: Schema.Struct({\n    code: Schema.optional(Schema.NullOr(Schema.String)),\n    message: Schema.optional(Schema.String),\n    type: Schema.optional(Schema.String),\n  }),\n})\ntype WireError = typeof WireError.Type\n\nconst decodeWireError = Schema.decodeUnknownEffect(Schema.fromJsonString(WireError))\n\n/**\n * A moderation refusal is a content decision, not a malformed request, so\n * it leaves the status mapping and becomes `ContentFiltered`. Both the\n * documented markers are checked: `moderation_details` is docs-only and\n * absent from the OpenAPI error schema, so it is not relied on.\n */\nconst moderationOf = (wire: WireError, raw: string): AiError.AiError | undefined => {\n  const { error } = wire\n  return error.code === \"moderation_blocked\" || error.type === \"image_generation_user_error\"\n    ? new AiError.ContentFiltered({\n        provider: \"openai\",\n        ...(error.message !== undefined && { reason: error.message }),\n        raw,\n      })\n    : undefined\n}\n\nconst classify = (body: string, fallback: () => AiError.AiError): Effect.Effect<AiError.AiError> =>\n  decodeWireError(body).pipe(\n    Effect.map((wire) => moderationOf(wire, body) ?? fallback()),\n    Effect.orElseSucceed(fallback),\n  )\n\n/** Never fails: the returned error is the value. */\nexport const imageHttpError = (status: number, body: string): Effect.Effect<AiError.AiError> =>\n  classify(body, () => httpStatusError(status, body))\n\n/**\n * An error frame mid-stream. The HTTP status was 200, so the status\n * mapping has nothing to say and a non-moderation failure is one the\n * model hit while generating.\n */\nexport const imageStreamError = (body: string): Effect.Effect<AiError.AiError> =>\n  classify(body, () => new AiError.GenerationFailed({ provider: \"openai\", raw: body }))\n\n// ---------------------------------------------------------------------------\n// Codec - stream frames\n// ---------------------------------------------------------------------------\n\nconst WirePartialImage = Schema.Struct({\n  type: Schema.Literal(\"image_generation.partial_image\"),\n  b64_json: Schema.String,\n  partial_image_index: Schema.Number,\n  output_format: Schema.optional(Schema.String),\n})\n\nconst WireCompletedImage = Schema.Struct({\n  type: Schema.Literal(\"image_generation.completed\"),\n  b64_json: Schema.String,\n  output_format: Schema.optional(Schema.String),\n  usage: Schema.optional(WireUsage),\n})\n\nconst WireStreamFrame = Schema.Union([WirePartialImage, WireCompletedImage])\ntype WireStreamFrame = typeof WireStreamFrame.Type\n\nconst decodeStreamFrame = Schema.decodeUnknownEffect(Schema.fromJsonString(WireStreamFrame))\n\nconst toStreamEvent = (\n  wire: WireStreamFrame,\n  requested: OpenAIImageKnobs[\"outputFormat\"],\n): ImageStreamEvent => {\n  const image = imageBase64(wire.b64_json, mimeOf(wire.output_format, requested))\n  return wire.type === \"image_generation.partial_image\"\n    ? ImageStreamEvent.PartialImage({ image, index: wire.partial_image_index })\n    : ImageStreamEvent.Complete({ images: [{ image }], usage: usageOf(wire.usage) })\n}\n\n/**\n * Decode one SSE frame. Frames this capability has no representation for\n * decode to `undefined` and are dropped, so a new event type on the wire\n * does not break the stream.\n */\nexport const streamEventOf = (\n  event: SSE.Event,\n  requested: OpenAIImageKnobs[\"outputFormat\"],\n): Effect.Effect<ImageStreamEvent | undefined, AiError.AiError> =>\n  event.event === \"error\"\n    ? Effect.flatMap(imageStreamError(event.data), Effect.fail)\n    : decodeStreamFrame(event.data).pipe(\n        Effect.map((wire) => toStreamEvent(wire, requested)),\n        Effect.orElseSucceed(() => undefined),\n      )\n\n// ---------------------------------------------------------------------------\n// HTTP\n// ---------------------------------------------------------------------------\n\n/** Generations take JSON, edits take multipart; only the body differs. */\nconst post = (\n  cfg: Config,\n  path: string,\n  withBody: (request: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest,\n): Effect.Effect<HttpClientResponse.HttpClientResponse, AiError.AiError, HttpClient.HttpClient> =>\n  Effect.flatMap(HttpClient.HttpClient, (client) =>\n    client\n      .execute(\n        HttpClientRequest.post(`${resolveHost(cfg)}${path}`).pipe(\n          HttpClientRequest.bearerToken(cfg.apiKey),\n          withBody,\n        ),\n      )\n      .pipe(Effect.mapError(transportFailure)),\n  )\n\nconst failOnStatus = (\n  response: HttpClientResponse.HttpClientResponse,\n): Effect.Effect<void, AiError.AiError> =>\n  response.status < 400\n    ? Effect.void\n    : Effect.gen(function* () {\n        const body = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n        return yield* Effect.flatMap(imageHttpError(response.status, body), Effect.fail)\n      })\n\nconst requestImages = (\n  cfg: Config,\n  path: string,\n  withBody: (request: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest,\n  requested: OpenAIImageKnobs[\"outputFormat\"],\n): Effect.Effect<ImageResponse, AiError.AiError, HttpClient.HttpClient> =>\n  Effect.gen(function* () {\n    const response = yield* post(cfg, path, withBody)\n    yield* failOnStatus(response)\n    const json = yield* response.json.pipe(Effect.mapError(transportFailure))\n    const wire = yield* decodeImagesResponse(json).pipe(Effect.mapError(transportFailure))\n    return yield* toResponse(wire, requested)\n  })\n\nconst generateImpl = (cfg: Config) => (request: OpenAIImageGenerateRequest) =>\n  Effect.flatMap(generateBody(request), (body) =>\n    requestImages(\n      cfg,\n      \"/images/generations\",\n      HttpClientRequest.bodyJsonUnsafe(body),\n      request.outputFormat,\n    ),\n  )\n\nconst editImpl = (cfg: Config) => (request: OpenAIImageEditRequest) =>\n  Effect.flatMap(Effect.flatMap(editForm(request), bodyMultipart), (withBody) =>\n    requestImages(cfg, \"/images/edits\", withBody, request.outputFormat),\n  )\n\n/** Both streaming endpoints answer with the same SSE frames. */\nconst streamFrames = (\n  cfg: Config,\n  path: string,\n  withBody: (request: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest,\n  requested: OpenAIImageKnobs[\"outputFormat\"],\n): Stream.Stream<ImageStreamEvent, AiError.AiError, HttpClient.HttpClient> =>\n  Stream.unwrap(\n    Effect.gen(function* () {\n      // `stream: true` in the body is what OpenAI keys off, but gateways in\n      // front of it read the header, so send both like every other\n      // streaming adapter here does.\n      const response = yield* post(cfg, path, (request) =>\n        HttpClientRequest.accept(\"text/event-stream\")(withBody(request)),\n      )\n      yield* failOnStatus(response)\n      return response.stream.pipe(\n        Stream.mapError(transportFailure),\n        SSE.fromBytes,\n        Stream.mapEffect((event) => streamEventOf(event, requested)),\n        Stream.filter((event) => event !== undefined),\n      )\n    }),\n  )\n\nconst streamImpl = (cfg: Config) => (request: OpenAIStreamImageRequest) =>\n  Stream.unwrap(\n    Effect.map(streamBody(request), (body) =>\n      streamFrames(\n        cfg,\n        \"/images/generations\",\n        HttpClientRequest.bodyJsonUnsafe(body),\n        request.outputFormat,\n      ),\n    ),\n  )\n\nconst streamEditImpl = (cfg: Config) => (request: OpenAIStreamImageEditRequest) =>\n  Stream.unwrap(\n    Effect.map(Effect.flatMap(streamEditForm(request), bodyMultipart), (withBody) =>\n      streamFrames(cfg, \"/images/edits\", withBody, request.outputFormat),\n    ),\n  )\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\nexport const make = (\n  cfg: Config,\n): Effect.Effect<OpenAIImageGeneratorService, never, HttpClient.HttpClient> =>\n  Effect.map(HttpClient.HttpClient, (client): OpenAIImageGeneratorService => ({\n    generate: (request) =>\n      generateImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n    edit: (request) =>\n      editImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n    streamGeneration: (request) =>\n      streamImpl(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client)),\n    streamEdit: (request) =>\n      streamEditImpl(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client)),\n  }))\n\n/**\n * Layer registering the provider-typed tag, the generic `ImageGenerator`,\n * and the `ImageStreaming` marker. A `CommonImageGenerateRequest` is\n * structurally an `OpenAIImageGenerateRequest` with no vendor knobs set,\n * so the generic registration forwards directly.\n *\n * `baseUrl` retargets the same wire protocol at an OpenAI-compatible\n * gateway. Whether such a gateway honours partial images is not this\n * Layer's promise; the marker is registered for the models it routes to.\n */\nexport const layer = (\n  cfg: Config,\n): Layer.Layer<\n  OpenAIImageGenerator | ImageGenerator | ImageStreaming,\n  never,\n  HttpClient.HttpClient\n> =>\n  Layer.mergeAll(\n    Layer.effect(OpenAIImageGenerator, make(cfg)),\n    Layer.effect(\n      ImageGenerator,\n      Effect.map(make(cfg), (s): ImageGeneratorService => ({\n        generate: (request: CommonImageGenerateRequest) =>\n          s.generate(request as OpenAIImageGenerateRequest),\n        edit: (request: CommonImageEditRequest) => s.edit(request as OpenAIImageEditRequest),\n        streamGeneration: (request: CommonStreamImageRequest) =>\n          s.streamGeneration(request as OpenAIStreamImageRequest),\n        streamEdit: (request: CommonStreamImageEditRequest) =>\n          s.streamEdit(request as OpenAIStreamImageEditRequest),\n      })),\n    ),\n    Layer.succeed(ImageStreaming, undefined),\n  )\n"],"mappings":";;;;;;;;;;;;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