@flipstream/sdk 0.0.0-stage → 0.4.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 (78) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/LICENSE +202 -0
  3. package/README.md +280 -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 +21 -0
  8. package/dist/auth/discovery.js +68 -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 +97 -0
  17. package/dist/auth/signIn.js +133 -0
  18. package/dist/auth/signIn.js.map +1 -0
  19. package/dist/auth/transport.d.ts +18 -0
  20. package/dist/auth/transport.js +26 -0
  21. package/dist/auth/transport.js.map +1 -0
  22. package/dist/core/body.d.ts +14 -0
  23. package/dist/core/body.js +69 -0
  24. package/dist/core/body.js.map +1 -0
  25. package/dist/core/call.d.ts +17 -0
  26. package/dist/core/call.js +116 -0
  27. package/dist/core/call.js.map +1 -0
  28. package/dist/core/fetch.d.ts +35 -0
  29. package/dist/core/fetch.js +105 -0
  30. package/dist/core/fetch.js.map +1 -0
  31. package/dist/core/read.d.ts +17 -0
  32. package/dist/core/read.js +92 -0
  33. package/dist/core/read.js.map +1 -0
  34. package/dist/core/result.d.ts +94 -0
  35. package/dist/core/result.js +40 -0
  36. package/dist/core/result.js.map +1 -0
  37. package/dist/core/retry.d.ts +40 -0
  38. package/dist/core/retry.js +41 -0
  39. package/dist/core/retry.js.map +1 -0
  40. package/dist/core/transport.d.ts +62 -0
  41. package/dist/core/transport.js +9 -0
  42. package/dist/core/transport.js.map +1 -0
  43. package/dist/flipstream.d.ts +45 -0
  44. package/dist/flipstream.js +26 -0
  45. package/dist/flipstream.js.map +1 -0
  46. package/dist/index.d.ts +11 -0
  47. package/dist/index.js +8 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/node/headless.d.ts +20 -0
  50. package/dist/node/headless.js +28 -0
  51. package/dist/node/headless.js.map +1 -0
  52. package/dist/node/index.d.ts +4 -0
  53. package/dist/node/index.js +5 -0
  54. package/dist/node/index.js.map +1 -0
  55. package/dist/node/loopback.d.ts +58 -0
  56. package/dist/node/loopback.js +126 -0
  57. package/dist/node/loopback.js.map +1 -0
  58. package/dist/query/catalog.d.ts +15 -0
  59. package/dist/query/catalog.js +41 -0
  60. package/dist/query/catalog.js.map +1 -0
  61. package/dist/query/errors.d.ts +8 -0
  62. package/dist/query/errors.js +16 -0
  63. package/dist/query/errors.js.map +1 -0
  64. package/dist/query/query.d.ts +27 -0
  65. package/dist/query/query.js +35 -0
  66. package/dist/query/query.js.map +1 -0
  67. package/dist/recorded/query-planner/catalog-google_search_console.json +140 -0
  68. package/dist/recorded/query-planner/catalog.json +1234 -0
  69. package/dist/spec/query-planner/index.d.ts +1 -0
  70. package/dist/spec/query-planner/index.js +3 -0
  71. package/dist/spec/query-planner/index.js.map +1 -0
  72. package/dist/spec/query-planner/types.gen.d.ts +300 -0
  73. package/dist/spec/query-planner/types.gen.js +3 -0
  74. package/dist/spec/query-planner/types.gen.js.map +1 -0
  75. package/dist/spec/query-planner/zod.gen.d.ts +325 -0
  76. package/dist/spec/query-planner/zod.gen.js +137 -0
  77. package/dist/spec/query-planner/zod.gen.js.map +1 -0
  78. package/package.json +90 -4
