@flipstream/sdk 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/LICENSE +202 -0
  3. package/README.md +491 -2
  4. package/dist/api/index.d.ts +1 -0
  5. package/dist/api/index.js +2 -0
  6. package/dist/api/index.js.map +1 -0
  7. package/dist/auth/discovery.d.ts +23 -0
  8. package/dist/auth/discovery.js +71 -0
  9. package/dist/auth/discovery.js.map +1 -0
  10. package/dist/auth/index.d.ts +5 -0
  11. package/dist/auth/index.js +5 -0
  12. package/dist/auth/index.js.map +1 -0
  13. package/dist/auth/pkce.d.ts +10 -0
  14. package/dist/auth/pkce.js +25 -0
  15. package/dist/auth/pkce.js.map +1 -0
  16. package/dist/auth/signIn.d.ts +106 -0
  17. package/dist/auth/signIn.js +125 -0
  18. package/dist/auth/signIn.js.map +1 -0
  19. package/dist/auth/tokenEndpoint.d.ts +18 -0
  20. package/dist/auth/tokenEndpoint.js +36 -0
  21. package/dist/auth/tokenEndpoint.js.map +1 -0
  22. package/dist/auth/transport.d.ts +18 -0
  23. package/dist/auth/transport.js +26 -0
  24. package/dist/auth/transport.js.map +1 -0
  25. package/dist/core/body.d.ts +14 -0
  26. package/dist/core/body.js +69 -0
  27. package/dist/core/body.js.map +1 -0
  28. package/dist/core/call.d.ts +17 -0
  29. package/dist/core/call.js +116 -0
  30. package/dist/core/call.js.map +1 -0
  31. package/dist/core/fetch.d.ts +43 -0
  32. package/dist/core/fetch.js +130 -0
  33. package/dist/core/fetch.js.map +1 -0
  34. package/dist/core/read.d.ts +17 -0
  35. package/dist/core/read.js +92 -0
  36. package/dist/core/read.js.map +1 -0
  37. package/dist/core/result.d.ts +96 -0
  38. package/dist/core/result.js +42 -0
  39. package/dist/core/result.js.map +1 -0
  40. package/dist/core/retry.d.ts +40 -0
  41. package/dist/core/retry.js +41 -0
  42. package/dist/core/retry.js.map +1 -0
  43. package/dist/core/transport.d.ts +62 -0
  44. package/dist/core/transport.js +9 -0
  45. package/dist/core/transport.js.map +1 -0
  46. package/dist/flipstream.d.ts +52 -0
  47. package/dist/flipstream.js +36 -0
  48. package/dist/flipstream.js.map +1 -0
  49. package/dist/index.d.ts +12 -0
  50. package/dist/index.js +8 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/node/clientSecret.d.ts +41 -0
  53. package/dist/node/clientSecret.js +124 -0
  54. package/dist/node/clientSecret.js.map +1 -0
  55. package/dist/node/fileLock.d.ts +27 -0
  56. package/dist/node/fileLock.js +248 -0
  57. package/dist/node/fileLock.js.map +1 -0
  58. package/dist/node/headless.d.ts +25 -0
  59. package/dist/node/headless.js +41 -0
  60. package/dist/node/headless.js.map +1 -0
  61. package/dist/node/index.d.ts +9 -0
  62. package/dist/node/index.js +11 -0
  63. package/dist/node/index.js.map +1 -0
  64. package/dist/node/loopback.d.ts +77 -0
  65. package/dist/node/loopback.js +183 -0
  66. package/dist/node/loopback.js.map +1 -0
  67. package/dist/node/session.d.ts +192 -0
  68. package/dist/node/session.js +480 -0
  69. package/dist/node/session.js.map +1 -0
  70. package/dist/query/catalog.d.ts +15 -0
  71. package/dist/query/catalog.js +41 -0
  72. package/dist/query/catalog.js.map +1 -0
  73. package/dist/query/errors.d.ts +8 -0
  74. package/dist/query/errors.js +16 -0
  75. package/dist/query/errors.js.map +1 -0
  76. package/dist/query/health.d.ts +16 -0
  77. package/dist/query/health.js +18 -0
  78. package/dist/query/health.js.map +1 -0
  79. package/dist/query/query.d.ts +35 -0
  80. package/dist/query/query.js +47 -0
  81. package/dist/query/query.js.map +1 -0
  82. package/dist/recorded/query-planner/catalog-google_search_console.json +140 -0
  83. package/dist/recorded/query-planner/catalog.json +1234 -0
  84. package/dist/spec/query-planner/index.d.ts +1 -0
  85. package/dist/spec/query-planner/index.js +3 -0
  86. package/dist/spec/query-planner/index.js.map +1 -0
  87. package/dist/spec/query-planner/types.gen.d.ts +300 -0
  88. package/dist/spec/query-planner/types.gen.js +3 -0
  89. package/dist/spec/query-planner/types.gen.js.map +1 -0
  90. package/dist/spec/query-planner/zod.gen.d.ts +325 -0
  91. package/dist/spec/query-planner/zod.gen.js +137 -0
  92. package/dist/spec/query-planner/zod.gen.js.map +1 -0
  93. package/package.json +99 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pkce.js","sourceRoot":"","sources":["../../src/auth/pkce.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,4DAA4D;AAC5D,MAAM,UAAU,SAAS,CAAC,KAAiB;IACzC,IAAI,MAAM,GAAG,EAAE,CAAA;IACf,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;AAChF,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,UAAkB;IAC5C,OAAO,SAAS,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;AACtE,CAAC;AAED,0EAA0E;AAC1E,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,QAAgB;IAChD,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAA;IACxF,OAAO,SAAS,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAA;AAC1C,CAAC"}
