@venizia/ignis-helpers 0.4.8 → 0.5.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/esm/common/constants/http.d.ts +3 -0
  2. package/dist/esm/common/constants/http.js +3 -0
  3. package/dist/esm/common/constants/http.js.map +1 -1
  4. package/dist/esm/common/redact.js +2 -0
  5. package/dist/esm/common/redact.js.map +1 -1
  6. package/dist/esm/core.d.ts +5 -2
  7. package/dist/esm/core.js +5 -2
  8. package/dist/esm/core.js.map +1 -1
  9. package/dist/esm/modules/network/http-request/base-network-request.helper.d.ts +5 -0
  10. package/dist/esm/modules/network/http-request/base-network-request.helper.js +14 -17
  11. package/dist/esm/modules/network/http-request/base-network-request.helper.js.map +1 -1
  12. package/dist/esm/modules/network/http-request/common/constants.d.ts +2 -1
  13. package/dist/esm/modules/network/http-request/common/constants.js +2 -1
  14. package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
  15. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +37 -11
  16. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +181 -38
  17. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  18. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +204 -18
  19. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +433 -13
  20. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  21. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.d.ts +36 -0
  22. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js +119 -0
  23. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js.map +1 -0
  24. package/dist/esm/modules/network/http-request/fetcher/common/errors.d.ts +40 -0
  25. package/dist/esm/modules/network/http-request/fetcher/common/errors.js +37 -0
  26. package/dist/esm/modules/network/http-request/fetcher/common/errors.js.map +1 -0
  27. package/dist/esm/modules/network/http-request/fetcher/common/guard.d.ts +27 -0
  28. package/dist/esm/modules/network/http-request/fetcher/common/guard.js +2 -0
  29. package/dist/esm/modules/network/http-request/fetcher/common/guard.js.map +1 -0
  30. package/dist/esm/modules/network/http-request/fetcher/common/index.d.ts +6 -0
  31. package/dist/esm/modules/network/http-request/fetcher/common/index.js +6 -0
  32. package/dist/esm/modules/network/http-request/fetcher/common/index.js.map +1 -1
  33. package/dist/esm/modules/network/http-request/fetcher/common/request-context.d.ts +15 -0
  34. package/dist/esm/modules/network/http-request/fetcher/common/request-context.js +11 -0
  35. package/dist/esm/modules/network/http-request/fetcher/common/request-context.js.map +1 -0
  36. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.d.ts +9 -0
  37. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js +14 -0
  38. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js.map +1 -0
  39. package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +65 -1
  40. package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
  41. package/dist/esm/modules/network/http-request/fetcher/common/utilities.d.ts +68 -0
  42. package/dist/esm/modules/network/http-request/fetcher/common/utilities.js +143 -0
  43. package/dist/esm/modules/network/http-request/fetcher/common/utilities.js.map +1 -0
  44. package/dist/esm/modules/network/http-request/fetcher/index.d.ts +2 -1
  45. package/dist/esm/modules/network/http-request/fetcher/index.js +2 -1
  46. package/dist/esm/modules/network/http-request/fetcher/index.js.map +1 -1
  47. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.d.ts +83 -0
  48. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js +221 -0
  49. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js.map +1 -0
  50. package/dist/esm/modules/network/utilities/index.d.ts +1 -0
  51. package/dist/esm/modules/network/utilities/index.js +1 -0
  52. package/dist/esm/modules/network/utilities/index.js.map +1 -1
  53. package/dist/esm/modules/network/utilities/query-string.d.ts +6 -23
  54. package/dist/esm/modules/network/utilities/query-string.js +3 -17
  55. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  56. package/dist/esm/modules/network/utilities/url-builder.d.ts +39 -0
  57. package/dist/esm/modules/network/utilities/url-builder.js +102 -0
  58. package/dist/esm/modules/network/utilities/url-builder.js.map +1 -0
  59. package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -3
  60. package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
  61. package/dist/esm/modules/network/utilities/url-safety/common/errors.d.ts +38 -0
  62. package/dist/esm/modules/network/utilities/url-safety/common/errors.js +33 -1
  63. package/dist/esm/modules/network/utilities/url-safety/common/errors.js.map +1 -1
  64. package/dist/esm/modules/network/utilities/url-safety/common/types.d.ts +26 -3
  65. package/dist/esm/modules/network/utilities/url-safety/common/types.js.map +1 -1
  66. package/dist/esm/modules/network/utilities/url-safety/guard.d.ts +46 -0
  67. package/dist/esm/modules/network/utilities/url-safety/guard.js +145 -0
  68. package/dist/esm/modules/network/utilities/url-safety/guard.js.map +1 -0
  69. package/dist/esm/modules/network/utilities/url-safety/index.d.ts +1 -1
  70. package/dist/esm/modules/network/utilities/url-safety/index.js +1 -1
  71. package/dist/esm/modules/network/utilities/url-safety/index.js.map +1 -1
  72. package/dist/esm/modules/network/utilities/url-safety/policy.d.ts +52 -2
  73. package/dist/esm/modules/network/utilities/url-safety/policy.js +161 -14
  74. package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
  75. package/dist/esm/modules/queue/bullmq/helper.d.ts +43 -7
  76. package/dist/esm/modules/queue/bullmq/helper.js +70 -2
  77. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  78. package/dist/esm/modules/retry/helper.d.ts +3 -1
  79. package/dist/esm/modules/retry/helper.js +8 -4
  80. package/dist/esm/modules/retry/helper.js.map +1 -1
  81. package/package.json +3 -3
  82. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +0 -41
  83. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +0 -111
  84. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +0 -1
  85. package/dist/esm/modules/network/utilities/url-safety/ingest.d.ts +0 -95
  86. package/dist/esm/modules/network/utilities/url-safety/ingest.js +0 -328
  87. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +0 -1