@@ -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,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AC,IAAI,EAAE,EAAE,CAAC,CAAA;QAClC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;IACxD,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,MAAM,GAAG,CAAC,KAAe,EAAoD,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA"}
@@ -0,0 +1,35 @@
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
+ /**
24
+ * One request out, as every transport of the SDK's own sends it (sign-in's too, #63), with
25
+ * `headers` in place of `built`'s. Nothing is sent once `signal` has fired. No cookies, and no
26
+ * redirect followed: a redirect would take what the request carries (a token, a code) to a URL
27
+ * nobody checked. A 3xx comes back as it is, outside the contract (`readJson`).
28
+ */
29
+ export declare function sendRequest(send: typeof fetch, built: Request, headers: Headers, signal: AbortSignal): Promise<{
30
+ readonly kind: 'sent';
31
+ readonly response: Response;
32
+ } | typeof ABORTED | {
33
+ readonly kind: 'unavailable';
34
+ }>;
35
+ export {};
@@ -0,0 +1,105 @@
1
+ const SERVICES = ['query', 'api', 'auth'];
2
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
3
+ const ABORTED = { kind: 'aborted' };
4
+ const REFUSED = { kind: 'refused', reason: 'destination' };
5
+ export function fetchTransport(options) {
6
+ const send = options.fetch ?? globalThis.fetch;
7
+ // Parsed once: a host that is not a URL throws here, at once, not on the first call.
8
+ const origins = new Map();
9
+ for (const service of SERVICES) {
10
+ const host = options.hosts[service];
11
+ if (host !== undefined)
12
+ origins.set(service, new URL(host).origin);
13
+ }
14
+ const secure = (url) => url.protocol === 'https:' ||
15
+ (options.allowLocalhostHttp === true && url.protocol === 'http:' && LOOPBACK.has(url.hostname));
16
+ /**
17
+ * One send. The destination comes first, so a call that may not go asks for no token and spends
18
+ * no refresh. The Request is built once, and that same object is checked and sent, so a
19
+ * factory can't hand the check one URL and the network another.
20
+ */
21
+ async function attempt(call, ask) {
22
+ const built = call.makeRequest();
23
+ const url = new URL(built.url);
24
+ if (!secure(url) || origins.get(call.service) !== url.origin)
25
+ return REFUSED;
26
+ const token = await tokenFor(options.token, ask, call.signal);
27
+ if (token.kind !== 'token')
28
+ return token;
29
+ if (call.signal.aborted)
30
+ return ABORTED;
31
+ const headers = new Headers(built.headers);
32
+ try {
33
+ headers.set('authorization', `Bearer ${token.token}`);
34
+ }
35
+ catch (cause) {
36
+ // A token no header can carry (a line break, a NUL, a character past U+00FF) is no token.
37
+ return { kind: 'no_token', cause };
38
+ }
39
+ const sent = await sendRequest(send, built, headers, call.signal);
40
+ return sent.kind === 'sent' ? { ...sent, token: token.token } : sent;
41
+ }
42
+ return async (call) => {
43
+ const first = await attempt(call, {});
44
+ if (first.kind !== 'sent')
45
+ return first;
46
+ if (first.response.status !== 401)
47
+ return { kind: 'response', response: first.response };
48
+ // A 401 means nothing ran, so the one resend is safe for any method (D414). A second 401 is
49
+ // the answer.
50
+ void first.response.body?.cancel().catch(() => undefined);
51
+ const again = await attempt(call, { rejected: first.token });
52
+ return again.kind === 'sent' ? { kind: 'response', response: again.response } : again;
53
+ };
54
+ }
55
+ /**
56
+ * One request out, as every transport of the SDK's own sends it (sign-in's too, #63), with
57
+ * `headers` in place of `built`'s. Nothing is sent once `signal` has fired. No cookies, and no
58
+ * redirect followed: a redirect would take what the request carries (a token, a code) to a URL
59
+ * nobody checked. A 3xx comes back as it is, outside the contract (`readJson`).
60
+ */
61
+ export async function sendRequest(send, built, headers, signal) {
62
+ if (signal.aborted)
63
+ return ABORTED;
64
+ const request = new Request(built, { headers, signal, credentials: 'omit', redirect: 'manual' });
65
+ // A Request follows its signal only weakly. Held from the call's signal while it is sent, so
66
+ // a fetch that keeps it only through its own abort listener is still told when the call ends
67
+ // (#57: without this, under forced garbage collection, it was told 0 times in 20).
68
+ const holdRequest = () => void request;
69
+ signal.addEventListener('abort', holdRequest, { once: true });
70
+ try {
71
+ return { kind: 'sent', response: await send(request) };
72
+ }
73
+ catch {
74
+ return signal.aborted ? ABORTED : { kind: 'unavailable' };
75
+ }
76
+ finally {
77
+ signal.removeEventListener('abort', holdRequest);
78
+ }
79
+ }
80
+ /**
81
+ * The token function's answer, raced against the call's signal: an abort while it is pending
82
+ * ends the call at once (#30). The function itself runs on; its answer is dropped.
83
+ */
84
+ async function tokenFor(token, ask, signal) {
85
+ if (signal.aborted)
86
+ return ABORTED;
87
+ let stop = () => undefined;
88
+ const aborted = new Promise((resolve) => {
89
+ stop = () => resolve(ABORTED);
90
+ signal.addEventListener('abort', stop, { once: true });
91
+ });
92
+ // Through then(), so a function that throws at once is caught like one that rejects.
93
+ const asked = Promise.resolve()
94
+ .then(() => token(ask))
95
+ .then((value) => typeof value === 'string' && value !== ''
96
+ ? { kind: 'token', token: value }
97
+ : { kind: 'no_token', cause: new TypeError('the token function gave no token') }, (cause) => ({ kind: 'no_token', cause }));
98
+ try {
99
+ return await Promise.race([asked, aborted]);
100
+ }
101
+ finally {
102
+ signal.removeEventListener('abort', stop);
103
+ }
104
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AC,CAAA;IAC7C,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;IAC3C,CAAC;AACH,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { z } from 'zod';
2
+ import { type ApiError, type ApiResult } from './result.js';
3
+ import type { ServiceName, TransportResult } from './transport.js';
4
+ type NoAnswer = Exclude<TransportResult, {
5
+ readonly kind: 'response';
6
+ }>;
7
+ /** Why a transport has no answer to read. */
8
+ export declare function noAnswer(sent: NoAnswer): ApiError;
9
+ /**
10
+ * A transport's answer, read under the call's `signal` and checked against `schema`: the data, or
11
+ * the one failure it is. A failure status keeps what the host said (`Said`), read by `service`'s
12
+ * own error envelope (D442). A 2xx whose body is
13
+ * not JSON, or fails its schema, is `invalid`: reported, never shown as empty. Zod's issues name
14
+ * paths and expected types, never the body's values.
15
+ */
16
+ export declare function readJson<T>(sent: TransportResult, schema: z.ZodType<T>, signal: AbortSignal, service: ServiceName): Promise<ApiResult<T>>;
17
+ export {};
@@ -0,0 +1,92 @@
1
+ import { z } from 'zod';
2
+ import { parseJson, said } from './body.js';
3
+ import { classifyStatus } from './result.js';
4
+ /** Why a transport has no answer to read. */
5
+ export function noAnswer(sent) {
6
+ switch (sent.kind) {
7
+ case 'refused':
8
+ return { kind: 'refused' };
9
+ case 'unavailable':
10
+ return { kind: 'unavailable' };
11
+ case 'cancelled':
12
+ return { kind: 'cancelled' };
13
+ case 'aborted':
14
+ return { kind: 'aborted' };
15
+ case 'no_token':
16
+ return { kind: 'no_token', cause: sent.cause };
17
+ default: {
18
+ const unhandled = sent;
19
+ throw new Error(`unhandled transport result ${JSON.stringify(unhandled)}`);
20
+ }
21
+ }
22
+ }
23
+ /**
24
+ * A transport's answer, read under the call's `signal` and checked against `schema`: the data, or
25
+ * the one failure it is. A failure status keeps what the host said (`Said`), read by `service`'s
26
+ * own error envelope (D442). A 2xx whose body is
27
+ * not JSON, or fails its schema, is `invalid`: reported, never shown as empty. Zod's issues name
28
+ * paths and expected types, never the body's values.
29
+ */
30
+ export async function readJson(sent, schema, signal, service) {
31
+ if (sent.kind !== 'response')
32
+ return failed(noAnswer(sent));
33
+ const { response } = sent;
34
+ const { status } = response;
35
+ const meaning = classifyStatus(status);
36
+ if (meaning === 'outside-contract') {
37
+ void response.body?.cancel().catch(() => undefined);
38
+ return failed({ kind: 'invalid', issues: `HTTP status ${String(status)} is outside the contract`, status });
39
+ }
40
+ const body = await readText(response, signal);
41
+ if (!body.ok)
42
+ return failed(body.error);
43
+ if (meaning !== 'success')
44
+ return failed({ kind: meaning, status, ...said(body.text, service) });
45
+ const json = parseJson(body.text);
46
+ if (!json.ok)
47
+ return failed({ kind: 'invalid', issues: 'the body is not JSON', status, text: body.text });
48
+ const parsed = schema.safeParse(json.value);
49
+ if (!parsed.success)
50
+ return failed({ kind: 'invalid', issues: z.prettifyError(parsed.error), status });
51
+ return { ok: true, data: parsed.data };
52
+ }
53
+ /**
54
+ * The whole body as text, or why there is none: the caller aborted, or it broke off. A
55
+ * transport's body need not observe the signal (one read from memory doesn't, and a transport
56
+ * may hand over any stream), so the read holds its own reader and cancels it when the signal
57
+ * fires: the call ends at once, the body is let go, and late data is never handed over.
58
+ */
59
+ async function readText(response, signal) {
60
+ const aborted = { ok: false, error: { kind: 'aborted' } };
61
+ const { body } = response;
62
+ if (signal.aborted) {
63
+ void body?.cancel().catch(() => undefined);
64
+ return aborted;
65
+ }
66
+ if (body === null)
67
+ return { ok: true, text: '' };
68
+ const reader = body.getReader();
69
+ const stop = () => void reader.cancel().catch(() => undefined);
70
+ signal.addEventListener('abort', stop, { once: true });
71
+ // As Response.text() decodes: UTF-8, a leading BOM dropped, bad bytes replaced.
72
+ const decoder = new TextDecoder();
73
+ let text = '';
74
+ try {
75
+ for (;;) {
76
+ const chunk = await reader.read();
77
+ if (chunk.done)
78
+ break;
79
+ text += decoder.decode(chunk.value, { stream: true });
80
+ }
81
+ text += decoder.decode();
82
+ return signal.aborted ? aborted : { ok: true, text };
83
+ }
84
+ catch {
85
+ return signal.aborted ? aborted : { ok: false, error: { kind: 'unavailable' } };
86
+ }
87
+ finally {
88
+ signal.removeEventListener('abort', stop);
89
+ }
90
+ }
91
+ const failed = (error) => ({ ok: false, error });
92
+ //# sourceMappingURL=read.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/core/read.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAC3C,OAAO,EAAE,cAAc,EAAiC,MAAM,aAAa,CAAA;AAK3E,6CAA6C;AAC7C,MAAM,UAAU,QAAQ,CAAC,IAAc;IACrC,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;QAClB,KAAK,SAAS;YACZ,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAA;QAC5B,KAAK,aAAa;YAChB,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,CAAA;QAChC,KAAK,WAAW;YACd,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAA;QAC9B,KAAK,SAAS;YACZ,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAA;QAC5B,KAAK,UAAU;YACb,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAA;QAChD,OAAO,CAAC,CAAC,CAAC;YACR,MAAM,SAAS,GAAU,IAAI,CAAA;YAC7B,MAAM,IAAI,KAAK,CAAC,8BAA8B,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;QAC5E,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,IAAqB,EACrB,MAAoB,EACpB,MAAmB,EACnB,OAAoB;IAEpB,IAAI,IAAI,CAAC,IAAI,KAAK,UA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B,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAA;QACvD,CAAC;QACD,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAA;QACxB,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;IACtD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE,EAAE,CAAA;IACjF,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;IAC3C,CAAC;AACH,CAAC;AAED,MAAM,MAAM,GAAG,CAAC,KAAe,EAAoD,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA"}
@@ -0,0 +1,94 @@
1
+ import type { PlannerErrorCode } from '../spec/query-planner/types.gen.js';
2
+ /** What every call returns: its data, or one failure with one meaning (D412). */
3
+ export type ApiResult<T> = {
4
+ readonly ok: true;
5
+ readonly data: T;
6
+ } | {
7
+ readonly ok: false;
8
+ readonly error: ApiError;
9
+ };
10
+ /** The failures a status gives: the host answered, and said no. */
11
+ export type StatusKind = 'unauthorized' | 'forbidden' | 'not_found' | 'conflict' | 'rejected' | 'unavailable';
12
+ /**
13
+ * A host's error code: one of the codes the planner documents (#61), or one it added since, kept
14
+ * as it came, never dropped. `isPlannerCode` narrows it to the known ones, so a switch over them
15
+ * can be exhaustive. Whether a code means a retry is safe is the server's to say (DW37), never
16
+ * inferred here: until then, each endpoint's rule decides.
17
+ */
18
+ export type ErrorCode = PlannerErrorCode | (string & Record<never, never>);
19
+ /**
20
+ * What came with a failure status: the host's error, read from its body (today the planner's
21
+ * `{ code, message }`, D429), or the body as it came, when it is not one (a proxy's `Bad gateway`).
22
+ */
23
+ export type Said = {
24
+ readonly code: ErrorCode;
25
+ readonly message: string;
26
+ /** The request's id, once a host sends one. None does yet (D429). */
27
+ readonly requestId?: string;
28
+ readonly text?: never;
29
+ } | {
30
+ readonly text: string;
31
+ readonly code?: never;
32
+ readonly message?: never;
33
+ readonly requestId?: never;
34
+ };
35
+ /** A failure the host answered with a status, and what came with it. */
36
+ export type Answered = {
37
+ readonly kind: StatusKind;
38
+ readonly status: number;
39
+ /** How long the host asked the caller to wait (`Retry-After`), when it said so. */
40
+ readonly retryAfterMs?: number;
41
+ } & Said;
42
+ export type ApiError = Answered
43
+ /** No answer at all: offline, a body that broke off, or no token right now. */
44
+ | {
45
+ readonly kind: 'unavailable';
46
+ readonly status?: never;
47
+ }
48
+ /**
49
+ * Outside the contract: reported, never shown as empty. `status` is the response's, when one
50
+ * arrived; `text` is its body, when a 2xx body is not JSON.
51
+ */
52
+ | {
53
+ readonly kind: 'invalid';
54
+ readonly issues: string;
55
+ readonly status?: number;
56
+ readonly text?: string;
57
+ }
58
+ /** The app's session moved while the call ran: nobody may see the answer. */
59
+ | {
60
+ readonly kind: 'cancelled';
61
+ }
62
+ /** The caller's own abort (D409). */
63
+ | {
64
+ readonly kind: 'aborted';
65
+ }
66
+ /** The call's own deadline passed first (#15). A write's outcome is then unknown: it may have run. */
67
+ | {
68
+ readonly kind: 'timeout';
69
+ }
70
+ /**
71
+ * Nothing was sent, by rule: the destination isn't one of the configured hosts over https, or a
72
+ * path value can't stay one segment ('', '.', '..'). No token was asked for, and none went anywhere.
73
+ */
74
+ | {
75
+ readonly kind: 'refused';
76
+ }
77
+ /** The token function failed, or gave no token, so nothing was sent; `cause` is what it threw. */
78
+ | {
79
+ readonly kind: 'no_token';
80
+ readonly cause: unknown;
81
+ };
82
+ /**
83
+ * What an HTTP status means (the console's table, D412). Only 2xx is a success. A status no host
84
+ * should send (1xx, 3xx, 0 from an opaque redirect, or not a whole number) is outside the
85
+ * contract, so it is reported, never quietly passed.
86
+ */
87
+ export declare function classifyStatus(status: number): 'success' | StatusKind | 'outside-contract';
88
+ /** A failed call, thrown by `orThrow`, carrying its `ApiError`. */
89
+ export declare class ApiFailure extends Error {
90
+ readonly error: ApiError;
91
+ constructor(error: ApiError);
92
+ }
93
+ /** The data, or the failure thrown as `ApiFailure`, for callers who want exceptions (D412). */
94
+ export declare function orThrow<T>(result: ApiResult<T>): T;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * What an HTTP status means (the console's table, D412). Only 2xx is a success. A status no host
3
+ * should send (1xx, 3xx, 0 from an opaque redirect, or not a whole number) is outside the
4
+ * contract, so it is reported, never quietly passed.
5
+ */
6
+ export function classifyStatus(status) {
7
+ if (!Number.isInteger(status))
8
+ return 'outside-contract';
9
+ if (status >= 200 && status <= 299)
10
+ return 'success';
11
+ if (status === 401)
12
+ return 'unauthorized';
13
+ if (status === 403)
14
+ return 'forbidden';
15
+ if (status === 404)
16
+ return 'not_found';
17
+ if (status === 409 || status === 412)
18
+ return 'conflict';
19
+ if (status === 429 || (status >= 500 && status <= 599))
20
+ return 'unavailable';
21
+ if (status >= 400 && status <= 499)
22
+ return 'rejected';
23
+ return 'outside-contract';
24
+ }
25
+ /** A failed call, thrown by `orThrow`, carrying its `ApiError`. */
26
+ export class ApiFailure extends Error {
27
+ error;
28
+ constructor(error) {
29
+ super(`the call failed: ${error.kind}`);
30
+ this.name = 'ApiFailure';
31
+ this.error = error;
32
+ }
33
+ }
34
+ /** The data, or the failure thrown as `ApiFailure`, for callers who want exceptions (D412). */
35
+ export function orThrow(result) {
36
+ if (!result.ok)
37
+ throw new ApiFailure(result.error);
38
+ return result.data;
39
+ }
40
+ //# sourceMappingURL=result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result.js","sourceRoot":"","sources":["../../src/core/result.ts"],"names":[],"mappings":"AA+EA;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,MAAc;IAC3C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC;QAAE,OAAO,kBAAkB,CAAA;IACxD,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG;QAAE,OAAO,SAAS,CAAA;IACpD,IAAI,MAAM,KAAK,GAAG;QAAE,OAAO,cAAc,CAAA;IACzC,IAAI,MAAM,KAAK,GAAG;QAAE,OAAO,WAAW,CAAA;IACtC,IAAI,MAAM,KAAK,GAAG;QAAE,OAAO,WAAW,CAAA;IACtC,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG;QAAE,OAAO,UAAU,CAAA;IACvD,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC;QAAE,OAAO,aAAa,CAAA;IAC5E,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG;QAAE,OAAO,UAAU,CAAA;IACrD,OAAO,kBAAkB,CAAA;AAC3B,CAAC;AAED,mEAAmE;AACnE,MAAM,OAAO,UAAW,SAAQ,KAAK;IAC1B,KAAK,CAAU;IAExB,YAAY,KAAe;QACzB,KAAK,CAAC,oBAAoB,KAAK,CAAC,IAAI,EAAE,CAAC,CAAA;QACvC,IAAI,CAAC,IAAI,GAAG,YAAY,CAAA;QACxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;CACF;AAED,+FAA+F;AAC/F,MAAM,UAAU,OAAO,CAAI,MAAoB;IAC7C,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,IAAI,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAClD,OAAO,MAAM,CAAC,IAAI,CAAA;AACpB,CAAC"}
@@ -0,0 +1,40 @@
1
+ /** An endpoint's rule, declared next to its schema: `never` for `POST /query` (D414), `read` for GETs. */
2
+ export type RetryRule = 'never' | 'read';
3
+ /** What one attempt came to, as far as the rule cares. */
4
+ export type Outcome = {
5
+ readonly kind: 'answered';
6
+ readonly status: number;
7
+ readonly retryAfter: string | null;
8
+ }
9
+ /** No answer: offline, or a connection that failed. */
10
+ | {
11
+ readonly kind: 'unavailable';
12
+ }
13
+ /** Refused, no token, cancelled or aborted: never tried again (D433). */
14
+ | {
15
+ readonly kind: 'final';
16
+ };
17
+ export type Decision = {
18
+ readonly kind: 'stop';
19
+ } | {
20
+ readonly kind: 'wait';
21
+ readonly ms: number;
22
+ };
23
+ /**
24
+ * Whether to try again after `attempt` attempts, and after how long. A wait that would not end
25
+ * before `deadline` is not started: the outcome is the answer, and the caller decides.
26
+ */
27
+ export declare function decide(rule: RetryRule, attempt: number, outcome: Outcome, now: number, deadline: number): Decision;
28
+ /**
29
+ * The ceiling for a host's stated wait: a hostile or broken header must never park a caller for
30
+ * hours (`Retry-After: 999999999` is about 31 years). From the CLI's `api/http.ts`.
31
+ */
32
+ export declare const MAX_RETRY_AFTER_MS = 3600000;
33
+ /**
34
+ * `Retry-After` as milliseconds, in its delay-seconds form only (D434): digits, so no sign,
35
+ * fraction, hex or exponent, clamped to MAX_RETRY_AFTER_MS. An HTTP date in any of its three forms
36
+ * reads as no hint, and the backoff applies: no Flipstream host sends one, and the asks to the
37
+ * planner and #91 say seconds. `undefined` when absent or not seconds, never a guess. Moved from
38
+ * the CLI's `parseRetryAfterMs`; `retry-after-ms` is not read (#14).
39
+ */
40
+ export declare function parseRetryAfterMs(header: string | null): number | undefined;
@@ -0,0 +1,41 @@
1
+ /*
2
+ * When a call is tried again (D414, D433): a pure decision, with no IO and no clock of its own,
3
+ * so every rule is tested without a server or a timer.
4
+ */
5
+ /** The statuses a read is tried again after (D414). A 500 is not one: it says the server failed. */
6
+ const READ_STATUSES = new Set([408, 429, 502, 503, 504]);
7
+ const MAX_RETRIES = 2;
8
+ const STOP = { kind: 'stop' };
9
+ /**
10
+ * Whether to try again after `attempt` attempts, and after how long. A wait that would not end
11
+ * before `deadline` is not started: the outcome is the answer, and the caller decides.
12
+ */
13
+ export function decide(rule, attempt, outcome, now, deadline) {
14
+ if (rule === 'never' || outcome.kind === 'final' || attempt > MAX_RETRIES)
15
+ return STOP;
16
+ if (outcome.kind === 'answered' && !READ_STATUSES.has(outcome.status))
17
+ return STOP;
18
+ const asked = outcome.kind === 'answered' ? parseRetryAfterMs(outcome.retryAfter) : undefined;
19
+ // When the host names no wait: 500 ms, then 1 s. No jitter, so the decision stays pure.
20
+ const ms = asked ?? (attempt === 1 ? 500 : 1000);
21
+ return now + ms < deadline ? { kind: 'wait', ms } : STOP;
22
+ }
23
+ /**
24
+ * The ceiling for a host's stated wait: a hostile or broken header must never park a caller for
25
+ * hours (`Retry-After: 999999999` is about 31 years). From the CLI's `api/http.ts`.
26
+ */
27
+ export const MAX_RETRY_AFTER_MS = 3_600_000;
28
+ /**
29
+ * `Retry-After` as milliseconds, in its delay-seconds form only (D434): digits, so no sign,
30
+ * fraction, hex or exponent, clamped to MAX_RETRY_AFTER_MS. An HTTP date in any of its three forms
31
+ * reads as no hint, and the backoff applies: no Flipstream host sends one, and the asks to the
32
+ * planner and #91 say seconds. `undefined` when absent or not seconds, never a guess. Moved from
33
+ * the CLI's `parseRetryAfterMs`; `retry-after-ms` is not read (#14).
34
+ */
35
+ export function parseRetryAfterMs(header) {
36
+ if (header === null)
37
+ return undefined;
38
+ const trimmed = header.trim();
39
+ return /^\d{1,10}$/.test(trimmed) ? Math.min(MAX_RETRY_AFTER_MS, Number(trimmed) * 1000) : undefined;
40
+ }
41
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/core/retry.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAeH,oGAAoG;AACpG,MAAM,aAAa,GAAwB,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAC7E,MAAM,WAAW,GAAG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