openapi-typesafe-fetch 1.0.0-rc.2 → 1.0.0-rc.4

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/src/index.js CHANGED
@@ -3,14 +3,16 @@ const PATH_PARAM_RE = /\{[^{}]+\}/g;
3
3
  /**
4
4
  * A `.` or `..` path segment; URLs resolve it, so a parameter value could leave its path (#2483).
5
5
  */
6
- const DOT_SEGMENT_RE = /(^|\/)\.\.?(\/|$)/;
6
+ const DOT_SEGMENT_RE = /^\.\.?$/;
7
7
  /** Where the path of a URL ends: its query or fragment, which have no segments. */
8
8
  const QUERY_OR_FRAGMENT_RE = /[?#]/;
9
9
  /**
10
- * Any JSON media type: `application/json`, `application/problem+json`, with or without
11
- * parameters.
10
+ * A JSON media type: `json` or a `+json` suffix (RFC 6838), as in `application/problem+json`, with
11
+ * or without parameters. Not `x-ndjson`, `jsonl` or `json-seq`: their bodies are lines of JSON.
12
12
  */
13
- const JSON_MEDIA_TYPE_RE = /json/i;
13
+ const JSON_MEDIA_TYPE_RE = /^[^/]+\/([^;]*\+)?json\s*(;|$)/i;
14
+ /** `text/*` media types: a JSON parse error of such a body points to `parseAs: "text"`. */
15
+ const TEXT_MEDIA_TYPE_RE = /^text\//i;
14
16
  /** `application/x-www-form-urlencoded`, with or without parameters such as `charset`. */
15
17
  const FORM_MEDIA_TYPE_RE = /^application\/x-www-form-urlencoded(;|$)/i;
16
18
  /** `multipart/form-data`, with or without parameters. */
@@ -19,6 +21,14 @@ const NESTED_FORM_VALUE_MESSAGE = "Nested form values need your own `bodySeriali
19
21
  /** The `boundary` parameter of a multipart `Content-Type`; only the platform knows its value. */
20
22
  const BOUNDARY_PARAMETER_RE = /;\s*boundary=/i;
21
23
 
24
+ /**
25
+ * Marks the FormData objects the default `bodySerializer` built. Only for them is the boundary the
26
+ * platform's alone, whoever returns them (a `bodySerializer` may wrap the default one). A
27
+ * registered symbol is the same in the CommonJS and ES module builds and in every copy of the
28
+ * package, so a form one of them built is known to the others (ADR-013, decision 10).
29
+ */
30
+ const CLIENT_BUILT_FORM = Symbol.for("openapi-typesafe-fetch/form");
31
+
22
32
  /**
23
33
  * Whether `fetch` is Node.js undici, which takes `requestInitExt` as a second argument. A Node.js
24
34
  * version check is not needed: every supported Node.js (`engines`) ships undici.
@@ -132,14 +142,8 @@ export default function createClient(clientOptions) {
132
142
  headers,
133
143
  params.header,
134
144
  );
135
- // `fetch` sends a FormData as multipart with a boundary only it knows. A `Content-Type` without
136
- // that boundary, set by hand, replaced the platform's, and the server could not split the parts
137
- // (upstream #1214), so it goes and the platform sets its own (ADR-013, decision 10).
138
- if (
139
- serializedBody instanceof FormData &&
140
- !BOUNDARY_PARAMETER_RE.test(finalHeaders.get("Content-Type"))
141
- ) {
142
- finalHeaders.delete("Content-Type");
145
+ if (isPlatformInstance(serializedBody, "FormData")) {
146
+ dropFormContentType(finalHeaders, serializedBody[CLIENT_BUILT_FORM] === true);
143
147
  }
144
148
 
145
149
  // Client level middleware take priority over request-level middleware
@@ -147,6 +151,8 @@ export default function createClient(clientOptions) {
147
151
 
148
152
  const requestInit = {
149
153
  redirect: "follow",
154
+ // The Fetch standard requires `duplex: "half"` (its only value) for a stream body.
155
+ duplex: isStreamBody(serializedBody) ? "half" : undefined,
150
156
  ...baseOptions,
151
157
  ...init,
152
158
  body: serializedBody,
@@ -254,6 +260,10 @@ export default function createClient(clientOptions) {
254
260
  throw errorAfterMiddleware;
255
261
  }
256
262
  }
263
+ // A lookalike from the `fetch` option is rejected as one from middleware is (ADR-025).
264
+ if (!isResponse(response)) {
265
+ throw new Error("fetch: must return new Response()");
266
+ }
257
267
 
258
268
  // middleware (response)
259
269
  // execute in reverse-array order (first priority gets last transform)
@@ -292,39 +302,10 @@ export default function createClient(clientOptions) {
292
302
  return response.ok ? { data: undefined, response } : { error: undefined, response };
293
303
  }
294
304
 
295
- // parse response (falling back to .text() when necessary)
296
305
  if (response.ok) {
297
- const getResponseData = async () => {
298
- // if "stream", skip parsing entirely
299
- if (parseAs === "stream") {
300
- return response.body;
301
- }
302
-
303
- if (parseAs === "json" && !contentLength) {
304
- // use text() when no content-length is provided to avoid errors parsing empty bodies
305
- // (200 with no content)
306
- const raw = await response.text();
307
- return raw ? JSON.parse(raw) : undefined;
308
- }
309
-
310
- return await response[parseAs]();
311
- };
312
- return { data: await getResponseData(), response };
313
- }
314
-
315
- // handle errors (use text() when no content-length to safely handle empty bodies from proxies)
316
- const raw = await response.text();
317
- if (!raw) {
318
- // empty error body - return undefined to be consistent with status 204 handling
319
- return { error: undefined, response };
306
+ return { data: await readSuccessBody(response, parseAs), response };
320
307
  }
321
- let error = raw;
322
- try {
323
- error = JSON.parse(raw); // attempt to parse as JSON
324
- } catch {
325
- // noop - keep as raw text
326
- }
327
- return { error, response };
308
+ return { error: await readErrorBody(response), response };
328
309
  }
329
310
 
330
311
  return {
@@ -477,6 +458,18 @@ export function createPathBasedClient(clientOptions) {
477
458
 
478
459
  // utils
479
460
 
461
+ /**
462
+ * `fetch` sends a FormData as multipart with a boundary only it knows, so a `Content-Type` set by
463
+ * hand replaced the platform's and the server could not split the parts (upstream #1214). It goes,
464
+ * and the platform sets its own, unless the user built the FormData and named a boundary for a
465
+ * `fetch` of their own (ADR-013, decision 10).
466
+ */
467
+ function dropFormContentType(headers, isClientBuilt) {
468
+ if (isClientBuilt || !BOUNDARY_PARAMETER_RE.test(headers.get("Content-Type"))) {
469
+ headers.delete("Content-Type");
470
+ }
471
+ }
472
+
480
473
  // Fetch API objects are recognized by the members the client uses, not by `instanceof`: that is
481
474
  // bound to one realm's class, and a Request from the `undici` package, another realm (an iframe,
482
475
  // an Electron host) or a custom `Request` option is not an instance of it (upstream #1847). The
@@ -493,17 +486,93 @@ function isRequest(value) {
493
486
  }
494
487
 
495
488
  function isResponse(value) {
496
- return typeof value?.status === "number" && isHeaders(value.headers);
489
+ return (
490
+ typeof value?.ok === "boolean" &&
491
+ typeof value.status === "number" &&
492
+ typeof value.text === "function" &&
493
+ isHeaders(value.headers)
494
+ );
497
495
  }
498
496
 
499
- // Parameter names and object keys can be data (an `additionalProperties` object). They are encoded
500
- // like values, except for characters common in names that do not split a URL (ADR-013, decision 9).
497
+ /**
498
+ * Parse a JSON body. A body that is not JSON, such as the HTML page of a proxy, threw a bare
499
+ * `SyntaxError`; this one names the response and says which `parseAs` reads it (ADR-041). It holds
500
+ * no body text, and so no `cause`: the parser's message quotes the body, and a body such as a
501
+ * form-encoded OAuth token answer would carry a secret into logs and error trackers.
502
+ */
503
+ function parseJSON(raw, response) {
504
+ try {
505
+ return JSON.parse(raw);
506
+ } catch {
507
+ const contentType = response.headers.get("Content-Type");
508
+ const hint = TEXT_MEDIA_TYPE_RE.test(contentType) ? 'set `parseAs: "text"`' : "set `parseAs`";
509
+ const subject = `Response ${response.status} (${contentType ?? "no Content-Type"})`;
510
+ throw new SyntaxError(`${subject} is not JSON (${raw.length} characters); ${hint}`);
511
+ }
512
+ }
513
+
514
+ /** The data of a success response, by `parseAs` (default `"json"`, as in openapi-fetch). */
515
+ async function readSuccessBody(response, parseAs) {
516
+ if (parseAs === "stream") {
517
+ return response.body;
518
+ }
519
+ if (parseAs !== "json") {
520
+ return response[parseAs]();
521
+ }
522
+ // text(), not json(): an empty body (no Content-Length) is no data, and the text names a failure.
523
+ const raw = await response.text();
524
+ return raw ? parseJSON(raw, response) : undefined;
525
+ }
526
+
527
+ /**
528
+ * The error of an error response: `undefined` for an empty body, else JSON. A body that is not
529
+ * JSON (a proxy's HTML page) stays text, as in openapi-fetch.
530
+ */
531
+ async function readErrorBody(response) {
532
+ const raw = await response.text();
533
+ if (!raw) {
534
+ return undefined;
535
+ }
536
+ try {
537
+ return JSON.parse(raw);
538
+ } catch {
539
+ // Deliberate fallback, not a lost failure: the caller gets the body as text in `error`.
540
+ return raw;
541
+ }
542
+ }
543
+
544
+ // Parameter names can be data (the keys of a free-form query). They are encoded like values,
545
+ // except for characters common in the names a schema declares (`filter[status]`, `$filter`) that
546
+ // do not split a URL (ADR-013, decision 9). Object keys are always data, so they are encoded as
547
+ // values are, with no exceptions: a `,` or `]` in a key added members for the server.
501
548
  const KEPT_NAME_ESCAPES = /%(?:5B|5D|24|3A|40|2C)/g;
502
549
 
503
550
  function encodeName(name) {
504
551
  return encodeURIComponent(name).replace(KEPT_NAME_ESCAPES, decodeURIComponent);
505
552
  }
506
553
 
554
+ /**
555
+ * A `Date` value. Checked by its method, not with `instanceof`, so a Date from another realm counts
556
+ * too (as for the Fetch API objects above).
557
+ */
558
+ function isDate(value) {
559
+ return typeof value?.toISOString === "function";
560
+ }
561
+
562
+ /**
563
+ * A parameter or form value as it is sent: a `Date` as ISO 8601, because `String(date)` is a
564
+ * local-time text such as "Thu Jan 01 1970 ..." (ADR-041); any other value as it is.
565
+ */
566
+ function valueText(value) {
567
+ return isDate(value) ? value.toISOString() : value;
568
+ }
569
+
570
+ /** One parameter value (or object key), percent-encoded unless `allowReserved`. */
571
+ function encodeValue(value, allowReserved) {
572
+ const text = valueText(value);
573
+ return allowReserved === true ? text : encodeURIComponent(text);
574
+ }
575
+
507
576
  /**
508
577
  * Serialize primitive param values
509
578
  * @type {import("./index.js").serializePrimitiveParam}
@@ -512,118 +581,136 @@ export function serializePrimitiveParam(name, value, options) {
512
581
  if (value === undefined || value === null) {
513
582
  return "";
514
583
  }
515
- if (typeof value === "object") {
584
+ if (typeof value === "object" && !isDate(value)) {
516
585
  throw new Error(
517
586
  "Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.",
518
587
  );
519
588
  }
520
- return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
589
+ return `${name}=${encodeValue(value, options?.allowReserved)}`;
590
+ }
591
+
592
+ /** Join exploded parts: by `,`, `.` or `;` in a path style (label and matrix also first), else `&`. */
593
+ function joinExploded(values, style) {
594
+ const joiner = { simple: ",", label: ".", matrix: ";" }[style] || "&";
595
+ const final = values.join(joiner);
596
+ return style === "label" || style === "matrix" ? `${joiner}${final}` : final;
597
+ }
598
+
599
+ /** A non-exploded object: names and values in one comma-separated list. */
600
+ function serializeUnexplodedObject(name, value, options) {
601
+ const values = [];
602
+ for (const k in value) {
603
+ values.push(encodeValue(k), encodeValue(value[k], options.allowReserved));
604
+ }
605
+ const final = values.join(",");
606
+ switch (options.style) {
607
+ case "form": {
608
+ return `${name}=${final}`;
609
+ }
610
+ case "label": {
611
+ return `.${final}`;
612
+ }
613
+ case "matrix": {
614
+ return `;${name}=${final}`;
615
+ }
616
+ default: {
617
+ return final;
618
+ }
619
+ }
521
620
  }
522
621
 
523
622
  /**
524
- * Serialize object param (shallow only)
623
+ * Serialize object param (shallow only). An object without members, or with only `null` and
624
+ * `undefined` ones when exploded, gives `""`: its empty parts added stray separators (ADR-041).
525
625
  * @type {import("./index.js").serializeObjectParam}
526
626
  */
527
- // biome-ignore lint/complexity/noExcessiveLinesPerFunction: inherited, kept until 1.1 (ADR-036)
528
627
  export function serializeObjectParam(name, value, options) {
529
- if (!value || typeof value !== "object") {
628
+ if (!value || typeof value !== "object" || !Object.keys(value).length) {
530
629
  return "";
531
630
  }
532
- const values = [];
533
- const joiner =
534
- {
535
- simple: ",",
536
- label: ".",
537
- matrix: ";",
538
- }[options.style] || "&";
539
-
540
- // explode: false
541
631
  if (options.style !== "deepObject" && options.explode === false) {
542
- for (const k in value) {
543
- values.push(
544
- encodeName(k),
545
- options.allowReserved === true ? value[k] : encodeURIComponent(value[k]),
546
- );
547
- }
548
- // note: values are always joined by comma in explode: false (but joiner can prefix)
549
- const final = values.join(",");
550
- switch (options.style) {
551
- case "form": {
552
- return `${name}=${final}`;
553
- }
554
- case "label": {
555
- return `.${final}`;
556
- }
557
- case "matrix": {
558
- return `;${name}=${final}`;
559
- }
560
- default: {
561
- return final;
562
- }
632
+ return serializeUnexplodedObject(name, value, options);
633
+ }
634
+ const values = [];
635
+ for (const k in value) {
636
+ const key = encodeValue(k);
637
+ const finalName = options.style === "deepObject" ? `${name}[${key}]` : key;
638
+ if (value[k] != null) {
639
+ values.push(serializePrimitiveParam(finalName, value[k], options));
563
640
  }
564
641
  }
642
+ return values.length ? joinExploded(values, options.style) : "";
643
+ }
565
644
 
566
- // explode: true
567
- for (const k in value) {
568
- const finalName = options.style === "deepObject" ? `${name}[${encodeName(k)}]` : encodeName(k);
569
- values.push(serializePrimitiveParam(finalName, value[k], options));
645
+ /** A non-exploded array; the item separator depends on the style. */
646
+ function serializeUnexplodedArray(name, value, options) {
647
+ const joiner = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[options.style] || ",";
648
+ const final = value.map((v) => encodeValue(v, options.allowReserved)).join(joiner);
649
+ switch (options.style) {
650
+ case "simple": {
651
+ return final;
652
+ }
653
+ case "label": {
654
+ return `.${final}`;
655
+ }
656
+ case "matrix": {
657
+ return `;${name}=${final}`;
658
+ }
659
+ default: {
660
+ // form, spaceDelimited, pipeDelimited
661
+ return `${name}=${final}`;
662
+ }
570
663
  }
571
- const final = values.join(joiner);
572
- return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
573
664
  }
574
665
 
575
666
  /**
576
- * Serialize array param (shallow only)
667
+ * Serialize array param (shallow only). An empty array gives `""`, and so does an exploded
668
+ * `form` array of only `null` and `undefined` items (ADR-041).
577
669
  * @type {import("./index.js").serializeArrayParam}
578
670
  */
579
- // biome-ignore lint/complexity/noExcessiveLinesPerFunction: inherited, kept until 1.1 (ADR-036)
580
671
  export function serializeArrayParam(name, value, options) {
581
- if (!Array.isArray(value)) {
672
+ if (!Array.isArray(value) || !value.length) {
582
673
  return "";
583
674
  }
584
-
585
- // explode: false
586
675
  if (options.explode === false) {
587
- // note: for arrays, joiners vary wildly based on style + explode behavior
588
- const joiner = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[options.style] || ",";
589
- const final = (
590
- options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))
591
- ).join(joiner);
592
- switch (options.style) {
593
- case "simple": {
594
- return final;
595
- }
596
- case "label": {
597
- return `.${final}`;
598
- }
599
- case "matrix": {
600
- return `;${name}=${final}`;
601
- }
602
- // case "spaceDelimited":
603
- // case "pipeDelimited":
604
- default: {
605
- return `${name}=${final}`;
606
- }
607
- }
676
+ return serializeUnexplodedArray(name, value, options);
608
677
  }
609
-
610
- // explode: true
611
- const joiner = { simple: ",", label: ".", matrix: ";" }[options.style] || "&";
612
678
  const values = [];
613
679
  for (const v of value) {
614
680
  if (options.style === "simple" || options.style === "label") {
615
- values.push(options.allowReserved === true ? v : encodeURIComponent(v));
616
- } else {
681
+ values.push(encodeValue(v, options.allowReserved));
682
+ } else if (v != null) {
617
683
  values.push(serializePrimitiveParam(name, v, options));
618
684
  }
619
685
  }
620
- return options.style === "label" || options.style === "matrix"
621
- ? `${joiner}${values.join(joiner)}`
622
- : values.join(joiner);
686
+ return values.length ? joinExploded(values, options.style) : "";
687
+ }
688
+
689
+ /** One query parameter with the default styles: `form` arrays, `deepObject` objects. */
690
+ function serializeQueryParam(name, value, options) {
691
+ const allowReserved = options?.allowReserved || false;
692
+ if (Array.isArray(value)) {
693
+ return serializeArrayParam(name, value, {
694
+ style: "form",
695
+ explode: true,
696
+ ...options?.array,
697
+ allowReserved,
698
+ });
699
+ }
700
+ if (value && typeof value === "object" && !isDate(value)) {
701
+ return serializeObjectParam(name, value, {
702
+ style: "deepObject",
703
+ explode: true,
704
+ ...options?.object,
705
+ allowReserved,
706
+ });
707
+ }
708
+ return serializePrimitiveParam(name, value, options);
623
709
  }
624
710
 
625
711
  /**
626
- * Serialize query params to string
712
+ * Serialize query params to string. A parameter that serializes to nothing (`null`, an empty
713
+ * array or object) is left out with its `&`; an empty part made `a=1&&b=2` (ADR-041).
627
714
  * @type {import("./index.js").createQuerySerializer}
628
715
  */
629
716
  export function createQuerySerializer(options) {
@@ -631,37 +718,10 @@ export function createQuerySerializer(options) {
631
718
  const search = [];
632
719
  if (queryParams && typeof queryParams === "object") {
633
720
  for (const key in queryParams) {
634
- const value = queryParams[key];
635
- const name = encodeName(key);
636
- if (value === undefined || value === null) {
637
- continue;
721
+ const part = serializeQueryParam(encodeName(key), queryParams[key], options);
722
+ if (part) {
723
+ search.push(part);
638
724
  }
639
- if (Array.isArray(value)) {
640
- if (value.length === 0) {
641
- continue;
642
- }
643
- search.push(
644
- serializeArrayParam(name, value, {
645
- style: "form",
646
- explode: true,
647
- ...options?.array,
648
- allowReserved: options?.allowReserved || false,
649
- }),
650
- );
651
- continue;
652
- }
653
- if (typeof value === "object") {
654
- search.push(
655
- serializeObjectParam(name, value, {
656
- style: "deepObject",
657
- explode: true,
658
- ...options?.object,
659
- allowReserved: options?.allowReserved || false,
660
- }),
661
- );
662
- continue;
663
- }
664
- search.push(serializePrimitiveParam(name, value, options));
665
725
  }
666
726
  }
667
727
  return search.join("&");
@@ -673,10 +733,13 @@ export function createQuerySerializer(options) {
673
733
  * @type {import("./index.js").defaultPathSerializer}
674
734
  * @see https://swagger.io/docs/specification/serialization/#path
675
735
  */
676
- // biome-ignore lint/complexity/noExcessiveLinesPerFunction: inherited, kept until 1.1 (ADR-036)
677
736
  export function defaultPathSerializer(pathname, pathParams) {
737
+ const matches = pathname.match(PATH_PARAM_RE);
738
+ if (!matches) {
739
+ return pathname;
740
+ }
678
741
  let nextURL = pathname;
679
- for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
742
+ for (const match of matches) {
680
743
  let name = match.substring(1, match.length - 1);
681
744
  let explode = false;
682
745
  let style = "simple";
@@ -698,50 +761,105 @@ export function defaultPathSerializer(pathname, pathParams) {
698
761
  let serialized;
699
762
  if (Array.isArray(value)) {
700
763
  serialized = serializeArrayParam(name, value, { style, explode });
701
- } else if (typeof value === "object") {
764
+ } else if (typeof value === "object" && !isDate(value)) {
702
765
  serialized = serializeObjectParam(name, value, { style, explode });
703
766
  } else if (style === "matrix") {
704
767
  serialized = `;${serializePrimitiveParam(name, value)}`;
705
768
  } else {
706
- serialized = style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value);
769
+ serialized = style === "label" ? `.${encodeValue(value)}` : encodeValue(value);
707
770
  }
708
771
  // A function: a string replacement reads `$'`, `$&` and the like, which object keys keep.
709
772
  nextURL = nextURL.replace(match, () => serialized);
710
773
  }
711
- const path = nextURL.split(QUERY_OR_FRAGMENT_RE, 1)[0];
774
+ checkSerializedPath(pathname, nextURL);
775
+ return nextURL;
776
+ }
777
+
778
+ /**
779
+ * Throw when the path parameters moved the request. Only the path part (before `?` or `#`) from the
780
+ * segment of the first parameter on is checked: the text before it is the `baseUrl` and the
781
+ * template, which no value changes, and a protocol-relative base (`//api.example/v1`) is valid.
782
+ * Values are percent-encoded, so they add no `/` and segment `i` of the URL comes from segment `i`
783
+ * of the template. The message names that template segment, never the URL: the `baseUrl` and the
784
+ * values may carry secrets (a token in the path, credentials in the base), and errors reach logs
785
+ * (ADR-041).
786
+ */
787
+ function checkSerializedPath(template, url) {
788
+ const fixed = template.slice(0, template.search(PATH_PARAM_RE));
789
+ const path = url.split(QUERY_OR_FRAGMENT_RE, 1)[0];
790
+ const first = fixed.split("/").length - 1;
712
791
  // `encodeURIComponent` keeps dots, so a value `..` would move the request up a path level
713
792
  // (ADR-013).
714
- // Only the path is checked: before a query (`/a/{id}?v=2`), `$` did not match after `..`.
715
- if (DOT_SEGMENT_RE.test(path)) {
716
- throw new Error(`Dot path segment in ${nextURL}`);
793
+ let index = path
794
+ .split("/")
795
+ .findIndex((segment, at) => at >= first && DOT_SEGMENT_RE.test(segment));
796
+ let problem = "Dot";
797
+ // `//host/…` is a protocol-relative URL: with a relative baseUrl a browser sends it to that host
798
+ // (ADR-030).
799
+ if (index === -1 && path.startsWith("//") && !fixed.startsWith("//")) {
800
+ [index, problem] = [1, "Empty first"];
717
801
  }
718
- // `//host/…` is a protocol-relative URL: with a relative baseUrl a browser sends it to that
719
- // host.
720
- if (path.startsWith("//")) {
721
- throw new Error(`Empty first path segment in ${nextURL}`);
802
+ if (index !== -1) {
803
+ const name = template.split(QUERY_OR_FRAGMENT_RE, 1)[0].split("/")[index];
804
+ throw new Error(`${problem} path segment in "${name}"`);
722
805
  }
723
- return nextURL;
806
+ }
807
+
808
+ /**
809
+ * Whether a value is an instance of the platform class `name`. A runtime may lack the class (React
810
+ * Native has no `ReadableStream`); then no value is one, and the check does not throw.
811
+ */
812
+ function isPlatformInstance(value, name) {
813
+ const type = globalThis[name];
814
+ return typeof type === "function" && value instanceof type;
815
+ }
816
+
817
+ /**
818
+ * A stream body: a `ReadableStream`, or an async iterable such as a Node.js `Readable`, which
819
+ * `fetch` in Node.js, Deno and Bun also streams. Both need `duplex: "half"` (ADR-013, decision 6).
820
+ */
821
+ function isStreamBody(body) {
822
+ return (
823
+ isPlatformInstance(body, "ReadableStream") || typeof body?.[Symbol.asyncIterator] === "function"
824
+ );
724
825
  }
725
826
 
726
827
  /**
727
828
  * Bodies `fetch` sends as they are, with their own `Content-Type` (FormData, Blob, URLSearchParams)
728
- * or none. JSON-encoding a Blob or an ArrayBuffer sent `{}` (ADR-013, decision 6).
829
+ * or none. JSON-encoding a Blob, an ArrayBuffer or a stream sent `{}` (ADR-013, decision 6).
729
830
  */
730
831
  function isRawBody(body) {
731
832
  return (
732
- body instanceof FormData ||
733
- body instanceof Blob ||
734
- body instanceof URLSearchParams ||
735
- body instanceof ArrayBuffer ||
736
- ArrayBuffer.isView(body)
833
+ ["FormData", "Blob", "URLSearchParams", "ArrayBuffer"].some((name) =>
834
+ isPlatformInstance(body, name),
835
+ ) ||
836
+ ArrayBuffer.isView(body) ||
837
+ isStreamBody(body)
737
838
  );
738
839
  }
739
840
 
740
841
  /**
741
- * A form body. A nested object has no standard form encoding (servers read `a[b]`, `a.b` or JSON),
742
- * and `URLSearchParams` wrote it as `[object Object]` (ADR-013, decision 7). `null` and `undefined`
743
- * fields are left out, as in a multipart body; `URLSearchParams` sent them as the text "null" and
744
- * "undefined" (ADR-030). A string or a list of pairs is form data already.
842
+ * Whether a form item is nested: an object or an array, which form encodings cannot hold. A `Date`
843
+ * is not. A field holds one level of array, so its items are checked, not the field.
844
+ */
845
+ function isNestedFormValue(value) {
846
+ return value && typeof value === "object" && !isDate(value);
847
+ }
848
+
849
+ /**
850
+ * The items of a form field: the items of an array, with a hole as `undefined` (`flat()` dropped
851
+ * holes, while `null` and `undefined` items stayed), or the value alone.
852
+ */
853
+ function formItems(value) {
854
+ return Array.isArray(value) ? Array.from(value) : [value];
855
+ }
856
+
857
+ /**
858
+ * A form body. A nested object or array, also as an array item, has no standard form encoding
859
+ * (servers read `a[b]`, `a.b` or JSON), and `URLSearchParams` wrote it as `[object Object]` or
860
+ * flattened it (ADR-013, decision 7). `null` and `undefined` fields are left out, as in a multipart
861
+ * body; `URLSearchParams` sent them as the text "null" and "undefined" (ADR-030). A string or a
862
+ * list of pairs is form data already.
745
863
  */
746
864
  function formBody(body) {
747
865
  if (!body || typeof body !== "object" || Array.isArray(body)) {
@@ -749,11 +867,13 @@ function formBody(body) {
749
867
  }
750
868
  const form = new URLSearchParams();
751
869
  for (const [name, value] of Object.entries(body)) {
752
- if (value && typeof value === "object" && !Array.isArray(value)) {
870
+ const items = formItems(value);
871
+ if (items.some(isNestedFormValue)) {
753
872
  throw new Error(NESTED_FORM_VALUE_MESSAGE);
754
873
  }
755
874
  if (value != null) {
756
- form.append(name, value);
875
+ // An array is one comma-separated value, as `URLSearchParams` writes it.
876
+ form.append(name, items.map(valueText).join(","));
757
877
  }
758
878
  }
759
879
  return form.toString();
@@ -762,19 +882,21 @@ function formBody(body) {
762
882
  /**
763
883
  * A `multipart/form-data` body: one part per field, one per item of an array. A `Blob` (or `File`)
764
884
  * is a file part, other primitives are text, `null` and `undefined` are left out. A nested object
765
- * would need a part content type such as JSON, which the client does not guess (ADR-013,
766
- * decision 10).
885
+ * or array would need a part content type such as JSON, which the client does not guess (ADR-013,
886
+ * decision 10). The FormData is marked as the client's, so its `Content-Type` is the platform's.
887
+ * A symbol key is not a form field, and `Object.keys` and JSON leave it out.
767
888
  */
768
889
  function multipartBody(body) {
769
890
  const formData = new FormData();
891
+ formData[CLIENT_BUILT_FORM] = true;
770
892
  for (const [name, value] of Object.entries(body)) {
771
- for (const item of [value].flat()) {
772
- if (item instanceof Blob) {
893
+ for (const item of formItems(value)) {
894
+ if (isPlatformInstance(item, "Blob")) {
773
895
  formData.append(name, item);
774
- } else if (item && typeof item === "object") {
896
+ } else if (isNestedFormValue(item)) {
775
897
  throw new Error(NESTED_FORM_VALUE_MESSAGE);
776
898
  } else if (item != null) {
777
- formData.append(name, String(item));
899
+ formData.append(name, String(valueText(item)));
778
900
  }
779
901
  }
780
902
  }