authoravatarclover caruso<git@paperclover.net>2026-11-11 10:38:09-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-11 11:13:55-08:00
logf5924c20c6666b5d38c24e19363361e3609e061d
tree980ae21013ce6dd0bd744497acb5d2b55506238f
parentfe2445675b26022550a41a0f80dc6f3cc32b1aef
signature Signed by SSH key SHA256:cOKiuRFOeSRxne6EWgHtdQQSlBxjOXm2hOCFnCdLQbQ

feat!: make Mutation the class define returns

`Mutation` was an interface left over from when two classes implemented it; only `BlockingMutation` remains. The class is now `Mutation` itself and every type position uses it, so `useMutate` and mutation buttons only accept mutations created by `define` (or `bindAsyncCallback`). The class keeps the interface's two type parameters. It no longer carries the client's `Auth` and `Config`: `define` erases the typed options once, where it pairs them with the client whose context runs them, which drops the casts `bindAsyncCallback` needed and the now-unused `MutationClientFromConfig`. The class's private options make `Args` invariant, so mutation buttons infer `Args` from `mutation` alone and `args={[]}` still fits a zero-argument mutation. Also drops the duplicate private client field and comments naming `defineBlocking`, `DebouncedMutation` and `runAndReturn`, and bumps the version to 4.0.0. Assisted-by: claude-opus-5.5

7 files changed, 199 insertions(+), 257 deletions(-)

