@enlitt/sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/LICENSE +21 -0
- package/README.md +61 -2
- package/dist/browser/auth.d.cts +44 -0
- package/dist/browser/auth.d.ts +45 -0
- package/dist/browser/auth.d.ts.map +1 -0
- package/dist/browser.cjs +35 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +12 -0
- package/dist/browser.d.ts +13 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +32 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-26SW63P5.cjs +883 -0
- package/dist/chunk-26SW63P5.cjs.map +1 -0
- package/dist/chunk-6DPBYLA5.js +855 -0
- package/dist/chunk-6DPBYLA5.js.map +1 -0
- package/dist/chunk-6OWXYBBT.cjs +146 -0
- package/dist/chunk-6OWXYBBT.cjs.map +1 -0
- package/dist/chunk-C76K6HLL.cjs +906 -0
- package/dist/chunk-C76K6HLL.cjs.map +1 -0
- package/dist/chunk-G4DTTV5E.cjs +35 -0
- package/dist/chunk-G4DTTV5E.cjs.map +1 -0
- package/dist/chunk-SFI4RLNN.js +900 -0
- package/dist/chunk-SFI4RLNN.js.map +1 -0
- package/dist/chunk-V5TCSQ7C.js +143 -0
- package/dist/chunk-V5TCSQ7C.js.map +1 -0
- package/dist/chunk-VNVMEU34.js +33 -0
- package/dist/chunk-VNVMEU34.js.map +1 -0
- package/dist/core/errors.d.cts +254 -0
- package/dist/core/errors.d.ts +255 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/index.d.cts +24 -0
- package/dist/core/index.d.ts +25 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/premium.d.cts +230 -0
- package/dist/core/premium.d.ts +231 -0
- package/dist/core/premium.d.ts.map +1 -0
- package/dist/core/session.d.cts +107 -0
- package/dist/core/session.d.ts +108 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/sse.d.cts +79 -0
- package/dist/core/sse.d.ts +80 -0
- package/dist/core/sse.d.ts.map +1 -0
- package/dist/core/transport.d.cts +223 -0
- package/dist/core/transport.d.ts +224 -0
- package/dist/core/transport.d.ts.map +1 -0
- package/dist/core/usage.d.cts +35 -0
- package/dist/core/usage.d.ts +36 -0
- package/dist/core/usage.d.ts.map +1 -0
- package/dist/core.cjs +73 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.js +4 -0
- package/dist/core.js.map +1 -0
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +16 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/openai/client.d.cts +48 -0
- package/dist/openai/client.d.ts +49 -0
- package/dist/openai/client.d.ts.map +1 -0
- package/dist/openai/index.d.cts +1 -0
- package/dist/openai/index.d.ts +2 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai.cjs +479 -0
- package/dist/openai.cjs.map +1 -0
- package/dist/openai.js +473 -0
- package/dist/openai.js.map +1 -0
- package/dist/server/callback.d.cts +106 -0
- package/dist/server/callback.d.ts +107 -0
- package/dist/server/callback.d.ts.map +1 -0
- package/dist/server/index.d.cts +19 -0
- package/dist/server/index.d.ts +20 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/secrets.d.cts +46 -0
- package/dist/server/secrets.d.ts +47 -0
- package/dist/server/secrets.d.ts.map +1 -0
- package/dist/server-unavailable.cjs +8 -0
- package/dist/server-unavailable.cjs.map +1 -0
- package/dist/server-unavailable.d.cts +10 -0
- package/dist/server-unavailable.d.ts +11 -0
- package/dist/server-unavailable.d.ts.map +1 -0
- package/dist/server-unavailable.js +6 -0
- package/dist/server-unavailable.js.map +1 -0
- package/dist/server.cjs +354 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.js +275 -0
- package/dist/server.js.map +1 -0
- package/dist/vercel/index.d.cts +15 -0
- package/dist/vercel/index.d.ts +16 -0
- package/dist/vercel/index.d.ts.map +1 -0
- package/dist/vercel/language-model.d.cts +131 -0
- package/dist/vercel/language-model.d.ts +132 -0
- package/dist/vercel/language-model.d.ts.map +1 -0
- package/dist/vercel/premium-language-model.d.cts +98 -0
- package/dist/vercel/premium-language-model.d.ts +99 -0
- package/dist/vercel/premium-language-model.d.ts.map +1 -0
- package/dist/vercel/standard-language-model.d.cts +104 -0
- package/dist/vercel/standard-language-model.d.ts +105 -0
- package/dist/vercel/standard-language-model.d.ts.map +1 -0
- package/dist/vercel.cjs +22 -0
- package/dist/vercel.cjs.map +1 -0
- package/dist/vercel.js +5 -0
- package/dist/vercel.js.map +1 -0
- package/package.json +129 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/errors.ts","../src/core/session.ts","../src/server/secrets.ts","../src/core/transport.ts","../src/core/premium.ts"],"names":["isEnlittErrorCode","ENLITT_ERROR_CODES","ENLITT_ERROR_CODE","classifyEnlittErrorResponse","facts","input","AsyncLocalStorage","ENLITT_VERSION_HEADER","ENLITT_API_VERSION","IDEMPOTENCY_KEY_MIN_LENGTH","parseCanonicalInteger","CanonicalIntegerError","validateCallerMetadata","assertIdempotencyKey","IdempotencyKeyError","IDEMPOTENCY_KEY_MAX_LENGTH","validateBeginPremiumOperationRequest","validateBeginPremiumOperationResponse","validateReportPremiumTerminalRequest","validateReportPremiumTerminalResponse"],"mappings":";;;;;;AAgGO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACnB,IAAA,GAAe,aAAA;AAAA,EAExB,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,eAAA,GAA2B,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ3B,SAAA;AAAA,EAEA,YAAA;AAAA,EACA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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A,CAAQ,QAAA,EAAU,UAAU,CAAA,GAAI,MAAA;AAExF,EAAA,OAAO,gBAAA;AAAA,IACL,MAAA;AAAA,IACA;AAAA,MACE,SAAA;AAAA,MACA,QAAA,EAAU,EAAE,EAAA,EAAI,OAAA,CAAQ,SAAS,EAAA,EAAI,KAAA,EAAO,OAAA,CAAQ,QAAA,CAAS,KAAA,EAAM;AAAA,MACnE,GAAI,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,KAAW,EAAC;AAAA,MACzC,GAAI,mBAAA,KAAwB,MAAA,GAAY,EAAE,mBAAA,KAAwB,EAAC;AAAA,MACnE,GAAI,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,KAAa,EAAC;AAAA,MAC7C,GAAI,QAAQ,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,OAAA,CAAQ,MAAA,EAAO,GAAI;AAAC,KACnE;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-26SW63P5.cjs","sourcesContent":["/**\n * The SDK's typed error hierarchy and the single mapping from an Enlitt\n * failure to one of its classes.\n *\n * This file declares no wire code list of its own. The stable codes, their\n * OpenAI-shaped `type`, their HTTP status, their retryability, and whether\n * they may carry `authorize_url` all come from the frozen record\n * `@enlitt/protocol` exports — the same record the backend raises from. That\n * is what keeps a code, and every fact about it, declared exactly once across\n * the wire rather than asserted independently in two workspaces.\n *\n * It declares one small closed set of SDK-local codes, for the four failures\n * that never reach the wire and so can have no entry in the protocol record.\n * That set is provably disjoint from the record's codes (see\n * `_LocalCodesDisjointFromWireCodes` below), so no reader ever has to ask\n * which side of the wire a given code came from.\n *\n * No class here carries a balance, plan, service tier, period, or personal\n * identity, and none wraps a provider's own error — a provider failure that\n * passes through the premium path is rethrown unchanged by\n * `normalizeEnlittModelError` and is never an instance of `EnlittError`.\n */\n\nimport {\n classifyEnlittErrorResponse,\n ENLITT_ERROR_CODE,\n ENLITT_ERROR_CODES,\n isEnlittErrorCode,\n // The frozen record's key type. Aliased on import so every reference in\n // this file reads as \"Enlitt's stable wire code\" rather than as a type this\n // module happens to reuse; the alias carries no members of its own.\n type EnlittErrorCode as EnlittWireCode\n} from \"@enlitt/protocol\";\n\n/**\n * The only codes this module originates. They exist because these four\n * failures never reach the wire: bad or missing configuration, a request\n * that never produced an HTTP response, a response that could not be parsed,\n * and a caller-initiated abort. All four are always non-retryable and always\n * report `providerInvoked: false`, the same as every wire-originated code,\n * because none of them means a provider was ever reached either.\n */\nexport type EnlittLocalCode =\n | \"configuration_invalid\"\n | \"transport_failed\"\n | \"malformed_response\"\n | \"request_canceled\";\n\n/**\n * A type-level proof, not a runtime check: if a future edit ever gives a\n * local code the same name as a protocol code, the intersection below stops\n * being `never` and this file fails to compile. `AssertNever` exists only to\n * force that failure at the point of collision instead of letting `EnlittError`\n * silently become ambiguous about which side of the wire a code came from.\n */\ntype AssertNever<T extends never> = T;\ntype _LocalCodesDisjointFromWireCodes = AssertNever<EnlittLocalCode & EnlittWireCode>;\n\n/**\n * The bounded facts a caller may attach when constructing an error: the\n * parsed `Retry-After`, the upstream `x-request-id`, and a navigation target.\n * Every field is optional because most codes carry none of them — a local\n * code carries none at all, and `authorizeUrl` is stored only where the\n * record permits the resulting code to carry one (see `EnlittError` below).\n */\nexport interface EnlittErrorFacts {\n /** Milliseconds, converted once from the wire's `Retry-After` seconds. */\n readonly retryAfterMs?: number;\n readonly requestId?: string;\n readonly authorizeUrl?: string;\n /**\n * Only meaningful for a code the record does not contain: the protocol\n * classifier's status-derived answer for a code from a newer server. A code\n * in the record always takes its `retryable` from the record instead.\n */\n readonly retryable?: boolean;\n}\n\n/**\n * Any other string: a code this SDK version does not know. `string & {}`\n * keeps editor completion for the known codes while forcing every business\n * `switch` over `EnlittError[\"code\"]` to carry a `default` branch. Exported as\n * a type only; it adds no runtime value.\n */\nexport type EnlittUnrecognizedCode = string & {};\n\n/**\n * The base class for every Enlitt-originated failure, and the only carrier\n * of Enlitt's stable wire codes into a caller's code.\n *\n * Enlitt failures with no distinct business action of their own — invalid\n * request, unsupported capability, conflict, routing, and server failures,\n * plus a wire code newer than this SDK knows — surface as this class\n * directly, carrying their stable code. Every other wire code that does\n * imply a distinct action gets its own subclass below.\n */\nexport class EnlittError extends Error {\n override readonly name: string = \"EnlittError\";\n\n readonly code: EnlittWireCode | EnlittLocalCode | EnlittUnrecognizedCode;\n\n /**\n * Always `false`. Enlitt refuses before a provider is ever reached, so no\n * instance of this hierarchy can report otherwise — that is the one\n * question a business needs answered before it retries or bills anything.\n * A provider's own error is never wrapped in this class in the first\n * place; see `normalizeEnlittModelError`.\n */\n readonly providerInvoked: boolean = false;\n\n /**\n * Read from the frozen record for a wire code, and always `false` for a\n * local code, which has no record entry. Never decided per instance: a\n * refusal carries the non-retryable marker the pinned Vercel AI SDK reads,\n * so a configured `maxRetries` cannot turn one refusal into several.\n */\n readonly retryable: boolean;\n\n readonly retryAfterMs?: number;\n readonly requestId?: string;\n\n /**\n * Present only when the record's `authorizeUrl` field for this instance's\n * code is `\"allowed\"` and a caller supplied one. It is a navigation\n * target, never a disclosure: the actual figures live only on Enlitt's own\n * dashboard behind it.\n *\n * The record allows this on the four `insufficient_credits_error` codes and\n * no others, which is what this module's spec text says. `authorizeUrl` is\n * still read from the record rather than decided here, per this module's own\n * rule; the record simply now agrees with the spec.\n */\n readonly authorizeUrl?: string;\n\n constructor(\n code: EnlittWireCode | EnlittLocalCode | EnlittUnrecognizedCode,\n message: string,\n facts: EnlittErrorFacts = {}\n ) {\n super(message);\n this.code = code;\n\n const definition = isEnlittErrorCode(code) ? ENLITT_ERROR_CODES[code] : undefined;\n // A code in the record always reads its retryability from the record. A\n // code from a newer server (not in the record, not local) takes the\n // classifier's status-derived answer; a local code is never retryable.\n this.retryable = definition?.retryable ?? (isLocalCode(code) ? false : (facts.retryable ?? false));\n\n if (facts.retryAfterMs !== undefined) {\n this.retryAfterMs = facts.retryAfterMs;\n }\n if (facts.requestId !== undefined) {\n this.requestId = facts.requestId;\n }\n // The record decides which known codes may carry a navigation target. For\n // a code from a newer server the protocol classifier has already kept the\n // URL only for a credit refusal with an acceptable origin, so it is copied\n // as given; a local code never carries one.\n if (\n facts.authorizeUrl !== undefined &&\n (definition?.authorizeUrl === \"allowed\" || (definition === undefined && !isLocalCode(code)))\n ) {\n this.authorizeUrl = facts.authorizeUrl;\n }\n }\n}\n\nconst LOCAL_CODES: ReadonlySet<string> = new Set<EnlittLocalCode>([\n \"configuration_invalid\",\n \"transport_failed\",\n \"malformed_response\",\n \"request_canceled\"\n]);\n\nfunction isLocalCode(code: string): code is EnlittLocalCode {\n return LOCAL_CODES.has(code);\n}\n\n/**\n * Code `configuration_invalid`. Missing or invalid SDK configuration: absent\n * business secret, browser use, invalid base URL, invalid call options, an\n * invalid quote, or a missing session context. Thrown locally before any\n * network call, so a misconfigured deployment fails without touching Enlitt\n * or a provider. Audience is the business's own logs; it must never reach an\n * end user's screen.\n */\nexport class EnlittConfigurationError extends EnlittError {\n override readonly name = \"EnlittConfigurationError\";\n constructor(message: string) {\n super(\"configuration_invalid\", message);\n }\n}\n\n/**\n * Code `personal_login_required`. No usable personal session resolves for\n * this application. It belongs to both the standard and premium paths\n * identically, with the provider left uninvoked either way: the alternative\n * — letting premium proceed at the business's own cost — would mean every\n * user whose session expired silently moved their spending onto the\n * business. Audience is the end user: the business sends them through\n * Enlitt login or reauthorization.\n */\nexport class EnlittLoginRequiredError extends EnlittError {\n override readonly name = \"EnlittLoginRequiredError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.personal_login_required, message, facts);\n }\n}\n\n/**\n * Code `spending_limit_exceeded`. One of the user's application limits\n * refused the call. `limitRule` copies `error.enlitt.limit_rule`\n * (`standard_per_call`, `premium_per_call`, `rate.standard`, `rate.premium`,\n * or a rule a newer server added) so the business can explain which limit refused without\n * learning its value. It carries no amount, because a user's ceiling is their\n * own financial position. An unknown future rule stays a string and is\n * rendered generically; this field is never a closed authorization decision.\n * Audience is the end user, who raises the limit at `authorizeUrl`.\n */\nexport class EnlittLimitExceededError extends EnlittError {\n override readonly name = \"EnlittLimitExceededError\";\n readonly limitRule: string;\n constructor(message: string, limitRule: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.spending_limit_exceeded, message, facts);\n this.limitRule = limitRule;\n }\n}\n\n/**\n * Codes `premium_balance_exhausted` and `standard_balance_exhausted` (and any\n * credit-refusal code from a newer server, carried raw). The first means the\n * matching allowance plus eligible bundles cannot cover the call; the second\n * is the standard equivalent. `admissibleMaxChargeNanoUsd` is present only on\n * a premium `premium_balance_exhausted`: the largest `maxCharge` the user's\n * remaining credits would admit now, copied byte for byte. It is the protocol's\n * single disclosed figure; the SDK never retries with it on its own. No other\n * balance, plan, tier, or period fact is ever carried. The audience is the\n * end user, who tops up or upgrades at `authorizeUrl`.\n */\nexport class EnlittInsufficientCreditsError extends EnlittError {\n override readonly name = \"EnlittInsufficientCreditsError\";\n readonly admissibleMaxChargeNanoUsd?: string;\n constructor(\n code:\n | typeof ENLITT_ERROR_CODE.premium_balance_exhausted\n | typeof ENLITT_ERROR_CODE.standard_balance_exhausted\n | EnlittUnrecognizedCode,\n message: string,\n facts: EnlittErrorFacts & { readonly admissibleMaxChargeNanoUsd?: string } = {}\n ) {\n super(code, message, facts);\n if (facts.admissibleMaxChargeNanoUsd !== undefined) {\n this.admissibleMaxChargeNanoUsd = facts.admissibleMaxChargeNanoUsd;\n }\n }\n}\n\n/**\n * Code `subscription_inactive`. No subscription period covers the current\n * instant. Because every registered user holds at least the free plan, this\n * is exceptional rather than the ordinary state of a user who has not paid:\n * a user who never subscribed, lapsed, or canceled receives\n * `EnlittInsufficientCreditsError` at free-plan ceilings instead. Audience is\n * the end user, but a business seeing this at any volume should treat it as\n * a defect signal rather than a funnel step.\n */\nexport class EnlittSubscriptionInactiveError extends EnlittError {\n override readonly name = \"EnlittSubscriptionInactiveError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.subscription_inactive, message, facts);\n }\n}\n\n/**\n * Code `rate_limit_exceeded`. This user has started as many standard calls as\n * their plan allows for the current minute. Only the standard path raises it:\n * a premium operation consumes no request budget. It is the only refusal-shaped\n * condition that is retryable, and the only class that carries\n * `retryAfterMs` in practice. It is emphatically not an\n * `EnlittInsufficientCreditsError`: conflating a transient wait with an\n * exhausted balance would tell users to buy credits they do not need. It\n * carries no rate, remaining request count, or plan fact, because those are\n * the user's plan details.\n */\nexport class EnlittRateLimitError extends EnlittError {\n override readonly name = \"EnlittRateLimitError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.rate_limit_exceeded, message, facts);\n }\n}\n\n/**\n * Code `invalid_api_key`. The presented business key is missing, invalid, or\n * revoked. Audience is the business's own logs; never rendered to an end\n * user, and never softened into a direct provider call.\n */\nexport class EnlittAuthenticationError extends EnlittError {\n override readonly name = \"EnlittAuthenticationError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.invalid_api_key, message, facts);\n }\n}\n\n/**\n * Code `insufficient_permissions`. The presented business key is valid but\n * used outside its authenticated application or scope. Audience is the\n * business's own logs; never rendered to an end user, and never softened\n * into a direct provider call.\n */\nexport class EnlittAuthorizationError extends EnlittError {\n override readonly name = \"EnlittAuthorizationError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.insufficient_permissions, message, facts);\n }\n}\n\n/**\n * Per-code facts the protocol classifier extracted that only some classes\n * carry. Passed to every factory so the table stays uniform.\n */\ninterface ClassifiedExtras {\n readonly limitRule?: string;\n readonly admissibleMaxChargeNanoUsd?: string;\n}\n\n/** One wire code's constructor, uniform across every entry in the map below. */\ntype WireErrorFactory = (message: string, facts: EnlittErrorFacts, extras: ClassifiedExtras) => EnlittError;\n\n/**\n * The wire-code-to-class mapping, exhaustive over the protocol record by\n * construction: `satisfies Record<EnlittWireCode, WireErrorFactory>` rejects\n * this object literal at compile time if it is missing a key the record\n * defines, and rejects it just as loudly if it carries a key the record does\n * not, so a code added to the protocol without a class here fails the build\n * instead of falling through to the base class at runtime.\n *\n * Codes with no distinct business action of their own (dashboard-only codes,\n * validation, conflicts, server failures) use the base class carrying their\n * stable code; every other entry uses the subclass named for it.\n */\nconst WIRE_CODE_FACTORY = {\n personal_login_required: (message, facts) => new EnlittLoginRequiredError(message, facts),\n spending_limit_exceeded: (message, facts, extras) =>\n new EnlittLimitExceededError(message, extras.limitRule ?? \"unrecognized\", facts),\n premium_balance_exhausted: (message, facts, extras) =>\n new EnlittInsufficientCreditsError(ENLITT_ERROR_CODE.premium_balance_exhausted, message, {\n ...facts,\n ...(extras.admissibleMaxChargeNanoUsd !== undefined\n ? { admissibleMaxChargeNanoUsd: extras.admissibleMaxChargeNanoUsd }\n : {})\n }),\n standard_balance_exhausted: (message, facts) =>\n new EnlittInsufficientCreditsError(ENLITT_ERROR_CODE.standard_balance_exhausted, message, facts),\n subscription_inactive: (message, facts) => new EnlittSubscriptionInactiveError(message, facts),\n rate_limit_exceeded: (message, facts) => new EnlittRateLimitError(message, facts),\n invalid_api_key: (message, facts) => new EnlittAuthenticationError(message, facts),\n insufficient_permissions: (message, facts) => new EnlittAuthorizationError(message, facts),\n dashboard_login_required: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.dashboard_login_required, message, facts),\n admin_authentication_required: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.admin_authentication_required, message, facts),\n conflict_error: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.conflict_error, message, facts),\n operation_in_progress: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.operation_in_progress, message, facts),\n idempotency_replay_unavailable: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.idempotency_replay_unavailable, message, facts),\n invalid_value: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.invalid_value, message, facts),\n unsupported_parameter: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.unsupported_parameter, message, facts),\n unsupported_value: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.unsupported_value, message, facts),\n reauthentication_required: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.reauthentication_required, message, facts),\n payment_declined: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.payment_declined, message, facts),\n invalid_sign_in_code: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.invalid_sign_in_code, message, facts),\n not_found: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.not_found, message, facts),\n request_too_large: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.request_too_large, message, facts),\n server_error: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.server_error, message, facts),\n provider_error: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.provider_error, message, facts),\n business_selection_required: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.business_selection_required, message, facts),\n bot_verification_failed: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.bot_verification_failed, message, facts),\n phone_verification_required: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.phone_verification_required, message, facts),\n invalid_phone_code: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.invalid_phone_code, message, facts),\n phone_number_not_supported: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.phone_number_not_supported, message, facts),\n phone_number_unavailable: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.phone_number_unavailable, message, facts),\n business_name_unavailable: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.business_name_unavailable, message, facts),\n // The four CLI device-flow codes (RFC 8628). No SDK route can return them, but\n // the mapping is exhaustive over the record, so they surface as the base class.\n authorization_pending: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.authorization_pending, message, facts),\n slow_down: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.slow_down, message, facts),\n access_denied: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.access_denied, message, facts),\n expired_token: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.expired_token, message, facts)\n} as const satisfies Record<EnlittWireCode, WireErrorFactory>;\n\n/**\n * An Enlitt HTTP error response, shaped for normalization: the HTTP status,\n * the parsed JSON body (untrusted, hence `unknown`), and the two response\n * headers normalization reads. `core/transport.ts` is the only intended\n * producer of this shape.\n */\nexport interface EnlittHttpErrorResponse {\n readonly kind: \"http_error\";\n readonly status: number;\n readonly body: unknown;\n readonly headers: Readonly<Record<string, string | undefined>>;\n}\n\n/** A request that never produced an HTTP response at all. */\nexport interface EnlittTransportFailure {\n readonly kind: \"transport_failed\";\n readonly message?: string;\n}\n\n/** A response that was received but could not be parsed as Enlitt's contract. */\nexport interface EnlittMalformedResponse {\n readonly kind: \"malformed_response\";\n readonly message?: string;\n}\n\n/** A caller-initiated abort of a request still in flight. */\nexport interface EnlittRequestCanceled {\n readonly kind: \"request_canceled\";\n readonly message?: string;\n}\n\n/**\n * Every shape `normalizeEnlittModelError` recognizes. `error` is typed\n * `unknown` at the function boundary because it is handed whatever the\n * transport or the runtime threw; this union is what it is checked against.\n */\nexport type EnlittNormalizationInput =\n | EnlittHttpErrorResponse\n | EnlittTransportFailure\n | EnlittMalformedResponse\n | EnlittRequestCanceled;\n\nfunction hasKind(value: unknown): value is { readonly kind: unknown } {\n return typeof value === \"object\" && value !== null && \"kind\" in value;\n}\n\n/**\n * Converts the wire's `Retry-After` seconds into milliseconds exactly once,\n * at the point the response is parsed. A missing or unparseable header\n * leaves the result `undefined` rather than defaulting to zero, because a\n * zero would invite an immediate retry into a limit that has not moved.\n */\nfunction parseRetryAfterMs(header: string | undefined): number | undefined {\n if (header === undefined) {\n return undefined;\n }\n const seconds = Number(header);\n if (!Number.isFinite(seconds) || seconds < 0) {\n return undefined;\n }\n return seconds * 1000;\n}\n\n/**\n * Maps an HTTP error response through the protocol's shared classifier, so\n * the SDK, the frontend, and the fixture tests classify an error the same\n * way. This function never parses the error body itself.\n */\nfunction normalizeHttpErrorResponse(input: EnlittHttpErrorResponse): EnlittError {\n const requestId = input.headers[\"x-request-id\"];\n const classified = classifyEnlittErrorResponse(input.status, input.body);\n\n // A body that is neither error envelope (an HTML gateway page, an empty\n // body, a JSON array): no code can be trusted, so it is a malformed response.\n if (classified === null) {\n return new EnlittError(\n \"malformed_response\",\n `Enlitt returned HTTP ${String(input.status)} with a body that is not an Enlitt error.`,\n requestId !== undefined ? { requestId } : {}\n );\n }\n\n const message = classified.message ?? \"Enlitt refused the request.\";\n\n if (classified.recognized && isEnlittErrorCode(classified.code)) {\n const retryAfterMs = parseRetryAfterMs(input.headers[\"retry-after\"]);\n const facts: EnlittErrorFacts = {\n ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n ...(classified.authorizeUrl !== undefined ? { authorizeUrl: classified.authorizeUrl } : {})\n };\n return WIRE_CODE_FACTORY[classified.code](message, facts, {\n ...(classified.limitRule !== undefined ? { limitRule: classified.limitRule } : {}),\n ...(classified.admissibleMaxChargeNanoUsd !== undefined\n ? { admissibleMaxChargeNanoUsd: classified.admissibleMaxChargeNanoUsd }\n : {})\n });\n }\n\n // A code this SDK does not recognize: most likely a newer backend. It never\n // throws and never fails the build. `Retry-After` is deliberately ignored,\n // because only a code the record marks `retryAfter: \"required\"` is known to\n // mean \"wait and repeat\", and a 429 with an unknown code is never the\n // rate-limit class so it is surfaced once instead of retried blindly.\n const upgradeMessage =\n `Enlitt returned error code \"${classified.code}\" (HTTP ${String(classified.status)}, type ` +\n `\"${classified.type ?? \"none\"}\"), which this version of @enlitt/sdk does not recognize. ` +\n \"Upgrade @enlitt/sdk to handle it.\" +\n (classified.message !== null ? ` ${classified.message}` : \"\");\n const facts: EnlittErrorFacts = {\n ...(requestId !== undefined ? { requestId } : {}),\n ...(classified.authorizeUrl !== undefined ? { authorizeUrl: classified.authorizeUrl } : {}),\n retryable: classified.retryable\n };\n if (classified.creditRefusal) {\n return new EnlittInsufficientCreditsError(classified.code, upgradeMessage, facts);\n }\n return new EnlittError(classified.code, upgradeMessage, facts);\n}\n\n/**\n * Maps one Enlitt failure to exactly one class.\n *\n * `providerInvoked` is accepted for signature symmetry with callers that\n * track it across the premium path, but every value returned is an\n * `EnlittError`, whose `providerInvoked` is always `false`: Enlitt refuses\n * before a provider is reached. A provider's own error is never routed\n * through this function; the premium path rethrows it unchanged.\n *\n * The mapping is keyed on the stable code alone, never on HTTP status: a\n * `429` carrying any code other than `rate_limit_exceeded` does not become\n * `EnlittRateLimitError`.\n */\nexport function normalizeEnlittModelError(error: unknown, providerInvoked: boolean): EnlittError {\n void providerInvoked;\n\n if (hasKind(error)) {\n switch (error.kind) {\n case \"http_error\":\n return normalizeHttpErrorResponse(error as EnlittHttpErrorResponse);\n case \"transport_failed\": {\n const input = error as EnlittTransportFailure;\n return new EnlittError(\n \"transport_failed\",\n input.message ?? \"The request to Enlitt failed before a response was received.\"\n );\n }\n case \"request_canceled\": {\n const input = error as EnlittRequestCanceled;\n return new EnlittError(\"request_canceled\", input.message ?? \"The request was canceled before it completed.\");\n }\n case \"malformed_response\":\n default:\n break;\n }\n }\n\n const input = hasKind(error) && error.kind === \"malformed_response\" ? (error as EnlittMalformedResponse) : undefined;\n return new EnlittError(\"malformed_response\", input?.message ?? \"Enlitt's response could not be parsed.\");\n}\n","/**\n * The read end of the Enlitt session cookie.\n *\n * `specs/SDK-side routing.md` gives this file the session handle, the\n * middleware, and the async-context accessors. It owns \"the user logs in and\n * their credits are just used\": it carries Enlitt's opaque session token from\n * the cookie Account's login callback already set, through an\n * `AsyncLocalStorage` context, to whatever call site needs it, without ever\n * reading, parsing, or validating what the token contains. Validity is\n * Enlitt's answer to give at call time, not this file's to guess.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { EnlittConfigurationError } from \"./errors.js\";\n\n/**\n * The canonical Enlitt session cookie name, and the default of both\n * `CallbackConfig.cookieName` and `SessionMiddlewareOptions.cookieName`.\n *\n * A business that passes a custom `cookieName` to the callback must pass the\n * identical value to the middleware. That is the one case the two ends can\n * still disagree, and it is the business's own to keep consistent; the default\n * is not, which is why it is one constant rather than two literals.\n */\nexport const ENLITT_SESSION_COOKIE_NAME = \"enlitt_session\";\n\n/**\n * The longest token value `enlittSession()` accepts.\n *\n * Not a claim about Enlitt's actual token format, which this module never\n * inspects: it exists only so a business's own bug (an empty string, or\n * something that is clearly not a token, such as a whole cookie header pasted\n * in whole) fails at construction instead of being carried silently to a call\n * Enlitt then refuses for a reason the caller cannot see locally.\n */\nconst MAX_SESSION_TOKEN_LENGTH = 4096;\n\n/**\n * An opaque handle around Enlitt's session token.\n *\n * The token has no subject, expiry, or scope readable from the SDK side, and\n * every fact about the user lives on Enlitt's servers. Deliberately just a\n * string wrapper: exposing it as a bare `string` anywhere in the call surface\n * would invite a business to construct or compare tokens as ordinary strings,\n * and there is no format a business can legitimately synthesize.\n */\nexport interface EnlittSession {\n readonly token: string;\n}\n\n/**\n * The only way to construct an `EnlittSession`.\n *\n * The token is a string the SDK never parses, decodes, validates, or\n * inspects; this is what lets Enlitt rotate or restructure the underlying\n * credential without a business shipping a release, and what keeps the\n * business from ever holding an OAuth token or implementing a refresh.\n * Constructing one from a value a business stored itself is legitimate and is\n * how linked accounts and background jobs work; constructing one from a value\n * the business derived, guessed, or built from a user identifier is not a\n * session, and Enlitt rejects it at call time. The factory validates only\n * that the token is a non-empty bounded string, because anything more would\n * be inspecting a credential this module must treat as opaque.\n */\nexport function enlittSession(token: string): EnlittSession {\n if (typeof token !== \"string\" || token.length === 0 || token.length > MAX_SESSION_TOKEN_LENGTH) {\n throw new EnlittConfigurationError(\n \"enlittSession() requires a non-empty session token no longer than \" +\n `${MAX_SESSION_TOKEN_LENGTH} characters.`\n );\n }\n return { token };\n}\n\n/**\n * Options for `enlittSessionMiddleware()`.\n *\n * `cookieName` exists solely to mirror a business's own custom\n * `CallbackConfig.cookieName`; the default matches `ENLITT_SESSION_COOKIE_NAME`\n * so the common case names nothing.\n */\nexport interface SessionMiddlewareOptions {\n cookieName?: string;\n}\n\n/**\n * The shape `enlittSessionMiddleware()` returns.\n *\n * Framework-agnostic over Web `Request` and `Response`, exactly as Account's\n * callback handlers are: v1 ships no per-framework adapter, so this is the\n * one shape every framework's own middleware layer can wrap.\n */\nexport type EnlittMiddleware = (request: Request, next: () => Promise<Response>) => Promise<Response>;\n\n/**\n * The single `AsyncLocalStorage` context carrying the current request's\n * session.\n *\n * Not exported: the module boundary between \"install the context\" and \"read\n * the context\" is what lets `getEnlittSession()` distinguish a missing\n * middleware from a signed-out visitor by whether a context exists at all,\n * a distinction that leaks the moment callers can reach the storage directly.\n */\nconst sessionContext = new AsyncLocalStorage<EnlittSession | null>();\n\n/**\n * Reads the Enlitt session cookie from an incoming request, runs `next()`\n * with an `AsyncLocalStorage` context carrying the resulting `EnlittSession`\n * or an explicit `null`, and leaves the context when the request ends.\n *\n * It never rejects a request: plenty of a business's routes are for\n * signed-out visitors, and deciding the business's authentication policy is\n * not this middleware's job. It performs no network call and no validation,\n * because validity is Enlitt's answer to give at call time and pre-validating\n * here would add a round trip to every request, including the ones that never\n * call a model. The cookie lives on the business's own domain and was set by\n * Enlitt's login callback, so no cross-site cookie, third-party storage, or\n * browser-side token is involved.\n */\nexport function enlittSessionMiddleware(options?: SessionMiddlewareOptions): EnlittMiddleware {\n const cookieName = options?.cookieName ?? ENLITT_SESSION_COOKIE_NAME;\n return async function enlittMiddleware(request: Request, next: () => Promise<Response>): Promise<Response> {\n const token = readCookie(request, cookieName);\n const session = token === null ? null : enlittSession(token);\n return sessionContext.run(session, next);\n };\n}\n\n/**\n * Runs `fn` with an explicit `EnlittSession` (or `null`) bound as the ambient\n * session for its entire synchronous and asynchronous extent.\n *\n * The escape hatch for a framework whose middleware shape\n * `enlittSessionMiddleware()` cannot wrap directly: a business on such a\n * framework establishes the same context in one line instead of waiting on a\n * per-framework adapter that v1 does not ship.\n */\nexport function runWithEnlittSession<T>(session: EnlittSession | null, fn: () => T): T {\n return sessionContext.run(session, fn);\n}\n\n/**\n * Returns the ambient session for the current request context.\n *\n * Throws `EnlittConfigurationError` when there is no context at all: no\n * context means the middleware is not installed on this path, which is the\n * business's own wiring bug, and treating that as \"signed out\" would make\n * every user of a misconfigured deployment silently unauthenticated. Returns\n * `null` when there is a context and no session, which is the genuine\n * signed-out state a business checks before calling a model. These two\n * conditions must never collapse into one: a deployment bug and a\n * signed-out visitor look identical at the call site and must not be\n * reported identically. A session this returns may still be expired or\n * revoked; that is not knowable locally, so the call carries it and Enlitt\n * answers with `personal_login_required` if it must.\n */\nexport function getEnlittSession(): EnlittSession | null {\n if (!hasEnlittSessionContext()) {\n throw new EnlittConfigurationError(\n \"getEnlittSession() was called with no enlittSessionMiddleware() (or \" +\n \"runWithEnlittSession()) context installed on this request path.\"\n );\n }\n return sessionContext.getStore() ?? null;\n}\n\n/**\n * Distinguishes \"no `AsyncLocalStorage` context at all\" from \"a context\n * holding `null`\", which reading `getStore()` alone cannot do since both\n * would otherwise read back as a nullish value.\n *\n * Relies on `AsyncLocalStorage`'s own documented signal: `getStore()` returns\n * `undefined` when no `run()` scope is active, and returns the exact value\n * (including `null`) passed to the innermost active `run()` otherwise. So the\n * presence of a context is `getStore() !== undefined`, given this module\n * never stores `undefined` itself — only an `EnlittSession` or `null`.\n */\nfunction hasEnlittSessionContext(): boolean {\n return sessionContext.getStore() !== undefined;\n}\n\n/**\n * Parses the named cookie out of a Web `Request`'s `Cookie` header.\n *\n * Deliberately minimal: this reads one opaque value off the business's own\n * domain and never interprets it, so it need not implement the full cookie\n * grammar, only enough to split `name=value` pairs safely.\n */\nfunction readCookie(request: Request, name: string): string | null {\n const header = request.headers.get(\"cookie\");\n if (header === null) {\n return null;\n }\n for (const part of header.split(\";\")) {\n const separatorIndex = part.indexOf(\"=\");\n if (separatorIndex === -1) {\n continue;\n }\n const rawName = part.slice(0, separatorIndex).trim();\n if (rawName !== name) {\n continue;\n }\n const rawValue = part.slice(separatorIndex + 1).trim();\n try {\n return decodeURIComponent(rawValue);\n } catch {\n return rawValue;\n }\n }\n return null;\n}\n","/**\n * The server-only boundary that turns a business secret into an outgoing\n * authorization header.\n *\n * There is exactly one export. Resolving a key and formatting a header used to\n * be two of them, which made \"resolve the key and forget to use it\" a\n * reachable mistake at every call site; there is now no way to obtain the\n * secret through this module's public surface without obtaining the header.\n *\n * A missing or unusable secret throws locally, before any network call, and\n * never yields an unauthenticated client or a credential-free request. That\n * local failure is what stops a managed premium call from silently falling\n * through to a direct, business-funded provider call.\n *\n * The resolved value is a secret. It is never logged, never serialized into a\n * thrown error's message or fields, and never returned to a caller: the\n * `browser` condition on the `./server` subpath keeps this file out of every\n * browser bundle, and the environment assertion below is the second net for a\n * bundler or runtime that ignores that condition.\n *\n * Both local failures — a browser environment and an unusable secret — raise\n * `EnlittConfigurationError`. That is what `enlitt()` documents its callers\n * will see for a missing or invalid secret, and the type has to be right here\n * rather than at one caller's boundary: any other caller of this function\n * (`server/callback.ts`'s handlers among them) would otherwise receive a bare\n * `Error` for exactly the same misconfiguration, and a business catching the\n * package's own error class would miss it.\n */\n\nimport { EnlittConfigurationError } from \"../core/errors.js\";\n\nconst ENV_KEY = \"ENLITT_SECRET_KEY\";\n\n/**\n * A single visible-ASCII run: exactly what an HTTP header value may carry.\n *\n * A secret holding a control character, a space, or a newline is unusable\n * rather than merely unusual — pasted with a trailing newline it would either\n * be rejected by the transport or, worse, split the header. Refusing it here\n * is the same local failure as a missing key.\n */\nconst USABLE_SECRET = /^[!-~]+$/;\n\n/**\n * Refuse before any secret-related work if this looks like a browser.\n *\n * The heuristic is the simultaneous presence of `window` and `document`,\n * which is reliably absent in Node, Deno, Bun, and Cloudflare Workers and\n * present in every mainstream browser. It is deliberately not exported: a\n * caller has no reason to ask the question separately from asking for the\n * header, and an exported assertion is one more thing that can be called and\n * its answer ignored.\n */\nfunction assertServerEnvironment(): void {\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n throw new EnlittConfigurationError(\n \"@enlitt/sdk: server-only module imported in a browser environment. \" +\n \"Use @enlitt/sdk/browser for code you ship to consumers.\"\n );\n }\n}\n\n// Fail on module evaluation too, so a mistaken browser import surfaces at\n// import time rather than at the first call that needed a credential.\nassertServerEnvironment();\n\n/**\n * Read the environment fallback without assuming a `process` global exists.\n *\n * Workers-style runtimes have no `process`, and reaching for it unguarded\n * would turn \"no key configured\" into a `ReferenceError` that reads like a\n * bug in the SDK rather than a missing configuration value.\n */\nfunction readEnvironmentSecret(): string | undefined {\n const runtime = globalThis as { process?: { env?: Record<string, string | undefined> } };\n return runtime.process?.env?.[ENV_KEY];\n}\n\n/**\n * Resolve the business secret and return the one header value that carries it.\n *\n * Resolution order is explicit configuration first, then the `ENLITT_SECRET_KEY`\n * environment fallback. An explicitly supplied key is never abandoned in\n * favour of the environment: a business that passed an empty or malformed\n * value has misconfigured that value, and silently authenticating as whatever\n * the environment happens to hold would be a different identity than the one\n * the call site asked for.\n *\n * @returns a single `Bearer <secret>` header value.\n * @throws {EnlittConfigurationError} in a browser environment, or when no\n * usable secret resolves. Neither the message nor any field of the thrown\n * error carries any part of the secret.\n */\nexport function resolveBusinessAuthorizationHeader(config: { secretKey?: string }): string {\n // Before resolution, not after: a browser must never reach the code that\n // reads a secret at all, let alone hold the result.\n assertServerEnvironment();\n\n const configured = config.secretKey;\n // Not `??`: that would treat a `null` from an untyped JavaScript caller as\n // \"nothing configured\" and fall through to the environment, authenticating as\n // whatever identity the environment happens to hold rather than refusing the\n // misconfigured value. Only `undefined` means the caller configured nothing.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const candidate: unknown = configured === undefined ? readEnvironmentSecret() : configured;\n\n if (typeof candidate !== \"string\" || !USABLE_SECRET.test(candidate)) {\n throw new EnlittConfigurationError(\n \"@enlitt/sdk: no usable Enlitt secret key. Pass one as { secretKey } or set \" +\n `the ${ENV_KEY} environment variable on the server. The value must be a ` +\n \"non-empty string of visible ASCII characters.\"\n );\n }\n\n return `Bearer ${candidate}`;\n}\n","/**\n * The module's single authenticated exit to Enlitt.\n *\n * `specs/SDK-side routing.md` gives this file three jobs that must live in\n * exactly one place: the definition of the internal client\n * (`InternalEnlittClient`, built once per factory call by\n * `createInternalClient()`), the one place a personal session is resolved\n * (`InternalEnlittClient.resolveSession`), and the one function that ever\n * issues an HTTP request to Enlitt (`requestEnlitt()`). Both the standard and\n * premium model files call through this file rather than `fetch` directly, so\n * every header, every safety check, and every retry the spec requires exists\n * exactly once instead of once per model.\n *\n * It owns exactly two internal retries and no others: the bounded, jittered\n * wait that absorbs `rate_limit_exceeded` (inside `requestEnlitt()` itself,\n * because it applies uniformly to every request this module sends), and a\n * bounded transient retry of a premium terminal report under one unchanged\n * `report_id`/`Idempotency-Key` (`reportEnlittPremiumTerminal()`, layered on\n * top of `requestEnlitt()` because it applies to exactly one call shape and\n * must never leak onto a preflight, a standard call, or a refusal). Every\n * other failure — every refusal, every conflict, every `4xx` other than `429\n * rate_limit_exceeded` — is normalized and thrown once, never retried here.\n *\n * It never accepts a personal identity as a caller-supplied parameter: the\n * only personal value that ever leaves this file is the opaque token\n * `client.resolveSession()` returns, and no argument, option, or request body\n * field can supply or override it. It never logs or returns that token,\n * prompt content, or a raw provider error, and it never runs in a browser —\n * it is reachable only through `@enlitt/sdk/server`, which the package export\n * map keeps out of the `browser` condition.\n */\n\nimport { ENLITT_API_VERSION, ENLITT_ERROR_CODE, ENLITT_VERSION_HEADER } from \"@enlitt/protocol\";\nimport {\n EnlittConfigurationError,\n EnlittError,\n normalizeEnlittModelError,\n type EnlittHttpErrorResponse,\n type EnlittMalformedResponse,\n type EnlittRequestCanceled,\n type EnlittTransportFailure\n} from \"./errors.js\";\nimport { resolveBusinessAuthorizationHeader } from \"../server/secrets.js\";\nimport { getEnlittSession, type EnlittSession } from \"./session.js\";\n\n/**\n * The SDK's own version, sent as `X-Enlitt-SDK-Version` so Enlitt's own logs\n * can tell which client behavior produced a given request without the header\n * carrying anything about the business or the user.\n *\n * A literal rather than a `package.json` import: this package ships as both\n * ESM and CJS, its `tsup` build does not embed the manifest, and a JSON\n * import here would tie a request-time value to a file layout assumption\n * this module has no other reason to make. It must be bumped by hand\n * alongside `package.json`'s `version` field.\n */\nexport const SDK_VERSION = \"0.1.0\";\n\n/** Hosts `http:` is still accepted for, matching a developer's own machine. */\nconst LOCAL_HTTP_HOSTS: ReadonlySet<string> = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/**\n * The deployed default floor for a rate-limit wait when the refusal carries\n * no `Retry-After`. One second: long enough that an immediate retry cannot\n * reassemble the burst that caused the refusal, short enough that a business\n * under its own `maxRetries` does not perceive a hang.\n */\nconst DEFAULT_RATE_LIMIT_FLOOR_MS = 1_000;\n\n/**\n * The deployed default bound on rate-limit retry attempts. Chosen so a caller\n * that never configures `rateLimit` still backs off a handful of times\n * before the failure surfaces, rather than waiting on `maxTotalWaitMs` alone\n * to end an unbounded attempt count.\n */\nconst DEFAULT_RATE_LIMIT_MAX_ATTEMPTS = 3;\n\n/**\n * The deployed default wall-clock budget for a rate-limit wait, measured\n * from the first refusal. Kept comfortably under common serverless request\n * timeouts (typically 10-60s) so an exhausted budget surfaces as a typed\n * `EnlittRateLimitError` rather than the platform killing the process\n * mid-wait.\n */\nconst DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS = 30_000;\n\n/**\n * The deployed bound on how many times `reportEnlittPremiumTerminal()` will\n * resend one terminal report before giving up and handing the failure to\n * `onTerminalReportError`. Small and fixed, unlike the rate-limit wait: a\n * terminal report that keeps failing after a few attempts is failing for a\n * reason a delay will not fix, and the credit hold it would otherwise\n * release already has its own deadline-driven backstop on Enlitt's side.\n */\nconst TERMINAL_REPORT_MAX_ATTEMPTS = 3;\n\n/** The floor of the delay between terminal-report retry attempts. */\nconst TERMINAL_REPORT_RETRY_DELAY_MS = 500;\n\n/**\n * The largest total byte size this module will read out of a response's\n * headers before giving up on it as malformed. Bounding it is what keeps a\n * misbehaving or compromised endpoint from making this module buffer an\n * unbounded amount of attacker-controlled data before normalization ever\n * runs.\n */\nconst MAX_RESPONSE_HEADER_BYTES = 32 * 1024;\n\n/** The largest response body this module will buffer before parsing it. */\nconst MAX_RESPONSE_BODY_BYTES = 1024 * 1024;\n\n/**\n * Caller-supplied tuning for the rate-limit wait. Every field is optional\n * because `createInternalClient()` folds it over the SDK's own defaults\n * exactly once, at construction, which is what lets every later read of\n * `client.rateLimit` assume every field but `onRateLimit` is present.\n */\nexport interface EnlittRateLimitRetryOptions {\n /** Upper bound on attempts, including the first (minimum 1). Default {@link DEFAULT_RATE_LIMIT_MAX_ATTEMPTS}. */\n readonly maxAttempts?: number;\n /** Upper bound on total time spent waiting, measured from the first refusal. Default {@link DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS}. */\n readonly maxTotalWaitMs?: number;\n /**\n * Invoked once per wait, with the attempt number (1-based) about to be\n * slept and the jittered delay in milliseconds. The only way a business\n * observes a rate-limit wait without this module disclosing a plan fact.\n */\n readonly onRateLimit?: (attempt: number, delayMs: number) => void;\n}\n\n/**\n * Constructor options for `createInternalClient()`.\n *\n * `secretKey` and `baseUrl` are exactly what `resolveBusinessAuthorizationHeader()`\n * and the HTTPS assertion need and nothing more; neither this type nor the\n * client it builds ever carries a personal identity, because the only\n * personal value the transport ever sends is the token `resolveSession()`\n * (built from `session`, or from the ambient context) produces at request\n * time.\n */\nexport interface EnlittOptions {\n /** Forwarded to `resolveBusinessAuthorizationHeader()` unchanged. */\n readonly secretKey?: string;\n /**\n * Enlitt's base URL. Resolves from this option, then `ENLITT_BASE_URL`, then\n * the deployed Enlitt origin compiled into the package. Must be `https:`, or\n * `http:` on a local host. Parsed and validated once, at construction.\n */\n readonly baseUrl?: string;\n /**\n * An explicit session, for a caller that cannot rely on the ambient\n * `AsyncLocalStorage` context — a background job, or a framework\n * `enlittSessionMiddleware()` cannot wrap. When absent, every call resolves\n * the session from `getEnlittSession()` instead.\n */\n readonly session?: EnlittSession;\n readonly rateLimit?: EnlittRateLimitRetryOptions;\n /**\n * Observes a failure `reportEnlittPremiumTerminal()` could not recover\n * from after exhausting its bounded retry. There is no caller left to\n * return the error to by the time this fires — the provider call this\n * report describes has already completed — so this hook is the only way a\n * business ever learns a terminal report did not land.\n */\n readonly onTerminalReportError?: (error: EnlittError) => void;\n}\n\n/**\n * The internal client every request in this module is built from.\n *\n * Constructed once per factory call from the business's resolved secret and\n * the deployed environment, and never held as nullable: holding a client at\n * all is what makes a call managed, so there is no code path in this package\n * that represents \"no Enlitt configuration\" as a null or optional client\n * instead of failing at construction.\n */\nexport interface InternalEnlittClient {\n readonly baseUrl: string;\n /** The full `Authorization` header value, e.g. `Bearer sk_...`. Never logged or returned. */\n readonly businessAuthorization: string;\n readonly sdkVersion: string;\n /**\n * The module's single session resolution. Returns the explicit\n * `EnlittOptions.session` when one was given; otherwise defers to\n * `getEnlittSession()`, which itself distinguishes \"no middleware\n * installed\" (`EnlittConfigurationError`) from \"signed out\" (`null`,\n * raised here as `EnlittLoginRequiredError` with `providerInvoked: false`).\n * Both model files call this indirectly through `requestEnlitt()` rather\n * than resolving a session themselves, which is what keeps the three\n * outcomes from drifting apart between the standard and premium paths.\n */\n readonly resolveSession: () => EnlittSession;\n readonly rateLimit: Required<Omit<EnlittRateLimitRetryOptions, \"onRateLimit\">> &\n Pick<EnlittRateLimitRetryOptions, \"onRateLimit\">;\n readonly onTerminalReportError?: (error: EnlittError) => void;\n}\n\n/**\n * Builds the internal client from a factory call's resolved options.\n *\n * Resolves the business authorization header eagerly (through\n * `resolveBusinessAuthorizationHeader()`, the only path to that secret) so a\n * missing or unusable key fails at construction, before any network call and\n * before a provider is ever at risk of running unaccounted. Folds\n * `rateLimit` over the SDK's defaults exactly once here, so no per-request\n * code has to treat any field but `onRateLimit` as possibly absent.\n */\nexport function createInternalClient(options: EnlittOptions): InternalEnlittClient {\n // First, before secret resolution, so a bundling mistake never reaches a key.\n assertServerRuntime();\n\n const baseUrl = resolveBaseUrl(options.baseUrl);\n const businessAuthorization = resolveBusinessAuthorizationHeader(\n options.secretKey !== undefined ? { secretKey: options.secretKey } : {}\n );\n\n const rateLimitOptions = options.rateLimit;\n const maxAttempts = rateLimitOptions?.maxAttempts ?? DEFAULT_RATE_LIMIT_MAX_ATTEMPTS;\n if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1) {\n throw new EnlittConfigurationError(\"rateLimit.maxAttempts must be an integer of at least 1.\");\n }\n const rateLimit: InternalEnlittClient[\"rateLimit\"] = {\n maxAttempts,\n maxTotalWaitMs: rateLimitOptions?.maxTotalWaitMs ?? DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS,\n ...(rateLimitOptions?.onRateLimit !== undefined ? { onRateLimit: rateLimitOptions.onRateLimit } : {})\n };\n\n const explicitSession = options.session;\n\n return {\n baseUrl,\n businessAuthorization,\n sdkVersion: SDK_VERSION,\n resolveSession: (): EnlittSession => {\n if (explicitSession !== undefined) {\n return explicitSession;\n }\n const session = getEnlittSession();\n if (session === null) {\n throw normalizeEnlittModelError(\n {\n kind: \"http_error\",\n status: 401,\n body: loginRequiredBody(),\n headers: {}\n },\n false\n );\n }\n return session;\n },\n rateLimit,\n ...(options.onTerminalReportError !== undefined\n ? { onTerminalReportError: options.onTerminalReportError }\n : {})\n };\n}\n\n/**\n * The deployed Enlitt origin compiled into the package, used when neither\n * `EnlittOptions.baseUrl` nor `ENLITT_BASE_URL` names one. Matches the default\n * `enlittOrigin` `server/callback.ts` falls back to; the two are the same\n * deployed origin and must not drift apart.\n */\nconst DEFAULT_ENLITT_ORIGIN = \"https://api.enlitt.com\";\n\n/** The environment variable a business may set instead of passing `baseUrl` explicitly. */\nconst BASE_URL_ENV_KEY = \"ENLITT_BASE_URL\";\n\n/**\n * Browser execution fails with `EnlittConfigurationError`. The check is\n * `typeof window !== \"undefined\" && typeof document !== \"undefined\"`,\n * matching `server/secrets.ts`'s own heuristic exactly.\n */\nfunction assertServerRuntime(): void {\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n throw new EnlittConfigurationError(\n \"enlitt() was called in a browser environment. It is server-only; ship @enlitt/sdk/browser to consumers instead.\"\n );\n }\n}\n\n/**\n * Resolves `baseUrl` from the option, then `ENLITT_BASE_URL`, then the\n * deployed default, and validates the result once through the identical HTTPS\n * rule `requestEnlitt()` applies per request (`assertHttps()`). A malformed\n * URL is folded into the same `EnlittConfigurationError` rather than leaking a\n * raw `TypeError`.\n */\nfunction resolveBaseUrl(optionBaseUrl: string | undefined): string {\n const candidate = optionBaseUrl ?? readBaseUrlFromEnv() ?? DEFAULT_ENLITT_ORIGIN;\n try {\n assertHttps(candidate);\n } catch (thrown) {\n if (thrown instanceof EnlittConfigurationError) {\n throw thrown;\n }\n throw new EnlittConfigurationError(`Enlitt base URL is not a valid URL: ${String(candidate)}.`);\n }\n return candidate;\n}\n\n/** Mirrors `server/secrets.ts`'s guarded read of a `process.env` fallback, which no Workers-style runtime provides. */\nfunction readBaseUrlFromEnv(): string | undefined {\n const runtime = globalThis as { process?: { env?: Record<string, string | undefined> } };\n return runtime.process?.env?.[BASE_URL_ENV_KEY];\n}\n\n/**\n * Synthesizes the one error body `resolveSession()` needs to raise\n * `EnlittLoginRequiredError` through `normalizeEnlittModelError()` rather\n * than constructing a second error path that could disagree with the one\n * every HTTP refusal already goes through.\n */\nfunction loginRequiredBody(): unknown {\n return {\n error: {\n message: \"No Enlitt session is available for this request. Send the user through Enlitt login.\",\n type: \"authentication_error\",\n param: null,\n code: ENLITT_ERROR_CODE.personal_login_required\n }\n };\n}\n\n/** One request this module knows how to issue. */\nexport interface EnlittRequestInit {\n readonly path: string;\n /** `POST` unless a read endpoint (`GET /v1/enlitt/usage`) says otherwise. */\n readonly method?: \"POST\" | \"GET\";\n /** Ignored for `GET`, which has no body. */\n readonly body?: unknown;\n /**\n * Sent as `Idempotency-Key` (and, for a terminal report, equals the body's\n * own `report_id`). Required for `POST`; a `GET` sends no `Idempotency-Key`,\n * because `PROTOCOLS.md` forbids one on a route that does not deduplicate.\n */\n readonly callId?: string;\n readonly accept: \"application/json\" | \"text/event-stream\";\n readonly signal?: AbortSignal;\n}\n\n/**\n * Issues one `POST` to `client.baseUrl + init.path` carrying every header the\n * protocol requires and no other identity-bearing header, and returns the\n * successful `Response` unread so a caller that needs a stream can consume\n * it incrementally.\n *\n * This is the only function in the package that calls `fetch()` against\n * Enlitt. Every safety property the spec requires — HTTPS, no redirects,\n * bounded response size, normalization of every failure, and the\n * `rate_limit_exceeded` wait — lives here so no call site can accidentally\n * skip one.\n */\nexport async function requestEnlitt(client: InternalEnlittClient, init: EnlittRequestInit): Promise<Response> {\n assertHttps(client.baseUrl);\n\n const url = new URL(init.path, client.baseUrl).toString();\n const session = client.resolveSession();\n\n // The exhaustive header set. `Enlitt-Version` names the API version this\n // build was written against; it is information for the server only, and the\n // SDK never reads a version header back (forward compatibility comes from\n // tolerant parsing, not negotiation).\n const headers: Record<string, string> = {\n Authorization: client.businessAuthorization,\n \"X-Enlitt-User-Authorization\": `Bearer ${session.token}`,\n Accept: init.accept,\n \"X-Request-Id\": generateRequestId(),\n [ENLITT_VERSION_HEADER]: ENLITT_API_VERSION,\n \"X-Enlitt-SDK-Version\": client.sdkVersion\n };\n if (init.method !== \"GET\") {\n if (init.callId === undefined) {\n throw new EnlittConfigurationError(\"An Enlitt POST request requires a call ID for its Idempotency-Key.\");\n }\n headers[\"Idempotency-Key\"] = init.callId;\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n const waitStartedAtMs = Date.now();\n\n for (let attempt = 1; ; attempt++) {\n const response = await sendOnce(url, headers, init);\n\n if (response.ok) {\n assertBoundedResponse(response);\n return response;\n }\n\n const error = await normalizeResponse(response);\n\n if (error.code !== ENLITT_ERROR_CODE.rate_limit_exceeded) {\n throw error;\n }\n\n const canRetry =\n attempt < client.rateLimit.maxAttempts &&\n Date.now() - waitStartedAtMs < client.rateLimit.maxTotalWaitMs;\n if (!canRetry) {\n throw error;\n }\n\n const floorMs = error.retryAfterMs ?? DEFAULT_RATE_LIMIT_FLOOR_MS;\n const delayMs = floorMs + Math.random() * (floorMs / 2);\n client.rateLimit.onRateLimit?.(attempt, delayMs);\n await sleep(delayMs, init.signal);\n }\n}\n\n/**\n * Retries a premium terminal report a bounded number of times on a\n * transient failure, resending the identical `init` — the same body (and so\n * the same `report_id`) and the same `Idempotency-Key` — on every attempt,\n * which is what makes the retry safe: Enlitt's own idempotency on that key\n * turns a duplicate send into a replay rather than a second report.\n *\n * Only a failure with no distinct business action of its own is treated as\n * transient: a transport failure that never produced a response, or one of\n * the three retryable server-side wire codes (`server_error`,\n * `provider_error`, `no_capable_route`). A refusal, a conflict, or an\n * exhausted `rate_limit_exceeded` wait (already retried once, inside\n * `requestEnlitt()`) is never retried again here — retrying a refusal a\n * second time under a different name is exactly what the spec forbids.\n *\n * Exhausting the bound reports the last error to `client.onTerminalReportError`\n * and rethrows it, rather than swallowing it: the hook exists because the\n * provider call this report describes has already finished and there is no\n * result left to withhold from a caller, not because the failure stops\n * mattering.\n */\nexport async function reportEnlittPremiumTerminal(\n client: InternalEnlittClient,\n init: EnlittRequestInit\n): Promise<Response> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await requestEnlitt(client, init);\n } catch (thrown) {\n const error = thrown instanceof EnlittError ? thrown : normalizeEnlittModelError(thrown, false);\n const canRetry = isTransientTerminalReportFailure(error) && attempt < TERMINAL_REPORT_MAX_ATTEMPTS;\n if (!canRetry) {\n client.onTerminalReportError?.(error);\n throw error;\n }\n await sleep(TERMINAL_REPORT_RETRY_DELAY_MS, init.signal);\n }\n }\n}\n\n/**\n * Transient means \"a delay may fix it\": a transport failure that never\n * produced a response, or a retryable 5xx (`server_error`, `provider_error`,\n * or a newer 5xx code the classifier marked retryable). Anything else,\n * including an exhausted rate-limit wait, is not retried again here.\n */\nfunction isTransientTerminalReportFailure(error: EnlittError): boolean {\n if (error.code === \"transport_failed\") {\n return true;\n }\n return error.retryable && error.code !== ENLITT_ERROR_CODE.rate_limit_exceeded;\n}\n\n/**\n * Sends exactly one HTTP request and normalizes a network-level failure into\n * the shapes `normalizeEnlittModelError()` recognizes, so `requestEnlitt()`\n * has only one kind of thing to handle beyond a `Response`: a thrown\n * `EnlittError`.\n *\n * Redirects are never followed: no legitimate Enlitt endpoint redirects,\n * and following one would either resend a bearer credential for two\n * principals to another origin or silently retarget a financial request.\n * `redirect: \"manual\"` hands the redirect back unfollowed and\n * `isRedirectResponse()` turns it into `transport_failed`. (`redirect:\n * \"error\"` would be the natural choice, but the Cloudflare Workers runtime\n * rejects it with a `TypeError` before sending, so every call from a Worker\n * failed.)\n */\nasync function sendOnce(url: string, headers: Record<string, string>, init: EnlittRequestInit): Promise<Response> {\n let response: Response;\n try {\n response = await fetch(url, {\n method: init.method ?? \"POST\",\n headers,\n ...(init.method === \"GET\" ? {} : { body: JSON.stringify(init.body) }),\n redirect: \"manual\",\n ...(init.signal !== undefined ? { signal: init.signal } : {})\n });\n } catch (thrown) {\n const message = describeThrown(thrown);\n if (init.signal?.aborted === true) {\n throw normalizeEnlittModelError(\n { kind: \"request_canceled\", ...(message !== undefined ? { message } : {}) } satisfies EnlittRequestCanceled,\n false\n );\n }\n throw normalizeEnlittModelError(\n { kind: \"transport_failed\", ...(message !== undefined ? { message } : {}) } satisfies EnlittTransportFailure,\n false\n );\n }\n if (isRedirectResponse(response)) throw redirectRefused(response);\n return response;\n}\n\n/** The one message for a refused redirect (`specs/SDK-side routing.md`). */\nconst REDIRECT_REFUSED_MESSAGE = \"Enlitt answered with a redirect, which the SDK never follows.\";\n\n/**\n * True for an unfollowed redirect under `redirect: \"manual\"`: a `3xx` status\n * (server runtimes such as Workers and Node) or an `opaqueredirect` response\n * with status `0` (browsers, which hide the redirect's details).\n */\nexport function isRedirectResponse(response: Response): boolean {\n return response.type === \"opaqueredirect\" || (response.status >= 300 && response.status < 400);\n}\n\n/**\n * The `transport_failed` error for a refused redirect. The body is cancelled\n * unread so the connection is released; nothing from it is used.\n */\nexport function redirectRefused(response: Response): EnlittError {\n void response.body?.cancel().catch(() => undefined);\n return normalizeEnlittModelError(\n { kind: \"transport_failed\", message: REDIRECT_REFUSED_MESSAGE } satisfies EnlittTransportFailure,\n false\n );\n}\n\n/**\n * Bounds response header and body size, then parses the OpenAI-shaped error\n * body and hands it to `normalizeEnlittModelError()`. A response this\n * function cannot safely read or parse normalizes to `malformed_response`\n * rather than exposing raw bytes or a parser exception to a caller.\n */\nasync function normalizeResponse(response: Response): Promise<EnlittError> {\n if (!isBoundedHeaderSet(response.headers)) {\n return normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response headers exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n\n const text = await readBoundedBody(response);\n if (text === undefined) {\n return normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n\n let body: unknown;\n try {\n body = JSON.parse(text) as unknown;\n } catch {\n return normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body was not valid JSON.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n\n // The body is handed to the normalizer as-is: the protocol's classifier\n // decides whether it is an Enlitt error envelope, so no second structural\n // check lives here.\n return normalizeEnlittModelError(\n {\n kind: \"http_error\",\n status: response.status,\n body,\n headers: {\n \"retry-after\": response.headers.get(\"retry-after\") ?? undefined,\n \"x-request-id\": response.headers.get(\"x-request-id\") ?? undefined\n }\n } satisfies EnlittHttpErrorResponse,\n false\n );\n}\n\n/**\n * Enforces `MAX_RESPONSE_HEADER_BYTES` over a response's own header set,\n * summing each name and value once. Cheap and approximate on purpose: this\n * exists to stop a misbehaving endpoint from making this module hold an\n * unbounded amount of attacker-controlled header data, not to bill bytes\n * exactly.\n */\nfunction isBoundedHeaderSet(headers: Headers): boolean {\n let total = 0;\n for (const [name, value] of headers.entries()) {\n total += name.length + value.length;\n if (total > MAX_RESPONSE_HEADER_BYTES) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Reads a response body up to `MAX_RESPONSE_BODY_BYTES`, returning\n * `undefined` rather than a truncated string when the bound is exceeded —\n * truncating and parsing a partial body risks succeeding on a document that\n * is not the one Enlitt actually sent.\n */\nasync function readBoundedBody(response: Response): Promise<string | undefined> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null && Number(contentLength) > MAX_RESPONSE_BODY_BYTES) {\n return undefined;\n }\n\n const body = response.body;\n if (body === null) {\n return \"\";\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n total += value.byteLength;\n if (total > MAX_RESPONSE_BODY_BYTES) {\n await reader.cancel();\n return undefined;\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n return new TextDecoder().decode(concatChunks(chunks, total));\n}\n\n/**\n * Reads a successful response's body as JSON, bounded by the same body-size\n * limit every other read in this file uses. An oversized body or one that is\n * not valid JSON is a `malformed_response` `EnlittError`, never a raw parser\n * exception. Every JSON-bodied Enlitt response (begin, terminal report, usage,\n * non-streaming standard response) is read through here, so no caller buffers\n * an unbounded body or parses JSON on its own.\n */\nexport async function readEnlittJson(response: Response): Promise<unknown> {\n const text = await readBoundedBody(response);\n if (text === undefined) {\n throw normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body was not valid JSON.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n}\n\nfunction concatChunks(chunks: readonly Uint8Array[], total: number): Uint8Array {\n const merged = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n merged.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return merged;\n}\n\n/**\n * A successful response is bounded the same way a failing one is — checked\n * eagerly here so an oversized `200` fails fast rather than letting a caller\n * downstream (the standard or premium model) buffer it first.\n */\nfunction assertBoundedResponse(response: Response): void {\n if (!isBoundedHeaderSet(response.headers)) {\n throw normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response headers exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null && Number(contentLength) > MAX_RESPONSE_BODY_BYTES) {\n throw normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n}\n\n/**\n * HTTPS is required outside local development. `http:` is accepted only for\n * the three hosts a developer's own machine can present as, and there is no\n * environment flag that relaxes this — a business misconfiguring its own\n * deployed base URL must fail loudly rather than send its business and\n * personal credentials in the clear.\n *\n * Exported (in addition to being used per-request by `requestEnlitt()`) so\n * `language-model.ts` can run the identical check once, at `enlitt()`\n * construction, against the resolved `baseUrl` before any request is made —\n * the spec requires base URL validation to happen at construction, not per\n * call, and duplicating this rule there would let the two copies drift.\n */\nexport function assertHttps(baseUrl: string): void {\n const parsed = new URL(baseUrl);\n if (parsed.protocol === \"https:\") {\n return;\n }\n if (parsed.protocol === \"http:\" && LOCAL_HTTP_HOSTS.has(parsed.hostname)) {\n return;\n }\n throw new EnlittConfigurationError(\n `Enlitt base URL must use https: outside local development (got ${parsed.protocol} for host ` +\n `${parsed.hostname}). There is no environment flag that relaxes this.`\n );\n}\n\n/** A bounded, non-authoritative caller trace ID. `crypto.randomUUID()` is 36 characters, well under any reasonable bound. */\nfunction generateRequestId(): string {\n return crypto.randomUUID();\n}\n\n/** Extracts a safe, bounded description from a caught value without ever including request content. */\nfunction describeThrown(thrown: unknown): string | undefined {\n if (thrown instanceof Error) {\n return thrown.message.slice(0, 500);\n }\n return undefined;\n}\n\n/**\n * Sleeps for `delayMs`, or rejects immediately with the signal's abort\n * reason if `signal` is aborted before the sleep completes. Used by both\n * internal retries, so a caller-initiated cancellation ends a rate-limit\n * wait or a terminal-report retry exactly as promptly as it ends an\n * in-flight request.\n */\nfunction sleep(delayMs: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted === true) {\n // The caller's abort reason must escape unchanged, not wrapped in an\n // Error this module invents, so a caller can compare it against the\n // exact value it passed to `AbortController.abort()`.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return Promise.reject(signal.reason as unknown);\n }\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, delayMs);\n function onAbort(): void {\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- see above.\n reject(signal?.reason as unknown);\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * The one premium billing lifecycle, with no framework dependency.\n *\n * `specs/SDK-side routing.md` gives this file the framework-agnostic core of\n * premium mode: a business runs a model call it pays for, and Enlitt only\n * accounts for it. The call is bracketed by a content-free begin (a maximum\n * charge in NANOUSD, declared before the provider runs) and exactly one\n * terminal report (a status and the actual NANOUSD charge, sent after it).\n *\n * `runPremiumCharge()` is the single implementation of that lifecycle: one\n * begin, one status rule, one charge rule, one report path. The public\n * `withPremiumCharge()` in this file and the Vercel adapter in\n * `vercel/premium-language-model.ts` are both thin layers over it, so moving a\n * call between the two changes how the charge is computed and nothing about how\n * it is settled.\n *\n * This file imports nothing from the Vercel AI SDK, and it never sends prompts,\n * messages, outputs, files, tools, provider options, provider keys, raw errors,\n * or content hashes to Enlitt: every body it builds is assembled field by field\n * from bounded named inputs, never by forwarding a caller-supplied object.\n *\n * Every NANOUSD amount is a canonical base-10 integer string and is compared\n * only as a `bigint`; none is ever converted to `number`, rounded, or displayed.\n */\n\nimport {\n CanonicalIntegerError,\n IDEMPOTENCY_KEY_MAX_LENGTH,\n IDEMPOTENCY_KEY_MIN_LENGTH,\n IdempotencyKeyError,\n assertIdempotencyKey,\n parseCanonicalInteger,\n validateBeginPremiumOperationRequest,\n validateBeginPremiumOperationResponse,\n validateCallerMetadata,\n validateReportPremiumTerminalRequest,\n validateReportPremiumTerminalResponse\n} from \"@enlitt/protocol\";\nimport { EnlittConfigurationError, EnlittError, normalizeEnlittModelError } from \"./errors.js\";\nimport {\n createInternalClient,\n readEnlittJson,\n reportEnlittPremiumTerminal,\n requestEnlitt,\n type EnlittOptions,\n type InternalEnlittClient\n} from \"./transport.js\";\n\n// --- Public types ----------------------------------------------------------\n\n/**\n * Records the NANOUSD amount to report for the call. Callable any number of\n * times; the last call wins. Throws `EnlittConfigurationError` synchronously\n * for an amount that is not a canonical nonnegative integer string, and for a\n * call made after the report has been sent.\n */\nexport type PremiumChargeFunction = (amountNanoUsd: string) => void;\n\n/**\n * The optional content-free facts a business may attach to the terminal\n * report. None is required and none has a financial effect.\n */\nexport interface PremiumTerminalFacts {\n readonly usage?: {\n inputTokens?: number;\n outputTokens?: number;\n cachedInputTokens?: number;\n reasoningTokens?: number;\n };\n readonly finishReason?: string;\n readonly providerResponseId?: string;\n readonly delivery?: { outputStarted: boolean; outputCompleted: boolean };\n readonly timing?: { startedAt: string; endedAt: string };\n readonly errorCategory?: \"provider\" | \"timeout\" | \"network\" | \"invalid_request\" | \"canceled\" | \"unknown\";\n}\n\n/** The admitted operation, as handed to a `withPremiumCharge()` callback. */\nexport interface PremiumChargeHandle {\n readonly operationId: string;\n /** The most the report can charge: the declared maximum, lowered by the server to this user's per-call limit. */\n readonly effectiveMaxChargeNanoUsd: string;\n readonly terminalDeadline: string;\n /** Records safe facts for the terminal report; the last call wins. */\n describe(facts: PremiumTerminalFacts): void;\n}\n\n/** What one premium operation declares at begin. */\nexport interface PremiumChargeRequest {\n readonly maxCharge: string;\n readonly provider: { id: string; model: string };\n readonly callId?: string;\n readonly reportingDeadlineMs?: number;\n readonly metadata?: Record<string, string>;\n readonly signal?: AbortSignal;\n}\n\n/**\n * The admitted operation as returned by Enlitt, carried opaquely to the\n * terminal report. The response's equal `reserved_nano_usd` is validated and\n * otherwise not exposed; no credit or pricing-version field exists on the wire.\n */\nexport interface PremiumOperation {\n readonly operationId: string;\n readonly effectiveMaxChargeNanoUsd: string;\n readonly terminalDeadline: string;\n}\n\n/** One terminal report in the TypeScript shape this module works in. */\nexport interface PremiumTerminalReport extends PremiumTerminalFacts {\n readonly reportId: string;\n readonly status: \"completed\" | \"failed\" | \"canceled\";\n readonly chargeNanoUsd: string;\n}\n\n/** Options for {@link withPremiumCharge}: the shared construction options plus one premium call's declaration. */\nexport interface WithPremiumChargeOptions extends EnlittOptions {\n /** NANOUSD, a canonical nonnegative integer string. */\n maxCharge: string;\n /** Bounded labels, as on the premium begin request. */\n provider: { id: string; model: string };\n /** The call ID; default a fresh random one. */\n idempotencyKey?: string;\n reportingDeadlineMs?: number;\n metadata?: Record<string, string>;\n signal?: AbortSignal;\n}\n\n// --- Shared option validation ----------------------------------------------\n//\n// `withPremiumCharge()` and the Vercel `readEnlittCallOptions()` apply the same\n// rules, so the rules live here once. Every failure is an\n// `EnlittConfigurationError` raised before any Enlitt or provider request.\n\n/** Visible ASCII, matching the protocol's own `Idempotency-Key` character rule. */\nconst VISIBLE_ASCII = /^[\\x21-\\x7e]+$/;\n\n/**\n * A supplied idempotency key is a base, not the call identity: the Vercel\n * adapter appends `.<prompt item count>`. The floor is the protocol's own\n * 16-character floor, imported rather than restated, so every derived ID\n * satisfies the wire bound by construction; the ceiling stays well under 255\n * so the appended suffix can never push a derived ID over it.\n */\nexport const IDEMPOTENCY_KEY_OPTION_MIN_LENGTH = IDEMPOTENCY_KEY_MIN_LENGTH;\nexport const IDEMPOTENCY_KEY_OPTION_MAX_LENGTH = 200;\n\n/**\n * Validates a NANOUSD amount: a canonical nonnegative base-10 integer string\n * with no sign, fraction, exponent, whitespace, or noncanonical leading zero.\n * `\"0\"` is valid. Parsed as `bigint` (so values beyond the safe-integer range\n * keep full precision) and returned as the exact string the caller supplied.\n */\nexport function assertNanoUsd(value: unknown, label: string): string {\n try {\n parseCanonicalInteger(value, label);\n } catch (thrown) {\n if (thrown instanceof CanonicalIntegerError) {\n throw new EnlittConfigurationError(thrown.message);\n }\n throw thrown;\n }\n return value as string;\n}\n\n/** Validates a business-supplied idempotency key base (16-200 visible ASCII characters). */\nexport function assertIdempotencyKeyBase(value: unknown, label: string): string {\n if (\n typeof value !== \"string\" ||\n value.length < IDEMPOTENCY_KEY_OPTION_MIN_LENGTH ||\n value.length > IDEMPOTENCY_KEY_OPTION_MAX_LENGTH ||\n !VISIBLE_ASCII.test(value)\n ) {\n throw new EnlittConfigurationError(\n `${label} must be ${IDEMPOTENCY_KEY_OPTION_MIN_LENGTH}-${IDEMPOTENCY_KEY_OPTION_MAX_LENGTH} visible ASCII characters.`\n );\n }\n return value;\n}\n\n/**\n * Validates a requested reporting deadline as a positive safe integer. The\n * deployed maximum is server policy and is not knowable locally, so no local\n * maximum is applied; the server bounds it and its returned deadline is\n * authoritative.\n */\nexport function assertReportingDeadlineMs(value: unknown, label: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0) {\n throw new EnlittConfigurationError(`${label} must be a positive safe integer.`);\n }\n return value;\n}\n\n/**\n * Validates caller metadata with the protocol's own `Record<string, string>`\n * rule (at most 16 entries, bounded keys and values, no `enlitt_` prefix): one\n * rule and one validator rather than a per-mode type.\n */\nexport function assertCallerMetadata(value: unknown, label: string): Record<string, string> {\n const validated = validateCallerMetadata(value, label);\n if (!validated.ok) {\n throw new EnlittConfigurationError(`${validated.error.message} (${validated.error.param})`);\n }\n return validated.value;\n}\n\n/** Validates a call ID against the protocol's 16-255 visible-ASCII `Idempotency-Key` bound. */\nexport function assertCallId(callId: string): string {\n try {\n return assertIdempotencyKey(callId);\n } catch (thrown) {\n if (thrown instanceof IdempotencyKeyError) {\n throw new EnlittConfigurationError(\n `The call ID \"${callId}\" is not a valid Idempotency-Key (must be ` +\n `${IDEMPOTENCY_KEY_MIN_LENGTH}-${IDEMPOTENCY_KEY_MAX_LENGTH} visible ASCII characters).`\n );\n }\n throw thrown;\n }\n}\n\n/** A freshly generated, unique-per-operation random value of at least 16 visible ASCII characters (a UUID is 36). */\nexport function generateRandomCallId(): string {\n return crypto.randomUUID();\n}\n\n// --- Wire paths ------------------------------------------------------------\n\n/** The one relative path an operation is begun at, per `specs/PROTOCOLS.md` \"Begin premium operation\". */\nconst BEGIN_PREMIUM_OPERATION_PATH = \"/v1/enlitt/operations\";\n\n/** The one relative path a terminal outcome is reported to, per \"Report premium terminal state\". */\nfunction terminalReportPath(operationId: string): string {\n return `/v1/enlitt/operations/${encodeURIComponent(operationId)}/terminal`;\n}\n\n// --- Begin -----------------------------------------------------------------\n\n/**\n * Calls **Begin premium operation** before the provider ever runs.\n *\n * Sends `mode: \"premium\"`, `max_charge_nano_usd` exactly as the business\n * declared it, `reporting_deadline_ms` when supplied, the bounded `provider`\n * labels, and `metadata`. The call ID travels as the request's\n * `Idempotency-Key`, never as a body field: the protocol lists no such field.\n * Enlitt performs the conversion to credit units; this function sends no credit\n * figure and reads no balance figure.\n *\n * The body is validated with the protocol's strict request validator before it\n * is sent (strict out). The response is parsed in tolerant mode (tolerant in):\n * an extra field or an unknown `billing` value still admits the operation. The\n * returned `effective_max_charge_nano_usd` and `terminal_deadline` are\n * authoritative regardless of what was requested.\n *\n * A refusal, a business authentication failure, or a transport failure\n * surfaces as the corresponding typed error with `providerInvoked: false`;\n * there is no path from a refusal to a provider invocation, including a\n * `rate_limit_exceeded` whose transport wait was exhausted (defensive: the\n * server never sends it on the premium path).\n */\nexport async function beginPremiumOperation(\n client: InternalEnlittClient,\n request: PremiumChargeRequest,\n callId: string\n): Promise<PremiumOperation> {\n const body: Record<string, unknown> = {\n mode: \"premium\",\n max_charge_nano_usd: request.maxCharge,\n provider: { id: request.provider.id, model: request.provider.model }\n };\n if (request.reportingDeadlineMs !== undefined) {\n body.reporting_deadline_ms = request.reportingDeadlineMs;\n }\n if (request.metadata !== undefined) {\n body.metadata = request.metadata;\n }\n\n const validated = validateBeginPremiumOperationRequest(body);\n if (!validated.ok) {\n throw new EnlittConfigurationError(\n `The premium operation request is invalid: ${validated.error.message} (${validated.error.param}).`\n );\n }\n\n const response = await requestEnlitt(client, {\n path: BEGIN_PREMIUM_OPERATION_PATH,\n body: validated.value,\n callId,\n accept: \"application/json\",\n ...(request.signal !== undefined ? { signal: request.signal } : {})\n });\n\n const parsed = validateBeginPremiumOperationResponse(await readEnlittJson(response), { mode: \"tolerant\" });\n if (!parsed.ok) {\n throw new EnlittError(\n \"malformed_response\",\n `Enlitt's premium operation response could not be validated: ${parsed.error.message} (${parsed.error.param}).`\n );\n }\n\n return {\n operationId: parsed.value.operation_id,\n effectiveMaxChargeNanoUsd: parsed.value.effective_max_charge_nano_usd,\n terminalDeadline: parsed.value.terminal_deadline\n };\n}\n\n// --- Terminal report -------------------------------------------------------\n\n/**\n * Sends one idempotent content-free terminal report to **Report premium\n * terminal state**, through the transport's bounded transient retry, which\n * resends the identical body and `Idempotency-Key` so a retry is a replay and\n * never a second report. `report.reportId` is generated once per operation.\n *\n * Never propagates a delivery failure into its caller. When the transport's\n * retries are exhausted, or Enlitt answers `409`, the typed error has already\n * been handed to `client.onTerminalReportError` (by the transport) and is\n * dropped here: a delivered provider output is a fact the business already\n * paid for, and turning an unrelated reporting failure into a thrown error\n * would make it discard output it already has. An undelivered report instead\n * lets the operation expire at its deadline, charging nothing.\n *\n * The response is parsed tolerantly. A report whose `status` reads as `\"other\"`\n * is still a delivered report: it is neither retried nor passed to\n * `onTerminalReportError`.\n */\nexport async function reportPremiumTerminalState(\n client: InternalEnlittClient,\n operation: PremiumOperation,\n report: PremiumTerminalReport\n): Promise<void> {\n const body: Record<string, unknown> = {\n report_id: report.reportId,\n status: report.status,\n charge_nano_usd: report.chargeNanoUsd\n };\n\n if (report.usage !== undefined) {\n const usage: Record<string, number> = {};\n if (report.usage.inputTokens !== undefined) usage.input_tokens = report.usage.inputTokens;\n if (report.usage.outputTokens !== undefined) usage.output_tokens = report.usage.outputTokens;\n if (report.usage.cachedInputTokens !== undefined) usage.cached_input_tokens = report.usage.cachedInputTokens;\n if (report.usage.reasoningTokens !== undefined) usage.reasoning_tokens = report.usage.reasoningTokens;\n body.usage = usage;\n }\n if (report.finishReason !== undefined) body.finish_reason = report.finishReason;\n if (report.providerResponseId !== undefined) body.provider_response_id = report.providerResponseId;\n if (report.delivery !== undefined) {\n body.delivery = { output_started: report.delivery.outputStarted, output_completed: report.delivery.outputCompleted };\n }\n if (report.timing !== undefined) {\n body.timing = { started_at: report.timing.startedAt, ended_at: report.timing.endedAt };\n }\n if (report.errorCategory !== undefined) body.error_category = report.errorCategory;\n\n // Strict out. A report the SDK built wrongly is observed like any other\n // undeliverable report: the operation will simply expire, charging nothing.\n const validated = validateReportPremiumTerminalRequest(body);\n if (!validated.ok) {\n client.onTerminalReportError?.(\n new EnlittConfigurationError(\n `The premium terminal report is invalid and was not sent: ${validated.error.message} (${validated.error.param}).`\n )\n );\n return;\n }\n\n try {\n const response = await reportEnlittPremiumTerminal(client, {\n path: terminalReportPath(operation.operationId),\n body: validated.value,\n callId: report.reportId,\n accept: \"application/json\"\n });\n const parsed = validateReportPremiumTerminalResponse(await readEnlittJson(response), { mode: \"tolerant\" });\n if (!parsed.ok) {\n client.onTerminalReportError?.(\n new EnlittError(\n \"malformed_response\",\n `Enlitt's terminal report response could not be validated: ${parsed.error.message} (${parsed.error.param}).`\n )\n );\n }\n } catch (thrown) {\n // `reportEnlittPremiumTerminal()` already delivered a transport or refusal\n // failure to `client.onTerminalReportError` before rethrowing it; a body\n // that could not be read is reported here. Neither reaches the caller.\n if (thrown instanceof EnlittError && thrown.code === \"malformed_response\") {\n client.onTerminalReportError?.(thrown);\n } else if (!(thrown instanceof EnlittError)) {\n client.onTerminalReportError?.(normalizeEnlittModelError(thrown, false));\n }\n }\n}\n\n// --- The lifecycle ---------------------------------------------------------\n\n/**\n * Whether `run` rejected because the call was canceled: the request's own\n * signal is aborted, or the error is an `AbortError`.\n */\nexport function isCancellation(thrown: unknown, signal: AbortSignal | undefined): boolean {\n if (signal?.aborted === true) {\n return true;\n }\n return typeof thrown === \"object\" && thrown !== null && (thrown as { name?: unknown }).name === \"AbortError\";\n}\n\n/**\n * Wraps exactly one model call: begins one operation, runs `run` only after\n * admission, and sends exactly one terminal report.\n *\n * - **Begin.** `request.callId` when supplied (validated against the protocol's\n * `Idempotency-Key` bounds), otherwise a fresh random ID. A refusal,\n * authentication failure, or transport failure rejects with the typed error\n * and `run` is never called.\n * - **Run.** `run` receives a `charge` function and the admitted operation.\n * `charge(amount)` records the amount to report; the last call wins.\n * - **Status.** `run` resolving is `completed`. `run` rejecting while\n * `request.signal` is aborted, or with an `AbortError`, is `canceled`. Any\n * other rejection is `failed`. The status is decided by how `run` settles,\n * never by the caller naming one, so a caller cannot report a failure as a\n * charged cancellation.\n * - **Charge.** `\"0\"` for `failed`, whatever `charge()` received (a failed call\n * is always free). For `completed` and `canceled`, the last amount passed to\n * `charge()`, or `\"0\"` if never called, lowered to the effective maximum\n * without an error.\n * - **Report.** One `PremiumTerminalReport` with a `reportId` generated once,\n * awaited before settling so a serverless process cannot end between the\n * call and its report.\n * - **Result.** `run`'s value, or `run`'s own error unchanged.\n */\nexport async function runPremiumCharge<T>(\n client: InternalEnlittClient,\n request: PremiumChargeRequest,\n run: (charge: PremiumChargeFunction, operation: PremiumChargeHandle) => Promise<T>\n): Promise<T> {\n const callId = assertCallId(request.callId ?? generateRandomCallId());\n const operation = await beginPremiumOperation(client, request, callId);\n\n const startedAt = new Date();\n let recordedChargeNanoUsd = \"0\";\n let facts: PremiumTerminalFacts = {};\n let reportSent = false;\n\n const charge: PremiumChargeFunction = (amountNanoUsd) => {\n if (reportSent) {\n throw new EnlittConfigurationError(\"charge() was called after the terminal report was sent.\");\n }\n recordedChargeNanoUsd = assertNanoUsd(amountNanoUsd, \"charge amount\");\n };\n\n const handle: PremiumChargeHandle = {\n operationId: operation.operationId,\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd,\n terminalDeadline: operation.terminalDeadline,\n describe: (next) => {\n facts = next;\n }\n };\n\n /** Builds and sends the one report for the status `run` settled with. */\n const report = async (status: PremiumTerminalReport[\"status\"]): Promise<void> => {\n reportSent = true;\n const effective = BigInt(operation.effectiveMaxChargeNanoUsd);\n const recorded = BigInt(recordedChargeNanoUsd);\n const chargeNanoUsd =\n status === \"failed\" ? \"0\" : recorded > effective ? operation.effectiveMaxChargeNanoUsd : recordedChargeNanoUsd;\n\n await reportPremiumTerminalState(client, operation, {\n // The describe() timing wins when the business supplied one; otherwise\n // the lifecycle's own bracket around `run` is the best content-free fact.\n timing: { startedAt: startedAt.toISOString(), endedAt: new Date().toISOString() },\n ...facts,\n reportId: crypto.randomUUID(),\n status,\n chargeNanoUsd\n });\n };\n\n let value: T;\n try {\n value = await run(charge, handle);\n } catch (thrown) {\n await report(isCancellation(thrown, request.signal) ? \"canceled\" : \"failed\");\n // Rethrown unchanged: Enlitt adds nothing to, and wraps nothing of, what\n // the business's code threw.\n throw thrown;\n }\n\n await report(\"completed\");\n return value;\n}\n\n/**\n * Accounts one premium model call made by code outside the Vercel AI SDK: a\n * direct provider SDK call, a raw `fetch`, anything the business runs itself.\n *\n * It performs `enlitt()`'s construction checks (server runtime, business\n * secret, base URL) by building one internal client from the `EnlittOptions`\n * fields, validates `maxCharge`, `idempotencyKey`, `reportingDeadlineMs`, and\n * `metadata` under the same rules the Vercel adapter applies, and delegates to\n * {@link runPremiumCharge} with `idempotencyKey` as the call ID. Every failure\n * of those checks is an `EnlittConfigurationError` before any request.\n *\n * It is one model call. A loop of calls is a loop of `withPremiumCharge()`\n * calls; retrying the same call with the same `idempotencyKey` replays that\n * operation instead of charging again.\n */\nexport async function withPremiumCharge<T>(\n options: WithPremiumChargeOptions,\n run: (charge: PremiumChargeFunction, operation: PremiumChargeHandle) => Promise<T>\n): Promise<T> {\n const client = createInternalClient({\n ...(options.secretKey !== undefined ? { secretKey: options.secretKey } : {}),\n ...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),\n ...(options.session !== undefined ? { session: options.session } : {}),\n ...(options.rateLimit !== undefined ? { rateLimit: options.rateLimit } : {}),\n ...(options.onTerminalReportError !== undefined ? { onTerminalReportError: options.onTerminalReportError } : {})\n });\n\n const maxCharge = assertNanoUsd(options.maxCharge, \"maxCharge\");\n const callId =\n options.idempotencyKey !== undefined\n ? assertIdempotencyKeyBase(options.idempotencyKey, \"idempotencyKey\")\n : undefined;\n const reportingDeadlineMs =\n options.reportingDeadlineMs !== undefined\n ? assertReportingDeadlineMs(options.reportingDeadlineMs, \"reportingDeadlineMs\")\n : undefined;\n const metadata =\n options.metadata !== undefined ? assertCallerMetadata(options.metadata, \"metadata\") : undefined;\n\n return runPremiumCharge(\n client,\n {\n maxCharge,\n provider: { id: options.provider.id, model: options.provider.model },\n ...(callId !== undefined ? { callId } : {}),\n ...(reportingDeadlineMs !== undefined ? { reportingDeadlineMs } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {})\n },\n run\n );\n}\n"]}
|