@collective-intelligence/extensions-sdk-frontend-react 0.2.2 → 0.2.3

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
@@ -7,10 +7,14 @@ the full API.
7
7
  ## Rules
8
8
 
9
9
  - Import each contribution kind from its subpath (`/studio`, `/dashboard`,
10
- `/workflow`, `/ui-react`, `/frontend`), and the `StudioApi` service from
11
- `/effect`.
10
+ `/workflow`, `/ui-react`, `/frontend`), and the `StudioApi` service and the
11
+ write parts (`fromEffect`, `EffectRuntimeProvider`, `useEffectRuntime`,
12
+ `QueryCache`) from `/effect`.
12
13
  - Keep one `effect` (`^4.1.0`) in the extension package. It is a required
13
- peer. `react` and `react-dom` come from the host.
14
+ peer. `react`, `react-dom` and `xstate` come from the host.
15
+ - Write in a `fromEffect` actor, never with `useMutation` or `fromPromise`;
16
+ after the write, refresh the reads through `QueryCache`. Mount
17
+ `EffectRuntimeProvider` at the root of each widget.
14
18
  - Call the Studio API from Effect code through `StudioApi`. A Studio Widget
15
19
  gives `layerStudioApi()` no base URL: the Studio Host binds the client.
16
20
  - Decode `StudioApiError.body` with a Schema before use; it is `unknown`.
@@ -18,7 +22,8 @@ the full API.
18
22
  ## Index
19
23
 
20
24
  - [docs/effect.md](docs/effect.md): read when a widget or view calls the
21
- Studio API from Effect, or you give the base URL of a test host.
25
+ Studio API from Effect, writes data, refreshes reads after a write, or you
26
+ give the base URL of a test host.
22
27
  - [docs/errors.md](docs/errors.md): read when you handle a failed Studio API
23
28
  call.
24
29
  - [skills/extensions-sdk-frontend-react-move-to-effect/SKILL.md](skills/extensions-sdk-frontend-react-move-to-effect/SKILL.md):
package/README.md CHANGED
@@ -9,7 +9,11 @@ React and React DOM are host-provided peers. The optional
9
9
 
10
10
  `effect` (`^4.1.0`) is a required peer: the app installs one copy of `effect`,
11
11
  and the package build keeps it external. The `/effect` entrypoint exports the