jsr.json+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1{1{
2 "name": "@clo/react-mutation",2 "name": "@clo/react-mutation",
3 "version": "3.0.4",3 "version": "4.0.0",
4 "exports": {4 "exports": {
5 ".": "./src/mod.ts",5 ".": "./src/mod.ts",
6 "./tanstack-query": "./src/tanstack-query.ts",6 "./tanstack-query": "./src/tanstack-query.ts",
readme.changes.md+6
...@@ -1,5 +1,11 @@...@@ -1,5 +1,11 @@
1# notable changes in React Mutation1# notable changes in React Mutation
22
3## v4
4
5### breaking
6
7- rewrite the api types to be cleaner. likely does not break most users.
8
3## v3.0.49## v3.0.4
410
5### bugfixes11### bugfixes
src/client.ts+7-18
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1import { BlockingMutation, type MutationOptions } from "./mutation.ts";1import { Mutation, type MutationOptions } from "./mutation.ts";
2import type { Mutation, MutationAction, Serializable, SerializableValue } from "./types.ts";2import type { MutationAction, Serializable, SerializableValue } from "./types.ts";
33
4/**4/**
5 * Every element of a fixed argument tuple passes the {@link Serializable} check.5 * Every element of a fixed argument tuple passes the {@link Serializable} check.
...@@ -37,13 +37,6 @@ export interface MutationClientConfig {...@@ -37,13 +37,6 @@ export interface MutationClientConfig {
37 authScopes: string;37 authScopes: string;
38}38}
3939
40export type MutationClientFromConfig<Config extends MutationClientConfig> = MutationClient<
41 Config["context"],
42 Config["optimisticHelpers"],
43 Config["userContext"],
44 Config["authScopes"]
45>;
46
47const defaultDeepEquals = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);40const defaultDeepEquals = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
4841
49// Declared locally to avoid depending on node types.42// Declared locally to avoid depending on node types.
...@@ -62,8 +55,8 @@ export interface MutationClientOptions<...@@ -62,8 +55,8 @@ export interface MutationClientOptions<
62 reportError: (message: string, error: unknown) => void;55 reportError: (message: string, error: unknown) => void;
63 reportSuccess?: (message: string) => void;56 reportSuccess?: (message: string) => void;
64 /**57 /**
65 * Compare two values for deep equality. Used by DebouncedMutation to determine58 * Compare two values for deep equality. Used with a mutation's `snapshot` to
66 * if the optimistic state has changed from the initial snapshot.59 * determine if the optimistic state has changed from the initial snapshot.
67 * @default JSON.stringify based comparison60 * @default JSON.stringify based comparison
68 */61 */
69 deepEquals?: (a: unknown, b: unknown) => boolean;62 deepEquals?: (a: unknown, b: unknown) => boolean;
...@@ -171,14 +164,10 @@ export class MutationClient<...@@ -171,14 +164,10 @@ export class MutationClient<
171 }164 }
172 console.error(`Mutation id "${options.id}" registered twice; assuming hot reload and replacing it.`);165 console.error(`Mutation id "${options.id}" registered twice; assuming hot reload and replacing it.`);
173 }166 }
174 const mutation = new BlockingMutation<167 const mutation = new Mutation<Args, Result>(
175 Args,
176 Result,
177 Auth,
178 { context: Context; optimisticHelpers: OptimisticHelpers; userContext: UserContext; authScopes: AuthScopes }
179 >(
180 this,168 this,
181 options,169 // `Mutation` runs these with this client's context and helpers.
170 options as MutationOptions<Args, Result, boolean | string, MutationClientConfig>,
182 );171 );
183 this.#mutations.set(options.id, mutation as unknown as Mutation<SerializableValue[], unknown>);172 this.#mutations.set(options.id, mutation as unknown as Mutation<SerializableValue[], unknown>);
184 return mutation;173 return mutation;
src/mod.ts+2-9
...@@ -1,11 +1,5 @@...@@ -1,11 +1,5 @@
1export {1export { MutationClient, type MutationClientConfig, type MutationClientOptions, type Reactive } from "./client.ts";
2 MutationClient,2export type { Mutation, MutationOptions, OptimisticContext } from "./mutation.ts";
3 type MutationClientConfig,
4 type MutationClientFromConfig,
5 type MutationClientOptions,
6 type Reactive,
7} from "./client.ts";
8export type { MutationOptions, OptimisticContext } from "./mutation.ts";
9export {3export {
10 type AsyncCallbackOptions,4 type AsyncCallbackOptions,
11 bindAsyncCallback,5 bindAsyncCallback,
...@@ -21,7 +15,6 @@ export {...@@ -21,7 +15,6 @@ export {
21} from "./react.ts";15} from "./react.ts";
22export type {16export type {
23 Json,17 Json,
24 Mutation,
25 MutationAction,18 MutationAction,
26 MutationEvent,19 MutationEvent,
27 Serializable,20 Serializable,
src/mutation.ts+167-172
...@@ -1,13 +1,12 @@...@@ -1,13 +1,12 @@
1import { message as errMessage } from "@clo/lib/error.ts";1import { message as errMessage } from "@clo/lib/error.ts";
2import type { MutationClientFromConfig, Reactive } from "./client.ts";2import type { MutationClient, MutationClientConfig, Reactive } from "./client.ts";
3import type { MutationClientConfig } from "./client.ts";3import type { MutationEvent, RunOptions, SerializableValue } from "./types.ts";
4import type { Mutation, MutationEvent, RunOptions, SerializableValue } from "./types.ts";
54
6/**5/**
7 * Argument to `defineBlocking`.6 * Argument to `MutationClient.define`.
8 * @template Args - the parameters to the mutation7 * @template Args - the parameters to the mutation
9 * @template Result - the result of the API call8 * @template Result - the result of the API call
10 * @template Config - global values and helpers from `MutationContext`9 * @template Config - global values and helpers from `MutationClient`
11 */10 */
12export interface MutationOptions<11export interface MutationOptions<
13 Args extends unknown[],12 Args extends unknown[],
...@@ -119,11 +118,11 @@ export type OptimisticContext<...@@ -119,11 +118,11 @@ export type OptimisticContext<
119 onRefetch: (cb: () => Promise<void>) => void;118 onRefetch: (cb: () => Promise<void>) => void;
120};119};
121120
122interface PendingDebouncedState<Args extends unknown[], Result, Context> {121interface PendingDebouncedState<Args extends unknown[], Result> {
123 /** Arguments from the most recent call */122 /** Arguments from the most recent call */
124 args: Args;123 args: Args;
125 /** Context captured when the most recent call was allowed */124 /** Context captured when the most recent call was allowed */
126 context: Context;125 context: object;
127 /** Restores registered by the most recent call */126 /** Restores registered by the most recent call */
128 rollbacks: Array<() => void>;127 rollbacks: Array<() => void>;
129 /** All pending promises from all superseded calls */128 /** All pending promises from all superseded calls */
...@@ -159,20 +158,20 @@ function unwrapMutationError(caught: unknown) {...@@ -159,20 +158,20 @@ function unwrapMutationError(caught: unknown) {
159 return { error: caught, description: null };158 return { error: caught, description: null };
160}159}
161160
162interface Channel<Args extends unknown[], Result, Context> {161interface Channel<Args extends unknown[], Result> {
163 listeners: Set<(update: MutationEvent<Result>) => void>;162 listeners: Set<(update: MutationEvent<Result>) => void>;
164 status: "idle" | "waiting" | "mutating" | "refetching" | "skipped";163 status: "idle" | "waiting" | "mutating" | "refetching" | "skipped";
165 queue: Array<Item<Args, Result, Context>>;164 queue: Array<Item<Args, Result>>;
166 // Debounce state (only used if debounce option is set)165 // Debounce state (only used if debounce option is set)
167 debounceTimer: ReturnType<typeof setTimeout> | null;166 debounceTimer: ReturnType<typeof setTimeout> | null;
168 pendingDebounced: PendingDebouncedState<Args, Result, Context> | null;167 pendingDebounced: PendingDebouncedState<Args, Result> | null;
169 // Track when last debounced mutation executed (for debounceImmediate)168 // Track when last debounced mutation executed (for debounceImmediate)
170 lastDebouncedExecutionTime: number | null;169 lastDebouncedExecutionTime: number | null;
171}170}
172171
173interface Item<Args extends unknown[], Result, Context> {172interface Item<Args extends unknown[], Result> {
174 args: Args;173 args: Args;
175 context: Context;174 context: object;
176 rollbacks: Array<() => void>;175 rollbacks: Array<() => void>;
177 refetches: Array<() => Promise<void>>;176 refetches: Array<() => Promise<void>>;
178 onSuccess: Array<(result: Result) => void>;177 onSuccess: Array<(result: Result) => void>;
...@@ -180,59 +179,37 @@ interface Item<Args extends unknown[], Result, Context> {...@@ -180,59 +179,37 @@ interface Item<Args extends unknown[], Result, Context> {
180 reject: (error: unknown) => void;179 reject: (error: unknown) => void;
181}180}
182181
183export class BlockingMutation<182/** A mutation defined with `MutationClient.define`. */
184 Args extends unknown[],183export class Mutation<Args extends unknown[], Result> {
185 Result,184 readonly client: MutationClient<object, object, object, string>;
186 Auth extends boolean | string,185 #options: MutationOptions<Args, Result, boolean | string, MutationClientConfig>;
187 Config extends MutationClientConfig,186 #channels: Map<string, Channel<Args, Result>> = new Map();
188> implements Mutation<Args, Result> {
189 #options: MutationOptions<Args, Result, Auth, Config>;
190 #client: MutationClientFromConfig<Config>;
191 #channels: Map<
192 string,
193 Channel<Args, Result, Context<Config, Auth>>
194 > = new Map();
195 client: MutationClientFromConfig<Config>;
196187
197 constructor(188 constructor(
198 client: MutationClientFromConfig<Config>,189 client: MutationClient<object, object, object, string>,
199 options: MutationOptions<Args, Result, Auth, Config>,190 options: MutationOptions<Args, Result, boolean | string, MutationClientConfig>,
200 ) {191 ) {
201 this.#options = options;
202 this.#client = client;
203 this.client = client;192 this.client = client;
193 this.#options = options;
204 }194 }
205195
196 /** Unique identifier passed to `define`. */
206 get id(): string {197 get id(): string {
207 return this.#options.id;198 return this.#options.id;
208 }199 }
209200
210 #context(): Context<Config, Auth> {201 /**
211 return {202 * `true` when an `auth: true` mutation has no user available. Scoped
212 ...this.#client.context,203 * mutations are excluded; they disable instead of routing to the sign-in flow.
213 ...(this.#client.userContext?.get() ?? {}),204 */
214 } as Context<Config, Auth>;
215 }
216
217 #reportUnauthenticated(options: RunOptions<Result>, args: Args) {
218 const handler = options.onUnauthenticated ?? this.#client.handleUnauthenticated;
219 handler?.call(
220 this.#client,
221 // Reached only for `auth: true`, whose arguments the define-time guard
222 // constrains to be serializable.
223 { id: this.#options.id, description: this.describe(...args), args: args as SerializableValue[] },
224 this as unknown as Mutation<SerializableValue[], unknown>,
225 );
226 }
227
228 isUnauthenticated(): boolean {205 isUnauthenticated(): boolean {
229 return this.#options.auth === true && this.#client.userContext?.get() == null;206 return this.#options.auth === true && this.client.userContext?.get() == null;
230 }207 }
231208
232 isAllowed(): boolean {209 isAllowed(): boolean {
233 const { auth } = this.#options;210 const { auth } = this.#options;
234 if (auth !== undefined && auth !== false && this.#client.userContext?.get() == null) return false;211 if (auth !== undefined && auth !== false && this.client.userContext?.get() == null) return false;
235 if (typeof auth === "string" && !(this.#client.authScopes?.[auth]?.get() ?? false)) return false;212 if (typeof auth === "string" && !(this.client.authScopes?.[auth]?.get() ?? false)) return false;
236 return this.#options.isAllowed?.get() ?? true;213 return this.#options.isAllowed?.get() ?? true;
237 }214 }
238215
...@@ -240,33 +217,19 @@ export class BlockingMutation<...@@ -240,33 +217,19 @@ export class BlockingMutation<
240 const { auth } = this.#options;217 const { auth } = this.#options;
241 const unsubscribes = [218 const unsubscribes = [
242 this.#options.isAllowed?.sub(cb),219 this.#options.isAllowed?.sub(cb),
243 typeof auth === "string" ? this.#client.authScopes?.[auth]?.sub(cb) : undefined,220 typeof auth === "string" ? this.client.authScopes?.[auth]?.sub(cb) : undefined,
244 ];221 ];
245 return () => unsubscribes.forEach((unsubscribe) => unsubscribe?.());222 return () => unsubscribes.forEach((unsubscribe) => unsubscribe?.());
246 }223 }
247224
248 key(args: Args) {225 /** Returns the concurrency key used for a given set of arguments */
226 key(args: Args): string {
249 const k = this.#options.key?.({ ...this.#context(), args })227 const k = this.#options.key?.({ ...this.#context(), args })
250 ?? "shared";228 ?? "shared";
251 return JSON.stringify(k);229 return JSON.stringify(k);
252 }230 }
253231
254 #getOrPutChannel(key: string) {232 /** Subscribe to status changes using the key from `key()` */
255 let channel = this.#channels.get(key);
256 if (!channel) {
257 channel = {
258 listeners: new Set(),
259 status: "idle",
260 queue: [],
261 debounceTimer: null,
262 pendingDebounced: null,
263 lastDebouncedExecutionTime: null,
264 };
265 this.#channels.set(key, channel);
266 }
267 return channel;
268 }
269
270 subscribe(233 subscribe(
271 key: string,234 key: string,
272 cb: (update: MutationEvent<Result>) => void,235 cb: (update: MutationEvent<Result>) => void,
...@@ -276,41 +239,6 @@ export class BlockingMutation<...@@ -276,41 +239,6 @@ export class BlockingMutation<
276 return () => channel?.listeners.delete(cb);239 return () => channel?.listeners.delete(cb);
277 }240 }
278241
279 #notify(
280 channel: Channel<Args, Result, Context<Config, Auth>>,
281 status: MutationEvent<Result>["status"],
282 result: Result | null = null,
283 error: unknown = null,
284 ) {
285 const event: MutationEvent<Result> = { status, result, error, debounced: this.#options.debounceMs !== undefined };
286 channel.listeners.forEach((cb) => cb(event));
287 }
288
289 #setIdle(
290 key: string,
291 channel: Channel<Args, Result, Context<Config, Auth>>,
292 ) {
293 // Check if there are pending debounced calls waiting
294 if (channel.pendingDebounced !== null) {
295 // Stay in waiting state
296 channel.status = "waiting";
297 this.#notify(channel, "waiting", null, null);
298 } else {
299 // Normal idle transition
300 channel.status = "idle";
301 this.#notify(channel, "idle", null, null);
302 // Clean up the channel if there are no listeners
303 if (channel.listeners.size === 0) {
304 // Clear any pending timers before deleting the channel
305 if (channel.debounceTimer !== null) {
306 clearTimeout(channel.debounceTimer);
307 channel.debounceTimer = null;
308 }
309 this.#channels.delete(key);
310 }
311 }
312 }
313
314 describe(...args: Args): string {242 describe(...args: Args): string {
315 const { describe } = this.#options;243 const { describe } = this.#options;
316 return typeof describe === "function"244 return typeof describe === "function"
...@@ -327,58 +255,13 @@ export class BlockingMutation<...@@ -327,58 +255,13 @@ export class BlockingMutation<
327 }255 }
328256
329 /** Calling the mutation in a global scope. Errors are turned into UI toasts. */257 /** Calling the mutation in a global scope. Errors are turned into UI toasts. */
330 run(...args: Args) {258 run(...args: Args): void {
331 this.runWithOptions(...args, {});259 this.runWithOptions(...args, {});
332 }260 }
333261
334 /**
335 * Using this in any situation is likely incorrect. Use {@linkcode runWithOptions}
336 * to handle success and error.
337 *
338 * By using this, you must handle the success and error conditions of the
339 * promise, or else the user will never see the result on screen. If the
340 * mutation has snapshots, be aware that cancelled mutations are implemented
341 * with promises that never resolve.
342 */
343 runAsHeadlessPromise(...array: [...Args, RunOptions<Result>]): Promise<Result> {
344 if (!this.#client.enabled) {
345 throw new Error(
346 "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?",
347 );
348 }
349
350 const args = array.slice() as Args;
351 const options = args.pop() as RunOptions<Result>;
352 const { onSuccessUi: onSuccess, onSuccessData, onError, onSettled, onRestore } = options;
353
354 if (!this.isAllowed()) {
355 if (this.isUnauthenticated()) {
356 this.#reportUnauthenticated(options, args);
357 return Promise.reject(new Error("Mutation requires authentication."));
358 }
359 return Promise.reject(new Error("Mutation is not allowed."));
360 }
361
362 const promise = this.#runWithOptions(args, onRestore, true);
363 return promise.then((result) => {
364 // Call user handlers
365 onSuccess?.(result);
366 onSuccessData?.(result);
367 onSettled?.({ status: "success", result });
368 return result;
369 }).catch((caught: unknown) => {
370 const { error } = unwrapMutationError(caught);
371
372 onError?.(error);
373 onSettled?.({ status: "error", error });
374
375 throw error;
376 });
377 }
378
379 /** Calls the mutation with custom handlers that can suppress global handlers. */262 /** Calls the mutation with custom handlers that can suppress global handlers. */
380 runWithOptions(...array: [...Args, RunOptions<Result>]): void {263 runWithOptions(...array: [...args: Args, options: RunOptions<Result>]): void {
381 if (!this.#client.enabled) {264 if (!this.client.enabled) {
382 throw new Error(265 throw new Error(
383 "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?",266 "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?",
384 );267 );
...@@ -396,7 +279,7 @@ export class BlockingMutation<...@@ -396,7 +279,7 @@ export class BlockingMutation<
396 onError?.(error);279 onError?.(error);
397 onSettled?.({ status: "error", error });280 onSettled?.({ status: "error", error });
398 if (!onError) {281 if (!onError) {
399 this.#client.reportError(formatFriendlyError(this.describe(...args), error), error);282 this.client.reportError(formatFriendlyError(this.describe(...args), error), error);
400 }283 }
401 return;284 return;
402 }285 }
...@@ -415,8 +298,8 @@ export class BlockingMutation<...@@ -415,8 +298,8 @@ export class BlockingMutation<
415 // Call global handler unless suppressed298 // Call global handler unless suppressed
416 if (!suppressGlobalSuccess) {299 if (!suppressGlobalSuccess) {
417 const message = this.describeResult(args, result);300 const message = this.describeResult(args, result);
418 if (message && this.#client.reportSuccess) {301 if (message && this.client.reportSuccess) {
419 this.#client.reportSuccess(message);302 this.client.reportSuccess(message);
420 }303 }
421 }304 }
422 }).catch((caught: unknown) => {305 }).catch((caught: unknown) => {
...@@ -427,8 +310,53 @@ export class BlockingMutation<...@@ -427,8 +310,53 @@ export class BlockingMutation<
427310
428 // Call global handler unless suppressed311 // Call global handler unless suppressed
429 if (!suppressGlobalError) {312 if (!suppressGlobalError) {
430 this.#client.reportError(formatFriendlyError(description, error), error);313 this.client.reportError(formatFriendlyError(description, error), error);
314 }
315 });
316 }
317
318 /**
319 * Using this in any situation is likely incorrect. Use {@linkcode runWithOptions}
320 * to handle success and error.
321 *
322 * By using this, you must handle the success and error conditions of the
323 * promise, or else the user will never see the result on screen. If the
324 * mutation has snapshots, be aware that cancelled mutations are implemented
325 * with promises that never resolve.
326 */
327 runAsHeadlessPromise(...array: [...args: Args, options: RunOptions<Result>]): Promise<Result> {
328 if (!this.client.enabled) {
329 throw new Error(
330 "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?",
331 );
332 }
333
334 const args = array.slice() as Args;
335 const options = args.pop() as RunOptions<Result>;
336 const { onSuccessUi: onSuccess, onSuccessData, onError, onSettled, onRestore } = options;
337
338 if (!this.isAllowed()) {
339 if (this.isUnauthenticated()) {
340 this.#reportUnauthenticated(options, args);
341 return Promise.reject(new Error("Mutation requires authentication."));
431 }342 }
343 return Promise.reject(new Error("Mutation is not allowed."));
344 }
345
346 const promise = this.#runWithOptions(args, onRestore, true);
347 return promise.then((result) => {
348 // Call user handlers
349 onSuccess?.(result);
350 onSuccessData?.(result);
351 onSettled?.({ status: "success", result });
352 return result;
353 }).catch((caught: unknown) => {
354 const { error } = unwrapMutationError(caught);
355
356 onError?.(error);
357 onSettled?.({ status: "error", error });
358
359 throw error;
432 });360 });
433 }361 }
434362
...@@ -437,7 +365,7 @@ export class BlockingMutation<...@@ -437,7 +365,7 @@ export class BlockingMutation<
437 userOnRestore: RunOptions<Result>["onRestore"],365 userOnRestore: RunOptions<Result>["onRestore"],
438 suppressGlobalHandlers: boolean,366 suppressGlobalHandlers: boolean,
439 ): Promise<Result> {367 ): Promise<Result> {
440 if (!this.#client.enabled) {368 if (!this.client.enabled) {
441 throw new Error(369 throw new Error(
442 "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?",370 "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?",
443 );371 );
...@@ -489,7 +417,7 @@ export class BlockingMutation<...@@ -489,7 +417,7 @@ export class BlockingMutation<
489 }417 }
490418
491 // Per call, so restores, refetches and refetch dedupe belong to this call419 // Per call, so restores, refetches and refetch dedupe belong to this call
492 const helpers = this.#client.getOptimisticHelpers({420 const helpers = this.client.getOptimisticHelpers({
493 onRestore: (cb) => {421 onRestore: (cb) => {
494 rollbacks.push(cb);422 rollbacks.push(cb);
495 },423 },
...@@ -535,7 +463,7 @@ export class BlockingMutation<...@@ -535,7 +463,7 @@ export class BlockingMutation<
535 context,463 context,
536 { ...context, args },464 { ...context, args },
537 );465 );
538 const isNoOp = this.#client.deepEquals(beforeSnapshot, afterSnapshot);466 const isNoOp = this.client.deepEquals(beforeSnapshot, afterSnapshot);
539467
540 if (isNoOp) {468 if (isNoOp) {
541 let next;469 let next;
...@@ -566,9 +494,44 @@ export class BlockingMutation<...@@ -566,9 +494,44 @@ export class BlockingMutation<
566 return promise;494 return promise;
567 }495 }
568496
497 #notify(
498 channel: Channel<Args, Result>,
499 status: MutationEvent<Result>["status"],
500 result: Result | null = null,
501 error: unknown = null,
502 ) {
503 const event: MutationEvent<Result> = { status, result, error, debounced: this.#options.debounceMs !== undefined };
504 channel.listeners.forEach((cb) => cb(event));
505 }
506
507 #setIdle(
508 key: string,
509 channel: Channel<Args, Result>,
510 ) {
511 // Check if there are pending debounced calls waiting
512 if (channel.pendingDebounced !== null) {
513 // Stay in waiting state
514 channel.status = "waiting";
515 this.#notify(channel, "waiting", null, null);
516 } else {
517 // Normal idle transition
518 channel.status = "idle";
519 this.#notify(channel, "idle", null, null);
520 // Clean up the channel if there are no listeners
521 if (channel.listeners.size === 0) {
522 // Clear any pending timers before deleting the channel
523 if (channel.debounceTimer !== null) {
524 clearTimeout(channel.debounceTimer);
525 channel.debounceTimer = null;
526 }
527 this.#channels.delete(key);
528 }
529 }
530 }
531
569 #executeNext(532 #executeNext(
570 key: string,533 key: string,
571 channel: Channel<Args, Result, Context<Config, Auth>>,534 channel: Channel<Args, Result>,
572 ) {535 ) {
573 const item = channel.queue.shift();536 const item = channel.queue.shift();
574 if (!item) {537 if (!item) {
...@@ -594,7 +557,7 @@ export class BlockingMutation<...@@ -594,7 +557,7 @@ export class BlockingMutation<
594 results.forEach((result) => {557 results.forEach((result) => {
595 if (result.status === "rejected") {558 if (result.status === "rejected") {
596 const message = `Failed to refetch data: ${errMessage(result.reason)}`;559 const message = `Failed to refetch data: ${errMessage(result.reason)}`;
597 this.#client.reportError(message, result.reason);560 this.client.reportError(message, result.reason);
598 }561 }
599 });562 });
600 },563 },
...@@ -637,7 +600,7 @@ export class BlockingMutation<...@@ -637,7 +600,7 @@ export class BlockingMutation<
637 results.forEach((result) => {600 results.forEach((result) => {
638 if (result.status === "rejected") {601 if (result.status === "rejected") {
639 const message = `Failed to refetch data: ${errMessage(result.reason)}`;602 const message = `Failed to refetch data: ${errMessage(result.reason)}`;
640 this.#client.reportError(message, result.reason);603 this.client.reportError(message, result.reason);
641 }604 }
642 });605 });
643 }).finally(() => {606 }).finally(() => {
...@@ -651,8 +614,8 @@ export class BlockingMutation<...@@ -651,8 +614,8 @@ export class BlockingMutation<
651 #runDebouncedAndReturn(614 #runDebouncedAndReturn(
652 args: Args,615 args: Args,
653 key: string,616 key: string,
654 channel: Channel<Args, Result, Context<Config, Auth>>,617 channel: Channel<Args, Result>,
655 context: Context<Config, Auth>,618 context: object,
656 userOnRestore: (() => void) | undefined,619 userOnRestore: (() => void) | undefined,
657 shouldExecuteImmediate: boolean,620 shouldExecuteImmediate: boolean,
658 shouldCallGlobalHandler: boolean,621 shouldCallGlobalHandler: boolean,
...@@ -672,7 +635,6 @@ export class BlockingMutation<...@@ -672,7 +635,6 @@ export class BlockingMutation<
672 this.#rollbackPendingDebounced(channel);635 this.#rollbackPendingDebounced(channel);
673 }636 }
674637
675 // Apply optimistic update (same logic as current runAndReturn)
676 const onSuccess: Array<(result: Result) => void> = [];638 const onSuccess: Array<(result: Result) => void> = [];
677 let expired = false;639 let expired = false;
678 const rollbacks: Array<() => void> = [];640 const rollbacks: Array<() => void> = [];
...@@ -692,7 +654,7 @@ export class BlockingMutation<...@@ -692,7 +654,7 @@ export class BlockingMutation<
692 }654 }
693655
694 // Per call, so restores, refetches and refetch dedupe belong to this call656 // Per call, so restores, refetches and refetch dedupe belong to this call
695 const helpers = this.#client.getOptimisticHelpers({657 const helpers = this.client.getOptimisticHelpers({
696 onRestore: (cb) => {658 onRestore: (cb) => {
697 rollbacks.push(cb);659 rollbacks.push(cb);
698 },660 },
...@@ -745,7 +707,7 @@ export class BlockingMutation<...@@ -745,7 +707,7 @@ export class BlockingMutation<
745707
746 if (708 if (
747 snapshotToCompare !== undefined709 snapshotToCompare !== undefined
748 && this.#client.deepEquals(snapshotToCompare, currentSnapshot)710 && this.client.deepEquals(snapshotToCompare, currentSnapshot)
749 ) {711 ) {
750 // No-op detected - rollback optimistic update712 // No-op detected - rollback optimistic update
751 let next;713 let next;
...@@ -818,7 +780,7 @@ export class BlockingMutation<...@@ -818,7 +780,7 @@ export class BlockingMutation<
818 }780 }
819781
820 #rollbackPendingDebounced(782 #rollbackPendingDebounced(
821 channel: Channel<Args, Result, Context<Config, Auth>>,783 channel: Channel<Args, Result>,
822 ) {784 ) {
823 if (!channel.pendingDebounced) return;785 if (!channel.pendingDebounced) return;
824786
...@@ -834,7 +796,7 @@ export class BlockingMutation<...@@ -834,7 +796,7 @@ export class BlockingMutation<
834796
835 #enqueueDebouncedCall(797 #enqueueDebouncedCall(
836 key: string,798 key: string,
837 channel: Channel<Args, Result, Context<Config, Auth>>,799 channel: Channel<Args, Result>,
838 ) {800 ) {
839 // Clear timer801 // Clear timer
840 channel.debounceTimer = null;802 channel.debounceTimer = null;
...@@ -870,8 +832,8 @@ export class BlockingMutation<...@@ -870,8 +832,8 @@ export class BlockingMutation<
870 // Call global handler if needed (based on whether component is watching success)832 // Call global handler if needed (based on whether component is watching success)
871 if (shouldCallGlobalHandler) {833 if (shouldCallGlobalHandler) {
872 const message = this.describeResult(args, result);834 const message = this.describeResult(args, result);
873 if (message && this.#client.reportSuccess) {835 if (message && this.client.reportSuccess) {
874 this.#client.reportSuccess(message);836 this.client.reportSuccess(message);
875 }837 }
876 }838 }
877 },839 },
...@@ -883,7 +845,7 @@ export class BlockingMutation<...@@ -883,7 +845,7 @@ export class BlockingMutation<
883845
884 // Call global handler if needed (based on whether component is watching errors)846 // Call global handler if needed (based on whether component is watching errors)
885 if (shouldCallGlobalHandler) {847 if (shouldCallGlobalHandler) {
886 this.#client.reportError(848 this.client.reportError(
887 formatFriendlyError(description, error),849 formatFriendlyError(description, error),
888 error,850 error,
889 );851 );
...@@ -891,7 +853,6 @@ export class BlockingMutation<...@@ -891,7 +853,6 @@ export class BlockingMutation<
891 },853 },
892 );854 );
893855
894 // Add to queue (same structure as regular blocking mutation)
895 channel.queue.push({856 channel.queue.push({
896 args,857 args,
897 context,858 context,
...@@ -908,6 +869,40 @@ export class BlockingMutation<...@@ -908,6 +869,40 @@ export class BlockingMutation<
908 }869 }
909 // Otherwise, it will execute when the current item finishes870 // Otherwise, it will execute when the current item finishes
910 }871 }
872
873 #context(): object {
874 return {
875 ...this.client.context,
876 ...this.client.userContext?.get(),
877 };
878 }
879
880 #reportUnauthenticated(options: RunOptions<Result>, args: Args) {
881 const handler = options.onUnauthenticated ?? this.client.handleUnauthenticated;
882 handler?.call(
883 this.client,
884 // Reached only for `auth: true`, whose arguments the define-time guard
885 // constrains to be serializable.
886 { id: this.#options.id, description: this.describe(...args), args: args as SerializableValue[] },
887 this as unknown as Mutation<SerializableValue[], unknown>,
888 );
889 }
890
891 #getOrPutChannel(key: string) {
892 let channel = this.#channels.get(key);
893 if (!channel) {
894 channel = {
895 listeners: new Set(),
896 status: "idle",
897 queue: [],
898 debounceTimer: null,
899 pendingDebounced: null,
900 lastDebouncedExecutionTime: null,
901 };
902 this.#channels.set(key, channel);
903 }
904 return channel;
905 }
911}906}
912907
913export function formatFriendlyError(908export function formatFriendlyError(
src/react.ts+15-19
...@@ -13,9 +13,9 @@ import {...@@ -13,9 +13,9 @@ import {
13 useSyncExternalStore,13 useSyncExternalStore,
14} from "react";14} from "react";
15import { jsx } from "react/jsx-runtime";15import { jsx } from "react/jsx-runtime";
16import type { MutationClient, MutationClientConfig, MutationClientFromConfig } from "./client.ts";16import type { MutationClient } from "./client.ts";
17import { BlockingMutation, formatFriendlyError } from "./mutation.ts";17import { formatFriendlyError, Mutation } from "./mutation.ts";
18import type { Mutation, RunOptions, SerializableValue } from "./types.ts";18import type { RunOptions } from "./types.ts";
1919
20/**20/**
21 * Subscribe to a mutation's status, as well as accessing a local `run` method.21 * Subscribe to a mutation's status, as well as accessing a local `run` method.
...@@ -77,22 +77,18 @@ export function bindAsyncCallback(...@@ -77,22 +77,18 @@ export function bindAsyncCallback(
77 const live = useRef({ callback, options });77 const live = useRef({ callback, options });
78 live.current = { callback, options };78 live.current = { callback, options };
79 // A stable, unregistered mutation with no optimistic state; every field79 // A stable, unregistered mutation with no optimistic state; every field
80 // reads the ref so it tracks the latest callback and options. Args are80 // reads the ref so it tracks the latest callback and options. Empty
81 // never serialized here (no id, no auth replay), so the serializable bound81 // describe/describeResult fall through to the generic error message and no
82 // is cast away locally. Empty describe/describeResult fall through to the82 // success toast, respectively.
83 // generic error message and no success toast, respectively.
84 const [mutation] = useState(() =>83 const [mutation] = useState(() =>
85 new BlockingMutation<SerializableValue[], Result, false, MutationClientConfig>(84 new Mutation<Args, Result>(client, {
86 client as unknown as MutationClientFromConfig<MutationClientConfig>,85 id: "",
87 {86 mutate: (...args) => live.current.callback(...args),
88 id: "",87 optimistic: () => {},
89 mutate: (...args) => live.current.callback(...(args as unknown as Args)),88 describe: () => live.current.options?.describe ?? "",
90 optimistic: () => {},89 describeResult: () => live.current.options?.describeResult ?? "",
91 describe: () => live.current.options?.describe ?? "",90 refetchOnSuccess: false,
92 describeResult: () => live.current.options?.describeResult ?? "",91 })
93 refetchOnSuccess: false,
94 },
95 ) as unknown as Mutation<Args, Result>
96 );92 );
97 return useMutate(mutation);93 return useMutate(mutation);
98 };94 };
...@@ -494,7 +490,7 @@ export interface MutationButtonProps<Args extends unknown[], Result> {...@@ -494,7 +490,7 @@ export interface MutationButtonProps<Args extends unknown[], Result> {
494 | Mutation<Args, Result>490 | Mutation<Args, Result>
495 | UseMutateResult<Args, Result>;491 | UseMutateResult<Args, Result>;
496 /** Preventing default will interrupt the mutation */492 /** Preventing default will interrupt the mutation */
497 args: Args | null | ((e: MouseEvent) => Args | null);493 args: NoInfer<Args> | null | ((e: MouseEvent) => NoInfer<Args> | null);
498 /** Preventing default will interrupt the mutation */494 /** Preventing default will interrupt the mutation */
499 onClick?: (e: MouseEvent) => void;495 onClick?: (e: MouseEvent) => void;
500 disabled?: boolean;496 disabled?: boolean;
src/types.ts+1-38
...@@ -1,4 +1,4 @@...@@ -1,4 +1,4 @@
1import type { MutationClient } from "./client.ts";1import type { Mutation } from "./mutation.ts";
22
3/**3/**
4 * Plain JSON value. The default serializable leaf set, still exported for4 * Plain JSON value. The default serializable leaf set, still exported for
...@@ -61,43 +61,6 @@ export interface MutationAction {...@@ -61,43 +61,6 @@ export interface MutationAction {
61 args: SerializableValue[];61 args: SerializableValue[];
62}62}
6363
64export interface Mutation<Args extends unknown[], Result> {
65 /** Unique identifier passed to `define`. */
66 readonly id: string;
67 /** Calling the mutation. Errors are turned into UI toasts. */
68 run(...args: Args): void;
69 /** Calls the mutation with custom handlers that can suppress global handlers. */
70 runWithOptions(...args: [...args: Args, options: RunOptions<Result>]): void;
71 /**
72 * Using this in any situation is likely incorrect, even internally.
73 * Use {@linkcode runWithOptions} to handle success and error.
74 *
75 * By using this, you must handle the success and error conditions of the
76 * promise, or else the user will never see the result on screen. If the
77 * mutation has snapshots, be aware that cancelled mutations are implemented
78 * with promises that never resolve.
79 */
80 runAsHeadlessPromise(...array: [...Args, RunOptions<Result>]): Promise<Result>;
81
82 /** Returns the concurrency key used for a given set of arguments */
83 key(args: Args): string;
84 /** Subscribe to status changes using the key from `key()` */
85 subscribe(
86 key: string,
87 cb: (update: MutationEvent<Result>) => void,
88 ): () => void;
89 describe(...args: Args): string;
90 describeResult: ((args: Args, result: Result) => string | undefined) | null;
91 /**
92 * `true` when an `auth: true` mutation has no user available. Scoped
93 * mutations are excluded; they disable instead of routing to the sign-in flow.
94 */
95 isUnauthenticated(): boolean;
96 isAllowed(): boolean;
97 subscribeAllowed(cb: () => void): () => void;
98 client: MutationClient<object, object, object>;
99}
100
101export interface RunOptions<Result> {64export interface RunOptions<Result> {
102 /** Called to show the success UI. Passing this suppresses the global success handler. */65 /** Called to show the success UI. Passing this suppresses the global success handler. */
103 onSuccessUi?: (result: Result) => void;66 onSuccessUi?: (result: Result) => void;