@collective-intelligence/external-apps-client-sdk-react 0.2.9 → 0.2.11

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/AGENTS.md CHANGED
@@ -20,7 +20,8 @@ holds the full API.
20
20
  - Run each side effect of a machine in a `fromEffect` actor. Keep remote data
21
21
  in `QueryCache`, never in machine context. After a write, refresh reads with
22
22
  `QueryCache` (`invalidate`, `setData`, `update`, `remove`); do not put the
23
- QueryClient in machine input. A view renders: it calls no `fetch` and runs
23
+ QueryClient in machine input. An optimistic write calls `cancel` on its keys
24
+ before `update`, and `invalidate` when the write settles. A view renders: it calls no `fetch` and runs
24
25
  no Effect.
25
26
  - Show write failures with `onWriteFailed` on the provider, for example
26
27
  `ciWriteFailedToast()` of `@collective-intelligence/ui-react/ui`.
package/README.md CHANGED
@@ -271,9 +271,13 @@ QueryClient. It has no Effect Atom bindings.
271
271
  `query` is interrupted. Thus in React Strict Mode, the actor that
272
272
  `useActorRef` starts again can run `query` a second time. A cancel of the
273
273
  key, for example `queryClient.cancelQueries({ queryKey })`, also interrupts
274
- `query`. A `fetch` that waits then returns the value from before the fetch,
275
- or is interrupted when the key has no value. `invalidate(queryKey)` marks
274
+ `query`. A `fetch` that waits then returns the cached value, or is
275
+ interrupted when the key has no value. `invalidate(queryKey)` marks
276
276
  values stale and refetches the ones that views show.
277
+ `cancel(queryKey)` cancels the running fetches and interrupts their
278
+ queries, so they write no value; it keeps the cached values and starts no
279
+ fetch. An optimistic write calls `cancel`, then `update`, runs the write,
280
+ and calls `invalidate` when the write settles.
277
281
  `setData(queryKey, value)` writes a value that views show at once.
278
282
  `update(queryKey, (current) => next)` replaces each cached value with the
279
283
  result of the function for its current value, without a refetch, for
@@ -282,11 +286,11 @@ QueryClient. It has no Effect Atom bindings.
282
286
  function takes. `current` is `undefined` for an entry without a value, an
283
287
  `undefined` result keeps the value, and a key that the cache does not hold
284
288
  stays absent. `update` does not cancel a running fetch, which can replace
285
- the new value when it ends.
289
+ the new value when it ends: call `cancel` first.
286
290
  `remove(queryKey)` removes the cached entries without a refetch, for example
287
291
  at sign-out; it cancels a running fetch of a removed key, and the next
288
292
  `fetch` runs its query. A mounted view of a removed key keeps its last
289
- result until it renders again. `invalidate`,
293
+ result until it renders again. `invalidate`, `cancel`,
290
294
  `update` and `remove` apply to `queryKey` and to each key below it
291
295
  (`["crm", "lead"]` matches `["crm", "lead", "7"]`, not `["crm", "leads"]`);
292
296
  `setData` writes `queryKey` only. Views read the same keys with `useQuery`.
package/dist/effect.d.ts CHANGED
@@ -7,7 +7,7 @@ import * as Effect from 'effect/Effect';
7
7
  import * as Layer from 'effect/Layer';
8
8
  import * as ManagedRuntime from 'effect/ManagedRuntime';
9
9
  import { ReactNode } from 'react';
10
- import { PromiseActorLogic } from 'xstate';
10
+ import { ActorRefFromLogic, MetaObject, PromiseActorLogic, StateMachine } from 'xstate';
11
11
 
12
12
  /** What runs an effect for an actor: a `ManagedRuntime` that provides `R`. */
13
13
  export type EffectRunner<R> = Pick<ManagedRuntime.ManagedRuntime<R, never>, "runPromise">;
