@collective-intelligence/external-apps-client-sdk-react 0.2.9 → 0.2.10
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 +2 -1
- package/README.md +8 -4
- package/dist/effect.d.ts +13 -2
- package/dist/effect.js +1 -1
- package/docs/effect.md +43 -2
- package/package.json +2 -2
- package/skills/client-sdk-react-move-to-effect/SKILL.md +4 -1
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.
|
|
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
|
|
275
|
-
|
|
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
|
@@ -102,11 +102,22 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
|
|
|
102
102
|
/**
|
|
103
103
|
* The fresh cached value of `queryKey`, or the value of one run of `query`,
|
|
104
104
|
* then cached. When the last view or caller of the key stops waiting, or
|
|
105
|
-
* TanStack Query cancels the key, `query` is interrupted.
|
|
105
|
+
* `cancel` or TanStack Query cancels the key, `query` is interrupted. After
|
|
106
|
+
* a cancel, the caller gets the cached value of the key, or an interruption
|
|
107
|
+
* when the key holds no value.
|
|
106
108
|
*/
|
|
107
109
|
fetch: <Data>(options: QueryCacheFetchOptions<Data>) => Effect.Effect<Data, CiError | CiTransportError>;
|
|
108
110
|
/** Marks the values of `queryKey` and of the keys below it stale, and refetches the ones that views show. */
|
|
109
111
|
invalidate: (queryKey: QueryKey) => Effect.Effect<void>;
|
|
112
|
+
/**
|
|
113
|
+
* Cancels the running fetches of `queryKey` and of the keys below it and
|
|
114
|
+
* interrupts their queries, so these fetches write no value. Keeps the
|
|
115
|
+
* cached values and starts no fetch, so a view of a key whose first fetch
|
|
116
|
+
* it cancels shows no value until the next fetch. Call it before an
|
|
117
|
+
* optimistic `update`, so that a fetch that ends later does not replace the
|
|
118
|
+
* new value, and `invalidate` when the write ends.
|
|
119
|
+
*/
|
|
120
|
+
cancel: (queryKey: QueryKey) => Effect.Effect<void>;
|
|
110
121
|
/** Caches `data` as the value of `queryKey`; views show it at once. */
|
|
111
122
|
setData: <Data>(queryKey: QueryKey, data: Data) => Effect.Effect<void>;
|
|
112
123
|
/**
|
|
@@ -116,7 +127,7 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
|
|
|
116
127
|
* without a value, and its `undefined` result keeps the value. Keys that the
|
|
117
128
|
* cache does not hold stay absent. Each key below `queryKey` must hold a
|
|
118
129
|
* `Data` value. A running fetch is not cancelled, and its value replaces the
|
|
119
|
-
* new value when it ends.
|
|
130
|
+
* new value when it ends; call `cancel` first to keep the new value.
|
|
120
131
|
*/
|
|
121
132
|
update: <Data>(queryKey: QueryKey, updater: (current: Data | undefined) => Data | undefined) => Effect.Effect<void>;
|
|
122
133
|
/**
|
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.
|
|
3
|
+
"version": "0.2.10",
|
|
4
4
|
"description": "React bindings for Collective Intelligence external applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -88,5 +88,5 @@
|
|
|
88
88
|
"vitest": "4.1.10",
|
|
89
89
|
"xstate": "5.33.3"
|
|
90
90
|
},
|
|
91
|
-
"gitHead": "
|
|
91
|
+
"gitHead": "7972d94333f423906752b69ac20d4ffc44e5d841"
|
|
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.
|
|
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
|