@formless63/provider-http 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/dist/.tsbuildinfo +1 -0
- package/dist/client.d.ts +79 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +176 -0
- package/dist/client.js.map +1 -0
- package/dist/errors.d.ts +65 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +117 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/rate-budget.d.ts +40 -0
- package/dist/rate-budget.d.ts.map +1 -0
- package/dist/rate-budget.js +110 -0
- package/dist/rate-budget.js.map +1 -0
- package/dist/url.d.ts +23 -0
- package/dist/url.d.ts.map +1 -0
- package/dist/url.js +134 -0
- package/dist/url.js.map +1 -0
- package/package.json +39 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 formless63
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @formless63/provider-http
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Plumbing for API clients: safe requests, safe errors, rate budgets. No dependencies.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { createHttpClient, createRateBudget, kindFromStatus } from "@formless63/provider-http";
|
|
7
|
+
|
|
8
|
+
const http = createHttpClient({
|
|
9
|
+
provider: "Acme",
|
|
10
|
+
baseUrl: "https://api.acme.example/v1",
|
|
11
|
+
headers: { authorization: `Bearer ${token}` },
|
|
12
|
+
secrets: [token],
|
|
13
|
+
rateBudget: createRateBudget({ provider: "Acme", capacity: 5, refillPerSecond: 1 })
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const result = await http.request({ operation: "things.list", path: "/things", query: { page: 1 } });
|
|
17
|
+
if (result.status !== 200) {
|
|
18
|
+
throw http.error({
|
|
19
|
+
kind: kindFromStatus(result.status),
|
|
20
|
+
message: `Acme refused: ${http.safeText(result.text)}`,
|
|
21
|
+
status: result.status,
|
|
22
|
+
retryAfterMs: result.retryAfterMs
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
const body = result.json();
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`request` resolves for any HTTP status and rejects only without a usable response: `timeout`, `aborted`,
|
|
29
|
+
`unavailable`, `rate_limited` (local budget) or `invalid_response` (too large). Redirects are refused.
|
|
30
|
+
|
|
31
|
+
Also exported: `normalizeBaseUrl`, `isPrivateHost` (literals and special names; it does not resolve DNS),
|
|
32
|
+
`parseRetryAfter`, `safeProviderText`, `readBounded`, `sleep`.
|
|
33
|
+
|
|
34
|
+
`retryable` means the request might succeed later. It does not mean repeating a write is safe.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":"7.0.2","root":[[64,68]],"packageJsons":["../package.json"],"fileNames":["lib.es5.d.ts","lib.es2015.d.ts","lib.es2016.d.ts","lib.es2017.d.ts","lib.es2018.d.ts","lib.es2019.d.ts","lib.es2020.d.ts","lib.es2021.d.ts","lib.es2022.d.ts","lib.es2023.d.ts","lib.dom.d.ts","lib.dom.iterable.d.ts","lib.es2015.core.d.ts","lib.es2015.collection.d.ts","lib.es2015.generator.d.ts","lib.es2015.iterable.d.ts","lib.es2015.promise.d.ts","lib.es2015.proxy.d.ts","lib.es2015.reflect.d.ts","lib.es2015.symbol.d.ts","lib.es2015.symbol.wellknown.d.ts","lib.es2016.array.include.d.ts","lib.es2016.intl.d.ts","lib.es2017.arraybuffer.d.ts","lib.es2017.date.d.ts","lib.es2017.object.d.ts","lib.es2017.sharedmemory.d.ts","lib.es2017.string.d.ts","lib.es2017.intl.d.ts","lib.es2017.typedarrays.d.ts","lib.es2018.asyncgenerator.d.ts","lib.es2018.asynciterable.d.ts","lib.es2018.intl.d.ts","lib.es2018.promise.d.ts","lib.es2018.regexp.d.ts","lib.es2019.array.d.ts","lib.es2019.object.d.ts","lib.es2019.string.d.ts","lib.es2019.symbol.d.ts","lib.es2019.intl.d.ts","lib.es2020.bigint.d.ts","lib.es2020.date.d.ts","lib.es2020.promise.d.ts","lib.es2020.sharedmemory.d.ts","lib.es2020.string.d.ts","lib.es2020.symbol.wellknown.d.ts","lib.es2020.intl.d.ts","lib.es2020.number.d.ts","lib.es2021.promise.d.ts","lib.es2021.string.d.ts","lib.es2021.weakref.d.ts","lib.es2021.intl.d.ts","lib.es2022.array.d.ts","lib.es2022.error.d.ts","lib.es2022.intl.d.ts","lib.es2022.object.d.ts","lib.es2022.string.d.ts","lib.es2022.regexp.d.ts","lib.es2023.array.d.ts","lib.es2023.collection.d.ts","lib.es2023.intl.d.ts","lib.decorators.d.ts","lib.decorators.legacy.d.ts","../src/errors.ts","../src/rate-budget.ts","../src/url.ts","../src/client.ts","../src/index.ts"],"fileInfos":[{"version":"16934abaab7026ac114da441aabea1a0","affectsGlobalScope":true,"impliedNodeFormat":1},"d4306fb2e47f74835e8674ffac07d76f","e437c5c1302869326c3bb93da85bbbcf","e4324975a566567b21d350615f1fc6ac","333b1b9a2a9ac3b8497dba5c63b5ba50","6cffacd662b6eb5fa7a36aa2ea366bfa","b4c34f9c23304dbef2d23698637ed638","e5cb86a5fc491796ecd1d2dd348d208f","feb6c6fb19cdb246a5d8acb36a6901c7","9443a7f109277ffaa79d893ed2549995",{"version":"aae8996e8b5684814785a42cbbefcd79","affectsGlobalScope":true,"impliedNodeFormat":1},"abad6dd56cc8caf095c165df8124d237",{"version":"926204c28cd3d073865348473ae28d2e","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"f25e42c801b2cb3cf2b39792006a9beb","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6344b55f26a4e81d9608777dbfb877dd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3c0ed28e53d3695b363e256ec1c023fd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4c2761daba7f17141c25baa0821ac5da","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b87656acabd63e69379ff6ffcfe52fc7","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"597469522da047a5af5222cc6989f405","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1708ea4d34dc37fadadc63ca01127e80","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"55d97a8c6fbf34a30450a7b1e5f7a298","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"0ee05eb59426d33e374226d8dcfa708b","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"e347c14030993906efcfbb88915b6a05","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b0231263857c9b6a03641acdc9280ceb","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3b15c4a83b598cacb4067676e6f0abed","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b417d97b7934cef63b1889abec0bbfbf","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"09a6cf4032ebba60ce22a501e663f881","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2b056277dd138e8f5650fc04e20eaa8d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"e22cc07e3f3cc242ba52fa3f8ea1fc58","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2c45da767a1bfbb220848df1bc4029e4","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b44c3e0fbaf2130cdcf6ac38b120ffa1","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b612fb5cf8e5d964b92063a75207632a","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"02705151a5e1551b9162a9ed8ab763f7","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"41025e398be9215d32e4337335da8f0b","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"52684c2b1f353a5538e4f275182a54cd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6dedb6a4f90d1df3a6fbe5693e44886c","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"ca3f36fe3562c07e0f0d71c2bebd3f6d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"409974d6129befbb8226ddd1c6558568","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4d9cfde2a1ae1b4925f1f9bc10848e5d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"7e1daecc66dd564144e3bb1a0266b5fd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a8e1d9bb35fd0637f2f9fd2b2a54f2ec","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4f168501772a6543182765bfd5f2fbfe","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a19c80aad1b2162103496f5ba293a732","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b69afa63cd5d059851c78adb2856ee09","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"ae2fc5d954e9b0f5feee3d481b953c27","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1cfd3091a071d8b6feec15277643bafe","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1da2c1f258970fd3cc91184f69e91a9d","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a0d87491913d843139e0c993650a3235","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4ef72aa378127e7b7abba915b0110b1e","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"3ec74c6a7d4463f0254db3a74cf75646","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"84c2bdfa470d075526cce6322d81b0b6","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"0b3844c2b8c73e4e1ab91431411cad11","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"4fc71cf4a15b8d99675a31df77f26e07","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d1b49564ddaeca3df5b6dbae925d2242","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6a25be566d60ccfc2d6e8b7bfdeefa83","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8a20e27646985dfd58c57ca6566553dd","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"9969f02ad3cdcbf4f709405cda44167f","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"9c9be4792a7a4f42c15ae7360bf28779","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8cf777fe00349b71ee9c4b6f3fe7fd19","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"74f96bc192530c9723f572bfff3d3078","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"1df91c56b25955c56387426f378173c5","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"f64453cbf9671f28158677fa5c43967a","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"33f317af5428801f944a478d2c1e38e5","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"5349a06a02cd85c15f5996b6f019218a","signature":"beb330e63ebb8f469a1fa417cdf076f4","impliedNodeFormat":99},{"version":"458b3fab84997c53c900f8195a341dc2","signature":"916d5c1edcce2ae32520b3c6eb62d519","impliedNodeFormat":99},{"version":"7eb7a52a059f953307ca6e5f4c60bfd1","signature":"de64673f25eb32e9f47f9e9aee4a4fe6","impliedNodeFormat":99},{"version":"69960d12efb86a6ea5321a9c15de7d20","signature":"6dfe22d6d2b05dc49395759eab07cd84","impliedNodeFormat":99},{"version":"cb426bf5a12c14db800be65b77a87c94","impliedNodeFormat":99}],"fileIdsList":[[64,65,66],[64,65,66,67],[64]],"options":{"allowImportingTsExtensions":true,"composite":true,"declaration":true,"declarationMap":true,"erasableSyntaxOnly":true,"exactOptionalPropertyTypes":true,"module":199,"noUncheckedIndexedAccess":true,"outDir":"./","rewriteRelativeImportExtensions":true,"rootDir":"../src","skipLibCheck":true,"strict":true,"sourceMap":true,"target":10,"tsBuildInfoFile":"./.tsbuildinfo","verbatimModuleSyntax":true},"referencedMap":[[67,1],[68,2],[65,3],[66,3]],"latestChangedDtsFile":"./index.d.ts"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { ProviderError, type ProviderErrorOptions } from './errors.ts';
|
|
2
|
+
import type { RateBudget } from './rate-budget.ts';
|
|
3
|
+
import { type BaseUrlOptions } from './url.ts';
|
|
4
|
+
/** The part of `fetch` this package uses. `globalThis.fetch` satisfies it. */
|
|
5
|
+
export type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponse>;
|
|
6
|
+
export interface FetchInit {
|
|
7
|
+
method: string;
|
|
8
|
+
headers: Record<string, string>;
|
|
9
|
+
signal: AbortSignal;
|
|
10
|
+
redirect: 'error' | 'manual';
|
|
11
|
+
body?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface FetchResponse {
|
|
14
|
+
readonly status: number;
|
|
15
|
+
readonly headers?: {
|
|
16
|
+
get(name: string): string | null;
|
|
17
|
+
};
|
|
18
|
+
readonly body?: ReadableStream<Uint8Array> | null;
|
|
19
|
+
text(): Promise<string>;
|
|
20
|
+
}
|
|
21
|
+
export type QueryValue = string | number | boolean | null | undefined;
|
|
22
|
+
export interface HttpRequest {
|
|
23
|
+
/** Label for errors, e.g. `zones.list`. */
|
|
24
|
+
operation: string;
|
|
25
|
+
method?: string;
|
|
26
|
+
/** Appended to the base URL. Build segments with `encodeURIComponent`. */
|
|
27
|
+
path?: string;
|
|
28
|
+
query?: Record<string, QueryValue>;
|
|
29
|
+
headers?: Record<string, string>;
|
|
30
|
+
/** Sent as JSON. */
|
|
31
|
+
json?: unknown;
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
}
|
|
34
|
+
export interface HttpResult {
|
|
35
|
+
status: number;
|
|
36
|
+
text: string;
|
|
37
|
+
retryAfterMs: number | null;
|
|
38
|
+
header(name: string): string | null;
|
|
39
|
+
/** Parses the body, throwing `invalid_response` when it is not JSON. */
|
|
40
|
+
json(): unknown;
|
|
41
|
+
}
|
|
42
|
+
export interface HttpClientOptions extends Omit<BaseUrlOptions, 'provider'> {
|
|
43
|
+
provider: string;
|
|
44
|
+
baseUrl: string;
|
|
45
|
+
/** Sent on every request. Values are never placed in errors. */
|
|
46
|
+
headers?: Record<string, string>;
|
|
47
|
+
/** Credential values to strip from any provider text that reaches an error. */
|
|
48
|
+
secrets?: readonly string[];
|
|
49
|
+
fetch?: FetchLike;
|
|
50
|
+
timeoutMs?: number;
|
|
51
|
+
maxResponseBytes?: number;
|
|
52
|
+
rateBudget?: RateBudget;
|
|
53
|
+
/** Lets a package throw its own subclass. */
|
|
54
|
+
createError?: (options: ProviderErrorOptions) => ProviderError;
|
|
55
|
+
}
|
|
56
|
+
export interface HttpClient {
|
|
57
|
+
readonly provider: string;
|
|
58
|
+
readonly baseUrl: string;
|
|
59
|
+
/** Performs one request. Resolves for any HTTP status; throws only without a usable response. */
|
|
60
|
+
request(request: HttpRequest): Promise<HttpResult>;
|
|
61
|
+
/** Builds an error with provider text already made safe. */
|
|
62
|
+
error(options: Omit<ProviderErrorOptions, 'provider'>): ProviderError;
|
|
63
|
+
/** Strips credentials and control characters from provider text. */
|
|
64
|
+
safeText(text: string, maxLength?: number): string;
|
|
65
|
+
}
|
|
66
|
+
export declare const DEFAULT_TIMEOUT_MS = 20000;
|
|
67
|
+
export declare const DEFAULT_MAX_RESPONSE_BYTES = 5000000;
|
|
68
|
+
/** Rejects values that would break out of a header. */
|
|
69
|
+
export declare function assertHeaderSafe(provider: string, label: string, value: unknown): string;
|
|
70
|
+
/** Reads at most `limit` bytes, so a hostile or broken server cannot exhaust memory. */
|
|
71
|
+
export declare function readBounded(response: FetchResponse, limit: number): Promise<string>;
|
|
72
|
+
/**
|
|
73
|
+
* A small request function with the safety rules every provider client needs:
|
|
74
|
+
* redirects are refused (so credentials cannot be replayed to another origin),
|
|
75
|
+
* responses are size-bounded, requests time out, and nothing from the request
|
|
76
|
+
* or the transport error can reach a thrown message.
|
|
77
|
+
*/
|
|
78
|
+
export declare function createHttpClient(options: HttpClientOptions): HttpClient;
|
|
79
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,aAAa,EAAoB,KAAK,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAC1G,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAoB,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAEjE,8EAA8E;AAC9E,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,KAAK,OAAO,CAAC,aAAa,CAAC,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EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAyBzF;AAoBD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,GAAG,UAAU,CAwGvE"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { parseRetryAfter, ProviderError, safeProviderText } from './errors.js';
|
|
2
|
+
import { normalizeBaseUrl } from './url.js';
|
|
3
|
+
export const DEFAULT_TIMEOUT_MS = 20_000;
|
|
4
|
+
export const DEFAULT_MAX_RESPONSE_BYTES = 5_000_000;
|
|
5
|
+
/** Rejects values that would break out of a header. */
|
|
6
|
+
export function assertHeaderSafe(provider, label, value) {
|
|
7
|
+
// oxlint-disable-next-line no-control-regex
|
|
8
|
+
if (typeof value !== 'string' || value.trim() === '' || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
9
|
+
throw new ProviderError({
|
|
10
|
+
provider,
|
|
11
|
+
kind: 'invalid_input',
|
|
12
|
+
message: `the ${provider} ${label} is missing or malformed`
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
return value.trim();
|
|
16
|
+
}
|
|
17
|
+
class TooLarge extends Error {
|
|
18
|
+
}
|
|
19
|
+
/** Reads at most `limit` bytes, so a hostile or broken server cannot exhaust memory. */
|
|
20
|
+
export async function readBounded(response, limit) {
|
|
21
|
+
const declared = Number(response.headers?.get('content-length') ?? Number.NaN);
|
|
22
|
+
if (declared > limit) {
|
|
23
|
+
await response.body?.cancel().catch(() => undefined);
|
|
24
|
+
throw new TooLarge();
|
|
25
|
+
}
|
|
26
|
+
if (!response.body) {
|
|
27
|
+
const text = await response.text();
|
|
28
|
+
if (new TextEncoder().encode(text).byteLength > limit)
|
|
29
|
+
throw new TooLarge();
|
|
30
|
+
return text;
|
|
31
|
+
}
|
|
32
|
+
const reader = response.body.getReader();
|
|
33
|
+
const decoder = new TextDecoder();
|
|
34
|
+
let size = 0;
|
|
35
|
+
let text = '';
|
|
36
|
+
for (;;) {
|
|
37
|
+
const { done, value } = await reader.read();
|
|
38
|
+
if (done)
|
|
39
|
+
return text + decoder.decode();
|
|
40
|
+
size += value.byteLength;
|
|
41
|
+
if (size > limit) {
|
|
42
|
+
await reader.cancel().catch(() => undefined);
|
|
43
|
+
throw new TooLarge();
|
|
44
|
+
}
|
|
45
|
+
text += decoder.decode(value, { stream: true });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** A network error code such as ECONNREFUSED. Anything else could echo a URL. */
|
|
49
|
+
function networkCode(error) {
|
|
50
|
+
for (const candidate of [error, error?.cause]) {
|
|
51
|
+
const code = candidate?.code;
|
|
52
|
+
if (typeof code === 'string' && /^[A-Z][A-Z0-9_]{2,40}$/.test(code))
|
|
53
|
+
return code;
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
function buildQuery(query) {
|
|
58
|
+
const params = new URLSearchParams();
|
|
59
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
60
|
+
if (value !== undefined && value !== null)
|
|
61
|
+
params.append(key, String(value));
|
|
62
|
+
}
|
|
63
|
+
const text = params.toString();
|
|
64
|
+
return text === '' ? '' : `?${text}`;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* A small request function with the safety rules every provider client needs:
|
|
68
|
+
* redirects are refused (so credentials cannot be replayed to another origin),
|
|
69
|
+
* responses are size-bounded, requests time out, and nothing from the request
|
|
70
|
+
* or the transport error can reach a thrown message.
|
|
71
|
+
*/
|
|
72
|
+
export function createHttpClient(options) {
|
|
73
|
+
const { provider } = options;
|
|
74
|
+
const baseUrl = normalizeBaseUrl(options.baseUrl, { ...options, provider });
|
|
75
|
+
const doFetch = options.fetch ?? ((url, init) => globalThis.fetch(url, init));
|
|
76
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
77
|
+
const limit = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
|
|
78
|
+
const secrets = options.secrets ?? [];
|
|
79
|
+
const makeError = options.createError ?? ((input) => new ProviderError(input));
|
|
80
|
+
const error = (input) => makeError({ ...input, provider });
|
|
81
|
+
const safeText = (text, maxLength) => safeProviderText(text, secrets, maxLength);
|
|
82
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
83
|
+
throw error({ kind: 'invalid_input', message: `the ${provider} timeout must be positive` });
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
provider,
|
|
87
|
+
baseUrl,
|
|
88
|
+
error,
|
|
89
|
+
safeText,
|
|
90
|
+
async request(input) {
|
|
91
|
+
const { operation } = input;
|
|
92
|
+
try {
|
|
93
|
+
await options.rateBudget?.acquire(1, input.signal ? { signal: input.signal } : {});
|
|
94
|
+
}
|
|
95
|
+
catch (cause) {
|
|
96
|
+
if (cause instanceof ProviderError) {
|
|
97
|
+
throw error({
|
|
98
|
+
kind: cause.kind,
|
|
99
|
+
message: cause.message,
|
|
100
|
+
operation,
|
|
101
|
+
retryAfterMs: cause.retryAfterMs,
|
|
102
|
+
detail: cause.detail
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
throw cause;
|
|
106
|
+
}
|
|
107
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
108
|
+
const signal = input.signal ? AbortSignal.any([timeout, input.signal]) : timeout;
|
|
109
|
+
const failure = (cause) => {
|
|
110
|
+
if (cause instanceof TooLarge) {
|
|
111
|
+
return error({
|
|
112
|
+
kind: 'invalid_response',
|
|
113
|
+
message: `the ${provider} answer is too large (over ${limit} bytes)`,
|
|
114
|
+
operation
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
if (input.signal?.aborted) {
|
|
118
|
+
return error({ kind: 'aborted', message: `the ${provider} request was aborted`, operation });
|
|
119
|
+
}
|
|
120
|
+
if (timeout.aborted || cause?.name === 'TimeoutError') {
|
|
121
|
+
return error({
|
|
122
|
+
kind: 'timeout',
|
|
123
|
+
message: `${provider} did not answer within ${timeoutMs} ms`,
|
|
124
|
+
operation
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
const code = networkCode(cause);
|
|
128
|
+
return error({
|
|
129
|
+
kind: 'unavailable',
|
|
130
|
+
message: `${provider} could not be reached${code ? ` (${code})` : ''}`,
|
|
131
|
+
operation,
|
|
132
|
+
detail: code ? { networkCode: code } : {}
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
try {
|
|
136
|
+
signal.throwIfAborted();
|
|
137
|
+
const response = await doFetch(`${baseUrl}${input.path ?? ''}${buildQuery(input.query)}`, {
|
|
138
|
+
method: input.method ?? 'GET',
|
|
139
|
+
headers: {
|
|
140
|
+
...(input.json === undefined ? {} : { 'content-type': 'application/json' }),
|
|
141
|
+
...options.headers,
|
|
142
|
+
...input.headers
|
|
143
|
+
},
|
|
144
|
+
signal,
|
|
145
|
+
redirect: 'error',
|
|
146
|
+
...(input.json === undefined ? {} : { body: JSON.stringify(input.json) })
|
|
147
|
+
});
|
|
148
|
+
const text = await readBounded(response, limit);
|
|
149
|
+
const header = (name) => response.headers?.get(name) ?? null;
|
|
150
|
+
return {
|
|
151
|
+
status: response.status,
|
|
152
|
+
text,
|
|
153
|
+
retryAfterMs: parseRetryAfter(header('retry-after')),
|
|
154
|
+
header,
|
|
155
|
+
json() {
|
|
156
|
+
try {
|
|
157
|
+
return JSON.parse(text);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
throw error({
|
|
161
|
+
kind: 'invalid_response',
|
|
162
|
+
message: `the ${provider} answer is not JSON`,
|
|
163
|
+
status: response.status,
|
|
164
|
+
operation
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
catch (cause) {
|
|
171
|
+
throw failure(cause);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|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AC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;YACvB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One error vocabulary for every provider client, so callers can branch on
|
|
3
|
+
* `kind` without knowing the provider.
|
|
4
|
+
*/
|
|
5
|
+
export declare const PROVIDER_ERROR_KINDS: readonly [
|
|
6
|
+
/** The caller passed something unusable; no request was made. */
|
|
7
|
+
'invalid_input',
|
|
8
|
+
/** The provider understood the request and refused it. */
|
|
9
|
+
'invalid_request',
|
|
10
|
+
/** The credential is missing, wrong or expired. */
|
|
11
|
+
'unauthorized',
|
|
12
|
+
/** The credential is valid but not allowed to do this. */
|
|
13
|
+
'forbidden', 'not_found',
|
|
14
|
+
/** The provider, or the local rate budget, is limiting requests. */
|
|
15
|
+
'rate_limited', 'timeout',
|
|
16
|
+
/** The caller's AbortSignal fired. */
|
|
17
|
+
'aborted',
|
|
18
|
+
/** Network failure or a provider 5xx. */
|
|
19
|
+
'unavailable',
|
|
20
|
+
/** The provider answered with something that could not be understood. */
|
|
21
|
+
'invalid_response'];
|
|
22
|
+
export type ProviderErrorKind = (typeof PROVIDER_ERROR_KINDS)[number];
|
|
23
|
+
export interface ProviderErrorOptions {
|
|
24
|
+
provider: string;
|
|
25
|
+
kind: ProviderErrorKind;
|
|
26
|
+
message: string;
|
|
27
|
+
/** HTTP status, when a response was received. */
|
|
28
|
+
status?: number | null;
|
|
29
|
+
/** Client operation label such as `zones.list`. Never a URL. */
|
|
30
|
+
operation?: string | null;
|
|
31
|
+
/** The provider's own error code, verbatim. */
|
|
32
|
+
providerCode?: string | null;
|
|
33
|
+
retryAfterMs?: number | null;
|
|
34
|
+
/** Extra sanitized evidence. Must not contain credentials, headers, URLs or bodies. */
|
|
35
|
+
detail?: Readonly<Record<string, unknown>>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Thrown by every client. Everything on it is safe to log: no headers, URLs,
|
|
39
|
+
* query strings, bodies, credentials, or underlying `cause`.
|
|
40
|
+
*/
|
|
41
|
+
export declare class ProviderError extends Error {
|
|
42
|
+
readonly provider: string;
|
|
43
|
+
readonly kind: ProviderErrorKind;
|
|
44
|
+
readonly status: number | null;
|
|
45
|
+
readonly operation: string | null;
|
|
46
|
+
readonly providerCode: string | null;
|
|
47
|
+
readonly retryAfterMs: number | null;
|
|
48
|
+
readonly detail: Readonly<Record<string, unknown>>;
|
|
49
|
+
constructor(options: ProviderErrorOptions);
|
|
50
|
+
/**
|
|
51
|
+
* Whether the same request might succeed later. This says nothing about
|
|
52
|
+
* whether repeating it is safe: a timed-out create may have happened.
|
|
53
|
+
*/
|
|
54
|
+
get retryable(): boolean;
|
|
55
|
+
toJSON(): Record<string, unknown>;
|
|
56
|
+
}
|
|
57
|
+
export declare function kindFromStatus(status: number): ProviderErrorKind;
|
|
58
|
+
/** Parses `Retry-After` (delta seconds or HTTP date) to milliseconds, or null. */
|
|
59
|
+
export declare function parseRetryAfter(value: string | null, now?: number): number | null;
|
|
60
|
+
/**
|
|
61
|
+
* Makes provider-supplied text safe to put in an error: secrets (and their
|
|
62
|
+
* URL-encoded forms) are replaced, control characters removed, length bounded.
|
|
63
|
+
*/
|
|
64
|
+
export declare function safeProviderText(text: string, secrets?: readonly string[], maxLength?: number): string;
|
|
65
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,oBAAoB;AAC/B,iEAAiE;AACjE,eAAe;AACf,0DAA0D;AAC1D,iBAAiB;AACjB,mDAAmD;AACnD,cAAc;AACd,0DAA0D;AAC1D,WAAW,EACX,WAAW;AACX,oEAAoE;AACpE,cAAc,EACd,SAAS;AACT,sCAAsC;AACt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AED,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,iBAAiB,CAShE;AAED,kFAAkF;AAClF,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,GAAE,MAAmB,GAAG,MAAM,GAAG,IAAI,CAM7F;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,SAAS,MAAM,EAAO,EAC/B,SAAS,SAAM,GACd,MAAM,CAeR"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One error vocabulary for every provider client, so callers can branch on
|
|
3
|
+
* `kind` without knowing the provider.
|
|
4
|
+
*/
|
|
5
|
+
export const PROVIDER_ERROR_KINDS = [
|
|
6
|
+
/** The caller passed something unusable; no request was made. */
|
|
7
|
+
'invalid_input',
|
|
8
|
+
/** The provider understood the request and refused it. */
|
|
9
|
+
'invalid_request',
|
|
10
|
+
/** The credential is missing, wrong or expired. */
|
|
11
|
+
'unauthorized',
|
|
12
|
+
/** The credential is valid but not allowed to do this. */
|
|
13
|
+
'forbidden',
|
|
14
|
+
'not_found',
|
|
15
|
+
/** The provider, or the local rate budget, is limiting requests. */
|
|
16
|
+
'rate_limited',
|
|
17
|
+
'timeout',
|
|
18
|
+
/** The caller's AbortSignal fired. */
|
|
19
|
+
'aborted',
|
|
20
|
+
/** Network failure or a provider 5xx. */
|
|
21
|
+
'unavailable',
|
|
22
|
+
/** The provider answered with something that could not be understood. */
|
|
23
|
+
'invalid_response'
|
|
24
|
+
];
|
|
25
|
+
/**
|
|
26
|
+
* Thrown by every client. Everything on it is safe to log: no headers, URLs,
|
|
27
|
+
* query strings, bodies, credentials, or underlying `cause`.
|
|
28
|
+
*/
|
|
29
|
+
export class ProviderError extends Error {
|
|
30
|
+
provider;
|
|
31
|
+
kind;
|
|
32
|
+
status;
|
|
33
|
+
operation;
|
|
34
|
+
providerCode;
|
|
35
|
+
retryAfterMs;
|
|
36
|
+
detail;
|
|
37
|
+
constructor(options) {
|
|
38
|
+
super(options.message);
|
|
39
|
+
this.name = new.target.name;
|
|
40
|
+
this.provider = options.provider;
|
|
41
|
+
this.kind = options.kind;
|
|
42
|
+
this.status = options.status ?? null;
|
|
43
|
+
this.operation = options.operation ?? null;
|
|
44
|
+
this.providerCode = options.providerCode ?? null;
|
|
45
|
+
this.retryAfterMs = options.retryAfterMs ?? null;
|
|
46
|
+
this.detail = options.detail ?? {};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Whether the same request might succeed later. This says nothing about
|
|
50
|
+
* whether repeating it is safe: a timed-out create may have happened.
|
|
51
|
+
*/
|
|
52
|
+
get retryable() {
|
|
53
|
+
return this.kind === 'rate_limited' || this.kind === 'timeout' || this.kind === 'unavailable';
|
|
54
|
+
}
|
|
55
|
+
toJSON() {
|
|
56
|
+
return {
|
|
57
|
+
name: this.name,
|
|
58
|
+
message: this.message,
|
|
59
|
+
provider: this.provider,
|
|
60
|
+
kind: this.kind,
|
|
61
|
+
status: this.status,
|
|
62
|
+
operation: this.operation,
|
|
63
|
+
providerCode: this.providerCode,
|
|
64
|
+
retryAfterMs: this.retryAfterMs,
|
|
65
|
+
detail: this.detail
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export function kindFromStatus(status) {
|
|
70
|
+
if (status === 401)
|
|
71
|
+
return 'unauthorized';
|
|
72
|
+
if (status === 403)
|
|
73
|
+
return 'forbidden';
|
|
74
|
+
if (status === 404)
|
|
75
|
+
return 'not_found';
|
|
76
|
+
if (status === 408 || status === 504)
|
|
77
|
+
return 'timeout';
|
|
78
|
+
if (status === 429)
|
|
79
|
+
return 'rate_limited';
|
|
80
|
+
if (status >= 400 && status < 500)
|
|
81
|
+
return 'invalid_request';
|
|
82
|
+
if (status >= 500)
|
|
83
|
+
return 'unavailable';
|
|
84
|
+
return 'invalid_response';
|
|
85
|
+
}
|
|
86
|
+
/** Parses `Retry-After` (delta seconds or HTTP date) to milliseconds, or null. */
|
|
87
|
+
export function parseRetryAfter(value, now = Date.now()) {
|
|
88
|
+
if (value === null)
|
|
89
|
+
return null;
|
|
90
|
+
const text = value.trim();
|
|
91
|
+
if (/^\d{1,9}$/.test(text))
|
|
92
|
+
return Number(text) * 1000;
|
|
93
|
+
const at = Date.parse(text);
|
|
94
|
+
return Number.isNaN(at) ? null : Math.max(0, at - now);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Makes provider-supplied text safe to put in an error: secrets (and their
|
|
98
|
+
* URL-encoded forms) are replaced, control characters removed, length bounded.
|
|
99
|
+
*/
|
|
100
|
+
export function safeProviderText(text, secrets = [], maxLength = 200) {
|
|
101
|
+
let clean = text;
|
|
102
|
+
for (const secret of secrets) {
|
|
103
|
+
if (secret === '')
|
|
104
|
+
continue;
|
|
105
|
+
for (const form of new Set([
|
|
106
|
+
secret,
|
|
107
|
+
encodeURIComponent(secret),
|
|
108
|
+
new URLSearchParams([['', secret]]).toString().slice(1)
|
|
109
|
+
])) {
|
|
110
|
+
clean = clean.split(form).join('[redacted]');
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// oxlint-disable-next-line no-control-regex
|
|
114
|
+
clean = clean.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim();
|
|
115
|
+
return clean.length > maxLength ? `${clean.slice(0, maxLength)}…` : clean;
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,iEAAiE;IACjE,eAAe;IACf,0DAA0D;IAC1D,iBAAiB;IACjB,mDAAmD;IACnD,cAAc;IACd,0DAA0D;IAC1D,WAAW;IACX,WAAW;IACX,oEAAoE;IACpE,cAAc;IACd,SAA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AGG;AACH,MAAM,UAAU,gBAAgB,CAC9B,IAAY,EACZ,OAAO,GAAsB,EAAE,EAC/B,SAAS,GAAG,GAAG;IAEf,IAAI,KAAK,GAAG,IAAI,CAAC;IACjB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,MAAM,KAAK,EAAE;YAAE,SAAS;QAC5B,KAAK,MAAM,IAAI,IAAI,IAAI,GAAG,CAAC;YACzB,MAAM;YACN,kBAAkB,CAAC,MAAM,CAAC;YAC1B,IAAI,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;SACxD,CAAC,EAAE,CAAC;YACH,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;IACD,4CAA4C;IAC5C,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IAC7D,OAAO,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC;AAC5E,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export interface RateBudgetStats {
|
|
2
|
+
capacity: number;
|
|
3
|
+
refillPerSecond: number;
|
|
4
|
+
/** Tokens available now; 0 while waiters have reserved ahead. */
|
|
5
|
+
available: number;
|
|
6
|
+
/** Acquisitions waiting on refill. */
|
|
7
|
+
pending: number;
|
|
8
|
+
acquired: number;
|
|
9
|
+
rejected: number;
|
|
10
|
+
}
|
|
11
|
+
export interface RateBudget {
|
|
12
|
+
/** Takes `cost` tokens, waiting for refill when needed. */
|
|
13
|
+
acquire(cost?: number, options?: {
|
|
14
|
+
maxWaitMs?: number;
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}): Promise<void>;
|
|
17
|
+
/** Takes `cost` tokens only if that needs no wait. */
|
|
18
|
+
tryAcquire(cost?: number): boolean;
|
|
19
|
+
stats(): RateBudgetStats;
|
|
20
|
+
}
|
|
21
|
+
export interface RateBudgetOptions {
|
|
22
|
+
/** Names the budget in errors. */
|
|
23
|
+
provider?: string;
|
|
24
|
+
capacity: number;
|
|
25
|
+
refillPerSecond: number;
|
|
26
|
+
/** Longest wait `acquire` accepts before failing. Default 30 000. */
|
|
27
|
+
maxWaitMs?: number;
|
|
28
|
+
/** Test seams. */
|
|
29
|
+
now?: () => number;
|
|
30
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/** A promise-based delay that rejects with the signal's reason when aborted. */
|
|
33
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
34
|
+
/**
|
|
35
|
+
* A token bucket: starts full, refills continuously, and makes waiters reserve
|
|
36
|
+
* ahead so they are served roughly in order. In-memory and per-process; divide
|
|
37
|
+
* the rate when several processes share one account.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createRateBudget(options: RateBudgetOptions): RateBudget;
|
|
40
|
+
//# sourceMappingURL=rate-budget.d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AAE,iBAAiB,GAAG,UAAU,CAqFvE"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { ProviderError } from './errors.js';
|
|
2
|
+
/** A promise-based delay that rejects with the signal's reason when aborted. */
|
|
3
|
+
export function sleep(ms, signal) {
|
|
4
|
+
return new Promise((resolve, reject) => {
|
|
5
|
+
if (signal?.aborted) {
|
|
6
|
+
reject(signal.reason);
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
const onAbort = () => {
|
|
10
|
+
clearTimeout(timer);
|
|
11
|
+
reject(signal.reason);
|
|
12
|
+
};
|
|
13
|
+
const timer = setTimeout(() => {
|
|
14
|
+
signal?.removeEventListener('abort', onAbort);
|
|
15
|
+
resolve();
|
|
16
|
+
}, ms);
|
|
17
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A token bucket: starts full, refills continuously, and makes waiters reserve
|
|
22
|
+
* ahead so they are served roughly in order. In-memory and per-process; divide
|
|
23
|
+
* the rate when several processes share one account.
|
|
24
|
+
*/
|
|
25
|
+
export function createRateBudget(options) {
|
|
26
|
+
const { capacity, refillPerSecond } = options;
|
|
27
|
+
const provider = options.provider ?? 'provider';
|
|
28
|
+
const defaultMaxWaitMs = options.maxWaitMs ?? 30_000;
|
|
29
|
+
const now = options.now ?? Date.now;
|
|
30
|
+
const wait = options.sleep ?? sleep;
|
|
31
|
+
const invalid = (message) => {
|
|
32
|
+
throw new ProviderError({ provider, kind: 'invalid_input', message });
|
|
33
|
+
};
|
|
34
|
+
if (!Number.isFinite(capacity) || capacity <= 0)
|
|
35
|
+
invalid('rate budget capacity must be positive');
|
|
36
|
+
if (!Number.isFinite(refillPerSecond) || refillPerSecond <= 0) {
|
|
37
|
+
invalid('rate budget refillPerSecond must be positive');
|
|
38
|
+
}
|
|
39
|
+
let tokens = capacity;
|
|
40
|
+
let refilledAt = now();
|
|
41
|
+
let pending = 0;
|
|
42
|
+
let acquired = 0;
|
|
43
|
+
let rejected = 0;
|
|
44
|
+
const refill = () => {
|
|
45
|
+
const at = now();
|
|
46
|
+
if (at > refilledAt)
|
|
47
|
+
tokens = Math.min(capacity, tokens + ((at - refilledAt) / 1000) * refillPerSecond);
|
|
48
|
+
refilledAt = at;
|
|
49
|
+
};
|
|
50
|
+
const check = (cost) => {
|
|
51
|
+
if (!Number.isFinite(cost) || cost <= 0 || cost > capacity) {
|
|
52
|
+
invalid('rate budget cost must be positive and no greater than capacity');
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
async acquire(cost = 1, { maxWaitMs = defaultMaxWaitMs, signal } = {}) {
|
|
57
|
+
check(cost);
|
|
58
|
+
refill();
|
|
59
|
+
if (tokens >= cost) {
|
|
60
|
+
tokens -= cost;
|
|
61
|
+
acquired += 1;
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const waitMs = Math.ceil(((cost - tokens) / refillPerSecond) * 1000);
|
|
65
|
+
if (waitMs > maxWaitMs) {
|
|
66
|
+
rejected += 1;
|
|
67
|
+
throw new ProviderError({
|
|
68
|
+
provider,
|
|
69
|
+
kind: 'rate_limited',
|
|
70
|
+
message: `the local ${provider} rate budget is exhausted`,
|
|
71
|
+
retryAfterMs: waitMs,
|
|
72
|
+
detail: { source: 'local_rate_budget', maxWaitMs }
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
tokens -= cost;
|
|
76
|
+
pending += 1;
|
|
77
|
+
try {
|
|
78
|
+
await wait(waitMs, signal);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Abandoned: give the reservation back so later callers are not charged for it.
|
|
82
|
+
refill();
|
|
83
|
+
tokens = Math.min(capacity, tokens + cost);
|
|
84
|
+
throw new ProviderError({
|
|
85
|
+
provider,
|
|
86
|
+
kind: 'aborted',
|
|
87
|
+
message: `the ${provider} request was aborted while waiting for the rate budget`
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
pending -= 1;
|
|
92
|
+
}
|
|
93
|
+
acquired += 1;
|
|
94
|
+
},
|
|
95
|
+
tryAcquire(cost = 1) {
|
|
96
|
+
check(cost);
|
|
97
|
+
refill();
|
|
98
|
+
if (tokens < cost)
|
|
99
|
+
return false;
|
|
100
|
+
tokens -= cost;
|
|
101
|
+
acquired += 1;
|
|
102
|
+
return true;
|
|
103
|
+
},
|
|
104
|
+
stats() {
|
|
105
|
+
refill();
|
|
106
|
+
return { capacity, refillPerSecond, available: Math.max(0, tokens), pending, acquired, rejected };
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=rate-budget.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-budget.js","sourceRoot":"","sources":["../src/rate-budget.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAiC5C,gFAAgF;AAChF,MAAM,UAAU,KAAK,CAAC,EAAU,EAAE,MAAoB;IACpD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;YACpB,MAAM,CAAC,MAAM,CAAC,MAAe,CAAC,CAAC;YAC/B,OAAO;QACT,CAAC;QACD,MAAM,OAAO,GAAG,GAAS,EAAE;YACzB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,MAAO,CAAC,MAAe,CAAC,CAAC;QAClC,CAAC,CAAC;QACF,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9C,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,EAAE,CAAC,CAAC;QACP,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EA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MAAM,CAAC;gBACP,gFAAgF;gBAChF,MAAM,EAAE,CAAC;gBACT,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC;gBAC3C,MAAM,IAAI,aAAa,CAAC;oBACtB,QAAQ;oBACR,IAAI,EAAE,SAAS;oBACf,OAAO,EAAE,OAAO,QAAQ,wDAAwD;iBACjF,CAAC,CAAC;YACL,CAAC;oBAAS,CAAC;gBACT,OAAO,IAAI,CAAC,CAAC;YACf,CAAC;YACD,QAAQ,IAAI,CAAC,CAAC;QAChB,CAAC;QAED,UAAU,CAAC,IAAI,GAAG,CAAC;YACjB,KAAK,CAAC,IAAI,CAAC,CAAC;YACZ,MAAM,EAAE,CAAC;YACT,IAAI,MAAM,GAAG,IAAI;gBAAE,OAAO,KAAK,CAAC;YAChC,MAAM,IAAI,IAAI,CAAC;YACf,QAAQ,IAAI,CAAC,CAAC;YACd,OAAO,IAAI,CAAC;QACd,CAAC;QAED,KAAK;YACH,MAAM,EAAE,CAAC;YACT,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC;QACpG,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/url.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a host is an address or name that only means something locally:
|
|
3
|
+
* loopback, private, shared (CGNAT), link-local, unique-local and multicast
|
|
4
|
+
* ranges, plus `localhost`, `.local`, `.internal`, `.home.arpa` and bare names.
|
|
5
|
+
*
|
|
6
|
+
* Names are not resolved. A public name that resolves to a private address
|
|
7
|
+
* passes; block that with an egress policy or a checking resolver.
|
|
8
|
+
*/
|
|
9
|
+
export declare function isPrivateHost(hostname: string): boolean;
|
|
10
|
+
export declare function isLoopbackHost(hostname: string): boolean;
|
|
11
|
+
export interface BaseUrlOptions {
|
|
12
|
+
provider: string;
|
|
13
|
+
/** Permit `http:` to a loopback host, for tests and local mocks. */
|
|
14
|
+
allowLoopbackHttp?: boolean;
|
|
15
|
+
/** Permit `http:` to other hosts whose transport is already encrypted. */
|
|
16
|
+
allowHttpHost?: (hostname: string) => boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Validates and normalizes an API base URL: https only (see options), no
|
|
20
|
+
* embedded credentials, no query or fragment, no trailing slash.
|
|
21
|
+
*/
|
|
22
|
+
export declare function normalizeBaseUrl(input: string, options: BaseUrlOptions): string;
|
|
23
|
+
//# sourceMappingURL=url.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../src/url.ts"],"names":[],"mappings":"AAsEA;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAWvD;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAKxD;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,oEAAoE;IACpE,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,0EAA0E;IAC1E,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;CAC/C;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,MAAM,CAsB/E"}
|
package/dist/url.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { ProviderError } from './errors.js';
|
|
2
|
+
function ipv4Value(address) {
|
|
3
|
+
const parts = address.split('.');
|
|
4
|
+
if (parts.length !== 4)
|
|
5
|
+
return null;
|
|
6
|
+
let value = 0;
|
|
7
|
+
for (const part of parts) {
|
|
8
|
+
if (!/^\d{1,3}$/.test(part) || Number(part) > 255)
|
|
9
|
+
return null;
|
|
10
|
+
value = value * 256 + Number(part);
|
|
11
|
+
}
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
const PRIVATE_V4 = [
|
|
15
|
+
['0.0.0.0', 8],
|
|
16
|
+
['10.0.0.0', 8],
|
|
17
|
+
['100.64.0.0', 10],
|
|
18
|
+
['127.0.0.0', 8],
|
|
19
|
+
['169.254.0.0', 16],
|
|
20
|
+
['172.16.0.0', 12],
|
|
21
|
+
['192.0.0.0', 24],
|
|
22
|
+
['192.168.0.0', 16],
|
|
23
|
+
['198.18.0.0', 15],
|
|
24
|
+
['224.0.0.0', 4],
|
|
25
|
+
['240.0.0.0', 4]
|
|
26
|
+
];
|
|
27
|
+
function isPrivateV4(value) {
|
|
28
|
+
return PRIVATE_V4.some(([base, prefix]) => {
|
|
29
|
+
const size = 2 ** (32 - prefix);
|
|
30
|
+
return Math.floor(value / size) === Math.floor(ipv4Value(base) / size);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function ipv6Value(address) {
|
|
34
|
+
let text = address.toLowerCase();
|
|
35
|
+
const tail = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(text);
|
|
36
|
+
if (tail) {
|
|
37
|
+
const v4 = ipv4Value(tail[2]);
|
|
38
|
+
if (v4 === null)
|
|
39
|
+
return null;
|
|
40
|
+
text = `${tail[1]}${Math.floor(v4 / 65536).toString(16)}:${(v4 % 65536).toString(16)}`;
|
|
41
|
+
}
|
|
42
|
+
const halves = text.split('::');
|
|
43
|
+
if (halves.length > 2)
|
|
44
|
+
return null;
|
|
45
|
+
const groups = (part) => (part === '' ? [] : part.split(':'));
|
|
46
|
+
const head = groups(halves[0]);
|
|
47
|
+
const end = halves.length === 2 ? groups(halves[1]) : [];
|
|
48
|
+
const missing = 8 - head.length - end.length;
|
|
49
|
+
if (halves.length === 2 ? missing < 1 : missing !== 0)
|
|
50
|
+
return null;
|
|
51
|
+
let value = 0n;
|
|
52
|
+
for (const group of [...head, ...Array(missing).fill('0'), ...end]) {
|
|
53
|
+
if (!/^[0-9a-f]{1,4}$/.test(group))
|
|
54
|
+
return null;
|
|
55
|
+
value = (value << 16n) | BigInt(`0x${group}`);
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
function isPrivateV6(value) {
|
|
60
|
+
const top = (bits) => value >> (128n - bits);
|
|
61
|
+
if (value <= 1n)
|
|
62
|
+
return true; // :: and ::1
|
|
63
|
+
if (top(7n) === 0x7en)
|
|
64
|
+
return true; // fc00::/7 unique local
|
|
65
|
+
if (top(10n) === 0x3fan)
|
|
66
|
+
return true; // fe80::/10 link local
|
|
67
|
+
if (top(8n) === 0xffn)
|
|
68
|
+
return true; // ff00::/8 multicast
|
|
69
|
+
const low32 = Number(value & 0xffffffffn);
|
|
70
|
+
if (top(96n) === 0xffffn)
|
|
71
|
+
return isPrivateV4(low32); // ::ffff:0:0/96 mapped
|
|
72
|
+
if (top(96n) === 0n)
|
|
73
|
+
return isPrivateV4(low32); // ::/96 compatible
|
|
74
|
+
if (top(96n) === 0x64ff9b0000000000000000n)
|
|
75
|
+
return isPrivateV4(low32); // 64:ff9b::/96 NAT64
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Whether a host is an address or name that only means something locally:
|
|
80
|
+
* loopback, private, shared (CGNAT), link-local, unique-local and multicast
|
|
81
|
+
* ranges, plus `localhost`, `.local`, `.internal`, `.home.arpa` and bare names.
|
|
82
|
+
*
|
|
83
|
+
* Names are not resolved. A public name that resolves to a private address
|
|
84
|
+
* passes; block that with an egress policy or a checking resolver.
|
|
85
|
+
*/
|
|
86
|
+
export function isPrivateHost(hostname) {
|
|
87
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
88
|
+
if (host.includes(':')) {
|
|
89
|
+
const value = ipv6Value(host);
|
|
90
|
+
return value === null || isPrivateV6(value);
|
|
91
|
+
}
|
|
92
|
+
const v4 = ipv4Value(host);
|
|
93
|
+
if (v4 !== null)
|
|
94
|
+
return isPrivateV4(v4);
|
|
95
|
+
return (!host.includes('.') || /(^|\.)(localhost|local|internal|home\.arpa)$/.test(host));
|
|
96
|
+
}
|
|
97
|
+
export function isLoopbackHost(hostname) {
|
|
98
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
99
|
+
if (host === 'localhost' || host === '::1')
|
|
100
|
+
return true;
|
|
101
|
+
const v4 = ipv4Value(host);
|
|
102
|
+
return v4 !== null && Math.floor(v4 / 2 ** 24) === 127;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Validates and normalizes an API base URL: https only (see options), no
|
|
106
|
+
* embedded credentials, no query or fragment, no trailing slash.
|
|
107
|
+
*/
|
|
108
|
+
export function normalizeBaseUrl(input, options) {
|
|
109
|
+
const fail = (message) => {
|
|
110
|
+
throw new ProviderError({
|
|
111
|
+
provider: options.provider,
|
|
112
|
+
kind: 'invalid_input',
|
|
113
|
+
message: `the ${options.provider} base URL ${message}`
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
let url;
|
|
117
|
+
try {
|
|
118
|
+
url = new URL(input);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return fail('is not an absolute URL');
|
|
122
|
+
}
|
|
123
|
+
if (url.username !== '' || url.password !== '')
|
|
124
|
+
fail('must not carry credentials');
|
|
125
|
+
if (url.search !== '' || url.hash !== '')
|
|
126
|
+
fail('must not carry a query string or fragment');
|
|
127
|
+
const httpAllowed = url.protocol === 'http:' &&
|
|
128
|
+
((options.allowLoopbackHttp === true && isLoopbackHost(url.hostname)) ||
|
|
129
|
+
options.allowHttpHost?.(url.hostname) === true);
|
|
130
|
+
if (url.protocol !== 'https:' && !httpAllowed)
|
|
131
|
+
fail(`must use https, not ${url.protocol}`);
|
|
132
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
|
|
133
|
+
}
|
|
134
|
+
//# sourceMapp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AG,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;AAC5D,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@formless63/provider-http",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Safe HTTP plumbing for API clients: URL guards, bounded reads, sanitized errors, rate budgets.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"http",
|
|
7
|
+
"fetch",
|
|
8
|
+
"rate-limit",
|
|
9
|
+
"api-client"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/formless63/netlibs.git",
|
|
15
|
+
"directory": "packages/provider-http"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://github.com/formless63/netlibs/tree/main/packages/provider-http#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/formless63/netlibs/issues"
|
|
20
|
+
},
|
|
21
|
+
"type": "module",
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"README.md"
|
|
30
|
+
],
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./package.json": "./package.json"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
}
|
|
41
|
+
}
|