@collective-intelligence/extensions-sdk-frontend-react 0.2.5 → 0.2.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/AGENTS.md CHANGED
@@ -17,6 +17,9 @@ the full API.
17
17
  write calls `QueryCache.cancel` on its keys before `update`, and
18
18
  `invalidate` when the write settles. Mount
19
19
  `EffectRuntimeProvider` at the root of each widget.
20
+ - Test machines with `makeTestQueryCache()` of `/effect`, never with a double
21
+ made with `QueryCache.of`. Seed its `queryClient`, then assert on its
22
+ entries or on `calls`.
20
23
  - Call the Studio API from Effect code through `StudioApi`. A Studio Widget
21
24
  gives `layerStudioApi()` no base URL: the Studio Host binds the client.
22
25
  - Decode `StudioApiError.body` with a Schema before use; it is `unknown`.
package/README.md CHANGED
@@ -315,6 +315,14 @@ and after the write the actor refreshes the reads through `QueryCache`.
315
315
  `update`, runs the write, and calls `invalidate` when the write settles. The
316
316
  Host and all widgets share one `QueryClient`, so start each key with the
317
317
  package name.
318
+ - `makeTestQueryCache(options?)` gives a machine test the `QueryCache` over a
319
+ real `QueryClient` of its own: `layer` for `ManagedRuntime.make`,
320
+ `queryClient` to seed and to assert on, and `calls`, one
321
+ `{ member, queryKey }` for each call that ran. `options.overrides` replaces
322
+ only the members that it names; `options.seed` holds the first entries.
323
+ Test with it, never with a double made with `QueryCache.of({ ... })`, which
324
+ breaks each time `QueryCache` gets a member. It adds no dependency, and a
325
+ widget bundle that does not import it does not contain it.
318
326
 