@@ -57,38 +57,25 @@ export type EffectTaskContext<A, R> = Readonly<{
57
57
  * A flow with steps of its own, such as a form that saves and then confirms,
58
58
  * is its own machine with `fromEffect` actors, not a task.
59
59
  */
60
- export declare const effectTask: <Input, A, E, R = never>(run: (input: Input) => Effect.Effect<A, E, R>) => import("xstate").StateMachine<Readonly<{
61
- /** The typed error or the defect of the last run, while the task is `failed`. */
62
- error: unknown;
63
- /** The value of the last run, while the task is `done`. */
64
- output: A | undefined;
60
+ export declare const effectTask: <Input, A, E, R = never>(run: (input: Input) => Effect.Effect<A, E, R>) => StateMachine<EffectTaskContext<A, R>, EffectTaskEvent<Input>, Record<string, ActorRefFromLogic<PromiseActorLogic<A, Readonly<{
65
61
  runtime: EffectRunner<R>;
66
- }>, Readonly<{
67
- input: Input;
68
- type: "RUN";
69
- }>, {
70
- [x: string]: import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<A, Readonly<{
71
- runtime: EffectRunner<R>;
72
- task: Input;
73
- }>>> | undefined;
74
- }, {
75
- src: "run";
76
- logic: import("xstate").PromiseActorLogic<A, Readonly<{
62
+ task: Input;
63
+ }>>> | undefined>, {
64
+ id: string | undefined;
65
+ logic: PromiseActorLogic<A, Readonly<{
77
66
  runtime: EffectRunner<R>;
78
67
  task: Input;
79
68
  }>>;
80
- id: string | undefined;
81
- }, never, never, never, "done" | "failed" | "idle" | "running", string, Readonly<{
82
- runtime: EffectRunner<R>;
83
- }>, undefined, EffectTaskEmitted<A>, import("xstate").MetaObject, {
69
+ src: "run";
70
+ }, never, never, never, "done" | "failed" | "idle" | "running", string, EffectTaskInput<R>, undefined, EffectTaskEmitted<A>, MetaObject, {
84
71
  id: "effectTask";
85
72
  states: {
86
- readonly done: {};
87
- readonly failed: {};
88
- readonly idle: {};
89
- readonly running: {};
73
+ readonly done: Record<never, never>;
74
+ readonly failed: Record<never, never>;
75
+ readonly idle: Record<never, never>;
76
+ readonly running: Record<never, never>;
90
77
  };
91
- }, import("xstate").MetaObject>;
78
+ }>;
92
79
  /** The machine `effectTask(run)` makes. */
93
80
  export type EffectTask<Input, A, E = never, R = never> = ReturnType<typeof effectTask<Input, A, E, R>>;
94
81
  export type QueryCacheFetchOptions<Data> = Readonly<{
@@ -102,11 +89,22 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
102
89
  /**
103
90
  * The fresh cached value of `queryKey`, or the value of one run of `query`,
104
91
  * then cached. When the last view or caller of the key stops waiting, or
105
- * TanStack Query cancels the key, `query` is interrupted.
92
+ * `cancel` or TanStack Query cancels the key, `query` is interrupted. After
93
+ * a cancel, the caller gets the cached value of the key, or an interruption
94
+ * when the key holds no value.
106
95
  */
107
96
  fetch: <Data>(options: QueryCacheFetchOptions<Data>) => Effect.Effect<Data, CiError | CiTransportError>;
108
97
  /** Marks the values of `queryKey` and of the keys below it stale, and refetches the ones that views show. */
109
98
  invalidate: (queryKey: QueryKey) => Effect.Effect<void>;
99
+ /**
100
+ * Cancels the running fetches of `queryKey` and of the keys below it and
101
+ * interrupts their queries, so these fetches write no value. Keeps the
102
+ * cached values and starts no fetch, so a view of a key whose first fetch
103
+ * it cancels shows no value until the next fetch. Call it before an
104
+ * optimistic `update`, so that a fetch that ends later does not replace the
105
+ * new value, and `invalidate` when the write ends.
106
+ */
107
+ cancel: (queryKey: QueryKey) => Effect.Effect<void>;
110
108
  /** Caches `data` as the value of `queryKey`; views show it at once. */
111
109
  setData: <Data>(queryKey: QueryKey, data: Data) => Effect.Effect<void>;
112
110
  /**
@@ -116,7 +114,7 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
116
114
  * without a value, and its `undefined` result keeps the value. Keys that the
117
115
  * cache does not hold stay absent. Each key below `queryKey` must hold a
118
116
  * `Data` value. A running fetch is not cancelled, and its value replaces the
119
- * new value when it ends.
117
+ * new value when it ends; call `cancel` first to keep the new value.
120
118
  */
121
119
  update: <Data>(queryKey: QueryKey, updater: (current: Data | undefined) => Data | undefined) => Effect.Effect<void>;
122
120
  /**
package/dist/effect.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{__export}from"./index-6ra894v2.js";var exports_effect={};__export(exports_effect,{EffectRuntimeProvider:()=>EffectRuntimeProvider,QueryCache:()=>QueryCache,effectTask:()=>effectTask,fromEffect:()=>fromEffect,useEffectRuntime:()=>useEffectRuntime});import{assign,emit,setup}from"xstate";import{fromPromise}from"xstate";var unsettled=()=>Promise.race([]);var fromEffect=(run)=>fromPromise(async({input,signal})=>{try{const value=await input.runtime.runPromise(run(input),{signal});return signal.aborted?unsettled():value}catch(error){if(signal.aborted){return unsettled()}throw error}});var effectTask=(run)=>{const actors={run:fromEffect(({task})=>run(task))};return setup({actors}).createMachine({context:({input})=>({error:undefined,output:undefined,runtime:input.runtime}),id:"effectTask",initial:"idle",on:{RUN:{target:".running"}},states:{done:{},failed:{},idle:{},running:{entry:assign({error:undefined,output:undefined}),invoke:{input:({context,event})=>({runtime:context.runtime,task:event.input}),onDone:{actions:[assign({output:({event})=>event.output}),emit(({event})=>({output:event.output,type:"done"}))],target:"done"},onError:{actions:[assign({error:({event})=>event.error}),emit(({event})=>({error:event.error,type:"failed"}))],target:"failed"},src:"run"},on:{RUN:{}}}}})};import{CiError,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import{isCancelledError,QueryObserver}from"@tanstack/react-query";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Layer from"effect/Layer";class QueryCache extends Context.Service()("@collective-intelligence/external-apps-client-sdk-react/QueryCache"){}var make=(queryClient)=>{const fetchExit=async({query,...options},context)=>{try{return Exit.succeed(await queryClient.fetchQuery({...options,queryFn:({signal})=>Effect.runPromiseWith(context)(query,{signal}),retry:false}))}catch(error){if(isCancelledError(error)){return Exit.interrupt()}return error instanceof CiError||error instanceof CiTransportError?Exit.fail(error):Exit.die(error)}};const waitOn=(queryKey)=>Effect.sync(()=>new QueryObserver(queryClient,{enabled:false,queryKey}).subscribe(constVoid));return QueryCache.of({fetch:(options)=>Effect.flatMap(Effect.context(),(context)=>Effect.acquireUseRelease(waitOn(options.queryKey),()=>Effect.flatten(Effect.promise(()=>fetchExit(options,context))),(stopWaiting)=>Effect.sync(stopWaiting))),invalidate:(queryKey)=>Effect.promise(()=>queryClient.invalidateQueries({queryKey})),remove:(queryKey)=>Effect.sync(()=>{queryClient.removeQueries({queryKey})}),setData:(queryKey,data)=>Effect.sync(()=>{queryClient.setQueryData(queryKey,data)}),update:(queryKey,updater)=>Effect.sync(()=>{queryClient.setQueriesData({queryKey},updater)})})};var layer=(queryClient)=>Layer.succeed(QueryCache,make(queryClient));import{useQueryClient}from"@tanstack/react-query";import*as ManagedRuntime from"effect/ManagedRuntime";import{createContext,useContext,useMemo}from"react";import{jsx}from"react/jsx-runtime";var RuntimeContext=createContext(null);var EffectRuntimeProvider=({children})=>{const queryClient=useQueryClient();const runtime=useMemo(()=>ManagedRuntime.make(layer(queryClient)),[queryClient]);return jsx(RuntimeContext.Provider,{value:runtime,children})};var useEffectRuntime=()=>{const runtime=useContext(RuntimeContext);if(runtime===null){throw new Error("useEffectRuntime requires an EffectRuntimeProvider")}return runtime};var{EffectRuntimeProvider:EffectRuntimeProvider2,QueryCache:QueryCache2,effectTask:effectTask2,fromEffect:fromEffect2,useEffectRuntime:useEffectRuntime2}=exports_effect;export{EffectRuntimeProvider2 as EffectRuntimeProvider,QueryCache2 as QueryCache,effectTask2 as effectTask,fromEffect2 as fromEffect,useEffectRuntime2 as useEffectRuntime};
2
+ import{__export}from"./index-6ra894v2.js";var exports_effect={};__export(exports_effect,{EffectRuntimeProvider:()=>EffectRuntimeProvider,QueryCache:()=>QueryCache,effectTask:()=>effectTask,fromEffect:()=>fromEffect,useEffectRuntime:()=>useEffectRuntime});import{assign,emit,setup}from"xstate";import{fromPromise}from"xstate";var unsettled=()=>Promise.race([]);var fromEffect=(run)=>fromPromise(async({input,signal})=>{try{const value=await input.runtime.runPromise(run(input),{signal});return signal.aborted?unsettled():value}catch(error){if(signal.aborted){return unsettled()}throw error}});var effectTask=(run)=>{const actors={run:fromEffect(({task})=>run(task))};return setup({actors}).createMachine({context:({input})=>({error:undefined,output:undefined,runtime:input.runtime}),id:"effectTask",initial:"idle",on:{RUN:{target:".running"}},states:{done:{},failed:{},idle:{},running:{entry:assign({error:undefined,output:undefined}),invoke:{input:({context,event})=>({runtime:context.runtime,task:event.input}),onDone:{actions:[assign({output:({event})=>event.output}),emit(({event})=>({output:event.output,type:"done"}))],target:"done"},onError:{actions:[assign({error:({event})=>event.error}),emit(({event})=>({error:event.error,type:"failed"}))],target:"failed"},src:"run"},on:{RUN:{}}}}})};import{CiError,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import{isCancelledError,QueryObserver}from"@tanstack/react-query";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Layer from"effect/Layer";class QueryCache extends Context.Service()("@collective-intelligence/external-apps-client-sdk-react/QueryCache"){}var make=(queryClient)=>{const fetchExit=async({query,...options},context)=>{try{return Exit.succeed(await queryClient.fetchQuery({...options,queryFn:({signal})=>Effect.runPromiseWith(context)(query,{signal}),retry:false}))}catch(error){if(isCancelledError(error)){return Exit.interrupt()}return error instanceof CiError||error instanceof CiTransportError?Exit.fail(error):Exit.die(error)}};const waitOn=(queryKey)=>Effect.sync(()=>new QueryObserver(queryClient,{enabled:false,queryKey}).subscribe(constVoid));return QueryCache.of({cancel:(queryKey)=>Effect.promise(()=>queryClient.cancelQueries({queryKey})),fetch:(options)=>Effect.flatMap(Effect.context(),(context)=>Effect.acquireUseRelease(waitOn(options.queryKey),()=>Effect.flatten(Effect.promise(()=>fetchExit(options,context))),(stopWaiting)=>Effect.sync(stopWaiting))),invalidate:(queryKey)=>Effect.promise(()=>queryClient.invalidateQueries({queryKey})),remove:(queryKey)=>Effect.sync(()=>{queryClient.removeQueries({queryKey})}),setData:(queryKey,data)=>Effect.sync(()=>{queryClient.setQueryData(queryKey,data)}),update:(queryKey,updater)=>Effect.sync(()=>{queryClient.setQueriesData({queryKey},updater)})})};var layer=(queryClient)=>Layer.succeed(QueryCache,make(queryClient));import{useQueryClient}from"@tanstack/react-query";import*as ManagedRuntime from"effect/ManagedRuntime";import{createContext,useContext,useMemo}from"react";import{jsx}from"react/jsx-runtime";var RuntimeContext=createContext(null);var EffectRuntimeProvider=({children})=>{const queryClient=useQueryClient();const runtime=useMemo(()=>ManagedRuntime.make(layer(queryClient)),[queryClient]);return jsx(RuntimeContext.Provider,{value:runtime,children})};var useEffectRuntime=()=>{const runtime=useContext(RuntimeContext);if(runtime===null){throw new Error("useEffectRuntime requires an EffectRuntimeProvider")}return runtime};var{EffectRuntimeProvider:EffectRuntimeProvider2,QueryCache:QueryCache2,effectTask:effectTask2,fromEffect:fromEffect2,useEffectRuntime:useEffectRuntime2}=exports_effect;export{EffectRuntimeProvider2 as EffectRuntimeProvider,QueryCache2 as QueryCache,effectTask2 as effectTask,fromEffect2 as fromEffect,useEffectRuntime2 as useEffectRuntime};
package/docs/effect.md CHANGED
@@ -21,6 +21,11 @@ is an actor; each actor is a `fromEffect` actor.
21
21
  `CiTransportError` stay typed errors; another failure is a defect.
22
22
  - `invalidate(queryKey)` marks values stale and refetches the ones that
23
23
  views show.
24
+ - `cancel(queryKey)` cancels the running fetches and interrupts their
25
+ queries, so they write no value. It keeps the cached values and starts no
26
+ fetch: a view of a key whose first fetch it cancels shows no value until
27
+ the next fetch. A `fetch` that waits on a cancelled key returns the cached value,
28
+ or is interrupted when the key has no value.
24
29
  - `setData(queryKey, value)` writes a value that views show at once.
25
30
  - `update(queryKey, (current) => next)` replaces each cached value with the
26
31
  result of the function for its current value, without a refetch, for example
@@ -28,13 +33,14 @@ is an actor; each actor is a `fromEffect` actor.
28
33
  an entry without a value; an `undefined` result keeps the value. A key
29
34
  that the cache does not hold stays absent. Each key under `queryKey`
30
35
  must hold a value of the type that the function takes. A running fetch
31
- is not cancelled and can replace the new value when it ends.
36
+ is not cancelled and can replace the new value when it ends: `cancel`
37
+ first.
32
38
  - `remove(queryKey)` removes the cached entries without a refetch, for
33
39
  example at sign-out. It cancels a running fetch of a removed key; the
34
40
  next `fetch` runs its query. A mounted view of a removed key keeps its
35
41
  last result until it renders again, so remove at sign-out before or as
36
42
  the views of the user unmount.
37
- - `invalidate`, `update` and `remove` apply to `queryKey` and to each key
43
+ - `invalidate`, `cancel`, `update` and `remove` apply to `queryKey` and to each key
38
44
  below it: `["crm", "lead"]` matches `["crm", "lead", "7"]`, not
39
45
  `["crm", "leads"]` or `["crm"]`. `setData` writes `queryKey` only.
40
46
  - Views read the same keys with `useQuery`.
@@ -97,6 +103,41 @@ const LeadEditor = ({ id }: { id: string }) => {
97
103
  }
98
104
  ```
99
105
 
106
+ ### Optimistic write
107
+
108
+ An optimistic write shows its value before CI answers. In its actor: `cancel`
109
+ the keys that it changes, so that a fetch that ends later does not replace the
110
+ new value; `update` them; run the write; and `invalidate` the keys when the
111
+ actor ends, also when it fails or is interrupted, so views read CI's value.
112
+
113
+ ```ts
114
+ const saveFollowing = fromEffect(
115
+ (
116
+ input: Readonly<{
117
+ following: boolean
118
+ id: string
119
+ runtime: EffectRunner<QueryCache>
120
+ }>
121
+ ) =>
122
+ QueryCache.use((cache) => {
123
+ const queryKey = ["crm", "lead", input.id]
124
+ return cache
125
+ .cancel(queryKey)
126
+ .pipe(
127
+ Effect.andThen(
128
+ cache.update<Lead>(queryKey, (lead) =>
129
+ lead === undefined
130
+ ? undefined
131
+ : { ...lead, following: input.following }
132
+ )
133
+ ),
134
+ Effect.andThen(writeFollowing(input.id, input.following)),
135
+ Effect.ensuring(cache.invalidate(queryKey))
136
+ )
137
+ })
138
+ )
139
+ ```
140
+
100
141
  ## Rules
101
142
 
102
143
  - Make each side-effect actor with `fromEffect`. The
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-client-sdk-react",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
4
4
  "description": "React bindings for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -57,7 +57,7 @@
57
57
  "effect": "^4.1.0",
58
58
  "react": ">=18.2 <20",
59
59
  "react-dom": ">=18.2 <20",
60
- "xstate": "^5.32.6"
60
+ "xstate": "^5.33.3"
61
61
  },
62
62
  "publishConfig": {
63
63
  "access": "public"
@@ -88,5 +88,5 @@
88
88
  "vitest": "4.1.10",
89
89
  "xstate": "5.33.3"
90
90
  },
91
- "gitHead": "5e694db7a00e52f9be053815a39cafd7418e56cf"
91
+ "gitHead": "6eb615293703ba8e92c566d40ce637fcd6adf7d7"
92
92
  }
@@ -25,7 +25,10 @@ Reference: [effect.md](../../docs/effect.md), [errors.md](../../docs/errors.md).
25
25
  4. **Move API data to `QueryCache`.** Read with `cache.fetch({ queryKey, query })`;
26
26
  after a write, `cache.invalidate(queryKey)`, `cache.setData`,
27
27
  `cache.update(queryKey, updater)` for a change from the current value, or
28
- `cache.remove(queryKey)` at sign-out. Views read the same keys with
28
+ `cache.remove(queryKey)` at sign-out. Before an optimistic `update`, call
29
+ `cache.cancel(queryKey)`, so that a running fetch does not replace the new
30
+ value; remove a query function that returns the cached value while a write
31
+ is pending, if the app has one for this reason. Views read the same keys with
29
32
  `useQuery`. Remove the API data and the QueryClient from machine context
30
33
  and input. Done when machine context holds flow state only.
31
34
  5. **Empty the views.** Move each `fetch` and Effect run of a view into an