@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.
- package/LICENSE +21 -0
- package/README.md +785 -2
- package/dist/core-DXSbz15-.d.ts +142 -0
- package/dist/dev-CNYwEGcY.js +14 -0
- package/dist/devtools.d.ts +61 -0
- package/dist/devtools.js +152 -0
- package/dist/errors-DT0d6Qhy.js +85 -0
- package/dist/index.d.ts +177 -0
- package/dist/index.js +2412 -0
- package/dist/observable-LsEew2iL.d.ts +30 -0
- package/dist/query-state-BlmK3fBM.js +37 -0
- package/dist/react.d.ts +75 -0
- package/dist/react.js +331 -0
- package/dist/shared-2HssxK9p.d.ts +53 -0
- package/dist/shared-BsSjKC7q.js +118 -0
- package/dist/stores-DGXWZXXg.js +195 -0
- package/dist/testing.d.ts +88 -0
- package/dist/testing.js +224 -0
- package/dist/types-B9nuOKel.d.ts +689 -0
- package/dist/upload.d.ts +27 -0
- package/dist/upload.js +94 -0
- package/docs/migration-1.0.md +423 -0
- package/docs/threat-model.md +69 -0
- package/package.json +151 -3
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { k as ResponseSource, lt as ReadableStore, pt as ConduitError, y as Plugin } from "./types-B9nuOKel.js";
|
|
2
|
+
type QueryStatus = "idle" | "loading" | "success" | "error";
|
|
3
|
+
interface QueryState<T> {
|
|
4
|
+
readonly status: QueryStatus;
|
|
5
|
+
readonly data: T | undefined;
|
|
6
|
+
readonly error: ConduitError | undefined;
|
|
7
|
+
/** Where the last answer came from. `stale` means it was served past its ttl while a refresh ran. */
|
|
8
|
+
readonly from: ResponseSource | undefined;
|
|
9
|
+
/** A request for this key is in the air, whether or not there is already data. */
|
|
10
|
+
readonly isFetching: boolean;
|
|
11
|
+
readonly updatedAt: number;
|
|
12
|
+
/** Bumped whenever a cache invalidation or identity reset targets this key. */
|
|
13
|
+
readonly invalidatedAt: number;
|
|
14
|
+
}
|
|
15
|
+
interface ObservableConfig {
|
|
16
|
+
/** How many keys to keep state for. Defaults to 200. A watched key is never evicted. */
|
|
17
|
+
max?: number | undefined;
|
|
18
|
+
}
|
|
19
|
+
interface ObservableApi {
|
|
20
|
+
/** The live state of one key, created on first call and shared by every watcher. */
|
|
21
|
+
observe<T = unknown>(key: string): ReadableStore<QueryState<T>>;
|
|
22
|
+
/** How many keys currently have state. */
|
|
23
|
+
getObservedCount(): number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Turns request traffic into per-key state for framework bindings to read. It
|
|
27
|
+
* lives on the client, so two remotes rendering the same query watch one store.
|
|
28
|
+
*/
|
|
29
|
+
declare function observable(config?: ObservableConfig): Plugin<ObservableApi>;
|
|
30
|
+
export { QueryStatus as a, QueryState as i, ObservableConfig as n, observable as r, ObservableApi as t };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// src/client/endpoint.ts
|
|
2
|
+
function defineEndpoint(def) {
|
|
3
|
+
return {
|
|
4
|
+
...def,
|
|
5
|
+
kind: "conduit.endpoint"
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
/** Endpoints accept a static list or a function of `vars`. It reads either. */
|
|
9
|
+
function resolveEndpointTags(tags, vars) {
|
|
10
|
+
if (tags === void 0) return;
|
|
11
|
+
return typeof tags === "function" ? tags(vars) : tags;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/http/method.ts
|
|
15
|
+
const READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
16
|
+
/** Whether a request reads: what it says, else whether the method is `GET` or `HEAD`. */
|
|
17
|
+
function isCacheable(method, cacheable) {
|
|
18
|
+
return cacheable ?? READ_METHODS.has(method);
|
|
19
|
+
}
|
|
20
|
+
/** Whether the method can carry no body at all. */
|
|
21
|
+
function isBodyless(method) {
|
|
22
|
+
return READ_METHODS.has(method);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// src/plugins/query-state.ts
|
|
26
|
+
/** What a key that nothing has asked for yet, or a disabled query, reads as. */
|
|
27
|
+
const IDLE_QUERY_STATE = {
|
|
28
|
+
status: "idle",
|
|
29
|
+
data: void 0,
|
|
30
|
+
error: void 0,
|
|
31
|
+
from: void 0,
|
|
32
|
+
isFetching: false,
|
|
33
|
+
updatedAt: 0,
|
|
34
|
+
invalidatedAt: 0
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export { resolveEndpointTags as a, defineEndpoint as i, isBodyless as n, isCacheable as r, IDLE_QUERY_STATE as t };
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { i as Endpoint, t as Client } from "./core-DXSbz15-.js";
|
|
2
|
+
import { a as QueryStatus, i as QueryState, t as ObservableApi } from "./observable-LsEew2iL.js";
|
|
3
|
+
import { A as SafeResult, ot as SessionState, pt as ConduitError, rt as SessionApi, u as MethodOptions } from "./types-B9nuOKel.js";
|
|
4
|
+
export interface UseRequestOptions extends MethodOptions {
|
|
5
|
+
/** Hold off until a dependency is ready. Defaults to true. */
|
|
6
|
+
enabled?: boolean | undefined;
|
|
7
|
+
/** Keep the last successful answer on screen while a new key's first fetch is in flight. Defaults to false. */
|
|
8
|
+
keepPreviousData?: boolean | undefined;
|
|
9
|
+
/** Read again when the tab becomes visible. A fresh cache entry is served as it is. Defaults to false. */
|
|
10
|
+
refetchOnFocus?: boolean | undefined;
|
|
11
|
+
/** Read again when the connection comes back. Defaults to false. */
|
|
12
|
+
refetchOnReconnect?: boolean | undefined;
|
|
13
|
+
}
|
|
14
|
+
export interface UseRequestResult<T> {
|
|
15
|
+
data: T | undefined;
|
|
16
|
+
error: ConduitError | undefined;
|
|
17
|
+
status: QueryStatus;
|
|
18
|
+
/** No data yet and a request is in the air. */
|
|
19
|
+
isLoading: boolean;
|
|
20
|
+
/** A request is in the air, with or without data on screen. */
|
|
21
|
+
isFetching: boolean;
|
|
22
|
+
/** The data on screen was served past its ttl, while a refresh runs behind it. */
|
|
23
|
+
isStale: boolean;
|
|
24
|
+
/** When the data on screen arrived, in epoch milliseconds. `0` before anything has. */
|
|
25
|
+
updatedAt: number;
|
|
26
|
+
/** Always asks the network, whatever the cache holds. */
|
|
27
|
+
refetch(): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
export interface UseMutationOptions<V> {
|
|
30
|
+
/** Tags to invalidate once `mutate` succeeds. Needs the cache plugin. */
|
|
31
|
+
invalidates?: readonly string[] | ((variables: V) => readonly string[]) | undefined;
|
|
32
|
+
}
|
|
33
|
+
export type MutationStatus = "idle" | "pending" | "success" | "error";
|
|
34
|
+
export interface UseMutationResult<T, V> {
|
|
35
|
+
/** Never rejects. Resolves the same `SafeResult` as `.safe()`, after the tags are invalidated. */
|
|
36
|
+
mutate(variables: V): Promise<SafeResult<T>>;
|
|
37
|
+
/** The latest call owns the state, whichever one settles last. */
|
|
38
|
+
status: MutationStatus;
|
|
39
|
+
data: T | undefined;
|
|
40
|
+
error: ConduitError | undefined;
|
|
41
|
+
isPending: boolean;
|
|
42
|
+
reset(): void;
|
|
43
|
+
}
|
|
44
|
+
export interface Hooks {
|
|
45
|
+
/**
|
|
46
|
+
* Runs a request and renders its state, keyed the way the cache and dedupe
|
|
47
|
+
* key it. It never cancels what it started: a request that was superseded or
|
|
48
|
+
* outlived its component finishes and fills the cache. Cancel with a `scope`
|
|
49
|
+
* or your own `signal`.
|
|
50
|
+
*
|
|
51
|
+
* A client `headers` function that answers differently per call gives every
|
|
52
|
+
* render a different key under `vary: '*'`, and this refetches on each one.
|
|
53
|
+
* Development warns when that happens.
|
|
54
|
+
*/
|
|
55
|
+
useRequest<T = unknown>(path: string, options?: UseRequestOptions): UseRequestResult<T>;
|
|
56
|
+
useRequest<Vars, Result>(endpoint: Endpoint<Vars, Result>, vars: Vars, options?: UseRequestOptions): UseRequestResult<Result>;
|
|
57
|
+
useMutation<T = unknown, V = void>(run: (variables: V) => PromiseLike<T>, options?: UseMutationOptions<V>): UseMutationResult<T, V>;
|
|
58
|
+
useMutation<Vars, Result>(endpoint: Endpoint<Vars, Result>, options?: UseMutationOptions<Vars>): UseMutationResult<Result, Vars>;
|
|
59
|
+
/** Returns a warm-the-cache function that runs in the prefetch lane. */
|
|
60
|
+
usePrefetch(): (path: string, options?: MethodOptions) => void;
|
|
61
|
+
}
|
|
62
|
+
export interface SessionHooks<S> {
|
|
63
|
+
useSession(): SessionState<S>;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Binds the hooks to one client, at module scope rather than through a
|
|
67
|
+
* provider. Context does not cross a federation boundary; a shared client does.
|
|
68
|
+
*
|
|
69
|
+
* ```ts
|
|
70
|
+
* export const { useRequest, useSession } = createHooks(api)
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
export declare function createHooks<S>(client: Client & ObservableApi & SessionApi<S>): Hooks & SessionHooks<S>;
|
|
74
|
+
export declare function createHooks(client: Client & ObservableApi): Hooks;
|
|
75
|
+
export type { QueryState, QueryStatus };
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
2
|
+
import { a as resolveEndpointTags, r as isCacheable, t as IDLE_QUERY_STATE } from "./query-state-BlmK3fBM.js";
|
|
3
|
+
import { t as IS_DEVELOPMENT } from "./dev-CNYwEGcY.js";
|
|
4
|
+
import { i as toConduitError, r as isErrorCode, t as ConduitError } from "./errors-DT0d6Qhy.js";
|
|
5
|
+
|
|
6
|
+
// src/react.ts
|
|
7
|
+
const disabledStore = {
|
|
8
|
+
getState: () => IDLE_QUERY_STATE,
|
|
9
|
+
subscribe: () => () => {}
|
|
10
|
+
};
|
|
11
|
+
const IDLE_MUTATION = {
|
|
12
|
+
status: "idle",
|
|
13
|
+
data: void 0,
|
|
14
|
+
error: void 0
|
|
15
|
+
};
|
|
16
|
+
/** The hook flags, split from the options that go to the request. */
|
|
17
|
+
function splitOptions(options) {
|
|
18
|
+
const { enabled = true, keepPreviousData = false, refetchOnFocus = false, refetchOnReconnect = false, ...request } = options;
|
|
19
|
+
return {
|
|
20
|
+
behaviour: {
|
|
21
|
+
keepPreviousData,
|
|
22
|
+
refetchOnFocus,
|
|
23
|
+
refetchOnReconnect
|
|
24
|
+
},
|
|
25
|
+
isEnabled: enabled,
|
|
26
|
+
request
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The query key, or `undefined` while there is not one yet. An `INVALID_ARGUMENT`
|
|
31
|
+
* is a request that is not ready, such as a missing param, and says nothing.
|
|
32
|
+
* Anything else is a problem worth a development warning.
|
|
33
|
+
*/
|
|
34
|
+
function tryGetKey(client, isEnabled, getKey) {
|
|
35
|
+
if (!isEnabled) return;
|
|
36
|
+
try {
|
|
37
|
+
return getKey();
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (IS_DEVELOPMENT && !isErrorCode(error, "INVALID_ARGUMENT")) client.config.logger.warn(`[conduit] useRequest cannot derive a key: ${toConduitError(error).message}`);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Adds `cache: 'refresh'` for an explicit refetch, which skips whatever is stored. */
|
|
44
|
+
function buildRunOptions(request, key, refresh) {
|
|
45
|
+
return refresh ? {
|
|
46
|
+
...request,
|
|
47
|
+
key,
|
|
48
|
+
meta: {
|
|
49
|
+
...request.meta,
|
|
50
|
+
cache: "refresh"
|
|
51
|
+
}
|
|
52
|
+
} : {
|
|
53
|
+
...request,
|
|
54
|
+
key
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Whether the previous key's data stands in while a new key's first fetch is in flight. */
|
|
58
|
+
function isShowingPrevious(state, previous, key, keepPreviousData) {
|
|
59
|
+
return keepPreviousData && previous !== void 0 && key !== void 0 && previous.key !== key && state.data === void 0 && state.status !== "success";
|
|
60
|
+
}
|
|
61
|
+
/** What the hook returns: the store's state, or the previous key's while a new one loads. */
|
|
62
|
+
function buildResult(state, previous, key, isEnabled, keepPreviousData, refetch) {
|
|
63
|
+
const view = isShowingPrevious(state, previous, key, keepPreviousData) ? {
|
|
64
|
+
...previous,
|
|
65
|
+
isFetching: true
|
|
66
|
+
} : state;
|
|
67
|
+
const isAboutToFetch = isEnabled && key !== void 0 && view.status === "idle";
|
|
68
|
+
return {
|
|
69
|
+
data: view.data,
|
|
70
|
+
error: view.error,
|
|
71
|
+
status: view.status,
|
|
72
|
+
isLoading: view.data === void 0 && (view.isFetching || isAboutToFetch),
|
|
73
|
+
isFetching: view.isFetching,
|
|
74
|
+
isStale: view.from === "stale",
|
|
75
|
+
updatedAt: view.updatedAt,
|
|
76
|
+
refetch
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function invalidateTags(client, tags, variables) {
|
|
80
|
+
const resolved = resolveEndpointTags(tags, variables);
|
|
81
|
+
if (resolved === void 0) return;
|
|
82
|
+
for (const tag of resolved) client.invalidateTag?.(tag);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* One listener per page event however many hooks want it, attached when the
|
|
86
|
+
* first hook subscribes and removed with the last.
|
|
87
|
+
*/
|
|
88
|
+
function createPageEvent(target, type, isRelevant) {
|
|
89
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
90
|
+
const handle = () => {
|
|
91
|
+
if (!isRelevant()) return;
|
|
92
|
+
for (const listener of [...listeners]) listener();
|
|
93
|
+
};
|
|
94
|
+
return (listener) => {
|
|
95
|
+
const source = target();
|
|
96
|
+
if (source === void 0) return () => {};
|
|
97
|
+
if (listeners.size === 0) source.addEventListener(type, handle);
|
|
98
|
+
listeners.add(listener);
|
|
99
|
+
return () => {
|
|
100
|
+
listeners.delete(listener);
|
|
101
|
+
if (listeners.size === 0) source.removeEventListener(type, handle);
|
|
102
|
+
};
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function createHooks(client) {
|
|
106
|
+
/**
|
|
107
|
+
* Runs the hooks have started and that have not settled, by key and
|
|
108
|
+
* invalidation. StrictMode's second effect, and every hook watching a key that
|
|
109
|
+
* was just invalidated, join one run instead of each starting a request.
|
|
110
|
+
*/
|
|
111
|
+
const runs = /* @__PURE__ */ new Map();
|
|
112
|
+
const subscribeVisible = createPageEvent(() => typeof document === "undefined" ? void 0 : document, "visibilitychange", () => document.visibilityState === "visible");
|
|
113
|
+
const subscribeOnline = createPageEvent(() => typeof window === "undefined" ? void 0 : window, "online", () => true);
|
|
114
|
+
function useRequestCore(descriptor, behaviour) {
|
|
115
|
+
const { key, isEnabled, run } = descriptor;
|
|
116
|
+
const { keepPreviousData, refetchOnFocus, refetchOnReconnect } = behaviour;
|
|
117
|
+
const activeStore = useMemo(() => key === void 0 ? void 0 : client.observe(key), [key]) ?? disabledStore;
|
|
118
|
+
const state = useSyncExternalStore(activeStore.subscribe, activeStore.getState, activeStore.getState);
|
|
119
|
+
const latestRun = useRef(run);
|
|
120
|
+
const latestInvalidatedAt = useRef(state.invalidatedAt);
|
|
121
|
+
useEffect(() => {
|
|
122
|
+
latestRun.current = run;
|
|
123
|
+
latestInvalidatedAt.current = state.invalidatedAt;
|
|
124
|
+
});
|
|
125
|
+
const execute = useCallback((refresh) => {
|
|
126
|
+
if (key === void 0) return Promise.resolve();
|
|
127
|
+
const runId = `${key}@${latestInvalidatedAt.current}${refresh ? ":refresh" : ""}`;
|
|
128
|
+
const pending = runs.get(runId);
|
|
129
|
+
if (pending !== void 0) return pending;
|
|
130
|
+
const started = latestRun.current({ refresh }).finally(() => {
|
|
131
|
+
runs.delete(runId);
|
|
132
|
+
});
|
|
133
|
+
runs.set(runId, started);
|
|
134
|
+
return started;
|
|
135
|
+
}, [key]);
|
|
136
|
+
const refetch = useCallback(() => execute(true), [execute]);
|
|
137
|
+
useEffect(() => {
|
|
138
|
+
if (isEnabled) execute(false);
|
|
139
|
+
}, [
|
|
140
|
+
execute,
|
|
141
|
+
isEnabled,
|
|
142
|
+
state.invalidatedAt
|
|
143
|
+
]);
|
|
144
|
+
useEffect(() => {
|
|
145
|
+
if (!isEnabled || !refetchOnFocus) return;
|
|
146
|
+
return subscribeVisible(() => {
|
|
147
|
+
execute(false);
|
|
148
|
+
});
|
|
149
|
+
}, [
|
|
150
|
+
execute,
|
|
151
|
+
isEnabled,
|
|
152
|
+
refetchOnFocus
|
|
153
|
+
]);
|
|
154
|
+
useEffect(() => {
|
|
155
|
+
if (!isEnabled || !refetchOnReconnect) return;
|
|
156
|
+
return subscribeOnline(() => {
|
|
157
|
+
execute(false);
|
|
158
|
+
});
|
|
159
|
+
}, [
|
|
160
|
+
execute,
|
|
161
|
+
isEnabled,
|
|
162
|
+
refetchOnReconnect
|
|
163
|
+
]);
|
|
164
|
+
const [previous, setPrevious] = useState(void 0);
|
|
165
|
+
useEffect(() => {
|
|
166
|
+
if (!keepPreviousData || key === void 0) return;
|
|
167
|
+
if (state.status === "success" || state.status === "error") setPrevious({
|
|
168
|
+
key,
|
|
169
|
+
data: state.data,
|
|
170
|
+
error: state.error,
|
|
171
|
+
status: state.status,
|
|
172
|
+
from: state.from,
|
|
173
|
+
updatedAt: state.updatedAt
|
|
174
|
+
});
|
|
175
|
+
}, [
|
|
176
|
+
keepPreviousData,
|
|
177
|
+
key,
|
|
178
|
+
state.status,
|
|
179
|
+
state.data,
|
|
180
|
+
state.error,
|
|
181
|
+
state.from,
|
|
182
|
+
state.updatedAt
|
|
183
|
+
]);
|
|
184
|
+
return buildResult(state, previous, key, isEnabled, keepPreviousData, refetch);
|
|
185
|
+
}
|
|
186
|
+
function useRequestByPath(path, options) {
|
|
187
|
+
const { behaviour, isEnabled, request } = splitOptions(options);
|
|
188
|
+
const latestRequest = useRef(request);
|
|
189
|
+
useEffect(() => {
|
|
190
|
+
latestRequest.current = request;
|
|
191
|
+
});
|
|
192
|
+
const key = tryGetKey(client, isEnabled, () => client.getKey(path, request));
|
|
193
|
+
const hasWarned = useRef(false);
|
|
194
|
+
useEffect(() => {
|
|
195
|
+
if (!IS_DEVELOPMENT || hasWarned.current || key === void 0) return;
|
|
196
|
+
hasWarned.current = true;
|
|
197
|
+
if (client.getKey(path, request) !== key) client.config.logger.warn(`[conduit] useRequest("${path}") derived two keys in one render, so the client's headers function answers differently per call. Narrow vary to the headers that matter.`);
|
|
198
|
+
}, [
|
|
199
|
+
path,
|
|
200
|
+
request,
|
|
201
|
+
key
|
|
202
|
+
]);
|
|
203
|
+
return useRequestCore(useMemo(() => ({
|
|
204
|
+
key,
|
|
205
|
+
isEnabled: isEnabled && key !== void 0,
|
|
206
|
+
run: async ({ refresh }) => {
|
|
207
|
+
if (key !== void 0) await client.request(path, buildRunOptions(latestRequest.current, key, refresh)).safe();
|
|
208
|
+
}
|
|
209
|
+
}), [
|
|
210
|
+
path,
|
|
211
|
+
key,
|
|
212
|
+
isEnabled
|
|
213
|
+
]), behaviour);
|
|
214
|
+
}
|
|
215
|
+
function useRequestByEndpoint(endpoint, vars, options) {
|
|
216
|
+
const { behaviour, isEnabled, request } = splitOptions(options);
|
|
217
|
+
const latestVars = useRef(vars);
|
|
218
|
+
const latestRequest = useRef(request);
|
|
219
|
+
useEffect(() => {
|
|
220
|
+
latestVars.current = vars;
|
|
221
|
+
latestRequest.current = request;
|
|
222
|
+
});
|
|
223
|
+
useEffect(() => {
|
|
224
|
+
if (IS_DEVELOPMENT && !isCacheable(endpoint.method, endpoint.cacheable)) client.config.logger.warn(`[conduit] useRequest was given a ${endpoint.method} endpoint for "${endpoint.path}" that is not cacheable, so it sends a request on every mount. Use useMutation, or set cacheable: true.`);
|
|
225
|
+
}, [endpoint]);
|
|
226
|
+
const key = tryGetKey(client, isEnabled, () => client.getKey(endpoint, vars));
|
|
227
|
+
return useRequestCore(useMemo(() => ({
|
|
228
|
+
key,
|
|
229
|
+
isEnabled: isEnabled && key !== void 0,
|
|
230
|
+
run: async ({ refresh }) => {
|
|
231
|
+
if (key !== void 0) await client.call(endpoint, latestVars.current, buildRunOptions(latestRequest.current, key, refresh)).safe();
|
|
232
|
+
}
|
|
233
|
+
}), [
|
|
234
|
+
endpoint,
|
|
235
|
+
key,
|
|
236
|
+
isEnabled
|
|
237
|
+
]), behaviour);
|
|
238
|
+
}
|
|
239
|
+
function useRequest(pathOrEndpoint, varsOrOptions, maybeOptions) {
|
|
240
|
+
if (typeof pathOrEndpoint === "string") return useRequestByPath(pathOrEndpoint, varsOrOptions ?? {});
|
|
241
|
+
return useRequestByEndpoint(pathOrEndpoint, varsOrOptions, maybeOptions ?? {});
|
|
242
|
+
}
|
|
243
|
+
function useMutation(runOrEndpoint, options) {
|
|
244
|
+
const [state, setState] = useState(IDLE_MUTATION);
|
|
245
|
+
const isAlive = useRef(true);
|
|
246
|
+
const latestCall = useRef(0);
|
|
247
|
+
const latest = useRef(runOrEndpoint);
|
|
248
|
+
const latestOptions = useRef(options);
|
|
249
|
+
useEffect(() => {
|
|
250
|
+
latest.current = runOrEndpoint;
|
|
251
|
+
latestOptions.current = options;
|
|
252
|
+
});
|
|
253
|
+
useEffect(() => {
|
|
254
|
+
isAlive.current = true;
|
|
255
|
+
return () => {
|
|
256
|
+
isAlive.current = false;
|
|
257
|
+
};
|
|
258
|
+
}, []);
|
|
259
|
+
const mutate = useCallback(async (variables) => {
|
|
260
|
+
const call = ++latestCall.current;
|
|
261
|
+
const ownsState = () => isAlive.current && latestCall.current === call;
|
|
262
|
+
setState((current) => ({
|
|
263
|
+
...current,
|
|
264
|
+
status: "pending",
|
|
265
|
+
error: void 0
|
|
266
|
+
}));
|
|
267
|
+
try {
|
|
268
|
+
const current = latest.current;
|
|
269
|
+
const data = typeof current === "function" ? await current(variables) : await client.call(current, variables);
|
|
270
|
+
if (typeof current !== "function") invalidateTags(client, current.invalidates, variables);
|
|
271
|
+
invalidateTags(client, latestOptions.current?.invalidates, variables);
|
|
272
|
+
if (ownsState()) setState({
|
|
273
|
+
status: "success",
|
|
274
|
+
data,
|
|
275
|
+
error: void 0
|
|
276
|
+
});
|
|
277
|
+
return {
|
|
278
|
+
data,
|
|
279
|
+
error: null
|
|
280
|
+
};
|
|
281
|
+
} catch (cause) {
|
|
282
|
+
const error = toConduitError(cause);
|
|
283
|
+
if (ownsState()) setState({
|
|
284
|
+
status: "error",
|
|
285
|
+
data: void 0,
|
|
286
|
+
error
|
|
287
|
+
});
|
|
288
|
+
return {
|
|
289
|
+
data: null,
|
|
290
|
+
error
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
}, []);
|
|
294
|
+
const reset = useCallback(() => {
|
|
295
|
+
latestCall.current++;
|
|
296
|
+
setState(IDLE_MUTATION);
|
|
297
|
+
}, []);
|
|
298
|
+
return {
|
|
299
|
+
mutate,
|
|
300
|
+
status: state.status,
|
|
301
|
+
data: state.data,
|
|
302
|
+
error: state.error,
|
|
303
|
+
isPending: state.status === "pending",
|
|
304
|
+
reset
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function usePrefetch() {
|
|
308
|
+
return useCallback((path, options) => {
|
|
309
|
+
client.get(path, {
|
|
310
|
+
...options,
|
|
311
|
+
lane: options?.lane ?? "prefetch"
|
|
312
|
+
}).safe();
|
|
313
|
+
}, []);
|
|
314
|
+
}
|
|
315
|
+
function useSession() {
|
|
316
|
+
const handle = client.session;
|
|
317
|
+
if (handle === void 0) throw new ConduitError({
|
|
318
|
+
code: "INVALID_ARGUMENT",
|
|
319
|
+
message: "useSession needs the session plugin. Install it with .with(session({ adapter }))."
|
|
320
|
+
});
|
|
321
|
+
return useSyncExternalStore(handle.subscribe, handle.getState, handle.getState);
|
|
322
|
+
}
|
|
323
|
+
return {
|
|
324
|
+
useRequest,
|
|
325
|
+
useMutation,
|
|
326
|
+
usePrefetch,
|
|
327
|
+
useSession
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export { createHooks };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { et as ConduitLogger } from "./types-B9nuOKel.js";
|
|
2
|
+
interface HotContext {
|
|
3
|
+
dispose(callback: () => void): void;
|
|
4
|
+
}
|
|
5
|
+
interface SharedClientConfig {
|
|
6
|
+
/** The API version this bundle was built against. Compared, never reconciled. */
|
|
7
|
+
apiVersion?: number | string | undefined;
|
|
8
|
+
/** This bundle's own expectation of the shared client's shape. */
|
|
9
|
+
clientVersion?: number | undefined;
|
|
10
|
+
/** Routes disagreements somewhere other than the console. */
|
|
11
|
+
onMismatch?: ((report: SharedMismatch) => void) | undefined;
|
|
12
|
+
/** Where the registry's own diagnostics go. Defaults to `console`. */
|
|
13
|
+
logger?: ConduitLogger | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Tears the client down and deregisters it when this module is about to be
|
|
16
|
+
* replaced, so a reload during development gets a fresh client rather than
|
|
17
|
+
* a destroyed one wedged in the registry.
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* sharedClient('acme.api', factory, { hot: import.meta.hot })
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
hot?: HotContext | undefined;
|
|
24
|
+
}
|
|
25
|
+
type SharedMismatchKind = "conduit-version" | "api-version" | "client-version";
|
|
26
|
+
interface SharedMismatch {
|
|
27
|
+
readonly key: string;
|
|
28
|
+
readonly kind: SharedMismatchKind;
|
|
29
|
+
readonly existing: string | number | undefined;
|
|
30
|
+
readonly joining: string | number | undefined;
|
|
31
|
+
readonly message: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* One client per key for the whole page, built by whoever asks first. A later
|
|
35
|
+
* caller's factory never runs, so pass `apiVersion` and `clientVersion` to be
|
|
36
|
+
* told when bundles disagree rather than finding out through a wrong response.
|
|
37
|
+
*
|
|
38
|
+
* ```ts
|
|
39
|
+
* export const api = sharedClient(
|
|
40
|
+
* 'acme.api',
|
|
41
|
+
* () => createClient({ baseUrl: '/api' }).with(cache()),
|
|
42
|
+
* { apiVersion: 'v1', clientVersion: 1 }
|
|
43
|
+
* )
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
declare function sharedClient<C>(key: string, factory: () => C, config?: SharedClientConfig): C;
|
|
47
|
+
/** Reads a shared client without creating one. `undefined` if nobody has registered it, or it was destroyed. */
|
|
48
|
+
declare function getSharedClient<C>(key: string): C | undefined;
|
|
49
|
+
/** Deregisters one key. Pair it with `destroy()`, or the next bundle gets the dead client. */
|
|
50
|
+
declare function releaseSharedClient(key: string): boolean;
|
|
51
|
+
/** Empties the registry. For tests: in an app it strands whoever already holds a client. */
|
|
52
|
+
declare function clearSharedClients(): void;
|
|
53
|
+
export { clearSharedClients as a, sharedClient as c, SharedMismatchKind as i, SharedClientConfig as n, getSharedClient as o, SharedMismatch as r, releaseSharedClient as s, HotContext as t };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// src/primitives/logger.ts
|
|
2
|
+
/** Calls through to `console` fresh on every message, so a test spy still sees it. */
|
|
3
|
+
const consoleLogger = {
|
|
4
|
+
warn: (message) => {
|
|
5
|
+
console.warn(message);
|
|
6
|
+
},
|
|
7
|
+
error: (message) => {
|
|
8
|
+
console.error(message);
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The one way conduit reports a failure nobody is awaiting: a listener that
|
|
13
|
+
* threw, a refresh in the background, a renewal that failed. It always goes
|
|
14
|
+
* through the client's logger.
|
|
15
|
+
*/
|
|
16
|
+
function describeCause(cause) {
|
|
17
|
+
if (cause === void 0) return "";
|
|
18
|
+
if (cause instanceof Error) return cause.message;
|
|
19
|
+
return typeof cause === "string" ? cause : JSON.stringify(cause);
|
|
20
|
+
}
|
|
21
|
+
function reportError(logger, message, cause) {
|
|
22
|
+
const detail = describeCause(cause);
|
|
23
|
+
logger.error(`[conduit] ${message}${detail === "" ? "" : ` ${detail}`}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// package.json
|
|
27
|
+
var version = "1.0.0";
|
|
28
|
+
|
|
29
|
+
// src/primitives/version.ts
|
|
30
|
+
/** The conduit build this bundle carries, so a shared client can report a version skew. */
|
|
31
|
+
const CONDUIT_VERSION = version;
|
|
32
|
+
|
|
33
|
+
// src/client/shared.ts
|
|
34
|
+
const REGISTRY_KEY = Symbol.for("conduit.sharedClients.1");
|
|
35
|
+
function getRegistry() {
|
|
36
|
+
const scope = globalThis;
|
|
37
|
+
const existing = scope[REGISTRY_KEY];
|
|
38
|
+
if (existing !== void 0) return existing;
|
|
39
|
+
const created = /* @__PURE__ */ new Map();
|
|
40
|
+
scope[REGISTRY_KEY] = created;
|
|
41
|
+
return created;
|
|
42
|
+
}
|
|
43
|
+
/** Duck-typed, since two bundles shipping their own copy have separate class identities. */
|
|
44
|
+
function isSpent(client) {
|
|
45
|
+
const candidate = client;
|
|
46
|
+
return typeof candidate?.isDestroyed === "function" && candidate.isDestroyed();
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* One client per key for the whole page, built by whoever asks first. A later
|
|
50
|
+
* caller's factory never runs, so pass `apiVersion` and `clientVersion` to be
|
|
51
|
+
* told when bundles disagree rather than finding out through a wrong response.
|
|
52
|
+
*
|
|
53
|
+
* ```ts
|
|
54
|
+
* export const api = sharedClient(
|
|
55
|
+
* 'acme.api',
|
|
56
|
+
* () => createClient({ baseUrl: '/api' }).with(cache()),
|
|
57
|
+
* { apiVersion: 'v1', clientVersion: 1 }
|
|
58
|
+
* )
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
function sharedClient(key, factory, config = {}) {
|
|
62
|
+
const logger = config.logger ?? consoleLogger;
|
|
63
|
+
const entries = getRegistry();
|
|
64
|
+
const existing = entries.get(key);
|
|
65
|
+
if (existing !== void 0 && !isSpent(existing.client)) {
|
|
66
|
+
reconcile(key, existing, config);
|
|
67
|
+
return existing.client;
|
|
68
|
+
}
|
|
69
|
+
if (existing !== void 0) logger.warn(`[conduit] Shared client "${key}" was destroyed, so a new one was built. Call releaseSharedClient("${key}") when you destroy it.`);
|
|
70
|
+
const client = factory();
|
|
71
|
+
entries.set(key, {
|
|
72
|
+
client,
|
|
73
|
+
conduitVersion: CONDUIT_VERSION,
|
|
74
|
+
apiVersion: config.apiVersion,
|
|
75
|
+
clientVersion: config.clientVersion
|
|
76
|
+
});
|
|
77
|
+
config.hot?.dispose(() => {
|
|
78
|
+
if (getRegistry().get(key)?.client !== client) return;
|
|
79
|
+
client.destroy?.();
|
|
80
|
+
releaseSharedClient(key);
|
|
81
|
+
});
|
|
82
|
+
return client;
|
|
83
|
+
}
|
|
84
|
+
/** Reads a shared client without creating one. `undefined` if nobody has registered it, or it was destroyed. */
|
|
85
|
+
function getSharedClient(key) {
|
|
86
|
+
const existing = getRegistry().get(key);
|
|
87
|
+
return existing !== void 0 && !isSpent(existing.client) ? existing.client : void 0;
|
|
88
|
+
}
|
|
89
|
+
/** Deregisters one key. Pair it with `destroy()`, or the next bundle gets the dead client. */
|
|
90
|
+
function releaseSharedClient(key) {
|
|
91
|
+
return getRegistry().delete(key);
|
|
92
|
+
}
|
|
93
|
+
/** Empties the registry. For tests: in an app it strands whoever already holds a client. */
|
|
94
|
+
function clearSharedClients() {
|
|
95
|
+
getRegistry().clear();
|
|
96
|
+
}
|
|
97
|
+
function reconcile(key, existing, config) {
|
|
98
|
+
const logger = config.logger ?? consoleLogger;
|
|
99
|
+
const report = (kind, from, to, message) => {
|
|
100
|
+
const mismatch = {
|
|
101
|
+
key,
|
|
102
|
+
kind,
|
|
103
|
+
existing: from,
|
|
104
|
+
joining: to,
|
|
105
|
+
message
|
|
106
|
+
};
|
|
107
|
+
if (config.onMismatch !== void 0) {
|
|
108
|
+
config.onMismatch(mismatch);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
logger.warn(`[conduit] ${message}`);
|
|
112
|
+
};
|
|
113
|
+
if (existing.conduitVersion !== CONDUIT_VERSION) report("conduit-version", existing.conduitVersion, CONDUIT_VERSION, `Shared client "${key}" was created by conduit ${existing.conduitVersion}, and this bundle ships ${CONDUIT_VERSION}. Align the versions, or share conduit as a singleton.`);
|
|
114
|
+
if (config.apiVersion !== void 0 && existing.apiVersion !== config.apiVersion) report("api-version", existing.apiVersion, config.apiVersion, `Shared client "${key}" was built against API ${String(existing.apiVersion)}, and this bundle expects ${String(config.apiVersion)}. Deploy the apps together.`);
|
|
115
|
+
if (config.clientVersion !== void 0 && existing.clientVersion !== config.clientVersion) report("client-version", existing.clientVersion, config.clientVersion, `Shared client "${key}" is version ${String(existing.clientVersion)}, and this bundle expects ${config.clientVersion}. The existing client stays in use. Deploy the apps together.`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export { consoleLogger as a, sharedClient as i, getSharedClient as n, reportError as o, releaseSharedClient as r, clearSharedClients as t };
|