@mmstack/resource 19.6.4 → 19.6.6

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/README.md CHANGED
@@ -279,6 +279,22 @@ mutationResource(
279
279
 
280
280
  The `TCTX` returned from `onMutate` flows into `onError` / `onSuccess` / `onSettled`. The optional `initialCtx` second arg to `.mutate(value, initialCtx)` flows into `onMutate` as its second argument.
281
281
 
282
+ ### Awaiting a mutation (`mutateAsync`)
283
+
284
+ `.mutate()` is fire-and-forget. When you need to `await` the outcome — a form submit handler, an async validator — use `.mutateAsync()`, which returns a `Promise` that resolves with the result or rejects with the error. The lifecycle hooks still run exactly as with `.mutate()`.
285
+
286
+ ```typescript
287
+ try {
288
+ const saved = await createPost.mutateAsync(post);
289
+ router.navigate(['/posts', saved.id]);
290
+ } catch (e) {
291
+ if (e instanceof MutationCancelledError) return; // never ran — see below
292
+ toast.error('Failed to save');
293
+ }
294
+ ```
295
+
296
+ If the mutation never completes — superseded by a newer one (latest-wins), dropped from the queue (`clearQueue()` / a `key` change), abandoned on `destroy()`, or its `request()` returned `undefined` — the promise rejects with a `MutationCancelledError` whose `.type` (`MutationCancellationReason`) tells you which. Awaiters that don't expect cancellation should rethrow it. (Plain `.mutate()` has no promise, so it never produces an unhandled rejection.)
297
+
282
298
  ### Queuing
283
299
 
284
300
  By default, calling `.mutate()` while another mutation is in flight starts immediately — concurrent mutations run in parallel. With `queue: true`, mutations are serialized:
@@ -316,13 +332,42 @@ mutationResource(request, { triggerOnSameRequest: true });
316
332
 
317
333
  A mutation also honours the `register` option — but it registers the **mutation ref itself** into the transition scope (its internal query is never registered), so a `<mm-suspense>`/transition reacts to the mutation's own `pending` state. See [transitions & Suspense](#transitions--suspense).
318
334
 
335
+ ### File uploads & progress (`multipart/form-data`)
336
+
337
+ There's no special upload API — return a `FormData` body and `HttpClient` sets the `multipart/form-data` boundary for you. Opt into upload progress with `reportProgress: true` and read the `progress` signal (an `HttpProgressEvent`).
338
+
339
+ ```typescript
340
+ const upload = mutationResource<UploadResult, UploadResult, FormData>((form) => ({
341
+ url: '/api/upload',
342
+ method: 'POST',
343
+ body: form,
344
+ reportProgress: true, // opt in to progress events
345
+ }));
346
+
347
+ // trigger it:
348
+ const form = new FormData();
349
+ form.append('file', file);
350
+ upload.mutate(form);
351
+
352
+ // derive a percentage in a computed / template:
353
+ readonly pct = computed(() => {
354
+ const p = upload.progress();
355
+ return p?.total ? Math.round((p.loaded / p.total) * 100) : null;
356
+ });
357
+ ```
358
+
359
+ `FormData`, `File`, and `Blob` bodies are hashed structurally for dedup/cache keys (a `File` by name + type + size + lastModified), so distinct files never collide. To re-upload the **same** file while one is already in flight, pair it with `triggerOnSameRequest: true`.
360
+
319
361
  ### Return shape (`MutationResourceRef<T, TMutation>`)
320
362
 
321
- | Member | Type | Notes |
322
- | --------------------------------------------- | --------------------------- | ------------------------------------------------------ |
323
- | `mutate` | `(value, ctx?) => void` | Trigger the mutation. |
324
- | `current` | `Signal<TMutation \| null>` | The value currently being mutated (or `null` if idle). |
325
- | `status` / `error` / `isLoading` / `disabled` | as in `QueryResourceRef` | |
363
+ | Member | Type | Notes |
364
+ | --------------------------------------------- | ------------------------------------------ | ------------------------------------------------------ |
365
+ | `mutate` | `(value, ctx?) => void` | Trigger the mutation (fire-and-forget). |
366
+ | `mutateAsync` | `(value, ctx?) => Promise<TResult>` | Trigger and `await` the result; rejects with the error or a `MutationCancelledError`. |
367
+ | `current` | `Signal<TMutation \| null>` | The value currently being mutated (or `null` if idle). |
368
+ | `progress` | `Signal<HttpProgressEvent \| undefined>` | Upload/download progress when `reportProgress: true`. |
369
+ | `status` / `error` / `isLoading` / `disabled` | as in `QueryResourceRef` | – |
370
+ | `headers` / `statusCode` | as in `QueryResourceRef` | Response metadata, when available. |
326
371
 
327
372
  (Mutations deliberately don't expose `value`, `hasValue`, `set`, `update`, or `prefetch` — those don't make sense for one-off writes.)
328
373
 
@@ -2359,6 +2359,23 @@ function manualQueryResource(request, options) {
2359
2359
  }
2360
2360
 
2361
2361
  const NULL_VALUE = Symbol('@mmstack/resource:null');
2362
+ /**
2363
+ * Rejection reason for a {@link MutationResourceRef.mutateAsync} promise whose
2364
+ * mutation never completed. The {@link MutationCancelledError.type} discriminant
2365
+ * carries the cause ({@link MutationCancellationReason}); the message is a
2366
+ * human-readable elaboration of it.
2367
+ *
2368
+ * Only `mutateAsync` promises reject with this; plain `mutate()` calls have no
2369
+ * promise and so produce no (potentially unhandled) rejection.
2370
+ */
2371
+ class MutationCancelledError extends Error {
2372
+ type;
2373
+ constructor(type, message) {
2374
+ super(message);
2375
+ this.type = type;
2376
+ this.name = 'MutationCancelledError';
2377
+ }
2378
+ }
2362
2379
  const MUTATION_RESOURCE_OPTIONS = new InjectionToken('@mmstack/resource:mutation-resource-options', { factory: () => ({}) });
2363
2380
  /**
2364
2381
  * Layer 2 (mutation): default options for every `mutationResource`, inheriting + overriding the
@@ -2372,55 +2389,6 @@ function injectMutationResourceOptions(injector) {
2372
2389
  ? injector.get(MUTATION_RESOURCE_OPTIONS)
2373
2390
  : inject(MUTATION_RESOURCE_OPTIONS);
2374
2391
  }
2375
- /**
2376
- * Creates a resource for performing mutations (e.g., POST, PUT, PATCH, DELETE requests).
2377
- * Unlike `queryResource`, `mutationResource` is designed for one-off operations that change data.
2378
- * It does *not* cache responses and does not provide a `value` signal. Instead, it focuses on
2379
- * managing the mutation lifecycle (pending, error, success) and provides callbacks for handling
2380
- * these states.
2381
- *
2382
- * @param request A function that returns the base `HttpResourceRequest` to be made. This function is called reactively. The parameter is the mutation value provided by the `mutate` method.
2383
- * @param options Configuration options for the mutation resource. This includes callbacks
2384
- * for `onMutate`, `onError`, `onSuccess`, and `onSettled`.
2385
- * @typeParam TResult - The type of the expected result from the mutation.
2386
- * @typeParam TRaw - The raw response type from the HTTP request (defaults to TResult).
2387
- * @typeParam TMutation - The type of the mutation value (the request body).
2388
- * @typeParam TICTX - The type of the initial context value passed to `onMutate`.
2389
- * @typeParam TCTX - The type of the context value returned by `onMutate`.
2390
- * @typeParam TMethod - The HTTP method to be used for the mutation (defaults to `HttpResourceRequest['method']`).
2391
- * @returns A `MutationResourceRef` instance, which provides methods for triggering the mutation
2392
- * and observing its status.
2393
- *
2394
- * @example
2395
- * ```ts
2396
- * // Basic PATCH mutation
2397
- * const updateUser = mutationResource<User, User, Partial<User>>(
2398
- * (body) => ({ url: `/api/users/${userId()}`, method: 'PATCH', body }),
2399
- * {
2400
- * onSuccess: (saved) => toast.success(`Updated ${saved.name}`),
2401
- * onError: (err) => toast.error(err),
2402
- * },
2403
- * );
2404
- *
2405
- * updateUser.mutate({ name: 'Alice' });
2406
- * ```
2407
- *
2408
- * @example
2409
- * ```ts
2410
- * // Optimistic update with rollback via the `ctx` returned from `onMutate`
2411
- * const updateUser = mutationResource<User, User, Partial<User>, { prev: User | null }>(
2412
- * (body) => ({ url: `/api/users/${userId()}`, method: 'PATCH', body }),
2413
- * {
2414
- * onMutate: (patch) => {
2415
- * const prev = current();
2416
- * current.update((u) => (u ? { ...u, ...patch } : u));
2417
- * return { prev };
2418
- * },
2419
- * onError: (_err, { prev }) => current.set(prev),
2420
- * },
2421
- * );
2422
- * ```
2423
- */
2424
2392
  function mutationResource(request, options0 = {}) {
2425
2393
  // Two-layer option injection: per-call > provideMutationResourceOptions > provideResourceOptions.
2426
2394
  const globalOpts = injectResourceOptions(options0.injector);
@@ -2437,11 +2405,6 @@ function mutationResource(request, options0 = {}) {
2437
2405
  const { onMutate, onError, onSuccess, onSettled, equal, register, equalRequest, invalidates, ...rest } = options;
2438
2406
  const cache = invalidates ? injectQueryCache(options.injector) : undefined;
2439
2407
  const requestEqual = equalRequest ?? createEqualRequest(equal);
2440
- // A mutation is an imperative command, so `triggerOnSameRequest` means "fire on EVERY mutate(),
2441
- // even with an identical body". By default we dedup an identical value/request while one is in
2442
- // flight (double-click protection); when this is set, both the `next` and `req` dedup are bypassed
2443
- // so a repeat click isn't silently swallowed mid-flight. (Otherwise it'd be dropped until `next`
2444
- // resets to NULL on settle — the "every other click" symptom.)
2445
2408
  const triggerOnSame = options.triggerOnSameRequest ?? false;
2446
2409
  const eq = equal ?? Object.is;
2447
2410
  const next = signal(NULL_VALUE, {
@@ -2455,25 +2418,19 @@ function mutationResource(request, options0 = {}) {
2455
2418
  return eq(a, b);
2456
2419
  },
2457
2420
  });
2458
- const queue = signal([]);
2459
- let ctx = undefined;
2460
- const queueRef = effect(() => {
2461
- const nextInQueue = queue().at(0);
2462
- if (nextInQueue === undefined || next() !== NULL_VALUE)
2463
- return;
2464
- queue.update((q) => q.slice(1));
2465
- const [value, ictx] = nextInQueue;
2466
- try {
2467
- ctx = onMutate?.(value, ictx);
2468
- next.set(value);
2469
- }
2470
- catch (mutationErr) {
2471
- ctx = undefined;
2472
- next.set(NULL_VALUE);
2473
- if (isDevMode())
2474
- console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2475
- }
2476
- }, { injector: options.injector });
2421
+ const queueEnabled = !!options.queue;
2422
+ const queueKeyFn = typeof options.queue === 'object' ? options.queue.key : undefined;
2423
+ const queue = linkedSignal({
2424
+ source: () => queueKeyFn?.(),
2425
+ computation: (_key, prev) => {
2426
+ // On a queue key change the previous pending entries are dropped — reject any
2427
+ // mutateAsync promises waiting on them so awaiters don't hang.
2428
+ if (prev)
2429
+ for (const [, , deferred] of untracked(prev.value))
2430
+ deferred?.reject(new MutationCancelledError('queue-key-changed', 'mutation dropped: queue key changed before it ran'));
2431
+ return signal([]);
2432
+ },
2433
+ });
2477
2434
  const req = computed(() => {
2478
2435
  const nr = next();
2479
2436
  if (nr === NULL_VALUE)
@@ -2490,6 +2447,57 @@ function mutationResource(request, options0 = {}) {
2490
2447
  return requestEqual(a, b);
2491
2448
  },
2492
2449
  });
2450
+ let ctx = undefined;
2451
+ let currentDeferred;
2452
+ const begin = (value, ictx, deferred) => {
2453
+ let nextCtx;
2454
+ try {
2455
+ nextCtx = onMutate?.(value, ictx);
2456
+ }
2457
+ catch (mutationErr) {
2458
+ // match legacy mutate(): the throw aborts the mutation and resets state
2459
+ ctx = undefined;
2460
+ next.set(NULL_VALUE);
2461
+ deferred?.reject(mutationErr);
2462
+ if (isDevMode())
2463
+ console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2464
+ return;
2465
+ }
2466
+ ctx = nextCtx;
2467
+ currentDeferred = deferred;
2468
+ next.set(value);
2469
+ if (deferred && untracked(req) === undefined) {
2470
+ ctx = undefined;
2471
+ currentDeferred = undefined;
2472
+ next.set(NULL_VALUE);
2473
+ deferred.reject(new MutationCancelledError('no-request', 'mutation not sent: request() returned undefined'));
2474
+ }
2475
+ };
2476
+ const supersedeInFlight = () => {
2477
+ if (untracked(next) === NULL_VALUE)
2478
+ return;
2479
+ if (isDevMode())
2480
+ console.warn('[@mmstack/resource]: mutate() called while another mutation was in flight — the previous mutation was superseded (latest-wins) and its onSettled was invoked. Use `queue: true` for sequential mutations.');
2481
+ try {
2482
+ onSettled?.(ctx);
2483
+ }
2484
+ catch (settleErr) {
2485
+ if (isDevMode())
2486
+ console.error('[@mmstack/resource]: error thrown in onSettled hook for a superseded mutation', settleErr);
2487
+ }
2488
+ currentDeferred?.reject(new MutationCancelledError('superseded', 'mutation superseded by a newer mutation (latest-wins)'));
2489
+ currentDeferred = undefined;
2490
+ ctx = undefined;
2491
+ };
2492
+ const queueRef = effect(() => {
2493
+ const q = queue(); // subscribe to swaps (key change / clearQueue)
2494
+ const nextInQueue = q().at(0); // subscribe to contents
2495
+ if (nextInQueue === undefined || next() !== NULL_VALUE)
2496
+ return;
2497
+ q.update((arr) => arr.slice(1));
2498
+ const [value, ictx, deferred] = nextInQueue;
2499
+ begin(value, ictx, deferred);
2500
+ }, { injector: options.injector });
2493
2501
  const lastValue = linkedSignal({
2494
2502
  source: next,
2495
2503
  computation: (next, prev) => {
@@ -2548,8 +2556,12 @@ function mutationResource(request, options0 = {}) {
2548
2556
  return NULL_VALUE;
2549
2557
  }), filter((v) => v !== NULL_VALUE), takeUntilDestroyed(destroyRef))
2550
2558
  .subscribe((result) => {
2551
- if (result.status === 'error')
2559
+ const deferred = currentDeferred;
2560
+ currentDeferred = undefined;
2561
+ if (result.status === 'error') {
2552
2562
  onError?.(result.error, ctx);
2563
+ deferred?.reject(result.error);
2564
+ }
2553
2565
  else {
2554
2566
  onSuccess?.(result.value, ctx);
2555
2567
  if (cache && invalidates) {
@@ -2557,61 +2569,61 @@ function mutationResource(request, options0 = {}) {
2557
2569
  const prefixes = typeof invalidates === 'function'
2558
2570
  ? invalidates(result.value, (mutation === NULL_VALUE ? undefined : mutation))
2559
2571
  : invalidates;
2560
- // auto-keys are `${method}:${url}:...` — a `GET:`-prefixed url prefix hits
2561
- // the url with any params/subpaths and every varyHeaders variant
2562
2572
  for (const prefix of prefixes)
2563
2573
  cache.invalidatePrefix(`GET:${prefix}`);
2564
2574
  }
2575
+ deferred?.resolve(result.value);
2565
2576
  }
2566
2577
  onSettled?.(ctx);
2567
2578
  ctx = undefined;
2568
2579
  next.set(NULL_VALUE);
2569
2580
  });
2570
- const shouldQueue = options.queue ?? false;
2571
2581
  const ref = {
2572
2582
  ...resource,
2573
2583
  destroy: () => {
2574
2584
  // queue first — a late queue flush must not poke an already-destroyed resource
2575
2585
  queueRef.destroy();
2576
2586
  statusSub.unsubscribe();
2587
+ // reject any outstanding mutateAsync promises so awaiters don't hang
2588
+ const cancelled = new MutationCancelledError('destroyed', 'mutation abandoned: resource destroyed');
2589
+ currentDeferred?.reject(cancelled);
2590
+ currentDeferred = undefined;
2591
+ for (const [, , deferred] of untracked(queue)())
2592
+ deferred?.reject(cancelled);
2577
2593
  resource.destroy();
2578
2594
  },
2579
2595
  mutate: (value, ictx) => {
2580
- if (shouldQueue) {
2581
- return queue.update((q) => [...q, [value, ictx]]);
2596
+ if (queueEnabled) {
2597
+ queue().update((arr) => [...arr, [value, ictx, undefined]]);
2598
+ return;
2599
+ }
2600
+ supersedeInFlight();
2601
+ begin(value, ictx, undefined);
2602
+ },
2603
+ mutateAsync: (value, ictx) => {
2604
+ const deferred = Promise.withResolvers();
2605
+ if (queueEnabled) {
2606
+ queue().update((arr) => [...arr, [value, ictx, deferred]]);
2582
2607
  }
2583
2608
  else {
2584
- // latest-wins: a mutation already in flight gets superseded (its request is
2585
- // aborted by the request change), so its onSuccess/onError will never fire —
2586
- // settle its context NOW so optimistic state can be rolled back/cleaned up
2587
- if (untracked(next) !== NULL_VALUE) {
2588
- if (isDevMode())
2589
- console.warn('[@mmstack/resource]: mutate() called while another mutation was in flight — the previous mutation was superseded (latest-wins) and its onSettled was invoked. Use `queue: true` for sequential mutations.');
2590
- try {
2591
- onSettled?.(ctx);
2592
- }
2593
- catch (settleErr) {
2594
- if (isDevMode())
2595
- console.error('[@mmstack/resource]: error thrown in onSettled hook for a superseded mutation', settleErr);
2596
- }
2597
- ctx = undefined;
2598
- }
2599
- try {
2600
- ctx = onMutate?.(value, ictx);
2601
- next.set(value);
2602
- }
2603
- catch (mutationErr) {
2604
- ctx = undefined;
2605
- next.set(NULL_VALUE);
2606
- if (isDevMode())
2607
- console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2608
- }
2609
+ supersedeInFlight();
2610
+ begin(value, ictx, deferred);
2609
2611
  }
2612
+ return deferred.promise;
2610
2613
  },
2611
2614
  current: computed(() => {
2612
2615
  const nv = next();
2613
2616
  return nv === NULL_VALUE ? null : nv;
2614
2617
  }),
2618
+ clearQueue: () => {
2619
+ if (!queueEnabled)
2620
+ return;
2621
+ const dropped = untracked(queue)();
2622
+ queue.set(signal([]));
2623
+ // reject mutateAsync promises whose entries we just dropped
2624
+ for (const [, , deferred] of dropped)
2625
+ deferred?.reject(new MutationCancelledError('queue-cleared', 'mutation dropped: queue cleared before it ran'));
2626
+ },
2615
2627
  // redeclare disabled with last value so that it is not affected by the resource's internal disablement logic
2616
2628
  disabled: computed(() => cb.isOpen() || lastValueRequest() === undefined),
2617
2629
  };
@@ -2623,5 +2635,5 @@ function mutationResource(request, options0 = {}) {
2623
2635
  * Generated bundle index. Do not edit.
2624
2636
  */
2625
2637
 
2626
- export { Cache, PAUSED, applyResourceRegistration, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, hashRequest, infiniteQueryResource, injectQueryCache, injectResourceOptions, manualQueryResource, mutationResource, noDedupe, provideCircuitBreakerDefaultOptions, provideMutationResourceOptions, provideQueryCache, provideQueryResourceOptions, provideResourceOptions, provideTypedResourceOptions, queryResource };
2638
+ export { Cache, MutationCancelledError, PAUSED, applyResourceRegistration, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, hashRequest, infiniteQueryResource, injectQueryCache, injectResourceOptions, manualQueryResource, mutationResource, noDedupe, provideCircuitBreakerDefaultOptions, provideMutationResourceOptions, provideQueryCache, provideQueryResourceOptions, provideResourceOptions, provideTypedResourceOptions, queryResource };
2627
2639
  //# sourceMappingURL=mmstack-resource.mjs.map