@redocly/cli 0.0.0-snapshot.1784554531 → 0.0.0-snapshot.1784620262
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/lib/chunks/{URE42RCZ.js → 32PZUSDF.js} +2 -2
- package/lib/chunks/{OLYAB3Z5.js → 5XWJ7SND.js} +3 -3
- package/lib/chunks/{N6FJ5HYR.js → 74VQSZ5T.js} +1 -1
- package/lib/chunks/{FLRQX75P.js → GHBEV27L.js} +2 -2
- package/lib/chunks/{QEKGREJP.js → H7EUHTNC.js} +1 -1
- package/lib/chunks/{KD24SG2E.js → HD24VMMU.js} +3 -1
- package/lib/chunks/{IT2ABZKC.js → IRDDR6ZX.js} +2 -2
- package/lib/chunks/{CQW6BTG6.js → LK5QRO6Z.js} +3 -3
- package/lib/chunks/{LGUVWMQ6.js → QDTFSU2A.js} +66 -21
- package/lib/chunks/{IJMPB5WN.js → U5H3NDWA.js} +1 -1
- package/lib/chunks/{M5ZNR5FB.js → UTL36DYM.js} +4 -4
- package/lib/chunks/{7COJB2Y6.js → UWZRCAHF.js} +1 -1
- package/lib/chunks/{T2PUTL2H.js → Y7AZMCRO.js} +3 -3
- package/lib/chunks/{EX5AKFM3.js → ZQF2RYWL.js} +1 -1
- package/lib/index.js +20 -14
- package/package.json +1 -1
|
@@ -12,10 +12,10 @@ import {
|
|
|
12
12
|
maskSecrets,
|
|
13
13
|
parseRuntimeExpression,
|
|
14
14
|
run
|
|
15
|
-
} from "./
|
|
15
|
+
} from "./ZQF2RYWL.js";
|
|
16
16
|
import "./HXIHIVQ5.js";
|
|
17
17
|
import "./XDVFCBV7.js";
|
|
18
|
-
import "./
|
|
18
|
+
import "./HD24VMMU.js";
|
|
19
19
|
import "./HRYOF224.js";
|
|
20
20
|
import "./YDPUXTSG.js";
|
|
21
21
|
export {
|
|
@@ -6,13 +6,13 @@ var __filename = __fileURLToPath(import.meta.url);
|
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
7
|
import {
|
|
8
8
|
RedoclyOAuthClient
|
|
9
|
-
} from "./
|
|
9
|
+
} from "./IRDDR6ZX.js";
|
|
10
10
|
import "./7COZBK76.js";
|
|
11
11
|
import "./JPNXFCZJ.js";
|
|
12
|
-
import "./
|
|
12
|
+
import "./U5H3NDWA.js";
|
|
13
13
|
import "./QRC5ADSZ.js";
|
|
14
14
|
import "./XDVFCBV7.js";
|
|
15
|
-
import "./
|
|
15
|
+
import "./HD24VMMU.js";
|
|
16
16
|
import "./HRYOF224.js";
|
|
17
17
|
import "./YDPUXTSG.js";
|
|
18
18
|
export {
|
|
@@ -7,7 +7,7 @@ var __dirname = __pathDirname(__filename);
|
|
|
7
7
|
import {
|
|
8
8
|
AbortFlowError,
|
|
9
9
|
exitWithError
|
|
10
|
-
} from "./
|
|
10
|
+
} from "./UWZRCAHF.js";
|
|
11
11
|
import {
|
|
12
12
|
ConfigValidationError,
|
|
13
13
|
HandledError,
|
|
@@ -31,7 +31,7 @@ import {
|
|
|
31
31
|
red,
|
|
32
32
|
stringifyYaml,
|
|
33
33
|
yellow
|
|
34
|
-
} from "./
|
|
34
|
+
} from "./HD24VMMU.js";
|
|
35
35
|
|
|
36
36
|
// src/commands/lint.ts
|
|
37
37
|
import { performance as performance3 } from "perf_hooks";
|
|
@@ -25485,6 +25485,7 @@ var Client = {
|
|
|
25485
25485
|
serverUrl: { type: "string" },
|
|
25486
25486
|
outputMode: { enum: ["single", "split"] },
|
|
25487
25487
|
runtime: { enum: ["inline", "package"] },
|
|
25488
|
+
importExt: { enum: ["js", "ts"] },
|
|
25488
25489
|
enumStyle: { enum: ["union", "const-object"] },
|
|
25489
25490
|
errorMode: { enum: ["throw", "result"] },
|
|
25490
25491
|
dateType: { enum: ["string", "Date"] },
|
|
@@ -25500,6 +25501,7 @@ var ClientPaginationRule = {
|
|
|
25500
25501
|
style: { enum: ["cursor", "offset", "page"] },
|
|
25501
25502
|
cursorParam: { type: "string" },
|
|
25502
25503
|
nextCursor: { type: "string" },
|
|
25504
|
+
hasMore: { type: "string" },
|
|
25503
25505
|
offsetParam: { type: "string" },
|
|
25504
25506
|
limitParam: { type: "string" },
|
|
25505
25507
|
items: { type: "string" }
|
|
@@ -37157,7 +37159,7 @@ function makeBundleVisitor({ version, dereference, rootDocument, resolvedRefMap,
|
|
|
37157
37159
|
return;
|
|
37158
37160
|
}
|
|
37159
37161
|
if (resolved.location.source === rootDocument.source && resolved.location.source === ctx.location.source && ctx.type.name !== "scalar" && !dereference) {
|
|
37160
|
-
if (node.$ref !== resolved.location.pointer) {
|
|
37162
|
+
if (parseRef(node.$ref).uri !== null && node.$ref !== resolved.location.pointer) {
|
|
37161
37163
|
node.$ref = resolved.location.pointer;
|
|
37162
37164
|
}
|
|
37163
37165
|
return;
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
} from "./JPNXFCZJ.js";
|
|
13
13
|
import {
|
|
14
14
|
version
|
|
15
|
-
} from "./
|
|
15
|
+
} from "./U5H3NDWA.js";
|
|
16
16
|
import {
|
|
17
17
|
require_undici
|
|
18
18
|
} from "./QRC5ADSZ.js";
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
blue,
|
|
21
21
|
green,
|
|
22
22
|
logger
|
|
23
|
-
} from "./
|
|
23
|
+
} from "./HD24VMMU.js";
|
|
24
24
|
import {
|
|
25
25
|
__toESM
|
|
26
26
|
} from "./YDPUXTSG.js";
|
|
@@ -12,18 +12,18 @@ import {
|
|
|
12
12
|
normalizeFsPath,
|
|
13
13
|
parseCsv,
|
|
14
14
|
renderReport
|
|
15
|
-
} from "./
|
|
15
|
+
} from "./74VQSZ5T.js";
|
|
16
16
|
import {
|
|
17
17
|
AbortFlowError,
|
|
18
18
|
exitWithError
|
|
19
|
-
} from "./
|
|
19
|
+
} from "./UWZRCAHF.js";
|
|
20
20
|
import {
|
|
21
21
|
require_undici
|
|
22
22
|
} from "./QRC5ADSZ.js";
|
|
23
23
|
import {
|
|
24
24
|
isPlainObject,
|
|
25
25
|
logger
|
|
26
|
-
} from "./
|
|
26
|
+
} from "./HD24VMMU.js";
|
|
27
27
|
import "./HRYOF224.js";
|
|
28
28
|
import {
|
|
29
29
|
__toESM
|
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
isPlainObject,
|
|
12
12
|
isRef,
|
|
13
13
|
logger
|
|
14
|
-
} from "./
|
|
14
|
+
} from "./HD24VMMU.js";
|
|
15
15
|
import "./HRYOF224.js";
|
|
16
16
|
import {
|
|
17
17
|
__commonJS,
|
|
@@ -212213,7 +212213,7 @@ function anchor(outputPath) {
|
|
|
212213
212213
|
var mockGenerator = ({ model, outputPath, emit }) => {
|
|
212214
212214
|
const { dir, stem } = anchor(outputPath);
|
|
212215
212215
|
const content = renderMockModule(model, {
|
|
212216
|
-
sdkModule: `./${stem}.js`,
|
|
212216
|
+
sdkModule: `./${stem}.${emit.importExt ?? "js"}`,
|
|
212217
212217
|
dateType: emit.dateType,
|
|
212218
212218
|
mockData: emit.mockData,
|
|
212219
212219
|
mockSeed: emit.mockSeed
|
|
@@ -212319,13 +212319,15 @@ function operationSignature(op) {
|
|
|
212319
212319
|
const hasQuery = op.queryParams.length > 0;
|
|
212320
212320
|
const hasBody = Boolean(op.requestBody);
|
|
212321
212321
|
const hasHeaders = op.headerParams.length > 0;
|
|
212322
|
+
const hasCookies = op.cookieParams.length > 0;
|
|
212322
212323
|
return {
|
|
212323
212324
|
pathParams,
|
|
212324
212325
|
hasQuery,
|
|
212325
212326
|
hasBody,
|
|
212326
212327
|
hasHeaders,
|
|
212327
|
-
|
|
212328
|
-
|
|
212328
|
+
hasCookies,
|
|
212329
|
+
hasInputs: pathParams.length > 0 || hasQuery || hasBody || hasHeaders || hasCookies,
|
|
212330
|
+
varsRequired: pathParams.length > 0 || op.queryParams.some((p) => p.required) || (op.requestBody?.required ?? false) || op.headerParams.some((p) => p.required) || op.cookieParams.some((p) => p.required),
|
|
212329
212331
|
variablesTypeName: `${pascalCase(op.name)}Variables`
|
|
212330
212332
|
};
|
|
212331
212333
|
}
|
|
@@ -212531,6 +212533,9 @@ function renderOperationAliases(op, responseType, orderedPathParams, pathParamId
|
|
|
212531
212533
|
if (op.headerParams.length > 0 && !schemaNames.has(`${name}Headers`)) {
|
|
212532
212534
|
aliases.push(exportType(`${name}Headers`, paramsTypeLiteral(op.headerParams, dateType)));
|
|
212533
212535
|
}
|
|
212536
|
+
if (op.cookieParams.length > 0 && !schemaNames.has(`${name}Cookies`)) {
|
|
212537
|
+
aliases.push(exportType(`${name}Cookies`, paramsTypeLiteral(op.cookieParams, dateType)));
|
|
212538
|
+
}
|
|
212534
212539
|
if (!schemaNames.has(`${name}Variables`)) {
|
|
212535
212540
|
const variables = renderVariablesAlias(op, name, orderedPathParams, pathParamIdent, ctx, pathKeys);
|
|
212536
212541
|
if (variables)
|
|
@@ -212566,6 +212571,9 @@ function variablesTypeLiteral(op, name, orderedPathParams, pathParamIdent, ctx,
|
|
|
212566
212571
|
if (op.headerParams.length > 0) {
|
|
212567
212572
|
props.push(inputProp("headers", `${name}Headers`, () => paramsTypeLiteral(op.headerParams, dateType), op.headerParams.some((p) => p.required), schemaNames));
|
|
212568
212573
|
}
|
|
212574
|
+
if (op.cookieParams.length > 0) {
|
|
212575
|
+
props.push(inputProp("cookies", `${name}Cookies`, () => paramsTypeLiteral(op.cookieParams, dateType), op.cookieParams.some((p) => p.required), schemaNames));
|
|
212576
|
+
}
|
|
212569
212577
|
return factory6.createTypeLiteralNode(props);
|
|
212570
212578
|
}
|
|
212571
212579
|
function inputProp(key, alias, inlineType, required, schemaNames) {
|
|
@@ -212635,7 +212643,7 @@ function packageIdents(model) {
|
|
|
212635
212643
|
return idents;
|
|
212636
212644
|
}
|
|
212637
212645
|
function descriptorValue(op, schemes, dateType, pagination) {
|
|
212638
|
-
const params = [...op.pathParams, ...op.queryParams, ...op.headerParams].map((p) => ({
|
|
212646
|
+
const params = [...op.pathParams, ...op.queryParams, ...op.headerParams, ...op.cookieParams].map((p) => ({
|
|
212639
212647
|
name: p.name,
|
|
212640
212648
|
in: p.in,
|
|
212641
212649
|
...p.style !== void 0 ? { style: p.style } : {},
|
|
@@ -212748,7 +212756,7 @@ function errorTypeArg(op, ctx) {
|
|
|
212748
212756
|
|
|
212749
212757
|
// ../client-generator/lib/emitters/runtime-sources.js
|
|
212750
212758
|
var RUNTIME_SOURCES = {
|
|
212751
|
-
"types.ts": "/**\n * The public type surface of the client runtime \u2014 `@redocly/client-generator`'s\n * app-facing runtime module. Pure types, no runtime code (excluded from coverage).\n * The generator emits `OPERATIONS` literals typed\n * `satisfies Record<string, OperationDescriptor>` against this module, so an\n * incompatible runtime/generated pair fails the consumer's build (the semver skew guard).\n */\n\n/** How one operation parameter is sent: its location plus OpenAPI query-serialization hints. */\nexport type ParamSpec = {\n name: string;\n in: 'path' | 'query' | 'header';\n style?: 'form' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject';\n explode?: boolean;\n allowReserved?: boolean;\n};\n\n/** One security scheme, denormalized onto the operation (`scheme` names the spec's scheme). */\nexport type SecuritySpec =\n | { scheme: string; kind: 'bearer' | 'basic' }\n | { scheme: string; kind: 'apiKey'; name: string; in: 'header' | 'query' | 'cookie' };\n\n/**\n * How to auto-iterate a paginated operation (drives its `.pages()`/`.items()` members).\n * `nextCursor` and `items` are RFC 6901 JSON pointers into the page (response) value.\n */\nexport type PaginationSpec = {\n style: 'cursor' | 'offset' | 'page';\n /** The query param the iterator advances: the cursor (`cursor`) or number (`offset`/`page`). */\n param: string;\n /** Optional page-size query param (recorded for tooling; never set by the runtime). */\n limitParam?: string;\n /** Cursor style only: pointer to the next cursor in the page. */\n nextCursor?: string;\n /** Pointer to the page's item array. */\n items: string;\n};\n\n/** The frozen data contract between generated code and the runtime: one operation's wire shape. */\nexport type OperationDescriptor = {\n id: string;\n method: string;\n path: string;\n tags?: readonly string[];\n params?: readonly ParamSpec[];\n /** `multipart: true` marks a typed object body serialized to FormData by the runtime. */\n body?: { contentType: string; multipart?: boolean };\n /** Defaults to `'json'` (content-type negotiation on parse). */\n responseKind?: 'json' | 'text' | 'blob' | 'void' | 'sse';\n sseDataKind?: 'json' | 'text';\n /** OR-alternatives, each an AND-set: the runtime applies the first fully-configured one. */\n security?: readonly (readonly SecuritySpec[])[];\n pagination?: PaginationSpec;\n};\n\n/** A query value: scalars, arrays of scalars, or objects (serialized as deepObject brackets). */\nexport type QueryValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Array<string | number | boolean | null | undefined>\n | Record<string, unknown>;\n\n/** A credential: a literal, or a (possibly async) function resolved per request (refresh flows). */\nexport type TokenProvider = string | (() => string | Promise<string>);\n\n/** Per-instance credentials, keyed by the scheme kinds the runtime can inject. */\nexport type AuthCredentials = {\n bearer?: TokenProvider;\n basic?: { username: string; password: string };\n apiKey?: Record<string, TokenProvider>;\n};\n\n/** Backoff shape: 'fixed' = constant delay; 'exponential' = doubling per attempt. */\nexport type RetryStrategy = 'fixed' | 'exponential';\n\n/**\n * The operation's identity, exposed to middleware for targeting (`ctx.operation`).\n * Generated clients instantiate the type parameters with the spec's literal unions\n * (`OperationId`/`OperationPath`/`OperationTag`) so a misspelled operation id in a\n * middleware comparison fails to compile; the string defaults keep every\n * spec-independent consumer (`runtime-contract.ts`, the runtime internals) working\n * with the base shape. `tags` stays mutable (`Tag[]`) so setup-contract types\n * (byte-locked to generated output) remain assignable through middleware callbacks.\n */\nexport type OperationContext<\n Id extends string = string,\n Path extends string = string,\n Tag extends string = string,\n> = { id: Id; path: Path; tags: Tag[] };\n\n/** The mutable request context threaded through the middleware chain. */\nexport type RequestContext<Op extends OperationContext = OperationContext> = {\n url: string;\n method: string;\n headers: Record<string, string>;\n body?: unknown;\n operation: Op;\n};\n\n/** The failed attempt handed to a custom `retryOn`: exactly one of `response`/`error` is set. */\nexport type RetryContext<Op extends OperationContext = OperationContext> = {\n attempt: number;\n request: RequestContext<Op>;\n response?: Response;\n error?: unknown;\n};\n\n/** Opt-in retry policy; a per-call override merges field-by-field over the config policy. */\nexport type RetryConfig<Op extends OperationContext = OperationContext> = {\n retries?: number;\n retryDelay?: number;\n retryStrategy?: RetryStrategy;\n jitter?: boolean;\n retryOn?: (ctx: RetryContext<Op>) => boolean | Promise<boolean>;\n};\n\n/**\n * Structural stand-in for the runtime's ApiError so this module stays import-free\n * (pure types); the real `ApiError` class is assignable to it.\n */\nexport type ApiErrorLike = globalThis.Error & {\n url: string;\n status: number;\n statusText: string;\n body: unknown;\n};\n\n/** One interceptor: any subset of the three hooks. */\nexport type Middleware<Op extends OperationContext = OperationContext> = {\n onRequest?: (ctx: RequestContext<Op>) => void | Promise<void>;\n onResponse?: (\n response: Response,\n ctx: RequestContext<Op>\n ) => Response | void | Promise<Response | void>;\n /** Throw mode only: may map/replace the error. */\n // `globalThis.Error` so a spec schema named `Error` cannot shadow it in inline mode.\n onError?: (\n error: ApiErrorLike,\n ctx: RequestContext<Op>\n ) => globalThis.Error | Promise<globalThis.Error>;\n};\n\n/** Client configuration: transport, defaults, retry policy, middleware, and credentials. */\nexport type ClientConfig<Op extends OperationContext = OperationContext> = {\n serverUrl?: string;\n fetch?: typeof fetch;\n headers?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n retry?: RetryConfig<Op>;\n middleware?: Middleware<Op>[];\n auth?: AuthCredentials;\n /** Fixed at generate time by the generator (`'throw'` when omitted); `configure()` ignores it. */\n errorMode?: 'throw' | 'result';\n onRequest?: Middleware<Op>['onRequest'];\n onResponse?: Middleware<Op>['onResponse'];\n onError?: Middleware<Op>['onError'];\n};\n\n/** Response readers for the per-call `parseAs` override. */\nexport type ParseAs = 'auto' | 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData' | 'stream';\n\n/** Per-call options: standard `RequestInit` plus a retry override and a forced reader. */\nexport type RequestOptions = RequestInit & { retry?: RetryConfig; parseAs?: ParseAs };\n\n/** Per-call options for an SSE stream; reconnect defaults to true. */\nexport type SseOptions = RequestInit & { reconnect?: boolean; reconnectDelay?: number };\n\n/** A single decoded Server-Sent Event with its payload typed from the spec. */\nexport type ServerSentEvent<T> = { event?: string; data: T; id?: string; retry?: number };\n\n/** Result-mode return shape: exactly one of `data`/`error` is set. */\nexport type Result<TData, TError> =\n | { data: TData; error: undefined; response: Response }\n | { data: undefined; error: TError; response: Response };\n\n/**\n * The generated `Ops` type's shape: per-operation args/result, plus `kind: 'sse'` for\n * streams and, for paginated operations, `item` (the page's element type) and \u2014 on\n * result-mode clients only \u2014 `page` (the RAW page type `.pages()` yields, since\n * iteration unwraps the `Result` envelope the one-shot `result` carries).\n */\nexport type OpsShape = Record<\n string,\n { args: object; result: unknown; kind?: 'sse'; item?: unknown; page?: unknown }\n>;\n\n/** The always-present client members (assigned after the operation loop \u2014 they win collisions). */\nexport type ClientCore<Op extends OperationContext = OperationContext> = {\n /** Merge into the config; note `middleware` REPLACES the chain (use `use()` to compose). */\n configure(config: ClientConfig<Op>): void;\n /** Append interceptors (composes with baked/publisher middleware). */\n use(...middleware: Middleware<Op>[]): void;\n auth: {\n bearer(token: TokenProvider): void;\n basic(username: string, password: string): void;\n apiKey(scheme: string, value: TokenProvider): void;\n };\n};\n\n/**\n * The standard TypeScript optionality probe: `{}` has no required members, so\n * `{} extends A` is true exactly when every member of `A` is optional.\n */\n// oxlint-disable-next-line typescript/no-empty-object-type\ntype NoRequiredKeys<A> = {} extends A ? true : false;\n\n/**\n * The page type `.pages()` yields: the RAW page declared by `page` (the generator\n * writes it only on result-mode paginated entries, whose `result` is the envelope),\n * or the method's own `result` (throw mode \u2014 already the raw page).\n */\ntype PageOf<Entry extends OpsShape[string]> = Entry extends { page: unknown }\n ? Entry['page']\n : Entry['result'];\n\n/**\n * The auto-pagination members intersected onto a paginated method \u2014 present exactly when\n * the Ops entry declares `item` (the generator writes it only for paginated operations).\n * Args optionality mirrors the method's own; `unknown` otherwise (identity under `&`).\n * Iteration is error-mode-agnostic: `.pages()`/`.items()` yield raw pages/items, and a\n * failed page aborts iteration by throwing `ApiError`, even on result-mode clients; the\n * `onError` middleware hook (throw-mode-only) is not invoked.\n */\ntype Paginated<Entry extends OpsShape[string]> = 'item' extends keyof Entry\n ? NoRequiredKeys<Entry['args']> extends true\n ? {\n pages(args?: Entry['args'], init?: RequestOptions): AsyncGenerator<PageOf<Entry>>;\n items(args?: Entry['args'], init?: RequestOptions): AsyncGenerator<Entry['item']>;\n }\n : {\n pages(args: Entry['args'], init?: RequestOptions): AsyncGenerator<PageOf<Entry>>;\n items(args: Entry['args'], init?: RequestOptions): AsyncGenerator<Entry['item']>;\n }\n : unknown;\n\n/** The typed instance client: one bound method per operation plus the core members. */\nexport type Client<Ops extends OpsShape, Op extends OperationContext = OperationContext> = {\n [K in keyof Ops]: Ops[K] extends { kind: 'sse' }\n ? NoRequiredKeys<Ops[K]['args']> extends true\n ? (\n args?: Ops[K]['args'],\n init?: SseOptions\n ) => AsyncGenerator<ServerSentEvent<Ops[K]['result']>>\n : (\n args: Ops[K]['args'],\n init?: SseOptions\n ) => AsyncGenerator<ServerSentEvent<Ops[K]['result']>>\n : (NoRequiredKeys<Ops[K]['args']> extends true\n ? (args?: Ops[K]['args'], init?: RequestOptions) => Promise<Ops[K]['result']>\n : (args: Ops[K]['args'], init?: RequestOptions) => Promise<Ops[K]['result']>) &\n Paginated<Ops[K]>;\n} & ClientCore<Op>;\n",
|
|
212759
|
+
"types.ts": "/**\n * The public type surface of the client runtime \u2014 `@redocly/client-generator`'s\n * app-facing runtime module. Pure types, no runtime code (excluded from coverage).\n * The generator emits `OPERATIONS` literals typed\n * `satisfies Record<string, OperationDescriptor>` against this module, so an\n * incompatible runtime/generated pair fails the consumer's build (the semver skew guard).\n */\n\n/** How one operation parameter is sent: its location plus OpenAPI query-serialization hints. */\nexport type ParamSpec = {\n name: string;\n in: 'path' | 'query' | 'header' | 'cookie';\n style?: 'form' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject';\n explode?: boolean;\n allowReserved?: boolean;\n};\n\n/** One security scheme, denormalized onto the operation (`scheme` names the spec's scheme). */\nexport type SecuritySpec =\n | { scheme: string; kind: 'bearer' | 'basic' }\n | { scheme: string; kind: 'apiKey'; name: string; in: 'header' | 'query' | 'cookie' };\n\n/**\n * How to auto-iterate a paginated operation (drives its `.pages()`/`.items()` members).\n * `nextCursor` and `items` are RFC 6901 JSON pointers into the page (response) value.\n */\nexport type PaginationSpec = {\n style: 'cursor' | 'offset' | 'page';\n /** The query param the iterator advances: the cursor (`cursor`) or number (`offset`/`page`). */\n param: string;\n /** Optional page-size query param (recorded for tooling; never set by the runtime). */\n limitParam?: string;\n /** Cursor style only: pointer to the next cursor in the page. */\n nextCursor?: string;\n /** Cursor style only: optional pointer to a boolean \"more pages\" flag \u2014 `false` stops iteration. */\n hasMore?: string;\n /** Pointer to the page's item array. */\n items: string;\n};\n\n/** The frozen data contract between generated code and the runtime: one operation's wire shape. */\nexport type OperationDescriptor = {\n id: string;\n method: string;\n path: string;\n tags?: readonly string[];\n params?: readonly ParamSpec[];\n /** `multipart: true` marks a typed object body serialized to FormData by the runtime. */\n body?: { contentType: string; multipart?: boolean };\n /** Defaults to `'json'` (content-type negotiation on parse). */\n responseKind?: 'json' | 'text' | 'blob' | 'void' | 'sse';\n sseDataKind?: 'json' | 'text';\n /** OR-alternatives, each an AND-set: the runtime applies the first fully-configured one. */\n security?: readonly (readonly SecuritySpec[])[];\n pagination?: PaginationSpec;\n};\n\n/** A query value: scalars, arrays of scalars, or objects (serialized as deepObject brackets). */\nexport type QueryValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Array<string | number | boolean | null | undefined>\n | Record<string, unknown>;\n\n/** A credential: a literal, or a (possibly async) function resolved per request (refresh flows). */\nexport type TokenProvider = string | (() => string | Promise<string>);\n\n/** Per-instance credentials, keyed by the scheme kinds the runtime can inject. */\nexport type AuthCredentials = {\n bearer?: TokenProvider;\n basic?: { username: string; password: string };\n apiKey?: Record<string, TokenProvider>;\n};\n\n/** Backoff shape: 'fixed' = constant delay; 'exponential' = doubling per attempt. */\nexport type RetryStrategy = 'fixed' | 'exponential';\n\n/**\n * The operation's identity, exposed to middleware for targeting (`ctx.operation`).\n * Generated clients instantiate the type parameters with the spec's literal unions\n * (`OperationId`/`OperationPath`/`OperationTag`) so a misspelled operation id in a\n * middleware comparison fails to compile; the string defaults keep every\n * spec-independent consumer (`runtime-contract.ts`, the runtime internals) working\n * with the base shape. `tags` stays mutable (`Tag[]`) so setup-contract types\n * (byte-locked to generated output) remain assignable through middleware callbacks.\n */\nexport type OperationContext<\n Id extends string = string,\n Path extends string = string,\n Tag extends string = string,\n> = { id: Id; path: Path; tags: Tag[] };\n\n/** The mutable request context threaded through the middleware chain. */\nexport type RequestContext<Op extends OperationContext = OperationContext> = {\n url: string;\n method: string;\n headers: Record<string, string>;\n body?: unknown;\n operation: Op;\n};\n\n/** The failed attempt handed to a custom `retryOn`: exactly one of `response`/`error` is set. */\nexport type RetryContext<Op extends OperationContext = OperationContext> = {\n attempt: number;\n request: RequestContext<Op>;\n response?: Response;\n error?: unknown;\n};\n\n/** Opt-in retry policy; a per-call override merges field-by-field over the config policy. */\nexport type RetryConfig<Op extends OperationContext = OperationContext> = {\n retries?: number;\n retryDelay?: number;\n retryStrategy?: RetryStrategy;\n jitter?: boolean;\n retryOn?: (ctx: RetryContext<Op>) => boolean | Promise<boolean>;\n};\n\n/**\n * Structural stand-in for the runtime's ApiError so this module stays import-free\n * (pure types); the real `ApiError` class is assignable to it.\n */\nexport type ApiErrorLike = globalThis.Error & {\n url: string;\n status: number;\n statusText: string;\n body: unknown;\n};\n\n/** One interceptor: any subset of the three hooks. */\nexport type Middleware<Op extends OperationContext = OperationContext> = {\n onRequest?: (ctx: RequestContext<Op>) => void | Promise<void>;\n onResponse?: (\n response: Response,\n ctx: RequestContext<Op>\n ) => Response | void | Promise<Response | void>;\n /** Throw mode only: may map/replace the error. */\n // `globalThis.Error` so a spec schema named `Error` cannot shadow it in inline mode.\n onError?: (\n error: ApiErrorLike,\n ctx: RequestContext<Op>\n ) => globalThis.Error | Promise<globalThis.Error>;\n};\n\n/** Client configuration: transport, defaults, retry policy, middleware, and credentials. */\nexport type ClientConfig<Op extends OperationContext = OperationContext> = {\n serverUrl?: string;\n fetch?: typeof fetch;\n headers?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n retry?: RetryConfig<Op>;\n middleware?: Middleware<Op>[];\n auth?: AuthCredentials;\n /** Fixed at generate time by the generator (`'throw'` when omitted); `configure()` ignores it. */\n errorMode?: 'throw' | 'result';\n onRequest?: Middleware<Op>['onRequest'];\n onResponse?: Middleware<Op>['onResponse'];\n onError?: Middleware<Op>['onError'];\n};\n\n/** Response readers for the per-call `parseAs` override. */\nexport type ParseAs = 'auto' | 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData' | 'stream';\n\n/** Per-call options: standard `RequestInit` plus a retry override and a forced reader. */\nexport type RequestOptions = RequestInit & { retry?: RetryConfig; parseAs?: ParseAs };\n\n/** Per-call options for an SSE stream; reconnect defaults to true. */\nexport type SseOptions = RequestInit & { reconnect?: boolean; reconnectDelay?: number };\n\n/** A single decoded Server-Sent Event with its payload typed from the spec. */\nexport type ServerSentEvent<T> = { event?: string; data: T; id?: string; retry?: number };\n\n/** Result-mode return shape: exactly one of `data`/`error` is set. */\nexport type Result<TData, TError> =\n | { data: TData; error: undefined; response: Response }\n | { data: undefined; error: TError; response: Response };\n\n/**\n * The generated `Ops` type's shape: per-operation args/result, plus `kind: 'sse'` for\n * streams and, for paginated operations, `item` (the page's element type) and \u2014 on\n * result-mode clients only \u2014 `page` (the RAW page type `.pages()` yields, since\n * iteration unwraps the `Result` envelope the one-shot `result` carries).\n */\nexport type OpsShape = Record<\n string,\n { args: object; result: unknown; kind?: 'sse'; item?: unknown; page?: unknown }\n>;\n\n/** The always-present client members (assigned after the operation loop \u2014 they win collisions). */\nexport type ClientCore<Op extends OperationContext = OperationContext> = {\n /** Merge into the config; note `middleware` REPLACES the chain (use `use()` to compose). */\n configure(config: ClientConfig<Op>): void;\n /** Append interceptors (composes with baked/publisher middleware). */\n use(...middleware: Middleware<Op>[]): void;\n auth: {\n bearer(token: TokenProvider): void;\n basic(username: string, password: string): void;\n apiKey(scheme: string, value: TokenProvider): void;\n };\n};\n\n/**\n * The standard TypeScript optionality probe: `{}` has no required members, so\n * `{} extends A` is true exactly when every member of `A` is optional.\n */\n// oxlint-disable-next-line typescript/no-empty-object-type\ntype NoRequiredKeys<A> = {} extends A ? true : false;\n\n/**\n * The page type `.pages()` yields: the RAW page declared by `page` (the generator\n * writes it only on result-mode paginated entries, whose `result` is the envelope),\n * or the method's own `result` (throw mode \u2014 already the raw page).\n */\ntype PageOf<Entry extends OpsShape[string]> = Entry extends { page: unknown }\n ? Entry['page']\n : Entry['result'];\n\n/**\n * The auto-pagination members intersected onto a paginated method \u2014 present exactly when\n * the Ops entry declares `item` (the generator writes it only for paginated operations).\n * Args optionality mirrors the method's own; `unknown` otherwise (identity under `&`).\n * Iteration is error-mode-agnostic: `.pages()`/`.items()` yield raw pages/items, and a\n * failed page aborts iteration by throwing `ApiError`, even on result-mode clients; the\n * `onError` middleware hook (throw-mode-only) is not invoked.\n */\ntype Paginated<Entry extends OpsShape[string]> = 'item' extends keyof Entry\n ? NoRequiredKeys<Entry['args']> extends true\n ? {\n pages(args?: Entry['args'], init?: RequestOptions): AsyncGenerator<PageOf<Entry>>;\n items(args?: Entry['args'], init?: RequestOptions): AsyncGenerator<Entry['item']>;\n }\n : {\n pages(args: Entry['args'], init?: RequestOptions): AsyncGenerator<PageOf<Entry>>;\n items(args: Entry['args'], init?: RequestOptions): AsyncGenerator<Entry['item']>;\n }\n : unknown;\n\n/** The typed instance client: one bound method per operation plus the core members. */\nexport type Client<Ops extends OpsShape, Op extends OperationContext = OperationContext> = {\n [K in keyof Ops]: Ops[K] extends { kind: 'sse' }\n ? NoRequiredKeys<Ops[K]['args']> extends true\n ? (\n args?: Ops[K]['args'],\n init?: SseOptions\n ) => AsyncGenerator<ServerSentEvent<Ops[K]['result']>>\n : (\n args: Ops[K]['args'],\n init?: SseOptions\n ) => AsyncGenerator<ServerSentEvent<Ops[K]['result']>>\n : (NoRequiredKeys<Ops[K]['args']> extends true\n ? (args?: Ops[K]['args'], init?: RequestOptions) => Promise<Ops[K]['result']>\n : (args: Ops[K]['args'], init?: RequestOptions) => Promise<Ops[K]['result']>) &\n Paginated<Ops[K]>;\n} & ClientCore<Op>;\n",
|
|
212752
212760
|
"errors.ts": "/** The error thrown (throw mode) for a non-2xx response, carrying the decoded error body. */\nexport class ApiError extends Error {\n public readonly url: string;\n public readonly status: number;\n public readonly statusText: string;\n public readonly body: unknown;\n constructor(url: string, status: number, statusText: string, body: unknown) {\n super(`Request failed with status ${status}`);\n this.name = 'ApiError';\n this.url = url;\n this.status = status;\n this.statusText = statusText;\n this.body = body;\n }\n}\n\n/** The error to throw for an aborted request: the caller's abort reason when it is an Error. */\n// `globalThis.Error` (not bare `Error`) so a spec schema named `Error` cannot shadow it\n// when this module is embedded alongside generated types (inline mode).\nexport function abortError(signal: AbortSignal): globalThis.Error {\n const reason = (signal as { reason?: unknown }).reason;\n if (reason instanceof Error) return reason;\n return new DOMException('The operation was aborted.', 'AbortError');\n}\n",
|
|
212753
212761
|
"url.ts": "import type { ParamSpec, QueryValue } from './types.js';\n\n/**\n * The RESOLVED OpenAPI serialization spec for one query parameter \u2014 callers apply the\n * OpenAPI defaults (`style: 'form'`, `explode: true`) before building one.\n */\nexport type QueryStyle = {\n style: NonNullable<ParamSpec['style']>;\n explode: boolean;\n allowReserved?: boolean;\n};\n\n/**\n * Encode everything except the RFC-3986 reserved set, for `allowReserved: true` params \u2014\n * `filter=a/b` survives instead of `filter=a%2Fb`.\n */\nexport function encodeReserved(value: string): string {\n return encodeURIComponent(value).replace(\n /%(3A|2F|3F|23|5B|5D|40|21|24|26|27|28|29|2A|2B|2C|3B|3D)/g,\n (match) => decodeURIComponent(match)\n );\n}\n\n/** Substitute `{name}` template segments with encoded values; a missing value is a caller bug. */\nexport function substitutePath(template: string, values: Record<string, unknown>): string {\n return template.replace(/\\{([^{}]+)\\}/g, (_match, name: string) => {\n const value = values[name];\n if (value === undefined) throw new Error(`Missing path parameter \"${name}\"`);\n return encodeURIComponent(String(value));\n });\n}\n\n/**\n * Build the request URL: `serverUrl` (trailing slash trimmed) + path + serialized query.\n * Query parameters honor their OpenAPI `style`/`explode`/`allowReserved` (from `styles`);\n * without a spec, arrays repeat the key (`form`+`explode`), objects serialize as\n * `deepObject` brackets, and `null`/`undefined` entries are skipped.\n */\nexport function buildUrl(\n serverUrl: string,\n path: string,\n query?: Record<string, QueryValue>,\n styles?: Record<string, QueryStyle>\n): string {\n // Trim trailing slashes with a scan, not `/\\/+$/` \u2014 an anchored `+` regex is\n // quadratic on adversarial many-slash input (the server URL is caller data).\n let end = serverUrl.length;\n while (end > 0 && serverUrl.charCodeAt(end - 1) === 47 /* '/' */) end--;\n const url = serverUrl.slice(0, end) + path;\n if (!query) return url;\n const params = new URLSearchParams();\n const raw: string[] = [];\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n const spec = styles?.[key];\n if (!spec) {\n if (Array.isArray(value)) {\n for (const v of value) {\n if (v !== undefined && v !== null) params.append(key, String(v));\n }\n } else if (Object(value) === value) {\n // Object-valued query params use `deepObject` style: key[subKey]=subValue.\n for (const [subKey, subValue] of Object.entries(value)) {\n if (subValue !== undefined && subValue !== null) {\n params.append(`${key}[${subKey}]`, String(subValue));\n }\n }\n } else {\n params.append(key, String(value));\n }\n continue;\n }\n if (Array.isArray(value)) {\n const items = value.filter((v) => v !== undefined && v !== null).map(String);\n if (spec.style === 'form' && spec.explode) {\n for (const v of items) {\n if (spec.allowReserved) raw.push(`${key}=${encodeReserved(v)}`);\n else params.append(key, v);\n }\n } else {\n // Delimited styles put the LITERAL delimiter on the wire; only the\n // values are encoded. `%20` (not `+`) is the literal space delimiter.\n const delim =\n spec.style === 'pipeDelimited' ? '|' : spec.style === 'spaceDelimited' ? '%20' : ',';\n const enc = spec.allowReserved ? encodeReserved : encodeURIComponent;\n raw.push(`${encodeURIComponent(key)}=${items.map(enc).join(delim)}`);\n }\n } else if (Object(value) === value) {\n // `deepObject` (and any object spec, for now): key[subKey]=subValue.\n for (const [subKey, subValue] of Object.entries(value)) {\n if (subValue !== undefined && subValue !== null) {\n if (spec.allowReserved) raw.push(`${key}[${subKey}]=${encodeReserved(String(subValue))}`);\n else params.append(`${key}[${subKey}]`, String(subValue));\n }\n }\n } else if (spec.allowReserved) {\n raw.push(`${key}=${encodeReserved(String(value))}`);\n } else {\n params.append(key, String(value));\n }\n }\n const qs = [params.toString(), ...raw].filter(Boolean).join('&');\n return qs ? `${url}?${qs}` : url;\n}\n",
|
|
212754
212762
|
"parse.ts": "import type { ParseAs } from './types.js';\n\n/**\n * Read the response body per `kind`. `'auto'` negotiates from the content type\n * (JSON, then `text/*`, then Blob); `'void'` and `204` responses read nothing.\n */\nexport async function parse(response: Response, kind: ParseAs | 'void'): Promise<unknown> {\n if (kind === 'void' || response.status === 204) return undefined;\n if (kind === 'stream') return response.body;\n if (kind === 'blob') return response.blob();\n if (kind === 'arrayBuffer') return response.arrayBuffer();\n if (kind === 'formData') return response.formData();\n if (kind === 'text') return response.text();\n if (kind === 'json') return response.json();\n // 'auto' \u2014 negotiate from the response's content type (case-insensitively:\n // `Text/Plain` and `application/JSON` are valid per RFC 9110).\n const contentType = (response.headers.get('content-type') ?? '').toLowerCase();\n if (contentType.includes('json')) return response.json();\n if (contentType.startsWith('text/')) return response.text();\n return response.blob();\n}\n\n/** Best-effort decode of a non-2xx body (JSON when declared, else text; undefined on failure). */\nexport async function readError(response: Response): Promise<unknown> {\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.toLowerCase().includes('json')) {\n return response.json().catch(() => undefined);\n }\n return response.text().catch(() => undefined);\n}\n",
|
|
@@ -212758,8 +212766,8 @@ var RUNTIME_SOURCES = {
|
|
|
212758
212766
|
"setup.ts": "import type { ClientConfig, Middleware } from './types.js';\n\n/**\n * Merge a publisher's baked setup (`defineClientSetup({...})`) with the app's config:\n * app config fields win per-field over baked defaults, while middleware composes \u2014\n * baked middleware runs first, then the app's.\n */\nexport function mergeSetup(\n setup: { config?: ClientConfig; middleware?: Middleware[] } | undefined,\n config: ClientConfig = {}\n): ClientConfig {\n return {\n ...setup?.config,\n ...config,\n middleware: [...(setup?.middleware ?? []), ...(config.middleware ?? [])],\n };\n}\n",
|
|
212759
212767
|
"send.ts": "import { abortError } from './errors.js';\nimport { defaultRetryOn, retryDelay, sleep } from './retry.js';\nimport type {\n ClientConfig,\n Middleware,\n OperationContext,\n RequestContext,\n RequestOptions,\n RetryConfig,\n} from './types.js';\n\n/**\n * Optional behaviors the send core can use but never statically imports \u2014 wired by\n * `createClient` (the same seam the future inline-mode assembler relies on).\n */\nexport type SendCapabilities = {\n /** Serialize a typed multipart body (a plain object) to FormData. */\n serializeMultipart?: (body: Record<string, unknown>) => FormData;\n};\n\n/**\n * Normalize a caller's `HeadersInit` (plain record, `Headers` instance, or entry pairs)\n * to a plain record \u2014 spreading a `Headers` or an array contributes no entries.\n */\nexport function toHeaderRecord(headers: HeadersInit | undefined): Record<string, string> {\n if (headers === undefined) return {};\n if (headers instanceof Headers) {\n const record: Record<string, string> = {};\n headers.forEach((value, key) => {\n record[key] = value;\n });\n return record;\n }\n if (Array.isArray(headers)) return Object.fromEntries(headers);\n return headers;\n}\n\n/**\n * The effective middleware chain for a request: the single `onRequest`/`onResponse`/\n * `onError` config hooks as one implicit first middleware, then `config.middleware`.\n */\nexport function middlewareChain(config: ClientConfig): Middleware[] {\n const single =\n config.onRequest || config.onResponse || config.onError\n ? [{ onRequest: config.onRequest, onResponse: config.onResponse, onError: config.onError }]\n : [];\n return [...single, ...(config.middleware ?? [])];\n}\n\n/**\n * The fetch core shared by every operation: default + config + per-call headers, the\n * `onRequest` chain (BEFORE body serialization, so mutations are sent), body\n * serialization (JSON, or FormData via the multipart capability), the retry loop\n * (idempotent-only defaults, `Retry-After`, abandoned-body drain), and the reverse\n * `onResponse` onion. Returns the final response plus the request context.\n */\nexport async function send(\n config: ClientConfig,\n op: OperationContext,\n url: string,\n init: RequestOptions,\n body: unknown | undefined,\n multipart: boolean,\n caps: SendCapabilities\n): Promise<{ response: Response; context: RequestContext }> {\n const { retry: callRetry, ...fetchInit } = init;\n const retry: RetryConfig = { ...config.retry, ...callRetry };\n const extra = typeof config.headers === 'function' ? await config.headers() : config.headers;\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...extra,\n ...toHeaderRecord(fetchInit.headers),\n };\n const context: RequestContext = {\n url,\n method: fetchInit.method ?? 'GET',\n headers,\n body,\n operation: op,\n };\n const middleware = middlewareChain(config);\n for (const mw of middleware) if (mw.onRequest) await mw.onRequest(context);\n // Serialize AFTER onRequest so body mutations (case conversion, enveloping, signing) take effect.\n let payload: BodyInit | undefined;\n if (context.body !== undefined) {\n const value = context.body;\n const isBinary =\n value instanceof Blob ||\n value instanceof ArrayBuffer ||\n ArrayBuffer.isView(value as ArrayBufferView);\n const isFormData = typeof FormData !== 'undefined' && value instanceof FormData;\n const isURLSearchParams = value instanceof URLSearchParams;\n if (isFormData || isURLSearchParams || isBinary || typeof value === 'string') {\n payload = value as BodyInit;\n } else if (multipart) {\n if (!caps.serializeMultipart) {\n throw new Error('Multipart capability not wired: cannot serialize the request body');\n }\n payload = caps.serializeMultipart(value as Record<string, unknown>);\n } else {\n payload = JSON.stringify(value);\n if (!('Content-Type' in context.headers) && !('content-type' in context.headers)) {\n context.headers['Content-Type'] = 'application/json';\n }\n }\n }\n const doFetch = config.fetch ?? fetch;\n const maxAttempts = 1 + (retry.retries ?? 0);\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const signal = fetchInit.signal ?? undefined;\n\n let attempt = 0;\n while (true) {\n attempt++;\n if (signal?.aborted) throw abortError(signal);\n let response: Response;\n try {\n response = await doFetch(context.url, {\n ...fetchInit,\n method: context.method,\n headers: context.headers,\n body: payload,\n });\n } catch (error) {\n if (\n attempt < maxAttempts &&\n !signal?.aborted &&\n (await retryOn({ attempt, request: context, error }))\n ) {\n await sleep(retryDelay(retry, attempt, null), signal);\n continue;\n }\n throw error;\n }\n // Reverse order: the last-registered middleware wraps closest to the network (onion).\n for (let i = middleware.length - 1; i >= 0; i--) {\n const onResponse = middleware[i].onResponse;\n if (onResponse) {\n const replaced = await onResponse(response, context);\n if (replaced && replaced !== response) {\n // Cancel the abandoned original's body \u2014 like the retry path, an unread body\n // keeps its connection checked out under Node/undici.\n await response.body?.cancel().catch(() => undefined);\n response = replaced;\n }\n }\n }\n if (\n !response.ok &&\n attempt < maxAttempts &&\n !signal?.aborted &&\n (await retryOn({ attempt, request: context, response }))\n ) {\n const retryAfter = response.headers.get('retry-after');\n // Drain the abandoned response body before the next attempt: an unread body\n // keeps the connection checked out (and can stall the pool) under Node/undici\n // and other strict HTTP clients. Ignore errors (e.g. a middleware already read it).\n await response.body?.cancel().catch(() => undefined);\n await sleep(retryDelay(retry, attempt, retryAfter), signal);\n continue;\n }\n return { response, context };\n }\n}\n",
|
|
212760
212768
|
"sse.ts": "import { ApiError } from './errors.js';\nimport { readError } from './parse.js';\nimport { sleep } from './retry.js';\nimport { send, toHeaderRecord } from './send.js';\nimport type { ClientConfig, OperationContext, ServerSentEvent, SseOptions } from './types.js';\n\n/**\n * A frame delimiter: two consecutive line terminators (each CR, LF, or CRLF, per the SSE\n * spec \u2014 so mixed endings like `\\n\\r\\n` are valid boundaries, not just matching pairs).\n */\nconst FRAME_DELIMITER = /(?:\\r\\n|\\r|\\n){2}/;\n\n/**\n * A terminally malformed event stream \u2014 unparseable JSON `data` or an unbounded frame.\n * A stable bad payload, not a dropped connection, so the stream never reconnects on it.\n */\nexport class SseParseError extends Error {}\n\n/**\n * Consume a `text/event-stream` operation as typed events (capability module \u2014 wired\n * into `createClient`). Auto-reconnects on dropped connections, resuming from the last\n * seen event id via `Last-Event-ID` (backoff: the server's `retry:` value, then\n * `reconnectDelay`, then 1s \u2014 exponential with jitter, capped at 30s). A clean stream\n * end flushes a trailing frame and finishes; `break`/abort end the iterator cleanly.\n */\nexport async function* sse<T>(\n config: ClientConfig,\n op: OperationContext,\n prepare: () => Promise<{ url: string; init: SseOptions }>,\n dataKind: 'json' | 'text' = 'text'\n): AsyncGenerator<ServerSentEvent<T>> {\n let lastEventId: string | undefined;\n let serverRetry: number | undefined;\n let failures = 0;\n while (true) {\n // Re-prepare each attempt so a refresh-style TokenProvider yields a fresh credential\n // on reconnect (the auth is baked into `url` query + `init.headers`). `reconnect`,\n // `reconnectDelay`, and `signal` come from the caller's original options unchanged.\n const { url, init } = await prepare();\n const { reconnect = true, reconnectDelay, ...rest } = init;\n const signal = rest.signal ?? undefined;\n if (signal?.aborted) return;\n const headers: Record<string, string> = {\n Accept: 'text/event-stream',\n ...toHeaderRecord(rest.headers),\n };\n const sendHeaders =\n lastEventId === undefined ? headers : { ...headers, 'Last-Event-ID': lastEventId };\n try {\n const { response } = await send(\n config,\n op,\n url,\n { ...rest, method: rest.method ?? 'GET', headers: sendHeaders },\n undefined,\n false,\n {}\n );\n if (!response.ok) {\n const errorBody = await readError(response);\n throw new ApiError(url, response.status, response.statusText, errorBody);\n }\n failures = 0;\n const body = response.body;\n if (!body) return;\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n while (true) {\n const { done, value } = await reader.read();\n buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n let match: RegExpMatchArray | null;\n while ((match = buffer.match(FRAME_DELIMITER)) !== null) {\n const index = match.index!;\n const raw = buffer.slice(0, index);\n buffer = buffer.slice(index + match[0].length);\n const event = parseSseFrame(raw, dataKind);\n if (event) {\n if (event.id !== undefined) lastEventId = event.id;\n if (event.retry !== undefined) serverRetry = event.retry;\n yield event as ServerSentEvent<T>;\n }\n }\n if (done) {\n // Stream closed cleanly. Flush a final event that arrived without a trailing\n // delimiter, then finish \u2014 a clean end is not a dropped connection, so do not reconnect.\n const event = buffer.length > 0 ? parseSseFrame(buffer, dataKind) : undefined;\n if (event) {\n if (event.id !== undefined) lastEventId = event.id;\n if (event.retry !== undefined) serverRetry = event.retry;\n yield event as ServerSentEvent<T>;\n }\n return;\n }\n // Bound memory: a server that never sends a frame delimiter would otherwise\n // grow `buffer` without limit. 1 MiB is far above any real SSE frame.\n if (buffer.length > 1048576) {\n throw new SseParseError('SSE frame exceeded 1048576 characters without a delimiter');\n }\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n } catch (error) {\n if (signal?.aborted) return;\n // A non-OK HTTP response (4xx/5xx) or an unparseable JSON payload is a definitive\n // error, not a transient drop \u2014 surface it instead of reconnecting in a loop (a\n // stable bad payload would otherwise reconnect forever).\n if (error instanceof ApiError || error instanceof SseParseError) throw error;\n // A transport failure (connect/DNS/reset) when opening the request, or a mid-stream\n // read error, is a dropped connection: fall through to backoff/reconnect when enabled.\n if (!reconnect) throw error;\n }\n // Only the swallowed-drop path reaches here: reconnect is on and the signal not aborted.\n failures++;\n const base = serverRetry ?? reconnectDelay ?? 1000;\n const delay = Math.min(base * Math.pow(2, failures - 1), 30_000);\n try {\n await sleep(Math.random() * delay, signal);\n } catch {\n return; // sleep rejects only on abort \u2014 end the iterator cleanly\n }\n }\n}\n\n/** Parse one raw SSE frame (its lines) into an event; returns undefined for comment-only frames. */\nexport function parseSseFrame(\n raw: string,\n dataKind: 'json' | 'text'\n): ServerSentEvent<unknown> | undefined {\n let event: string | undefined;\n const dataLines: string[] = [];\n let id: string | undefined;\n let retry: number | undefined;\n let sawField = false;\n for (const line of raw.split(/\\r\\n|\\n|\\r/)) {\n if (line === '' || line.startsWith(':')) continue;\n const colon = line.indexOf(':');\n const field = colon === -1 ? line : line.slice(0, colon);\n let val = colon === -1 ? '' : line.slice(colon + 1);\n if (val.startsWith(' ')) val = val.slice(1);\n sawField = true;\n if (field === 'event') event = val;\n else if (field === 'data') dataLines.push(val);\n else if (field === 'id') id = val;\n else if (field === 'retry') {\n const n = Number(val);\n if (!Number.isNaN(n)) retry = n;\n }\n }\n if (!sawField) return undefined;\n const dataText = dataLines.join('\\n');\n let data: unknown = dataText;\n if (dataKind === 'json' && dataText !== '') {\n try {\n data = JSON.parse(dataText);\n } catch (error) {\n throw new SseParseError(\n `Failed to parse SSE event data as JSON: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n return { event, data, id, retry };\n}\n",
|
|
212761
|
-
"create-client.ts": "import { ApiError } from './errors.js';\nimport { parse, readError } from './parse.js';\nimport { middlewareChain, send, toHeaderRecord, type SendCapabilities } from './send.js';\nimport type {\n ApiErrorLike,\n Client,\n ClientConfig,\n Middleware,\n OperationContext,\n OperationDescriptor,\n OpsShape,\n PaginationSpec,\n ParseAs,\n QueryValue,\n RequestOptions,\n SecuritySpec,\n ServerSentEvent,\n SseOptions,\n TokenProvider,\n} from './types.js';\nimport { buildUrl, substitutePath, type QueryStyle } from './url.js';\n\n/**\n * The optional behaviors `createClientCore` can dispatch to but never statically\n * imports. The package's public `createClient` wires the full set; the future\n * inline-mode assembler wires only the capabilities a spec needs.\n */\nexport type Capabilities = SendCapabilities & {\n resolveAuth?: (\n security: readonly (readonly SecuritySpec[])[],\n config: ClientConfig\n ) => Promise<{ headers: Record<string, string>; query: Record<string, string> }>;\n sse?: (\n config: ClientConfig,\n op: OperationContext,\n // Re-preparing per (re)connect (not a frozen url/init) lets a refresh-style\n // TokenProvider issue a fresh credential after a dropped stream reconnects.\n prepare: () => Promise<{ url: string; init: SseOptions }>,\n dataKind: 'json' | 'text'\n ) => AsyncGenerator<ServerSentEvent<unknown>>;\n paginate?: {\n pages: (\n call: (args?: OperationArgs, init?: RequestOptions) => Promise<unknown>,\n spec: PaginationSpec,\n args?: OperationArgs,\n init?: RequestOptions\n ) => AsyncGenerator<unknown>;\n items: (\n call: (args?: OperationArgs, init?: RequestOptions) => Promise<unknown>,\n spec: PaginationSpec,\n args?: OperationArgs,\n init?: RequestOptions\n ) => AsyncGenerator<unknown>;\n };\n};\n\n/** The grouped args wire shape: path params by name plus the `params`/`body`/`headers` slots. */\nexport type OperationArgs = {\n params?: Record<string, QueryValue>;\n body?: unknown;\n headers?: Record<string, unknown>;\n} & Record<string, unknown>;\n\n/** The response reader implied by the descriptor (before any per-call `parseAs` override). */\nfunction kindFor(op: OperationDescriptor): ParseAs | 'void' {\n if (op.responseKind === 'void' || op.responseKind === 'blob' || op.responseKind === 'text') {\n return op.responseKind;\n }\n return 'auto';\n}\n\n/** Route the grouped args by the descriptor: path values, query object, body, extra headers. */\nfunction splitArgs(op: OperationDescriptor, args: OperationArgs) {\n const path: Record<string, unknown> = {};\n for (const param of op.params ?? []) {\n if (param.in === 'path') path[param.name] = args[param.name];\n }\n return { path, query: args.params, body: args.body, headers: args.headers };\n}\n\n/**\n * The query-serialization hints for the descriptor's query params. A spec is built only\n * when the param deviates from the OpenAPI defaults (`form` + `explode: true`, encoded),\n * and always fully resolved \u2014 so `explode: false` or `allowReserved` alone (no `style`)\n * are honored, and an omitted `explode` keeps the exploded default.\n */\nfunction queryStyles(op: OperationDescriptor): Record<string, QueryStyle> | undefined {\n let styles: Record<string, QueryStyle> | undefined;\n for (const param of op.params ?? []) {\n if (param.in !== 'query') continue;\n const deviates =\n (param.style !== undefined && param.style !== 'form') ||\n param.explode === false ||\n param.allowReserved === true;\n if (!deviates) continue;\n styles ??= {};\n styles[param.name] = {\n style: param.style ?? 'form',\n explode: param.explode ?? true,\n allowReserved: param.allowReserved,\n };\n }\n return styles;\n}\n\n/** Stringify caller-supplied extra headers, skipping empty entries. */\nfunction stringHeaders(headers: Record<string, unknown> | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers ?? {})) {\n if (value !== undefined && value !== null) out[key] = String(value);\n }\n return out;\n}\n\n/** Build the request pieces an attempt needs: the final URL and the merged per-call init. */\nasync function prepareRequest(\n config: ClientConfig,\n op: OperationDescriptor,\n args: OperationArgs,\n init: RequestOptions | SseOptions,\n caps: Capabilities\n): Promise<{ url: string; init: RequestOptions; body: unknown }> {\n const { path, query, body, headers } = splitArgs(op, args);\n const authed =\n op.security?.length && caps.resolveAuth\n ? await caps.resolveAuth(op.security, config)\n : { headers: {}, query: {} };\n const fullQuery: Record<string, QueryValue> = { ...query, ...authed.query };\n const url = buildUrl(\n config.serverUrl ?? '',\n substitutePath(op.path, path),\n Object.keys(fullQuery).length > 0 ? fullQuery : undefined,\n queryStyles(op)\n );\n const mergedInit: RequestOptions = {\n ...init,\n method: op.method.toUpperCase(),\n // Precedence, lowest \u2192 highest (later spreads win): injected auth \u2192 explicit\n // header params \u2192 caller `init.headers` \u2014 the caller always overrides both.\n headers: {\n ...authed.headers,\n ...stringHeaders(headers),\n ...toHeaderRecord(init.headers),\n },\n };\n return { url, init: mergedInit, body };\n}\n\n/** One non-SSE call: send, then branch on the configured error mode. */\nasync function execute(\n config: ClientConfig,\n op: OperationDescriptor,\n args: OperationArgs,\n init: RequestOptions,\n caps: Capabilities\n): Promise<unknown> {\n const prepared = await prepareRequest(config, op, args, init, caps);\n const opCtx: OperationContext = { id: op.id, path: op.path, tags: [...(op.tags ?? [])] };\n const { parseAs, ...sendInit } = prepared.init;\n const { response, context } = await send(\n config,\n opCtx,\n prepared.url,\n sendInit,\n prepared.body,\n op.body?.multipart === true,\n caps\n );\n const readKind = parseAs ?? kindFor(op);\n if (config.errorMode === 'result') {\n if (!response.ok) {\n return { data: undefined, error: await readError(response), response };\n }\n return { data: await parse(response, readKind), error: undefined, response };\n }\n if (!response.ok) {\n let error: globalThis.Error = new ApiError(\n context.url,\n response.status,\n response.statusText,\n await readError(response)\n );\n // Thread the error through each middleware's onError in turn (each may replace it).\n for (const mw of middlewareChain(config)) {\n if (mw.onError) error = await mw.onError(error as ApiErrorLike, context);\n }\n throw error;\n }\n return parse(response, readKind);\n}\n\n/** The paginate capability, or a descriptive throw when a paginated op is iterated unwired. */\nfunction paginateCapability(caps: Capabilities, op: OperationDescriptor) {\n if (!caps.paginate) {\n throw new Error(`Pagination capability not wired: cannot iterate operation \"${op.id}\"`);\n }\n return caps.paginate;\n}\n\n/**\n * The per-page call the iterators drive: the method itself in throw mode; in result\n * mode a wrapper that unwraps the `{ data, error, response }` envelope \u2014 the page\n * pointers are data-rooted \u2014 rethrowing a failed page as `ApiError` (iteration is\n * error-mode-agnostic; the throw-mode-only `onError` middleware hook is not invoked).\n */\nfunction pageCall(\n method: (args?: OperationArgs, init?: RequestOptions) => Promise<unknown>,\n config: ClientConfig\n) {\n if (config.errorMode !== 'result') return method;\n return async (args?: OperationArgs, init?: RequestOptions) => {\n const envelope = (await method(args, init)) as {\n data: unknown;\n error: unknown;\n response: Response;\n };\n // Failure is `!response.ok` \u2014 NOT `data === undefined`: a successful bodyless page\n // (204/void) also parses to undefined data, and a failed page's `error` can be\n // undefined too (unreadable body). The pointers then miss on the undefined data\n // and iteration stops cleanly, which is the correct semantics for an empty page.\n if (!envelope.response.ok) {\n const { response } = envelope;\n throw new ApiError(response.url, response.status, response.statusText, envelope.error);\n }\n return envelope.data;\n };\n}\n\n/**\n * Build a typed instance client over operation descriptors: one real bound method per\n * operation (attached by a construction-time loop \u2014 no Proxy), plus the core members\n * (`configure`/`use`/`auth`), which are assigned AFTER the loop so they win any name\n * collision with an operation. All behavior dispatches through the capability seam.\n */\nexport function createClientCore<\n Ops extends OpsShape,\n Id extends string = string,\n Path extends string = string,\n Tag extends string = string,\n>(\n operations: Record<string, OperationDescriptor>,\n initial: ClientConfig<OperationContext<Id, Path, Tag>> = {},\n caps: Capabilities = {}\n): Client<Ops, OperationContext<Id, Path, Tag>> {\n // The literal-union narrowing is a compile-time DX contract only; internally the\n // runtime works with the base (string-typed) context. One cast at this boundary \u2014\n // `ClientConfig<Narrow>` is not assignable to `ClientConfig` (middleware ctx\n // params are contravariant).\n const given = initial as ClientConfig;\n // Private mutable config; the middleware array is copied so `use()` never mutates the caller's.\n const config: ClientConfig = { ...given, middleware: [...(given.middleware ?? [])] };\n const client = {} as Record<string, unknown>;\n\n for (const [name, op] of Object.entries(operations)) {\n if (op.responseKind === 'sse') {\n client[name] = (args: OperationArgs = {}, init: SseOptions = {}) => {\n if (!caps.sse) {\n throw new Error(`SSE capability not wired: cannot stream operation \"${op.id}\"`);\n }\n const stream = caps.sse;\n return (async function* () {\n const opCtx: OperationContext = { id: op.id, path: op.path, tags: [...(op.tags ?? [])] };\n // A thunk the stream re-runs on every (re)connect, so auth (which `prepareRequest`\n // resolves) is refreshed per attempt rather than frozen at the first connect.\n const prepare = async () => {\n const prepared = await prepareRequest(config, op, args, init, caps);\n return { url: prepared.url, init: prepared.init as SseOptions };\n };\n yield* stream(config, opCtx, prepare, op.sseDataKind ?? 'text');\n })();\n };\n } else {\n const method = (args: OperationArgs = {}, init: RequestOptions = {}) =>\n execute(config, op, args, init, caps);\n const spec = op.pagination;\n // Paginated ops keep their one-shot call and gain `.pages`/`.items`, dispatching\n // through the capability seam (like SSE: absent capability throws descriptively).\n // Iteration is error-mode-agnostic: the iterators' pointers are data-rooted, so on\n // a result-mode client (`errorMode` is fixed at construction \u2014 `configure()`\n // ignores it) each page's envelope is unwrapped before it reaches the capability.\n // A failed page aborts iteration by throwing ApiError, even on result-mode\n // clients; the `onError` middleware hook (throw-mode-only) is not invoked.\n client[name] = spec\n ? Object.assign(method, {\n pages: (args?: OperationArgs, init?: RequestOptions) =>\n paginateCapability(caps, op).pages(pageCall(method, config), spec, args, init),\n items: (args?: OperationArgs, init?: RequestOptions) =>\n paginateCapability(caps, op).items(pageCall(method, config), spec, args, init),\n })\n : method;\n }\n }\n\n // Core members are assigned AFTER the operation loop \u2014 they win over colliding op names.\n client.configure = (next: ClientConfig): void => {\n // `errorMode` is fixed at generate time (it shapes the static types); flipping it at\n // runtime would silently desync return shapes from `Client<Ops>`, so it is ignored.\n const { errorMode: _fixed, auth, ...rest } = next;\n Object.assign(config, rest);\n // `auth` merges into existing credentials (like the `auth.*` setters) rather than\n // replacing wholesale \u2014 so `configure({ auth: { bearer } })` keeps a previously set\n // basic/apiKey. `apiKey` merges per scheme.\n if (auth) {\n config.auth = {\n ...config.auth,\n ...auth,\n ...(auth.apiKey ? { apiKey: { ...config.auth?.apiKey, ...auth.apiKey } } : {}),\n };\n }\n };\n client.use = (...middleware: Middleware[]): void => {\n // Reassign (don't push) so a caller-provided `middleware` array isn't mutated.\n config.middleware = [...(config.middleware ?? []), ...middleware];\n };\n client.auth = {\n bearer(token: TokenProvider): void {\n config.auth = { ...config.auth, bearer: token };\n },\n basic(username: string, password: string): void {\n config.auth = { ...config.auth, basic: { username, password } };\n },\n apiKey(scheme: string, value: TokenProvider): void {\n config.auth = { ...config.auth, apiKey: { ...config.auth?.apiKey, [scheme]: value } };\n },\n };\n\n return client as Client<Ops, OperationContext<Id, Path, Tag>>;\n}\n",
|
|
212762
|
-
"paginate.ts": "import type { OperationArgs } from './create-client.js';\nimport type { PaginationSpec, QueryValue, RequestOptions } from './types.js';\n\n/**\n * Auto-pagination (capability module \u2014 wired into `createClient`, dispatched by the\n * method's `.pages()`/`.items()`): walk an operation's pages by advancing the descriptor's\n * `param` query parameter, per its `style`. The caller's args are never mutated \u2014 each\n * request gets a fresh `params` clone \u2014 and `init` is forwarded to every call.\n *\n * Iteration is error-mode-agnostic: `call` always resolves to the RAW page (on a\n * result-mode client the attachment unwraps the envelope first), so a failed page\n * aborts iteration by throwing `ApiError`, even on result-mode clients; the `onError`\n * middleware hook (throw-mode-only) is not invoked.\n */\n\n/**\n * Resolve an RFC 6901 JSON pointer (`~1` \u2192 `/`, `~0` \u2192 `~`) against a value.\n * The empty pointer is the whole document; anything else must start with `/`.\n * Returns `undefined` on any miss (bad token, absent key, non-object step) \u2014 never throws.\n */\nexport function resolvePointer(value: unknown, pointer: string): unknown {\n if (pointer === '') return value;\n if (!pointer.startsWith('/')) return undefined;\n let current = value;\n for (const token of pointer.slice(1).split('/')) {\n const key = token.replaceAll('~1', '/').replaceAll('~0', '~');\n if (Array.isArray(current)) {\n if (!/^(0|[1-9]\\d*)$/.test(key)) return undefined;\n current = current[Number(key)];\n } else if (Object(current) === current && key in (current as object)) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/**\n * Iterate an operation's full page results. Every page is yielded before the stop\n * condition is evaluated, so the last page always arrives. Cursor style resumes from a\n * caller-provided `params[spec.param]`, stops when `
|
|
212769
|
+
"create-client.ts": "import { ApiError } from './errors.js';\nimport { parse, readError } from './parse.js';\nimport { middlewareChain, send, toHeaderRecord, type SendCapabilities } from './send.js';\nimport type {\n ApiErrorLike,\n Client,\n ClientConfig,\n Middleware,\n OperationContext,\n OperationDescriptor,\n OpsShape,\n PaginationSpec,\n ParseAs,\n QueryValue,\n RequestOptions,\n SecuritySpec,\n ServerSentEvent,\n SseOptions,\n TokenProvider,\n} from './types.js';\nimport { buildUrl, substitutePath, type QueryStyle } from './url.js';\n\n/**\n * The optional behaviors `createClientCore` can dispatch to but never statically\n * imports. The package's public `createClient` wires the full set; the future\n * inline-mode assembler wires only the capabilities a spec needs.\n */\nexport type Capabilities = SendCapabilities & {\n resolveAuth?: (\n security: readonly (readonly SecuritySpec[])[],\n config: ClientConfig\n ) => Promise<{ headers: Record<string, string>; query: Record<string, string> }>;\n sse?: (\n config: ClientConfig,\n op: OperationContext,\n // Re-preparing per (re)connect (not a frozen url/init) lets a refresh-style\n // TokenProvider issue a fresh credential after a dropped stream reconnects.\n prepare: () => Promise<{ url: string; init: SseOptions }>,\n dataKind: 'json' | 'text'\n ) => AsyncGenerator<ServerSentEvent<unknown>>;\n paginate?: {\n pages: (\n call: (args?: OperationArgs, init?: RequestOptions) => Promise<unknown>,\n spec: PaginationSpec,\n args?: OperationArgs,\n init?: RequestOptions\n ) => AsyncGenerator<unknown>;\n items: (\n call: (args?: OperationArgs, init?: RequestOptions) => Promise<unknown>,\n spec: PaginationSpec,\n args?: OperationArgs,\n init?: RequestOptions\n ) => AsyncGenerator<unknown>;\n };\n};\n\n/** The grouped args wire shape: path params by name plus the `params`/`body`/`headers`/`cookies` slots. */\nexport type OperationArgs = {\n params?: Record<string, QueryValue>;\n body?: unknown;\n headers?: Record<string, unknown>;\n cookies?: Record<string, unknown>;\n} & Record<string, unknown>;\n\n/** The response reader implied by the descriptor (before any per-call `parseAs` override). */\nfunction kindFor(op: OperationDescriptor): ParseAs | 'void' {\n if (op.responseKind === 'void' || op.responseKind === 'blob' || op.responseKind === 'text') {\n return op.responseKind;\n }\n return 'auto';\n}\n\n/** Route the grouped args by the descriptor: path values, query object, body, extra headers, cookies. */\nfunction splitArgs(op: OperationDescriptor, args: OperationArgs) {\n const path: Record<string, unknown> = {};\n for (const param of op.params ?? []) {\n if (param.in === 'path') path[param.name] = args[param.name];\n }\n return {\n path,\n query: args.params,\n body: args.body,\n headers: args.headers,\n cookies: args.cookies,\n };\n}\n\n/**\n * The query-serialization hints for the descriptor's query params. A spec is built only\n * when the param deviates from the OpenAPI defaults (`form` + `explode: true`, encoded),\n * and always fully resolved \u2014 so `explode: false` or `allowReserved` alone (no `style`)\n * are honored, and an omitted `explode` keeps the exploded default.\n */\nfunction queryStyles(op: OperationDescriptor): Record<string, QueryStyle> | undefined {\n let styles: Record<string, QueryStyle> | undefined;\n for (const param of op.params ?? []) {\n if (param.in !== 'query') continue;\n const deviates =\n (param.style !== undefined && param.style !== 'form') ||\n param.explode === false ||\n param.allowReserved === true;\n if (!deviates) continue;\n styles ??= {};\n styles[param.name] = {\n style: param.style ?? 'form',\n explode: param.explode ?? true,\n allowReserved: param.allowReserved,\n };\n }\n return styles;\n}\n\n/** Stringify caller-supplied extra headers, skipping empty entries. */\nfunction stringHeaders(headers: Record<string, unknown> | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers ?? {})) {\n if (value !== undefined && value !== null) out[key] = String(value);\n }\n return out;\n}\n\n/** Build the request pieces an attempt needs: the final URL and the merged per-call init. */\nasync function prepareRequest(\n config: ClientConfig,\n op: OperationDescriptor,\n args: OperationArgs,\n init: RequestOptions | SseOptions,\n caps: Capabilities\n): Promise<{ url: string; init: RequestOptions; body: unknown }> {\n const { path, query, body, headers, cookies } = splitArgs(op, args);\n const authed: { headers: Record<string, string>; query: Record<string, string> } =\n op.security?.length && caps.resolveAuth\n ? await caps.resolveAuth(op.security, config)\n : { headers: {}, query: {} };\n // Cookie params join the auth-injected cookies in one `Cookie` header (values\n // percent-encoded, like auth cookies). Server-side only \u2014 browsers own the header.\n const cookiePairs = Object.entries(cookies ?? {})\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([cookieName, value]) => `${cookieName}=${encodeURIComponent(String(value))}`);\n if (cookiePairs.length > 0) {\n authed.headers.Cookie = [authed.headers.Cookie, ...cookiePairs].filter(Boolean).join('; ');\n }\n const fullQuery: Record<string, QueryValue> = { ...query, ...authed.query };\n const url = buildUrl(\n config.serverUrl ?? '',\n substitutePath(op.path, path),\n Object.keys(fullQuery).length > 0 ? fullQuery : undefined,\n queryStyles(op)\n );\n const mergedInit: RequestOptions = {\n ...init,\n method: op.method.toUpperCase(),\n // Precedence, lowest \u2192 highest (later spreads win): injected auth \u2192 explicit\n // header params \u2192 caller `init.headers` \u2014 the caller always overrides both.\n headers: {\n ...authed.headers,\n ...stringHeaders(headers),\n ...toHeaderRecord(init.headers),\n },\n };\n return { url, init: mergedInit, body };\n}\n\n/** One non-SSE call: send, then branch on the configured error mode. */\nasync function execute(\n config: ClientConfig,\n op: OperationDescriptor,\n args: OperationArgs,\n init: RequestOptions,\n caps: Capabilities\n): Promise<unknown> {\n const prepared = await prepareRequest(config, op, args, init, caps);\n const opCtx: OperationContext = { id: op.id, path: op.path, tags: [...(op.tags ?? [])] };\n const { parseAs, ...sendInit } = prepared.init;\n const { response, context } = await send(\n config,\n opCtx,\n prepared.url,\n sendInit,\n prepared.body,\n op.body?.multipart === true,\n caps\n );\n const readKind = parseAs ?? kindFor(op);\n if (config.errorMode === 'result') {\n if (!response.ok) {\n return { data: undefined, error: await readError(response), response };\n }\n return { data: await parse(response, readKind), error: undefined, response };\n }\n if (!response.ok) {\n let error: globalThis.Error = new ApiError(\n context.url,\n response.status,\n response.statusText,\n await readError(response)\n );\n // Thread the error through each middleware's onError in turn (each may replace it).\n for (const mw of middlewareChain(config)) {\n if (mw.onError) error = await mw.onError(error as ApiErrorLike, context);\n }\n throw error;\n }\n return parse(response, readKind);\n}\n\n/** The paginate capability, or a descriptive throw when a paginated op is iterated unwired. */\nfunction paginateCapability(caps: Capabilities, op: OperationDescriptor) {\n if (!caps.paginate) {\n throw new Error(`Pagination capability not wired: cannot iterate operation \"${op.id}\"`);\n }\n return caps.paginate;\n}\n\n/**\n * The per-page call the iterators drive: the method itself in throw mode; in result\n * mode a wrapper that unwraps the `{ data, error, response }` envelope \u2014 the page\n * pointers are data-rooted \u2014 rethrowing a failed page as `ApiError` (iteration is\n * error-mode-agnostic; the throw-mode-only `onError` middleware hook is not invoked).\n */\nfunction pageCall(\n method: (args?: OperationArgs, init?: RequestOptions) => Promise<unknown>,\n config: ClientConfig\n) {\n if (config.errorMode !== 'result') return method;\n return async (args?: OperationArgs, init?: RequestOptions) => {\n const envelope = (await method(args, init)) as {\n data: unknown;\n error: unknown;\n response: Response;\n };\n // Failure is `!response.ok` \u2014 NOT `data === undefined`: a successful bodyless page\n // (204/void) also parses to undefined data, and a failed page's `error` can be\n // undefined too (unreadable body). The pointers then miss on the undefined data\n // and iteration stops cleanly, which is the correct semantics for an empty page.\n if (!envelope.response.ok) {\n const { response } = envelope;\n throw new ApiError(response.url, response.status, response.statusText, envelope.error);\n }\n return envelope.data;\n };\n}\n\n/**\n * Build a typed instance client over operation descriptors: one real bound method per\n * operation (attached by a construction-time loop \u2014 no Proxy), plus the core members\n * (`configure`/`use`/`auth`), which are assigned AFTER the loop so they win any name\n * collision with an operation. All behavior dispatches through the capability seam.\n */\nexport function createClientCore<\n Ops extends OpsShape,\n Id extends string = string,\n Path extends string = string,\n Tag extends string = string,\n>(\n operations: Record<string, OperationDescriptor>,\n initial: ClientConfig<OperationContext<Id, Path, Tag>> = {},\n caps: Capabilities = {}\n): Client<Ops, OperationContext<Id, Path, Tag>> {\n // The literal-union narrowing is a compile-time DX contract only; internally the\n // runtime works with the base (string-typed) context. One cast at this boundary \u2014\n // `ClientConfig<Narrow>` is not assignable to `ClientConfig` (middleware ctx\n // params are contravariant).\n const given = initial as ClientConfig;\n // Private mutable config; the middleware array is copied so `use()` never mutates the caller's.\n const config: ClientConfig = { ...given, middleware: [...(given.middleware ?? [])] };\n const client = {} as Record<string, unknown>;\n\n for (const [name, op] of Object.entries(operations)) {\n if (op.responseKind === 'sse') {\n const method = (args: OperationArgs = {}, init: SseOptions = {}) => {\n if (!caps.sse) {\n throw new Error(`SSE capability not wired: cannot stream operation \"${op.id}\"`);\n }\n const stream = caps.sse;\n return (async function* () {\n const opCtx: OperationContext = { id: op.id, path: op.path, tags: [...(op.tags ?? [])] };\n // A thunk the stream re-runs on every (re)connect, so auth (which `prepareRequest`\n // resolves) is refreshed per attempt rather than frozen at the first connect.\n const prepare = async () => {\n const prepared = await prepareRequest(config, op, args, init, caps);\n return { url: prepared.url, init: prepared.init as SseOptions };\n };\n yield* stream(config, opCtx, prepare, op.sseDataKind ?? 'text');\n })();\n };\n // Consumers key off the function reference (cache keys, `OPERATIONS[fn.name]`), so\n // each closure carries its operationId instead of an inferred binding name.\n Object.defineProperty(method, 'name', { value: name });\n client[name] = method;\n } else {\n const method = (args: OperationArgs = {}, init: RequestOptions = {}) =>\n execute(config, op, args, init, caps);\n Object.defineProperty(method, 'name', { value: name });\n const spec = op.pagination;\n // Paginated ops keep their one-shot call and gain `.pages`/`.items`, dispatching\n // through the capability seam (like SSE: absent capability throws descriptively).\n // Iteration is error-mode-agnostic: the iterators' pointers are data-rooted, so on\n // a result-mode client (`errorMode` is fixed at construction \u2014 `configure()`\n // ignores it) each page's envelope is unwrapped before it reaches the capability.\n // A failed page aborts iteration by throwing ApiError, even on result-mode\n // clients; the `onError` middleware hook (throw-mode-only) is not invoked.\n client[name] = spec\n ? Object.assign(method, {\n pages: (args?: OperationArgs, init?: RequestOptions) =>\n paginateCapability(caps, op).pages(pageCall(method, config), spec, args, init),\n items: (args?: OperationArgs, init?: RequestOptions) =>\n paginateCapability(caps, op).items(pageCall(method, config), spec, args, init),\n })\n : method;\n }\n }\n\n // Core members are assigned AFTER the operation loop \u2014 they win over colliding op names.\n client.configure = (next: ClientConfig): void => {\n // `errorMode` is fixed at generate time (it shapes the static types); flipping it at\n // runtime would silently desync return shapes from `Client<Ops>`, so it is ignored.\n const { errorMode: _fixed, auth, ...rest } = next;\n Object.assign(config, rest);\n // `auth` merges into existing credentials (like the `auth.*` setters) rather than\n // replacing wholesale \u2014 so `configure({ auth: { bearer } })` keeps a previously set\n // basic/apiKey. `apiKey` merges per scheme.\n if (auth) {\n config.auth = {\n ...config.auth,\n ...auth,\n ...(auth.apiKey ? { apiKey: { ...config.auth?.apiKey, ...auth.apiKey } } : {}),\n };\n }\n };\n client.use = (...middleware: Middleware[]): void => {\n // Reassign (don't push) so a caller-provided `middleware` array isn't mutated.\n config.middleware = [...(config.middleware ?? []), ...middleware];\n };\n client.auth = {\n bearer(token: TokenProvider): void {\n config.auth = { ...config.auth, bearer: token };\n },\n basic(username: string, password: string): void {\n config.auth = { ...config.auth, basic: { username, password } };\n },\n apiKey(scheme: string, value: TokenProvider): void {\n config.auth = { ...config.auth, apiKey: { ...config.auth?.apiKey, [scheme]: value } };\n },\n };\n\n return client as Client<Ops, OperationContext<Id, Path, Tag>>;\n}\n",
|
|
212770
|
+
"paginate.ts": "import type { OperationArgs } from './create-client.js';\nimport type { PaginationSpec, QueryValue, RequestOptions } from './types.js';\n\n/**\n * Auto-pagination (capability module \u2014 wired into `createClient`, dispatched by the\n * method's `.pages()`/`.items()`): walk an operation's pages by advancing the descriptor's\n * `param` query parameter, per its `style`. The caller's args are never mutated \u2014 each\n * request gets a fresh `params` clone \u2014 and `init` is forwarded to every call.\n *\n * Iteration is error-mode-agnostic: `call` always resolves to the RAW page (on a\n * result-mode client the attachment unwraps the envelope first), so a failed page\n * aborts iteration by throwing `ApiError`, even on result-mode clients; the `onError`\n * middleware hook (throw-mode-only) is not invoked.\n */\n\n/**\n * Resolve an RFC 6901 JSON pointer (`~1` \u2192 `/`, `~0` \u2192 `~`) against a value.\n * The empty pointer is the whole document; anything else must start with `/`.\n * Returns `undefined` on any miss (bad token, absent key, non-object step) \u2014 never throws.\n */\nexport function resolvePointer(value: unknown, pointer: string): unknown {\n if (pointer === '') return value;\n if (!pointer.startsWith('/')) return undefined;\n let current = value;\n for (const token of pointer.slice(1).split('/')) {\n const key = token.replaceAll('~1', '/').replaceAll('~0', '~');\n if (Array.isArray(current)) {\n if (!/^(0|[1-9]\\d*)$/.test(key)) return undefined;\n current = current[Number(key)];\n } else if (Object(current) === current && key in (current as object)) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/**\n * Iterate an operation's full page results. Every page is yielded before the stop\n * condition is evaluated, so the last page always arrives. Cursor style resumes from a\n * caller-provided `params[spec.param]`, stops when the optional `hasMore` pointer\n * resolves to `false` or when `nextCursor` resolves to `undefined`/`null`/`''`, and\n * throws if the next cursor is not a string or number, or\n * if the same cursor comes back twice in a row (infinite-loop guards). Offset/page\n * styles advance by item count / by one and stop when\n * the `items` pointer misses or the array is empty.\n */\nexport async function* pages<TPage>(\n call: (args?: OperationArgs, init?: RequestOptions) => Promise<TPage>,\n spec: PaginationSpec,\n args: OperationArgs = {},\n init?: RequestOptions\n): AsyncGenerator<TPage> {\n if (spec.style === 'cursor') {\n let cursor: unknown = args.params?.[spec.param];\n while (true) {\n const params = { ...args.params };\n if (cursor !== undefined) params[spec.param] = cursor as QueryValue;\n const page = await call({ ...args, params }, init);\n yield page;\n // Connection-style APIs keep a non-null cursor on the last page and signal the\n // end via a boolean flag \u2014 honor it before the cursor check to skip the\n // follow-up empty request. Strictly `false`: a missing pointer falls through.\n if (spec.hasMore !== undefined && resolvePointer(page, spec.hasMore) === false) return;\n const next = resolvePointer(page, spec.nextCursor!);\n if (next === undefined || next === null || next === '') return;\n if (typeof next !== 'string' && typeof next !== 'number') {\n // A fresh non-scalar cursor never compares equal, so without this guard a lying\n // server would slip past the did-not-advance check into an infinite loop.\n throw new Error(`Pagination cursor at ${spec.nextCursor} is not a string or number`);\n }\n if (next === cursor) {\n throw new Error('Pagination did not advance: operation returned the same cursor twice');\n }\n cursor = next;\n }\n } else {\n // Coerce the starting position to a number: a caller may pass `params[spec.param]` as a\n // string (common from URL/form input), and `+=` on a string would concatenate.\n const start = args.params?.[spec.param];\n const fallback = spec.style === 'page' ? 1 : 0;\n let position = start === undefined || Number.isNaN(Number(start)) ? fallback : Number(start);\n while (true) {\n const page = await call(\n { ...args, params: { ...args.params, [spec.param]: position } },\n init\n );\n yield page;\n const pageItems = resolvePointer(page, spec.items);\n if (!Array.isArray(pageItems) || pageItems.length === 0) return;\n position += spec.style === 'page' ? 1 : pageItems.length;\n }\n }\n}\n\n/**\n * Iterate the operation's individual items: each page's `items` pointer, flattened.\n * A cursor-style page whose pointer misses yields nothing but pagination continues;\n * for offset/page styles a miss has already stopped `pages`.\n */\nexport async function* items<TItem>(\n call: (args?: OperationArgs, init?: RequestOptions) => Promise<unknown>,\n spec: PaginationSpec,\n args?: OperationArgs,\n init?: RequestOptions\n): AsyncGenerator<TItem> {\n for await (const page of pages(call, spec, args, init)) {\n const pageItems = resolvePointer(page, spec.items);\n if (Array.isArray(pageItems)) yield* pageItems as TItem[];\n }\n}\n"
|
|
212763
212771
|
};
|
|
212764
212772
|
|
|
212765
212773
|
// ../client-generator/lib/emitters/inline-runtime.js
|
|
@@ -212848,6 +212856,8 @@ function renderArgList(op, orderedPathParams, pathParamIdent, ctx) {
|
|
|
212848
212856
|
}
|
|
212849
212857
|
if (op.headerParams.length > 0)
|
|
212850
212858
|
args.push(renderParamsObjectArg("headers", op.headerParams, dateType));
|
|
212859
|
+
if (op.cookieParams.length > 0)
|
|
212860
|
+
args.push(renderParamsObjectArg("cookies", op.cookieParams, dateType));
|
|
212851
212861
|
args.push(simpleParam("init", factory9.createTypeReferenceNode(isSseOp(op) ? "SseOptions" : "RequestOptions"), true));
|
|
212852
212862
|
return args;
|
|
212853
212863
|
}
|
|
@@ -212925,6 +212935,15 @@ function applyRule(op, model, rule, source, explicit) {
|
|
|
212925
212935
|
if (!isStringish(cursorTarget, model)) {
|
|
212926
212936
|
return misfit(`the "nextCursor" pointer "${valid.nextCursor}" must point at a string (got ${cursorTarget.kind})`);
|
|
212927
212937
|
}
|
|
212938
|
+
if (valid.hasMore !== void 0) {
|
|
212939
|
+
const moreTarget = resolveSchemaPointer(page.schema, valid.hasMore, model);
|
|
212940
|
+
if (moreTarget === void 0) {
|
|
212941
|
+
return misfit(`the "hasMore" pointer "${valid.hasMore}" does not resolve in the success response schema`);
|
|
212942
|
+
}
|
|
212943
|
+
if (moreTarget.kind !== "scalar" || moreTarget.scalar !== "boolean") {
|
|
212944
|
+
return misfit(`the "hasMore" pointer "${valid.hasMore}" must point at a boolean (got ${moreTarget.kind})`);
|
|
212945
|
+
}
|
|
212946
|
+
}
|
|
212928
212947
|
}
|
|
212929
212948
|
return {
|
|
212930
212949
|
spec: {
|
|
@@ -212932,6 +212951,7 @@ function applyRule(op, model, rule, source, explicit) {
|
|
|
212932
212951
|
param: param2,
|
|
212933
212952
|
...valid.limitParam !== void 0 ? { limitParam: valid.limitParam } : {},
|
|
212934
212953
|
...valid.style === "cursor" ? { nextCursor: valid.nextCursor } : {},
|
|
212954
|
+
...valid.style === "cursor" && valid.hasMore !== void 0 ? { hasMore: valid.hasMore } : {},
|
|
212935
212955
|
items: valid.items
|
|
212936
212956
|
},
|
|
212937
212957
|
itemSchema: itemsTarget.items
|
|
@@ -212940,7 +212960,7 @@ function applyRule(op, model, rule, source, explicit) {
|
|
|
212940
212960
|
function ruleShapeProblem(rule) {
|
|
212941
212961
|
if (!isPlainObject(rule))
|
|
212942
212962
|
return "the rule must be an object";
|
|
212943
|
-
const { style, cursorParam, nextCursor, offsetParam, limitParam, items: items2 } = rule;
|
|
212963
|
+
const { style, cursorParam, nextCursor, hasMore, offsetParam, limitParam, items: items2 } = rule;
|
|
212944
212964
|
if (style !== "cursor" && style !== "offset" && style !== "page") {
|
|
212945
212965
|
return `"style" must be one of "cursor" | "offset" | "page" (got ${JSON.stringify(style)})`;
|
|
212946
212966
|
}
|
|
@@ -212954,6 +212974,9 @@ function ruleShapeProblem(rule) {
|
|
|
212954
212974
|
if (typeof nextCursor !== "string" || !nextCursor.startsWith("/")) {
|
|
212955
212975
|
return 'cursor style requires a "nextCursor" JSON pointer starting with "/"';
|
|
212956
212976
|
}
|
|
212977
|
+
if (hasMore !== void 0 && (typeof hasMore !== "string" || !hasMore.startsWith("/"))) {
|
|
212978
|
+
return '"hasMore" must be a JSON pointer starting with "/"';
|
|
212979
|
+
}
|
|
212957
212980
|
} else if (typeof offsetParam !== "string" || offsetParam === "") {
|
|
212958
212981
|
return `${style} style requires an "offsetParam" query parameter name`;
|
|
212959
212982
|
}
|
|
@@ -213239,7 +213262,7 @@ function emitClient(model, options, splitStem) {
|
|
|
213239
213262
|
entry: banner([
|
|
213240
213263
|
HEADER,
|
|
213241
213264
|
renderTitleComment(model),
|
|
213242
|
-
hasSchemas ? schemaLinks(body + "\n" + sugar, ctx.schemaNames, `./${splitStem}.schemas.js`) : "",
|
|
213265
|
+
hasSchemas ? schemaLinks(body + "\n" + sugar, ctx.schemaNames, `./${splitStem}.schemas.${options.importExt ?? "js"}`) : "",
|
|
213243
213266
|
...embed ? [] : [runtimeSection],
|
|
213244
213267
|
body,
|
|
213245
213268
|
...embed ? [runtimeSection] : [],
|
|
@@ -213346,6 +213369,9 @@ function flatSugarStatement(op, ident, ctx) {
|
|
|
213346
213369
|
if (op.headerParams.length > 0) {
|
|
213347
213370
|
props.push(factory11.createShorthandPropertyAssignment("headers"));
|
|
213348
213371
|
}
|
|
213372
|
+
if (op.cookieParams.length > 0) {
|
|
213373
|
+
props.push(factory11.createShorthandPropertyAssignment("cookies"));
|
|
213374
|
+
}
|
|
213349
213375
|
const call2 = factory11.createCallExpression(factory11.createPropertyAccessExpression(factory11.createIdentifier("client"), ident), void 0, [factory11.createObjectLiteralExpression(props, false), factory11.createIdentifier("init")]);
|
|
213350
213376
|
const fn = arrow(params, call2);
|
|
213351
213377
|
if (!ctx.pagination?.has(op.name))
|
|
@@ -213441,6 +213467,8 @@ function sdkCall(op, argsStyle, source, withInit) {
|
|
|
213441
213467
|
args.push(factory12.createPropertyAccessExpression(sourceIdent, "body"));
|
|
213442
213468
|
if (sig.hasHeaders)
|
|
213443
213469
|
args.push(factory12.createPropertyAccessExpression(sourceIdent, "headers"));
|
|
213470
|
+
if (sig.hasCookies)
|
|
213471
|
+
args.push(factory12.createPropertyAccessExpression(sourceIdent, "cookies"));
|
|
213444
213472
|
}
|
|
213445
213473
|
if (withInit)
|
|
213446
213474
|
args.push(factory12.createIdentifier("init"));
|
|
@@ -213525,7 +213553,7 @@ var swrGenerator = ({ model, outputPath, emit }) => {
|
|
|
213525
213553
|
const { dir, stem } = anchor(outputPath);
|
|
213526
213554
|
const content = renderSwrModule(model, {
|
|
213527
213555
|
argsStyle: emit.argsStyle ?? "flat",
|
|
213528
|
-
sdkModule: `./${stem}.js`
|
|
213556
|
+
sdkModule: `./${stem}.${emit.importExt ?? "js"}`
|
|
213529
213557
|
});
|
|
213530
213558
|
if (content === "")
|
|
213531
213559
|
return [];
|
|
@@ -213592,7 +213620,7 @@ var tanstackQueryGenerator = ({ model, outputPath, emit }) => {
|
|
|
213592
213620
|
const { dir, stem } = anchor(outputPath);
|
|
213593
213621
|
const content = renderTanstackModule(model, {
|
|
213594
213622
|
argsStyle: emit.argsStyle ?? "flat",
|
|
213595
|
-
sdkModule: `./${stem}.js`,
|
|
213623
|
+
sdkModule: `./${stem}.${emit.importExt ?? "js"}`,
|
|
213596
213624
|
framework: emit.queryFramework ?? "react"
|
|
213597
213625
|
});
|
|
213598
213626
|
if (content === "")
|
|
@@ -213820,9 +213848,11 @@ function renderTransformersModule(model, opts) {
|
|
|
213820
213848
|
}
|
|
213821
213849
|
|
|
213822
213850
|
// ../client-generator/lib/generators/transformers.js
|
|
213823
|
-
var transformersGenerator = ({ model, outputPath }) => {
|
|
213851
|
+
var transformersGenerator = ({ model, outputPath, emit }) => {
|
|
213824
213852
|
const { dir, stem } = anchor(outputPath);
|
|
213825
|
-
const content = renderTransformersModule(model, {
|
|
213853
|
+
const content = renderTransformersModule(model, {
|
|
213854
|
+
sdkModule: `./${stem}.${emit.importExt ?? "js"}`
|
|
213855
|
+
});
|
|
213826
213856
|
if (content === "")
|
|
213827
213857
|
return [];
|
|
213828
213858
|
return [{ path: join5(dir, `${stem}.transformers.ts`), content: `${HEADER}
|
|
@@ -214327,6 +214357,8 @@ function rewriteOperationRefs(op, fixRef) {
|
|
|
214327
214357
|
rewriteRefs(p.schema, fixRef);
|
|
214328
214358
|
for (const p of op.headerParams)
|
|
214329
214359
|
rewriteRefs(p.schema, fixRef);
|
|
214360
|
+
for (const p of op.cookieParams)
|
|
214361
|
+
rewriteRefs(p.schema, fixRef);
|
|
214330
214362
|
if (op.requestBody)
|
|
214331
214363
|
rewriteRefs(op.requestBody.schema, fixRef);
|
|
214332
214364
|
for (const r of [...op.successResponses, ...op.errorResponses]) {
|
|
@@ -214629,10 +214661,6 @@ function buildOperation(method2, path, operation, name, pathLevelParams, doc, in
|
|
|
214629
214661
|
const queryParams = allParams.filter((p) => p.in === "query");
|
|
214630
214662
|
const headerParams = allParams.filter((p) => p.in === "header");
|
|
214631
214663
|
const cookieParams = allParams.filter((p) => p.in === "cookie");
|
|
214632
|
-
if (cookieParams.length > 0) {
|
|
214633
|
-
logger.warn(`generate-client: skipped cookie parameter(s) ${cookieParams.map((p) => `"${p.name}"`).join(", ")} on operation "${name}" \u2014 cookie parameters are not supported.
|
|
214634
|
-
`);
|
|
214635
|
-
}
|
|
214636
214664
|
const requestBody = operation.requestBody ? buildRequestBody(deref2(doc, operation.requestBody), `${method2} ${path}`, doc) : void 0;
|
|
214637
214665
|
const successResponses = buildSuccessResponses(operation, path, doc);
|
|
214638
214666
|
const errorResponses = buildErrorResponses(operation, path, doc);
|
|
@@ -214647,6 +214675,7 @@ function buildOperation(method2, path, operation, name, pathLevelParams, doc, in
|
|
|
214647
214675
|
pathParams,
|
|
214648
214676
|
queryParams,
|
|
214649
214677
|
headerParams,
|
|
214678
|
+
cookieParams,
|
|
214650
214679
|
requestBody,
|
|
214651
214680
|
successResponses,
|
|
214652
214681
|
errorResponses,
|
|
@@ -215437,7 +215466,13 @@ function splitArgs(op, args) {
|
|
|
215437
215466
|
if (param2.in === "path")
|
|
215438
215467
|
path[param2.name] = args[param2.name];
|
|
215439
215468
|
}
|
|
215440
|
-
return {
|
|
215469
|
+
return {
|
|
215470
|
+
path,
|
|
215471
|
+
query: args.params,
|
|
215472
|
+
body: args.body,
|
|
215473
|
+
headers: args.headers,
|
|
215474
|
+
cookies: args.cookies
|
|
215475
|
+
};
|
|
215441
215476
|
}
|
|
215442
215477
|
function queryStyles(op) {
|
|
215443
215478
|
let styles;
|
|
@@ -215465,8 +215500,12 @@ function stringHeaders(headers) {
|
|
|
215465
215500
|
return out;
|
|
215466
215501
|
}
|
|
215467
215502
|
async function prepareRequest(config, op, args, init, caps) {
|
|
215468
|
-
const { path, query, body, headers } = splitArgs(op, args);
|
|
215503
|
+
const { path, query, body, headers, cookies } = splitArgs(op, args);
|
|
215469
215504
|
const authed = op.security?.length && caps.resolveAuth ? await caps.resolveAuth(op.security, config) : { headers: {}, query: {} };
|
|
215505
|
+
const cookiePairs = Object.entries(cookies ?? {}).filter(([, value]) => value !== void 0 && value !== null).map(([cookieName, value]) => `${cookieName}=${encodeURIComponent(String(value))}`);
|
|
215506
|
+
if (cookiePairs.length > 0) {
|
|
215507
|
+
authed.headers.Cookie = [authed.headers.Cookie, ...cookiePairs].filter(Boolean).join("; ");
|
|
215508
|
+
}
|
|
215470
215509
|
const fullQuery = { ...query, ...authed.query };
|
|
215471
215510
|
const url = buildUrl(config.serverUrl ?? "", substitutePath(op.path, path), Object.keys(fullQuery).length > 0 ? fullQuery : void 0, queryStyles(op));
|
|
215472
215511
|
const mergedInit = {
|
|
@@ -215528,7 +215567,7 @@ function createClientCore(operations, initial = {}, caps = {}) {
|
|
|
215528
215567
|
const client = {};
|
|
215529
215568
|
for (const [name, op] of Object.entries(operations)) {
|
|
215530
215569
|
if (op.responseKind === "sse") {
|
|
215531
|
-
|
|
215570
|
+
const method2 = (args = {}, init = {}) => {
|
|
215532
215571
|
if (!caps.sse) {
|
|
215533
215572
|
throw new Error(`SSE capability not wired: cannot stream operation "${op.id}"`);
|
|
215534
215573
|
}
|
|
@@ -215542,8 +215581,11 @@ function createClientCore(operations, initial = {}, caps = {}) {
|
|
|
215542
215581
|
yield* stream(config, opCtx, prepare, op.sseDataKind ?? "text");
|
|
215543
215582
|
})();
|
|
215544
215583
|
};
|
|
215584
|
+
Object.defineProperty(method2, "name", { value: name });
|
|
215585
|
+
client[name] = method2;
|
|
215545
215586
|
} else {
|
|
215546
215587
|
const method2 = (args = {}, init = {}) => execute(config, op, args, init, caps);
|
|
215588
|
+
Object.defineProperty(method2, "name", { value: name });
|
|
215547
215589
|
const spec = op.pagination;
|
|
215548
215590
|
client[name] = spec ? Object.assign(method2, {
|
|
215549
215591
|
pages: (args, init) => paginateCapability(caps, op).pages(pageCall(method2, config), spec, args, init),
|
|
@@ -215634,6 +215676,8 @@ async function* pages(call2, spec, args = {}, init) {
|
|
|
215634
215676
|
params[spec.param] = cursor;
|
|
215635
215677
|
const page = await call2({ ...args, params }, init);
|
|
215636
215678
|
yield page;
|
|
215679
|
+
if (spec.hasMore !== void 0 && resolvePointer(page, spec.hasMore) === false)
|
|
215680
|
+
return;
|
|
215637
215681
|
const next = resolvePointer(page, spec.nextCursor);
|
|
215638
215682
|
if (next === void 0 || next === null || next === "")
|
|
215639
215683
|
return;
|
|
@@ -215900,6 +215944,7 @@ async function generateClient(options) {
|
|
|
215900
215944
|
mockSeed: options.mockSeed,
|
|
215901
215945
|
setup: setupBlock,
|
|
215902
215946
|
runtime: options.runtime,
|
|
215947
|
+
importExt: options.importExt,
|
|
215903
215948
|
pagination: options.pagination
|
|
215904
215949
|
},
|
|
215905
215950
|
generators: selected,
|
|
@@ -7,17 +7,17 @@ var __dirname = __pathDirname(__filename);
|
|
|
7
7
|
import {
|
|
8
8
|
getExecutionTime,
|
|
9
9
|
getFallbackApisOrExit
|
|
10
|
-
} from "./
|
|
10
|
+
} from "./GHBEV27L.js";
|
|
11
11
|
import {
|
|
12
12
|
exitWithError
|
|
13
|
-
} from "./
|
|
13
|
+
} from "./UWZRCAHF.js";
|
|
14
14
|
import {
|
|
15
15
|
require_dist
|
|
16
16
|
} from "./JPNXFCZJ.js";
|
|
17
17
|
import {
|
|
18
18
|
redocStandaloneSri,
|
|
19
19
|
redocVersion
|
|
20
|
-
} from "./
|
|
20
|
+
} from "./U5H3NDWA.js";
|
|
21
21
|
import {
|
|
22
22
|
require_json_pointer,
|
|
23
23
|
require_openapi_sampler
|
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
require_fast_deep_equal,
|
|
30
30
|
require_json_schema_traverse,
|
|
31
31
|
require_pluralize
|
|
32
|
-
} from "./
|
|
32
|
+
} from "./HD24VMMU.js";
|
|
33
33
|
import "./HRYOF224.js";
|
|
34
34
|
import {
|
|
35
35
|
__commonJS,
|
|
@@ -20,15 +20,15 @@ import {
|
|
|
20
20
|
readProbe,
|
|
21
21
|
renderReport,
|
|
22
22
|
streamNdjsonObjects
|
|
23
|
-
} from "./
|
|
23
|
+
} from "./74VQSZ5T.js";
|
|
24
24
|
import {
|
|
25
25
|
AbortFlowError,
|
|
26
26
|
exitWithError
|
|
27
|
-
} from "./
|
|
27
|
+
} from "./UWZRCAHF.js";
|
|
28
28
|
import {
|
|
29
29
|
isPlainObject,
|
|
30
30
|
logger
|
|
31
|
-
} from "./
|
|
31
|
+
} from "./HD24VMMU.js";
|
|
32
32
|
import "./HRYOF224.js";
|
|
33
33
|
import "./YDPUXTSG.js";
|
|
34
34
|
|
package/lib/index.js
CHANGED
|
@@ -32,11 +32,11 @@ import {
|
|
|
32
32
|
saveBundle,
|
|
33
33
|
sortTopLevelKeys,
|
|
34
34
|
writeToFileByExtension
|
|
35
|
-
} from "./chunks/
|
|
35
|
+
} from "./chunks/GHBEV27L.js";
|
|
36
36
|
import {
|
|
37
37
|
AbortFlowError,
|
|
38
38
|
exitWithError
|
|
39
|
-
} from "./chunks/
|
|
39
|
+
} from "./chunks/UWZRCAHF.js";
|
|
40
40
|
import {
|
|
41
41
|
RedoclyOAuthClient,
|
|
42
42
|
ReuniteApi,
|
|
@@ -46,7 +46,7 @@ import {
|
|
|
46
46
|
getProxyUrl,
|
|
47
47
|
getReuniteUrl,
|
|
48
48
|
shouldBypassProxy
|
|
49
|
-
} from "./chunks/
|
|
49
|
+
} from "./chunks/IRDDR6ZX.js";
|
|
50
50
|
import {
|
|
51
51
|
ANONYMOUS_ID_CACHE_FILE,
|
|
52
52
|
DEFAULT_FETCH_TIMEOUT,
|
|
@@ -57,7 +57,7 @@ import {
|
|
|
57
57
|
engines,
|
|
58
58
|
name,
|
|
59
59
|
version
|
|
60
|
-
} from "./chunks/
|
|
60
|
+
} from "./chunks/U5H3NDWA.js";
|
|
61
61
|
import {
|
|
62
62
|
require_undici
|
|
63
63
|
} from "./chunks/QRC5ADSZ.js";
|
|
@@ -65,7 +65,7 @@ import {
|
|
|
65
65
|
RESET_ESCAPE_CODE,
|
|
66
66
|
calculateTotals,
|
|
67
67
|
conditionallyMaskSecrets
|
|
68
|
-
} from "./chunks/
|
|
68
|
+
} from "./chunks/ZQF2RYWL.js";
|
|
69
69
|
import "./chunks/HXIHIVQ5.js";
|
|
70
70
|
import "./chunks/XDVFCBV7.js";
|
|
71
71
|
import {
|
|
@@ -118,7 +118,7 @@ import {
|
|
|
118
118
|
white,
|
|
119
119
|
xmlEscape,
|
|
120
120
|
yellow
|
|
121
|
-
} from "./chunks/
|
|
121
|
+
} from "./chunks/HD24VMMU.js";
|
|
122
122
|
import "./chunks/HRYOF224.js";
|
|
123
123
|
import {
|
|
124
124
|
__commonJS,
|
|
@@ -7713,7 +7713,7 @@ async function handleGenerateArazzo({
|
|
|
7713
7713
|
config: config3
|
|
7714
7714
|
};
|
|
7715
7715
|
try {
|
|
7716
|
-
const { generate } = await import("./chunks/
|
|
7716
|
+
const { generate } = await import("./chunks/32PZUSDF.js");
|
|
7717
7717
|
logger.info(gray("\n Generating Arazzo description... \n"));
|
|
7718
7718
|
const generatedArazzo = await generate(options);
|
|
7719
7719
|
writeFileSync2(outputFile, stringifyYaml(generatedArazzo));
|
|
@@ -7763,7 +7763,7 @@ async function handleGenerateClient({
|
|
|
7763
7763
|
argv,
|
|
7764
7764
|
config: config3
|
|
7765
7765
|
}) {
|
|
7766
|
-
const { generateClient, mergeConfig } = await import("./chunks/
|
|
7766
|
+
const { generateClient, mergeConfig } = await import("./chunks/QDTFSU2A.js");
|
|
7767
7767
|
const configDir = config3.configPath ? dirname3(config3.configPath) : process.cwd();
|
|
7768
7768
|
const apisCfg = config3.resolvedConfig.apis ?? {};
|
|
7769
7769
|
const cliFlags = {
|
|
@@ -7771,6 +7771,7 @@ async function handleGenerateClient({
|
|
|
7771
7771
|
enumStyle: argv["enum-style"],
|
|
7772
7772
|
outputMode: argv["output-mode"],
|
|
7773
7773
|
runtime: argv.runtime,
|
|
7774
|
+
importExt: argv["import-ext"],
|
|
7774
7775
|
argsStyle: argv["args-style"],
|
|
7775
7776
|
errorMode: argv["error-mode"],
|
|
7776
7777
|
dateType: argv["date-type"],
|
|
@@ -9331,7 +9332,7 @@ async function handleRespect({
|
|
|
9331
9332
|
let mtlsCerts;
|
|
9332
9333
|
let harLogs;
|
|
9333
9334
|
try {
|
|
9334
|
-
const { run, conditionallyMaskSecrets: conditionallyMaskSecrets2 } = await import("./chunks/
|
|
9335
|
+
const { run, conditionallyMaskSecrets: conditionallyMaskSecrets2 } = await import("./chunks/32PZUSDF.js");
|
|
9335
9336
|
const workingDir = config3.configPath ? dirname5(config3.configPath) : process.cwd();
|
|
9336
9337
|
if (argv.mtls) {
|
|
9337
9338
|
mtlsCerts = resolveMtlsCertificates(argv.mtls, workingDir);
|
|
@@ -12851,7 +12852,7 @@ async function sendTelemetry({
|
|
|
12851
12852
|
$0: _,
|
|
12852
12853
|
...args
|
|
12853
12854
|
} = argv;
|
|
12854
|
-
const { RedoclyOAuthClient: RedoclyOAuthClient2 } = await import("./chunks/
|
|
12855
|
+
const { RedoclyOAuthClient: RedoclyOAuthClient2 } = await import("./chunks/5XWJ7SND.js");
|
|
12855
12856
|
const oauthClient = new RedoclyOAuthClient2();
|
|
12856
12857
|
const reuniteUrl = getReuniteUrl(config3, args.residency);
|
|
12857
12858
|
const logged_in = await oauthClient.isAuthorized(reuniteUrl);
|
|
@@ -12899,7 +12900,7 @@ async function sendTelemetry({
|
|
|
12899
12900
|
category: "product",
|
|
12900
12901
|
data: eventData
|
|
12901
12902
|
});
|
|
12902
|
-
const { otelTelemetry } = await import("./chunks/
|
|
12903
|
+
const { otelTelemetry } = await import("./chunks/H7EUHTNC.js");
|
|
12903
12904
|
otelTelemetry.send(cloudEvent);
|
|
12904
12905
|
} catch (err) {
|
|
12905
12906
|
}
|
|
@@ -13729,7 +13730,7 @@ yargs_default(hideBin(process.argv)).version("version", "Show version number.",
|
|
|
13729
13730
|
return true;
|
|
13730
13731
|
}),
|
|
13731
13732
|
async (argv) => {
|
|
13732
|
-
const { handlerBuildCommand } = await import("./chunks/
|
|
13733
|
+
const { handlerBuildCommand } = await import("./chunks/UTL36DYM.js");
|
|
13733
13734
|
commandWrapper(handlerBuildCommand)(argv);
|
|
13734
13735
|
}
|
|
13735
13736
|
).command(
|
|
@@ -13924,6 +13925,11 @@ yargs_default(hideBin(process.argv)).version("version", "Show version number.",
|
|
|
13924
13925
|
choices: ["inline", "package"],
|
|
13925
13926
|
requiresArg: true
|
|
13926
13927
|
},
|
|
13928
|
+
"import-ext": {
|
|
13929
|
+
describe: "Extension in generated relative imports: 'js' (default) suits tsc and bundlers; 'ts' suits runtimes that resolve specifiers literally, like Node's built-in type stripping (node client.ts).",
|
|
13930
|
+
choices: ["js", "ts"],
|
|
13931
|
+
requiresArg: true
|
|
13932
|
+
},
|
|
13927
13933
|
setup: {
|
|
13928
13934
|
describe: "Path to a publisher setup module (export default defineClientSetup({ config, middleware })) baked into the generated client, so a published SDK ships its request/response defaults built in. Works across all output modes.",
|
|
13929
13935
|
type: "string",
|
|
@@ -14087,7 +14093,7 @@ yargs_default(hideBin(process.argv)).version("version", "Show version number.",
|
|
|
14087
14093
|
}
|
|
14088
14094
|
}),
|
|
14089
14095
|
async (argv) => {
|
|
14090
|
-
const { handleDrift } = await import("./chunks/
|
|
14096
|
+
const { handleDrift } = await import("./chunks/Y7AZMCRO.js");
|
|
14091
14097
|
commandWrapper(handleDrift)(argv);
|
|
14092
14098
|
}
|
|
14093
14099
|
).command(
|
|
@@ -14155,7 +14161,7 @@ yargs_default(hideBin(process.argv)).version("version", "Show version number.",
|
|
|
14155
14161
|
}
|
|
14156
14162
|
}),
|
|
14157
14163
|
async (argv) => {
|
|
14158
|
-
const { handleProxy } = await import("./chunks/
|
|
14164
|
+
const { handleProxy } = await import("./chunks/LK5QRO6Z.js");
|
|
14159
14165
|
commandWrapper(handleProxy)(argv);
|
|
14160
14166
|
}
|
|
14161
14167
|
).completion("completion", "Generate autocomplete script for `redocly` command.").demandCommand(1).middleware([notifyUpdateCliVersion]).strict().argv;
|