@kizunajs/fetch 2.0.0-beta.2 → 2.0.0-beta.21

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/dist/index.mjs CHANGED
@@ -1,263 +1,1126 @@
1
- import { buildPath, isProblemDetails, isRouteDefinition, isStreamResponse, isValidationError, streamMode } from "kizunajs";
2
- //#region src/sse.ts
3
- const parseData = (text) => {
4
- try {
5
- return JSON.parse(text);
6
- } catch {
7
- return text;
8
- }
1
+ import { ValidationErrorSchema } from "kizunajs/schemas";
2
+ import { defineClient, isBinarySchema, isFileSchema, isStreamResponse, isVoidSchema, listedRoutes, readDef, readDeprecation, readDiscriminatedUnion, readMetaBrand, readMetaDescription, readMetaExamples, readMetaId, readObjectShape, resolveResponseBody, resolveResponseHeaders, sanitizeIdentifier, streamContentType, streamMode, toPascalCase, unwrapOptionalWrappers } from "kizunajs/generator";
3
+ import { z } from "zod";
4
+ //#region src/runtime.ts
5
+ /**
6
+ * The code every generated client runs, written into the file below its route
7
+ * table. It imports nothing, so a client installs nothing, and it always comes
8
+ * from the release that wrote the table it reads.
9
+ */
10
+ const runtimeSource = String.raw`/**
11
+ * What the client knows about one response: nothing for a body it reads as
12
+ * JSON, the media type for one that streams.
13
+ */
14
+ export type GeneratedResponse =
15
+ | Record<string, never>
16
+ | {
17
+ stream: true;
18
+ contentType: string;
19
+ };
20
+
21
+ /**
22
+ * One route in the table: how to reach it, and how to read each status it
23
+ * answers with.
24
+ */
25
+ export interface GeneratedRoute {
26
+ method: string;
27
+ path: string;
28
+ contentType?: string;
29
+ responses: Record<number, GeneratedResponse>;
30
+ }
31
+
32
+ /**
33
+ * The route table, nested the way the client is.
34
+ */
35
+ export interface GeneratedRoutes {
36
+ [key: string]: GeneratedRoutes | GeneratedRoute;
37
+ }
38
+
39
+ /**
40
+ * The request onRequest receives before it is sent. A header set on headers
41
+ * is sent with it.
42
+ */
43
+ export interface OutgoingRequest {
44
+ url: string;
45
+ method: string;
46
+ headers: Headers;
47
+ route: GeneratedRoute;
48
+ }
49
+
50
+ /**
51
+ * Where the client sends its requests, and what it adds to each one.
52
+ */
53
+ export interface ClientConfig {
54
+ baseUrl: string;
55
+ baseHeaders?: Record<string, string>;
56
+ credentials?: RequestCredentials;
57
+ fetch?: typeof fetch;
58
+ onRequest?: (request: OutgoingRequest) => void | Promise<void>;
59
+ retry?: RetryOptions;
60
+ reconnect?: ReconnectOptions;
61
+ }
62
+
63
+ /**
64
+ * Retries a GET, HEAD, OPTIONS, PUT or DELETE that failed on the network or
65
+ * was answered 429 or 503, waiting what Retry-After asks or backing off.
66
+ */
67
+ export interface RetryOptions {
68
+ /**
69
+ * Attempts in all, the first included.
70
+ */
71
+ maximumAttempts?: number;
72
+ /**
73
+ * Milliseconds the first backoff waits at most.
74
+ */
75
+ initialDelay?: number;
76
+ /**
77
+ * Milliseconds any wait may take.
78
+ */
79
+ maximumDelay?: number;
80
+ }
81
+
82
+ /**
83
+ * Reconnects an event stream on a GET, HEAD, OPTIONS, PUT or DELETE when its
84
+ * connection drops, sending the id of the last event as Last-Event-ID.
85
+ */
86
+ export interface ReconnectOptions {
87
+ /**
88
+ * Reconnections in a row before the stream fails. An event received resets the count.
89
+ */
90
+ maximumAttempts?: number;
91
+ /**
92
+ * Milliseconds to wait before reconnecting, until the server sends a retry field.
93
+ */
94
+ reconnectionTime?: number;
95
+ /**
96
+ * Milliseconds the wait may grow to after reconnections in a row that fail.
97
+ */
98
+ maximumDelay?: number;
99
+ }
100
+
101
+ /**
102
+ * One method on the client. Its '~route' names the method it sends and
103
+ * whether its response streams, so a wrapper like @kizunajs/tanstack-query
104
+ * reads both off the client.
105
+ */
106
+ export type ClientMethod<Method extends string, Streams extends boolean, Args, Result> = ({} extends Args
107
+ ? (args?: Args) => Promise<Result>
108
+ : (args: Args) => Promise<Result>) & {
109
+ readonly '~route': GeneratedRoute & {
110
+ readonly method: Method;
111
+ readonly streams: Streams;
112
+ };
113
+ };
114
+
115
+ interface CallArgs {
116
+ params?: Record<string, unknown>;
117
+ query?: Record<string, unknown>;
118
+ body?: unknown;
119
+ headers?: Record<string, string | undefined>;
120
+ fetchOptions?: RequestInit;
121
+ }
122
+
123
+ /**
124
+ * Dates go on the wire as ISO 8601, everything else as String gives it.
125
+ */
126
+ const serializeValue = (value: unknown): string => (value instanceof Date ? value.toISOString() : String(value));
127
+
128
+ const buildPath = (path: string, params: Record<string, unknown> = {}): string =>
129
+ path.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, (_, name: string) => {
130
+ const value = params[name];
131
+ if (value === undefined) throw new Error('Missing path parameter: ' + name);
132
+ return encodeURIComponent(serializeValue(value));
133
+ });
134
+
135
+ /**
136
+ * An array repeats its key, and an undefined or null field is left out.
137
+ */
138
+ const buildSearchParams = (fields: Record<string, unknown>): URLSearchParams => {
139
+ const params = new URLSearchParams();
140
+ for (const [key, value] of Object.entries(fields)) {
141
+ if (value === undefined || value === null) continue;
142
+ for (const item of Array.isArray(value) ? value : [value]) params.append(key, serializeValue(item));
143
+ }
144
+ return params;
145
+ };
146
+
147
+ const buildFormData = (fields: Record<string, unknown>): FormData => {
148
+ const formData = new FormData();
149
+ for (const [key, value] of Object.entries(fields)) {
150
+ for (const item of Array.isArray(value) ? value : [value]) {
151
+ if (item instanceof Blob) formData.append(key, item);
152
+ else if (item !== undefined && item !== null) formData.append(key, typeof item === 'string' ? item : JSON.stringify(item));
153
+ }
154
+ }
155
+ return formData;
156
+ };
157
+
158
+ /**
159
+ * A multipart body leaves Content-Type to fetch, which adds the boundary.
160
+ */
161
+ const encodeBody = (route: GeneratedRoute, body: unknown, headers: Headers): BodyInit => {
162
+ switch (route.contentType) {
163
+ case 'multipart/form-data':
164
+ return body instanceof FormData ? body : buildFormData(body as Record<string, unknown>);
165
+ case 'application/x-www-form-urlencoded':
166
+ if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/x-www-form-urlencoded');
167
+ return buildSearchParams(body as Record<string, unknown>);
168
+ default:
169
+ if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
170
+ return JSON.stringify(body);
171
+ }
172
+ };
173
+
174
+ const parseJson = (text: string): unknown => {
175
+ try {
176
+ return JSON.parse(text) as unknown;
177
+ } catch {
178
+ return text;
179
+ }
180
+ };
181
+
182
+ interface ServerSentEvent {
183
+ event?: string;
184
+ data: unknown;
185
+ id?: string;
186
+ retry?: number;
187
+ }
188
+
189
+ /**
190
+ * A lone carriage return at the end may be half of CRLF, so it waits for more
191
+ * unless the stream is over.
192
+ */
193
+ const findLineEnd = (buffer: string, final: boolean): { index: number; length: number } | undefined => {
194
+ for (let index = 0; index < buffer.length; index += 1) {
195
+ const character = buffer[index];
196
+ if (character === '\n') return { index, length: 1 };
197
+ if (character === '\r') {
198
+ if (index + 1 < buffer.length) return { index, length: buffer[index + 1] === '\n' ? 2 : 1 };
199
+ if (final) return { index, length: 1 };
200
+ return undefined;
201
+ }
202
+ }
203
+ return undefined;
204
+ };
205
+
206
+ /**
207
+ * Reads text/event-stream as the WHATWG HTML specification parses it.
208
+ */
209
+ interface EventStreamState {
210
+ lastEventId: string;
211
+ reconnectionTime: number;
212
+ }
213
+
214
+ async function* readEvents(
215
+ body: ReadableStream<Uint8Array>,
216
+ state: EventStreamState = {
217
+ lastEventId: '',
218
+ reconnectionTime: 3000,
219
+ }
220
+ ): AsyncGenerator<ServerSentEvent> {
221
+ const reader = body.getReader();
222
+ const decoder = new TextDecoder();
223
+ let buffer = '';
224
+ let first = true;
225
+ let dataLines: string[] = [];
226
+ let eventType = '';
227
+ let lastEventId = state.lastEventId;
228
+ let retry: number | undefined;
229
+
230
+ const dispatch = (): ServerSentEvent | undefined => {
231
+ state.lastEventId = lastEventId;
232
+ if (dataLines.length === 0) {
233
+ eventType = '';
234
+ return undefined;
235
+ }
236
+ const message: ServerSentEvent = {
237
+ data: parseJson(dataLines.join('\n')),
238
+ };
239
+ if (eventType !== '') message.event = eventType;
240
+ if (lastEventId !== '') message.id = lastEventId;
241
+ if (retry !== undefined) message.retry = retry;
242
+ dataLines = [];
243
+ eventType = '';
244
+ retry = undefined;
245
+ return message;
246
+ };
247
+
248
+ const processLine = (line: string): ServerSentEvent | undefined => {
249
+ if (line === '') return dispatch();
250
+ if (line.startsWith(':')) return undefined;
251
+ const separator = line.indexOf(':');
252
+ const field = separator === -1 ? line : line.slice(0, separator);
253
+ let value = separator === -1 ? '' : line.slice(separator + 1);
254
+ if (value.startsWith(' ')) value = value.slice(1);
255
+ switch (field) {
256
+ case 'event':
257
+ eventType = value;
258
+ break;
259
+ case 'data':
260
+ dataLines.push(value);
261
+ break;
262
+ case 'id':
263
+ if (!value.includes('\0')) lastEventId = value;
264
+ break;
265
+ case 'retry':
266
+ if (/^\d+$/.test(value)) {
267
+ retry = Number(value);
268
+ state.reconnectionTime = Math.min(retry, 3_600_000);
269
+ }
270
+ break;
271
+ }
272
+ return undefined;
273
+ };
274
+
275
+ try {
276
+ for (;;) {
277
+ const { done, value } = await reader.read();
278
+ let chunk = done ? decoder.decode() : decoder.decode(value, { stream: true });
279
+ if (first && chunk.length > 0) {
280
+ if (chunk.charCodeAt(0) === 0xfeff) chunk = chunk.slice(1);
281
+ first = false;
282
+ }
283
+ buffer += chunk;
284
+ for (;;) {
285
+ const lineEnd = findLineEnd(buffer, done);
286
+ if (lineEnd === undefined) break;
287
+ const line = buffer.slice(0, lineEnd.index);
288
+ buffer = buffer.slice(lineEnd.index + lineEnd.length);
289
+ const message = processLine(line);
290
+ if (message !== undefined) yield message;
291
+ }
292
+ if (done) return;
293
+ }
294
+ } finally {
295
+ void reader.cancel().catch(() => undefined);
296
+ }
297
+ }
298
+
299
+ async function* reconnectingEvents(
300
+ first: Response,
301
+ reopen: (lastEventId: string) => Promise<Response>,
302
+ options: ReconnectOptions,
303
+ signal: AbortSignal | null | undefined
304
+ ): AsyncGenerator<ServerSentEvent> {
305
+ const maximumAttempts = options.maximumAttempts ?? 5;
306
+ const maximumDelay = options.maximumDelay ?? 30_000;
307
+ const state: EventStreamState = {
308
+ lastEventId: '',
309
+ reconnectionTime: options.reconnectionTime ?? 3000,
310
+ };
311
+ let response: Response | undefined = first;
312
+ let attempts = 0;
313
+ let failure: unknown;
314
+ for (;;) {
315
+ if (response?.body) {
316
+ try {
317
+ for await (const message of readEvents(response.body, state)) {
318
+ attempts = 0;
319
+ failure = undefined;
320
+ yield message;
321
+ }
322
+ } catch (error) {
323
+ failure = error;
324
+ }
325
+ }
326
+ if (signal?.aborted) throw signal.reason;
327
+ if (attempts >= maximumAttempts) {
328
+ if (failure !== undefined) throw failure;
329
+ return;
330
+ }
331
+ attempts += 1;
332
+ const ceiling = Math.min(maximumDelay, state.reconnectionTime * 2 ** (attempts - 1));
333
+ await wait(state.reconnectionTime + Math.random() * Math.max(0, ceiling - state.reconnectionTime), signal);
334
+ try {
335
+ response = await reopen(state.lastEventId);
336
+ } catch (error) {
337
+ if (signal?.aborted) throw error;
338
+ failure = error;
339
+ response = undefined;
340
+ continue;
341
+ }
342
+ if (response.status === 204) return;
343
+ const contentType = response.headers.get('content-type') ?? '';
344
+ if (response.status !== first.status || !contentType.toLowerCase().startsWith('text/event-stream')) {
345
+ throw new Error('Reconnecting to the event stream failed with status ' + response.status);
346
+ }
347
+ }
348
+ }
349
+
350
+ async function* readText(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
351
+ const reader = body.getReader();
352
+ const decoder = new TextDecoder();
353
+ try {
354
+ for (;;) {
355
+ const { done, value } = await reader.read();
356
+ if (done) {
357
+ const tail = decoder.decode();
358
+ if (tail.length > 0) yield tail;
359
+ return;
360
+ }
361
+ const text = decoder.decode(value, { stream: true });
362
+ if (text.length > 0) yield text;
363
+ }
364
+ } finally {
365
+ void reader.cancel().catch(() => undefined);
366
+ }
367
+ }
368
+
369
+ async function* readBytes(body: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array> {
370
+ const reader = body.getReader();
371
+ try {
372
+ for (;;) {
373
+ const { done, value } = await reader.read();
374
+ if (done) return;
375
+ yield value;
376
+ }
377
+ } finally {
378
+ void reader.cancel().catch(() => undefined);
379
+ }
380
+ }
381
+
382
+ const readStream = (body: ReadableStream<Uint8Array>, contentType: string): AsyncIterable<unknown> => {
383
+ const essence = (contentType.split(';')[0] ?? '').trim().toLowerCase();
384
+ if (essence === 'text/event-stream') return readEvents(body);
385
+ if (essence.startsWith('text/')) return readText(body);
386
+ return readBytes(body);
387
+ };
388
+
389
+ const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
390
+
391
+ const RETRY_STATUSES = new Set([429, 503]);
392
+
393
+ const retryAfter = (header: string | null): number | undefined => {
394
+ if (header === null) return undefined;
395
+ if (/^\d+$/.test(header.trim())) return Number(header.trim()) * 1000;
396
+ const date = Date.parse(header);
397
+ return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
9
398
  };
10
- const findLineEnd = (buffer, final) => {
11
- for (let index = 0; index < buffer.length; index += 1) {
12
- const character = buffer[index];
13
- if (character === "\n") return {
14
- index,
15
- length: 1
16
- };
17
- if (character === "\r") {
18
- if (index + 1 < buffer.length) return {
19
- index,
20
- length: buffer[index + 1] === "\n" ? 2 : 1
21
- };
22
- if (final) return {
23
- index,
24
- length: 1
25
- };
26
- return;
399
+
400
+ const wait = (milliseconds: number, signal: AbortSignal | null | undefined): Promise<void> =>
401
+ new Promise((resolve, reject) => {
402
+ if (signal?.aborted) {
403
+ reject(signal.reason);
404
+ return;
405
+ }
406
+ const onAbort = () => {
407
+ clearTimeout(timer);
408
+ reject(signal?.reason);
409
+ };
410
+ const timer = setTimeout(() => {
411
+ signal?.removeEventListener('abort', onAbort);
412
+ resolve();
413
+ }, milliseconds);
414
+ signal?.addEventListener('abort', onAbort, {
415
+ once: true,
416
+ });
417
+ });
418
+
419
+ const send = async (url: string, init: RequestInit, route: GeneratedRoute, config: ClientConfig): Promise<Response> => {
420
+ const fetcher = config.fetch ?? fetch;
421
+ const retry = config.retry;
422
+ if (retry === undefined || !IDEMPOTENT_METHODS.has(route.method)) return fetcher(url, init);
423
+ const maximumAttempts = retry.maximumAttempts ?? 3;
424
+ const initialDelay = retry.initialDelay ?? 500;
425
+ const maximumDelay = retry.maximumDelay ?? 30_000;
426
+ for (let attempt = 1; ; attempt += 1) {
427
+ const backoff = Math.random() * Math.min(maximumDelay, initialDelay * 2 ** (attempt - 1));
428
+ let response: Response;
429
+ try {
430
+ response = await fetcher(url, init);
431
+ } catch (error) {
432
+ if (attempt >= maximumAttempts || init.signal?.aborted || !(error instanceof TypeError)) throw error;
433
+ await wait(backoff, init.signal);
434
+ continue;
435
+ }
436
+ if (attempt >= maximumAttempts || !RETRY_STATUSES.has(response.status)) return response;
437
+ const asked = retryAfter(response.headers.get('retry-after'));
438
+ if (asked !== undefined && asked > maximumDelay) return response;
439
+ await response.body?.cancel();
440
+ await wait(asked ?? backoff, init.signal);
441
+ }
442
+ };
443
+
444
+ const buildMethod = (route: GeneratedRoute, config: ClientConfig) => {
445
+ const call = async (args: CallArgs = {}) => {
446
+ const query = args.query === undefined ? '' : buildSearchParams(args.query).toString();
447
+ const url = config.baseUrl + buildPath(route.path, args.params) + (query.length > 0 ? '?' + query : '');
448
+ const prepare = async (lastEventId = ''): Promise<RequestInit> => {
449
+ const headers = new Headers(config.baseHeaders);
450
+ for (const [name, value] of Object.entries(args.headers ?? {})) {
451
+ if (value !== undefined) headers.set(name, value);
452
+ }
453
+ if (lastEventId !== '') headers.set('Last-Event-ID', lastEventId);
454
+ const init: RequestInit = {
455
+ method: route.method,
456
+ headers,
457
+ };
458
+ if (args.body !== undefined) init.body = encodeBody(route, args.body, headers);
459
+ if (config.credentials !== undefined) init.credentials = config.credentials;
460
+ await config.onRequest?.({
461
+ url,
462
+ method: route.method,
463
+ headers,
464
+ route,
465
+ });
466
+ return {
467
+ ...init,
468
+ ...args.fetchOptions,
469
+ };
470
+ };
471
+
472
+ const response = await send(url, await prepare(), route, config);
473
+ const responseHeaders: Record<string, string> = {};
474
+ response.headers.forEach((value, name) => {
475
+ responseHeaders[name] = value;
476
+ });
477
+ const declared = route.responses[response.status];
478
+ if (declared !== undefined && 'stream' in declared && response.body !== null) {
479
+ const essence = (declared.contentType.split(';')[0] ?? '').trim().toLowerCase();
480
+ const reconnect = essence === 'text/event-stream' && IDEMPOTENT_METHODS.has(route.method) ? config.reconnect : undefined;
481
+ const reopen = async (lastEventId: string) => send(url, await prepare(lastEventId), route, config);
482
+ return {
483
+ status: response.status,
484
+ body: reconnect
485
+ ? reconnectingEvents(response, reopen, reconnect, args.fetchOptions?.signal)
486
+ : readStream(response.body, declared.contentType),
487
+ headers: responseHeaders,
488
+ };
489
+ }
490
+ const text = await response.text();
491
+ return {
492
+ status: response.status,
493
+ body: text.length > 0 ? parseJson(text) : undefined,
494
+ headers: responseHeaders,
495
+ };
496
+ };
497
+ const streams = Object.values(route.responses).some((response) => 'stream' in response);
498
+ return Object.defineProperty(call, '~route', {
499
+ value: {
500
+ ...route,
501
+ streams,
502
+ },
503
+ });
504
+ };
505
+
506
+ const isRoute = (node: GeneratedRoutes | GeneratedRoute): node is GeneratedRoute => typeof node['method'] === 'string';
507
+
508
+ const buildTree = (routes: GeneratedRoutes, config: ClientConfig): Record<string, unknown> => {
509
+ const tree: Record<string, unknown> = {};
510
+ for (const [key, node] of Object.entries(routes)) {
511
+ tree[key] = isRoute(node) ? buildMethod(node, config) : buildTree(node, config);
512
+ }
513
+ return tree;
514
+ };
515
+
516
+ /**
517
+ * Sends the request context headers with every request. An explicit
518
+ * baseHeaders entry wins.
519
+ */
520
+ const buildClient = (routes: GeneratedRoutes, config: ClientConfig & { requestContext?: object }): Record<string, unknown> => {
521
+ const contextHeaders: Record<string, string> = {};
522
+ for (const [name, value] of Object.entries(config.requestContext ?? {})) {
523
+ if (value !== undefined) contextHeaders[name] = String(value);
524
+ }
525
+ return buildTree(routes, {
526
+ ...config,
527
+ baseHeaders: {
528
+ ...contextHeaders,
529
+ ...config.baseHeaders,
530
+ },
531
+ });
532
+ };
533
+ `;
534
+ //#endregion
535
+ //#region src/zod-to-typescript.ts
536
+ /**
537
+ * Collects the named types a walk produces, so a model shared by many routes is
538
+ * declared once.
539
+ */
540
+ var TypeCollector = class {
541
+ named = /* @__PURE__ */ new Map();
542
+ claimed = /* @__PURE__ */ new Set();
543
+ brands = /* @__PURE__ */ new Map();
544
+ /**
545
+ * Which side of a pipe a schema is read from: the input a request sends, or
546
+ * the output a response carries.
547
+ */
548
+ direction = "output";
549
+ /**
550
+ * Reads the schemas `read` walks from the side a request sends.
551
+ */
552
+ readingInput(read) {
553
+ const previous = this.direction;
554
+ this.direction = "input";
555
+ try {
556
+ return read();
557
+ } finally {
558
+ this.direction = previous;
27
559
  }
28
560
  }
561
+ readsInput() {
562
+ return this.direction === "input";
563
+ }
564
+ /**
565
+ * Claims a name before its body is walked, so a model that refers to itself
566
+ * resolves to its own name instead of recursing. Answers whether the caller
567
+ * is the one that has to emit it.
568
+ */
569
+ claim(name) {
570
+ if (this.claimed.has(name)) return false;
571
+ this.claimed.add(name);
572
+ return true;
573
+ }
574
+ add(type) {
575
+ this.named.set(type.name, type);
576
+ }
577
+ /**
578
+ * Declares a brand as a named type, `UserId = string & KizunaBrand<"UserId">`,
579
+ * and answers the name.
580
+ */
581
+ addBrand(brand, base, example) {
582
+ const name = sanitizeIdentifier(brand);
583
+ const existing = this.brands.get(name);
584
+ if (existing !== void 0 && (existing.brand !== brand || existing.base !== base)) throw new Error(`@kizunajs/fetch: brand ${quote(brand)} wraps both ${existing.base} and ${base}. Give each its own name.`);
585
+ if (existing === void 0) this.brands.set(name, {
586
+ brand,
587
+ base,
588
+ example
589
+ });
590
+ return name;
591
+ }
592
+ usesBrand() {
593
+ return this.brands.size > 0;
594
+ }
595
+ /**
596
+ * Each brand's name, the type it wraps, and a value for its `@example`, for
597
+ * the constructors the file exports.
598
+ */
599
+ allBrands() {
600
+ return [...this.brands].map(([name, { base, example }]) => ({
601
+ name,
602
+ base,
603
+ example
604
+ }));
605
+ }
606
+ all() {
607
+ for (const name of this.brands.keys()) if (this.named.has(name)) throw new Error(`@kizunajs/fetch: brand ${quote(name)} has the same name as a model. Give each its own name.`);
608
+ const brands = [...this.brands].map(([name, { brand, base }]) => ({
609
+ name,
610
+ description: `A branded \`${base}\`. Responses hand one back, and \`to${name}\` makes one from a plain value.`,
611
+ body: `${base} & KizunaBrand<${quote(brand)}>`
612
+ }));
613
+ return [...this.named.values(), ...brands].sort((left, right) => left.name.localeCompare(right.name));
614
+ }
29
615
  };
616
+ const quote = (value) => JSON.stringify(value);
30
617
  /**
31
- * Parses `text/event-stream` per the WHATWG HTML specification.
618
+ * What a brand wraps: the scalars, as the JSON carries them.
32
619
  */
33
- async function* parseServerSentEvents(body) {
34
- const reader = body.getReader();
35
- const decoder = new TextDecoder();
36
- let buffer = "";
37
- let first = true;
38
- let dataLines = [];
39
- let eventType = "";
40
- let lastEventId = "";
41
- let retry;
42
- const dispatch = () => {
43
- if (dataLines.length === 0) {
44
- eventType = "";
45
- return;
46
- }
47
- const message = { data: parseData(dataLines.join("\n")) };
48
- if (eventType !== "") message.event = eventType;
49
- if (lastEventId !== "") message.id = lastEventId;
50
- if (retry !== void 0) message.retry = retry;
51
- dataLines = [];
52
- eventType = "";
53
- retry = void 0;
54
- return message;
55
- };
56
- const processLine = (line) => {
57
- if (line === "") return dispatch();
58
- if (line.startsWith(":")) return void 0;
59
- const separator = line.indexOf(":");
60
- const field = separator === -1 ? line : line.slice(0, separator);
61
- let value = separator === -1 ? "" : line.slice(separator + 1);
62
- if (value.startsWith(" ")) value = value.slice(1);
63
- switch (field) {
64
- case "event":
65
- eventType = value;
66
- break;
67
- case "data":
68
- dataLines.push(value);
69
- break;
70
- case "id":
71
- if (!value.includes("\0")) lastEventId = value;
72
- break;
73
- case "retry":
74
- if (/^\d+$/.test(value)) retry = Number(value);
75
- break;
76
- }
77
- };
78
- try {
79
- for (;;) {
80
- const { done, value } = await reader.read();
81
- let chunk = done ? decoder.decode() : decoder.decode(value, { stream: true });
82
- if (first && chunk.length > 0) {
83
- if (chunk.charCodeAt(0) === 65279) chunk = chunk.slice(1);
84
- first = false;
85
- }
86
- buffer += chunk;
87
- for (;;) {
88
- const lineEnd = findLineEnd(buffer, done);
89
- if (lineEnd === void 0) break;
90
- const line = buffer.slice(0, lineEnd.index);
91
- buffer = buffer.slice(lineEnd.index + lineEnd.length);
92
- const message = processLine(line);
93
- if (message !== void 0) yield message;
94
- }
95
- if (done) return;
96
- }
97
- } finally {
98
- reader.cancel().catch(() => void 0);
620
+ const BRANDABLE_BASES = new Set([
621
+ "string",
622
+ "number",
623
+ "boolean"
624
+ ]);
625
+ /**
626
+ * A literal as the type the JSON carries, so `z.literal(true)` is `true`.
627
+ */
628
+ const literalType = (value) => {
629
+ if (typeof value === "string") return quote(value);
630
+ if (typeof value === "bigint") return `${value}n`;
631
+ if (value === void 0) return "undefined";
632
+ return String(value);
633
+ };
634
+ const indent$1 = (text, depth = 1) => text.split("\n").map((line) => line.length > 0 ? " ".repeat(depth) + line : line).join("\n");
635
+ /**
636
+ * A property name, quoted only when it is not a plain identifier.
637
+ */
638
+ const propertyKey = (key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : quote(key);
639
+ /**
640
+ * A doc comment over the lines it is given, or nothing when there are none.
641
+ * Always multi-line, the way the rest of this repository writes them.
642
+ */
643
+ const docComment = (lines) => {
644
+ const body = lines.flatMap((line) => line.split("\n"));
645
+ if (body.length === 0) return "";
646
+ return `/**\n${body.map((line) => ` * ${line}`.trimEnd()).join("\n")}\n */\n`;
647
+ };
648
+ /**
649
+ * Renders a declared example as the TypeScript literal a caller would write.
650
+ */
651
+ const exampleLiteral = (value) => {
652
+ if (typeof value === "string") return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
653
+ if (value === void 0) return "undefined";
654
+ return JSON.stringify(value) ?? "undefined";
655
+ };
656
+ const STRING_SAMPLES = {
657
+ email: "ada@example.com",
658
+ url: "https://example.com",
659
+ uuid: "3f1c2d9e-5b6a-4c7d-8e9f-0a1b2c3d4e5f",
660
+ datetime: "2026-01-01T00:00:00Z",
661
+ date: "2026-01-01",
662
+ time: "00:00:00"
663
+ };
664
+ const stringSample = (schema, key) => {
665
+ const def = readDef(schema);
666
+ const formats = [def.format, ...(def.checks ?? []).map((check) => check.format ?? check.def?.format)];
667
+ for (const format of formats) if (format !== void 0 && format in STRING_SAMPLES) return exampleLiteral(STRING_SAMPLES[format]);
668
+ if (key !== void 0 && /id$/i.test(key)) return exampleLiteral("1");
669
+ return exampleLiteral("string");
670
+ };
671
+ /**
672
+ * A value a caller could pass for a schema, used in the `@example` on each
673
+ * client method. A schema that declares an example is taken at its word;
674
+ * anything else gets a value of the right shape.
675
+ */
676
+ const sampleValue = (schema, depth = 0, key) => {
677
+ const [declared] = readMetaExamples(schema);
678
+ if (declared !== void 0) return exampleLiteral(declared);
679
+ if (isFileSchema(schema)) return "new File([], 'upload.txt')";
680
+ if (isBinarySchema(schema)) return "new Uint8Array()";
681
+ const def = readDef(schema);
682
+ if (def.type === "default" && def.defaultValue !== void 0) return exampleLiteral(def.defaultValue);
683
+ if (def.type === "pipe") {
684
+ const side = def.in ?? def.out;
685
+ return side ? sampleValue(side, depth, key) : "undefined";
99
686
  }
100
- }
101
- async function* readTextChunks(body) {
102
- const reader = body.getReader();
103
- const decoder = new TextDecoder();
104
- try {
105
- for (;;) {
106
- const { done, value } = await reader.read();
107
- if (done) {
108
- const tail = decoder.decode();
109
- if (tail.length > 0) yield tail;
110
- return;
111
- }
112
- const text = decoder.decode(value, { stream: true });
113
- if (text.length > 0) yield text;
687
+ if (def.innerType && def.type !== "object") return sampleValue(def.innerType, depth, key);
688
+ switch (def.type) {
689
+ case "number":
690
+ case "int": return "1";
691
+ case "bigint": return exampleLiteral("1");
692
+ case "boolean": return "true";
693
+ case "date": return exampleLiteral("2026-01-01");
694
+ case "null": return "null";
695
+ case "literal": return def.values?.length ? exampleLiteral(def.values[0]) : "undefined";
696
+ case "enum": {
697
+ const [first] = Object.values(def.entries ?? {});
698
+ return first === void 0 ? "undefined" : exampleLiteral(first);
114
699
  }
115
- } finally {
116
- reader.cancel().catch(() => void 0);
117
- }
118
- }
119
- async function* readByteChunks(body) {
120
- const reader = body.getReader();
121
- try {
122
- for (;;) {
123
- const { done, value } = await reader.read();
124
- if (done) return;
125
- yield value;
700
+ case "array":
701
+ if (!def.element || depth >= SAMPLE_DEPTH) return "[]";
702
+ return `[\n${indent$1(`${sampleValue(def.element, depth + 1, key)},`)}\n]`;
703
+ case "tuple": return `[${(def.items ?? []).map((item) => sampleValue(item, depth + 1, key)).join(", ")}]`;
704
+ case "object": return sampleObject(schema, depth);
705
+ case "record": return "{}";
706
+ case "union": {
707
+ const options = readDiscriminatedUnion(schema)?.options ?? def.options ?? [];
708
+ return options[0] ? sampleValue(options[0], depth, key) : "undefined";
126
709
  }
127
- } finally {
128
- reader.cancel().catch(() => void 0);
710
+ case "string": return stringSample(schema, key);
711
+ default: return "undefined";
129
712
  }
130
- }
131
- //#endregion
132
- //#region src/client.ts
133
- const buildFormData = (body) => {
134
- const formData = new FormData();
135
- for (const [key, entry] of Object.entries(body)) {
136
- const values = Array.isArray(entry) ? entry : [entry];
137
- for (const value of values) if (value instanceof File || value instanceof Blob) formData.append(key, value);
138
- else if (value !== void 0 && value !== null) formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
713
+ };
714
+ const SAMPLE_DEPTH = 2;
715
+ /**
716
+ * The required fields of an object schema, written as the literal a caller
717
+ * would pass. Optional fields are left out, since an example shows the least
718
+ * the route needs.
719
+ */
720
+ const sampleObject = (schema, depth = 0) => {
721
+ const shape = readObjectShape(schema);
722
+ if (!shape) return "{}";
723
+ const required = Object.entries(shape).filter(([, field]) => !unwrapOptionalWrappers(field).optional);
724
+ if (required.length === 0 || depth >= SAMPLE_DEPTH) return "{}";
725
+ return `{\n${indent$1(required.map(([key, field]) => `${propertyKey(key)}: ${sampleValue(unwrapOptionalWrappers(field).inner, depth + 1, key)},`).join("\n"))}\n}`;
726
+ };
727
+ /**
728
+ * What an editor shows above a field: its description, whether it is on its way
729
+ * out, and the values the schema declares as examples.
730
+ */
731
+ const fieldDoc = (field) => {
732
+ const lines = [];
733
+ const description = readMetaDescription(field);
734
+ if (description !== void 0) lines.push(description);
735
+ const deprecation = readDeprecation(field);
736
+ if (deprecation !== void 0) {
737
+ if (lines.length > 0) lines.push("");
738
+ lines.push(`@deprecated ${deprecation.message ?? ""}`.trimEnd());
739
+ }
740
+ for (const example of readMetaExamples(field)) {
741
+ if (lines.length > 0) lines.push("");
742
+ lines.push("@example", exampleLiteral(example));
139
743
  }
140
- return formData;
744
+ return lines;
745
+ };
746
+ const objectBody = (schema, collector, hint) => {
747
+ const shape = readObjectShape(schema);
748
+ if (!shape) return "Record<string, unknown>";
749
+ const entries = Object.entries(shape);
750
+ if (entries.length === 0) return "Record<string, never>";
751
+ return `{\n${indent$1(entries.map(([key, field]) => {
752
+ const doc = docComment(fieldDoc(field));
753
+ const mark = unwrapOptionalWrappers(field).optional ? "?" : "";
754
+ return `${doc}${propertyKey(key)}${mark}: ${typeOf(field, collector, `${hint}${toPascalCase(key)}`)};`;
755
+ }).join("\n"))}\n}`;
141
756
  };
142
757
  /**
143
- * Serializes a query or path value for the URL. Dates use ISO 8601; everything
144
- * else uses `String`.
758
+ * The TypeScript type a schema describes. Named models are collected and
759
+ * referenced; anonymous shapes are inlined. A brand is named like a model.
145
760
  */
146
- const serializeValue = (value) => value instanceof Date ? value.toISOString() : String(value);
147
- const buildQueryString = (query) => {
148
- const params = new URLSearchParams();
149
- for (const [key, value] of Object.entries(query)) {
150
- if (value === void 0 || value === null) continue;
151
- if (Array.isArray(value)) for (const item of value) params.append(key, serializeValue(item));
152
- else params.append(key, serializeValue(value));
761
+ const typeOf = (schema, collector, hint) => {
762
+ const type = unbrandedTypeOf(schema, collector, hint);
763
+ const brand = readMetaBrand(schema);
764
+ if (brand === void 0 || !BRANDABLE_BASES.has(type)) return type;
765
+ return collector.addBrand(brand, type, sampleValue(schema, 0, brand));
766
+ };
767
+ const unbrandedTypeOf = (schema, collector, hint) => {
768
+ if (isFileSchema(schema)) return "File | Blob";
769
+ if (isBinarySchema(schema)) return "Uint8Array";
770
+ const def = readDef(schema);
771
+ if (def.type === "nullable" && def.innerType) return `${typeOf(def.innerType, collector, hint)} | null`;
772
+ if (def.type === "nullish" && def.innerType) return `${typeOf(def.innerType, collector, hint)} | null`;
773
+ if (def.innerType && def.type !== "object") return typeOf(def.innerType, collector, hint);
774
+ if (def.type === "pipe") {
775
+ const side = collector.readsInput() ? def.in : def.out ?? def.in;
776
+ return side ? typeOf(side, collector, hint) : "unknown";
777
+ }
778
+ const modelName = readMetaId(schema);
779
+ if (modelName !== void 0) {
780
+ if (collector.claim(modelName)) collector.add({
781
+ name: modelName,
782
+ description: readMetaDescription(schema),
783
+ body: structuralType(schema, collector, modelName)
784
+ });
785
+ return modelName;
153
786
  }
154
- const result = params.toString();
155
- return result.length > 0 ? `?${result}` : "";
787
+ return structuralType(schema, collector, hint);
156
788
  };
157
- const CLIENT_ROUTE = Symbol.for("kizuna.client-route");
158
789
  /**
159
- * The route a client method answers, or `undefined` for anything that is not
160
- * one.
790
+ * The type a schema describes by its shape, its name already spent by the caller.
161
791
  */
162
- const routeOf = (value) => typeof value === "function" ? value[CLIENT_ROUTE] : void 0;
163
- const buildRouteFn = (route, config) => {
164
- const call = async (args = {}) => {
165
- const url = config.baseUrl + buildPath(route.path, args.params) + (args.query ? buildQueryString(args.query) : "");
166
- const headers = {
167
- ...config.baseHeaders ?? {},
168
- ...args.headers ?? {}
169
- };
170
- let body;
171
- if (args.body !== void 0) {
172
- const hasContentTypeHeader = "Content-Type" in headers || "content-type" in headers;
173
- switch (route.contentType) {
174
- case "multipart/form-data":
175
- body = args.body instanceof FormData ? args.body : buildFormData(args.body);
176
- break;
177
- case "application/x-www-form-urlencoded":
178
- if (!hasContentTypeHeader) headers["Content-Type"] = "application/x-www-form-urlencoded";
179
- body = new URLSearchParams(args.body);
180
- break;
181
- default:
182
- if (!hasContentTypeHeader) headers["Content-Type"] = "application/json";
183
- body = JSON.stringify(args.body);
184
- }
792
+ const structuralType = (schema, collector, hint) => {
793
+ const def = readDef(schema);
794
+ switch (def.type) {
795
+ case "string": return "string";
796
+ case "number":
797
+ case "int": return "number";
798
+ case "bigint": return "string";
799
+ case "boolean": return "boolean";
800
+ case "date": return "string";
801
+ case "null": return "null";
802
+ case "any":
803
+ case "unknown": return "unknown";
804
+ case "never": return "never";
805
+ case "void":
806
+ case "undefined": return "undefined";
807
+ case "literal": {
808
+ const values = def.values ?? [];
809
+ return values.length > 0 ? values.map(literalType).join(" | ") : "never";
185
810
  }
186
- const requestHeaders = new Headers(headers);
187
- if (config.onRequest) await config.onRequest({
188
- url,
189
- method: route.method,
190
- headers: requestHeaders,
191
- route
192
- });
193
- const res = await (config.fetch ?? fetch)(url, {
194
- method: route.method,
195
- headers: requestHeaders,
196
- body,
197
- credentials: config.credentials,
198
- ...args.fetchOptions
199
- });
200
- const responseHeaders = {};
201
- res.headers.forEach((value, key) => {
202
- responseHeaders[key] = value;
203
- });
204
- const responseSpec = route.responses[res.status];
205
- if (isStreamResponse(responseSpec) && res.body !== null) return {
206
- status: res.status,
207
- body: readStream(res.body, responseSpec),
208
- headers: responseHeaders
209
- };
210
- const text = await res.text();
211
- let parsed;
212
- try {
213
- parsed = text.length > 0 ? JSON.parse(text) : void 0;
214
- } catch {
215
- parsed = text;
811
+ case "enum": {
812
+ const values = Object.values(def.entries ?? {});
813
+ return values.length > 0 ? values.map(literalType).join(" | ") : "never";
216
814
  }
217
- return {
218
- status: res.status,
219
- body: parsed,
220
- headers: responseHeaders
221
- };
222
- };
223
- call[CLIENT_ROUTE] = route;
224
- return call;
225
- };
226
- const readStream = (body, definition) => {
227
- switch (streamMode(definition)) {
228
- case "events": return parseServerSentEvents(body);
229
- case "text": return readTextChunks(body);
230
- case "binary": return readByteChunks(body);
815
+ case "array": return def.element ? `Array<${typeOf(def.element, collector, `${hint}Item`)}>` : "unknown[]";
816
+ case "tuple": {
817
+ const items = (def.items ?? []).map((item, index) => typeOf(item, collector, `${hint}${index}`));
818
+ const rest = def.rest ? [`...Array<${typeOf(def.rest, collector, `${hint}Rest`)}>`] : [];
819
+ return `[${[...items, ...rest].join(", ")}]`;
820
+ }
821
+ case "object": return objectBody(schema, collector, hint);
822
+ case "record": return `Record<string, ${def.valueType ? typeOf(def.valueType, collector, `${hint}Value`) : "unknown"}>`;
823
+ case "union": {
824
+ const options = readDiscriminatedUnion(schema)?.options ?? def.options ?? [];
825
+ if (options.length === 0) return "unknown";
826
+ return options.map((option, index) => typeOf(option, collector, `${hint}${index}`)).join(" | ");
827
+ }
828
+ default: return "unknown";
231
829
  }
232
830
  };
233
- const buildClientTree = (router, config) => {
234
- const result = {};
235
- for (const key of Object.keys(router)) {
236
- const node = router[key];
237
- if (isRouteDefinition(node)) result[key] = buildRouteFn(node, config);
238
- else if (node && typeof node === "object") result[key] = buildClientTree(node, config);
831
+ //#endregion
832
+ //#region src/generator.ts
833
+ const indent = (text, depth = 1) => text.split("\n").map((line) => line.length > 0 ? " ".repeat(depth) + line : line).join("\n");
834
+ const pathParamNames = (path) => [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1] ?? "");
835
+ /**
836
+ * One server-sent event, typed from what the response declares. A record of
837
+ * event name to schema becomes a union discriminated on `event`; a single
838
+ * schema is the only shape a message takes.
839
+ */
840
+ const eventUnion = (stream, collector, namespace) => {
841
+ const frame = "id?: string; retry?: number";
842
+ if (stream && typeof stream === "object" && !("_zod" in stream) && !("_def" in stream)) {
843
+ const arms = Object.entries(stream).map(([event, schema]) => `{ event: '${event}'; data: ${typeOf(schema, collector, `${namespace}${toPascalCase(event)}`)}; ${frame} }`);
844
+ return arms.length > 0 ? arms.join(" | ") : `{ event?: string; data: string; ${frame} }`;
845
+ }
846
+ return `{ event?: string; data: ${typeOf(stream, collector, `${namespace}Message`)}; ${frame} }`;
847
+ };
848
+ const streamBody = (mode, stream, collector, namespace) => {
849
+ if (mode === "binary") return "AsyncIterable<Uint8Array>";
850
+ if (mode === "text") return "AsyncIterable<string>";
851
+ return `AsyncIterable<${eventUnion(stream, collector, namespace)}>`;
852
+ };
853
+ /**
854
+ * The call a route's `@example` shows: the arguments it cannot be called
855
+ * without, filled with values of the shape each schema declares.
856
+ */
857
+ const exampleCall = (routeKey, route) => {
858
+ const entries = [];
859
+ const params = pathParamNames(route.path);
860
+ if (params.length > 0) {
861
+ const shape = route.pathParams ? readObjectShape(route.pathParams) : void 0;
862
+ const fields = params.map((name) => {
863
+ const declared = shape?.[name];
864
+ return `${name}: ${declared ? sampleValue(declared, 0, name) : "'1'"},`;
865
+ });
866
+ entries.push(`params: {\n${indent(fields.join("\n"))}\n},`);
239
867
  }
240
- return result;
868
+ if (route.query && requiresArgument(route.query)) entries.push(`query: ${sampleObject(route.query)},`);
869
+ if (route.body && !isVoidSchema(route.body) && requiresArgument(route.body)) entries.push(`body: ${sampleValue(route.body)},`);
870
+ if (route.headers && requiresArgument(route.headers)) entries.push(`headers: ${sampleObject(route.headers)},`);
871
+ return `const result = await client.${routeKey}(${entries.length > 0 ? `{\n${indent(entries.join("\n"))}\n}` : ""});`;
872
+ };
873
+ /**
874
+ * Whether a schema has anything a caller has to pass, so a route whose query is
875
+ * every-field-optional keeps its example to the call itself.
876
+ */
877
+ const requiresArgument = (schema) => {
878
+ const shape = readObjectShape(schema);
879
+ if (!shape) return true;
880
+ return Object.values(shape).some((field) => !unwrapOptionalWrappers(field).optional);
241
881
  };
242
882
  /**
243
- * Folds the request context headers into `baseHeaders`, so every request
244
- * carries them. An explicit `baseHeaders` entry wins.
883
+ * What an editor shows above a client method: what the route is for, whether it
884
+ * is on its way out, and how it is called.
245
885
  */
246
- const withContextHeaders = (config) => {
247
- const contextHeaders = config.requestContext;
248
- if (!contextHeaders) return config;
886
+ const routeDoc = (routeKey, route) => {
887
+ const lines = [];
888
+ if (route.summary) lines.push(route.summary);
889
+ if (route.description) {
890
+ if (lines.length > 0) lines.push("");
891
+ lines.push(route.description);
892
+ }
893
+ if (route.deprecated !== void 0 && route.deprecated !== false) {
894
+ const message = typeof route.deprecated === "string" ? route.deprecated : typeof route.deprecated === "object" ? route.deprecated.message : void 0;
895
+ if (lines.length > 0) lines.push("");
896
+ lines.push(`@deprecated ${message ?? ""}`.trimEnd());
897
+ }
898
+ if (lines.length > 0) lines.push("");
899
+ lines.push("@example", exampleCall(routeKey, route));
900
+ return docComment(lines);
901
+ };
902
+ const emitRoute = (routeKey, key, route, collector, namespaceName) => {
903
+ const namespace = routeKey.split(".").map(toPascalCase).join("");
904
+ const members = [];
905
+ const args = [];
906
+ const params = pathParamNames(route.path);
907
+ const { pathParams, query, body, headers } = route;
908
+ if (params.length > 0) {
909
+ const paramsType = pathParams ? collector.readingInput(() => typeOf(pathParams, collector, `${namespace}Params`)) : `{\n${indent(params.map((name) => `${name}: string;`).join("\n"))}\n}`;
910
+ members.push(`export type Params = ${paramsType};`);
911
+ args.push(`params: ${namespaceName}.${namespace}.Params`);
912
+ }
913
+ if (query) {
914
+ members.push(`export type Query = ${collector.readingInput(() => typeOf(query, collector, `${namespace}Query`))};`);
915
+ args.push(`query${requiresArgument(query) ? "" : "?"}: ${namespaceName}.${namespace}.Query`);
916
+ }
917
+ if (body && !isVoidSchema(body)) {
918
+ members.push(`export type Body = ${collector.readingInput(() => typeOf(body, collector, `${namespace}Body`))};`);
919
+ args.push(`body: ${namespaceName}.${namespace}.Body`);
920
+ }
921
+ if (headers) {
922
+ members.push(`export type Headers = ${collector.readingInput(() => typeOf(headers, collector, `${namespace}Headers`))};`);
923
+ args.push(`headers${requiresArgument(headers) ? "" : "?"}: ${namespaceName}.${namespace}.Headers`);
924
+ } else args.push("headers?: Record<string, string>");
925
+ args.push("fetchOptions?: RequestInit");
926
+ const validates = route.body !== void 0 || route.query !== void 0;
927
+ const declaredBadRequest = Object.keys(route.responses).includes("400");
928
+ const validationBody = validates ? typeOf(ValidationErrorSchema, collector, "ValidationError") : void 0;
929
+ const results = Object.entries(route.responses).map(([status, response]) => {
930
+ const headers = resolveResponseHeaders(response);
931
+ const headerType = headers ? typeOf(headers, collector, `${namespace}${status}Headers`) : "Record<string, string>";
932
+ if (isStreamResponse(response)) return `{ status: ${status}; body: ${streamBody(streamMode(response), response.stream, collector, `${namespace}${status}`)}; headers: ${headerType} }`;
933
+ const schema = resolveResponseBody(response);
934
+ const body = schema ? typeOf(schema, collector, `${namespace}${status}`) : "undefined";
935
+ return `{ status: ${status}; body: ${status === "400" && validationBody ? `${body} | ${validationBody}` : body}; headers: ${headerType} }`;
936
+ });
937
+ if (validationBody && !declaredBadRequest) results.push(`{ status: 400; body: ${validationBody}; headers: Record<string, string> }`);
938
+ members.push(`export type Result =\n${indent(results.map((result) => `| ${result}`).join("\n"))};`);
939
+ const argsType = `{\n${indent(args.map((arg) => `${arg};`).join("\n"))}\n}`;
940
+ const tableEntries = [`method: '${route.method}'`, `path: '${route.path}'`];
941
+ if (route.contentType) tableEntries.push(`contentType: '${route.contentType}'`);
942
+ const responses = Object.entries(route.responses).map(([status, response]) => isStreamResponse(response) ? `${status}: { stream: true, contentType: '${streamContentType(response)}' }` : `${status}: {}`);
943
+ if (validationBody && !declaredBadRequest) responses.push("400: {}");
944
+ tableEntries.push(`responses: {\n${indent(responses.map((entry) => `${entry},`).join("\n"))}\n}`);
945
+ const streams = Object.values(route.responses).some((response) => isStreamResponse(response));
249
946
  return {
250
- ...config,
251
- baseHeaders: {
252
- ...Object.fromEntries(Object.entries(contextHeaders).filter(([, value]) => value !== void 0)),
253
- ...config.baseHeaders ?? {}
947
+ namespace,
948
+ signature: `${routeDoc(routeKey, route)}${key}: ClientMethod<'${route.method}', ${streams}, ${argsType}, ${namespaceName}.${namespace}.Result>;`,
949
+ declaration: `export namespace ${namespace} {\n${indent(members.join("\n\n"))}\n}`,
950
+ table: `${key}: {\n${indent(tableEntries.map((entry) => `${entry},`).join("\n"))}\n},`
951
+ };
952
+ };
953
+ const isRoute = (value) => !!value && typeof value === "object" && typeof value.method === "string";
954
+ const emitTree = (routes, prefix, collector, namespaceName) => {
955
+ const signatures = [];
956
+ const tables = [];
957
+ const declarations = [];
958
+ for (const key of Object.keys(routes)) {
959
+ const node = routes[key];
960
+ const routeKey = prefix ? `${prefix}.${key}` : key;
961
+ if (isRoute(node)) {
962
+ const emitted = emitRoute(routeKey, key, node, collector, namespaceName);
963
+ signatures.push(emitted.signature);
964
+ tables.push(emitted.table);
965
+ declarations.push(emitted.declaration);
966
+ continue;
967
+ }
968
+ if (node && typeof node === "object") {
969
+ const group = emitTree(node, routeKey, collector, namespaceName);
970
+ signatures.push(`${key}: {\n${indent(group.signatures)}\n};`);
971
+ tables.push(`${key}: {\n${indent(group.table)}\n},`);
972
+ declarations.push(...group.declarations);
254
973
  }
974
+ }
975
+ return {
976
+ signatures: signatures.join("\n"),
977
+ table: tables.join("\n"),
978
+ declarations
255
979
  };
256
980
  };
257
981
  /**
258
- * Builds the client tree a generated client exposes. The generated file owns the
259
- * types; this owns the requests.
982
+ * Renders a TypeScript client from an api: its named types, the route table
983
+ * the runtime reads, and a `createClient` typed against both.
984
+ */
985
+ /**
986
+ * The headers a request context declares, as one interface the caller fills
987
+ * once. Absent when the API declares no request context that reads headers.
988
+ */
989
+ const emitRequestContext = (contract, collector) => {
990
+ const declarations = Object.values(contract.requestContext ?? {});
991
+ const fields = [];
992
+ let required = false;
993
+ for (const declaration of declarations) {
994
+ const headers = declaration.headers;
995
+ if (!headers) continue;
996
+ required ||= requiresArgument(headers);
997
+ const inner = collector.readingInput(() => typeOf(headers, collector, "RequestContext")).trim().replace(/^\{/, "").replace(/\}$/, "").split("\n").map((line) => line.trim()).filter((line) => line !== "").join("\n");
998
+ if (inner !== "") fields.push(inner);
999
+ }
1000
+ if (fields.length === 0) return void 0;
1001
+ return {
1002
+ declaration: `export interface RequestContext {\n${indent(fields.join("\n"))}\n}`,
1003
+ required
1004
+ };
1005
+ };
1006
+ /**
1007
+ * A constructor per brand, so a value from outside the API becomes one with
1008
+ * `toUserId('usr_k7f3q9')` rather than a cast.
1009
+ */
1010
+ const emitBrandConstructors = (collector, namespaceName) => collector.allBrands().map(({ name, base, example }) => `
1011
+ ${docComment([
1012
+ `Brands a value from outside the API, like a URL segment, as \`${namespaceName}.${name}\`. A value from a response is branded already.`,
1013
+ "",
1014
+ "@example",
1015
+ `const id = to${name}(${example});`
1016
+ ])}export const to${name} = (value: ${base}): ${namespaceName}.${name} => value as ${namespaceName}.${name};
1017
+ `).join("");
1018
+ /**
1019
+ * Tells kizuna's validation error from a 400 the route declares itself.
1020
+ */
1021
+ const emitValidationGuard = (namespaceName) => `
1022
+ ${docComment([
1023
+ `Whether a \`400\` body is the validation error kizuna sends, rather than a \`400\` the route declares itself.`,
1024
+ "",
1025
+ "@example",
1026
+ "if (result.status === 400 && isValidationError(result.body)) {",
1027
+ " console.log(result.body.errors);",
1028
+ "}"
1029
+ ])}export const isValidationError = (body: unknown): body is ${namespaceName}.ValidationError =>
1030
+ typeof body === 'object' && body !== null && 'errors' in body && Array.isArray(body.errors);
1031
+ `;
1032
+ /**
1033
+ * Declared in the file, so a brand needs nothing installed.
1034
+ */
1035
+ const BRAND_DECLARATION = `declare const kizunaBrand: unique symbol;
1036
+
1037
+ /**
1038
+ * Tells one branded type from another with the same base.
1039
+ */
1040
+ type KizunaBrand<Name extends string> = {
1041
+ readonly [kizunaBrand]: {
1042
+ readonly [Key in Name]: true;
1043
+ };
1044
+ };
1045
+
1046
+ `;
1047
+ const generateFetchClient = (contract, options = {}) => {
1048
+ const { namespace: namespaceName = "API", regenerateCommand = "kizuna generate", source } = options;
1049
+ const collector = new TypeCollector();
1050
+ const tree = emitTree(listedRoutes(contract), "", collector, namespaceName);
1051
+ const requestContext = emitRequestContext(contract, collector);
1052
+ const api = [...collector.all().map((model) => {
1053
+ return `${model.description ? `/**\n * ${model.description}\n */\n` : ""}export type ${model.name} = ${model.body};`;
1054
+ }), ...tree.declarations].join("\n\n");
1055
+ const brands = emitBrandConstructors(collector, namespaceName);
1056
+ const guards = collector.all().some((model) => model.name === "ValidationError") ? emitValidationGuard(namespaceName) : "";
1057
+ return `/* eslint-disable */
1058
+ /**
1059
+ ${[
1060
+ " * Generated by @kizunajs/fetch. Do not edit.",
1061
+ " *",
1062
+ ...source === void 0 ? [] : [` * Source: ${source}`],
1063
+ ` * Regenerate: ${regenerateCommand}`
1064
+ ].join("\n")}
1065
+ */
1066
+ ${collector.usesBrand() ? BRAND_DECLARATION : ""}export namespace ${namespaceName} {
1067
+ ${indent(api)}
1068
+ }
1069
+
1070
+ export interface Client {
1071
+ ${indent(tree.signatures)}
1072
+ }
1073
+
1074
+ const routes: GeneratedRoutes = {
1075
+ ${indent(tree.table)}
1076
+ };
1077
+ ${brands}${guards}
1078
+ ${requestContext === void 0 ? `/**
1079
+ * A client for this API. Pass the base URL and anything else the runtime takes.
1080
+ */
1081
+ export const createClient = (config: ClientConfig): Client => buildClient(routes, config) as unknown as Client;` : `${requestContext.declaration}
1082
+
1083
+ /**
1084
+ * A client for this API. Pass the base URL, the request context headers this
1085
+ * API declares, and anything else the runtime takes.
1086
+ */
1087
+ export const createClient = (config: ClientConfig & { requestContext${requestContext.required ? "" : "?"}: RequestContext }): Client =>
1088
+ buildClient(routes, config) as unknown as Client;`}
1089
+
1090
+ ${runtimeSource}`;
1091
+ };
1092
+ /**
1093
+ * A TypeScript client for `kizuna.config.ts`.
1094
+ *
1095
+ * @example
1096
+ * fetchClient({
1097
+ * output: './packages/api-client/src/generated.ts',
1098
+ * });
260
1099
  */
261
- const createGeneratedClient = (routes, config) => buildClientTree(routes, withContextHeaders(config));
1100
+ const fetchClient = defineClient({
1101
+ target: "fetch",
1102
+ options: z.object({
1103
+ /**
1104
+ * Name of the generated namespace holding every model and every route's
1105
+ * `Params`, `Query`, `Body`, `Headers` and `Result`.
1106
+ *
1107
+ * @default 'API'
1108
+ */
1109
+ namespace: z.string().optional(),
1110
+ /**
1111
+ * Command the file's header tells a reader to run.
1112
+ *
1113
+ * @default 'kizuna generate'
1114
+ */
1115
+ regenerateCommand: z.string().optional(),
1116
+ /**
1117
+ * Path to the api this was generated from, relative to the generated
1118
+ * file. Named in the header so tooling can tell when the client has fallen
1119
+ * behind, and so a reader knows where the API is declared.
1120
+ */
1121
+ source: z.string().optional()
1122
+ }),
1123
+ generate: ({ options, api }) => ({ finalize: () => generateFetchClient(api, options) })
1124
+ });
262
1125
  //#endregion
263
- export { CLIENT_ROUTE, createGeneratedClient, isProblemDetails, isValidationError, routeOf };
1126
+ export { fetchClient, generateFetchClient };