@zerosumstudio/conduit 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,195 @@
1
+ import { t as ConduitError } from "./errors-DT0d6Qhy.js";
2
+
3
+ // src/http/redact.ts
4
+ /** What `ClientConfig.redact` falls back to. Spread it to widen the lists rather than replace them. */
5
+ const DEFAULT_REDACT = Object.freeze({
6
+ headers: Object.freeze([
7
+ "authorization",
8
+ "cookie",
9
+ "proxy-authorization",
10
+ "x-api-key",
11
+ "x-auth-token",
12
+ "x-csrf-token",
13
+ "x-xsrf-token",
14
+ "x-session-token",
15
+ "x-access-token",
16
+ "x-amz-security-token"
17
+ ]),
18
+ query: Object.freeze([
19
+ "token",
20
+ "access_token",
21
+ "refresh_token",
22
+ "id_token",
23
+ "code",
24
+ "key",
25
+ "api_key",
26
+ "apikey",
27
+ "password",
28
+ "secret",
29
+ "signature",
30
+ "sig",
31
+ "client_secret",
32
+ "access-token",
33
+ "jwt",
34
+ "private_token",
35
+ "sessionid",
36
+ "x-amz-*",
37
+ "x-goog-*"
38
+ ])
39
+ });
40
+ const REDACTED = "[redacted]";
41
+ /** Lowercases both lists, and falls back to the defaults for whichever one is left out. */
42
+ function resolveRedact(config = {}) {
43
+ return {
44
+ headers: (config.headers ?? DEFAULT_REDACT.headers).map((name) => name.toLowerCase()),
45
+ query: (config.query ?? DEFAULT_REDACT.query).map((name) => name.toLowerCase())
46
+ };
47
+ }
48
+ /** The headers the redirect and upload guards treat as credentials: the defaults, plus any configured. */
49
+ function resolveCredentialHeaders(config = {}) {
50
+ const configured = (config.headers ?? []).map((name) => name.toLowerCase());
51
+ return [.../* @__PURE__ */ new Set([...DEFAULT_REDACT.headers, ...configured])];
52
+ }
53
+ function stripQuery(url) {
54
+ const mark = url.search(/[?#]/);
55
+ return mark === -1 ? url : url.slice(0, mark);
56
+ }
57
+ function decodeName(name) {
58
+ try {
59
+ return decodeURIComponent(name.replace(/\+/g, " ")).toLowerCase();
60
+ } catch {
61
+ return name.toLowerCase();
62
+ }
63
+ }
64
+ /** Builds a function that replaces the value of every named query parameter in a url. */
65
+ function createUrlRedactor(names) {
66
+ if (names.length === 0) return (url) => url;
67
+ const exact = /* @__PURE__ */ new Set();
68
+ const prefixes = [];
69
+ for (const name of names) if (name.endsWith("*")) prefixes.push(name.slice(0, -1));
70
+ else exact.add(name);
71
+ const isSecret = (name) => exact.has(name) || prefixes.some((prefix) => name.startsWith(prefix));
72
+ return (url) => {
73
+ const mark = url.indexOf("?");
74
+ if (mark === -1) return url;
75
+ const hashMark = url.indexOf("#", mark);
76
+ const end = hashMark === -1 ? url.length : hashMark;
77
+ const pairs = url.slice(mark + 1, end).split("&").map((pair) => {
78
+ const split = pair.indexOf("=");
79
+ if (split === -1) return pair;
80
+ return isSecret(decodeName(pair.slice(0, split))) ? `${pair.slice(0, split)}=${REDACTED}` : pair;
81
+ });
82
+ return `${url.slice(0, mark)}?${pairs.join("&")}${url.slice(end)}`;
83
+ };
84
+ }
85
+ /** `GET https://host/path`, with no query, for every message conduit writes. */
86
+ function describeRequest(request) {
87
+ return `${request.method} ${stripQuery(request.url)}`;
88
+ }
89
+ /** The key as events and `.response()` show it: query secrets hidden, the real key left to the cache. */
90
+ function formatKey(request) {
91
+ return request.redactUrl(request.key);
92
+ }
93
+ /** The url a `ConduitError` carries: the request's url with its secret query values hidden. */
94
+ function formatErrorUrl(request) {
95
+ return request.redactUrl(request.url);
96
+ }
97
+ /** An error about one request: its method, query-safe url and owner, and a message that starts with what was asked. */
98
+ function createRequestError(request, code, detail, extras = {}) {
99
+ return new ConduitError({
100
+ code,
101
+ message: `${describeRequest(request)} ${detail}`,
102
+ method: request.method,
103
+ url: formatErrorUrl(request),
104
+ owner: request.owner,
105
+ ...extras
106
+ });
107
+ }
108
+ /**
109
+ * The request as events and `.response()` show it: credential headers read
110
+ * `[redacted]` and secret query values are hidden. The pipeline keeps the real one.
111
+ */
112
+ function redactRequest(request, rules) {
113
+ const descriptors = Object.getOwnPropertyDescriptors(request);
114
+ descriptors["url"] = {
115
+ enumerable: true,
116
+ configurable: true,
117
+ value: formatErrorUrl(request)
118
+ };
119
+ descriptors["key"] = {
120
+ enumerable: true,
121
+ configurable: true,
122
+ value: formatKey(request)
123
+ };
124
+ descriptors["headers"] = {
125
+ enumerable: true,
126
+ configurable: true,
127
+ get() {
128
+ const redacted = new Headers(request.headers);
129
+ const hidden = /* @__PURE__ */ new Set([...rules.headers, ...request.meta.credentialHeaders ?? []]);
130
+ for (const name of hidden) if (redacted.has(name)) redacted.set(name, REDACTED);
131
+ return redacted;
132
+ }
133
+ };
134
+ return Object.defineProperties({}, descriptors);
135
+ }
136
+ /** Same idea as {@link redactRequest}, applied to the `request` a response carries. */
137
+ function redactResponse(response, rules) {
138
+ const descriptors = Object.getOwnPropertyDescriptors(response);
139
+ let redacted;
140
+ descriptors["request"] = {
141
+ enumerable: true,
142
+ configurable: true,
143
+ get() {
144
+ redacted ??= redactRequest(response.request, rules);
145
+ return redacted;
146
+ }
147
+ };
148
+ return Object.defineProperties({}, descriptors);
149
+ }
150
+
151
+ // src/primitives/stores.ts
152
+ const schedule = typeof queueMicrotask === "function" ? queueMicrotask : (task) => void Promise.resolve().then(task);
153
+ /**
154
+ * A value with subscribers. `getState()` is always current, and only the fan-out is
155
+ * batched onto a microtask, so one request settling is one render.
156
+ */
157
+ function createStore(initial) {
158
+ const listeners = /* @__PURE__ */ new Set();
159
+ let value = initial;
160
+ let isScheduled = false;
161
+ const notify = () => {
162
+ if (isScheduled || listeners.size === 0) return;
163
+ isScheduled = true;
164
+ schedule(() => {
165
+ isScheduled = false;
166
+ const snapshot = value;
167
+ for (const listener of [...listeners]) if (listeners.has(listener)) listener(snapshot);
168
+ });
169
+ };
170
+ return {
171
+ getState: () => value,
172
+ subscribe: (listener) => {
173
+ listeners.add(listener);
174
+ return () => {
175
+ listeners.delete(listener);
176
+ };
177
+ },
178
+ set: (next) => {
179
+ if (Object.is(next, value)) return;
180
+ value = next;
181
+ notify();
182
+ },
183
+ update: (recipe) => {
184
+ const next = recipe(value);
185
+ if (Object.is(next, value)) return;
186
+ value = next;
187
+ notify();
188
+ },
189
+ get listeners() {
190
+ return listeners.size;
191
+ }
192
+ };
193
+ }
194
+
195
+ export { formatErrorUrl as a, redactResponse as c, stripQuery as d, createUrlRedactor as i, resolveCredentialHeaders as l, DEFAULT_REDACT as n, formatKey as o, createRequestError as r, redactRequest as s, createStore as t, resolveRedact as u };
@@ -0,0 +1,88 @@
1
+ import { c as HttpMethod, s as FetchLike } from "./types-B9nuOKel.js";
2
+ import { a as clearSharedClients } from "./shared-2HssxK9p.js";
3
+ export interface MockRequest {
4
+ method: string;
5
+ /** The absolute url the client sent, query and all. */
6
+ url: string;
7
+ /** Just the path, which is what routes match against. */
8
+ path: string;
9
+ query: URLSearchParams;
10
+ /** Values captured by `:name` segments in the route pattern. */
11
+ params: Readonly<Record<string, string>>;
12
+ /** What a real fetch would send, including the `content-type` it derives from the body. */
13
+ headers: Headers;
14
+ body: BodyInit | null;
15
+ /** Aborts when the client cancels the request, so a responder can stop what it started. */
16
+ signal: AbortSignal;
17
+ /** The body decoded as JSON, or `undefined` if it was not text. */
18
+ json<T = unknown>(): T | undefined;
19
+ /** The body as text, or `undefined` if it was not text. */
20
+ text(): string | undefined;
21
+ }
22
+ export type MockCall = Pick<MockRequest, "method" | "url" | "path" | "headers" | "body">;
23
+ /** Spelled out rather than `unknown`, which would absorb the function arm of {@link MockResponder}. */
24
+ export type MockValue = Response | Error | Blob | FormData | URLSearchParams | ArrayBuffer | ReadableStream | Record<string, unknown> | readonly unknown[] | string | number | boolean | null | undefined;
25
+ /**
26
+ * What a route answers with:
27
+ *
28
+ * - a `Response` is used as-is
29
+ * - an `Error` is a network failure
30
+ * - `undefined` is a 204
31
+ * - a string, `Blob`, `FormData`, `URLSearchParams`, `ArrayBuffer` or stream is the body of a `new Response()`, so a string is text
32
+ * - anything else is JSON, so the common case is `server.get('/me', { id: 1 })`
33
+ *
34
+ * A function may return any of these, and one that throws answers 500.
35
+ */
36
+ export type MockResponder = ((request: MockRequest) => unknown) | MockValue;
37
+ export declare function json(body: unknown, init?: ResponseInit): Response;
38
+ export declare function text(body: string, init?: ResponseInit): Response;
39
+ /** A failing status with an optional body. */
40
+ export declare function status(code: number, body?: unknown): Response;
41
+ /** A request that never reached a server, as distinct from one that failed. */
42
+ export declare function networkError(message?: string): TypeError;
43
+ /** Wraps a responder so it answers late. Pair it with fake timers. */
44
+ export declare function delay(ms: number, responder: MockResponder): MockResponder;
45
+ export interface MockRouteOptions {
46
+ /** Retire the route after this many matches. */
47
+ times?: number | undefined;
48
+ }
49
+ export interface MockServerConfig {
50
+ /**
51
+ * Prefixed to every string pattern, so routes read like the client's paths.
52
+ * An absolute one, `https://api.test/v1`, also pins the origin the routes match.
53
+ */
54
+ baseUrl?: string | undefined;
55
+ /** What an unmatched request does. Throwing, the default, fails it where it was made. */
56
+ onUnmatched?: "throw" | "notFound" | undefined;
57
+ }
58
+ export interface MockServer {
59
+ /** Hand this to `createClient({ fetch })`. */
60
+ readonly fetch: FetchLike;
61
+ /** Every request that arrived, in order. */
62
+ readonly calls: readonly MockCall[];
63
+ /** Later routes win, and a route used up by `times` falls through to the earlier ones. */
64
+ route(method: HttpMethod | "*", pattern: string | RegExp, responder: MockResponder, options?: MockRouteOptions): MockServer;
65
+ get(pattern: string | RegExp, responder: MockResponder, options?: MockRouteOptions): MockServer;
66
+ post(pattern: string | RegExp, responder: MockResponder, options?: MockRouteOptions): MockServer;
67
+ put(pattern: string | RegExp, responder: MockResponder, options?: MockRouteOptions): MockServer;
68
+ patch(pattern: string | RegExp, responder: MockResponder, options?: MockRouteOptions): MockServer;
69
+ delete(pattern: string | RegExp, responder: MockResponder, options?: MockRouteOptions): MockServer;
70
+ any(pattern: string | RegExp, responder: MockResponder, options?: MockRouteOptions): MockServer;
71
+ /** Drops every route and every recorded call. */
72
+ reset(): void;
73
+ }
74
+ /**
75
+ * A server for tests, without a server. It sits at the transport, so cache,
76
+ * dedupe, retry, the queue and session recovery all run for real, and it honours
77
+ * the request's signal the way a real fetch does.
78
+ *
79
+ * ```ts
80
+ * const server = createMockServer({ baseUrl: 'https://api.test' })
81
+ * server.get('/users/:id', request => ({ id: request.params.id }))
82
+ * server.post('/users', status(201, { id: 2 }))
83
+ *
84
+ * const api = createClient({ baseUrl: 'https://api.test', fetch: server.fetch })
85
+ * ```
86
+ */
87
+ export declare function createMockServer(config?: MockServerConfig): MockServer;
88
+ export { clearSharedClients };
@@ -0,0 +1,224 @@
1
+ import { t as ConduitError } from "./errors-DT0d6Qhy.js";
2
+ import { t as clearSharedClients } from "./shared-BsSjKC7q.js";
3
+
4
+ // src/testing.ts
5
+ function json(body, init = {}) {
6
+ const headers = new Headers(init.headers);
7
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
8
+ return new Response(JSON.stringify(body), {
9
+ ...init,
10
+ headers
11
+ });
12
+ }
13
+ function text(body, init = {}) {
14
+ const headers = new Headers(init.headers);
15
+ if (!headers.has("content-type")) headers.set("content-type", "text/plain");
16
+ return new Response(body, {
17
+ ...init,
18
+ headers
19
+ });
20
+ }
21
+ /** A failing status with an optional body. */
22
+ function status(code, body = null) {
23
+ return body === null ? new Response(null, { status: code }) : json(body, { status: code });
24
+ }
25
+ /** A request that never reached a server, as distinct from one that failed. */
26
+ function networkError(message = "Failed to fetch") {
27
+ return new TypeError(message);
28
+ }
29
+ /** A real fetch rejects with the abort reason as it is, which need not be an Error. */
30
+ function rejectWith(reject, reason) {
31
+ reject(reason);
32
+ }
33
+ /** Waits, unless the request is cancelled first, and frees its timer when it is. */
34
+ function sleep(ms, signal) {
35
+ return new Promise((resolve, reject) => {
36
+ if (signal.aborted) {
37
+ rejectWith(reject, signal.reason);
38
+ return;
39
+ }
40
+ const onAbort = () => {
41
+ clearTimeout(timer);
42
+ rejectWith(reject, signal.reason);
43
+ };
44
+ const timer = setTimeout(() => {
45
+ signal.removeEventListener("abort", onAbort);
46
+ resolve();
47
+ }, ms);
48
+ signal.addEventListener("abort", onAbort, { once: true });
49
+ });
50
+ }
51
+ /** Wraps a responder so it answers late. Pair it with fake timers. */
52
+ function delay(ms, responder) {
53
+ return async (request) => {
54
+ await sleep(ms, request.signal);
55
+ return typeof responder === "function" ? responder(request) : responder;
56
+ };
57
+ }
58
+ const ESCAPE = /[.+^${}()|[\]\\]/g;
59
+ /**
60
+ * Turns `/users/:id` into a matcher that also captures `id`, and `*` into a
61
+ * wildcard. A `RegExp` is used as given.
62
+ */
63
+ function toMatcher(pattern) {
64
+ if (pattern instanceof RegExp) return pattern;
65
+ const source = pattern.replace(ESCAPE, "\\$&").replace(/\*/g, ".*").replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, "(?<$1>[^/]+)");
66
+ return new RegExp(`^${source}$`);
67
+ }
68
+ const RESPONSE_BODIES = [
69
+ Blob,
70
+ FormData,
71
+ URLSearchParams,
72
+ ArrayBuffer,
73
+ ReadableStream
74
+ ];
75
+ /** Resolves once the answer is ready, or rejects with `signal.reason` the moment the request is cancelled. */
76
+ function raceSignal(promise, signal) {
77
+ return new Promise((resolve, reject) => {
78
+ if (signal.aborted) {
79
+ rejectWith(reject, signal.reason);
80
+ return;
81
+ }
82
+ const onAbort = () => {
83
+ rejectWith(reject, signal.reason);
84
+ };
85
+ signal.addEventListener("abort", onAbort, { once: true });
86
+ promise.then((value) => {
87
+ signal.removeEventListener("abort", onAbort);
88
+ resolve(value);
89
+ }, (error) => {
90
+ signal.removeEventListener("abort", onAbort);
91
+ rejectWith(reject, error);
92
+ });
93
+ });
94
+ }
95
+ function toResponse(result) {
96
+ if (result instanceof Response) return result.clone();
97
+ if (result instanceof Error) throw result;
98
+ if (result === void 0) return new Response(null, { status: 204 });
99
+ if (typeof result === "string" || RESPONSE_BODIES.some((body) => result instanceof body)) return new Response(result);
100
+ return json(result);
101
+ }
102
+ async function answer(responder, request) {
103
+ let result;
104
+ try {
105
+ result = typeof responder === "function" ? await responder(request) : responder;
106
+ } catch (error) {
107
+ return json({ message: error instanceof Error ? error.message : String(error) }, { status: 500 });
108
+ }
109
+ return toResponse(result);
110
+ }
111
+ function parseBase(baseUrl) {
112
+ if (URL.canParse(baseUrl)) {
113
+ const parsed = new URL(baseUrl);
114
+ return {
115
+ origin: parsed.origin,
116
+ prefix: parsed.pathname.replace(/\/$/, "")
117
+ };
118
+ }
119
+ return {
120
+ origin: void 0,
121
+ prefix: baseUrl.replace(/\/$/, "")
122
+ };
123
+ }
124
+ /**
125
+ * A server for tests, without a server. It sits at the transport, so cache,
126
+ * dedupe, retry, the queue and session recovery all run for real, and it honours
127
+ * the request's signal the way a real fetch does.
128
+ *
129
+ * ```ts
130
+ * const server = createMockServer({ baseUrl: 'https://api.test' })
131
+ * server.get('/users/:id', request => ({ id: request.params.id }))
132
+ * server.post('/users', status(201, { id: 2 }))
133
+ *
134
+ * const api = createClient({ baseUrl: 'https://api.test', fetch: server.fetch })
135
+ * ```
136
+ */
137
+ function createMockServer(config = {}) {
138
+ const base = parseBase(config.baseUrl ?? "");
139
+ const unmatched = config.onUnmatched ?? "throw";
140
+ const routes = [];
141
+ const calls = [];
142
+ /** The last registered route that still has matches left and fits the method and path. */
143
+ const findRoute = (method, path) => {
144
+ for (let index = routes.length - 1; index >= 0; index--) {
145
+ const route = routes[index];
146
+ if (route === void 0 || route.remaining <= 0) continue;
147
+ if (route.method !== "*" && route.method !== method) continue;
148
+ const match = route.matcher.exec(path);
149
+ if (match !== null) return {
150
+ route,
151
+ match
152
+ };
153
+ }
154
+ };
155
+ const handle = async (url, init) => {
156
+ const request = new Request(url, init);
157
+ const parsed = new URL(url);
158
+ const method = request.method;
159
+ const headers = request.headers;
160
+ const body = init.body ?? null;
161
+ const path = parsed.pathname;
162
+ calls.push({
163
+ method,
164
+ url: parsed.href,
165
+ path,
166
+ headers,
167
+ body
168
+ });
169
+ const route = base.origin !== void 0 && parsed.origin !== base.origin ? void 0 : findRoute(method, path);
170
+ if (route !== void 0) {
171
+ route.route.remaining--;
172
+ return answer(route.route.responder, {
173
+ method,
174
+ url: parsed.href,
175
+ path,
176
+ query: parsed.searchParams,
177
+ params: route.match.groups ?? {},
178
+ headers,
179
+ body,
180
+ signal: request.signal,
181
+ json: () => typeof body === "string" ? JSON.parse(body) : void 0,
182
+ text: () => typeof body === "string" ? body : void 0
183
+ });
184
+ }
185
+ if (unmatched === "notFound") return new Response(null, { status: 404 });
186
+ const registered = routes.length === 0 ? "(none)" : routes.map((r) => r.label).reverse().join(", ");
187
+ throw new ConduitError({
188
+ code: "INVALID_ARGUMENT",
189
+ message: `No route for ${method} ${path}. Registered, latest first: ${registered}`,
190
+ method
191
+ });
192
+ };
193
+ const server = {
194
+ calls,
195
+ fetch: (url, init) => {
196
+ const signal = init.signal ?? new AbortController().signal;
197
+ return raceSignal(handle(url, init), signal);
198
+ },
199
+ route: (method, pattern, responder, options = {}) => {
200
+ const prefixed = typeof pattern === "string" ? `${base.prefix}${pattern}` : pattern;
201
+ routes.push({
202
+ method,
203
+ label: `${method} ${String(prefixed)}`,
204
+ matcher: toMatcher(prefixed),
205
+ responder,
206
+ remaining: options.times ?? Number.POSITIVE_INFINITY
207
+ });
208
+ return server;
209
+ },
210
+ get: (pattern, responder, options) => server.route("GET", pattern, responder, options),
211
+ post: (pattern, responder, options) => server.route("POST", pattern, responder, options),
212
+ put: (pattern, responder, options) => server.route("PUT", pattern, responder, options),
213
+ patch: (pattern, responder, options) => server.route("PATCH", pattern, responder, options),
214
+ delete: (pattern, responder, options) => server.route("DELETE", pattern, responder, options),
215
+ any: (pattern, responder, options) => server.route("*", pattern, responder, options),
216
+ reset: () => {
217
+ routes.length = 0;
218
+ calls.length = 0;
219
+ }
220
+ };
221
+ return server;
222
+ }
223
+
224
+ export { clearSharedClients, createMockServer, delay, json, networkError, status, text };