@@ -0,0 +1,106 @@
1
+ import type { ApiError } from '../core/result.js';
2
+ import type { AuthServer } from './discovery.js';
3
+ import { type AuthCallOptions } from './transport.js';
4
+ /** What `startSignIn` takes. */
5
+ export interface SignInRequest {
6
+ /** The server, as `discover` gave it. */
7
+ readonly server: AuthServer;
8
+ /** The app's own OAuth client ID, never one a server announces (D421). */
9
+ readonly clientId: string;
10
+ /** Where the server sends the person back, as registered for the client. */
11
+ readonly redirectUri: string;
12
+ /** What the app asks for. At least one: there are no default scopes (D421). */
13
+ readonly scopes: readonly [string, ...string[]];
14
+ }
15
+ /**
16
+ * What finishing needs, held by the app between the two halves: only strings and a flag, so it
17
+ * survives a page load in the app's own storage. The verifier is a secret: never log it.
18
+ */
19
+ export interface PendingSignIn {
20
+ /** What the redirect must carry back (CSRF). */
21
+ readonly state: string;
22
+ /** The PKCE code verifier: the secret the code is exchanged with. */
23
+ readonly verifier: string;
24
+ readonly clientId: string;
25
+ readonly redirectUri: string;
26
+ /** The scopes asked for, space-separated (RFC 6749 §3.3). */
27
+ readonly scope: string;
28
+ /** The server's issuer, its token endpoint, and whether it puts `iss` on every redirect. */
29
+ readonly issuer: string;
30
+ readonly tokenEndpoint: string;
31
+ readonly issuerOnRedirect: boolean;
32
+ }
33
+ /** What a sign-in gives. The app stores them; the SDK keeps no copy. */
34
+ export interface Tokens {
35
+ /** For the transport's token function: never log it. */
36
+ readonly accessToken: string;
37
+ /** Absent when the server issued none. */
38
+ readonly refreshToken?: string;
39
+ /** When the access token expires, in ms since the epoch; absent when the server didn't say. */
40
+ readonly expiresAt?: number;
41
+ /** The scopes granted, space-separated. */
42
+ readonly scope: string;
43
+ }
44
+ /** Why the redirect the person came back on was not taken. Nothing was sent for any of them. */
45
+ export type CallbackError =
46
+ /** Its `state` isn't this sign-in's: another sign-in's redirect, or a forged one. */
47
+ {
48
+ readonly kind: 'wrong_state';
49
+ }
50
+ /** Its `iss` names another server, or is missing though the server sends one (RFC 9207). */
51
+ | {
52
+ readonly kind: 'wrong_issuer';
53
+ }
54
+ /** The server ended the sign-in (RFC 6749 §4.1.2.1): `access_denied` when the person declined. */
55
+ | {
56
+ readonly kind: 'provider_error';
57
+ readonly code: string;
58
+ readonly description?: string;
59
+ }
60
+ /** No code and no error. */
61
+ | {
62
+ readonly kind: 'no_code';
63
+ };
64
+ /** Why a sign-in didn't finish: the redirect's (`CallbackError`), or the exchange's (`ApiError`). */
65
+ export type SignInError = ApiError | CallbackError;
66
+ /** What `finishSignIn` gives: the tokens, or one failure with one meaning (D412). */
67
+ export type SignInResult = {
68
+ readonly ok: true;
69
+ readonly data: Tokens;
70
+ } | {
71
+ readonly ok: false;
72
+ readonly error: SignInError;
73
+ };
74
+ /**
75
+ * The URL to send the person to, and what finishing will need. Rejects with a TypeError, before
76
+ * anything is made, when the client ID is missing or empty, the redirect URI isn't absolute, or
77
+ * the scopes are empty or one holds a space: from TypeScript, none of these compiles. Always S256;
78
+ * no `resource` is sent, since the hosts share one audience.
79
+ */
80
+ export declare function startSignIn(request: SignInRequest): Promise<{
81
+ readonly url: string;
82
+ readonly pending: PendingSignIn;
83
+ }>;
84
+ /**
85
+ * The redirect, read in this order: its state first, so a forged one learns nothing; then its
86
+ * issuer, then the server's error, then the code. Pure: nothing is sent.
87
+ */
88
+ export declare function readCallback(callbackUrl: string | URL, pending: PendingSignIn): {
89
+ readonly kind: 'code';
90
+ readonly code: string;
91
+ } | CallbackError;
92
+ /** A pending sign-in as `startSignIn` makes one, checked: it comes back from the app's storage. */
93
+ export declare const isPendingSignIn: (value: unknown) => value is PendingSignIn;
94
+ /**
95
+ * Finishes a sign-in: the redirect is read (`readCallback`), and only then is its code exchanged
96
+ * for tokens, once (`tokenCall`). A `pending` that isn't one (from
97
+ * storage the app couldn't read back) is `refused`, with nothing sent. A public client's: an app
98
+ * with a server signs in as a confidential client with `@flipstream/sdk/node`'s `finishSignIn`.
99
+ */
100
+ export declare function finishSignIn(callbackUrl: string | URL, pending: PendingSignIn, options?: AuthCallOptions): Promise<SignInResult>;
101
+ /**
102
+ * `finishSignIn`'s work, with `authorization` as the token request's Authorization header when
103
+ * the app authenticates as a confidential client (only `@flipstream/sdk/node` makes one). The main
104
+ * entry never exports this, so browser code has no way to send client credentials.
105
+ */
106
+ export declare function exchangeCode(callbackUrl: string | URL, pending: PendingSignIn, options: AuthCallOptions, authorization?: string): Promise<SignInResult>;
@@ -0,0 +1,125 @@
1
+ import { z } from 'zod';
2
+ import { call } from '../core/call.js';
3
+ import { challengeOf, randomValue } from './pkce.js';
4
+ import { tokenCall } from './tokenEndpoint.js';
5
+ import { authTransport, isHttpsUrl } from './transport.js';
6
+ const nonEmpty = (value) => typeof value === 'string' && value !== '';
7
+ /**
8
+ * The URL to send the person to, and what finishing will need. Rejects with a TypeError, before
9
+ * anything is made, when the client ID is missing or empty, the redirect URI isn't absolute, or
10
+ * the scopes are empty or one holds a space: from TypeScript, none of these compiles. Always S256;
11
+ * no `resource` is sent, since the hosts share one audience.
12
+ */
13
+ export async function startSignIn(request) {
14
+ const { server, clientId, redirectUri, scopes } = request;
15
+ if (!nonEmpty(clientId))
16
+ throw new TypeError("startSignIn: clientId is required: the app's own OAuth client ID");
17
+ if (!nonEmpty(redirectUri) || !URL.canParse(redirectUri))
18
+ throw new TypeError('startSignIn: redirectUri must be an absolute URL');
19
+ if (!Array.isArray(scopes) || scopes.length === 0 || !scopes.every((scope) => nonEmpty(scope) && !/\s/.test(scope))) {
20
+ throw new TypeError('startSignIn: scopes must be one or more scope names, none with a space');
21
+ }
22
+ const state = randomValue(32);
23
+ const verifier = randomValue(64);
24
+ const scope = scopes.join(' ');
25
+ const url = new URL(server.authorizationEndpoint);
26
+ url.searchParams.set('response_type', 'code');
27
+ url.searchParams.set('client_id', clientId);
28
+ url.searchParams.set('redirect_uri', redirectUri);
29
+ url.searchParams.set('scope', scope);
30
+ url.searchParams.set('state', state);
31
+ url.searchParams.set('code_challenge', await challengeOf(verifier));
32
+ url.searchParams.set('code_challenge_method', 'S256');
33
+ return {
34
+ url: url.toString(),
35
+ pending: {
36
+ state,
37
+ verifier,
38
+ clientId,
39
+ redirectUri,
40
+ scope,
41
+ issuer: server.issuer,
42
+ tokenEndpoint: server.tokenEndpoint,
43
+ issuerOnRedirect: server.issuerOnRedirect,
44
+ },
45
+ };
46
+ }
47
+ /**
48
+ * The redirect, read in this order: its state first, so a forged one learns nothing; then its
49
+ * issuer, then the server's error, then the code. Pure: nothing is sent.
50
+ */
51
+ export function readCallback(callbackUrl, pending) {
52
+ const params = new URL(callbackUrl).searchParams;
53
+ if (params.get('state') !== pending.state)
54
+ return { kind: 'wrong_state' };
55
+ const iss = params.get('iss');
56
+ // Compared as strings, as RFC 9207 §2.4 says: the issuer exactly as its metadata names it.
57
+ if (iss === null ? pending.issuerOnRedirect : iss !== pending.issuer)
58
+ return { kind: 'wrong_issuer' };
59
+ const error = params.get('error');
60
+ if (error !== null) {
61
+ const description = params.get('error_description');
62
+ return description === null ? { kind: 'provider_error', code: error } : { kind: 'provider_error', code: error, description };
63
+ }
64
+ const code = params.get('code');
65
+ return nonEmpty(code) ? { kind: 'code', code } : { kind: 'no_code' };
66
+ }
67
+ const zPending = z.object({
68
+ state: z.string().min(1),
69
+ verifier: z.string().min(43).max(128),
70
+ clientId: z.string().min(1),
71
+ redirectUri: z.string().min(1),
72
+ scope: z.string().min(1),
73
+ issuer: z.string().min(1),
74
+ tokenEndpoint: z.string().refine(isHttpsUrl),
75
+ issuerOnRedirect: z.boolean(),
76
+ });
77
+ /** A pending sign-in as `startSignIn` makes one, checked: it comes back from the app's storage. */
78
+ export const isPendingSignIn = (value) => zPending.safeParse(value).success;
79
+ /**
80
+ * Finishes a sign-in: the redirect is read (`readCallback`), and only then is its code exchanged
81
+ * for tokens, once (`tokenCall`). A `pending` that isn't one (from
82
+ * storage the app couldn't read back) is `refused`, with nothing sent. A public client's: an app
83
+ * with a server signs in as a confidential client with `@flipstream/sdk/node`'s `finishSignIn`.
84
+ */
85
+ export function finishSignIn(callbackUrl, pending, options = {}) {
86
+ return exchangeCode(callbackUrl, pending, options);
87
+ }
88
+ /**
89
+ * `finishSignIn`'s work, with `authorization` as the token request's Authorization header when
90
+ * the app authenticates as a confidential client (only `@flipstream/sdk/node` makes one). The main
91
+ * entry never exports this, so browser code has no way to send client credentials.
92
+ */
93
+ export async function exchangeCode(callbackUrl, pending, options, authorization) {
94
+ if (!isPendingSignIn(pending) || !URL.canParse(callbackUrl))
95
+ return { ok: false, error: { kind: 'refused' } };
96
+ const callback = readCallback(callbackUrl, pending);
97
+ if (callback.kind !== 'code')
98
+ return { ok: false, error: callback };
99
+ const form = {
100
+ grant_type: 'authorization_code',
101
+ code: callback.code,
102
+ redirect_uri: pending.redirectUri,
103
+ client_id: pending.clientId,
104
+ code_verifier: pending.verifier,
105
+ };
106
+ // Before the request, so the expiry is never later than the server's own.
107
+ const sentAt = Date.now();
108
+ const answer = await call(authTransport(options), tokenCall('auth.token', pending.tokenEndpoint, form, 30_000, authorization), options.signal);
109
+ if (!answer.ok)
110
+ return answer;
111
+ const { access_token, expires_in, refresh_token, scope } = answer.data;
112
+ return {
113
+ ok: true,
114
+ data: {
115
+ accessToken: access_token,
116
+ // pulse-auth sends "" for "no refresh token" (its model's default): that is none, not a token.
117
+ ...(nonEmpty(refresh_token) ? { refreshToken: refresh_token } : {}),
118
+ ...(expires_in === undefined ? {} : { expiresAt: sentAt + expires_in * 1000 }),
119
+ // RFC 6749 §5.1: a server leaves `scope` out when it granted what was asked. pulse-auth
120
+ // always leaves it out.
121
+ scope: scope ?? pending.scope,
122
+ },
123
+ };
124
+ }
125
+ //# sourceMappingURL=signIn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signIn.js","sourceRoot":"","sources":["../../src/auth/signIn.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAA;AAGtC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,aAAa,EAAE,UAAU,EAAwB,MA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AI,CAAC,MAAM,CAAC,EAAE;QAAE,OAAO,MAAM,CAAA;IAC7B,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,KAAK,EAAE,GAAG,MAAM,CAAC,IAAI,CAAA;IACtE,OAAO;QACL,EAAE,EAAE,IAAI;QACR,IAAI,EAAE;YACJ,WAAW,EAAE,YAAY;YACzB,+FAA+F;YAC/F,GAAG,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACnE,GAAG,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,EAAE,CAAC;YAC9E,wFAAwF;YACxF,wBAAwB;YACxB,KAAK,EAAE,KAAK,IAAI,OAAO,CAAC,KAAK;SAC9B;KACF,CAAA;AACH,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { z } from 'zod';
2
+ import type { CallSpec } from '../core/call.js';
3
+ declare const zTokenAnswer: z.ZodObject<{
4
+ access_token: z.ZodString;
5
+ token_type: z.ZodString;
6
+ expires_in: z.ZodExactOptional<z.ZodInt>;
7
+ refresh_token: z.ZodExactOptional<z.ZodString>;
8
+ scope: z.ZodExactOptional<z.ZodString>;
9
+ }, z.core.$loose>;
10
+ export type TokenAnswer = z.infer<typeof zTokenAnswer>;
11
+ /**
12
+ * One POST to the token endpoint, form-encoded, with no token of its own (a public client sends
13
+ * none). Never tried again: a code is good once, and a refresh token resent after an answer that
14
+ * was lost on the way counts as reuse. `authorization` is a confidential client's own header
15
+ * (client_secret_basic, made only in `@flipstream/sdk/node`); the only header a caller can add.
16
+ */
17
+ export declare function tokenCall(endpoint: 'auth.token' | 'auth.refresh', tokenEndpoint: string, form: Record<string, string>, deadlineMs: number, authorization?: string): CallSpec<TokenAnswer>;
18
+ export {};
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ // RFC 6749 §5.1. Kept loose: the server's own fields (`id_token`, `refresh_expires_in`) pass by.
3
+ const zTokenAnswer = z.looseObject({
4
+ access_token: z.string().min(1),
5
+ token_type: z.string().refine((type) => type.toLowerCase() === 'bearer', 'the token type is not bearer'),
6
+ expires_in: z.int().nonnegative().exactOptional(),
7
+ refresh_token: z.string().exactOptional(),
8
+ scope: z.string().exactOptional(),
9
+ });
10
+ /**
11
+ * One POST to the token endpoint, form-encoded, with no token of its own (a public client sends
12
+ * none). Never tried again: a code is good once, and a refresh token resent after an answer that
13
+ * was lost on the way counts as reuse. `authorization` is a confidential client's own header
14
+ * (client_secret_basic, made only in `@flipstream/sdk/node`); the only header a caller can add.
15
+ */
16
+ export function tokenCall(endpoint, tokenEndpoint, form, deadlineMs, authorization) {
17
+ const body = new URLSearchParams(form).toString();
18
+ return {
19
+ effect: 'write',
20
+ service: 'auth',
21
+ endpoint,
22
+ makeRequest: () => new Request(tokenEndpoint, {
23
+ method: 'POST',
24
+ headers: {
25
+ accept: 'application/json',
26
+ 'content-type': 'application/x-www-form-urlencoded',
27
+ ...(authorization === undefined ? {} : { authorization }),
28
+ },
29
+ body,
30
+ }),
31
+ schema: zTokenAnswer,
32
+ deadlineMs,
33
+ retry: 'never',
34
+ };
35
+ }
36
+ //# sourceMappingURL=tokenEndpoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokenEndpoint.js","sourceRoot":"","sources":["../../src/auth/tokenEndpoint.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAGvB,iGAAiG;AACjG,MAAM,YAAY,GAAG,CAAC,CAAC,WAAW,CAAC;IACjC,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/B,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,QAAQ,EAAE,8BAA8B,CAAC;IACxG,UAAU,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,aAAa,EAAE;IACjD,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,aAAa,EAAE;IACzC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,aAAa,EAAE;CAClC,CAAC,CAAA;AAIF;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CACvB,QAAuC,EACvC,aAAqB,EACrB,IAA4B,EAC5B,UAAkB,EAClB,aAAsB;IAEtB,MAAM,IAAI,GAAG,IAAI,eAAe,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAA;IACjD,OAAO;QACL,MAAM,EAAE,OAAO;QACf,OAAO,EAAE,MAAM;QACf,QAAQ;QACR,WAAW,EAAE,GAAG,EAAE,CAChB,IAAI,OAAO,CAAC,aAAa,EAAE;YACzB,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACP,MAAM,EAAE,kBAAkB;gBAC1B,cAAc,EAAE,mCAAmC;gBACnD,GAAG,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,CAAC;aAC1D;YACD,IAAI;SACL,CAAC;QACJ,MAAM,EAAE,YAAY;QACpB,UAAU;QACV,KAAK,EAAE,OAAO;KACf,CAAA;AACH,CAAC"}
@@ -0,0 +1,18 @@
1
+ import type { Transport } from '../core/transport.js';
2
+ /** What every sign-in call takes. */
3
+ export interface AuthCallOptions {
4
+ /** Ends the call at once: its answer is `aborted`. */
5
+ readonly signal?: AbortSignal | undefined;
6
+ /** The app's own fetch, called as a plain function; the global one when it is undefined. */
7
+ readonly fetch?: typeof fetch | undefined;
8
+ }
9
+ /**
10
+ * An absolute https URL a Request can be made for: one with a user or password in it is refused
11
+ * by fetch, so it is no endpoint either.
12
+ */
13
+ export declare function isHttpsUrl(value: string): boolean;
14
+ /**
15
+ * Sign-in's transport: https only, and no token, since these calls are how a token is had. It
16
+ * sends as the default transport does (`sendRequest`): no cookies, and no redirect followed.
17
+ */
18
+ export declare function authTransport(options: AuthCallOptions): Transport;
@@ -0,0 +1,26 @@
1
+ import { sendRequest } from '../core/fetch.js';
2
+ /**
3
+ * An absolute https URL a Request can be made for: one with a user or password in it is refused
4
+ * by fetch, so it is no endpoint either.
5
+ */
6
+ export function isHttpsUrl(value) {
7
+ if (!URL.canParse(value))
8
+ return false;
9
+ const url = new URL(value);
10
+ return url.protocol === 'https:' && url.username === '' && url.password === '';
11
+ }
12
+ /**
13
+ * Sign-in's transport: https only, and no token, since these calls are how a token is had. It
14
+ * sends as the default transport does (`sendRequest`): no cookies, and no redirect followed.
15
+ */
16
+ export function authTransport(options) {
17
+ const send = options.fetch ?? globalThis.fetch;
18
+ return async (call) => {
19
+ const built = call.makeRequest();
20
+ if (new URL(built.url).protocol !== 'https:')
21
+ return { kind: 'refused', reason: 'destination' };
22
+ const sent = await sendRequest(send, built, new Headers(built.headers), call.signal);
23
+ return sent.kind === 'sent' ? { kind: 'response', response: sent.response } : sent;
24
+ };
25
+ }
26
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../src/auth/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAW9C;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa;IACtC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IACtC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAA;IAC1B,OAAO,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,KAAK,EAAE,IAAI,GAAG,CAAC,QAAQ,KAAK,EAAE,CAAA;AAChF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,OAAwB;IACpD,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,CAAA;IAC9C,OAAO,KAAK,EAAE,IAAI,EAAE,EAAE;QACpB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,EAAE,CAAA;QAChC,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,QAAQ,KAAK,QAAQ;YAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,CAAA;QAC/F,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QACpF,OAAO,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,IAAI,CAAA;IACpF,CAAC,CAAA;AACH,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { Said } from './result.js';
2
+ import type { ServiceName } from './transport.js';
3
+ export type Json = {
4
+ readonly ok: true;
5
+ readonly value: unknown;
6
+ } | {
7
+ readonly ok: false;
8
+ };
9
+ export declare function parseJson(text: string): Json;
10
+ /**
11
+ * What a failure status from `service` came with: the first of its envelopes that reads the body,
12
+ * or the body as it came.
13
+ */
14
+ export declare function said(text: string, service: ServiceName): Said;
@@ -0,0 +1,69 @@
1
+ import { zErrorBody } from '../spec/query-planner/zod.gen.js';
2
+ export function parseJson(text) {
3
+ try {
4
+ return { ok: true, value: JSON.parse(text) };
5
+ }
6
+ catch {
7
+ return { ok: false };
8
+ }
9
+ }
10
+ /**
11
+ * A code is SCREAMING_SNAKE, as the CLI checks it (its `planner/errors.ts`): anything else isn't
12
+ * a host's code, gets no trust, and leaves the body read as text. It keeps the field bounded, so it
13
+ * can't carry a token or terminal escapes to wherever a caller prints it.
14
+ */
15
+ const CODE_SHAPE = /^[A-Z][A-Z0-9_]{0,63}$/;
16
+ /** A message is capped, by code point so the cap never splits a character in two. */
17
+ const MESSAGE_MAX = 500;
18
+ const capped = (message) => (message.length <= MESSAGE_MAX ? message : Array.from(message).slice(0, MESSAGE_MAX).join(''));
19
+ /** The planner's `{ code, message }`, its spec's ErrorBody (D429), with a code of a code's shape. */
20
+ const planner = (body) => {
21
+ const read = zErrorBody.safeParse(body);
22
+ if (!read.success || !CODE_SHAPE.test(read.data.code))
23
+ return null;
24
+ return { code: read.data.code, message: capped(read.data.message) };
25
+ };
26
+ /**
27
+ * An OAuth code is lowercase (`invalid_grant`, RFC 6749 §5.2), so it has its own bound, kept as
28
+ * tight as a planner code's for the same reason.
29
+ */
30
+ const OAUTH_CODE_SHAPE = /^[a-z][a-z0-9_]{0,63}$/;
31
+ /**
32
+ * OAuth's `{ error, error_description? }` (RFC 6749 §5.2), as pulse-auth's sign-in and token
33
+ * endpoints send it (D442). Written from the RFC, because pulse-auth declares no error schema; a
34
+ * declared one would replace this. Its codes stay raw strings, with no typed list until a caller
35
+ * needs one. A missing description reads as an empty message.
36
+ */
37
+ const oauth = (body) => {
38
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
39
+ return null;
40
+ const error = 'error' in body ? body.error : undefined;
41
+ const description = 'error_description' in body ? body.error_description : undefined;
42
+ if (typeof error !== 'string' || !OAUTH_CODE_SHAPE.test(error))
43
+ return null;
44
+ if (description !== undefined && typeof description !== 'string')
45
+ return null;
46
+ return { code: error, message: capped(description ?? '') };
47
+ };
48
+ /**
49
+ * Each service's envelopes (D442): a host's error body is read only by the envelope that host
50
+ * sends, so a proxy's `{"error":"not_found"}` on the query host is never taken for an OAuth code.
51
+ * #91's `{ error: { code, message, request_id } }` joins `api` from its own spec (SD37).
52
+ */
53
+ const ENVELOPES = { query: [planner], auth: [oauth], api: [] };
54
+ /**
55
+ * What a failure status from `service` came with: the first of its envelopes that reads the body,
56
+ * or the body as it came.
57
+ */
58
+ export function said(text, service) {
59
+ const json = parseJson(text);
60
+ if (json.ok) {
61
+ for (const read of ENVELOPES[service]) {
62
+ const error = read(json.value);
63
+ if (error !== null)
64
+ return error;
65
+ }
66
+ }
67
+ return { text };
68
+ }
69
+ //# sourceMappingURL=body.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"body.js","sourceRoot":"","sources":["../../src/core/body.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAA;AAQ7D,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,IAAI,CAAC;QACH,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAA;IAC9C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAA;IACtB,CAAC;AACH,CAAC;AAOD;;;;GAIG;AACH,MAAM,UAAU,GAAG,wBAAwB,CAAA;AAE3C,qFAAqF;AACrF,MAAM,WAAW,GAAG,GAAG,CAAA;AACvB,MAAM,MAAM,GAAG,CAAC,OAAe,EAAU,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAA;AAE1I,qGAAqG;AACrG,MAAM,OAAO,GAAa,CAAC,IAAI,EAAE,EAAE;IACjC,MAAM,IAAI,GAAG,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;IACvC,IAAI,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IAClE,OAA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,EAAE,CAAC;QACZ,KAAK,MAAM,IAAI,IAAI,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC;YACtC,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;YAC9B,IAAI,KAAK,KAAK,IAAI;gBAAE,OAAO,KAAK,CAAA;QAClC,CAAC;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,CAAA;AACjB,CAAC"}
@@ -0,0 +1,17 @@
1
+ import type { z } from 'zod';
2
+ import { type ApiResult } from './result.js';
3
+ import { type RetryRule } from './retry.js';
4
+ import type { ApiRequest, Transport } from './transport.js';
5
+ /** One endpoint's call: what it sends, and the rules it is sent under, declared next to its schema. */
6
+ export interface CallSpec<T> extends Omit<ApiRequest, 'signal'> {
7
+ readonly schema: z.ZodType<T>;
8
+ /** How long the whole call may take: every attempt, every wait and the reading of the answer. */
9
+ readonly deadlineMs: number;
10
+ readonly retry: RetryRule;
11
+ }
12
+ /**
13
+ * One call: attempts under its rule, every attempt, wait and read under one signal that joins the
14
+ * caller's with the deadline. Whichever fires first decides the answer, `timeout` or `aborted`
15
+ * (#15), never mixed. The call ends when it fires, whatever the transport does with the signal.
16
+ */
17
+ export declare function call<T>(transport: Transport, spec: CallSpec<T>, signal?: AbortSignal): Promise<ApiResult<T>>;
@@ -0,0 +1,116 @@
1
+ import { readJson } from './read.js';
2
+ import { classifyStatus } from './result.js';
3
+ import { decide, parseRetryAfterMs } from './retry.js';
4
+ /**
5
+ * One call: attempts under its rule, every attempt, wait and read under one signal that joins the
6
+ * caller's with the deadline. Whichever fires first decides the answer, `timeout` or `aborted`
7
+ * (#15), never mixed. The call ends when it fires, whatever the transport does with the signal.
8
+ */
9
+ export async function call(transport, spec, signal) {
10
+ if (signal?.aborted === true)
11
+ return failed({ kind: 'aborted' });
12
+ const deadline = Date.now() + spec.deadlineMs;
13
+ // Owned here, strongly: the timer and the caller's listener each hold `stop`, so the deadline
14
+ // reaches every attempt, however weakly a transport or its fetch keeps the signal (#57).
15
+ const stop = new AbortController();
16
+ const timedOut = new DOMException(`${spec.endpoint} passed its deadline of ${String(spec.deadlineMs)} ms`, 'TimeoutError');
17
+ const timer = setTimeout(() => stop.abort(timedOut), spec.deadlineMs);
18
+ const onAbort = () => stop.abort(signal?.reason);
19
+ signal?.addEventListener('abort', onAbort, { once: true });
20
+ // The first abort's reason stays: that is how the call knows which came first.
21
+ const ended = () => failed(stop.signal.reason === timedOut ? { kind: 'timeout' } : { kind: 'aborted' });
22
+ const fired = new Promise((resolve) => stop.signal.addEventListener('abort', () => resolve(ENDED), { once: true }));
23
+ const { makeRequest, effect, service, endpoint } = spec;
24
+ const request = { makeRequest, effect, service, endpoint, signal: stop.signal };
25
+ try {
26
+ for (let attempt = 1;; attempt++) {
27
+ const sent = await unlessFired(transport(request), fired, letGo);
28
+ if (sent === ENDED)
29
+ return ended();
30
+ if (stop.signal.aborted) {
31
+ letGo(sent);
32
+ return ended();
33
+ }
34
+ let decision = decide(spec.retry, attempt, outcomeOf(sent), Date.now(), deadline);
35
+ if (decision.kind === 'stop') {
36
+ const result = await unlessFired(readJson(sent, spec.schema, stop.signal, spec.service), fired, () => undefined);
37
+ if (result === ENDED || stop.signal.aborted)
38
+ return ended();
39
+ // A success whose body broke off is a transport failure too, so a read tries again under
40
+ // its rule. Any other status already decided: its answer stands, however its body ended.
41
+ if (brokeOff(sent, result))
42
+ decision = decide(spec.retry, attempt, { kind: 'unavailable' }, Date.now(), deadline);
43
+ if (decision.kind === 'stop')
44
+ return withRetryAfter(result, sent);
45
+ }
46
+ else {
47
+ letGo(sent);
48
+ }
49
+ // The wait ends early when the signal fires; then no attempt follows it.
50
+ await sleep(decision.ms, stop.signal);
51
+ if (stop.signal.aborted)
52
+ return ended();
53
+ }
54
+ }
55
+ finally {
56
+ clearTimeout(timer);
57
+ // A minimal polyfill signal may have no removeEventListener; it keeps its one listener.
58
+ if (typeof signal?.removeEventListener === 'function')
59
+ signal.removeEventListener('abort', onAbort);
60
+ }
61
+ }
62
+ const ENDED = Symbol('ended');
63
+ /** `work`'s result, or ENDED as soon as the call's signal fires. Work that settles later is let go. */
64
+ async function unlessFired(work, fired, release) {
65
+ const first = await Promise.race([work, fired]);
66
+ if (first === ENDED)
67
+ void work.then(release, () => undefined);
68
+ return first;
69
+ }
70
+ /** An attempt's answer, unread, released: its body is cancelled, so its connection is free. */
71
+ function letGo(sent) {
72
+ if (sent.kind === 'response')
73
+ void sent.response.body?.cancel().catch(() => undefined);
74
+ }
75
+ /** A 2xx whose body broke off: readJson's `unavailable` with no status, for a success. */
76
+ function brokeOff(sent, result) {
77
+ return (sent.kind === 'response' &&
78
+ classifyStatus(sent.response.status) === 'success' &&
79
+ !result.ok &&
80
+ result.error.kind === 'unavailable' &&
81
+ result.error.status === undefined);
82
+ }
83
+ function outcomeOf(sent) {
84
+ if (sent.kind === 'response') {
85
+ return { kind: 'answered', status: sent.response.status, retryAfter: sent.response.headers.get('retry-after') };
86
+ }
87
+ return sent.kind === 'unavailable' ? { kind: 'unavailable' } : { kind: 'final' };
88
+ }
89
+ /** A failure the host answered keeps the wait it asked for, so the caller can decide (D414). */
90
+ function withRetryAfter(result, sent) {
91
+ if (result.ok || sent.kind !== 'response' || !answered(result.error))
92
+ return result;
93
+ const retryAfterMs = parseRetryAfterMs(sent.response.headers.get('retry-after'));
94
+ return retryAfterMs === undefined ? result : failed({ ...result.error, retryAfterMs });
95
+ }
96
+ // Of what readJson gives for a response, only a failure status's answer has a kind other than
97
+ // `invalid` and a status.
98
+ const answered = (error) => error.kind !== 'invalid' && 'status' in error && typeof error.status === 'number';
99
+ /** Waits `ms`, or less when the signal fires, or not at all when it already has. Its timer is cleared either way. */
100
+ function sleep(ms, signal) {
101
+ return new Promise((resolve) => {
102
+ // An abort event is never sent twice: one that came while the last answer was let go (a
103
+ // body's own cancel can abort) would otherwise leave this wait to run its full length.
104
+ if (signal.aborted)
105
+ return resolve();
106
+ const done = () => {
107
+ clearTimeout(timer);
108
+ signal.removeEventListener('abort', done);
109
+ resolve();
110
+ };
111
+ const timer = setTimeout(done, ms);
112
+ signal.addEventListener('abort', done, { once: true });
113
+ });
114
+ }
115
+ const failed = (error) => ({ ok: false, error });
116
+ //# sourceMappingURL=call.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"call.js","sourceRoot":"","sources":["../../src/core/call.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,cAAc,EAAgD,MAAM,aAAa,CAAA;AAC1F,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAgC,MAAM,YAAY,CAAA;AAgBpF;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,IAAI,CAAI,SAAoB,EAAE,IAAiB,EAAE,MAAoB;IACzF,IAAI,MAAM,EAAE,OAAO,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;IAChE,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,UAAU,CAAA;IAC7C,8FAA8F;IAC9F,yFAAyF;IACzF,MAAM,IAAI,GAAG,IAAI,eAAe,EAAE,CAAA;IAClC,MAAM,QAAQ,GAAG,IAAI,YAAY,CAAC,GAAG,IAAI,CAAC,QAAQ,2BAA2B,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,cAAc,CAAC,CAAA;IAC1H,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;IACrE,MAAM,OAAO,GAAG,GAAS,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACtD,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;IAC1D,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,CAAC,KAAe,EAAoD,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA"}
@@ -0,0 +1,43 @@
1
+ import type { ServiceName, Transport } from './transport.js';
2
+ /** What the token function is told: after a 401, the token the host refused, so it renews. */
3
+ export interface TokenAsk {
4
+ readonly rejected?: string;
5
+ }
6
+ export interface FetchTransportOptions {
7
+ /** Asked before every attempt (#30). Throwing, or giving no token, is `no_token`. */
8
+ readonly token: (ask: TokenAsk) => string | Promise<string>;
9
+ /** The caller's own fetch, called as a plain function; the global one when it is undefined. */
10
+ readonly fetch?: typeof fetch | undefined;
11
+ /**
12
+ * Each service's host. Only its origin counts: a call goes out only to its own service's
13
+ * origin, over https, and a service with no host here is refused.
14
+ */
15
+ readonly hosts: Readonly<Partial<Record<ServiceName, string>>>;
16
+ /** Plain http to a loopback host (localhost, 127.0.0.1, [::1]): development and tests only. */
17
+ readonly allowLocalhostHttp?: boolean | undefined;
18
+ }
19
+ declare const ABORTED: {
20
+ readonly kind: "aborted";
21
+ };
22
+ export declare function fetchTransport(options: FetchTransportOptions): Transport;
23
+ /** The default transport's options, less the token function. */
24
+ export type TokenlessTransportOptions = Omit<FetchTransportOptions, 'token'>;
25
+ /**
26
+ * The default transport without a token, for `GET /health` (#111): the same destinations and the
27
+ * same send, but it asks no token function and adds no `authorization` header, so it works
28
+ * signed out. It never resends after a 401: there is no token to renew.
29
+ */
30
+ export declare function tokenlessTransport(options: TokenlessTransportOptions): Transport;
31
+ /**
32
+ * One request out, as every transport of the SDK's own sends it (sign-in's too, #63), with
33
+ * `headers` in place of `built`'s. Nothing is sent once `signal` has fired. No cookies, and no
34
+ * redirect followed: a redirect would take what the request carries (a token, a code) to a URL
35
+ * nobody checked. A 3xx comes back as it is, outside the contract (`readJson`).
36
+ */
37
+ export declare function sendRequest(send: typeof fetch, built: Request, headers: Headers, signal: AbortSignal): Promise<{
38
+ readonly kind: 'sent';
39
+ readonly response: Response;
40
+ } | typeof ABORTED | {
41
+ readonly kind: 'unavailable';
42
+ }>;
43
+ export {};