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 @@
11{
22 "name": "@clo/react-mutation",
3 "version": "3.0.4",
3 "version": "4.0.0",
44 "exports": {
55 ".": "./src/mod.ts",
66 "./tanstack-query": "./src/tanstack-query.ts",
readme.changes.md+6
......@@ -1,5 +1,11 @@
11# 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
39## v3.0.4
410
511### bugfixes
src/client.ts+7-18
......@@ -1,5 +1,5 @@
1import { BlockingMutation, type MutationOptions } from "./mutation.ts";
2import type { Mutation, MutationAction, Serializable, SerializableValue } from "./types.ts";
1import { Mutation, type MutationOptions } from "./mutation.ts";
2import type { MutationAction, Serializable, SerializableValue } from "./types.ts";
33
44/**
55 * Every element of a fixed argument tuple passes the {@link Serializable} check.
......@@ -37,13 +37,6 @@ export interface MutationClientConfig {
3737 authScopes: string;
3838}
3939
40export type MutationClientFromConfig<Config extends MutationClientConfig> = MutationClient<
41 Config["context"],
42 Config["optimisticHelpers"],
43 Config["userContext"],
44 Config["authScopes"]
45>;
46
4740const defaultDeepEquals = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
4841
4942// Declared locally to avoid depending on node types.
......@@ -62,8 +55,8 @@ export interface MutationClientOptions<
6255 reportError: (message: string, error: unknown) => void;
6356 reportSuccess?: (message: string) => void;
6457 /**
65 * Compare two values for deep equality. Used by DebouncedMutation to determine
66 * if the optimistic state has changed from the initial snapshot.
58 * Compare two values for deep equality. Used with a mutation's `snapshot` to
59 * determine if the optimistic state has changed from the initial snapshot.
6760 * @default JSON.stringify based comparison
6861 */
6962 deepEquals?: (a: unknown, b: unknown) => boolean;
......@@ -171,14 +164,10 @@ export class MutationClient<
171164 }
172165 console.error(`Mutation id "${options.id}" registered twice; assuming hot reload and replacing it.`);
173166 }
174 const mutation = new BlockingMutation<
175 Args,
176 Result,
177 Auth,
178 { context: Context; optimisticHelpers: OptimisticHelpers; userContext: UserContext; authScopes: AuthScopes }
179 >(
167 const mutation = new Mutation<Args, Result>(
180168 this,
181 options,
169 // `Mutation` runs these with this client's context and helpers.
170 options as MutationOptions<Args, Result, boolean | string, MutationClientConfig>,
182171 );
183172 this.#mutations.set(options.id, mutation as unknown as Mutation<SerializableValue[], unknown>);
184173 return mutation;
src/mod.ts+2-9
......@@ -1,11 +1,5 @@
1export {
2 MutationClient,
3 type MutationClientConfig,
4 type MutationClientFromConfig,
5 type MutationClientOptions,
6 type Reactive,
7} from "./client.ts";
8export type { MutationOptions, OptimisticContext } from "./mutation.ts";
1export { MutationClient, type MutationClientConfig, type MutationClientOptions, type Reactive } from "./client.ts";
2export type { Mutation, MutationOptions, OptimisticContext } from "./mutation.ts";
93export {
104 type AsyncCallbackOptions,
115 bindAsyncCallback,
......@@ -21,7 +15,6 @@ export {
2115} from "./react.ts";
2216export type {
2317 Json,
24 Mutation,
2518 MutationAction,
2619 MutationEvent,
2720 Serializable,
src/mutation.ts+167-172
......@@ -1,13 +1,12 @@
11import { message as errMessage } from "@clo/lib/error.ts";
2import type { MutationClientFromConfig, Reactive } from "./client.ts";
3import type { MutationClientConfig } from "./client.ts";
4import type { Mutation, MutationEvent, RunOptions, SerializableValue } from "./types.ts";
2import type { MutationClient, MutationClientConfig, Reactive } from "./client.ts";
3import type { MutationEvent, RunOptions, SerializableValue } from "./types.ts";
54
65/**
7 * Argument to `defineBlocking`.
6 * Argument to `MutationClient.define`.
87 * @template Args - the parameters to the mutation
98 * @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`
1110 */
1211export interface MutationOptions<
1312 Args extends unknown[],
......@@ -119,11 +118,11 @@ export type OptimisticContext<
119118 onRefetch: (cb: () => Promise<void>) => void;
120119};
121120
122interface PendingDebouncedState<Args extends unknown[], Result, Context> {
121interface PendingDebouncedState<Args extends unknown[], Result> {
123122 /** Arguments from the most recent call */
124123 args: Args;
125124 /** Context captured when the most recent call was allowed */
126 context: Context;
125 context: object;
127126 /** Restores registered by the most recent call */
128127 rollbacks: Array<() => void>;
129128 /** All pending promises from all superseded calls */
......@@ -159,20 +158,20 @@ function unwrapMutationError(caught: unknown) {
159158 return { error: caught, description: null };
160159}
161160
162interface Channel<Args extends unknown[], Result, Context> {
161interface Channel<Args extends unknown[], Result> {
163162 listeners: Set<(update: MutationEvent<Result>) => void>;
164163 status: "idle" | "waiting" | "mutating" | "refetching" | "skipped";
165 queue: Array<Item<Args, Result, Context>>;
164 queue: Array<Item<Args, Result>>;
166165 // Debounce state (only used if debounce option is set)
167166 debounceTimer: ReturnType<typeof setTimeout> | null;
168 pendingDebounced: PendingDebouncedState<Args, Result, Context> | null;
167 pendingDebounced: PendingDebouncedState<Args, Result> | null;
169168 // Track when last debounced mutation executed (for debounceImmediate)
170169 lastDebouncedExecutionTime: number | null;
171170}
172171
173interface Item<Args extends unknown[], Result, Context> {
172interface Item<Args extends unknown[], Result> {
174173 args: Args;
175 context: Context;
174 context: object;
176175 rollbacks: Array<() => void>;
177176 refetches: Array<() => Promise<void>>;
178177 onSuccess: Array<(result: Result) => void>;
......@@ -180,59 +179,37 @@ interface Item<Args extends unknown[], Result, Context> {
180179 reject: (error: unknown) => void;
181180}
182181
183export class BlockingMutation<
184 Args extends unknown[],
185 Result,
186 Auth extends boolean | string,
187 Config extends MutationClientConfig,
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>;
182/** A mutation defined with `MutationClient.define`. */
183export class Mutation<Args extends unknown[], Result> {
184 readonly client: MutationClient<object, object, object, string>;
185 #options: MutationOptions<Args, Result, boolean | string, MutationClientConfig>;
186 #channels: Map<string, Channel<Args, Result>> = new Map();
196187
197188 constructor(
198 client: MutationClientFromConfig<Config>,
199 options: MutationOptions<Args, Result, Auth, Config>,
189 client: MutationClient<object, object, object, string>,
190 options: MutationOptions<Args, Result, boolean | string, MutationClientConfig>,
200191 ) {
201 this.#options = options;
202 this.#client = client;
203192 this.client = client;
193 this.#options = options;
204194 }
205195
196 /** Unique identifier passed to `define`. */
206197 get id(): string {
207198 return this.#options.id;
208199 }
209200
210 #context(): Context<Config, Auth> {
211 return {
212 ...this.#client.context,
213 ...(this.#client.userContext?.get() ?? {}),
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
201 /**
202 * `true` when an `auth: true` mutation has no user available. Scoped
203 * mutations are excluded; they disable instead of routing to the sign-in flow.
204 */
228205 isUnauthenticated(): boolean {
229 return this.#options.auth === true && this.#client.userContext?.get() == null;
206 return this.#options.auth === true && this.client.userContext?.get() == null;
230207 }
231208
232209 isAllowed(): boolean {
233210 const { auth } = this.#options;
234 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;
211 if (auth !== undefined && auth !== false && this.client.userContext?.get() == null) return false;
212 if (typeof auth === "string" && !(this.client.authScopes?.[auth]?.get() ?? false)) return false;
236213 return this.#options.isAllowed?.get() ?? true;
237214 }
238215
......@@ -240,33 +217,19 @@ export class BlockingMutation<
240217 const { auth } = this.#options;
241218 const unsubscribes = [
242219 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,
244221 ];
245222 return () => unsubscribes.forEach((unsubscribe) => unsubscribe?.());
246223 }
247224
248 key(args: Args) {
225 /** Returns the concurrency key used for a given set of arguments */
226 key(args: Args): string {
249227 const k = this.#options.key?.({ ...this.#context(), args })
250228 ?? "shared";
251229 return JSON.stringify(k);
252230 }
253231
254 #getOrPutChannel(key: string) {
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
232 /** Subscribe to status changes using the key from `key()` */
270233 subscribe(
271234 key: string,
272235 cb: (update: MutationEvent<Result>) => void,
......@@ -276,41 +239,6 @@ export class BlockingMutation<
276239 return () => channel?.listeners.delete(cb);
277240 }
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
314242 describe(...args: Args): string {
315243 const { describe } = this.#options;
316244 return typeof describe === "function"
......@@ -327,58 +255,13 @@ export class BlockingMutation<
327255 }
328256
329257 /** Calling the mutation in a global scope. Errors are turned into UI toasts. */
330 run(...args: Args) {
258 run(...args: Args): void {
331259 this.runWithOptions(...args, {});
332260 }
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
379262 /** Calls the mutation with custom handlers that can suppress global handlers. */
380 runWithOptions(...array: [...Args, RunOptions<Result>]): void {
381 if (!this.#client.enabled) {
263 runWithOptions(...array: [...args: Args, options: RunOptions<Result>]): void {
264 if (!this.client.enabled) {
382265 throw new Error(
383266 "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?",
384267 );
......@@ -396,7 +279,7 @@ export class BlockingMutation<
396279 onError?.(error);
397280 onSettled?.({ status: "error", error });
398281 if (!onError) {
399 this.#client.reportError(formatFriendlyError(this.describe(...args), error), error);
282 this.client.reportError(formatFriendlyError(this.describe(...args), error), error);
400283 }
401284 return;
402285 }
......@@ -415,8 +298,8 @@ export class BlockingMutation<
415298 // Call global handler unless suppressed
416299 if (!suppressGlobalSuccess) {
417300 const message = this.describeResult(args, result);
418 if (message && this.#client.reportSuccess) {
419 this.#client.reportSuccess(message);
301 if (message && this.client.reportSuccess) {
302 this.client.reportSuccess(message);
420303 }
421304 }
422305 }).catch((caught: unknown) => {
......@@ -427,8 +310,53 @@ export class BlockingMutation<
427310
428311 // Call global handler unless suppressed
429312 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."));
431342 }
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;
432360 });
433361 }
434362
......@@ -437,7 +365,7 @@ export class BlockingMutation<
437365 userOnRestore: RunOptions<Result>["onRestore"],
438366 suppressGlobalHandlers: boolean,
439367 ): Promise<Result> {
440 if (!this.#client.enabled) {
368 if (!this.client.enabled) {
441369 throw new Error(
442370 "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?",
443371 );
......@@ -489,7 +417,7 @@ export class BlockingMutation<
489417 }
490418
491419 // Per call, so restores, refetches and refetch dedupe belong to this call
492 const helpers = this.#client.getOptimisticHelpers({
420 const helpers = this.client.getOptimisticHelpers({
493421 onRestore: (cb) => {
494422 rollbacks.push(cb);
495423 },
......@@ -535,7 +463,7 @@ export class BlockingMutation<
535463 context,
536464 { ...context, args },
537465 );
538 const isNoOp = this.#client.deepEquals(beforeSnapshot, afterSnapshot);
466 const isNoOp = this.client.deepEquals(beforeSnapshot, afterSnapshot);
539467
540468 if (isNoOp) {
541469 let next;
......@@ -566,9 +494,44 @@ export class BlockingMutation<
566494 return promise;
567495 }
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
569532 #executeNext(
570533 key: string,
571 channel: Channel<Args, Result, Context<Config, Auth>>,
534 channel: Channel<Args, Result>,
572535 ) {
573536 const item = channel.queue.shift();
574537 if (!item) {
......@@ -594,7 +557,7 @@ export class BlockingMutation<
594557 results.forEach((result) => {
595558 if (result.status === "rejected") {
596559 const message = `Failed to refetch data: ${errMessage(result.reason)}`;
597 this.#client.reportError(message, result.reason);
560 this.client.reportError(message, result.reason);
598561 }
599562 });
600563 },
......@@ -637,7 +600,7 @@ export class BlockingMutation<
637600 results.forEach((result) => {
638601 if (result.status === "rejected") {
639602 const message = `Failed to refetch data: ${errMessage(result.reason)}`;
640 this.#client.reportError(message, result.reason);
603 this.client.reportError(message, result.reason);
641604 }
642605 });
643606 }).finally(() => {
......@@ -651,8 +614,8 @@ export class BlockingMutation<
651614 #runDebouncedAndReturn(
652615 args: Args,
653616 key: string,
654 channel: Channel<Args, Result, Context<Config, Auth>>,
655 context: Context<Config, Auth>,
617 channel: Channel<Args, Result>,
618 context: object,
656619 userOnRestore: (() => void) | undefined,
657620 shouldExecuteImmediate: boolean,
658621 shouldCallGlobalHandler: boolean,
......@@ -672,7 +635,6 @@ export class BlockingMutation<
672635 this.#rollbackPendingDebounced(channel);
673636 }
674637
675 // Apply optimistic update (same logic as current runAndReturn)
676638 const onSuccess: Array<(result: Result) => void> = [];
677639 let expired = false;
678640 const rollbacks: Array<() => void> = [];
......@@ -692,7 +654,7 @@ export class BlockingMutation<
692654 }
693655
694656 // Per call, so restores, refetches and refetch dedupe belong to this call
695 const helpers = this.#client.getOptimisticHelpers({
657 const helpers = this.client.getOptimisticHelpers({
696658 onRestore: (cb) => {
697659 rollbacks.push(cb);
698660 },
......@@ -745,7 +707,7 @@ export class BlockingMutation<
745707
746708 if (
747709 snapshotToCompare !== undefined
748 && this.#client.deepEquals(snapshotToCompare, currentSnapshot)
710 && this.client.deepEquals(snapshotToCompare, currentSnapshot)
749711 ) {
750712 // No-op detected - rollback optimistic update
751713 let next;
......@@ -818,7 +780,7 @@ export class BlockingMutation<
818780 }
819781
820782 #rollbackPendingDebounced(
821 channel: Channel<Args, Result, Context<Config, Auth>>,
783 channel: Channel<Args, Result>,
822784 ) {
823785 if (!channel.pendingDebounced) return;
824786
......@@ -834,7 +796,7 @@ export class BlockingMutation<
834796
835797 #enqueueDebouncedCall(
836798 key: string,
837 channel: Channel<Args, Result, Context<Config, Auth>>,
799 channel: Channel<Args, Result>,
838800 ) {
839801 // Clear timer
840802 channel.debounceTimer = null;
......@@ -870,8 +832,8 @@ export class BlockingMutation<
870832 // Call global handler if needed (based on whether component is watching success)
871833 if (shouldCallGlobalHandler) {
872834 const message = this.describeResult(args, result);
873 if (message && this.#client.reportSuccess) {
874 this.#client.reportSuccess(message);
835 if (message && this.client.reportSuccess) {
836 this.client.reportSuccess(message);
875837 }
876838 }
877839 },
......@@ -883,7 +845,7 @@ export class BlockingMutation<
883845
884846 // Call global handler if needed (based on whether component is watching errors)
885847 if (shouldCallGlobalHandler) {
886 this.#client.reportError(
848 this.client.reportError(
887849 formatFriendlyError(description, error),
888850 error,
889851 );
......@@ -891,7 +853,6 @@ export class BlockingMutation<
891853 },
892854 );
893855
894 // Add to queue (same structure as regular blocking mutation)
895856 channel.queue.push({
896857 args,
897858 context,
......@@ -908,6 +869,40 @@ export class BlockingMutation<
908869 }
909870 // Otherwise, it will execute when the current item finishes
910871 }
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 }
911906}
912907
913908export function formatFriendlyError(
src/react.ts+15-19
......@@ -13,9 +13,9 @@ import {
1313 useSyncExternalStore,
1414} from "react";
1515import { jsx } from "react/jsx-runtime";
16import type { MutationClient, MutationClientConfig, MutationClientFromConfig } from "./client.ts";
17import { BlockingMutation, formatFriendlyError } from "./mutation.ts";
18import type { Mutation, RunOptions, SerializableValue } from "./types.ts";
16import type { MutationClient } from "./client.ts";
17import { formatFriendlyError, Mutation } from "./mutation.ts";
18import type { RunOptions } from "./types.ts";
1919
2020/**
2121 * Subscribe to a mutation's status, as well as accessing a local `run` method.
......@@ -77,22 +77,18 @@ export function bindAsyncCallback(
7777 const live = useRef({ callback, options });
7878 live.current = { callback, options };
7979 // A stable, unregistered mutation with no optimistic state; every field
80 // reads the ref so it tracks the latest callback and options. Args are
81 // never serialized here (no id, no auth replay), so the serializable bound
82 // is cast away locally. Empty describe/describeResult fall through to the
83 // generic error message and no success toast, respectively.
80 // reads the ref so it tracks the latest callback and options. Empty
81 // describe/describeResult fall through to the generic error message and no
82 // success toast, respectively.
8483 const [mutation] = useState(() =>
85 new BlockingMutation<SerializableValue[], Result, false, MutationClientConfig>(
86 client as unknown as MutationClientFromConfig<MutationClientConfig>,
87 {
88 id: "",
89 mutate: (...args) => live.current.callback(...(args as unknown as Args)),
90 optimistic: () => {},
91 describe: () => live.current.options?.describe ?? "",
92 describeResult: () => live.current.options?.describeResult ?? "",
93 refetchOnSuccess: false,
94 },
95 ) as unknown as Mutation<Args, Result>
84 new Mutation<Args, Result>(client, {
85 id: "",
86 mutate: (...args) => live.current.callback(...args),
87 optimistic: () => {},
88 describe: () => live.current.options?.describe ?? "",
89 describeResult: () => live.current.options?.describeResult ?? "",
90 refetchOnSuccess: false,
91 })
9692 );
9793 return useMutate(mutation);
9894 };
......@@ -494,7 +490,7 @@ export interface MutationButtonProps<Args extends unknown[], Result> {
494490 | Mutation<Args, Result>
495491 | UseMutateResult<Args, Result>;
496492 /** Preventing default will interrupt the mutation */
497 args: Args | null | ((e: MouseEvent) => Args | null);
493 args: NoInfer<Args> | null | ((e: MouseEvent) => NoInfer<Args> | null);
498494 /** Preventing default will interrupt the mutation */
499495 onClick?: (e: MouseEvent) => void;
500496 disabled?: boolean;
src/types.ts+1-38
......@@ -1,4 +1,4 @@
1import type { MutationClient } from "./client.ts";
1import type { Mutation } from "./mutation.ts";
22
33/**
44 * Plain JSON value. The default serializable leaf set, still exported for
......@@ -61,43 +61,6 @@ export interface MutationAction {
6161 args: SerializableValue[];
6262}
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
10164export interface RunOptions<Result> {
10265 /** Called to show the success UI. Passing this suppresses the global success handler. */
10366 onSuccessUi?: (result: Result) => void;