@@ -0,0 +1,143 @@
1
+ import { HTTP } from '../../../../../common/constants/http.js';
2
+ import { UrlFetchError, UrlSafetyRefusals, } from '../../../utilities/url-safety/common/errors.js';
3
+ import { FetchSchemaError } from './errors.js';
4
+ /** Header maps: merged per header, the call winning, a `null` or `undefined` value removing a header. */
5
+ export class FetchHeaders {
6
+ /** The headers of `layers` in order, later layers over earlier ones, as one `Headers`. */
7
+ static merge(opts) {
8
+ const merged = new Headers();
9
+ for (const layer of opts.layers) {
10
+ if (layer === undefined) {
11
+ continue;
12
+ }
13
+ if (layer instanceof Headers) {
14
+ layer.forEach((value, name) => merged.set(name, value));
15
+ continue;
16
+ }
17
+ for (const [name, value] of Object.entries(layer)) {
18
+ if (value === null || value === undefined) {
19
+ merged.delete(name);
20
+ }
21
+ else {
22
+ merged.set(name, value);
23
+ }
24
+ }
25
+ }
26
+ return merged;
27
+ }
28
+ /** `merge` under a JSON content type: the layers may replace it (any case) or remove it with `null`. */
29
+ static withJsonDefault(opts) {
30
+ return FetchHeaders.merge({
31
+ layers: [
32
+ { [HTTP.Headers.CONTENT_TYPE]: HTTP.HeaderValues.APPLICATION_JSON_UTF8 },
33
+ ...opts.layers,
34
+ ],
35
+ });
36
+ }
37
+ /** A copy of `headers` keeping only the names in `names`. */
38
+ static only(opts) {
39
+ const kept = new Headers();
40
+ opts.headers.forEach((value, name) => {
41
+ if (opts.names.includes(name.toLowerCase())) {
42
+ kept.set(name, value);
43
+ }
44
+ });
45
+ return kept;
46
+ }
47
+ /** A copy of `headers` without the names in `names`. */
48
+ static without(opts) {
49
+ const kept = new Headers();
50
+ opts.headers.forEach((value, name) => {
51
+ if (!opts.names.includes(name.toLowerCase())) {
52
+ kept.set(name, value);
53
+ }
54
+ });
55
+ return kept;
56
+ }
57
+ }
58
+ /** Which statuses a fetcher takes as an answer. */
59
+ export class FetchStatus {
60
+ /** Whether `status` is 2xx. */
61
+ static isSuccess(opts) {
62
+ return Math.floor(opts.status / 100) === 2;
63
+ }
64
+ /** The one place `acceptStatus` becomes a decision: a list adds to 2xx, a function replaces it, unset is 2xx. */
65
+ static toPredicate(opts) {
66
+ const { accept } = opts;
67
+ if (typeof accept === 'function') {
68
+ return accept;
69
+ }
70
+ const extra = new Set(accept);
71
+ return (status) => FetchStatus.isSuccess({ status }) || extra.has(status);
72
+ }
73
+ }
74
+ /** The statuses that name a new location; a 304 or a 300 is an answer, not a redirect. */
75
+ const REDIRECT_STATUSES = [301, 302, 303, 307, 308];
76
+ /** The redirect rules of a fetcher that walks redirects by hand. */
77
+ export class FetchRedirects {
78
+ /** Request headers that name the body; they go when a redirect turns the request into a GET. */
79
+ static { this.BODY_HEADERS = [
80
+ HTTP.Headers.CONTENT_TYPE,
81
+ HTTP.Headers.CONTENT_LENGTH,
82
+ HTTP.Headers.CONTENT_ENCODING,
83
+ ]; }
84
+ /**
85
+ * The only caller headers a cross-origin redirect keeps. Every other one is dropped: a tenant's webhook secret
86
+ * (`x-api-key`, a signature) must not follow a redirect to a host that tenant did not name.
87
+ */
88
+ static { this.CROSS_ORIGIN_HEADERS = [
89
+ HTTP.Headers.ACCEPT,
90
+ HTTP.Headers.ACCEPT_LANGUAGE,
91
+ HTTP.Headers.USER_AGENT,
92
+ ]; }
93
+ static isRedirect(opts) {
94
+ return REDIRECT_STATUSES.includes(opts.status);
95
+ }
96
+ /** 303, and a POST answered 301 or 302, continue as a GET without the body. */
97
+ static becomesGet(opts) {
98
+ return (opts.status === 303 ||
99
+ ((opts.status === 301 || opts.status === 302) && opts.method === 'POST'));
100
+ }
101
+ }
102
+ /** What a retried call retries, and for how long a server asks it to wait. */
103
+ export class FetchRetry {
104
+ /** The longest wait a call takes between two attempts unless `backoff.maxDelayMs` says otherwise; the retry helper's own default. */
105
+ static { this.DEFAULT_MAX_DELAY_MS = 30_000; }
106
+ /**
107
+ * The default decision: a network error, a timeout, a 5xx and a 429 are worth another attempt. Any other 4xx, a 3xx, a
108
+ * url the guard refused (refused forever), a schema mismatch and a caller's own abort are not.
109
+ */
110
+ static isRetryable(opts) {
111
+ const { error, signal } = opts;
112
+ if (UrlFetchError.is(error)) {
113
+ return error.status >= 500 || error.status === 429;
114
+ }
115
+ if (FetchSchemaError.is(error) || UrlSafetyRefusals.is({ error })) {
116
+ return false;
117
+ }
118
+ // The caller's own abort ends the call; a per-attempt timeout is not the caller's and is retried.
119
+ return signal?.aborted !== true;
120
+ }
121
+ /** The wait a 429 or 503 asks for in `Retry-After`, in milliseconds: seconds, or an HTTP date. `undefined` when there is none. */
122
+ static readRetryAfterMs(opts) {
123
+ const { error } = opts;
124
+ if (!UrlFetchError.is(error) || (error.status !== 429 && error.status !== 503)) {
125
+ return undefined;
126
+ }
127
+ const header = error.headers.get(HTTP.Headers.RETRY_AFTER)?.trim();
128
+ if (!header) {
129
+ return undefined;
130
+ }
131
+ if (/^\d+$/.test(header)) {
132
+ const seconds = Number(header);
133
+ return Number.isSafeInteger(seconds) ? seconds * 1000 : undefined;
134
+ }
135
+ // An HTTP date has letters (`Thu, 19 Nov ...`); a bare number that is not whole seconds is garbage, not a date.
136
+ if (!/[a-z]/i.test(header)) {
137
+ return undefined;
138
+ }
139
+ const date = Date.parse(header);
140
+ return Number.isNaN(date) ? undefined : Math.max(0, date - (opts.now ?? Date.now()));
141
+ }
142
+ }
143
+ //# sourceMappingURL=utilities.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utilities.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/utilities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EACL,aAAa,EACb,iBAAiB,GAClB,MAAM,sDAAsD,CAAC;AAC9D,OA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AK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IACvF,CAAC","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport {\n UrlFetchError,\n UrlSafetyRefusals,\n} from '@/modules/network/utilities/url-safety/common/errors';\nimport { FetchSchemaError } from './errors';\nimport type { TFetchHeaders } from './types';\n\n/** Header maps: merged per header, the call winning, a `null` or `undefined` value removing a header. */\nexport class FetchHeaders {\n /** The headers of `layers` in order, later layers over earlier ones, as one `Headers`. */\n static merge(opts: { layers: ReadonlyArray<TFetchHeaders | undefined> }): Headers {\n const merged = new Headers();\n\n for (const layer of opts.layers) {\n if (layer === undefined) {\n continue;\n }\n\n if (layer instanceof Headers) {\n layer.forEach((value, name) => merged.set(name, value));\n continue;\n }\n\n for (const [name, value] of Object.entries(layer)) {\n if (value === null || value === undefined) {\n merged.delete(name);\n } else {\n merged.set(name, value);\n }\n }\n }\n\n return merged;\n }\n\n /** `merge` under a JSON content type: the layers may replace it (any case) or remove it with `null`. */\n static withJsonDefault(opts: { layers: ReadonlyArray<TFetchHeaders | undefined> }): Headers {\n return FetchHeaders.merge({\n layers: [\n { [HTTP.Headers.CONTENT_TYPE]: HTTP.HeaderValues.APPLICATION_JSON_UTF8 },\n ...opts.layers,\n ],\n });\n }\n\n /** A copy of `headers` keeping only the names in `names`. */\n static only(opts: { headers: Headers; names: ReadonlyArray<string> }): Headers {\n const kept = new Headers();\n\n opts.headers.forEach((value, name) => {\n if (opts.names.includes(name.toLowerCase())) {\n kept.set(name, value);\n }\n });\n\n return kept;\n }\n\n /** A copy of `headers` without the names in `names`. */\n static without(opts: { headers: Headers; names: ReadonlyArray<string> }): Headers {\n const kept = new Headers();\n\n opts.headers.forEach((value, name) => {\n if (!opts.names.includes(name.toLowerCase())) {\n kept.set(name, value);\n }\n });\n\n return kept;\n }\n}\n\n/** Which statuses a fetcher takes as an answer. */\nexport class FetchStatus {\n /** Whether `status` is 2xx. */\n private static isSuccess(opts: { status: number }): boolean {\n return Math.floor(opts.status / 100) === 2;\n }\n\n /** The one place `acceptStatus` becomes a decision: a list adds to 2xx, a function replaces it, unset is 2xx. */\n static toPredicate(opts: {\n accept: ReadonlyArray<number> | ((status: number) => boolean) | undefined;\n }): (status: number) => boolean {\n const { accept } = opts;\n\n if (typeof accept === 'function') {\n return accept;\n }\n\n const extra = new Set(accept);\n\n return (status) => FetchStatus.isSuccess({ status }) || extra.has(status);\n }\n}\n\n/** The statuses that name a new location; a 304 or a 300 is an answer, not a redirect. */\nconst REDIRECT_STATUSES: ReadonlyArray<number> = [301, 302, 303, 307, 308];\n\n/** The redirect rules of a fetcher that walks redirects by hand. */\nexport class FetchRedirects {\n /** Request headers that name the body; they go when a redirect turns the request into a GET. */\n static readonly BODY_HEADERS: ReadonlyArray<string> = [\n HTTP.Headers.CONTENT_TYPE,\n HTTP.Headers.CONTENT_LENGTH,\n HTTP.Headers.CONTENT_ENCODING,\n ];\n\n /**\n * The only caller headers a cross-origin redirect keeps. Every other one is dropped: a tenant's webhook secret\n * (`x-api-key`, a signature) must not follow a redirect to a host that tenant did not name.\n */\n static readonly CROSS_ORIGIN_HEADERS: ReadonlyArray<string> = [\n HTTP.Headers.ACCEPT,\n HTTP.Headers.ACCEPT_LANGUAGE,\n HTTP.Headers.USER_AGENT,\n ];\n\n static isRedirect(opts: { status: number }): boolean {\n return REDIRECT_STATUSES.includes(opts.status);\n }\n\n /** 303, and a POST answered 301 or 302, continue as a GET without the body. */\n static becomesGet(opts: { status: number; method: string }): boolean {\n return (\n opts.status === 303 ||\n ((opts.status === 301 || opts.status === 302) && opts.method === 'POST')\n );\n }\n}\n\n/** What a retried call retries, and for how long a server asks it to wait. */\nexport class FetchRetry {\n /** The longest wait a call takes between two attempts unless `backoff.maxDelayMs` says otherwise; the retry helper's own default. */\n static readonly DEFAULT_MAX_DELAY_MS = 30_000;\n\n /**\n * The default decision: a network error, a timeout, a 5xx and a 429 are worth another attempt. Any other 4xx, a 3xx, a\n * url the guard refused (refused forever), a schema mismatch and a caller's own abort are not.\n */\n static isRetryable(opts: { error: unknown; signal?: AbortSignal }): boolean {\n const { error, signal } = opts;\n\n if (UrlFetchError.is(error)) {\n return error.status >= 500 || error.status === 429;\n }\n\n if (FetchSchemaError.is(error) || UrlSafetyRefusals.is({ error })) {\n return false;\n }\n\n // The caller's own abort ends the call; a per-attempt timeout is not the caller's and is retried.\n return signal?.aborted !== true;\n }\n\n /** The wait a 429 or 503 asks for in `Retry-After`, in milliseconds: seconds, or an HTTP date. `undefined` when there is none. */\n static readRetryAfterMs(opts: { error: unknown; now?: number }): number | undefined {\n const { error } = opts;\n\n if (!UrlFetchError.is(error) || (error.status !== 429 && error.status !== 503)) {\n return undefined;\n }\n\n const header = error.headers.get(HTTP.Headers.RETRY_AFTER)?.trim();\n\n if (!header) {\n return undefined;\n }\n\n if (/^\\d+$/.test(header)) {\n const seconds = Number(header);\n\n return Number.isSafeInteger(seconds) ? seconds * 1000 : undefined;\n }\n\n // An HTTP date has letters (`Thu, 19 Nov ...`); a bare number that is not whole seconds is garbage, not a date.\n if (!/[a-z]/i.test(header)) {\n return undefined;\n }\n\n const date = Date.parse(header);\n\n return Number.isNaN(date) ? undefined : Math.max(0, date - (opts.now ?? Date.now()));\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
1
  export * from './base-fetcher.js';
