@collective-intelligence/external-apps-client-sdk-react 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -3
- package/dist/index.d.ts +5 -1
- package/dist/index.js +1 -1
- package/docs/guide/develop/extensions.md +34 -29
- package/docs/guide/develop/sdks.md +3 -3
- package/docs/guide/platform/access.md +4 -4
- package/docs/guide/platform/architecture.md +2 -2
- package/docs/guide/platform/entrypoints.md +17 -19
- package/docs/guide/template/index.md +106 -93
- package/docs/guide/template/state-machines.md +5 -5
- package/docs/sign-in.md +13 -3
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -94,12 +94,18 @@ const auth = createServerSessionAuth({ basePath: "/api/auth" })
|
|
|
94
94
|
`verify(code)`, `complete(name)`, `sso(provider)` and `password()`.
|
|
95
95
|
- `SignIn.Root` calls `auth.signIn.methods()` when it mounts. The answer sets
|
|
96
96
|
the SSO buttons and the password button. When the app allows only a
|
|
97
|
-
password, it is `redirect_to_web`, and the SDK opens the CI page.
|
|
97
|
+
password, it is `redirect_to_web`, and the SDK opens the CI page. When the
|
|
98
|
+
app allows no email code, the email form stays, because CI sends the
|
|
99
|
+
address to its SSO provider or to the CI page; its button then shows
|
|
100
|
+
`emailContinue` ("Continue") in place of `emailSubmit` ("Send code").
|
|
98
101
|
- `onSignedIn` runs on the `signed_in` step. `onRegistered` runs before it
|
|
99
102
|
when the step has `registered: true`. `onError` gets `CiTransportError`
|
|
100
103
|
(the call got no step) or `FederatedAuthError` (the SDK could not
|
|
101
104
|
navigate); the form keeps its values. A refusal, such as a wrong code, is a
|
|
102
|
-
step: `SignIn.Notice` shows it.
|
|
105
|
+
step: `SignIn.Notice` shows it. An email, code or name that CI cannot read
|
|
106
|
+
is the `invalid_input` step, not a fault: the same form stays, the notice
|
|
107
|
+
asks the person to check the input (`invalidInput`), and `onError` does
|
|
108
|
+
not run.
|
|
103
109
|
- `labels` replaces any default text (`SignInLabels`). `className` goes on
|
|
104
110
|
the card and on each part. `components` replaces `EmailField`, `CodeField`,
|
|
105
111
|
`NameField` or `Button`; a field slot gets input props and renders one
|
|
@@ -110,7 +116,8 @@ const auth = createServerSessionAuth({ basePath: "/api/auth" })
|
|
|
110
116
|
19; the parts disable their buttons and set `aria-busy` while it is true.
|
|
111
117
|
An action while a call runs does nothing, so a double submit sends one
|
|
112
118
|
call. The SDK sends the calls of one client one at a time.
|
|
113
|
-
- The sign-in components import `@collective-intelligence/ui-react/ui
|
|
119
|
+
- The sign-in components import `@collective-intelligence/ui-react/ui` and
|
|
120
|
+
`@collective-intelligence/ui-react/ui-extensions/labeled-field`, so the
|
|
114
121
|
application installs `react-hook-form`, a required peer of `ui-react`.
|
|
115
122
|
|
|
116
123
|
## Optimistic Writes
|
package/dist/index.d.ts
CHANGED
|
@@ -213,7 +213,7 @@ export type SignInMethods = Omit<Extract<SignInStep, Readonly<{
|
|
|
213
213
|
export type SignInNotice = Extract<SignInStep, Readonly<{
|
|
214
214
|
step: "email_domain_not_allowed" | "invalid_code" | "retry_after";
|
|
215
215
|
}>> | Readonly<{
|
|
216
|
-
step: "access_denied" | "code_expired";
|
|
216
|
+
step: "access_denied" | "code_expired" | "invalid_input";
|
|
217
217
|
}>;
|
|
218
218
|
/**
|
|
219
219
|
* The state of one Embedded Sign-In. `stage` names the form or the end that
|
|
@@ -245,9 +245,13 @@ export type SignInLabels = Readonly<{
|
|
|
245
245
|
codeSentTo: (email: string) => string;
|
|
246
246
|
codeSubmit: string;
|
|
247
247
|
email: string;
|
|
248
|
+
/** The email button when the app allows no email code: CI routes the address. */
|
|
249
|
+
emailContinue: string;
|
|
248
250
|
emailDomainNotAllowed: (allowedDomains: readonly string[]) => string;
|
|
249
251
|
emailSubmit: string;
|
|
250
252
|
invalidCode: (attemptsLeft: number) => string;
|
|
253
|
+
/** CI cannot read the email, code or name that the person typed. */
|
|
254
|
+
invalidInput: string;
|
|
251
255
|
name: string;
|
|
252
256
|
nameSubmit: string;
|
|
253
257
|
noSignInMethod: string;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{EntityRuntimeProvider,createDelegatedEntitySource2,defineEntity2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-0fbftb7q.js";import"./index-e0z6c7w9.js";import{useCallback,useId,useRef,useState as useState2}from"react";import{QueryClient,QueryClientProvider}from"@tanstack/react-query";import{createContext,useContext,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";var ClientContext=createContext(null);var CollectiveIntelligenceProvider=(props)=>{const{clientFactory}=props;const[ownedQueryClient]=useState(()=>new QueryClient({defaultOptions:{mutations:{retry:false},queries:{retry:false}}}));const ownedClient=useMemo(()=>clientFactory===undefined?undefined:clientFactory(),[clientFactory]);const client=props.client??ownedClient;const queryClient=props.queryClient??ownedQueryClient;if(client===undefined){throw new TypeError("A client or clientFactory is required")}return jsx(ClientContext.Provider,{value:client,children:jsx(QueryClientProvider,{client:queryClient,children:props.entitySource===undefined?props.children:jsx(EntityRuntimeProvider,{onWriteFailed:props.onWriteFailed,source:props.entitySource,children:props.children})})})};var useCollectiveIntelligenceClient=()=>{const client=useContext(ClientContext);if(client===null){throw new Error("CollectiveIntelligenceProvider must wrap Collective Intelligence hooks")}return client};var useOrganizationClient=(organizationId)=>{const client=useCollectiveIntelligenceClient();return useMemo(()=>client.forOrganization(organizationId),[client,organizationId])};var useKnowledge=(organizationId)=>useOrganizationClient(organizationId).knowledge;var useAgents=(organizationId)=>useOrganizationClient(organizationId).agents;var useSkills=(organizationId)=>useOrganizationClient(organizationId).skills;var useWorkflows=(organizationId)=>useOrganizationClient(organizationId).workflows;var useRuns=(organizationId)=>useOrganizationClient(organizationId).runs;var useAttachments=(organizationId)=>useOrganizationClient(organizationId).attachments;var useClientContext=(organizationId)=>useOrganizationClient(organizationId).context;import{jsx as jsx2,jsxs}from"react/jsx-runtime";var ignoreSubmit=()=>false;var createPromptKeyHandler=(onSubmit)=>(event)=>{if(event.key==="Enter"&&!event.shiftKey&&!event.isComposing){event.preventDefault();onSubmit()}};var AgentPromptPrimitive=({autoFocus=false,className,components,id,label,onChange,onSubmit,pending,status,style,submitLabel="Send",value})=>{const Form=components?.Form??"form";const Label=components?.Label??"label";const Textarea=components?.Textarea??"textarea";const Button=components?.Button??"button";const Status=components?.Status??"div";const statusId=`${id}-status`;const submit=(event)=>{event.preventDefault();if(!pending){onSubmit()}};const onKeyDown=(event)=>{createPromptKeyHandler(pending?ignoreSubmit:onSubmit)({isComposing:event.nativeEvent.isComposing,key:event.key,preventDefault:()=>{event.preventDefault()},shiftKey:event.shiftKey})};return jsxs(Form,{className:["ci-agent-prompt",className].filter(Boolean).join(" "),onSubmit:submit,style,children:[jsx2(Label,{className:"ci-agent-prompt__label",htmlFor:id,children:label}),jsx2(Textarea,{"aria-describedby":statusId,autoFocus,className:"ci-agent-prompt__input",disabled:pending,id,onChange:(event)=>{onChange(event.currentTarget.value)},onKeyDown,value}),jsx2(Button,{className:"ci-agent-prompt__submit",disabled:pending||value.trim().length===0,type:"submit",children:submitLabel}),jsx2(Status,{"aria-live":"polite",className:"ci-agent-prompt__status",id:statusId,children:status})]})};var useAgentInvocation=(organizationId)=>{const{agents}=useOrganizationClient(organizationId);const[state,setState]=useState2({status:"idle"});const generation=useRef(0);const invoke=useCallback(async(input)=>{generation.current+=1;const request=generation.current;const settle=(settled)=>{if(request===generation.current){setState(settled)}};setState({status:"submitting"});try{const result=await agents.invoke(input);settle(result.ok?{result,status:"success"}:{result,status:"failure"});return result}catch(error){settle({error,status:"error"});throw error}},[agents]);return{invoke,reset:()=>{generation.current+=1;setState({status:"idle"})},state}};var invocationStatus=(state)=>{switch(state.status){case"submitting":{return"Sending"}case"success":{return"Request started"}case"failure":{return state.result.error.message}case"error":{return"Request failed"}case"idle":{return null}default:{return null}}};var EMPTY_AGENT_PROMPT_COMPONENTS={};var EMPTY_AGENT_PROMPT_STYLE={};var createDefaultIdempotencyKey=()=>globalThis.crypto.randomUUID();var AgentPrompt=({agentId,autoFocus=false,className="",components=EMPTY_AGENT_PROMPT_COMPONENTS,createIdempotencyKey=createDefaultIdempotencyKey,label="Message",onResult,organizationId,style=EMPTY_AGENT_PROMPT_STYLE,submitLabel="Send"})=>{const id=`ci-agent-prompt-${useId().replaceAll(":","")}`;const[value,setValue]=useState2("");const invocation=useAgentInvocation(organizationId);const submit=()=>{const prompt=value.trim();if(prompt.length===0||invocation.state.status==="submitting"){return}const submitInvocation=async()=>{try{const result=await invocation.invoke({agentId,idempotencyKey:createIdempotencyKey(),input:{prompt}});if(result.ok){setValue("")}onResult?.(result)}catch{}};submitInvocation()};return jsx2(AgentPromptPrimitive,{autoFocus,className,components,id,label,onChange:setValue,onSubmit:submit,pending:invocation.state.status==="submitting",status:invocationStatus(invocation.state),style,submitLabel,value})};import{FederatedAuthError}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext2,useCallback as useCallback2,useContext as useContext2,useEffect,useMemo as useMemo2,useSyncExternalStore}from"react";import{jsx as jsx3}from"react/jsx-runtime";var AuthContext=createContext2(null);var toFederatedAuthError=(error)=>new FederatedAuthError("authorization_failed",error.message);var unknownAuthError=()=>new FederatedAuthError("authorization_failed","Sign in failed");var CollectiveIntelligenceLoginProvider=(props)=>{const state=useSyncExternalStore(props.auth.subscribe,props.auth.getState,props.auth.getState);const contextValue=useMemo2(()=>({auth:props.auth,state}),[props.auth,state]);return jsx3(AuthContext.Provider,{value:contextValue,children:props.clientFactory===undefined?jsx3(CollectiveIntelligenceProvider,{client:props.client,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children}):jsx3(CollectiveIntelligenceProvider,{clientFactory:props.clientFactory,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children})})};var useCollectiveIntelligenceAuth=()=>{const value=useContext2(AuthContext);if(value===null){throw new Error("CollectiveIntelligenceLoginProvider must wrap authentication bindings")}return{...value,beginLogin:value.auth.beginLogin,completeLogin:value.auth.completeLogin,logout:value.auth.logout,reauthorize:value.auth.reauthorize}};var LoginButton=({children="Sign in with Collective Intelligence",className,components,disabled=false,onError,returnTo,style})=>{const{auth,state}=useCollectiveIntelligenceAuth();const Button=components?.Button??"button";const redirecting=state.status==="redirecting";const onClick=useCallback2((event)=>{event.preventDefault();const target=returnTo??globalThis.location.href;const begin=async()=>{try{await auth.beginLogin({returnTo:target})}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};begin()},[auth,onError,returnTo]);return jsx3(Button,{"aria-busy":redirecting,className:["ci-login-button",className].filter(Boolean).join(" "),disabled:disabled||redirecting,onClick,style,type:"button",children})};var callbackMessage=(state)=>{switch(state.status){case"authenticated":{return"Sign in complete"}case"error":{return state.error.message}case"expired":{return"Sign in expired"}case"anonymous":case"redirecting":{return"Completing sign in"}default:{return"Completing sign in"}}};var LoginCallbackPrimitive=({className,components,state,style})=>{const Status=components?.Status??"div";return jsx3(Status,{"aria-live":"polite",className:["ci-login-callback",className].filter(Boolean).join(" "),style,children:callbackMessage(state)})};var LoginCallback=({callbackUrl,onComplete,onError,...primitiveProps})=>{const{auth,state}=useCollectiveIntelligenceAuth();useEffect(()=>{const url=callbackUrl??globalThis.location.href;const complete=async()=>{try{const{returnTo}=await auth.completeLogin(url);onComplete?.(returnTo)}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};complete()},[auth,callbackUrl,onComplete,onError]);return jsx3(LoginCallbackPrimitive,{...primitiveProps,state})};var useSession=()=>{const{state}=useCollectiveIntelligenceAuth();return state};var SessionGate=({children,fallback=null})=>{const session=useSession();if(session.status!=="authenticated"){return fallback}return children};import{FederatedAuthError as FederatedAuthError2}from"@collective-intelligence/external-apps-client-sdk";import{CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import*as Schema from"effect/Schema";import{createContext as createContext3,useCallback as useCallback3,useContext as useContext3,useEffect as useEffect2,useMemo as useMemo3,useReducer,useRef as useRef2,useState as useState3}from"react";var initialSignInState={email:"",methods:null,notice:null,stage:"email"};var reduceSignIn=(state,{email=state.email,step})=>{const next={email,methods:state.methods,notice:null};switch(step.step){case"methods":{const{step:_methods,...methods}=step;return{...state,methods}}case"code_sent":{return{...next,stage:"code"}}case"registration_required":{return{...next,stage:"name"}}case"invalid_code":{return{...next,notice:step,stage:"code"}}case"retry_after":{return{...state,email,notice:step}}case"email_domain_not_allowed":{return{...next,notice:step,stage:"email"}}case"access_denied":case"code_expired":{return{...next,notice:{step:step.step},stage:"email"}}case"sso_required":{return{...next,provider:step.provider,stage:"sso_required"}}case"signed_in":{return{...next,registered:step.registered,stage:"signed_in"}}case"no_sign_in_method":case"redirect_to_web":{return{...next,stage:step.step}}default:{return step}}};import{jsx as jsx4}from"react/jsx-runtime";var defaultLabels={accessDenied:"You cannot sign in to this app with this address.",code:"Code",codeExpired:"The code is no longer valid. Enter your email again.",codeSentTo:(email)=>`Enter the code that we sent to ${email}.`,codeSubmit:"Continue",email:"Email",emailDomainNotAllowed:(allowedDomains)=>`Use an address of ${allowedDomains.join(", ")}.`,emailSubmit:"Send code",invalidCode:(attemptsLeft)=>`The code is not correct. Attempts left: ${attemptsLeft}.`,name:"Name",nameSubmit:"Create account",noSignInMethod:"No sign-in method is available for this app.",password:"Sign in with password",redirecting:"Opening the sign-in page…",resendCode:"Send a new code",retryAfter:(seconds)=>`Wait ${seconds} seconds, then ask for a new code.`,signedIn:"You are signed in.",sso:(provider)=>`Continue with ${provider}`,ssoRequired:(provider)=>`Your organization signs you in with ${provider}.`,title:"Sign in"};var SignInContext=createContext3(null);var noComponents={};var isSignInError=Schema.is(Schema.Union([CiTransportError,FederatedAuthError2]));var redirectToWeb={step:"redirect_to_web"};var SignInRoot=({children,components=noComponents,labels,...options})=>{const{auth}=useCollectiveIntelligenceAuth();if(!("signIn"in auth)){throw new Error("The sign-in components need the auth of createServerSessionAuth")}const{beginLogin,signIn}=auth;const[state,dispatch]=useReducer(reduceSignIn,initialSignInState);const[pending,setPending]=useState3(false);const running=useRef2(false);const latest=useRef2(options);useEffect2(()=>{latest.current=options});const run=useCallback3(async(call,email)=>{if(running.current){return}running.current=true;setPending(true);const answer=async()=>{try{const step=await call();dispatch(email===undefined?{step}:{email,step});if(step.step==="signed_in"){if(step.registered){latest.current.onRegistered?.()}latest.current.onSignedIn?.()}}catch(error){latest.current.onError?.(isSignInError(error)?error:new CiTransportError({cause:error}))}};await answer().finally(()=>{running.current=false;setPending(false)})},[]);const{actions,methods}=useMemo3(()=>{const returnTarget=()=>{const{returnTo}=latest.current;return returnTo===undefined?{}:{returnTo}};const languages=()=>{const{uiLocales}=latest.current;return uiLocales===undefined?{}:{uiLocales}};return{actions:{complete:(name)=>{run(()=>signIn.complete({name,...returnTarget()}))},password:()=>{run(async()=>{await beginLogin({returnTo:latest.current.returnTo??"/"});return redirectToWeb})},sso:(provider)=>{run(()=>signIn.sso({provider,...returnTarget()}))},start:(email)=>{run(()=>signIn.start({email,...languages(),...returnTarget()}),email)},verify:(code)=>{run(()=>signIn.verify({code,...returnTarget()}))}},methods:()=>{run(()=>signIn.methods({...languages(),...returnTarget()}))}}},[beginLogin,run,signIn]);useEffect2(()=>{methods()},[methods]);const value=useMemo3(()=>({binding:{...actions,pending,state},components,labels:{...defaultLabels,...labels}}),[actions,components,labels,pending,state]);return jsx4(SignInContext.Provider,{value,children})};var useSignInParts=()=>{const value=useContext3(SignInContext);if(value===null){throw new Error("SignIn.Root must wrap the sign-in components")}return value};var useSignIn=()=>useSignInParts().binding;import{Alert,AlertDescription,Button,Input,InputOTP,InputOTPGroup,InputOTPSlot,Label}from"@collective-intelligence/ui-react/ui";import{cn}from"@collective-intelligence/ui-react/utils/cn";import{useId as useId2}from"react";import{jsx as jsx5,jsxs as jsxs2}from"react/jsx-runtime";var codeSlots=[0,1,2,3,4,5];var CodeInput=(props)=>jsx5(InputOTP,{...props,maxLength:codeSlots.length,pattern:"^[0-9]+$",children:jsx5(InputOTPGroup,{children:codeSlots.map((index)=>jsx5(InputOTPSlot,{index},index))})});var Labeled=({children,id,label})=>jsxs2("div",{className:"grid gap-2",children:[jsx5(Label,{htmlFor:id,children:label}),children]});var Action=({variant,...props})=>{const{components}=useSignInParts();return components.Button===undefined?jsx5(Button,{variant,...props}):jsx5(components.Button,{...props})};var submitted=(event,name)=>{event.preventDefault();const value=new FormData(event.currentTarget).get(name);return value instanceof File||value===null?"":value.trim()};var EmailForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="email"){return null}const Field=components.EmailField??Input;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.start(submitted(event,"email"))},children:[jsx5(Labeled,{id,label:labels.email,children:jsx5(Field,{autoComplete:"email",defaultValue:binding.state.email,id,name:"email",required:true,type:"email"})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.emailSubmit})]})};var CodeForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="code"){return null}const{email}=binding.state;const Field=components.CodeField??CodeInput;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.verify(submitted(event,"code"))},children:[jsx5("p",{className:"text-sm",id:`${id}-sent`,children:labels.codeSentTo(email)}),jsx5(Labeled,{id,label:labels.code,children:jsx5(Field,{"aria-describedby":`${id}-sent`,autoComplete:"one-time-code",id,name:"code",required:true})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.codeSubmit}),jsx5(Action,{disabled:binding.pending,onClick:()=>{binding.start(email)},type:"button",variant:"link",children:labels.resendCode})]})};var NameForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="name"){return null}const Field=components.NameField??Input;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.complete(submitted(event,"name"))},children:[jsx5(Labeled,{id,label:labels.name,children:jsx5(Field,{autoComplete:"name",id,maxLength:255,name:"name",required:true})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.nameSubmit})]})};var ssoProviders=(state)=>{if(state.stage==="sso_required"){return[state.provider]}return state.stage==="email"?state.methods?.ssoProviders??[]:[]};var SsoButtons=({className})=>{const{binding,labels}=useSignInParts();const providers=ssoProviders(binding.state);if(providers.length===0){return null}return jsx5("div",{className:cn("grid gap-2",className),children:providers.map((provider)=>jsx5(Action,{disabled:binding.pending,onClick:()=>{binding.sso(provider.id)},type:"button",variant:"outline",children:labels.sso(provider.displayName)},provider.id))})};var PasswordButton=({className})=>{const{binding,labels}=useSignInParts();if(binding.state.stage!=="email"||binding.state.methods?.password!==true){return null}return jsx5(Action,{className,disabled:binding.pending,onClick:()=>{binding.password()},type:"button",variant:"outline",children:labels.password})};var noticeText=(notice,labels)=>{switch(notice.step){case"access_denied":{return labels.accessDenied}case"code_expired":{return labels.codeExpired}case"email_domain_not_allowed":{return labels.emailDomainNotAllowed(notice.allowedDomains)}case"invalid_code":{return labels.invalidCode(notice.attemptsLeft)}case"retry_after":{return labels.retryAfter(notice.seconds)}default:{return notice}}};var Notice=({className})=>{const{binding,labels}=useSignInParts();const{notice}=binding.state;if(notice===null){return null}return jsx5(Alert,{className,variant:"destructive",children:jsx5(AlertDescription,{children:noticeText(notice,labels)})})};var statusText=(state,labels)=>{switch(state.stage){case"no_sign_in_method":{return labels.noSignInMethod}case"redirect_to_web":{return labels.redirecting}case"signed_in":{return labels.signedIn}case"sso_required":{return labels.ssoRequired(state.provider.displayName)}default:{return null}}};var Status=({className})=>{const{binding,labels}=useSignInParts();const text=statusText(binding.state,labels);if(text===null){return null}return jsx5("output",{className:cn("text-sm",className),children:text})};var SignIn={CodeForm,EmailForm,NameForm,Notice,PasswordButton,Root:SignInRoot,SsoButtons,Status};import{Card,CardContent,CardHeader,CardTitle}from"@collective-intelligence/ui-react/ui";import{jsx as jsx6,jsxs as jsxs3}from"react/jsx-runtime";var Title=()=>jsx6(CardTitle,{children:useSignInParts().labels.title});var SignInCard=({className,...rootProps})=>jsx6(SignIn.Root,{...rootProps,children:jsxs3(Card,{className,children:[jsx6(CardHeader,{children:jsx6(Title,{})}),jsxs3(CardContent,{className:"grid gap-4",children:[jsx6(SignIn.Notice,{}),jsx6(SignIn.EmailForm,{}),jsx6(SignIn.CodeForm,{}),jsx6(SignIn.NameForm,{}),jsx6(SignIn.SsoButtons,{}),jsx6(SignIn.PasswordButton,{}),jsx6(SignIn.Status,{})]})]})});import{createRealtimeClient}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext4,useContext as useContext4,useEffect as useEffect3,useState as useState4}from"react";import{jsx as jsx7}from"react/jsx-runtime";var idle={connections:0,lastEventId:undefined,status:"idle",topics:[]};var hasOnReset=(options)=>options.onReset!==undefined;var shareClient=(initial)=>{let options=initial;let shared={status:"none"};const subscriptions=new Set;const create=()=>createRealtimeClient({document:globalThis.document,window:globalThis.window,...options,onAccessChanged:()=>options.onAccessChanged?.(),onRefused:()=>options.onRefused?.(),...hasOnReset(options)&&{onReset:()=>options.onReset?.()}});const acquire=()=>{const client=shared.status==="none"?create():shared.client;shared={client,holders:shared.status==="held"?shared.holders+1:1,status:"held"};return client};const release=()=>{if(shared.status!=="held"){return}if(shared.holders>1){shared={...shared,holders:shared.holders-1};return}shared={client:shared.client,status:"releasing"};queueMicrotask(()=>{if(shared.status==="releasing"){shared.client.close();shared={status:"none"}}})};const subscribe=(topic,onChanges)=>{const subscription={onChanges,topic,unsubscribe:acquire().subscribe(topic,onChanges)};subscriptions.add(subscription);return()=>{if(subscriptions.delete(subscription)){subscription.unsubscribe();release()}}};return{acquire,getState:()=>shared.status==="none"?idle:shared.client.getState(),release,subscribe,update:(next)=>{const previous=options;options=next;if(shared.status==="none"||hasOnReset(next)===hasOnReset(previous)){return}for(const subscription of subscriptions){subscription.unsubscribe()}shared.client.close();const client=create();shared={...shared,client};for(const subscription of subscriptions){subscription.unsubscribe=client.subscribe(subscription.topic,subscription.onChanges)}}}};var RealtimeContext=createContext4(null);var RealtimeProvider=({children,...options})=>{const[shared]=useState4(()=>shareClient(options));useEffect3(()=>{shared.update(options)});useEffect3(()=>{shared.acquire();return shared.release},[shared]);return jsx7(RealtimeContext.Provider,{value:shared,children})};var useRealtimeClient=()=>{const client=useContext4(RealtimeContext);if(client===null){throw new Error("useRealtimeClient requires a RealtimeProvider")}return client};import{realtimeTopicKey}from"@collective-intelligence/external-apps-client-sdk";import{useEffect as useEffect4,useRef as useRef3,useState as useState5}from"react";var useRealtimeTopic=(topic,onChanges)=>{const client=useRealtimeClient();const latest=useRef3(onChanges);const key=topic===null?null:realtimeTopicKey(topic);const[subscribed,setSubscribed]=useState5({key,topic});if(subscribed.key!==key){setSubscribed({key,topic})}useEffect4(()=>{latest.current=onChanges});useEffect4(()=>subscribed.topic===null?undefined:client.subscribe(subscribed.topic,(changes)=>latest.current(changes)),[client,subscribed])};var clientSdkReactEntrypoint="react";export{AgentPrompt,AgentPromptPrimitive,CollectiveIntelligenceLoginProvider,CollectiveIntelligenceProvider,EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,LoginButton,LoginCallback,LoginCallbackPrimitive,RealtimeProvider,SessionGate,SignIn,SignInCard,clientSdkReactEntrypoint,createDelegatedEntitySource2 as createDelegatedEntitySource,createPromptKeyHandler,defineEntity2 as defineEntity,useAgentInvocation,useAgents,useAttachments,useClientContext,useCollectiveIntelligenceAuth,useCollectiveIntelligenceClient,useEntityViewState2 as useEntityViewState,useKnowledge,useMemoryEntityViewState2 as useMemoryEntityViewState,useOrganizationClient,useRealtimeClient,useRealtimeTopic,useRuns,useSession,useSignIn,useSkills,useWorkflows};
|
|
2
|
+
import{EntityRuntimeProvider,createDelegatedEntitySource2,defineEntity2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-0fbftb7q.js";import"./index-e0z6c7w9.js";import{useCallback,useId,useRef,useState as useState2}from"react";import{QueryClient,QueryClientProvider}from"@tanstack/react-query";import{createContext,useContext,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";var ClientContext=createContext(null);var CollectiveIntelligenceProvider=(props)=>{const{clientFactory}=props;const[ownedQueryClient]=useState(()=>new QueryClient({defaultOptions:{mutations:{retry:false},queries:{retry:false}}}));const ownedClient=useMemo(()=>clientFactory===undefined?undefined:clientFactory(),[clientFactory]);const client=props.client??ownedClient;const queryClient=props.queryClient??ownedQueryClient;if(client===undefined){throw new TypeError("A client or clientFactory is required")}return jsx(ClientContext.Provider,{value:client,children:jsx(QueryClientProvider,{client:queryClient,children:props.entitySource===undefined?props.children:jsx(EntityRuntimeProvider,{onWriteFailed:props.onWriteFailed,source:props.entitySource,children:props.children})})})};var useCollectiveIntelligenceClient=()=>{const client=useContext(ClientContext);if(client===null){throw new Error("CollectiveIntelligenceProvider must wrap Collective Intelligence hooks")}return client};var useOrganizationClient=(organizationId)=>{const client=useCollectiveIntelligenceClient();return useMemo(()=>client.forOrganization(organizationId),[client,organizationId])};var useKnowledge=(organizationId)=>useOrganizationClient(organizationId).knowledge;var useAgents=(organizationId)=>useOrganizationClient(organizationId).agents;var useSkills=(organizationId)=>useOrganizationClient(organizationId).skills;var useWorkflows=(organizationId)=>useOrganizationClient(organizationId).workflows;var useRuns=(organizationId)=>useOrganizationClient(organizationId).runs;var useAttachments=(organizationId)=>useOrganizationClient(organizationId).attachments;var useClientContext=(organizationId)=>useOrganizationClient(organizationId).context;import{jsx as jsx2,jsxs}from"react/jsx-runtime";var ignoreSubmit=()=>false;var createPromptKeyHandler=(onSubmit)=>(event)=>{if(event.key==="Enter"&&!event.shiftKey&&!event.isComposing){event.preventDefault();onSubmit()}};var AgentPromptPrimitive=({autoFocus=false,className,components,id,label,onChange,onSubmit,pending,status,style,submitLabel="Send",value})=>{const Form=components?.Form??"form";const Label=components?.Label??"label";const Textarea=components?.Textarea??"textarea";const Button=components?.Button??"button";const Status=components?.Status??"div";const statusId=`${id}-status`;const submit=(event)=>{event.preventDefault();if(!pending){onSubmit()}};const onKeyDown=(event)=>{createPromptKeyHandler(pending?ignoreSubmit:onSubmit)({isComposing:event.nativeEvent.isComposing,key:event.key,preventDefault:()=>{event.preventDefault()},shiftKey:event.shiftKey})};return jsxs(Form,{className:["ci-agent-prompt",className].filter(Boolean).join(" "),onSubmit:submit,style,children:[jsx2(Label,{className:"ci-agent-prompt__label",htmlFor:id,children:label}),jsx2(Textarea,{"aria-describedby":statusId,autoFocus,className:"ci-agent-prompt__input",disabled:pending,id,onChange:(event)=>{onChange(event.currentTarget.value)},onKeyDown,value}),jsx2(Button,{className:"ci-agent-prompt__submit",disabled:pending||value.trim().length===0,type:"submit",children:submitLabel}),jsx2(Status,{"aria-live":"polite",className:"ci-agent-prompt__status",id:statusId,children:status})]})};var useAgentInvocation=(organizationId)=>{const{agents}=useOrganizationClient(organizationId);const[state,setState]=useState2({status:"idle"});const generation=useRef(0);const invoke=useCallback(async(input)=>{generation.current+=1;const request=generation.current;const settle=(settled)=>{if(request===generation.current){setState(settled)}};setState({status:"submitting"});try{const result=await agents.invoke(input);settle(result.ok?{result,status:"success"}:{result,status:"failure"});return result}catch(error){settle({error,status:"error"});throw error}},[agents]);return{invoke,reset:()=>{generation.current+=1;setState({status:"idle"})},state}};var invocationStatus=(state)=>{switch(state.status){case"submitting":{return"Sending"}case"success":{return"Request started"}case"failure":{return state.result.error.message}case"error":{return"Request failed"}case"idle":{return null}default:{return null}}};var EMPTY_AGENT_PROMPT_COMPONENTS={};var EMPTY_AGENT_PROMPT_STYLE={};var createDefaultIdempotencyKey=()=>globalThis.crypto.randomUUID();var AgentPrompt=({agentId,autoFocus=false,className="",components=EMPTY_AGENT_PROMPT_COMPONENTS,createIdempotencyKey=createDefaultIdempotencyKey,label="Message",onResult,organizationId,style=EMPTY_AGENT_PROMPT_STYLE,submitLabel="Send"})=>{const id=`ci-agent-prompt-${useId().replaceAll(":","")}`;const[value,setValue]=useState2("");const invocation=useAgentInvocation(organizationId);const submit=()=>{const prompt=value.trim();if(prompt.length===0||invocation.state.status==="submitting"){return}const submitInvocation=async()=>{try{const result=await invocation.invoke({agentId,idempotencyKey:createIdempotencyKey(),input:{prompt}});if(result.ok){setValue("")}onResult?.(result)}catch{}};submitInvocation()};return jsx2(AgentPromptPrimitive,{autoFocus,className,components,id,label,onChange:setValue,onSubmit:submit,pending:invocation.state.status==="submitting",status:invocationStatus(invocation.state),style,submitLabel,value})};import{FederatedAuthError}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext2,useCallback as useCallback2,useContext as useContext2,useEffect,useMemo as useMemo2,useSyncExternalStore}from"react";import{jsx as jsx3}from"react/jsx-runtime";var AuthContext=createContext2(null);var toFederatedAuthError=(error)=>new FederatedAuthError("authorization_failed",error.message);var unknownAuthError=()=>new FederatedAuthError("authorization_failed","Sign in failed");var CollectiveIntelligenceLoginProvider=(props)=>{const state=useSyncExternalStore(props.auth.subscribe,props.auth.getState,props.auth.getState);const contextValue=useMemo2(()=>({auth:props.auth,state}),[props.auth,state]);return jsx3(AuthContext.Provider,{value:contextValue,children:props.clientFactory===undefined?jsx3(CollectiveIntelligenceProvider,{client:props.client,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children}):jsx3(CollectiveIntelligenceProvider,{clientFactory:props.clientFactory,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children})})};var useCollectiveIntelligenceAuth=()=>{const value=useContext2(AuthContext);if(value===null){throw new Error("CollectiveIntelligenceLoginProvider must wrap authentication bindings")}return{...value,beginLogin:value.auth.beginLogin,completeLogin:value.auth.completeLogin,logout:value.auth.logout,reauthorize:value.auth.reauthorize}};var LoginButton=({children="Sign in with Collective Intelligence",className,components,disabled=false,onError,returnTo,style})=>{const{auth,state}=useCollectiveIntelligenceAuth();const Button=components?.Button??"button";const redirecting=state.status==="redirecting";const onClick=useCallback2((event)=>{event.preventDefault();const target=returnTo??globalThis.location.href;const begin=async()=>{try{await auth.beginLogin({returnTo:target})}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};begin()},[auth,onError,returnTo]);return jsx3(Button,{"aria-busy":redirecting,className:["ci-login-button",className].filter(Boolean).join(" "),disabled:disabled||redirecting,onClick,style,type:"button",children})};var callbackMessage=(state)=>{switch(state.status){case"authenticated":{return"Sign in complete"}case"error":{return state.error.message}case"expired":{return"Sign in expired"}case"anonymous":case"redirecting":{return"Completing sign in"}default:{return"Completing sign in"}}};var LoginCallbackPrimitive=({className,components,state,style})=>{const Status=components?.Status??"div";return jsx3(Status,{"aria-live":"polite",className:["ci-login-callback",className].filter(Boolean).join(" "),style,children:callbackMessage(state)})};var LoginCallback=({callbackUrl,onComplete,onError,...primitiveProps})=>{const{auth,state}=useCollectiveIntelligenceAuth();useEffect(()=>{const url=callbackUrl??globalThis.location.href;const complete=async()=>{try{const{returnTo}=await auth.completeLogin(url);onComplete?.(returnTo)}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};complete()},[auth,callbackUrl,onComplete,onError]);return jsx3(LoginCallbackPrimitive,{...primitiveProps,state})};var useSession=()=>{const{state}=useCollectiveIntelligenceAuth();return state};var SessionGate=({children,fallback=null})=>{const session=useSession();if(session.status!=="authenticated"){return fallback}return children};import{FederatedAuthError as FederatedAuthError2}from"@collective-intelligence/external-apps-client-sdk";import{CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import*as Schema from"effect/Schema";import{createContext as createContext3,useCallback as useCallback3,useContext as useContext3,useEffect as useEffect2,useMemo as useMemo3,useReducer,useRef as useRef2,useState as useState3}from"react";var initialSignInState={email:"",methods:null,notice:null,stage:"email"};var reduceSignIn=(state,{email=state.email,step})=>{const next={email,methods:state.methods,notice:null};switch(step.step){case"methods":{const{step:_methods,...methods}=step;return{...state,methods}}case"code_sent":{return{...next,stage:"code"}}case"registration_required":{return{...next,stage:"name"}}case"invalid_code":{return{...next,notice:step,stage:"code"}}case"retry_after":{return{...state,email,notice:step}}case"invalid_input":{return{...state,notice:{step:step.step}}}case"email_domain_not_allowed":{return{...next,notice:step,stage:"email"}}case"access_denied":case"code_expired":{return{...next,notice:{step:step.step},stage:"email"}}case"sso_required":{return{...next,provider:step.provider,stage:"sso_required"}}case"signed_in":{return{...next,registered:step.registered,stage:"signed_in"}}case"no_sign_in_method":case"redirect_to_web":{return{...next,stage:step.step}}default:{return step}}};import{jsx as jsx4}from"react/jsx-runtime";var defaultLabels={accessDenied:"You cannot sign in to this app with this address.",code:"Code",codeExpired:"The code is no longer valid. Enter your email again.",codeSentTo:(email)=>`Enter the code that we sent to ${email}.`,codeSubmit:"Continue",email:"Email",emailContinue:"Continue",emailDomainNotAllowed:(allowedDomains)=>`Use an address of ${allowedDomains.join(", ")}.`,emailSubmit:"Send code",invalidCode:(attemptsLeft)=>`The code is not correct. Attempts left: ${attemptsLeft}.`,invalidInput:"Check what you typed, then try again.",name:"Name",nameSubmit:"Create account",noSignInMethod:"No sign-in method is available for this app.",password:"Sign in with password",redirecting:"Opening the sign-in page…",resendCode:"Send a new code",retryAfter:(seconds)=>`Wait ${seconds} seconds, then ask for a new code.`,signedIn:"You are signed in.",sso:(provider)=>`Continue with ${provider}`,ssoRequired:(provider)=>`Your organization signs you in with ${provider}.`,title:"Sign in"};var SignInContext=createContext3(null);var noComponents={};var isSignInError=Schema.is(Schema.Union([CiTransportError,FederatedAuthError2]));var redirectToWeb={step:"redirect_to_web"};var SignInRoot=({children,components=noComponents,labels,...options})=>{const{auth}=useCollectiveIntelligenceAuth();if(!("signIn"in auth)){throw new Error("The sign-in components need the auth of createServerSessionAuth")}const{beginLogin,signIn}=auth;const[state,dispatch]=useReducer(reduceSignIn,initialSignInState);const[pending,setPending]=useState3(false);const running=useRef2(false);const latest=useRef2(options);useEffect2(()=>{latest.current=options});const run=useCallback3(async(call,email)=>{if(running.current){return}running.current=true;setPending(true);const answer=async()=>{try{const step=await call();dispatch(email===undefined?{step}:{email,step});if(step.step==="signed_in"){if(step.registered){latest.current.onRegistered?.()}latest.current.onSignedIn?.()}}catch(error){latest.current.onError?.(isSignInError(error)?error:new CiTransportError({cause:error}))}};await answer().finally(()=>{running.current=false;setPending(false)})},[]);const{actions,methods}=useMemo3(()=>{const returnTarget=()=>{const{returnTo}=latest.current;return returnTo===undefined?{}:{returnTo}};const languages=()=>{const{uiLocales}=latest.current;return uiLocales===undefined?{}:{uiLocales}};return{actions:{complete:(name)=>{run(()=>signIn.complete({name,...returnTarget()}))},password:()=>{run(async()=>{await beginLogin({returnTo:latest.current.returnTo??"/"});return redirectToWeb})},sso:(provider)=>{run(()=>signIn.sso({provider,...returnTarget()}))},start:(email)=>{run(()=>signIn.start({email,...languages(),...returnTarget()}),email)},verify:(code)=>{run(()=>signIn.verify({code,...returnTarget()}))}},methods:()=>{run(()=>signIn.methods({...languages(),...returnTarget()}))}}},[beginLogin,run,signIn]);useEffect2(()=>{methods()},[methods]);const value=useMemo3(()=>({binding:{...actions,pending,state},components,labels:{...defaultLabels,...labels}}),[actions,components,labels,pending,state]);return jsx4(SignInContext.Provider,{value,children})};var useSignInParts=()=>{const value=useContext3(SignInContext);if(value===null){throw new Error("SignIn.Root must wrap the sign-in components")}return value};var useSignIn=()=>useSignInParts().binding;import{Alert,AlertDescription,Button,Input,InputOTP,InputOTPGroup,InputOTPSlot}from"@collective-intelligence/ui-react/ui";import{LabeledField}from"@collective-intelligence/ui-react/ui-extensions/labeled-field";import{cn}from"@collective-intelligence/ui-react/utils/cn";import{useId as useId2}from"react";import{jsx as jsx5,jsxs as jsxs2}from"react/jsx-runtime";var codeSlots=[0,1,2,3,4,5];var CodeInput=(props)=>jsx5(InputOTP,{...props,maxLength:codeSlots.length,pattern:"^[0-9]+$",children:jsx5(InputOTPGroup,{children:codeSlots.map((index)=>jsx5(InputOTPSlot,{index},index))})});var Action=({variant,...props})=>{const{components}=useSignInParts();return components.Button===undefined?jsx5(Button,{variant,...props}):jsx5(components.Button,{...props})};var submitted=(event,name)=>{event.preventDefault();const value=new FormData(event.currentTarget).get(name);return value instanceof File||value===null?"":value.trim()};var EmailForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="email"){return null}const Field=components.EmailField??Input;const submitLabel=binding.state.methods?.emailCode===false?labels.emailContinue:labels.emailSubmit;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.start(submitted(event,"email"))},children:[jsx5(LabeledField,{id,label:labels.email,children:jsx5(Field,{autoComplete:"email",defaultValue:binding.state.email,id,name:"email",required:true,type:"email"})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:submitLabel})]})};var CodeForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="code"){return null}const{email}=binding.state;const Field=components.CodeField??CodeInput;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.verify(submitted(event,"code"))},children:[jsx5("p",{className:"text-sm",id:`${id}-sent`,children:labels.codeSentTo(email)}),jsx5(LabeledField,{id,label:labels.code,children:jsx5(Field,{"aria-describedby":`${id}-sent`,autoComplete:"one-time-code",id,name:"code",required:true})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.codeSubmit}),jsx5(Action,{disabled:binding.pending,onClick:()=>{binding.start(email)},type:"button",variant:"link",children:labels.resendCode})]})};var NameForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="name"){return null}const Field=components.NameField??Input;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.complete(submitted(event,"name"))},children:[jsx5(LabeledField,{id,label:labels.name,children:jsx5(Field,{autoComplete:"name",id,maxLength:255,name:"name",required:true})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.nameSubmit})]})};var ssoProviders=(state)=>{if(state.stage==="sso_required"){return[state.provider]}return state.stage==="email"?state.methods?.ssoProviders??[]:[]};var SsoButtons=({className})=>{const{binding,labels}=useSignInParts();const providers=ssoProviders(binding.state);if(providers.length===0){return null}return jsx5("div",{className:cn("grid gap-2",className),children:providers.map((provider)=>jsx5(Action,{disabled:binding.pending,onClick:()=>{binding.sso(provider.id)},type:"button",variant:"outline",children:labels.sso(provider.displayName)},provider.id))})};var PasswordButton=({className})=>{const{binding,labels}=useSignInParts();if(binding.state.stage!=="email"||binding.state.methods?.password!==true){return null}return jsx5(Action,{className,disabled:binding.pending,onClick:()=>{binding.password()},type:"button",variant:"outline",children:labels.password})};var noticeText=(notice,labels)=>{switch(notice.step){case"access_denied":{return labels.accessDenied}case"code_expired":{return labels.codeExpired}case"email_domain_not_allowed":{return labels.emailDomainNotAllowed(notice.allowedDomains)}case"invalid_code":{return labels.invalidCode(notice.attemptsLeft)}case"invalid_input":{return labels.invalidInput}case"retry_after":{return labels.retryAfter(notice.seconds)}default:{return notice}}};var Notice=({className})=>{const{binding,labels}=useSignInParts();const{notice}=binding.state;if(notice===null){return null}return jsx5(Alert,{className,variant:"destructive",children:jsx5(AlertDescription,{children:noticeText(notice,labels)})})};var statusText=(state,labels)=>{switch(state.stage){case"no_sign_in_method":{return labels.noSignInMethod}case"redirect_to_web":{return labels.redirecting}case"signed_in":{return labels.signedIn}case"sso_required":{return labels.ssoRequired(state.provider.displayName)}default:{return null}}};var Status=({className})=>{const{binding,labels}=useSignInParts();const text=statusText(binding.state,labels);if(text===null){return null}return jsx5("output",{className:cn("text-sm",className),children:text})};var SignIn={CodeForm,EmailForm,NameForm,Notice,PasswordButton,Root:SignInRoot,SsoButtons,Status};import{Card,CardContent,CardHeader,CardTitle}from"@collective-intelligence/ui-react/ui";import{jsx as jsx6,jsxs as jsxs3}from"react/jsx-runtime";var Title=()=>jsx6(CardTitle,{children:useSignInParts().labels.title});var SignInCard=({className,...rootProps})=>jsx6(SignIn.Root,{...rootProps,children:jsxs3(Card,{className,children:[jsx6(CardHeader,{children:jsx6(Title,{})}),jsxs3(CardContent,{className:"grid gap-4",children:[jsx6(SignIn.Notice,{}),jsx6(SignIn.EmailForm,{}),jsx6(SignIn.CodeForm,{}),jsx6(SignIn.NameForm,{}),jsx6(SignIn.SsoButtons,{}),jsx6(SignIn.PasswordButton,{}),jsx6(SignIn.Status,{})]})]})});import{createRealtimeClient}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext4,useContext as useContext4,useEffect as useEffect3,useState as useState4}from"react";import{jsx as jsx7}from"react/jsx-runtime";var idle={connections:0,lastEventId:undefined,status:"idle",topics:[]};var hasOnReset=(options)=>options.onReset!==undefined;var shareClient=(initial)=>{let options=initial;let shared={status:"none"};const subscriptions=new Set;const create=()=>createRealtimeClient({document:globalThis.document,window:globalThis.window,...options,onAccessChanged:()=>options.onAccessChanged?.(),onRefused:()=>options.onRefused?.(),...hasOnReset(options)&&{onReset:()=>options.onReset?.()}});const acquire=()=>{const client=shared.status==="none"?create():shared.client;shared={client,holders:shared.status==="held"?shared.holders+1:1,status:"held"};return client};const release=()=>{if(shared.status!=="held"){return}if(shared.holders>1){shared={...shared,holders:shared.holders-1};return}shared={client:shared.client,status:"releasing"};queueMicrotask(()=>{if(shared.status==="releasing"){shared.client.close();shared={status:"none"}}})};const subscribe=(topic,onChanges)=>{const subscription={onChanges,topic,unsubscribe:acquire().subscribe(topic,onChanges)};subscriptions.add(subscription);return()=>{if(subscriptions.delete(subscription)){subscription.unsubscribe();release()}}};return{acquire,getState:()=>shared.status==="none"?idle:shared.client.getState(),release,subscribe,update:(next)=>{const previous=options;options=next;if(shared.status==="none"||hasOnReset(next)===hasOnReset(previous)){return}for(const subscription of subscriptions){subscription.unsubscribe()}shared.client.close();const client=create();shared={...shared,client};for(const subscription of subscriptions){subscription.unsubscribe=client.subscribe(subscription.topic,subscription.onChanges)}}}};var RealtimeContext=createContext4(null);var RealtimeProvider=({children,...options})=>{const[shared]=useState4(()=>shareClient(options));useEffect3(()=>{shared.update(options)});useEffect3(()=>{shared.acquire();return shared.release},[shared]);return jsx7(RealtimeContext.Provider,{value:shared,children})};var useRealtimeClient=()=>{const client=useContext4(RealtimeContext);if(client===null){throw new Error("useRealtimeClient requires a RealtimeProvider")}return client};import{realtimeTopicKey}from"@collective-intelligence/external-apps-client-sdk";import{useEffect as useEffect4,useRef as useRef3,useState as useState5}from"react";var useRealtimeTopic=(topic,onChanges)=>{const client=useRealtimeClient();const latest=useRef3(onChanges);const key=topic===null?null:realtimeTopicKey(topic);const[subscribed,setSubscribed]=useState5({key,topic});if(subscribed.key!==key){setSubscribed({key,topic})}useEffect4(()=>{latest.current=onChanges});useEffect4(()=>subscribed.topic===null?undefined:client.subscribe(subscribed.topic,(changes)=>latest.current(changes)),[client,subscribed])};var clientSdkReactEntrypoint="react";export{AgentPrompt,AgentPromptPrimitive,CollectiveIntelligenceLoginProvider,CollectiveIntelligenceProvider,EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,LoginButton,LoginCallback,LoginCallbackPrimitive,RealtimeProvider,SessionGate,SignIn,SignInCard,clientSdkReactEntrypoint,createDelegatedEntitySource2 as createDelegatedEntitySource,createPromptKeyHandler,defineEntity2 as defineEntity,useAgentInvocation,useAgents,useAttachments,useClientContext,useCollectiveIntelligenceAuth,useCollectiveIntelligenceClient,useEntityViewState2 as useEntityViewState,useKnowledge,useMemoryEntityViewState2 as useMemoryEntityViewState,useOrganizationClient,useRealtimeClient,useRealtimeTopic,useRuns,useSession,useSignIn,useSkills,useWorkflows};
|
|
@@ -49,51 +49,56 @@ A package that declares Agents or Skills needs a person to install it; an instal
|
|
|
49
49
|
```mermaid
|
|
50
50
|
flowchart TD
|
|
51
51
|
ext["apps/extensions (@acme/extensions)<br/>index.ts: declarePackage, deploy order<br/>studio.ts: loadFrontendCatalog"]
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
52
|
+
idci["products/acme/identity/ci<br/>domain, Sales group, external application,<br/>profiles, grants, Studio app"]
|
|
53
|
+
idm["products/acme/identity/model<br/>package identity, VERSION"]
|
|
54
|
+
lead["features/lead/ci<br/>Lead schema, capabilities, policies"]
|
|
55
|
+
opp["features/opportunity/ci<br/>Opportunity schema, capabilities, policies"]
|
|
56
|
+
qual["features/lead-qualification/ci<br/>tool, Skill, Agent, widget"]
|
|
57
|
+
conv["features/lead-conversion/ci<br/>convert-lead workflow"]
|
|
58
|
+
models["model parts<br/>schema FQNs, capability codes, component FQNs"]
|
|
59
|
+
ext --> idci
|
|
60
|
+
ext --> idm
|
|
58
61
|
ext --> lead
|
|
59
62
|
ext --> opp
|
|
60
63
|
ext --> qual
|
|
61
64
|
ext --> conv
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
+
idci --> idm
|
|
66
|
+
idci -->|"grants by name"| models
|
|
67
|
+
lead --> models
|
|
68
|
+
opp --> models
|
|
69
|
+
qual --> models
|
|
65
70
|
```
|
|
66
71
|
|
|
67
|
-
The template keeps its CI code in three
|
|
72
|
+
The template keeps its CI code in three places. `apps/extensions` is the CI Extension Package app and the composition root. It imports the Identity Domain components and the factory of each domain's `ci` part, and lists every component in deploy order. The Identity Domain `products/acme/identity` holds everything the product shares. Its `model` part holds the package identity and `VERSION`. Its `ci` part holds the domain, the Sales Group, the external application, the profiles that grant the package capabilities, their grants and the Max Privileges. Each domain exports a factory from its `ci` part, for example `leadQualificationComponents({ application, audience, version })`. The factory takes the Identity Domain handles and the package version, and returns its components in deploy order. A `features` domain never imports a product, and a `ci` part never imports another domain's `ci` part. It names the resources of other domains by the constants in their `model` parts.
|
|
68
73
|
|
|
69
74
|
This is the whole package entry:
|
|
70
75
|
|
|
71
76
|
```ts
|
|
72
|
-
import {
|
|
73
|
-
import {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
} from "@
|
|
77
|
-
import {
|
|
78
|
-
import { opportunityComponents } from "@
|
|
77
|
+
import { declarePackage } from "@collective-intelligence/extensions-sdk"
|
|
78
|
+
import { declareFrontendCatalogContribution } from "@collective-intelligence/extensions-sdk-frontend"
|
|
79
|
+
import { leadComponents } from "@packages/features-lead-ci"
|
|
80
|
+
import { convertLeadComponents } from "@packages/features-lead-conversion-ci"
|
|
81
|
+
import { leadQualificationComponents } from "@packages/features-lead-qualification-ci"
|
|
82
|
+
import { leadScoreCardContributionFqn } from "@packages/features-lead-qualification-model"
|
|
83
|
+
import { opportunityComponents } from "@packages/features-opportunity-ci"
|
|
79
84
|
import {
|
|
80
85
|
acmeApplication,
|
|
81
86
|
crmDomain,
|
|
82
|
-
|
|
83
|
-
packageManifest,
|
|
87
|
+
identityComponents,
|
|
84
88
|
salesDeskApp,
|
|
85
|
-
salesMembers
|
|
89
|
+
salesMembers
|
|
90
|
+
} from "@packages/products-acme-identity-ci"
|
|
91
|
+
import {
|
|
92
|
+
packageManifest,
|
|
86
93
|
VERSION
|
|
87
|
-
} from "@acme
|
|
88
|
-
import { declarePackage } from "@collective-intelligence/extensions-sdk"
|
|
89
|
-
import { declareFrontendCatalogContribution } from "@collective-intelligence/extensions-sdk-frontend"
|
|
94
|
+
} from "@packages/products-acme-identity-model"
|
|
90
95
|
|
|
91
96
|
export default declarePackage({
|
|
92
97
|
components: [
|
|
93
98
|
crmDomain,
|
|
94
99
|
...leadComponents({ domain: crmDomain, version: VERSION }),
|
|
95
100
|
...opportunityComponents({ domain: crmDomain, version: VERSION }),
|
|
96
|
-
...
|
|
101
|
+
...identityComponents,
|
|
97
102
|
...convertLeadComponents({
|
|
98
103
|
application: acmeApplication,
|
|
99
104
|
version: VERSION
|
|
@@ -117,19 +122,19 @@ export default declarePackage({
|
|
|
117
122
|
})
|
|
118
123
|
```
|
|
119
124
|
|
|
120
|
-
`apps/extensions/src/studio.ts`
|
|
125
|
+
`apps/extensions/src/studio.ts` exports only `loadFrontendCatalog`. That function gathers the Studio renderers of the `ci` parts under the package identity. Only an app may import several `ci` parts, so the catalog lives in `apps/extensions`. `ci package build` resolves a relative `load` import against the declaration file, so the contribution is the one declaration in `apps/extensions`. The build ships every export of that module to the browser, so it exports only the catalog loader.
|
|
121
126
|
|
|
122
|
-
One
|
|
127
|
+
One domain such as `features/lead` keeps each runtime in its own part: the CI schema in `ci`, the BFF code in `server` and the React views in `client`. Each part has one runtime, so `turbo boundaries` keeps React out of the CI release. The `runtime:ci` tag lets a `ci` part import only `ci`, neutral and build packages, and the `part:*` tags stop a part from importing a `server`, `client` or `ci` part.
|
|
123
128
|
|
|
124
|
-
The template names components `acme.app.<kind>.<name>`, for example `acme.app.tools.lead-score` or `acme.app.workflows.convert-lead`, and the package itself is `acme.app.knowledge`. Each
|
|
129
|
+
The template names components `acme.app.<kind>.<name>`, for example `acme.app.tools.lead-score` or `acme.app.workflows.convert-lead`, and the package itself is `acme.app.knowledge`. Each domain's `model` part exports its FQN constants, and other code imports the constant instead of typing the string again.
|
|
125
130
|
|
|
126
131
|
A widget needs two declarations. On the backend side, `declareStudioComponent` with `category: "widget"`, a `propsSchema` and a `sourceRef` goes into `components`. On the frontend side, `declareFrontendComponent` with a `load` callback and a `studio_component` target is returned from `loadFrontendCatalog`. The `sourceRef` names the Studio hosted contribution of the package.
|
|
127
132
|
|
|
128
133
|
To add a component to the template:
|
|
129
134
|
|
|
130
|
-
1. Declare it in the
|
|
135
|
+
1. Declare it in the `ci` part of the domain that owns it. Put its FQN constant in the domain's `model` part when other code names it.
|
|
131
136
|
2. Add it to `components` in `apps/extensions/src/index.ts` after every component it references.
|
|
132
|
-
3. Bump `VERSION` in `packages/
|
|
137
|
+
3. Bump `VERSION` in `packages/products/acme/identity/model/src/package.ts`. The package and every component share this one version.
|
|
133
138
|
|
|
134
139
|
## Lifecycle
|
|
135
140
|
|
|
@@ -10,7 +10,7 @@ The template keeps the families apart. Package code imports only `extensions-sdk
|
|
|
10
10
|
|
|
11
11
|
```mermaid
|
|
12
12
|
flowchart LR
|
|
13
|
-
subgraph pkg["Package: apps/extensions and
|
|
13
|
+
subgraph pkg["Package: apps/extensions and the ci parts"]
|
|
14
14
|
decl["Declarations<br/>extensions-sdk"]
|
|
15
15
|
impl["Tool and connector classes<br/>extensions-sdk-backend"]
|
|
16
16
|
widget["Studio widgets<br/>extensions-sdk-frontend(-react)"]
|
|
@@ -32,7 +32,7 @@ flowchart LR
|
|
|
32
32
|
server -->|"confidential credentials"| backend
|
|
33
33
|
```
|
|
34
34
|
|
|
35
|
-
In the template, the left side is `apps/extensions` plus the
|
|
35
|
+
In the template, the left side is `apps/extensions` plus the `ci` part of each domain. The CLI builds that code into a release and installs it into your Organization. After install, CI runs the backend classes and Studio renders the widgets, so this code never runs in your app.
|
|
36
36
|
|
|
37
37
|
The right side is `apps/web`. Its browser code talks to its own server through a same-origin proxy, and the server calls CI with the application's confidential credentials. A browser can also call CI directly through the client SDK; in that case your app does not need the server SDK.
|
|
38
38
|
|
|
@@ -122,7 +122,7 @@ import { useQuery } from "@tanstack/react-query"
|
|
|
122
122
|
|
|
123
123
|
`external-apps-client-sdk-react` adds `CollectiveIntelligenceProvider`, `CollectiveIntelligenceLoginProvider` and the entity hooks on `/resources`: `useEntityList`, `useEntityRecord`, `useEntityCreate`, `useEntityUpdate` and `useEntityDelete`. A write hook reports `conflict`, `rejected` and `uncertain` as well as `idle`, `pending` and `success`, and `resubmit()` repeats the exact same action when the user asks for it. Install its peers in your app: `react`, `react-dom`, `@tanstack/react-query`, `xstate`, `effect` and `@collective-intelligence/ui-react`.
|
|
124
124
|
|
|
125
|
-
The template's own pages use the template's shadcn/ui package, `@
|
|
125
|
+
The template's own pages use the template's shadcn/ui package, `@packages/ui-design-system`. `ui-react` appears in the Studio widget and in SDK toasts.
|
|
126
126
|
|
|
127
127
|
### Server SDK subpaths an external app uses
|
|
128
128
|
|
|
@@ -129,7 +129,7 @@ The app's server acts only with the grants that an Organization admin gave to it
|
|
|
129
129
|
|
|
130
130
|
## Data policies narrow records
|
|
131
131
|
|
|
132
|
-
A capability opens a feature. A Knowledge Data Policy decides which records of one schema that capability reaches. Each template entity
|
|
132
|
+
A capability opens a feature. A Knowledge Data Policy decides which records of one schema that capability reaches. Each template entity domain declares its capabilities and two policies for its schema in its `ci` part: reading needs `read` on the entity's capabilities, and writing needs `manage`. This is the Lead write policy in `@packages/features-lead-ci`:
|
|
133
133
|
|
|
134
134
|
```ts
|
|
135
135
|
declareAccessKnowledgeDataPolicy({
|
|
@@ -170,7 +170,7 @@ export const managerProfile = declareAccessProfile({
|
|
|
170
170
|
})
|
|
171
171
|
```
|
|
172
172
|
|
|
173
|
-
The
|
|
173
|
+
The Identity Domain grants the entity capabilities by the FQN constants that `@packages/features-lead-model` and `@packages/features-opportunity-model` export. The Sales rep profile holds the same gate with `platform.knowledge`, `platform.agents` and `read` on Leads and Opportunities. It leaves out `platform.workflows` and `manage`.
|
|
174
174
|
|
|
175
175
|
The gate lets a user in. Max Privileges then limit what the app's user tokens may use, for every caller including tenant users:
|
|
176
176
|
|
|
@@ -227,7 +227,7 @@ flowchart LR
|
|
|
227
227
|
Route --> CI["CI<br/>grants, Max Privileges, policies<br/>for the run and each record"]
|
|
228
228
|
```
|
|
229
229
|
|
|
230
|
-
An Access Requirement is a serializable guard built from `requires`, `enters`, `allOf` and `anyOf`. A
|
|
230
|
+
An Access Requirement is a serializable guard built from `requires`, `enters`, `allOf` and `anyOf`. A domain exports the requirement of each operation from its `ci` part, so the page and the route check the same value. On the server, `CiRuntime.access(cookie)` returns the app's slice of the user's capabilities, and `holds(slice, requirement)` checks one requirement against it. The browser SDK session holds no access data.
|
|
231
231
|
|
|
232
232
|
```tsx
|
|
233
233
|
const CrmLeaf = async () => {
|
|
@@ -245,7 +245,7 @@ Dashboard feature flags such as `organization_onboarding`, `knowledge_setup` and
|
|
|
245
245
|
The template's CRM page has a Convert action that starts the convert-lead workflow. Here is how to give it to every Sales member.
|
|
246
246
|
|
|
247
247
|
1. Check what the template does today. `convertLeadRequirement` is `{ mode: "on", requires: "platform.workflows" }`. Only the Sales manager profile allows `core.platform.workflows`, so today only members of Sales managers see Convert and can run it. A member who is only in Sales gets no button, and the BFF route answers 403.
|
|
248
|
-
2. Add `allow(core.platform.workflows)` to `repProfile` in the
|
|
248
|
+
2. Add `allow(core.platform.workflows)` to `repProfile` in the Identity Domain (`packages/products/acme/identity/ci`). The app's Max Privileges already allow `platform.workflows`, so they need no change. Bump `VERSION`, then build, publish, promote and install the package.
|
|
249
249
|
3. Know who the run acts as. The BFF route starts the workflow with the signed-in user's delegated token, so the run acts as that user, with the user's current grants, and not as `convertLeadRunner`. The workflow's only node sets a run variable (`converted: true`) and writes no Lead record, so no Knowledge write policy takes part. Confirm it with one trial run as a rep before the demo.
|
|
250
250
|
4. Sign in as a user who is only in Sales. The CRM page now shows Convert, and `POST /api/leads/:id/convert` answers `{ runId }`. In the Dashboard Check access tab, choose that user and `platform.workflows` to see which grant gives it. Allow up to 60 seconds after a grant change, or wait for the realtime access event to refresh the page.
|
|
251
251
|
|
|
@@ -111,7 +111,7 @@ The `next-effect-app` template has two composition roots, one for each side of t
|
|
|
111
111
|
| `apps/extensions` | Inside CI, installed in the Organization | `extensions-sdk`, `extensions-sdk-backend`, `extensions-sdk-frontend-react`, `ui-react` | `ci package build`, publish, promote and install |
|
|
112
112
|
| `apps/web` | Your host, as a Next.js app | `external-apps-server-sdk` on the server, `external-apps-client-sdk-react` in the browser | The BFF calls the Application API |
|
|
113
113
|
|
|
114
|
-
The package root in `apps/extensions` is short. It lists the
|
|
114
|
+
The package root in `apps/extensions` is short. It lists the Identity Domain components and the components of each domain's `ci` part in deploy order, with the Lead score card widget for Studio:
|
|
115
115
|
|
|
116
116
|
```ts
|
|
117
117
|
export default declarePackage({
|
|
@@ -119,7 +119,7 @@ export default declarePackage({
|
|
|
119
119
|
crmDomain,
|
|
120
120
|
...leadComponents({ domain: crmDomain, version: VERSION }),
|
|
121
121
|
...opportunityComponents({ domain: crmDomain, version: VERSION }),
|
|
122
|
-
...
|
|
122
|
+
...identityComponents,
|
|
123
123
|
...convertLeadComponents({
|
|
124
124
|
application: acmeApplication,
|
|
125
125
|
version: VERSION
|
|
@@ -250,7 +250,7 @@ A connection keeps every field that its template marks secret as a secret. A pac
|
|
|
250
250
|
|
|
251
251
|
## Code entrypoints
|
|
252
252
|
|
|
253
|
-
Code in the template imports CI packages and its own workspaces by package name and exported
|
|
253
|
+
Code in the template imports CI packages and its own workspaces by package name and exported entry, for example `@packages/features-lead-client`, and never by relative path. A CI SDK splits its code by subpath. A template domain splits its code by part: one package for each runtime.
|
|
254
254
|
|
|
255
255
|
### SDK subpaths
|
|
256
256
|
|
|
@@ -268,32 +268,30 @@ The SDKs split by where the code runs. [SDKs](../develop/sdks.md) has the full m
|
|
|
268
268
|
|
|
269
269
|
Every SDK puts its Promise API at the root and its Effect services, Layers, errors and Schemas at `/effect`. `effect` is a required peer of every SDK, so install it next to the SDK and keep one `effect` version in the app. Optional peers such as Next.js, Express, Drizzle, Better Auth and the AI SDK sit behind their own subpaths, so importing the server SDK root never loads them. In the template, `/next` is imported only inside `apps/web/src/server`, because `/next` loads Next.js and `/effect` does not.
|
|
270
270
|
|
|
271
|
-
### Template
|
|
271
|
+
### Template domain parts
|
|
272
272
|
|
|
273
|
-
Each template
|
|
273
|
+
Each template domain has up to four parts. A part is one package with one runtime:
|
|
274
274
|
|
|
275
|
-
|
|
|
276
|
-
|
|
|
277
|
-
| `
|
|
278
|
-
| `
|
|
279
|
-
| `
|
|
280
|
-
| `
|
|
281
|
-
| `headless` | Typed client, query options, XState machines, entity bindings, Realtime hooks, simulated sources | `views`, the app |
|
|
282
|
-
| `views` | Wired React views on `@acme/ui`, with slots for feature parts | The app |
|
|
275
|
+
| Part | Holds | Imported by |
|
|
276
|
+
| -------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------- |
|
|
277
|
+
| `model` | Effect Schema models, resource contracts, pure rules, the domain `HttpApi` under `/api/app`, and the CI names other parts need | the domain's other parts, other domains, the apps |
|
|
278
|
+
| `server` | The route Layer of the domain `HttpApi` and its services | `apps/web/src/server` only |
|
|
279
|
+
| `client` | Typed client, query options, XState machines, entity bindings, Realtime hooks, simulated sources, wired React views | the app |
|
|
280
|
+
| `ci` | CI declarations, written as factories over Identity Domain handles | `apps/extensions` |
|
|
283
281
|
|
|
284
|
-
|
|
282
|
+
In one domain, `server`, `client` and `ci` import their own `model` and never each other. Across domains, a part imports only the other domain's `model` part. `turbo boundaries` enforces these rules with the `tier:*`, `runtime:*` and `part:*` tags of each package.
|
|
285
283
|
|
|
286
|
-
A
|
|
284
|
+
A domain has only the parts it needs. `features/lead` has all four, while `features/lead-qualification` has only `model` and `ci`. Its `ci` part holds the lead qualifier agent, its Skill, its tool and its Studio widget, and its `model` part holds their FQNs. The `ci` part is where solution code becomes code that CI installs.
|
|
287
285
|
|
|
288
286
|
### Template routes and widgets
|
|
289
287
|
|
|
290
|
-
The web app has three route files, and each only re-exports handlers from `server/` and the
|
|
288
|
+
The web app has three route files, and each only re-exports handlers from `server/` and the domain parts:
|
|
291
289
|
|
|
292
|
-
| Route file | Serves
|
|
293
|
-
| ------------------------------------- |
|
|
294
|
-
| `app/api/app/[[...path]]/route.ts` | The app's own API, composed from the
|
|
295
|
-
| `app/api/[...path]/route.ts` | The CI BFF: sign-in, Resources, Realtime ticket
|
|
296
|
-
| `app/api/leads/[id]/convert/route.ts` | The fixed convert-lead workflow
|
|
290
|
+
| Route file | Serves |
|
|
291
|
+
| ------------------------------------- | ------------------------------------------------------ |
|
|
292
|
+
| `app/api/app/[[...path]]/route.ts` | The app's own API, composed from the domain `HttpApi`s |
|
|
293
|
+
| `app/api/[...path]/route.ts` | The CI BFF: sign-in, Resources, Realtime ticket |
|
|
294
|
+
| `app/api/leads/[id]/convert/route.ts` | The fixed convert-lead workflow |
|
|
297
295
|
|
|
298
296
|
Inside CI, a Studio or Dashboard widget enters through a hosted contribution. You write `declareFrontendCatalogContribution({ fqn, host: "studio", load: () => import("./studio") })` and pass it to `declarePackage({ hostedContributions })`. The `load` function stays out of the serialized package manifest, and the loaded module exports `loadFrontendCatalog` for the host.
|
|
299
297
|
|
|
@@ -8,100 +8,113 @@ What you get from next-effect-app, where each piece of code goes, and how to tak
|
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
10
|
apps/
|
|
11
|
-
web/
|
|
12
|
-
extensions/
|
|
11
|
+
web/ # @acme/web Next app: routes, composition, Data Sources, app API and BFF instances
|
|
12
|
+
extensions/ # @acme/extensions Extension Package declaration (composes the ci parts)
|
|
13
13
|
packages/
|
|
14
|
-
|
|
15
|
-
features/
|
|
16
|
-
features/
|
|
17
|
-
features/
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
modules/identity
|
|
21
|
-
modules/app-api
|
|
22
|
-
|
|
23
|
-
tooling/config/
|
|
14
|
+
products/acme/identity/{model,ci} # Identity Domain: package identity and VERSION, access, groups, external application, Sales desk
|
|
15
|
+
features/lead/{model,server,client,ci} # Lead contract and CI names, Lead API and Read Port, Realtime and views, CI schema
|
|
16
|
+
features/opportunity/{model,client,ci} # Opportunity contract and CI names, views, CI schema
|
|
17
|
+
features/intake/{model,server,client} # lead intake: schemas and API, store, XState flow and views
|
|
18
|
+
features/lead-conversion/{client,ci} # convert-lead browser flow and Workflow
|
|
19
|
+
features/lead-qualification/{model,ci} # lead qualifier agent, Skill, tool, Studio widget, and their FQNs
|
|
20
|
+
modules/identity-{api,server,client} # principal and Authentication contract, CI runtime, login providers
|
|
21
|
+
modules/app-api, app-api-server # typed domain API client, QueryClient, simulated network; ApiPrefetch
|
|
22
|
+
ui/design-system/ # shadcn/ui primitives, AI Elements, theme, workspace-kit
|
|
23
|
+
tooling/config/ # shared TypeScript base config and the Layout Guard
|
|
24
24
|
```
|
|
25
25
|
|
|
26
|
-
Intake is a form with an XState flow and an app API that keeps its data in an in-memory store. Lead conversion is a Fixed workflow started by a single-action task. Lead qualification is an agent with a Skill, a tool and a Studio widget. The repository has no docs wiki, no infra folder and no generated client code, because the browser derives each typed client from its
|
|
26
|
+
Intake is a form with an XState flow and an app API that keeps its data in an in-memory store. Lead conversion is a Fixed workflow started by a single-action task. Lead qualification is an agent with a Skill, a tool and a Studio widget. The repository has no docs wiki, no infra folder and no generated client code, because the browser derives each typed client from its domain `HttpApi` at runtime. It also ships an agent harness: an `AGENTS.md` per scope, and `.agents/` with skills, rules and lint scripts.
|
|
27
27
|
|
|
28
|
-
##
|
|
28
|
+
## Domains, parts and the import rules
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
The template groups its code by domain. One domain is one folder, and each runtime of the domain is its own package, a part. The folder directly below `packages/` is the kind:
|
|
31
|
+
|
|
32
|
+
| Kind | Holds |
|
|
33
|
+
| ------------------------------------ | ---------------------------------------------------------- |
|
|
34
|
+
| `features/<domain>/<part>` | a domain that names no product, such as `lead` or `intake` |
|
|
35
|
+
| `products/<product>/<domain>/<part>` | a domain of one product; it may name its product |
|
|
36
|
+
| `ui/<name>` | the design system and page blocks, with no product terms |
|
|
37
|
+
| `modules/<name>` | business-agnostic machinery with one runtime |
|
|
38
|
+
| `tooling/<name>` | TypeScript, lint, build and test configuration |
|
|
39
|
+
|
|
40
|
+
A domain has only the parts it needs, and each part has exactly one runtime:
|
|
41
|
+
|
|
42
|
+
| Part | Runtime | Holds |
|
|
43
|
+
| -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
44
|
+
| `model` | neutral | Effect Schema models, resource contracts, pure rules, the domain `HttpApi` under `/api/app`, and the CI names other parts need |
|
|
45
|
+
| `server` | server | the route Layer of the domain `HttpApi` and its services; only `apps/web/src/server` imports it |
|
|
46
|
+
| `client` | client | typed client, query options, XState machines, entity bindings, Realtime topics and hooks, simulated sources, wired React views |
|
|
47
|
+
| `ci` | ci | CI declarations (extensions SDK) as factories over Identity Domain handles |
|
|
48
|
+
|
|
49
|
+
A package name is `@packages/` plus its path below `packages/`, with `-` in place of `/`. For example, `packages/features/lead/client` is `@packages/features-lead-client`. The apps keep their own names. Every internal dependency uses `workspace:*`. A part exports `.`, and a `client` part adds `./headless` only when a consumer needs state without components.
|
|
31
50
|
|
|
32
51
|
```mermaid
|
|
33
52
|
flowchart TD
|
|
34
53
|
web["apps/web"]
|
|
35
54
|
ext["apps/extensions"]
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
f2["lead-conversion"]
|
|
40
|
-
f3["lead-qualification"]
|
|
55
|
+
subgraph identity["products/acme/identity"]
|
|
56
|
+
im["model"]
|
|
57
|
+
ic["ci"]
|
|
41
58
|
end
|
|
42
|
-
subgraph
|
|
43
|
-
|
|
44
|
-
|
|
59
|
+
subgraph lead["features/lead"]
|
|
60
|
+
lm["model"]
|
|
61
|
+
ls["server"]
|
|
62
|
+
lc["client"]
|
|
63
|
+
lci["ci"]
|
|
45
64
|
end
|
|
46
|
-
subgraph
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
m3["ui"]
|
|
65
|
+
subgraph conv["features/lead-conversion"]
|
|
66
|
+
cc["client"]
|
|
67
|
+
cci["ci"]
|
|
50
68
|
end
|
|
51
|
-
|
|
52
|
-
web
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
69
|
+
modules["modules, ui, tooling"]
|
|
70
|
+
web -->|"composes server and client parts"| ls
|
|
71
|
+
web --> lc
|
|
72
|
+
web --> cc
|
|
73
|
+
ext -->|"lists each ci part in deploy order"| lci
|
|
74
|
+
ext --> cci
|
|
75
|
+
ext --> ic
|
|
76
|
+
ic -->|"grants by the names in model parts"| lm
|
|
77
|
+
ls --> lm
|
|
78
|
+
lc --> lm
|
|
79
|
+
lci --> lm
|
|
80
|
+
cc -->|"another domain's model only"| lm
|
|
81
|
+
lc --> modules
|
|
82
|
+
lc -.-|"never imports"| cc
|
|
61
83
|
```
|
|
62
84
|
|
|
63
|
-
|
|
85
|
+
- In one domain, `server`, `client` and `ci` import their own `model`. They never import each other.
|
|
86
|
+
- Across domains, a part imports only the other domain's `model` part. The `server`, `client` and `ci` parts of different domains meet only in an app: `apps/web` composes the views, and `apps/extensions` composes the `ci` parts.
|
|
87
|
+
- `features`, `ui` and `modules` never import `products`. A product never imports another product.
|
|
88
|
+
- `ui` imports only `ui` and `tooling`. `modules` imports only `modules` and `tooling`.
|
|
64
89
|
|
|
65
|
-
The
|
|
90
|
+
The rules are real configuration. Each workspace `turbo.json` has the Boundary Tags of its place: one `tier:*` tag, one `runtime:*` tag (apps have none), and one `part:*` tag for a part. The root `turbo.json` holds one rule for each tag, and `bunx turbo boundaries` fails the build on a wrong import:
|
|
66
91
|
|
|
67
92
|
```json
|
|
68
|
-
"tier:features": { "dependencies": { "allow": ["tier:
|
|
69
|
-
"
|
|
70
|
-
"
|
|
93
|
+
"tier:features": { "dependencies": { "allow": ["tier:features", "tier:ui", "tier:modules", "tier:tooling"] } },
|
|
94
|
+
"runtime:client": { "dependencies": { "deny": ["runtime:server", "runtime:ci"] } },
|
|
95
|
+
"part:client": { "dependencies": { "deny": ["part:server", "part:client", "part:ci"] } }
|
|
71
96
|
```
|
|
72
97
|
|
|
73
|
-
|
|
98
|
+
The full table is `BOUNDARY_TAGS` from `@collective-intelligence/lint/layout`. The `part:*` rules deny every `server`, `client` and `ci` part, so a part reaches only `model` parts. An app has no `part:*` tag, so the parts of different domains meet there.
|
|
74
99
|
|
|
75
|
-
|
|
100
|
+
Workspaces import each other by package name and exported entry, such as `@packages/features-lead-client`, and never by relative path.
|
|
76
101
|
|
|
77
|
-
|
|
102
|
+
The template has these domains:
|
|
78
103
|
|
|
79
|
-
|
|
|
80
|
-
|
|
|
81
|
-
| `
|
|
82
|
-
| `
|
|
83
|
-
| `
|
|
84
|
-
| `
|
|
85
|
-
| `
|
|
86
|
-
| `
|
|
104
|
+
| Domain | Parts |
|
|
105
|
+
| ----------------------------- | --------------------------------- |
|
|
106
|
+
| `features/lead` | `model`, `server`, `client`, `ci` |
|
|
107
|
+
| `features/opportunity` | `model`, `client`, `ci` |
|
|
108
|
+
| `features/intake` | `model`, `server`, `client` |
|
|
109
|
+
| `features/lead-conversion` | `client`, `ci` |
|
|
110
|
+
| `features/lead-qualification` | `model`, `ci` |
|
|
111
|
+
| `products/acme/identity` | `model`, `ci` |
|
|
87
112
|
|
|
88
|
-
|
|
113
|
+
`features/lead-qualification` adds an agent, a Skill, a tool and a Studio widget, and all of that is CI-side behavior. Its `model` holds only the FQNs, and its `ci` part holds the declarations. That shows that you can ship an AI capability without writing any web code.
|
|
89
114
|
|
|
90
|
-
|
|
115
|
+
## Domains take their audience as a parameter
|
|
91
116
|
|
|
92
|
-
|
|
93
|
-
| -------------------------- | ------------------------------------- |
|
|
94
|
-
| `@acme/lead` | `domain ci api server headless views` |
|
|
95
|
-
| `@acme/opportunity` | `domain ci headless views` |
|
|
96
|
-
| `@acme/intake` | `domain api server headless views` |
|
|
97
|
-
| `@acme/lead-conversion` | `ci headless views` |
|
|
98
|
-
| `@acme/lead-qualification` | `ci` |
|
|
99
|
-
|
|
100
|
-
`@acme/lead-qualification` adds an agent, a Skill, a tool and a Studio widget, and all of that is CI-side behavior. Its single `./ci` subpath shows that you can ship an AI capability without writing any web code.
|
|
101
|
-
|
|
102
|
-
## Features take their audience as a parameter
|
|
103
|
-
|
|
104
|
-
A feature package must not import `@acme/organization`, because organization sits above it in the tiers. A feature that offers something to a group of users therefore takes that `audience`, and the application handle, as parameters. The organization package owns the groups, the application and the profiles; each entity package declares its own capabilities and Knowledge Data Policies, and the profiles grant them by the FQN constants of `@acme/lead/ci` and `@acme/opportunity/ci`. `apps/extensions/src/index.ts` passes the organization handles in and lists every component in deploy order, where each component follows the components it references:
|
|
117
|
+
`products/acme/identity` is the Identity Domain of the product `acme`. Its `model` part holds the package identity and `VERSION`. Its `ci` part holds the groups, the application, the Access Profiles, their grants and the Max Privileges. A `features` domain never imports a product, so a `ci` part that offers something to a group of users takes that `audience`, and the application handle, as parameters. Each domain declares its own capabilities and Knowledge Data Policies in its `ci` part. The profiles grant them by the FQN constants of `@packages/features-lead-model` and `@packages/features-opportunity-model`. `apps/extensions/src/index.ts` passes the Identity Domain handles in and lists every component in deploy order, where each component follows the components it references:
|
|
105
118
|
|
|
106
119
|
```ts
|
|
107
120
|
export default declarePackage({
|
|
@@ -109,7 +122,7 @@ export default declarePackage({
|
|
|
109
122
|
crmDomain,
|
|
110
123
|
...leadComponents({ domain: crmDomain, version: VERSION }),
|
|
111
124
|
...opportunityComponents({ domain: crmDomain, version: VERSION }),
|
|
112
|
-
...
|
|
125
|
+
...identityComponents,
|
|
113
126
|
...convertLeadComponents({
|
|
114
127
|
application: acmeApplication,
|
|
115
128
|
version: VERSION
|
|
@@ -126,21 +139,21 @@ export default declarePackage({
|
|
|
126
139
|
})
|
|
127
140
|
```
|
|
128
141
|
|
|
129
|
-
`
|
|
142
|
+
`identityComponents` holds the Sales Group, the application, the profiles, their grants and the Max Privileges. The Studio contribution is the one declaration in `apps/extensions`: `ci package build` resolves its relative `load` import against that file.
|
|
130
143
|
|
|
131
144
|
[Extensions](../develop/extensions.md) describes each kind of declaration, and [Access](../platform/access.md) explains the Access Profiles and Access Grants in that list.
|
|
132
145
|
|
|
133
146
|
## The web app layers
|
|
134
147
|
|
|
135
|
-
|
|
148
|
+
Domain code lives in the domain parts. The web app keeps only routes, Composition, the sign-in gate, Data Sources and server instances, arranged in a fixed set of layers where each layer imports only the layers below it:
|
|
136
149
|
|
|
137
|
-
| Layer in `apps/web/src` | Holds
|
|
138
|
-
| ----------------------- |
|
|
139
|
-
| `app/` | route files only; each re-exports a Composition export, and `app/api/**` forwards to `server/<domain>/server`
|
|
140
|
-
| `composition/` | `providers/` (global providers, Realtime providers) and `routing/` (access, shells, pages)
|
|
141
|
-
| `features/` | app-local capabilities: their Data Sources (`remote/server.ts`) and `page-link/`
|
|
142
|
-
| `entities/` | app-local entity machinery that several features need (the CI session), Data Sources of
|
|
143
|
-
| `server/` | beside the layers: one folder per domain, where `server.ts` (`server-only`) holds the process instance
|
|
150
|
+
| Layer in `apps/web/src` | Holds |
|
|
151
|
+
| ----------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
152
|
+
| `app/` | route files only; each re-exports a Composition export, and `app/api/**` forwards to `server/<domain>/server` |
|
|
153
|
+
| `composition/` | `providers/` (global providers, Realtime providers) and `routing/` (access, shells, pages) |
|
|
154
|
+
| `features/` | app-local capabilities: their Data Sources (`remote/server.ts`) and `page-link/` |
|
|
155
|
+
| `entities/` | app-local entity machinery that several features need (the CI session), Data Sources of domain parts, `page-link/` |
|
|
156
|
+
| `server/` | beside the layers: one folder per domain, where `server.ts` (`server-only`) holds the process instance |
|
|
144
157
|
|
|
145
158
|
Only Composition imports a Data Source, and only Data Sources and `app/api/**` import a `server/<domain>/server.ts`. Peers still meet without importing each other: the CRM page template passes `ConvertLead` into the `selectionActions` slot of `LeadWorkspace` and `LeadAttachment` into its `editorActions` slot. Each page's owner gives its `{ label, path }` in `page-link/`, and shells and links read it, so no route path is written twice.
|
|
146
159
|
|
|
@@ -148,7 +161,7 @@ One Next app serves two server surfaces:
|
|
|
148
161
|
|
|
149
162
|
| Path | Handler | What it is |
|
|
150
163
|
| ------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
|
151
|
-
| `/api/app/*` | `server/app-api/server` | the app API: the
|
|
164
|
+
| `/api/app/*` | `server/app-api/server` | the app API: the domains' Effect `HttpApi`s merged , OpenAPI at `/api/app/openapi.json`, Scalar docs at `/api/app/docs` |
|
|
152
165
|
| `/api/*` | `server/ci/server` | the CI SDK BFF: sign-in with a sealed cookie, Lead and Opportunity resource proxy, Realtime ticket and revalidate routes |
|
|
153
166
|
| `/api/leads/[id]/convert` | `server/ci/server` | the Fixed convert-lead workflow route |
|
|
154
167
|
|
|
@@ -157,7 +170,7 @@ The BFF holds the CI session in a sealed cookie and proxies resource calls, so t
|
|
|
157
170
|
## Start a new demo
|
|
158
171
|
|
|
159
172
|
1. Generate a repository with **Use this template** on the template repository. In the new repository, delete the README "Contributing" section and `.github/workflows/close-pull-requests.yml`, which only matter in the template repository itself.
|
|
160
|
-
2. Rename the template for the customer. Replace the `@acme/` package
|
|
173
|
+
2. Rename the template for the customer. Replace the `@acme/` app names, the product folder `packages/products/acme` with its package names `@packages/products-acme-*`, and the `acme.app.` FQNs. Replace `https://acme.localhost` in `packages/products/acme/identity/ci/src/application.ts` and `.env.example`, and replace the theme tokens and the sidebar brand in `apps/web/src/composition/routing/shells/workspace/app-sidebar.tsx`. Theme tokens live once, in `packages/ui/design-system/src/styles/globals.css`.
|
|
161
174
|
3. Run it locally. The Overview and Lead intake pages work with no configuration, because the intake API keeps requests in memory:
|
|
162
175
|
|
|
163
176
|
```bash
|
|
@@ -226,22 +239,22 @@ The BFF holds the CI session in a sealed cookie and proxies resource calls, so t
|
|
|
226
239
|
|
|
227
240
|
## What to change and what to keep
|
|
228
241
|
|
|
229
|
-
A new demo changes the
|
|
242
|
+
A new demo changes the Identity Domain, the `features` domains, the theme and the origins. It keeps the `modules/identity-*` and `modules/app-api*` packages, the BFF and server wiring, the Boundary Tags, the Layout Guard, the lint configuration and the harness files, because they hold no business logic. A new environment variable goes into `apps/web/.env.example`, `packages/modules/identity-server/src/env.ts`, `turbo.json` `globalEnv` and the README tenant section together.
|
|
230
243
|
|
|
231
244
|
## Checks that keep the structure honest
|
|
232
245
|
|
|
246
|
+
Three checks keep the layout. `turbo boundaries` checks every import against the Boundary Tags. The Layout Guard, the Bun test `packages/tooling/config/src/workspace-layout.test.ts`, checks what the tags cannot express: the root `workspaces` globs, package names, each `turbo.json`, `workspace:*` ranges and product isolation. The `ci-solution/workspace-layout` lint rule reports a package that sits outside the accepted places. All three read one layout definition, `@collective-intelligence/lint/layout`.
|
|
247
|
+
|
|
233
248
|
`@collective-intelligence/lint` is one Oxlint plugin named `ci-solution`. Extending `recommended` turns every rule on as an error:
|
|
234
249
|
|
|
235
|
-
| Rule | Checks
|
|
236
|
-
| -------------------------------- |
|
|
237
|
-
| `ci-solution/package-entrypoint` | an import of another package targets an entrypoint in its `package.json` `exports`
|
|
238
|
-
| `ci-solution/
|
|
239
|
-
| `ci-solution/subpath
|
|
240
|
-
| `ci-solution/
|
|
241
|
-
| `ci-solution/effect-
|
|
242
|
-
| `ci-solution/
|
|
243
|
-
| `ci-solution/effect-actors` | XState side-effect actors are `fromEffect` actors |
|
|
244
|
-
| `ci-solution/effect-writes` | no module uses TanStack Query `useMutation`; writes run in `fromEffect` actors |
|
|
250
|
+
| Rule | Checks |
|
|
251
|
+
| -------------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
252
|
+
| `ci-solution/package-entrypoint` | an import of another package targets an entrypoint in its `package.json` `exports` |
|
|
253
|
+
| `ci-solution/workspace-layout` | each workspace sits at `apps/<name>`, a domain part, or `packages/{ui,modules,tooling}/<name>` |
|
|
254
|
+
| `ci-solution/effect-subpath` | SDK Effect APIs come from the SDK `/effect` subpath |
|
|
255
|
+
| `ci-solution/no-run-in-view` | a view module calls no `fetch` and runs no Effect |
|
|
256
|
+
| `ci-solution/effect-actors` | XState side-effect actors are `fromEffect` actors |
|
|
257
|
+
| `ci-solution/effect-writes` | no module uses TanStack Query `useMutation`; writes run in `fromEffect` actors |
|
|
245
258
|
|
|
246
259
|
Each package has an `oxlint.local.ts` that extends the preset:
|
|
247
260
|
|
|
@@ -264,14 +277,14 @@ The web app also runs a `frontend-layers` lint for layer order, domain entrypoin
|
|
|
264
277
|
|
|
265
278
|
```bash
|
|
266
279
|
bun run check-types
|
|
267
|
-
bun run test
|
|
280
|
+
bun run test # includes the Layout Guard
|
|
268
281
|
bunx turbo boundaries
|
|
269
282
|
bun run lint
|
|
270
283
|
bun run format:check
|
|
271
284
|
bun run build
|
|
272
285
|
```
|
|
273
286
|
|
|
274
|
-
When you change the Lead cache, a Lead write or Lead Realtime, also run `bun run check:models` in `packages/
|
|
287
|
+
When you change the Lead cache, a Lead write or Lead Realtime, also run `bun run check:models` in `packages/features/lead/client`. [State machines](state-machines.md) explains what that command checks.
|
|
275
288
|
|
|
276
289
|
## Related pages
|
|
277
290
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
How next-effect-app models UI flows as XState machines with Effect actors, keeps server data in the QueryCache, resends uncertain writes safely, and checks hard flows with Models.
|
|
4
4
|
|
|
5
|
-
In `next-effect-app`, a UI flow that carries business logic is an XState machine in the `headless/` folder of its
|
|
5
|
+
In `next-effect-app`, a UI flow that carries business logic is an XState machine in the `src/headless/` folder of its domain's `client` part, at `src/headless/<flow>-machine.ts`. Flows that belong only to the web app live at `apps/web/src/{features,entities}/<domain>/<flow>-machine.ts`. The machine decides where the flow is: editing, reviewing, submitting, failed. Every side effect is an Effect program that the machine runs as an actor, and TanStack Query owns the remote data that those programs read and write.
|
|
6
6
|
|
|
7
7
|
The machine context holds flow state only and never an API response. Two views that show the same record therefore read one cache entry, and no machine keeps a copy that can go stale. Server Components never run machines or Effects; they await a Promise boundary, and machines exist only in client code.
|
|
8
8
|
|
|
@@ -72,7 +72,7 @@ submitting: {
|
|
|
72
72
|
|
|
73
73
|
Leaving the invoking state interrupts the Effect fiber. The machine has no UI of its own: `submitted` is a typed action, and the view provides the toast with `machine.provide({ actions })`. The view runs `useMachine(intakeMachine.provide(...), { input: { runtime } })` and renders by `snapshot.matches("editing")`, `matches("submitting")` and `matches("done")`.
|
|
74
74
|
|
|
75
|
-
The same `provide` call swaps the data source for a demo without a backend. A simulated source lives in `headless/simulated-*.ts`, built with `simulate("<pace>", effect)` from `@
|
|
75
|
+
The same `provide` call swaps the data source for a demo without a backend. A simulated source lives in `headless/simulated-*.ts`, built with `simulate("<pace>", effect)` from `@packages/modules-app-api`, and only Composition or a test selects it. Tests use the same mechanism. A test drives the machine on a `ManagedRuntime` of the SDK `makeTestQueryCache` layer, never a hand-made `QueryCache` double, and asserts on cache entries or recorded calls:
|
|
76
76
|
|
|
77
77
|
```ts
|
|
78
78
|
const cache = makeTestQueryCache({ seed: [[intakeRequestsQuery.queryKey, []]] })
|
|
@@ -160,7 +160,7 @@ stateDiagram-v2
|
|
|
160
160
|
done --> running: RUN with a new file
|
|
161
161
|
```
|
|
162
162
|
|
|
163
|
-
The steps inside `running` are steps of the Effect program, and the machine itself sees one `running` state. A resubmit skips the upload and sends only the final write. The size and type checks use `leadAttachmentAccepts` and `leadAttachmentMaxBytes` (5 MiB) from `@
|
|
163
|
+
The steps inside `running` are steps of the Effect program, and the machine itself sees one `running` state. A resubmit skips the upload and sends only the final write. The size and type checks use `leadAttachmentAccepts` and `leadAttachmentMaxBytes` (5 MiB) from `@packages/features-lead-model`. The CI schema declares the same values on the File field, so CI refuses a larger upload too, while a file that fails the local check sends nothing.
|
|
164
164
|
|
|
165
165
|
The write that might need a resend is a value the failure carries:
|
|
166
166
|
|
|
@@ -224,7 +224,7 @@ A Model is a `*.proof.ts` TypeScript module that states the state, actions and i
|
|
|
224
224
|
| `/** @constraint */` | a bound, so the search ends |
|
|
225
225
|
| `ghost` prefix on a `let` | records what a consumer saw, only to state a guarantee |
|
|
226
226
|
|
|
227
|
-
The Lead Realtime Model in `packages/
|
|
227
|
+
The Lead Realtime Model in `packages/features/lead/client/src/headless/lead-realtime.proof.ts` is trimmed here. The full file also has `writeConfirm`, `otherWrite`, `realtimeChange` and `neverBehindConfirmed`:
|
|
228
228
|
|
|
229
229
|
```ts
|
|
230
230
|
let server: Revision = 0
|
|
@@ -260,7 +260,7 @@ export const isRefetchDue = () => refetchDue && !isFresh()
|
|
|
260
260
|
The checker visits 22 states and proves two things. A Realtime refetch never hides the tab's pending optimistic write (`pendingWriteShown`, `neverBehindConfirmed`), and after a Realtime change the views eventually reach the stored revision (`@leadsTo isFresh`). The package runs it with one script:
|
|
261
261
|
|
|
262
262
|
```bash
|
|
263
|
-
cd packages/
|
|
263
|
+
cd packages/features/lead/client
|
|
264
264
|
bun run check:models
|
|
265
265
|
```
|
|
266
266
|
|
package/docs/sign-in.md
CHANGED
|
@@ -42,7 +42,8 @@ For a fully own UI, read `useSignIn()` inside `SignIn.Root`: `state`,
|
|
|
42
42
|
`pending`, and the actions `start(email)`, `verify(code)`, `complete(name)`,
|
|
43
43
|
`sso(provider)` and `password()`. `state.stage` is `email`, `code`, `name`,
|
|
44
44
|
`sso_required`, `signed_in`, `redirect_to_web` or `no_sign_in_method`;
|
|
45
|
-
`state.notice` holds the refusal of the last call, such as `invalid_code
|
|
45
|
+
`state.notice` holds the refusal of the last call, such as `invalid_code` or
|
|
46
|
+
`invalid_input`.
|
|
46
47
|
|
|
47
48
|
## Rules
|
|
48
49
|
|
|
@@ -50,6 +51,10 @@ For a fully own UI, read `useSignIn()` inside `SignIn.Root`: `state`,
|
|
|
50
51
|
mounts; the SSO buttons and the password button follow its answer. Run each
|
|
51
52
|
later step through the actions of `useSignIn`, not through `auth.signIn`,
|
|
52
53
|
so the state follows every answer.
|
|
54
|
+
- When the app allows no email code (`methods.emailCode` is `false`), the
|
|
55
|
+
email form stays: CI sends the address to its SSO provider or to the CI
|
|
56
|
+
page. Its button shows `labels.emailContinue` in place of
|
|
57
|
+
`labels.emailSubmit`.
|
|
53
58
|
- `pending` is true from an action until its call settles, on React 18
|
|
54
59
|
and 19. An action while a call runs does nothing: show `pending` in an
|
|
55
60
|
own UI, and do not queue the next step.
|
|
@@ -59,6 +64,10 @@ For a fully own UI, read `useSignIn()` inside `SignIn.Root`: `state`,
|
|
|
59
64
|
- `onError` gets `CiTransportError` (the call got no step) or
|
|
60
65
|
`FederatedAuthError` (the SDK could not navigate). The form keeps its
|
|
61
66
|
values. A refusal such as a wrong code is no error: `SignIn.Notice` shows it.
|
|
67
|
+
- An email, code or name that CI cannot read, such as `bob@example`, is the
|
|
68
|
+
`invalid_input` step, not a fault: the same form stays, `SignIn.Notice`
|
|
69
|
+
asks the person to check the input (`labels.invalidInput`), and `onError`
|
|
70
|
+
does not run.
|
|
62
71
|
- `labels` replaces any default text; some texts are functions, such as
|
|
63
72
|
`invalidCode(attemptsLeft)`. `className` goes on the card and on each part.
|
|
64
73
|
- `components` replaces `EmailField`, `CodeField`, `NameField` or `Button`. A
|
|
@@ -66,5 +75,6 @@ For a fully own UI, read `useSignIn()` inside `SignIn.Root`: `state`,
|
|
|
66
75
|
render one input with them, because the form reads the value by `name`.
|
|
67
76
|
- The auth of `createFederatedAuth` has no `signIn`: the sign-in components
|
|
68
77
|
throw with it. Use `LoginButton` for the CI page instead.
|
|
69
|
-
- The components import `@collective-intelligence/ui-react/ui
|
|
70
|
-
|
|
78
|
+
- The components import `@collective-intelligence/ui-react/ui` and
|
|
79
|
+
`@collective-intelligence/ui-react/ui-extensions/labeled-field`; install the
|
|
80
|
+
`ui-react` peer `react-hook-form`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@collective-intelligence/external-apps-client-sdk-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "React bindings for Collective Intelligence external applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -48,11 +48,11 @@
|
|
|
48
48
|
"type-check": "bun check --no-script -p tsconfig.json"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@collective-intelligence/external-apps-client-sdk": "0.
|
|
51
|
+
"@collective-intelligence/external-apps-client-sdk": "0.7.0",
|
|
52
52
|
"nuqs": "2.10.1"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
|
-
"@collective-intelligence/ui-react": "0.
|
|
55
|
+
"@collective-intelligence/ui-react": "0.7.0",
|
|
56
56
|
"@tanstack/react-query": "^5.101.4",
|
|
57
57
|
"effect": "^4.1.0",
|
|
58
58
|
"react": ">=18.2 <20",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"access": "public"
|
|
64
64
|
},
|
|
65
65
|
"devDependencies": {
|
|
66
|
-
"@collective-intelligence/ui-react": "0.
|
|
66
|
+
"@collective-intelligence/ui-react": "0.7.0",
|
|
67
67
|
"@effect/eslint-plugin": "0.3.2",
|
|
68
68
|
"@oxlint/plugins": "1.94.0",
|
|
69
69
|
"@punks/lints": "0.2.0",
|
|
@@ -92,5 +92,5 @@
|
|
|
92
92
|
"vitest": "4.1.10",
|
|
93
93
|
"xstate": "5.33.3"
|
|
94
94
|
},
|
|
95
|
-
"gitHead": "
|
|
95
|
+
"gitHead": "e387355aacb167f048998872edebc78d4c669d8d"
|
|
96
96
|
}
|