319
327
  ```tsx
320
328
  import type { EffectRunner } from "@collective-intelligence/extensions-sdk-frontend-react/effect"
@@ -0,0 +1,43 @@
1
+ import type { QueryKey } from "@tanstack/react-query";
2
+ import { QueryClient } from "@tanstack/react-query";
3
+ import * as Layer from "effect/Layer";
4
+ import { QueryCache } from "./query-cache";
5
+ /** One call of a `QueryCache` member, as the test layer logs it when it runs. */
6
+ export type QueryCacheCall = Readonly<{
7
+ member: keyof QueryCache["Service"];
8
+ /** The key of the call; for `fetch`, the `queryKey` of its options. */
9
+ queryKey: QueryKey;
10
+ }>;
11
+ export type TestQueryCacheOptions = Readonly<{
12
+ /**
13
+ * Replaces these members only. Each other member works on the
14
+ * `QueryClient`, also members that a later SDK release adds.
15
+ */
16
+ overrides?: Partial<QueryCache["Service"]>;
17
+ /**
18
+ * The `QueryClient` under the cache. Without it, a new one that keeps its
19
+ * entries until the test ends (`gcTime: Infinity`); a `QueryClient` that
20
+ * the test passes keeps its own `gcTime`.
21
+ */
22
+ queryClient?: QueryClient;
23
+ /** Values that the `QueryClient` holds before the test runs. */
24
+ seed?: readonly (readonly [queryKey: QueryKey, data: unknown])[];
25
+ }>;
26
+ export type TestQueryCache = Readonly<{
27
+ /** The calls of the members, in the order that they ran. */
28
+ calls: readonly QueryCacheCall[];
29
+ /** Provides the `QueryCache` of `./effect`, as `EffectRuntimeProvider` does. */
30
+ layer: Layer.Layer<QueryCache>;
31
+ /** The `QueryClient` under the cache: seed it and read it in assertions. */
32
+ queryClient: QueryClient;
33
+ }>;
34
+ /**
35
+ * The `QueryCache` of a test, over a real `QueryClient`: each member works as
36
+ * in the app, including key prefixes, `cancel` and `remove`. Give the `layer`
37
+ * to `ManagedRuntime.make` for the `runtime` of a machine input, then assert
38
+ * on `queryClient` or on `calls`. A test overrides only the members that it
39
+ * must control, so a member that a later release adds does not break it, as
40
+ * it breaks a double made with `QueryCache.of`. Each test makes its own: the
41
+ * Studio Host shares one `QueryClient` with every widget, a test does not.
42
+ */
43
+ export declare const makeTestQueryCache: (options?: TestQueryCacheOptions) => TestQueryCache;
@@ -98,6 +98,47 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
98
98
  */
99
99
  export declare class QueryCache extends QueryCache_base {
100
100
  }
101
+ /** The `QueryCache` over `queryClient`. */
102
+ export declare const make: (queryClient: QueryClient) => Readonly<{
103
+ /**
104
+ * The fresh cached value of `queryKey`, or the value of one run of `query`,
105
+ * then cached. When the last view or caller of the key stops waiting, or
106
+ * `cancel` or TanStack Query cancels the key, `query` is interrupted. After
107
+ * a cancel, the caller gets the cached value of the key, or an interruption
108
+ * when the key holds no value.
109
+ */
110
+ fetch: <Data>(options: QueryCacheFetchOptions<Data>) => Effect.Effect<Data, StudioApiError | StudioApiTransportError>;
111
+ /** Marks the values of `queryKey` and of the keys below it stale, and refetches the ones that views show. */
112
+ invalidate: (queryKey: QueryKey) => Effect.Effect<void>;
113
+ /**
114
+ * Cancels the running fetches of `queryKey` and of the keys below it and
115
+ * interrupts their queries, so these fetches write no value. Keeps the
116
+ * cached values and starts no fetch, so a view of a key whose first fetch
117
+ * it cancels shows no value until the next fetch. Call it before an
118
+ * optimistic `update`, so that a fetch that ends later does not replace the
119
+ * new value, and `invalidate` when the write ends.
120
+ */
121
+ cancel: (queryKey: QueryKey) => Effect.Effect<void>;
122
+ /** Caches `data` as the value of `queryKey`; views show it at once. */
123
+ setData: <Data>(queryKey: QueryKey, data: Data) => Effect.Effect<void>;
124
+ /**
125
+ * Replaces the cached value of `queryKey` and of each cached key below it
126
+ * with the result of `updater` for its current value, without a refetch;
127
+ * views show the new values at once. `updater` gets `undefined` for an entry
128
+ * without a value, and its `undefined` result keeps the value. Keys that the
129
+ * cache does not hold stay absent. Each key below `queryKey` must hold a
130
+ * `Data` value. A running fetch is not cancelled, and its value replaces the
131
+ * new value when it ends; call `cancel` first to keep the new value.
132
+ */
133
+ update: <Data>(queryKey: QueryKey, updater: (current: Data | undefined) => Data | undefined) => Effect.Effect<void>;
134
+ /**
135
+ * Removes the entries of `queryKey` and of the keys below it from the cache,
136
+ * without a refetch, and cancels a running fetch of a removed key. The next
137
+ * fetch of a removed key runs its query. A mounted view of a removed key
138
+ * keeps its last result until it renders again.
139
+ */
140
+ remove: (queryKey: QueryKey) => Effect.Effect<void>;
141
+ }>;
101
142
  /** A layer of the `QueryCache` over `queryClient`. */
102
143
  export declare const layer: (queryClient: QueryClient) => Layer.Layer<QueryCache, never, never>;
103
144
  export {};
package/dist/effect.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export { StudioApiError, StudioApiTransportError } from "./errors.js";
2
2
  export { fromEffect } from "./effect/effect-runtime/from-effect.js";
3
3
  export { QueryCache } from "./effect/effect-runtime/query-cache.js";
4
+ export { makeTestQueryCache } from "./effect/effect-runtime/query-cache-testing.js";
4
5
  export { EffectRuntimeProvider, useEffectRuntime } from "./effect/effect-runtime/runtime-provider.js";
5
6
  export { StudioApi, layer as layerStudioApi, layerConfig as layerStudioApiConfig } from "./effect/studio-api/service.js";
6
7
  export type { EffectRunner } from "./effect/effect-runtime/from-effect.js";
7
8
  export type { QueryCacheFetchOptions } from "./effect/effect-runtime/query-cache.js";
9
+ export type { QueryCacheCall, TestQueryCache, TestQueryCacheOptions } from "./effect/effect-runtime/query-cache-testing.js";
8
10
  export type { StudioApiOperation, StudioApiOperationName, StudioApiOptions, StudioApiRequest, StudioApiSuccess, StudioApiValue } from "./effect/studio-api/service.js";
package/dist/effect.js CHANGED
@@ -1 +1 @@
1
- import*as n from"effect/Schema";class c extends n.TaggedError()("StudioApiError",{body:n.Unknown,status:n.Int}){}class f extends n.TaggedError()("StudioApiTransportError",{cause:n.Defect()}){}import{fromPromise as Q}from"xstate";var w=()=>Promise.race([]),v=(r)=>Q(async({input:a,signal:i})=>{try{let e=await a.runtime.runPromise(r(a),{signal:i});return i.aborted?w():e}catch(e){if(i.aborted)return w();throw e}});import{isCancelledError as L,QueryObserver as I}from"@tanstack/react-query";import*as D from"effect/Context";import*as o from"effect/Effect";import*as u from"effect/Exit";import{constVoid as N}from"effect/Function";import*as h from"effect/Layer";class l extends D.Service()("@collective-intelligence/extensions-sdk-frontend-react/QueryCache"){}var W=(r)=>{let a=async({query:e,...t},S)=>{try{return u.succeed(await r.fetchQuery({...t,queryFn:({signal:s})=>o.runPromiseWith(S)(e,{signal:s}),retry:!1}))}catch(s){if(L(s))return u.interrupt();return s instanceof c||s instanceof f?u.fail(s):u.die(s)}},i=(e)=>o.sync(()=>new I(r,{enabled:!1,queryKey:e}).subscribe(N));return l.of({cancel:(e)=>o.promise(()=>r.cancelQueries({queryKey:e})),fetch:(e)=>o.flatMap(o.context(),(t)=>o.acquireUseRelease(i(e.queryKey),()=>o.flatten(o.promise(()=>a(e,t))),(S)=>o.sync(S))),invalidate:(e)=>o.promise(()=>r.invalidateQueries({queryKey:e})),remove:(e)=>o.sync(()=>{r.removeQueries({queryKey:e})}),setData:(e,t)=>o.sync(()=>{r.setQueryData(e,t)}),update:(e,t)=>o.sync(()=>{r.setQueriesData({queryKey:e},t)})})},x=(r)=>h.succeed(l,W(r));import{useQueryClient as M}from"@tanstack/react-query";import*as g from"effect/ManagedRuntime";import{createContext as q,useContext as U,useMemo as P}from"react";import{jsx as F}from"react/jsx-runtime";var V=q(null),K=({children:r})=>{let a=M(),i=P(()=>g.make(x(a)),[a]);return F(V.Provider,{value:i,children:r})},T=()=>{let r=U(V);if(r===null)throw Error("useEffectRuntime requires an EffectRuntimeProvider");return r};import{client as j,studioAgentRunsGet as z,studioAgentRunsList as B,studioViewDataGetItem as H,studioViewDataSearch as J,studioViewDataSearchMembers as X,studioViewDataUpdateItem as Y,studioWorkflowRunsGet as Z,studioWorkflowRunsList as _}from"@collective-intelligence/extensions-sdk-frontend-react/studio-api";import*as G from"effect/Config";import*as k from"effect/Context";import*as m from"effect/Effect";import*as y from"effect/Layer";class E extends k.Service()("@collective-intelligence/extensions-sdk-frontend-react/StudioApi"){}var ee=(r={})=>{let a=r.baseUrl===void 0?{}:{baseUrl:r.baseUrl},i=(e,t)=>m.fn(`StudioApi.${e}`)(function*(s){let R=!1,A=j.getConfig().fetch??globalThis.fetch,C=Object.assign(async(p,b)=>(R=!0,await A(p,b)),A),d=yield*m.tryPromise({catch:(p)=>{if(R)return new f({cause:p});throw p},try:(p)=>t(s,{...a,fetch:C,responseStyle:"fields",signal:p,throwOnError:!1})});if(d.response===void 0)return yield*new f({cause:d.error});if(!d.response.ok)return yield*new c({body:d.error,status:d.response.status});return d.data});return E.of({studioAgentRunsGet:i("studioAgentRunsGet",(e,t)=>z({...e,...t})),studioAgentRunsList:i("studioAgentRunsList",(e,t)=>B({...e,...t})),studioViewDataGetItem:i("studioViewDataGetItem",(e,t)=>H({...e,...t})),studioViewDataSearch:i("studioViewDataSearch",(e,t)=>J({...e,...t})),studioViewDataSearchMembers:i("studioViewDataSearchMembers",(e,t)=>X({...e,...t})),studioViewDataUpdateItem:i("studioViewDataUpdateItem",(e,t)=>Y({...e,...t})),studioWorkflowRunsGet:i("studioWorkflowRunsGet",(e,t)=>Z({...e,...t})),studioWorkflowRunsList:i("studioWorkflowRunsList",(e,t)=>_({...e,...t}))})},O=(r={})=>y.sync(E,()=>ee(r)),te=(r)=>y.unwrap(m.map(G.unwrap(r),O));export{K as EffectRuntimeProvider,l as QueryCache,E as StudioApi,c as StudioApiError,f as StudioApiTransportError,v as fromEffect,O as layerStudioApi,te as layerStudioApiConfig,T as useEffectRuntime};
1
+ import*as c from"effect/Schema";class l extends c.TaggedError()("StudioApiError",{body:c.Unknown,status:c.Int}){}class d extends c.TaggedError()("StudioApiTransportError",{cause:c.Defect()}){}import{fromPromise as I}from"xstate";var w=()=>Promise.race([]),q=(o)=>I(async({input:s,signal:a})=>{try{let e=await s.runtime.runPromise(o(s),{signal:a});return a.aborted?w():e}catch(e){if(a.aborted)return w();throw e}});import{isCancelledError as N,QueryObserver as T}from"@tanstack/react-query";import*as D from"effect/Context";import*as i from"effect/Effect";import*as f from"effect/Exit";import{constVoid as W}from"effect/Function";import*as x from"effect/Layer";class p extends D.Service()("@collective-intelligence/extensions-sdk-frontend-react/QueryCache"){}var A=(o)=>{let s=async({query:e,...r},n)=>{try{return f.succeed(await o.fetchQuery({...r,queryFn:({signal:t})=>i.runPromiseWith(n)(e,{signal:t}),retry:!1}))}catch(t){if(N(t))return f.interrupt();return t instanceof l||t instanceof d?f.fail(t):f.die(t)}},a=(e)=>i.sync(()=>new T(o,{enabled:!1,queryKey:e}).subscribe(W));return p.of({cancel:(e)=>i.promise(()=>o.cancelQueries({queryKey:e})),fetch:(e)=>i.flatMap(i.context(),(r)=>i.acquireUseRelease(a(e.queryKey),()=>i.flatten(i.promise(()=>s(e,r))),(n)=>i.sync(n))),invalidate:(e)=>i.promise(()=>o.invalidateQueries({queryKey:e})),remove:(e)=>i.sync(()=>{o.removeQueries({queryKey:e})}),setData:(e,r)=>i.sync(()=>{o.setQueryData(e,r)}),update:(e,r)=>i.sync(()=>{o.setQueriesData({queryKey:e},r)})})},C=(o)=>x.succeed(p,A(o));import{QueryClient as M}from"@tanstack/react-query";import*as Q from"effect/Effect";import*as g from"effect/Layer";var U=(o={})=>{let s=o.queryClient??new M({defaultOptions:{queries:{gcTime:1/0}}});for(let[t,u]of o.seed??[])s.setQueryData(t,u);let a=A(s),e=o.overrides??{},r=[],n=(t,u,E)=>Q.suspend(()=>(r.push({member:t,queryKey:u}),E()));return{calls:r,layer:g.succeed(p,p.of({cancel:(t)=>n("cancel",t,()=>(e.cancel??a.cancel)(t)),fetch:(t)=>n("fetch",t.queryKey,()=>(e.fetch??a.fetch)(t)),invalidate:(t)=>n("invalidate",t,()=>(e.invalidate??a.invalidate)(t)),remove:(t)=>n("remove",t,()=>(e.remove??a.remove)(t)),setData:(t,u)=>n("setData",t,()=>(e.setData??a.setData)(t,u)),update:(t,u)=>n("update",t,()=>(e.update??a.update)(t,u))})),queryClient:s}};import{useQueryClient as K}from"@tanstack/react-query";import*as V from"effect/ManagedRuntime";import{createContext as P,useContext as F,useMemo as j}from"react";import{jsx as H}from"react/jsx-runtime";var v=P(null),z=({children:o})=>{let s=K(),a=j(()=>V.make(C(s)),[s]);return H(v.Provider,{value:a,children:o})},B=()=>{let o=F(v);if(o===null)throw Error("useEffectRuntime requires an EffectRuntimeProvider");return o};import{client as J,studioAgentRunsGet as X,studioAgentRunsList as Y,studioViewDataGetItem as Z,studioViewDataSearch as _,studioViewDataSearchMembers as ee,studioViewDataUpdateItem as te,studioWorkflowRunsGet as re,studioWorkflowRunsList as oe}from"@collective-intelligence/extensions-sdk-frontend-react/studio-api";import*as k from"effect/Config";import*as G from"effect/Context";import*as S from"effect/Effect";import*as R from"effect/Layer";class h extends G.Service()("@collective-intelligence/extensions-sdk-frontend-react/StudioApi"){}var ae=(o={})=>{let s=o.baseUrl===void 0?{}:{baseUrl:o.baseUrl},a=(e,r)=>S.fn(`StudioApi.${e}`)(function*(t){let u=!1,E=J.getConfig().fetch??globalThis.fetch,L=Object.assign(async(y,b)=>(u=!0,await E(y,b)),E),m=yield*S.tryPromise({catch:(y)=>{if(u)return new d({cause:y});throw y},try:(y)=>r(t,{...s,fetch:L,responseStyle:"fields",signal:y,throwOnError:!1})});if(m.response===void 0)return yield*new d({cause:m.error});if(!m.response.ok)return yield*new l({body:m.error,status:m.response.status});return m.data});return h.of({studioAgentRunsGet:a("studioAgentRunsGet",(e,r)=>X({...e,...r})),studioAgentRunsList:a("studioAgentRunsList",(e,r)=>Y({...e,...r})),studioViewDataGetItem:a("studioViewDataGetItem",(e,r)=>Z({...e,...r})),studioViewDataSearch:a("studioViewDataSearch",(e,r)=>_({...e,...r})),studioViewDataSearchMembers:a("studioViewDataSearchMembers",(e,r)=>ee({...e,...r})),studioViewDataUpdateItem:a("studioViewDataUpdateItem",(e,r)=>te({...e,...r})),studioWorkflowRunsGet:a("studioWorkflowRunsGet",(e,r)=>re({...e,...r})),studioWorkflowRunsList:a("studioWorkflowRunsList",(e,r)=>oe({...e,...r}))})},O=(o={})=>R.sync(h,()=>ae(o)),ie=(o)=>R.unwrap(S.map(k.unwrap(o),O));export{z as EffectRuntimeProvider,p as QueryCache,h as StudioApi,l as StudioApiError,d as StudioApiTransportError,q as fromEffect,O as layerStudioApi,ie as layerStudioApiConfig,U as makeTestQueryCache,B as useEffectRuntime};
package/docs/effect.md CHANGED
@@ -151,6 +151,15 @@ const rename = fromEffect((input: RenameInput) =>
151
151
  `StudioApiError` or `StudioApiTransportError`. Another failure is a Defect.
152
152
  A cancel of the key interrupts the query; the waiting `fetch` then returns
153
153
  the cached value, or is interrupted when the key has no value.
154
+ - Test machines with `makeTestQueryCache(options?)`, never with a double made
155
+ with `QueryCache.of`: that double breaks when `QueryCache` gets a member.
156
+ Give its `layer` to `ManagedRuntime.make` for the machine input `runtime`.
157
+ Each member works on a real `QueryClient`, as in the Host. `options.seed`
158
+ holds the first entries and `options.overrides` replaces some members
159
+ only. Assert on the entries of its `queryClient`, so that a machine that
160
+ skips a call fails: after `remove`, `getQueryCache().findAll({ queryKey })`
161
+ is empty; after `invalidate`, `getQueryState(key)?.isInvalidated` is
162
+ `true`. `calls` holds `{ member, queryKey }` for each call that ran.
154
163
  - `QueryCache.cancel` cancels the running fetches and interrupts their
155
164
  queries, so they write no value. It keeps the cached values and starts no
156
165
  fetch: a view of a key whose first fetch it cancels shows no value until the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/extensions-sdk-frontend-react",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Public hosted React contribution contracts for Collective Intelligence extensions.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -125,5 +125,5 @@
125
125
  "@xstate/react": "6.1.0",
126
126
  "xstate": "5.33.3"
127
127
  },
128
- "gitHead": "6eb615293703ba8e92c566d40ce637fcd6adf7d7"
128
+ "gitHead": "651f2a1a48f0c82cd24c832378da8a664172a970"
129
129
  }