@venizia/ignis-helpers 0.4.8 → 0.5.0-1
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/esm/common/constants/http.d.ts +17 -1
- package/dist/esm/common/constants/http.js +17 -0
- package/dist/esm/common/constants/http.js.map +1 -1
- package/dist/esm/common/redact.js +2 -0
- package/dist/esm/common/redact.js.map +1 -1
- package/dist/esm/core.d.ts +5 -2
- package/dist/esm/core.js +5 -2
- package/dist/esm/core.js.map +1 -1
- package/dist/esm/modules/network/http-request/base-network-request.helper.d.ts +5 -0
- package/dist/esm/modules/network/http-request/base-network-request.helper.js +14 -17
- package/dist/esm/modules/network/http-request/base-network-request.helper.js.map +1 -1
- package/dist/esm/modules/network/http-request/common/constants.d.ts +2 -1
- package/dist/esm/modules/network/http-request/common/constants.js +2 -1
- package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +37 -11
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +181 -38
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +204 -18
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +433 -13
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/body-limit.d.ts +36 -0
- package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js +119 -0
- package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/errors.d.ts +40 -0
- package/dist/esm/modules/network/http-request/fetcher/common/errors.js +37 -0
- package/dist/esm/modules/network/http-request/fetcher/common/errors.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/guard.d.ts +27 -0
- package/dist/esm/modules/network/http-request/fetcher/common/guard.js +2 -0
- package/dist/esm/modules/network/http-request/fetcher/common/guard.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/index.d.ts +6 -0
- package/dist/esm/modules/network/http-request/fetcher/common/index.js +6 -0
- package/dist/esm/modules/network/http-request/fetcher/common/index.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/request-context.d.ts +15 -0
- package/dist/esm/modules/network/http-request/fetcher/common/request-context.js +11 -0
- package/dist/esm/modules/network/http-request/fetcher/common/request-context.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/response-reader.d.ts +133 -0
- package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js +264 -0
- package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +65 -1
- package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/utilities.d.ts +68 -0
- package/dist/esm/modules/network/http-request/fetcher/common/utilities.js +143 -0
- package/dist/esm/modules/network/http-request/fetcher/common/utilities.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/index.d.ts +2 -1
- package/dist/esm/modules/network/http-request/fetcher/index.js +2 -1
- package/dist/esm/modules/network/http-request/fetcher/index.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/native-fetcher.d.ts +85 -0
- package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js +221 -0
- package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js.map +1 -0
- package/dist/esm/modules/network/utilities/index.d.ts +1 -0
- package/dist/esm/modules/network/utilities/index.js +1 -0
- package/dist/esm/modules/network/utilities/index.js.map +1 -1
- package/dist/esm/modules/network/utilities/query-string.d.ts +6 -23
- package/dist/esm/modules/network/utilities/query-string.js +3 -17
- package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-builder.d.ts +39 -0
- package/dist/esm/modules/network/utilities/url-builder.js +102 -0
- package/dist/esm/modules/network/utilities/url-builder.js.map +1 -0
- package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -3
- package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/common/errors.d.ts +38 -0
- package/dist/esm/modules/network/utilities/url-safety/common/errors.js +33 -1
- package/dist/esm/modules/network/utilities/url-safety/common/errors.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/common/types.d.ts +26 -3
- package/dist/esm/modules/network/utilities/url-safety/common/types.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/guard.d.ts +46 -0
- package/dist/esm/modules/network/utilities/url-safety/guard.js +145 -0
- package/dist/esm/modules/network/utilities/url-safety/guard.js.map +1 -0
- package/dist/esm/modules/network/utilities/url-safety/index.d.ts +1 -1
- package/dist/esm/modules/network/utilities/url-safety/index.js +1 -1
- package/dist/esm/modules/network/utilities/url-safety/index.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/policy.d.ts +52 -2
- package/dist/esm/modules/network/utilities/url-safety/policy.js +161 -14
- package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
- package/dist/esm/modules/queue/bullmq/helper.d.ts +43 -7
- package/dist/esm/modules/queue/bullmq/helper.js +70 -2
- package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
- package/dist/esm/modules/retry/helper.d.ts +3 -1
- package/dist/esm/modules/retry/helper.js +8 -4
- package/dist/esm/modules/retry/helper.js.map +1 -1
- package/dist/esm/utilities/request.utility.d.ts +1 -25
- package/dist/esm/utilities/request.utility.js +0 -46
- package/dist/esm/utilities/request.utility.js.map +1 -1
- package/package.json +4 -4
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +0 -41
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +0 -111
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +0 -1
- package/dist/esm/modules/network/utilities/url-safety/ingest.d.ts +0 -95
- package/dist/esm/modules/network/utilities/url-safety/ingest.js +0 -328
- package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export * from './base-fetcher.js';
|
|
2
|
-
export * from './
|
|
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,
|
|
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,85 @@
|
|
|
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
|
+
/** 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. */
|
|
22
|
+
static isRawBody(body: unknown): body is NonNullable<RequestInit['body']>;
|
|
23
|
+
private requestInit;
|
|
24
|
+
private sender;
|
|
25
|
+
private queryString;
|
|
26
|
+
constructor(opts: {
|
|
27
|
+
name: string;
|
|
28
|
+
/** `RequestInit` settings for every call (`credentials`, `mode`, `cache`, ...); headers and the signal belong to `defaults` and to the call. */
|
|
29
|
+
defaultConfigs?: TNativeRequestInit;
|
|
30
|
+
defaults?: IFetcherDefaults;
|
|
31
|
+
hooks?: IFetcherHooks;
|
|
32
|
+
/** The server half of the url guard (`UrlGuard`); a call that passes `guard` needs it. */
|
|
33
|
+
guardEngine?: IFetchGuard;
|
|
34
|
+
/** What sends a request, in place of the global `fetch` (read at call time): a test double, a proxy, an instrumented client. */
|
|
35
|
+
fetch?: TNativeFetchSender;
|
|
36
|
+
/** How `params` are written into the url query; unset fields behave as `node:querystring` does. */
|
|
37
|
+
queryString?: IQueryStringOptions;
|
|
38
|
+
logger?: TFetcherLogger;
|
|
39
|
+
});
|
|
40
|
+
/** A standard `FormData` is encoded afresh on every send, so it can be sent again. */
|
|
41
|
+
protected isReplayable(opts: {
|
|
42
|
+
body: unknown;
|
|
43
|
+
}): boolean;
|
|
44
|
+
/** With a guard the pipeline alone picks the connection: an option that picks one is refused, per call or in `defaultConfigs`. */
|
|
45
|
+
protected assertCallSupported(opts: {
|
|
46
|
+
guard?: IUrlSafetyPolicy;
|
|
47
|
+
extra: Record<string | symbol, unknown>;
|
|
48
|
+
}): void;
|
|
49
|
+
/** A raw body passes through; a plain object or an array is JSON-encoded; no body stays no body. */
|
|
50
|
+
protected serializeBody(opts: {
|
|
51
|
+
body: unknown;
|
|
52
|
+
}): RequestInit['body'] | undefined;
|
|
53
|
+
protected buildUrl(opts: {
|
|
54
|
+
url: string;
|
|
55
|
+
params?: Record<string, unknown>;
|
|
56
|
+
}): string;
|
|
57
|
+
protected describeBody(opts: {
|
|
58
|
+
body: unknown;
|
|
59
|
+
}): string | undefined;
|
|
60
|
+
/** `fetch` over one connection to `addresses`, in order; the next one is tried only when the connection itself fails. */
|
|
61
|
+
private fetchPinned;
|
|
62
|
+
/** The sender the fetcher was given, or the global `fetch` looked up now (a test that swaps it is heard). */
|
|
63
|
+
private request;
|
|
64
|
+
/** One `fetch`: pinned to the vetted addresses when there are some and no proxy was asked for. */
|
|
65
|
+
private dispatch;
|
|
66
|
+
protected exchange(opts: IFetchExchangeRequest): Promise<IFetchExchange<Response>>;
|
|
67
|
+
}
|
|
68
|
+
/** Options of `NativeFetchNetworkRequest`: `RequestInit` plus `baseUrl` and `queryString`, which sets how `params` are written into every url. */
|
|
69
|
+
export interface INativeFetchNetworkRequestOptions {
|
|
70
|
+
name: string;
|
|
71
|
+
networkOptions: RequestInit & {
|
|
72
|
+
baseUrl?: string;
|
|
73
|
+
/** How `params` are written into every url this request sends; see {@link IQueryStringOptions}. */
|
|
74
|
+
queryString?: IQueryStringOptions;
|
|
75
|
+
};
|
|
76
|
+
defaults?: IFetcherDefaults;
|
|
77
|
+
hooks?: IFetcherHooks;
|
|
78
|
+
guardEngine?: IFetchGuard;
|
|
79
|
+
}
|
|
80
|
+
/** `BaseNetworkRequest` over a `NativeFetcher`. Request headers default to a JSON content type, and the caller's headers win. */
|
|
81
|
+
export declare class NativeFetchNetworkRequest extends BaseNetworkRequest<'native'> {
|
|
82
|
+
constructor(opts: INativeFetchNetworkRequestOptions);
|
|
83
|
+
}
|
|
84
|
+
export {};
|
|
85
|
+
//# 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 { HttpResponseReader } from './common/response-reader.js';
|
|
8
|
+
import { HttpHeaders } from './common/utilities.js';
|
|
9
|
+
/**
|
|
10
|
+
* The `fetch` options a guarded call accepts, besides the ones the pipeline owns. An allowlist: Bun adds options that choose
|
|
11
|
+
* the connection (`unix`, `proxy`, `tls`, ...) and a guard must not meet a new one by surprise.
|
|
12
|
+
*/
|
|
13
|
+
const GUARDED_OPTIONS = new Set([
|
|
14
|
+
'credentials',
|
|
15
|
+
'mode',
|
|
16
|
+
'cache',
|
|
17
|
+
'referrer',
|
|
18
|
+
'referrerPolicy',
|
|
19
|
+
'integrity',
|
|
20
|
+
'keepalive',
|
|
21
|
+
'priority',
|
|
22
|
+
]);
|
|
23
|
+
/** Connect-phase errors: nothing was sent, so trying the next vetted address cannot deliver a request twice. */
|
|
24
|
+
const CONNECT_ERROR_CODES = ['ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'EADDRNOTAVAIL'];
|
|
25
|
+
/** Fetcher over the global `fetch` (`getWorker()`): the pipeline of `AbstractNetworkFetchableHelper` with `fetch` as the client. */
|
|
26
|
+
export class NativeFetcher extends AbstractNetworkFetchableHelper {
|
|
27
|
+
/** 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. */
|
|
28
|
+
static isRawBody(body) {
|
|
29
|
+
if (typeof body === 'string' || ArrayBuffer.isView(body) || body instanceof ArrayBuffer) {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
return ['Blob', 'FormData', 'URLSearchParams', 'ReadableStream'].some((name) => {
|
|
33
|
+
const ctor = Reflect.get(globalThis, name);
|
|
34
|
+
return typeof ctor === 'function' && body instanceof ctor;
|
|
35
|
+
});
|
|
36
|
+
}
|
|
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 NativeFetcher.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 HttpResponseReader.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 = HttpHeaders.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,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAG9D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAwBjD;;;GAGG;AACH,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,aAAa;IACb,MAAM;IACN,OAAO;IACP,UAAU;IACV,gBAAgB;IAChB,WAAW;IACX,WAAW;IACX,UAAU;CACX,CAAC,CAAC;AAEH,gHAAgH;AAChH,MAAM,mBAAmB,GAAG,CAAC,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,CAAC,CAAC;AAE7F,oIAAoI;AACpI,MAAM,OAAO,aAAc,SAAQ,8BAKlC;IACC,iNAAiN;IACjN,MAAM,CAAC,SAAS,CAAC,IAAa;QAC5B,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,YAAY,WAAW,EAAE,CAAC;YACxF,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,CAAC,MAAM,EAAE,UAAU,EAAE,iBAAiB,EAAE,gBAAgB,CAAC,CAAC,IAAI,C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AE,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,WAAW,CAAC,eAAe,CAAC;YAChD,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 { HttpResponseReader } from './common/response-reader';\nimport type { IFetchGuard } from './common/guard';\nimport type { IFetcherDefaults, IFetcherHooks } from './common/types';\nimport { HttpHeaders } 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/**\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 /** 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. */\n static 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 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 NativeFetcher.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 HttpResponseReader.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 = HttpHeaders.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 +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
|
-
*
|
|
14
|
+
* `'empty'` is `a=` (what `node:querystring` does), `'skip'` leaves the pair out.
|
|
15
|
+
* @default 'empty'
|
|
34
16
|
*/
|
|
35
|
-
nullish?:
|
|
17
|
+
nullish?: 'empty' | 'skip';
|
|
36
18
|
/**
|
|
37
19
|
* What an object or an array value becomes.
|
|
38
|
-
*
|
|
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?:
|
|
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 {
|
|
@@ -7,20 +7,6 @@ export class QueryStringSeparators {
|
|
|
7
7
|
/** Between a name and its value. */
|
|
8
8
|
static { this.ASSIGN = '='; }
|
|
9
9
|
}
|
|
10
|
-
/** What a `null` or `undefined` value becomes. */
|
|
11
|
-
export class QueryStringNullishModes {
|
|
12
|
-
/** An empty value (`a=`): what `node:querystring` does. */
|
|
13
|
-
static { this.EMPTY = 'empty'; }
|
|
14
|
-
/** The pair is left out. */
|
|
15
|
-
static { this.SKIP = 'skip'; }
|
|
16
|
-
}
|
|
17
|
-
/** What an object or an array value becomes. */
|
|
18
|
-
export class QueryStringNestedModes {
|
|
19
|
-
/** An empty value (an array repeats its key instead): what `node:querystring` does. */
|
|
20
|
-
static { this.DROP = 'drop'; }
|
|
21
|
-
/** One JSON-encoded parameter (`ids=[1,2]`, `filter={"where":{}}`), the shape a JSON filter travels in. */
|
|
22
|
-
static { this.JSON = 'json'; }
|
|
23
|
-
}
|
|
24
10
|
/** Builds a query string without a node builtin, so the network layer stays browser-safe. */
|
|
25
11
|
export class QueryStringUtility {
|
|
26
12
|
/**
|
|
@@ -40,10 +26,10 @@ export class QueryStringUtility {
|
|
|
40
26
|
* the trip. Without them the behavior is the one above.
|
|
41
27
|
*/
|
|
42
28
|
static toQueryString(opts) {
|
|
43
|
-
const { params, nullish =
|
|
29
|
+
const { params, nullish = 'empty', nested = 'drop' } = opts;
|
|
44
30
|
const parts = [];
|
|
45
|
-
const isSkipped = (value) => nullish ===
|
|
46
|
-
const isJson = nested ===
|
|
31
|
+
const isSkipped = (value) => nullish === 'skip' && (value === null || value === undefined);
|
|
32
|
+
const isJson = nested === 'json';
|
|
47
33
|
// A primitive only. `querystring` drops an object or a nested array to an empty value rather than
|
|
48
34
|
// stringifying it, and a caller that passed one meant something this format cannot carry anyway.
|
|
49
35
|
const encode = (value) => value === null || value === undefined || typeof value === 'object'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-string.js","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/query-string.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"query-string.js","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/query-string.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,MAAM,OAAO,qBAAqB;IAChC,2CAA2C;aAC3B,UAAK,GAAG,GAAG,CAAC;IAC5B,yBAAyB;aACT,SAAI,GAA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E,CACrF,CAAC;gBACF,SAAS;YACX,CAAC;YAED,2EAA2E;YAC3E,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;gBACzB,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,CAAC;oBAC1B,IAAI,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;wBACrB,SAAS;oBACX,CAAC;oBAED,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACvE,CAAC;gBAED,SAAS;YACX,CAAC;YAED,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACvE,CAAC;QAED,OAAO,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;IAChD,CAAC;CACF","sourcesContent":["/** The punctuation of a query string, named so a reader sees the role rather than the character. */\nexport class QueryStringSeparators {\n /** Between the path and the first pair. */\n static readonly START = '?';\n /** Between two pairs. */\n static readonly PAIR = '&';\n /** Between a name and its value. */\n static readonly ASSIGN = '=';\n}\n\n/** How {@link QueryStringUtility.toQueryString} treats the values `node:querystring` has no answer for. */\nexport interface IQueryStringOptions {\n /**\n * What a `null` or `undefined` value becomes.\n * `'empty'` is `a=` (what `node:querystring` does), `'skip'` leaves the pair out.\n * @default 'empty'\n */\n nullish?: 'empty' | 'skip';\n /**\n * What an object or an array value becomes.\n * `'drop'` is an empty value (an array repeats its key: what `node:querystring` does), `'json'` is one JSON-encoded parameter (`filter={\"where\":{}}`).\n * @default 'drop'\n */\n nested?: 'drop' | 'json';\n}\n\n/** Builds a query string without a node builtin, so the network layer stays browser-safe. */\nexport class QueryStringUtility {\n /**\n * `node:querystring`'s `stringify`, written out so nothing on the HTTP path carries a node builtin -\n * that one import is what kept the whole network layer out of a browser bundle.\n *\n * Not `new URLSearchParams(params).toString()`, which differs on four counts measured against the\n * original: an array becomes `a=1%2C2` instead of `a=1&a=2`, `undefined` and `null` become the\n * STRINGS \"undefined\" and \"null\" instead of an empty value, and a space encodes as `+` rather than\n * `%20`. The first changes what a server parses; the second is the same coercion that sends a header\n * reading \"undefined\".\n *\n * Diffed against `node:querystring` across 22 shapes with zero mismatches.\n *\n * `nullish: 'skip'` leaves a null or undefined pair out. `nested: 'json'` sends an object or an\n * array as ONE JSON parameter instead (an array does not repeat its key), so a filter object survives\n * the trip. Without them the behavior is the one above.\n */\n static toQueryString(opts: { params: Record<string, unknown> } & IQueryStringOptions): string {\n const { params, nullish = 'empty', nested = 'drop' } = opts;\n const parts: string[] = [];\n const isSkipped = (value: unknown) =>\n nullish === 'skip' && (value === null || value === undefined);\n const isJson = nested === 'json';\n\n // A primitive only. `querystring` drops an object or a nested array to an empty value rather than\n // stringifying it, and a caller that passed one meant something this format cannot carry anyway.\n const encode = (value: unknown) =>\n value === null || value === undefined || typeof value === 'object'\n ? ''\n : encodeURIComponent(String(value));\n\n const entries = Object.entries(params);\n\n for (const [key, value] of entries) {\n const name = encodeURIComponent(key);\n\n if (isSkipped(value)) {\n continue;\n }\n\n if (isJson && typeof value === 'object' && value !== null) {\n parts.push(\n `${name}${QueryStringSeparators.ASSIGN}${encodeURIComponent(JSON.stringify(value))}`,\n );\n continue;\n }\n\n // An array repeats the key, which is what a server reading a list expects.\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (isSkipped(entry)) {\n continue;\n }\n\n parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(entry)}`);\n }\n\n continue;\n }\n\n parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(value)}`);\n }\n\n return parts.join(QueryStringSeparators.PAIR);\n }\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Building the url of a request from a base and path segments, so a segment cannot leave the base. */
|
|
2
|
+
export declare class UrlBuilder {
|
|
3
|
+
/** The origin of the page or Web Worker that runs this, or `undefined` on a server: the browser global `location` is not declared for a server build, so it is probed. */
|
|
4
|
+
static readLocationOrigin(): string | undefined;
|
|
5
|
+
/** The base is an absolute url or a path from the origin (`/api`), and carries no query or fragment. */
|
|
6
|
+
static assertBase(opts: {
|
|
7
|
+
baseUrl: string;
|
|
8
|
+
scope: string;
|
|
9
|
+
}): void;
|
|
10
|
+
/** The request paths name a place under the base path, so none may be a dot segment, hide one, or carry a separator the URL parser would read differently from a server. */
|
|
11
|
+
static assertPaths(opts: {
|
|
12
|
+
paths: ReadonlyArray<string>;
|
|
13
|
+
scope: string;
|
|
14
|
+
}): void;
|
|
15
|
+
/** `baseUrl` (no trailing slash) followed by each path with one leading slash: `('/api/', ['a', '/b'])` is `/api/a/b`. */
|
|
16
|
+
static toText(opts: {
|
|
17
|
+
baseUrl: string;
|
|
18
|
+
paths: ReadonlyArray<string>;
|
|
19
|
+
}): string;
|
|
20
|
+
/**
|
|
21
|
+
* The url of a request: the base and the paths, checked. A path may not be a dot segment, hide one, or carry a backslash
|
|
22
|
+
* or a control character; a relative base (`/api`) is resolved against `origin` (the page's, by default); and the result
|
|
23
|
+
* must be on the base's origin and under its path.
|
|
24
|
+
*/
|
|
25
|
+
static join(opts: {
|
|
26
|
+
baseUrl: string;
|
|
27
|
+
paths: ReadonlyArray<string>;
|
|
28
|
+
scope: string;
|
|
29
|
+
origin?: string;
|
|
30
|
+
}): URL;
|
|
31
|
+
/** The resolved URL, whatever built it, is on the base's origin and under its path: the check that holds when the text checks above miss a form. */
|
|
32
|
+
static assertUnderBase(opts: {
|
|
33
|
+
url: URL;
|
|
34
|
+
baseUrl: string;
|
|
35
|
+
origin?: string;
|
|
36
|
+
scope: string;
|
|
37
|
+
}): void;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=url-builder.d.ts.map
|