12
- `StudioApi` service; see [Studio API on Effect](#studio-api-on-effect).
12
+ `StudioApi` service; see [Studio API on Effect](#studio-api-on-effect). It
13
+ also exports `fromEffect`, `EffectRuntimeProvider`, `useEffectRuntime` and
14
+ `QueryCache`, the parts of a write in a Studio Widget; see
15
+ [Writes in a Studio Widget](#writes-in-a-studio-widget). They need the
16
+ required `xstate` peer, which the Studio and Dashboard Hosts provide.
13
17
 
14
18
  ```tsx
15
19
  import { declareFrontendCatalogContribution } from "@collective-intelligence/extensions-sdk-frontend"
@@ -282,6 +286,94 @@ the URL of its Backend. That URL is deployment configuration, so
282
286
  `layerStudioApiConfig({ baseUrl: Config.String("STUDIO_API_BASE_URL") })`
283
287
  reads it with Effect `Config`.
284
288
 
289
+ ### Writes in a Studio Widget
290
+
291
+ A Studio Widget follows the write convention of a detached app, and the
292
+ `ci-solution/effect-writes` and `ci-solution/effect-actors` lint rules apply to
293
+ it: a write runs in a `fromEffect` XState actor, views read with `useQuery`,
294
+ and after the write the actor refreshes the reads through `QueryCache`.
295
+ `/effect` exports these parts:
296
+
297
+ - `EffectRuntimeProvider` gives its tree an Effect runtime with the
298
+ `QueryCache` over the nearest `QueryClient`, which is the `QueryClient` of
299
+ the Studio Host. The Host mounts no Effect runtime. Each widget mounts
300
+ `EffectRuntimeProvider` at its root: the bundle of each widget has its own
301
+ copy of `/effect`, so it does not see the provider of another bundle.
302
+ - `useEffectRuntime()` gives that runtime. A view passes it to the machines it
303
+ starts, in their input.
304
+ - `fromEffect(run)` makes XState actor logic that runs the effect of `run` on
305
+ `input.runtime`. A stop of the actor interrupts the fiber; after a stop, no
306
+ result of that run gets to the actor, also in a React Strict Mode remount.
307
+ - `QueryCache` has `fetch`, `invalidate`, `setData`, `update` and `remove`.
308
+ `invalidate`, `update` and `remove` apply to the key and to each key below
309
+ it. `fetch` runs its query once, without a retry, and fails with
310
+ `StudioApiError` or `StudioApiTransportError`; another failure is a Defect,
311
+ and a cancel of the key is an interruption. The Host and all widgets share
312
+ one `QueryClient`, so start each key with the package name.
313
+
314
+ ```tsx
315
+ import type { EffectRunner } from "@collective-intelligence/extensions-sdk-frontend-react/effect"
316
+ import type { StudioViewContext } from "@collective-intelligence/extensions-sdk-frontend-react/studio"
317
+
318
+ import {
319
+ EffectRuntimeProvider,
320
+ fromEffect,
321
+ layerStudioApi,
322
+ QueryCache,
323
+ StudioApi
324
+ } from "@collective-intelligence/extensions-sdk-frontend-react/effect"
325
+ import { studioViewScope } from "@collective-intelligence/extensions-sdk-frontend-react/studio"
326
+ import * as Effect from "effect/Effect"
327
+ import { setup } from "xstate"
328
+
329
+ const customersKey = ["com.acme.crm", "customers"] as const
330
+
331
+ type RenameInput = Readonly<{
332
+ context: StudioViewContext
333
+ instanceId: string
334
+ name: string
335
+ runtime: EffectRunner<QueryCache>
336
+ }>
337
+
338
+ export const renameMachine = setup({
339
+ actors: {
340
+ rename: fromEffect((input: RenameInput) =>
341
+ Effect.gen(function* () {
342
+ const api = yield* StudioApi
343
+ const scope = studioViewScope(input.context)
344
+ yield* api.studioViewDataUpdateItem({
345
+ ...scope,
346
+ body: { name: input.name },
347
+ path: { ...scope.path, instanceId: input.instanceId }
348
+ })
349
+ const cache = yield* QueryCache
350
+ yield* cache.invalidate(customersKey)
351
+ }).pipe(Effect.provide(layerStudioApi()))
352
+ )
353
+ }
354
+ }).createMachine({/* states that invoke "rename" with the input above */})
355
+
356
+ // The widget root: the runtime is over the QueryClient of the Studio Host.
357
+ export const CustomersWidget = (props: CustomersViewProps) => (
358
+ <EffectRuntimeProvider>
359
+ <CustomersView {...props} />
360
+ </EffectRuntimeProvider>
361
+ )
362
+ ```
363
+
364
+ `xstate` (`^5.32.6`) is a required peer. The Studio and Dashboard Hosts provide
365
+ their one copy of `xstate`, and the `ci` CLI keeps `xstate` external in both
366
+ Hosts' artifacts, so a widget bundle carries no copy of XState. The first
367
+ Hosts that provide `xstate` ship in the first ci-app release after
368
+ `@collective-intelligence/cli@0.2.2`, together with the CLI that keeps it
369
+ external: a release built with that CLI or a later one runs on Hosts of that
370
+ ci-app release or a later one. A widget that uses `@xstate/react` bundles it;
371
+ it imports the Host copies of `react` and `xstate`.
372
+ Import XState only from `xstate`: the Host provides that one name, and a
373
+ release bundles a subpath such as `xstate/actors`, which is a second copy of
374
+ XState. The Host does not check the `xstate` version of a widget: build
375
+ against the `xstate` 5 that the Hosts ship.
376
+
285
377
  ## Building in the workspace
286
378
 
287
379
  This package needs the built `@collective-intelligence/ui-react` declarations
@@ -0,0 +1,14 @@
1
+ import type * as Effect from "effect/Effect";
2
+ import type * as ManagedRuntime from "effect/ManagedRuntime";
3
+ import type { PromiseActorLogic } from "xstate";
4
+ /** What runs an effect for an actor: a `ManagedRuntime` that provides `R`. */
5
+ export type EffectRunner<R> = Pick<ManagedRuntime.ManagedRuntime<R, never>, "runPromise">;
6
+ /**
7
+ * XState actor logic that runs the effect of `run` on the runtime of the actor
8
+ * input. The actor's output is the effect's value; a failure or a defect fails
9
+ * the actor. A stop of the actor interrupts the fiber, so its run settles.
10
+ * After the stop, no result of that run gets to the actor.
11
+ */
12
+ export declare const fromEffect: <A, E, R, I extends {
13
+ readonly runtime: EffectRunner<R>;
14
+ }>(run: (input: I) => Effect.Effect<A, E, R>) => PromiseActorLogic<A, I>;
@@ -0,0 +1,81 @@
1
+ import type { QueryClient, QueryKey } from "@tanstack/react-query";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import { StudioApiError, StudioApiTransportError } from "../../errors";
6
+ export type QueryCacheFetchOptions<Data> = Readonly<{
7
+ queryKey: QueryKey;
8
+ /** Runs when the cache holds no fresh value for `queryKey`. */
9
+ query: Effect.Effect<Data, StudioApiError | StudioApiTransportError>;
10
+ /** Milliseconds for which a cached value stays fresh; without it, the QueryClient default applies. */
11
+ staleTime?: number;
12
+ }>;
13
+ export type QueryCacheValue = Readonly<{
14
+ /**
15
+ * The fresh cached value of `queryKey`, or the value of one run of `query`,
16
+ * then cached. When the last view or caller of the key stops waiting, or
17
+ * TanStack Query cancels the key, `query` is interrupted.
18
+ */
19
+ fetch: <Data>(options: QueryCacheFetchOptions<Data>) => Effect.Effect<Data, StudioApiError | StudioApiTransportError>;
20
+ /** Marks the values of `queryKey` and of the keys below it stale, and refetches the ones that views show. */
21
+ invalidate: (queryKey: QueryKey) => Effect.Effect<void>;
22
+ /** Caches `data` as the value of `queryKey`; views show it at once. */
23
+ setData: <Data>(queryKey: QueryKey, data: Data) => Effect.Effect<void>;
24
+ /**
25
+ * Replaces the cached value of `queryKey` and of each cached key below it
26
+ * with the result of `updater` for its current value, without a refetch;
27
+ * views show the new values at once. `updater` gets `undefined` for an entry
28
+ * without a value, and its `undefined` result keeps the value. Keys that the
29
+ * cache does not hold stay absent. Each key below `queryKey` must hold a
30
+ * `Data` value. A running fetch is not cancelled, and its value replaces the
31
+ * new value when it ends.
32
+ */
33
+ update: <Data>(queryKey: QueryKey, updater: (current: Data | undefined) => Data | undefined) => Effect.Effect<void>;
34
+ /**
35
+ * Removes the entries of `queryKey` and of the keys below it from the cache,
36
+ * without a refetch, and cancels a running fetch of a removed key. The next
37
+ * fetch of a removed key runs its query. A mounted view of a removed key
38
+ * keeps its last result until it renders again.
39
+ */
40
+ remove: (queryKey: QueryKey) => Effect.Effect<void>;
41
+ }>;
42
+ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-intelligence/extensions-sdk-frontend-react/QueryCache", Readonly<{
43
+ /**
44
+ * The fresh cached value of `queryKey`, or the value of one run of `query`,
45
+ * then cached. When the last view or caller of the key stops waiting, or
46
+ * TanStack Query cancels the key, `query` is interrupted.
47
+ */
48
+ fetch: <Data>(options: QueryCacheFetchOptions<Data>) => Effect.Effect<Data, StudioApiError | StudioApiTransportError>;
49
+ /** Marks the values of `queryKey` and of the keys below it stale, and refetches the ones that views show. */
50
+ invalidate: (queryKey: QueryKey) => Effect.Effect<void>;
51
+ /** Caches `data` as the value of `queryKey`; views show it at once. */
52
+ setData: <Data>(queryKey: QueryKey, data: Data) => Effect.Effect<void>;
53
+ /**
54
+ * Replaces the cached value of `queryKey` and of each cached key below it
55
+ * with the result of `updater` for its current value, without a refetch;
56
+ * views show the new values at once. `updater` gets `undefined` for an entry
57
+ * without a value, and its `undefined` result keeps the value. Keys that the
58
+ * cache does not hold stay absent. Each key below `queryKey` must hold a
59
+ * `Data` value. A running fetch is not cancelled, and its value replaces the
60
+ * new value when it ends.
61
+ */
62
+ update: <Data>(queryKey: QueryKey, updater: (current: Data | undefined) => Data | undefined) => Effect.Effect<void>;
63
+ /**
64
+ * Removes the entries of `queryKey` and of the keys below it from the cache,
65
+ * without a refetch, and cancels a running fetch of a removed key. The next
66
+ * fetch of a removed key runs its query. A mounted view of a removed key
67
+ * keeps its last result until it renders again.
68
+ */
69
+ remove: (queryKey: QueryKey) => Effect.Effect<void>;
70
+ }>>;
71
+ /**
72
+ * The remote data of the Studio Host's `QueryClient`, as the machine actors of
73
+ * a Studio Widget read and write it. Views read the same entries with
74
+ * `useQuery`. The Host shares this `QueryClient` with every widget, so a
75
+ * widget starts its keys with its package name.
76
+ */
77
+ export declare class QueryCache extends QueryCache_base {
78
+ }
79
+ /** A layer of the `QueryCache` over `queryClient`. */
80
+ export declare const layer: (queryClient: QueryClient) => Layer.Layer<QueryCache, never, never>;
81
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { ReactNode } from "react";
2
+ import type { EffectRunner } from "./from-effect";
3
+ import type { QueryCache } from "./query-cache";
4
+ /**
5
+ * Gives its tree an Effect runtime with the `QueryCache` over the nearest
6
+ * `QueryClient`; in a Studio Widget, that is the `QueryClient` of the Studio
7
+ * Host. A widget mounts the provider at its root, because the bundle of each
8
+ * widget has its own copy of `./effect`. A view passes the runtime to the
9
+ * machines it starts, in their input. The runtime holds no resource, so the
10
+ * provider never disposes it: a Strict Mode remount and a machine that keeps
11
+ * it stay valid.
12
+ */
13
+ export declare const EffectRuntimeProvider: ({ children }: Readonly<{
14
+ children: ReactNode;
15
+ }>) => import("react").JSX.Element;
16
+ /** The runtime of the nearest `EffectRuntimeProvider`. */
17
+ export declare const useEffectRuntime: () => EffectRunner<QueryCache>;
package/dist/effect.d.ts CHANGED
@@ -1,3 +1,8 @@
1
1
  export { StudioApiError, StudioApiTransportError } from "./errors.js";
2
+ export { fromEffect } from "./effect/effect-runtime/from-effect.js";
3
+ export { QueryCache } from "./effect/effect-runtime/query-cache.js";
4
+ export { EffectRuntimeProvider, useEffectRuntime } from "./effect/effect-runtime/runtime-provider.js";
2
5
  export { StudioApi, layer as layerStudioApi, layerConfig as layerStudioApiConfig } from "./effect/studio-api/service.js";
6
+ export type { EffectRunner } from "./effect/effect-runtime/from-effect.js";
7
+ export type { QueryCacheFetchOptions } from "./effect/effect-runtime/query-cache.js";
3
8
  export type { StudioApiOperation, StudioApiOperationName, StudioApiOptions, StudioApiRequest, StudioApiSuccess, StudioApiValue } from "./effect/studio-api/service.js";
package/dist/effect.js CHANGED
@@ -1 +1 @@
1
- import*as o from"effect/Schema";class d extends o.TaggedError()("StudioApiError",{body:o.Unknown,status:o.Int}){}class n extends o.TaggedError()("StudioApiTransportError",{cause:o.Defect()}){}import{client as g,studioAgentRunsGet as y,studioAgentRunsList as h,studioViewDataGetItem as E,studioViewDataSearch as G,studioViewDataSearchMembers as k,studioViewDataUpdateItem as O,studioWorkflowRunsGet as x,studioWorkflowRunsList as L}from"@collective-intelligence/extensions-sdk-frontend-react/studio-api";import*as f from"effect/Config";import*as c from"effect/Context";import*as u from"effect/Effect";import*as p from"effect/Layer";class S extends c.Service()("@collective-intelligence/extensions-sdk-frontend-react/StudioApi"){}var N=(s={})=>{let w=s.baseUrl===void 0?{}:{baseUrl:s.baseUrl},i=(t,e)=>u.fn(`StudioApi.${t}`)(function*(A){let l=!1,m=g.getConfig().fetch??globalThis.fetch,D=Object.assign(async(r,V)=>(l=!0,await m(r,V)),m),a=yield*u.tryPromise({catch:(r)=>{if(l)return new n({cause:r});throw r},try:(r)=>e(A,{...w,fetch:D,responseStyle:"fields",signal:r,throwOnError:!1})});if(a.response===void 0)return yield*new n({cause:a.error});if(!a.response.ok)return yield*new d({body:a.error,status:a.response.status});return a.data});return S.of({studioAgentRunsGet:i("studioAgentRunsGet",(t,e)=>y({...t,...e})),studioAgentRunsList:i("studioAgentRunsList",(t,e)=>h({...t,...e})),studioViewDataGetItem:i("studioViewDataGetItem",(t,e)=>E({...t,...e})),studioViewDataSearch:i("studioViewDataSearch",(t,e)=>G({...t,...e})),studioViewDataSearchMembers:i("studioViewDataSearchMembers",(t,e)=>k({...t,...e})),studioViewDataUpdateItem:i("studioViewDataUpdateItem",(t,e)=>O({...t,...e})),studioWorkflowRunsGet:i("studioWorkflowRunsGet",(t,e)=>x({...t,...e})),studioWorkflowRunsList:i("studioWorkflowRunsList",(t,e)=>L({...t,...e}))})},R=(s={})=>p.sync(S,()=>N(s)),b=(s)=>p.unwrap(u.map(f.unwrap(s),R));export{S as StudioApi,d as StudioApiError,n as StudioApiTransportError,R as layerStudioApi,b as layerStudioApiConfig};
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 v}from"xstate";var w=()=>Promise.race([]),L=(r)=>v(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 Q,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(Q(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({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),T=({children:r})=>{let a=M(),i=P(()=>g.make(x(a)),[a]);return F(V.Provider,{value:i,children:r})},K=()=>{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 R 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 E=!1,A=j.getConfig().fetch??globalThis.fetch,C=Object.assign(async(p,b)=>(E=!0,await A(p,b)),A),d=yield*m.tryPromise({catch:(p)=>{if(E)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 R.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(R,()=>ee(r)),te=(r)=>y.unwrap(m.map(G.unwrap(r),O));export{T as EffectRuntimeProvider,l as QueryCache,R as StudioApi,c as StudioApiError,f as StudioApiTransportError,L as fromEffect,O as layerStudioApi,te as layerStudioApiConfig,K as useEffectRuntime};
@@ -1,4 +1,4 @@
1
1
  export { type QueryKey, studioAgentRunsGetOptions, studioAgentRunsGetQueryKey, studioAgentRunsListInfiniteOptions, studioAgentRunsListInfiniteQueryKey, studioAgentRunsListOptions, studioAgentRunsListQueryKey, studioViewDataGetItemOptions, studioViewDataGetItemQueryKey, studioViewDataSearchInfiniteOptions, studioViewDataSearchInfiniteQueryKey, studioViewDataSearchMembersInfiniteOptions, studioViewDataSearchMembersInfiniteQueryKey, studioViewDataSearchMembersOptions, studioViewDataSearchMembersQueryKey, studioViewDataSearchOptions, studioViewDataSearchQueryKey, studioViewDataUpdateItemMutation, studioWorkflowRunsGetOptions, studioWorkflowRunsGetQueryKey, studioWorkflowRunsListInfiniteOptions, studioWorkflowRunsListInfiniteQueryKey, studioWorkflowRunsListOptions, studioWorkflowRunsListQueryKey } from "./@tanstack/react-query.gen";
2
2
  export { client, type CreateClientConfig } from "./client.gen";
3
3
  export { type Options, studioAgentRunsGet, studioAgentRunsList, studioViewDataGetItem, studioViewDataSearch, studioViewDataSearchMembers, studioViewDataUpdateItem, studioWorkflowRunsGet, studioWorkflowRunsList } from "./sdk.gen";
4
- export type { ClientOptions, EffectHttpApiErrorBadRequestEncoded, EffectHttpApiErrorForbiddenEncoded, EffectHttpApiErrorInternalServerErrorEncoded, EffectHttpApiErrorNotFoundEncoded, EffectHttpApiErrorUnauthorizedEncoded, EntityFileFieldConflictDiagnosticEncoded, EntityFileFieldDiagnosticEncoded, EntityRelationFieldDiagnosticEncoded, EntityUniqueFieldConflictDiagnosticEncoded, EntityValueDiagnosticEncoded, InvalidIncludePathEncoded, KnowledgeReadLimitExceededEncoded, StudioAgentRunsGetData, StudioAgentRunsGetError, StudioAgentRunsGetErrors, StudioAgentRunsGetResponse, StudioAgentRunsGetResponses, StudioAgentRunsListData, StudioAgentRunsListError, StudioAgentRunsListErrors, StudioAgentRunsListResponse, StudioAgentRunsListResponses, StudioViewDataGetItemData, StudioViewDataGetItemError, StudioViewDataGetItemErrors, StudioViewDataGetItemResponses, StudioViewDataSearchData, StudioViewDataSearchError, StudioViewDataSearchErrors, StudioViewDataSearchMembersData, StudioViewDataSearchMembersError, StudioViewDataSearchMembersErrors, StudioViewDataSearchMembersResponses, StudioViewDataSearchResponses, StudioViewDataUpdateItemData, StudioViewDataUpdateItemError, StudioViewDataUpdateItemErrors, StudioViewDataUpdateItemResponse, StudioViewDataUpdateItemResponses, StudioWorkflowRunsGetData, StudioWorkflowRunsGetError, StudioWorkflowRunsGetErrors, StudioWorkflowRunsGetResponse, StudioWorkflowRunsGetResponses, StudioWorkflowRunsListData, StudioWorkflowRunsListError, StudioWorkflowRunsListErrors, StudioWorkflowRunsListResponse, StudioWorkflowRunsListResponses, Suspend3 } from "./types.gen";
4
+ export type { ClientOptions, EffectHttpApiErrorBadRequestEncoded, EffectHttpApiErrorForbiddenEncoded, EffectHttpApiErrorInternalServerErrorEncoded, EffectHttpApiErrorNotFoundEncoded, EffectHttpApiErrorUnauthorizedEncoded, EntityFileFieldConflictDiagnosticEncoded, EntityFileFieldDiagnosticEncoded, EntityRelationFieldDiagnosticEncoded, EntityUniqueFieldConflictDiagnosticEncoded, EntityValueDiagnosticEncoded, InvalidIncludePathEncoded, KnowledgeReadLimitExceededEncoded, StudioAgentRunsGetData, StudioAgentRunsGetError, StudioAgentRunsGetErrors, StudioAgentRunsGetResponse, StudioAgentRunsGetResponses, StudioAgentRunsListData, StudioAgentRunsListError, StudioAgentRunsListErrors, StudioAgentRunsListResponse, StudioAgentRunsListResponses, StudioViewDataGetItemData, StudioViewDataGetItemError, StudioViewDataGetItemErrors, StudioViewDataGetItemResponses, StudioViewDataSearchData, StudioViewDataSearchError, StudioViewDataSearchErrors, StudioViewDataSearchMembersData, StudioViewDataSearchMembersError, StudioViewDataSearchMembersErrors, StudioViewDataSearchMembersResponses, StudioViewDataSearchResponses, StudioViewDataUpdateItemData, StudioViewDataUpdateItemError, StudioViewDataUpdateItemErrors, StudioViewDataUpdateItemResponse, StudioViewDataUpdateItemResponses, StudioWorkflowRunsGetData, StudioWorkflowRunsGetError, StudioWorkflowRunsGetErrors, StudioWorkflowRunsGetResponse, StudioWorkflowRunsGetResponses, StudioWorkflowRunsListData, StudioWorkflowRunsListError, StudioWorkflowRunsListErrors, StudioWorkflowRunsListResponse, StudioWorkflowRunsListResponses, Suspend2 } from "./types.gen";
@@ -39,8 +39,8 @@ export type EntityFileFieldConflictDiagnosticEncoded = {
39
39
  field: string;
40
40
  message: string;
41
41
  };
42
- export type Suspend3 = null | boolean | number | string | Array<Suspend3> | {
43
- [key: string]: Suspend3;
42
+ export type Suspend2 = null | boolean | number | string | Array<Suspend2> | {
43
+ [key: string]: Suspend2;
44
44
  };
45
45
  export type InvalidIncludePathEncoded = {
46
46
  _tag: "InvalidIncludePath";
@@ -205,7 +205,7 @@ export type StudioViewDataSearchMembersData = {
205
205
  caseSensitive?: boolean;
206
206
  field: string;
207
207
  operator: "eq" | "ne" | "in" | "nin" | "contains" | "not_contains" | "starts_with" | "ends_with" | "gt" | "gte" | "lt" | "lte" | "exists" | "is_empty" | "is_not_empty" | "contains_any" | "contains_all" | "contains_none" | "not_in";
208
- value: Suspend3 | Array<Suspend3>;
208
+ value: Suspend2 | Array<Suspend2>;
209
209
  }>;
210
210
  include?: Array<string>;
211
211
  limit?: number;
@@ -264,7 +264,7 @@ export type StudioViewDataSearchData = {
264
264
  caseSensitive?: boolean;
265
265
  field: string;
266
266
  operator: "eq" | "ne" | "in" | "nin" | "contains" | "not_contains" | "starts_with" | "ends_with" | "gt" | "gte" | "lt" | "lte" | "exists" | "is_empty" | "is_not_empty" | "contains_any" | "contains_all" | "contains_none" | "not_in";
267
- value: Suspend3 | Array<Suspend3>;
267
+ value: Suspend2 | Array<Suspend2>;
268
268
  }>;
269
269
  include?: Array<string>;
270
270
  limit?: number;
package/docs/effect.md CHANGED
@@ -45,4 +45,84 @@ const runCount = (context: StudioViewContext) =>
45
45
  - A Dashboard release bundles its own copy of the client, and no Host binds
46
46
  it.
47
47
 
48
+ ## Writes in a Studio Widget
49
+
50
+ A widget writes in a `fromEffect` XState actor and refreshes its reads through
51
+ `QueryCache`. Views read with `useQuery`. The lint rules
52
+ `ci-solution/effect-writes` and `ci-solution/effect-actors` report
53
+ `useMutation`, `fromPromise` and `fromCallback`.
54
+
55
+ ```tsx
56
+ import type { EffectRunner } from "@collective-intelligence/extensions-sdk-frontend-react/effect"
57
+
58
+ import {
59
+ EffectRuntimeProvider,
60
+ fromEffect,
61
+ layerStudioApi,
62
+ QueryCache,
63
+ StudioApi,
64
+ useEffectRuntime
65
+ } from "@collective-intelligence/extensions-sdk-frontend-react/effect"
66
+ import { useActorRef } from "@xstate/react"
67
+ import * as Effect from "effect/Effect"
68
+ import { setup } from "xstate"
69
+
70
+ const rowsKey = ["com.acme.crm", "rows"] as const
71
+
72
+ type SaveInput = Readonly<{ name: string; runtime: EffectRunner<QueryCache> }>
73
+
74
+ const saveMachine = setup({
75
+ actors: {
76
+ save: fromEffect((input: SaveInput) =>
77
+ Effect.gen(function* () {
78
+ const api = yield* StudioApi
79
+ // ... the write, for example api.studioViewDataUpdateItem(...)
80
+ const cache = yield* QueryCache
81
+ yield* cache.invalidate(rowsKey)
82
+ }).pipe(Effect.provide(layerStudioApi()))
83
+ )
84
+ },
85
+ types: { context: {} as SaveInput, input: {} as SaveInput }
86
+ }).createMachine({
87
+ context: ({ input }) => input,
88
+ invoke: { input: ({ context }) => context, src: "save" }
89
+ })
90
+
91
+ const SaveView = ({ name }: Readonly<{ name: string }>) => {
92
+ const runtime = useEffectRuntime()
93
+ useActorRef(saveMachine, { input: { name, runtime } })
94
+ return null
95
+ }
96
+
97
+ export const RowsWidget = (props: Readonly<{ name: string }>) => (
98
+ <EffectRuntimeProvider>
99
+ <SaveView {...props} />
100
+ </EffectRuntimeProvider>
101
+ )
102
+ ```
103
+
104
+ ## Rules of the write parts
105
+
106
+ - Mount `EffectRuntimeProvider` at the root of each widget. It uses the
107
+ `QueryClient` of the Studio Host. The Host mounts no Effect runtime, and a
108
+ widget does not see the provider of another bundle.
109
+ - Pass the runtime of `useEffectRuntime()` to each machine in its input. A
110
+ `fromEffect` actor runs on `input.runtime`.
111
+ - A stop of the actor interrupts the fiber. After a stop, no result of that
112
+ run gets to the actor, also in a React Strict Mode remount.
113
+ - `QueryCache.invalidate`, `update` and `remove` apply to the key and to each
114
+ key below it. Start each key with the package name: the Host and all widgets
115
+ share one `QueryClient`.
116
+ - `QueryCache.fetch` runs its query once, without a retry, and fails with
117
+ `StudioApiError` or `StudioApiTransportError`. Another failure is a Defect;
118
+ a cancel of the key is an interruption.
119
+ - `xstate` is a required peer that the Studio and Dashboard Hosts provide; a
120
+ widget bundle carries no copy of XState. The first Hosts that provide it
121
+ ship in the first ci-app release after `@collective-intelligence/cli@0.2.2`,
122
+ with the CLI that keeps it external: build with that CLI or a later one,
123
+ and run on Hosts of that release or a later one.
124
+ - Import XState only from `xstate`, never from a subpath such as
125
+ `xstate/actors`: a release bundles a subpath, which is a second copy of
126
+ XState. Build against `xstate` 5; the Host does not check the version.
127
+
48
128
  Errors: [errors.md](errors.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/extensions-sdk-frontend-react",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Public hosted React contribution contracts for Collective Intelligence extensions.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -67,7 +67,7 @@
67
67
  "api:codegen:studio-api": "bun tools/codegen/generate-studio-api.ts",
68
68
  "api:codegen:studio-api:check": "bun tools/codegen/generate-studio-api.ts --check",
69
69
  "build": "bun tools/build.ts",
70
- "test": "bun --conditions=ci-source test src tools && bun run test:pack && vitest run test/frontend-runtime.test.tsx test/built-runtime.test.ts test/workflow-field-help.test.tsx",
70
+ "test": "bun --conditions=ci-source test src tools && bun run test:pack && vitest run test/frontend-runtime.test.tsx test/built-runtime.test.ts test/workflow-field-help.test.tsx test/effect-runtime.test.tsx",
71
71
  "test:unit": "bun --conditions=ci-source test src",
72
72
  "test:pack": "bun tools/test-pack.ts",
73
73
  "test:properties": "vitest run test/properties",
@@ -80,8 +80,8 @@
80
80
  "type-check": "bun check && bun check -p tsconfig.type-tests.json"
81
81
  },
82
82
  "dependencies": {
83
- "@collective-intelligence/extensions-sdk": "0.2.2",
84
- "@collective-intelligence/extensions-sdk-frontend": "0.2.2"
83
+ "@collective-intelligence/extensions-sdk": "0.2.3",
84
+ "@collective-intelligence/extensions-sdk-frontend": "0.2.3"
85
85
  },
86
86
  "peerDependencies": {
87
87
  "@collective-intelligence/ui-react": "0.2.0",
@@ -89,7 +89,8 @@
89
89
  "@xyflow/react": ">=12 <13",
90
90
  "effect": "^4.1.0",
91
91
  "react": ">=18 <20",
92
- "react-dom": ">=18 <20"
92
+ "react-dom": ">=18 <20",
93
+ "xstate": "^5.32.6"
93
94
  },
94
95
  "peerDependenciesMeta": {
95
96
  "@collective-intelligence/ui-react": {
@@ -120,7 +121,9 @@
120
121
  "typescript": "7.0.2",
121
122
  "ultracite": "7.10.7",
122
123
  "vitest": "5.0.2",
123
- "es-module-lexer": "2.3.2"
124
+ "es-module-lexer": "2.3.2",
125
+ "@xstate/react": "6.1.0",
126
+ "xstate": "5.33.3"
124
127
  },
125
- "gitHead": "51fdea833e25fe215b3cf0d70adf1984b8e0f81c"
128
+ "gitHead": "1718b80bc8d0ba696d78ac8f5f905c8dc46fe0c5"
126
129
  }