2
- export * from './node-fetcher.js';
2
+ export * from './common/index.js';
3
+ export * from './native-fetcher.js';
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export * from './base-fetcher.js';
2
- export * from './node-fetcher.js';
2
+ export * from './common/index.js';
3
+ export * from './native-fetcher.js';
3
4
  // axios-fetcher is NOT re-exported here on purpose: it value-imports `axios`, an OPTIONAL peer, so a barrel export would make `import '@venizia/ignis-helpers'` fail for every app that does not install axios - reach it through `@venizia/ignis-helpers/axios`.
4
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAE/B,kQAAkQ","sourcesContent":["export * from './base-fetcher';\nexport * from './node-fetcher';\n\n// axios-fetcher is NOT re-exported here on purpose: it value-imports `axios`, an OPTIONAL peer, so a barrel export would make `import '@venizia/ignis-helpers'` fail for every app that does not install axios - reach it through `@venizia/ignis-helpers/axios`.\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AAEjC,kQAAkQ","sourcesContent":["export * from './base-fetcher';\nexport * from './common';\nexport * from './native-fetcher';\n\n// axios-fetcher is NOT re-exported here on purpose: it value-imports `axios`, an OPTIONAL peer, so a barrel export would make `import '@venizia/ignis-helpers'` fail for every app that does not install axios - reach it through `@venizia/ignis-helpers/axios`.\n"]}
@@ -0,0 +1,83 @@
1
+ import type { IUrlSafetyPolicy } from '../../utilities/url-safety/common/types.js';
2
+ import { type IQueryStringOptions } from '../../utilities/query-string.js';
3
+ import { BaseNetworkRequest } from '../base-network-request.helper.js';
4
+ import { AbstractNetworkFetchableHelper, type IFetchExchange, type IFetchExchangeRequest, type IRequestOptions, type TFetcherLogger } from './base-fetcher.js';
5
+ import type { IFetchGuard } from './common/guard.js';
6
+ import type { IFetcherDefaults, IFetcherHooks } from './common/types.js';
7
+ /** The fields of `RequestInit` a call or a fetcher cannot set because the pipeline owns them. */
8
+ type TOwnedInitFields = 'body' | 'headers' | 'method' | 'signal' | 'redirect';
9
+ /** `RequestInit` as a fetcher takes it for the settings the pipeline does not own (`credentials`, `mode`, `cache`, ...). */
10
+ export type TNativeRequestInit = Omit<RequestInit, TOwnedInitFields>;
11
+ /** Request accepted by `NativeFetcher`: `RequestInit` plus `url`; `params` are written into the url query. */
12
+ export interface INativeFetchRequestOptions extends TNativeRequestInit, IRequestOptions {
13
+ url: string;
14
+ params?: Record<string, unknown>;
15
+ body?: RequestInit['body'] | Record<string, unknown> | unknown[];
16
+ }
17
+ /** What sends a request when the fetcher is given one: the part of `fetch` it uses. */
18
+ export type TNativeFetchSender = (url: string, init: RequestInit) => Promise<Response>;
19
+ /** Fetcher over the global `fetch` (`getWorker()`): the pipeline of `AbstractNetworkFetchableHelper` with `fetch` as the client. */
20
+ export declare class NativeFetcher extends AbstractNetworkFetchableHelper<'native', INativeFetchRequestOptions, Awaited<ReturnType<typeof fetch>>, typeof fetch> {
21
+ private requestInit;
22
+ private sender;
23
+ private queryString;
24
+ constructor(opts: {
25
+ name: string;
26
+ /** `RequestInit` settings for every call (`credentials`, `mode`, `cache`, ...); headers and the signal belong to `defaults` and to the call. */
27
+ defaultConfigs?: TNativeRequestInit;
28
+ defaults?: IFetcherDefaults;
29
+ hooks?: IFetcherHooks;
30
+ /** The server half of the url guard (`UrlGuard`); a call that passes `guard` needs it. */
31
+ guardEngine?: IFetchGuard;
32
+ /** What sends a request, in place of the global `fetch` (read at call time): a test double, a proxy, an instrumented client. */
33
+ fetch?: TNativeFetchSender;
34
+ /** How `params` are written into the url query; unset fields behave as `node:querystring` does. */
35
+ queryString?: IQueryStringOptions;
36
+ logger?: TFetcherLogger;
37
+ });
38
+ /** A standard `FormData` is encoded afresh on every send, so it can be sent again. */
39
+ protected isReplayable(opts: {
40
+ body: unknown;
41
+ }): boolean;
42
+ /** With a guard the pipeline alone picks the connection: an option that picks one is refused, per call or in `defaultConfigs`. */
43
+ protected assertCallSupported(opts: {
44
+ guard?: IUrlSafetyPolicy;
45
+ extra: Record<string | symbol, unknown>;
46
+ }): void;
47
+ /** A raw body passes through; a plain object or an array is JSON-encoded; no body stays no body. */
48
+ protected serializeBody(opts: {
49
+ body: unknown;
50
+ }): RequestInit['body'] | undefined;
51
+ protected buildUrl(opts: {
52
+ url: string;
53
+ params?: Record<string, unknown>;
54
+ }): string;
55
+ protected describeBody(opts: {
56
+ body: unknown;
57
+ }): string | undefined;
58
+ /** `fetch` over one connection to `addresses`, in order; the next one is tried only when the connection itself fails. */
59
+ private fetchPinned;
60
+ /** The sender the fetcher was given, or the global `fetch` looked up now (a test that swaps it is heard). */
61
+ private request;
62
+ /** One `fetch`: pinned to the vetted addresses when there are some and no proxy was asked for. */
63
+ private dispatch;
64
+ protected exchange(opts: IFetchExchangeRequest): Promise<IFetchExchange<Response>>;
65
+ }
66
+ /** Options of `NativeFetchNetworkRequest`: `RequestInit` plus `baseUrl` and `queryString`, which sets how `params` are written into every url. */
67
+ export interface INativeFetchNetworkRequestOptions {
68
+ name: string;
69
+ networkOptions: RequestInit & {
70
+ baseUrl?: string;
71
+ /** How `params` are written into every url this request sends; see {@link IQueryStringOptions}. */
72
+ queryString?: IQueryStringOptions;
73
+ };
74
+ defaults?: IFetcherDefaults;
75
+ hooks?: IFetcherHooks;
76
+ guardEngine?: IFetchGuard;
77
+ }
78
+ /** `BaseNetworkRequest` over a `NativeFetcher`. Request headers default to a JSON content type, and the caller's headers win. */
79
+ export declare class NativeFetchNetworkRequest extends BaseNetworkRequest<'native'> {
80
+ constructor(opts: INativeFetchNetworkRequestOptions);
81
+ }
82
+ export {};
83
+ //# sourceMappingURL=native-fetcher.d.ts.map
@@ -0,0 +1,221 @@
1
+ import { HTTP } from '../../../../common/constants/http.js';
2
+ import { getError } from '../../../error/index.js';
3
+ import { QueryStringSeparators, QueryStringUtility, } from '../../utilities/query-string.js';
4
+ import { BaseNetworkRequest } from '../base-network-request.helper.js';
5
+ import { AbstractNetworkFetchableHelper, } from './base-fetcher.js';
6
+ import { BodyLimit } from './common/body-limit.js';
7
+ import { ResponseReader } from './common/response-reader.js';
8
+ import { FetchHeaders } from './common/utilities.js';
9
+ /** What `fetch` takes as a body as it is: encoding any of these again would change the bytes sent. A constructor is looked up on `globalThis` so a runtime without one (no `FormData`) just never matches it. */
10
+ const isRawBody = (body) => {
11
+ if (typeof body === 'string' || ArrayBuffer.isView(body) || body instanceof ArrayBuffer) {
12
+ return true;
13
+ }
14
+ return ['Blob', 'FormData', 'URLSearchParams', 'ReadableStream'].some((name) => {
15
+ const ctor = Reflect.get(globalThis, name);
16
+ return typeof ctor === 'function' && body instanceof ctor;
17
+ });
18
+ };
19
+ /**
20
+ * The `fetch` options a guarded call accepts, besides the ones the pipeline owns. An allowlist: Bun adds options that choose
21
+ * the connection (`unix`, `proxy`, `tls`, ...) and a guard must not meet a new one by surprise.
22
+ */
23
+ const GUARDED_OPTIONS = new Set([
24
+ 'credentials',
25
+ 'mode',
26
+ 'cache',
27
+ 'referrer',
28
+ 'referrerPolicy',
29
+ 'integrity',
30
+ 'keepalive',
31
+ 'priority',
32
+ ]);
33
+ /** Connect-phase errors: nothing was sent, so trying the next vetted address cannot deliver a request twice. */
34
+ const CONNECT_ERROR_CODES = ['ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'EADDRNOTAVAIL'];
35
+ /** Fetcher over the global `fetch` (`getWorker()`): the pipeline of `AbstractNetworkFetchableHelper` with `fetch` as the client. */
36
+ export class NativeFetcher extends AbstractNetworkFetchableHelper {
37
+ constructor(opts) {
38
+ super({
39
+ name: opts.name,
40
+ variant: 'native',
41
+ worker: fetch,
42
+ defaults: opts.defaults,
43
+ hooks: opts.hooks,
44
+ guardEngine: opts.guardEngine,
45
+ });
46
+ opts?.logger?.info('Creating new network request worker instance! Name: %s', this.name);
47
+ this.requestInit = opts.defaultConfigs ?? {};
48
+ this.sender = opts.fetch;
49
+ this.queryString = opts.queryString ?? {};
50
+ }
51
+ /** A standard `FormData` is encoded afresh on every send, so it can be sent again. */
52
+ isReplayable(opts) {
53
+ return ((typeof FormData !== 'undefined' && opts.body instanceof FormData) || super.isReplayable(opts));
54
+ }
55
+ /** With a guard the pipeline alone picks the connection: an option that picks one is refused, per call or in `defaultConfigs`. */
56
+ assertCallSupported(opts) {
57
+ if (opts.guard === undefined) {
58
+ return;
59
+ }
60
+ const source = { ...this.requestInit, ...opts.extra };
61
+ const found = Object.keys(source).filter((name) => source[name] !== undefined && !GUARDED_OPTIONS.has(name));
62
+ if (found.length > 0) {
63
+ throw getError({
64
+ message: `[${this.name}] A guarded call cannot set ${found.join(', ')} | only ${[...GUARDED_OPTIONS].join(', ')} are accepted with a guard: any other option could connect to an address the guard did not vet`,
65
+ });
66
+ }
67
+ }
68
+ /** A raw body passes through; a plain object or an array is JSON-encoded; no body stays no body. */
69
+ serializeBody(opts) {
70
+ const { body } = opts;
71
+ if (body === undefined || body === null) {
72
+ return undefined;
73
+ }
74
+ return isRawBody(body) ? body : JSON.stringify(body);
75
+ }
76
+ buildUrl(opts) {
77
+ const { url, params } = opts;
78
+ // `?` only when the url carries no query string of its own - a second `?` is not a separator, so the server would read the previous parameter's value as `1?extra=2`.
79
+ const serializedParams = params
80
+ ? QueryStringUtility.toQueryString({ params, ...this.queryString })
81
+ : '';
82
+ return serializedParams
83
+ ? `${url}${url.includes(QueryStringSeparators.START) ? QueryStringSeparators.PAIR : QueryStringSeparators.START}${serializedParams}`
84
+ : url;
85
+ }
86
+ describeBody(opts) {
87
+ const serialized = this.serializeBody(opts);
88
+ if (typeof serialized === 'string') {
89
+ return `[body ${serialized.length} chars]`;
90
+ }
91
+ return serialized ? '[body]' : undefined;
92
+ }
93
+ /** `fetch` over one connection to `addresses`, in order; the next one is tried only when the connection itself fails. */
94
+ async fetchPinned(opts) {
95
+ const { url, addresses, tlsServerName, init } = opts;
96
+ const headers = new Headers(init.headers);
97
+ headers.set(HTTP.Headers.HOST, url.host);
98
+ let lastError;
99
+ for (const address of addresses) {
100
+ const pinned = new URL(url);
101
+ pinned.hostname = address.includes(':') ? `[${address}]` : address;
102
+ try {
103
+ const result = await this.request({
104
+ url: pinned,
105
+ init: {
106
+ ...init,
107
+ // `proxy: false` is Bun's way to ignore HTTP_PROXY / HTTPS_PROXY for this call (an empty string or undefined keeps the environment's proxy, which would resolve the name itself and undo the pin). A test pins it.
108
+ proxy: false,
109
+ headers,
110
+ ...(tlsServerName === undefined ? {} : { tls: { serverName: tlsServerName } }),
111
+ },
112
+ });
113
+ return result;
114
+ }
115
+ catch (error) {
116
+ const name = error instanceof Error ? error.name : '';
117
+ // The deadline, or the caller's own abort (whatever reason it carried), is not a reason to try another address.
118
+ if (init.signal?.aborted || name === 'AbortError' || name === 'TimeoutError') {
119
+ throw error;
120
+ }
121
+ // A request that may have reached the server (a reset after the body went out) is not repeated on another address unless it is safe to repeat: a webhook must not be delivered twice.
122
+ const code = String(Reflect.get(Object(error), 'code') ?? '');
123
+ const method = (init.method ?? 'GET').toUpperCase();
124
+ if (method !== 'GET' && method !== 'HEAD' && !CONNECT_ERROR_CODES.includes(code)) {
125
+ throw error;
126
+ }
127
+ lastError = error;
128
+ }
129
+ }
130
+ throw lastError;
131
+ }
132
+ /** The sender the fetcher was given, or the global `fetch` looked up now (a test that swaps it is heard). */
133
+ async request(opts) {
134
+ const { url, init } = opts;
135
+ // Taken off `this` first: `window.fetch` throws "Illegal invocation" when it is called as a method of another object.
136
+ const { sender } = this;
137
+ if (sender) {
138
+ const answer = await sender(url.toString(), init);
139
+ return answer;
140
+ }
141
+ const answer = await fetch(url.toString(), init);
142
+ return answer;
143
+ }
144
+ /** One `fetch`: pinned to the vetted addresses when there are some and no proxy was asked for. */
145
+ async dispatch(opts) {
146
+ const { url, addresses, tlsServerName, proxy, init } = opts;
147
+ if (addresses.length > 0 && !proxy) {
148
+ const pinned = await this.fetchPinned({ url, addresses, tlsServerName, init });
149
+ return pinned;
150
+ }
151
+ const plain = await this.request({ url, init });
152
+ return plain;
153
+ }
154
+ async exchange(opts) {
155
+ const { method, url, headers, body, signal, addresses, tlsServerName, proxy, isManualRedirect, extra, } = opts;
156
+ const init = {
157
+ ...this.requestInit,
158
+ ...extra,
159
+ method,
160
+ body: this.serializeBody({ body }),
161
+ headers,
162
+ signal,
163
+ redirect: isManualRedirect ? 'manual' : 'follow',
164
+ ...(proxy ? { proxy } : {}),
165
+ };
166
+ const response = await this.dispatch({ url, addresses, tlsServerName, proxy, init });
167
+ return {
168
+ response,
169
+ status: response.status,
170
+ statusText: response.statusText,
171
+ headers: response.headers,
172
+ discard: async () => {
173
+ await response.body?.cancel();
174
+ },
175
+ keepBody: async ({ maxBytes }) => {
176
+ const bytes = await BodyLimit.readPrefix({ response, maxBytes });
177
+ // A status without a body (204, 205, 304) cannot carry one in a `Response`.
178
+ return new Response(bytes.length > 0 ? bytes : null, {
179
+ status: response.status,
180
+ statusText: response.statusText,
181
+ headers: response.headers,
182
+ });
183
+ },
184
+ readJson: async ({ maxBytes }) => {
185
+ const text = await ResponseReader.readText({ response, maxBytes });
186
+ return JSON.parse(text);
187
+ },
188
+ capped: ({ maxBytes }) => response.body
189
+ ? new Response(BodyLimit.capStream({ source: response.body, maxBytes }), {
190
+ status: response.status,
191
+ statusText: response.statusText,
192
+ headers: response.headers,
193
+ })
194
+ : response,
195
+ };
196
+ }
197
+ }
198
+ /** `BaseNetworkRequest` over a `NativeFetcher`. Request headers default to a JSON content type, and the caller's headers win. */
199
+ export class NativeFetchNetworkRequest extends BaseNetworkRequest {
200
+ constructor(opts) {
201
+ const { name, networkOptions } = opts;
202
+ const { headers, baseUrl, queryString, signal: _signal, body: _body, method: _method, redirect: _redirect, ...requestInit } = networkOptions;
203
+ // Case-insensitive, like the wire: a caller's `Content-Type` replaces the default one.
204
+ const mergedHeaders = FetchHeaders.withJsonDefault({
205
+ layers: [headers === undefined ? undefined : new Headers(headers), opts.defaults?.headers],
206
+ });
207
+ super({
208
+ name,
209
+ baseUrl,
210
+ fetcher: new NativeFetcher({
211
+ name,
212
+ defaultConfigs: requestInit,
213
+ defaults: { ...opts.defaults, headers: mergedHeaders },
214
+ hooks: opts.hooks,
215
+ guardEngine: opts.guardEngine,
216
+ queryString,
217
+ }),
218
+ });
219
+ }
220
+ }
221
+ //# sourceMappingURL=native-fetcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/native-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,EAEL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EACL,8BAA8B,GAK/B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAG1D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAwBlD,iNAAiN;AACjN,MAAM,SAAS,GAAG,CAAC,IAAa,EAA4C,EAAE;IAC5E,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,YAAY,WAAW,EAAE,CAAC;QACxF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CAAC,MAAM,EAAE,UAAU,EAAE,iBAAiB,EAAE,gBAAgB,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;QAC7E,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QAE3C,OAAO,OAAO,IAAI,KAAK,UAAU,IAAI,IAAI,YAAY,IAAI,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,aAAa;IACb,MAAM;IACN,OAAO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AO,EAAE,QAAQ,CAAC,OAAO;iBAC1B,CAAC;gBACJ,CAAC,CAAC,QAAQ;SACf,CAAC;IACJ,CAAC;CACF;AAeD,iIAAiI;AACjI,MAAM,OAAO,yBAA0B,SAAQ,kBAA4B;IACzE,YAAY,IAAuC;QACjD,MAAM,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;QACtC,MAAM,EACJ,OAAO,EACP,OAAO,EACP,WAAW,EACX,MAAM,EAAE,OAAO,EACf,IAAI,EAAE,KAAK,EACX,MAAM,EAAE,OAAO,EACf,QAAQ,EAAE,SAAS,EACnB,GAAG,WAAW,EACf,GAAG,cAAc,CAAC;QAEnB,uFAAuF;QACvF,MAAM,aAAa,GAAG,YAAY,CAAC,eAAe,CAAC;YACjD,MAAM,EAAE,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC;SAC3F,CAAC,CAAC;QAEH,KAAK,CAAC;YACJ,IAAI;YACJ,OAAO;YACP,OAAO,EAAE,IAAI,aAAa,CAAC;gBACzB,IAAI;gBACJ,cAAc,EAAE,WAAW;gBAC3B,QAAQ,EAAE,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,aAAa,EAAE;gBACtD,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,WAAW;aACZ,CAAC;SACH,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport type { IUrlSafetyPolicy } from '@/modules/network/utilities/url-safety/common/types';\nimport {\n type IQueryStringOptions,\n QueryStringSeparators,\n QueryStringUtility,\n} from '../../utilities/query-string';\n\nimport { BaseNetworkRequest } from '../base-network-request.helper';\nimport {\n AbstractNetworkFetchableHelper,\n type IFetchExchange,\n type IFetchExchangeRequest,\n type IRequestOptions,\n type TFetcherLogger,\n} from './base-fetcher';\nimport { BodyLimit } from './common/body-limit';\nimport { ResponseReader } from './common/response-reader';\nimport type { IFetchGuard } from './common/guard';\nimport type { IFetcherDefaults, IFetcherHooks } from './common/types';\nimport { FetchHeaders } from './common/utilities';\n\n/** The fields of `RequestInit` a call or a fetcher cannot set because the pipeline owns them. */\ntype TOwnedInitFields = 'body' | 'headers' | 'method' | 'signal' | 'redirect';\n\n/** `RequestInit` as a fetcher takes it for the settings the pipeline does not own (`credentials`, `mode`, `cache`, ...). */\nexport type TNativeRequestInit = Omit<RequestInit, TOwnedInitFields>;\n\n/** Request accepted by `NativeFetcher`: `RequestInit` plus `url`; `params` are written into the url query. */\nexport interface INativeFetchRequestOptions extends TNativeRequestInit, IRequestOptions {\n url: string;\n params?: Record<string, unknown>;\n body?: RequestInit['body'] | Record<string, unknown> | unknown[];\n}\n\n/** What sends a request when the fetcher is given one: the part of `fetch` it uses. */\nexport type TNativeFetchSender = (url: string, init: RequestInit) => Promise<Response>;\n\n/** The options Bun's `fetch` takes beyond the standard ones; the standard `RequestInit` does not declare `proxy`. */\ninterface IBunFetchInit extends RequestInit {\n proxy?: string | false;\n tls?: { serverName?: string };\n}\n\n/** What `fetch` takes as a body as it is: encoding any of these again would change the bytes sent. A constructor is looked up on `globalThis` so a runtime without one (no `FormData`) just never matches it. */\nconst isRawBody = (body: unknown): body is NonNullable<RequestInit['body']> => {\n if (typeof body === 'string' || ArrayBuffer.isView(body) || body instanceof ArrayBuffer) {\n return true;\n }\n\n return ['Blob', 'FormData', 'URLSearchParams', 'ReadableStream'].some((name) => {\n const ctor = Reflect.get(globalThis, name);\n\n return typeof ctor === 'function' && body instanceof ctor;\n });\n};\n\n/**\n * The `fetch` options a guarded call accepts, besides the ones the pipeline owns. An allowlist: Bun adds options that choose\n * the connection (`unix`, `proxy`, `tls`, ...) and a guard must not meet a new one by surprise.\n */\nconst GUARDED_OPTIONS = new Set([\n 'credentials',\n 'mode',\n 'cache',\n 'referrer',\n 'referrerPolicy',\n 'integrity',\n 'keepalive',\n 'priority',\n]);\n\n/** Connect-phase errors: nothing was sent, so trying the next vetted address cannot deliver a request twice. */\nconst CONNECT_ERROR_CODES = ['ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'EADDRNOTAVAIL'];\n\n/** Fetcher over the global `fetch` (`getWorker()`): the pipeline of `AbstractNetworkFetchableHelper` with `fetch` as the client. */\nexport class NativeFetcher extends AbstractNetworkFetchableHelper<\n 'native',\n INativeFetchRequestOptions,\n Awaited<ReturnType<typeof fetch>>,\n typeof fetch\n> {\n private requestInit: TNativeRequestInit;\n private sender: TNativeFetchSender | undefined;\n private queryString: IQueryStringOptions;\n\n constructor(opts: {\n name: string;\n /** `RequestInit` settings for every call (`credentials`, `mode`, `cache`, ...); headers and the signal belong to `defaults` and to the call. */\n defaultConfigs?: TNativeRequestInit;\n defaults?: IFetcherDefaults;\n hooks?: IFetcherHooks;\n /** The server half of the url guard (`UrlGuard`); a call that passes `guard` needs it. */\n guardEngine?: IFetchGuard;\n /** What sends a request, in place of the global `fetch` (read at call time): a test double, a proxy, an instrumented client. */\n fetch?: TNativeFetchSender;\n /** How `params` are written into the url query; unset fields behave as `node:querystring` does. */\n queryString?: IQueryStringOptions;\n logger?: TFetcherLogger;\n }) {\n super({\n name: opts.name,\n variant: 'native',\n worker: fetch,\n defaults: opts.defaults,\n hooks: opts.hooks,\n guardEngine: opts.guardEngine,\n });\n opts?.logger?.info('Creating new network request worker instance! Name: %s', this.name);\n\n this.requestInit = opts.defaultConfigs ?? {};\n this.sender = opts.fetch;\n this.queryString = opts.queryString ?? {};\n }\n\n /** A standard `FormData` is encoded afresh on every send, so it can be sent again. */\n protected override isReplayable(opts: { body: unknown }): boolean {\n return (\n (typeof FormData !== 'undefined' && opts.body instanceof FormData) || super.isReplayable(opts)\n );\n }\n\n /** With a guard the pipeline alone picks the connection: an option that picks one is refused, per call or in `defaultConfigs`. */\n protected override assertCallSupported(opts: {\n guard?: IUrlSafetyPolicy;\n extra: Record<string | symbol, unknown>;\n }): void {\n if (opts.guard === undefined) {\n return;\n }\n\n const source: Record<string, unknown> = { ...this.requestInit, ...opts.extra };\n const found = Object.keys(source).filter(\n (name) => source[name] !== undefined && !GUARDED_OPTIONS.has(name),\n );\n\n if (found.length > 0) {\n throw getError({\n message: `[${this.name}] A guarded call cannot set ${found.join(', ')} | only ${[...GUARDED_OPTIONS].join(', ')} are accepted with a guard: any other option could connect to an address the guard did not vet`,\n });\n }\n }\n\n /** A raw body passes through; a plain object or an array is JSON-encoded; no body stays no body. */\n protected serializeBody(opts: { body: unknown }): RequestInit['body'] | undefined {\n const { body } = opts;\n\n if (body === undefined || body === null) {\n return undefined;\n }\n\n return isRawBody(body) ? body : JSON.stringify(body);\n }\n\n protected override buildUrl(opts: { url: string; params?: Record<string, unknown> }): string {\n const { url, params } = opts;\n\n // `?` only when the url carries no query string of its own - a second `?` is not a separator, so the server would read the previous parameter's value as `1?extra=2`.\n const serializedParams = params\n ? QueryStringUtility.toQueryString({ params, ...this.queryString })\n : '';\n\n return serializedParams\n ? `${url}${url.includes(QueryStringSeparators.START) ? QueryStringSeparators.PAIR : QueryStringSeparators.START}${serializedParams}`\n : url;\n }\n\n protected override describeBody(opts: { body: unknown }): string | undefined {\n const serialized = this.serializeBody(opts);\n\n if (typeof serialized === 'string') {\n return `[body ${serialized.length} chars]`;\n }\n\n return serialized ? '[body]' : undefined;\n }\n\n /** `fetch` over one connection to `addresses`, in order; the next one is tried only when the connection itself fails. */\n private async fetchPinned(opts: {\n url: URL;\n addresses: string[];\n tlsServerName?: string;\n init: IBunFetchInit;\n }): Promise<Response> {\n const { url, addresses, tlsServerName, init } = opts;\n const headers = new Headers(init.headers);\n\n headers.set(HTTP.Headers.HOST, url.host);\n\n let lastError: unknown;\n\n for (const address of addresses) {\n const pinned = new URL(url);\n pinned.hostname = address.includes(':') ? `[${address}]` : address;\n\n try {\n const result = await this.request({\n url: pinned,\n init: {\n ...init,\n // `proxy: false` is Bun's way to ignore HTTP_PROXY / HTTPS_PROXY for this call (an empty string or undefined keeps the environment's proxy, which would resolve the name itself and undo the pin). A test pins it.\n proxy: false,\n headers,\n ...(tlsServerName === undefined ? {} : { tls: { serverName: tlsServerName } }),\n },\n });\n\n return result;\n } catch (error) {\n const name = error instanceof Error ? error.name : '';\n\n // The deadline, or the caller's own abort (whatever reason it carried), is not a reason to try another address.\n if (init.signal?.aborted || name === 'AbortError' || name === 'TimeoutError') {\n throw error;\n }\n\n // A request that may have reached the server (a reset after the body went out) is not repeated on another address unless it is safe to repeat: a webhook must not be delivered twice.\n const code = String(Reflect.get(Object(error), 'code') ?? '');\n const method = (init.method ?? 'GET').toUpperCase();\n\n if (method !== 'GET' && method !== 'HEAD' && !CONNECT_ERROR_CODES.includes(code)) {\n throw error;\n }\n\n lastError = error;\n }\n }\n\n throw lastError;\n }\n\n /** The sender the fetcher was given, or the global `fetch` looked up now (a test that swaps it is heard). */\n private async request(opts: { url: URL; init: IBunFetchInit }): Promise<Response> {\n const { url, init } = opts;\n\n // Taken off `this` first: `window.fetch` throws \"Illegal invocation\" when it is called as a method of another object.\n const { sender } = this;\n\n if (sender) {\n const answer = await sender(url.toString(), init);\n\n return answer;\n }\n\n const answer = await fetch(url.toString(), init);\n\n return answer;\n }\n\n /** One `fetch`: pinned to the vetted addresses when there are some and no proxy was asked for. */\n private async dispatch(opts: {\n url: URL;\n addresses: string[];\n tlsServerName?: string;\n proxy: string | undefined;\n init: IBunFetchInit;\n }): Promise<Response> {\n const { url, addresses, tlsServerName, proxy, init } = opts;\n\n if (addresses.length > 0 && !proxy) {\n const pinned = await this.fetchPinned({ url, addresses, tlsServerName, init });\n\n return pinned;\n }\n\n const plain = await this.request({ url, init });\n\n return plain;\n }\n\n protected override async exchange(\n opts: IFetchExchangeRequest,\n ): Promise<IFetchExchange<Response>> {\n const {\n method,\n url,\n headers,\n body,\n signal,\n addresses,\n tlsServerName,\n proxy,\n isManualRedirect,\n extra,\n } = opts;\n const init: IBunFetchInit = {\n ...this.requestInit,\n ...extra,\n method,\n body: this.serializeBody({ body }),\n headers,\n signal,\n redirect: isManualRedirect ? 'manual' : 'follow',\n ...(proxy ? { proxy } : {}),\n };\n const response = await this.dispatch({ url, addresses, tlsServerName, proxy, init });\n\n return {\n response,\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n discard: async () => {\n await response.body?.cancel();\n },\n keepBody: async ({ maxBytes }) => {\n const bytes = await BodyLimit.readPrefix({ response, maxBytes });\n\n // A status without a body (204, 205, 304) cannot carry one in a `Response`.\n return new Response(bytes.length > 0 ? bytes : null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n },\n readJson: async ({ maxBytes }) => {\n const text = await ResponseReader.readText({ response, maxBytes });\n\n return JSON.parse(text);\n },\n capped: ({ maxBytes }) =>\n response.body\n ? new Response(BodyLimit.capStream({ source: response.body, maxBytes }), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n })\n : response,\n };\n }\n}\n\n/** Options of `NativeFetchNetworkRequest`: `RequestInit` plus `baseUrl` and `queryString`, which sets how `params` are written into every url. */\nexport interface INativeFetchNetworkRequestOptions {\n name: string;\n networkOptions: RequestInit & {\n baseUrl?: string;\n /** How `params` are written into every url this request sends; see {@link IQueryStringOptions}. */\n queryString?: IQueryStringOptions;\n };\n defaults?: IFetcherDefaults;\n hooks?: IFetcherHooks;\n guardEngine?: IFetchGuard;\n}\n\n/** `BaseNetworkRequest` over a `NativeFetcher`. Request headers default to a JSON content type, and the caller's headers win. */\nexport class NativeFetchNetworkRequest extends BaseNetworkRequest<'native'> {\n constructor(opts: INativeFetchNetworkRequestOptions) {\n const { name, networkOptions } = opts;\n const {\n headers,\n baseUrl,\n queryString,\n signal: _signal,\n body: _body,\n method: _method,\n redirect: _redirect,\n ...requestInit\n } = networkOptions;\n\n // Case-insensitive, like the wire: a caller's `Content-Type` replaces the default one.\n const mergedHeaders = FetchHeaders.withJsonDefault({\n layers: [headers === undefined ? undefined : new Headers(headers), opts.defaults?.headers],\n });\n\n super({\n name,\n baseUrl,\n fetcher: new NativeFetcher({\n name,\n defaultConfigs: requestInit,\n defaults: { ...opts.defaults, headers: mergedHeaders },\n hooks: opts.hooks,\n guardEngine: opts.guardEngine,\n queryString,\n }),\n });\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
1
  export * from './query-string.js';
2
+ export * from './url-builder.js';
2
3
  export * from './url-safety/index.js';
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,3 +1,4 @@
1
1
  export * from './query-string.js';
2
+ export * from './url-builder.js';
2
3
  export * from './url-safety/index.js';
3
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC","sourcesContent":["export * from './query-string';\nexport * from './url-safety';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,cAAc,CAAC","sourcesContent":["export * from './query-string';\nexport * from './url-builder';\nexport * from './url-safety';\n"]}
@@ -1,4 +1,3 @@
1
- import { type TConstValue } from '../../../common/types/index.js';
2
1
  /** The punctuation of a query string, named so a reader sees the role rather than the character. */
3
2
  export declare class QueryStringSeparators {
4
3
  /** Between the path and the first pair. */
@@ -8,36 +7,20 @@ export declare class QueryStringSeparators {
8
7
  /** Between a name and its value. */
9
8
  static readonly ASSIGN = "=";
10
9
  }
11
- /** What a `null` or `undefined` value becomes. */
12
- export declare class QueryStringNullishModes {
13
- /** An empty value (`a=`): what `node:querystring` does. */
14
- static readonly EMPTY = "empty";
15
- /** The pair is left out. */
16
- static readonly SKIP = "skip";
17
- }
18
- /** What {@link QueryStringNullishModes} selects: `empty` or `skip`. */
19
- export type TQueryStringNullishMode = TConstValue<typeof QueryStringNullishModes>;
20
- /** What an object or an array value becomes. */
21
- export declare class QueryStringNestedModes {
22
- /** An empty value (an array repeats its key instead): what `node:querystring` does. */
23
- static readonly DROP = "drop";
24
- /** One JSON-encoded parameter (`ids=[1,2]`, `filter={"where":{}}`), the shape a JSON filter travels in. */
25
- static readonly JSON = "json";
26
- }
27
- /** What {@link QueryStringNestedModes} selects: `drop` or `json`. */
28
- export type TQueryStringNestedMode = TConstValue<typeof QueryStringNestedModes>;
29
10
  /** How {@link QueryStringUtility.toQueryString} treats the values `node:querystring` has no answer for. */
30
11
  export interface IQueryStringOptions {
31
12
  /**
32
13
  * What a `null` or `undefined` value becomes.
33
- * @default QueryStringNullishModes.EMPTY
14
+ * `'empty'` is `a=` (what `node:querystring` does), `'skip'` leaves the pair out.
15
+ * @default 'empty'
34
16
  */
35
- nullish?: TQueryStringNullishMode;
17
+ nullish?: 'empty' | 'skip';
36
18
  /**
37
19
  * What an object or an array value becomes.
38
- * @default QueryStringNestedModes.DROP
20
+ * `'drop'` is an empty value (an array repeats its key: what `node:querystring` does), `'json'` is one JSON-encoded parameter (`filter={"where":{}}`).
21
+ * @default 'drop'
39
22
  */
40
- nested?: TQueryStringNestedMode;
23
+ nested?: 'drop' | 'json';
41
24
  }
42
25
  /** Builds a query string without a node builtin, so the network layer stays browser-safe. */
43
26
  export declare class QueryStringUtility {