vibe64 0.1.47 → 0.1.49
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/bin/run.js +1734 -1687
- package/bin/server.js +75 -75
- package/bin/upgrade-state.js +4539 -4471
- package/dist/assets/GithubBrowserTabs-BwpiRS2u.js +1 -0
- package/dist/assets/{LocalDatabaseServer-6VzPWZxG.js → LocalDatabaseServer-u_Ky7bNS.js} +1 -1
- package/dist/assets/{Vibe64AuthSettingsButton-TLwqAxDo.js → Vibe64AuthSettingsButton-BCwswT1G.js} +1 -1
- package/dist/assets/{Vibe64DashboardShell-B4dQ-oHD.js → Vibe64DashboardShell-CWlgrR2B.js} +1 -1
- package/dist/assets/{Vibe64DatabaseWorkspace-Bh5WIPOj.js → Vibe64DatabaseWorkspace-Dhs8_H0P.js} +1 -1
- package/dist/assets/Vibe64OutputControls-Dn548CZa.js +8 -0
- package/dist/assets/{Vibe64RepositoryWorkspace-idDg94lc.js → Vibe64RepositoryWorkspace-C-8S4JUF.js} +1 -1
- package/dist/assets/{Vibe64SessionFiles-Z9zxosyl.js → Vibe64SessionFiles-Cx6J7DDN.js} +2 -3
- package/dist/assets/{Vibe64UiStoryboardView-CrCDWMdR.js → Vibe64UiStoryboardView-DHyhJiWS.js} +1 -1
- package/dist/assets/{Vibe64UnavailableSessions-TqsxvGSf.js → Vibe64UnavailableSessions-Da4RxIhA.js} +1 -1
- package/dist/assets/{_sessionId_-7F1VGOou.js → _sessionId_-DCpgDPSI.js} +1 -1
- package/dist/assets/_slug_-BbEWp01a.js +25 -0
- package/dist/assets/{_slug_-B16mTWjj.css → _slug_-DerKOisL.css} +1 -1
- package/dist/assets/{access-Cx9RH95J.js → access-D4di2sCr.js} +1 -1
- package/dist/assets/{app-DPx4KKOa.js → app-Adr9Iz8p.js} +1 -1
- package/dist/assets/asyncModuleRecovery-DJsn5NrL.js +1 -0
- package/dist/assets/{changes-DYsuQLFW.js → changes-3Dd1O8Lu.js} +1 -1
- package/dist/assets/client-BAXHGUOC.js +1 -0
- package/dist/assets/{client-BYsDPxR3.js → client-CCZIu6yc.js} +1 -1
- package/dist/assets/{conversation-3ln-WnbL.css → conversation-CSDHdGDb.css} +1 -1
- package/dist/assets/conversation-DG9lp25w.js +8 -0
- package/dist/assets/conversation-ErAO1CmH.js +13 -0
- package/dist/assets/{dashboard-CWswAbYP.js → dashboard-0tCzDYCX.js} +1 -1
- package/dist/assets/english-definitions-DeiQ-jTT.js +1 -0
- package/dist/assets/env-DsyQ2MFX.js +1 -0
- package/dist/assets/{health-C0f6s-G1.js → health-DyTXU-nb.js} +1 -1
- package/dist/assets/{history-BQjETNB9.js → history-BXGAdPMI.js} +1 -1
- package/dist/assets/{incoming-COpY201m.js → incoming-yajkdGBY.js} +1 -1
- package/dist/assets/{index-MWACm8Pp.css → index-B-dukXUB.css} +1 -1
- package/dist/assets/index-CGz4Yow6.js +136 -0
- package/dist/assets/{integrations-BBkvNRHu.js → integrations-BMrXET36.js} +10 -2
- package/dist/assets/issues-kc1XBZCK.js +1 -0
- package/dist/assets/{learning-B8_wHoe1.js → learning-CIE5ghYv.js} +1 -1
- package/dist/assets/linkPath-Ch9eft18.js +1 -0
- package/dist/assets/{placement-DXvgK433.js → placement-BNmlke_j.js} +1 -1
- package/dist/assets/placement-DYM3JJ-F.js +1 -0
- package/dist/assets/publish-DTh6amqi.js +3 -0
- package/dist/assets/pull-requests-CbfGSSIh.js +1 -0
- package/dist/assets/{repository-BNPt7UWc.js → repository-BstMh-bG.js} +1 -1
- package/dist/assets/settings-Bf8C6dls.js +1 -0
- package/dist/assets/{studioGateApi-BVdclhPL.js → studioGateApi-mkX1eOTX.js} +1 -1
- package/dist/assets/{studioUrls-CGKCbM_d.js → studioUrls-B0-GdWh8.js} +1 -1
- package/dist/assets/useArchivedVibe64Sessions-DIOpfUxD.js +1 -0
- package/dist/assets/useCommand-CVuya6vG.js +1 -0
- package/dist/assets/useEndpointResource-7-YDfAxX.js +1 -0
- package/dist/assets/usePaths-Y6UuQxmI.js +1 -0
- package/dist/assets/{useUiFeedback-B51xtCAK.js → useUiFeedback-Bd3rao6E.js} +1 -1
- package/dist/assets/useVibe64ConversationLog-ChJOU2SD.js +1 -0
- package/dist/assets/{useVibe64DatabaseTools-BE_yXZFn.js → useVibe64DatabaseTools-DKV-TeNJ.js} +1 -1
- package/dist/assets/{useVibe64ProjectScope-D7b8n1gx.js → useVibe64ProjectScope-DXjsKKhl.js} +1 -1
- package/dist/assets/useVibe64SessionData-BkIHUrP5.js +1 -0
- package/dist/assets/useVibe64SessionSelection-N8wX5oqo.js +1 -0
- package/dist/assets/{useVibe64SystemGraph-CDDcsye4.js → useVibe64SystemGraph-Db_eD-X8.js} +1 -1
- package/dist/assets/{useVibe64Terminal-Zr3Mig2L.js → useVibe64Terminal-B9EWJ9Ba.js} +2 -2
- package/dist/assets/vibe64ProjectScope.local-l5_-E6pq.js +1 -0
- package/dist/assets/vibe64RepositoryRealtime-CHT4-6VN.js +1 -0
- package/dist/assets/vibe64SessionFocus-CS6Ex53G.js +1 -0
- package/dist/assets/vibe64SessionFocus-CSm4YJQD.css +1 -0
- package/dist/assets/vibe64SessionRequestConfig-xIx-5jxQ.js +1 -0
- package/dist/index.html +26 -22
- package/docs/colleague-usage/ai-accounts.md +6 -2
- package/docs/colleague-usage/ai-balance-and-allowance.md +15 -2
- package/docs/colleague-usage/coding-agent-failures.md +2 -1
- package/docs/colleague-usage/coding-agent-goals.md +8 -3
- package/docs/colleague-usage/coding-agents.md +16 -0
- package/docs/colleague-usage/github-work.md +14 -0
- package/docs/colleague-usage/preview-browser-checks.md +5 -3
- package/docs/colleague-usage/project-setup.md +6 -3
- package/docs/colleague-usage/running-vibe64-on-your-computer.md +3 -1
- package/docs/colleague-usage/sessions.md +35 -7
- package/docs/colleague-usage/starter-apps.md +3 -0
- package/docs/colleague-usage/temporary-chat-context.md +2 -1
- package/docs/colleague-usage/temporary-chats.md +17 -5
- package/node_modules/@jskit-ai/assistant-core/CHANGELOG.md +539 -0
- package/node_modules/@jskit-ai/assistant-core/locales/en.json +383 -0
- package/node_modules/@jskit-ai/assistant-core/package.json +3 -2
- package/node_modules/@jskit-ai/assistant-runtime/CHANGELOG.md +138 -0
- package/node_modules/@jskit-ai/assistant-runtime/README.md +2 -1
- package/node_modules/@jskit-ai/assistant-runtime/locales/en.json +137 -0
- package/node_modules/@jskit-ai/assistant-runtime/package.json +3 -2
- package/node_modules/@jskit-ai/assistant-runtime/src/server/repositories/assistantConfigRepository.js +223 -203
- package/node_modules/@jskit-ai/assistant-runtime/src/server/repositories/conversationsRepository.js +286 -266
- package/node_modules/@jskit-ai/assistant-runtime/src/server/repositories/messagesRepository.js +270 -250
- package/node_modules/@jskit-ai/assistant-voice/locales/en.json +182 -0
- package/node_modules/@jskit-ai/assistant-voice/package.json +3 -2
- package/node_modules/@jskit-ai/connector-google-calendar/CHANGELOG.md +83 -0
- package/node_modules/@jskit-ai/connector-google-calendar/locales/en.json +91 -0
- package/node_modules/@jskit-ai/connector-google-calendar/package.json +4 -3
- package/node_modules/@jskit-ai/connectors-catalog/CHANGELOG.md +1722 -0
- package/node_modules/@jskit-ai/connectors-catalog/README.md +11 -0
- package/node_modules/@jskit-ai/connectors-catalog/locales/en.json +3139 -0
- package/node_modules/@jskit-ai/connectors-catalog/package.json +5 -4
- package/node_modules/@jskit-ai/connectors-core/CHANGELOG.md +183 -0
- package/node_modules/@jskit-ai/connectors-core/locales/en.json +92 -0
- package/node_modules/@jskit-ai/connectors-core/package.json +3 -2
- package/node_modules/@jskit-ai/http-runtime/CHANGELOG.md +31 -0
- package/node_modules/@jskit-ai/http-runtime/locales/en.json +14 -0
- package/node_modules/@jskit-ai/http-runtime/package.json +3 -2
- package/node_modules/@jskit-ai/kernel/CHANGELOG.md +182 -0
- package/node_modules/@jskit-ai/kernel/locales/en.json +94 -0
- package/node_modules/@jskit-ai/kernel/package.json +6 -2
- package/node_modules/@jskit-ai/payments-core/CHANGELOG.md +128 -0
- package/node_modules/@jskit-ai/payments-core/locales/en.json +77 -0
- package/node_modules/@jskit-ai/payments-core/package.json +3 -2
- package/node_modules/@jskit-ai/realtime/CHANGELOG.md +20 -0
- package/node_modules/@jskit-ai/realtime/locales/en.json +14 -0
- package/node_modules/@jskit-ai/realtime/package.json +3 -2
- package/node_modules/@jskit-ai/resource-core/package.json +1 -1
- package/node_modules/@jskit-ai/resource-crud-core/package.json +1 -1
- package/node_modules/@jskit-ai/uploads-runtime/CHANGELOG.md +35 -0
- package/node_modules/@jskit-ai/uploads-runtime/locales/en.json +15 -0
- package/node_modules/@jskit-ai/uploads-runtime/package.json +3 -2
- package/node_modules/@local/vibe64-execution/src/host/execHelper.js +49 -48
- package/node_modules/@local/vibe64-execution/src/server/gitTurnCheckpointCommand.js +1327 -0
- package/node_modules/@local/vibe64-genesis/bin/vibe64-genesis-host-context +430 -390
- package/node_modules/@local/vibe64-genesis/src/server/index.js +45 -45
- package/node_modules/@local/vibe64-genesis/src/server/promptContext.js +119 -119
- package/node_modules/@local/vibe64-runtime/src/server/codexAppServerProcess.js +57 -57
- package/node_modules/@local/vibe64-sessions/package.json +2 -1
- package/node_modules/@local/vibe64-terminals/src/server/opencodeSessionEnvironmentPlugin.js +195 -175
- package/node_modules/@local/vibe64-terminals/src/server/sessionWorkOperationCommand.js +1385 -1362
- package/package.json +15 -15
- package/server.bundle.mjs +44206 -42825
- package/dist/assets/GithubBrowserTabs-D-Z3TlA8.js +0 -1
- package/dist/assets/Vibe64OutputControls-DtybwgL3.js +0 -8
- package/dist/assets/_slug_-Bq84T_Iv.js +0 -24
- package/dist/assets/conversation-Bn7wpATa.js +0 -2
- package/dist/assets/conversation-CNcCrV-R.js +0 -16
- package/dist/assets/definitions-CEbi4qae.js +0 -1
- package/dist/assets/env-X7EOFLtl.js +0 -1
- package/dist/assets/index-CBo1BEk6.js +0 -138
- package/dist/assets/issues-BiSiUd5o.js +0 -1
- package/dist/assets/placement-B5T1LR7m.js +0 -1
- package/dist/assets/publish-CeLZE2AG.js +0 -3
- package/dist/assets/pull-requests-pTdQOT7i.js +0 -1
- package/dist/assets/settings-lecRzZ-r.js +0 -1
- package/dist/assets/useArchivedVibe64Sessions-DHYRnyJD.js +0 -1
- package/dist/assets/useCommand-Epd2yHhQ.js +0 -1
- package/dist/assets/useEndpointResource-DBRQISI_.js +0 -1
- package/dist/assets/usePaths-DdAnjVDj.js +0 -1
- package/dist/assets/useVibe64ConversationLog-DboM3tYN.js +0 -1
- package/dist/assets/useVibe64SessionData-CreWtQAO.js +0 -1
- package/dist/assets/useVibe64SessionSelection-CDaX4uwY.js +0 -1
- package/dist/assets/vibe64ProjectScope.local-BxTBYuRg.js +0 -1
- package/dist/assets/vibe64RepositoryRealtime-C-J0I5jY.js +0 -1
- package/dist/assets/vibe64SessionFocus-DSW5Irm6.css +0 -1
- package/dist/assets/vibe64SessionFocus-DzqbVq60.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ht as watch,g as computed,hn as proxyRefs,vn as ref}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{D as ROUTE_VISIBILITY_PUBLIC,t as useEndpointResource}from"./useEndpointResource-7-YDfAxX.js";import{g as useRoute}from"./useApi-BPuI6ZR9-CFWU1m37.js";import{d as getHttpWebClient,r as projectAppPath}from"./vibe64ProjectScope.local-l5_-E6pq.js";import{Nt as mdiFileDocumentOutline,gr as mdiSourceBranch,yr as mdiSourceCommit}from"./mdi-X9prU-DG.js";import{a as normalizeConversationLogPage,i as mergeConversationLogPages,o as normalizeConversationLogPagination,r as conversationLogReadQuery}from"./conversation-DG9lp25w.js";import{t as usePaths}from"./usePaths-Y6UuQxmI.js";import{n as useVibe64ProjectSlug}from"./useVibe64ProjectScope-DXjsKKhl.js";import{B as vibe64SessionsQueryKey,F as vibe64SessionPath,b as vibe64ConversationLogQueryKey,n as VIBE64_ARCHIVED_SESSIONS_API_SUFFIX,o as VIBE64_SESSIONS_API_SUFFIX,y as vibe64ConversationLogPath,z as vibe64SessionQueryKey}from"./vibe64SessionRequestConfig-xIx-5jxQ.js";import{C as readRefOrGetterValue}from"./index-CGz4Yow6.js";import{t as isArchivedVibe64Session}from"./vibe64SessionViewModel-B0cCumM8.js";import{n as enrichVibe64SessionForDisplay}from"./vibe64SessionPanelModel-DoorGDCG.js";import{t as normalizeConversationLog}from"./useVibe64ConversationLog-ChJOU2SD.js";function useArchivedVibe64ConversationHistory({active=true,projectSlug,session,sessionsApiPath}={}){const httpClient=getHttpWebClient();const sessionId=computed(()=>String(readRefOrGetterValue(session)?.sessionId||``).trim());const enabled=computed(()=>readRefOrGetterValue(active)!==false&&Boolean(sessionId.value));const path=computed(()=>sessionId.value?vibe64ConversationLogPath(readRefOrGetterValue(sessionsApiPath),sessionId.value):``);const resource=useEndpointResource({enabled,fallbackLoadError:`Conversation history could not be loaded.`,path,queryKey:computed(()=>vibe64ConversationLogQueryKey(`app`,ROUTE_VISIBILITY_PUBLIC,sessionId.value,readRefOrGetterValue(projectSlug))),queryOptions:{queryFn:({signal})=>httpClient.request(path.value,{method:`GET`,query:conversationLogReadQuery(),signal}),placeholderData:previousData=>previousData,refetchOnMount:false,refetchOnWindowFocus:false},readMethod:`GET`,refreshOnPull:true,requestRecoveryLabel:`Conversation history`,realtime:null});const olderPages=ref([]);const loadingMore=ref(false);const loadMoreError=ref(``);const latestPage=computed(()=>normalizeConversationLogPage(resource.data.value||{}));const oldestLoadedPage=computed(()=>olderPages.value[0]||latestPage.value);const hasMoreBefore=computed(()=>Boolean(normalizeConversationLogPagination(oldestLoadedPage.value?.pagination).hasMoreBefore));const turns=computed(()=>normalizeConversationLog(mergeConversationLogPages([...olderPages.value,latestPage.value])));function reload(){olderPages.value=[];loadMoreError.value=``;return resource.reload()}async function loadMore({complete}={}){const finish=result=>{if(typeof complete===`function`)complete(result)};const pagination=normalizeConversationLogPagination(oldestLoadedPage.value?.pagination);const beforeTurnId=pagination.nextBeforeTurnId||pagination.oldestTurnId||String(turns.value[0]?.turnId||``).trim();if(!enabled.value||!path.value||!hasMoreBefore.value||loadingMore.value||!beforeTurnId){finish({changed:false,loaded:false});return false}const requestedSessionId=sessionId.value;loadingMore.value=true;loadMoreError.value=``;try{const page=await httpClient.request(path.value,{method:`GET`,query:conversationLogReadQuery({beforeTurnId,limit:10})});if(sessionId.value!==requestedSessionId){finish({changed:false,loaded:false});return false}const messageCount=()=>turns.value.reduce((count,turn)=>count+(turn.messages?.length||0),0);const previousOldestTurnId=String(turns.value[0]?.turnId||``).trim();const previousMessageCount=messageCount();olderPages.value=[normalizeConversationLogPage(page),...olderPages.value];const nextOldestTurnId=String(turns.value[0]?.turnId||``).trim();finish({changed:Boolean(nextOldestTurnId&&(nextOldestTurnId!==previousOldestTurnId||messageCount()!==previousMessageCount)),loaded:true});return true}catch(error){if(sessionId.value===requestedSessionId)loadMoreError.value=String(error?.message||error||`Older conversation history could not be loaded.`);finish({changed:false,loaded:false});return false}finally{loadingMore.value=false}}watch(sessionId,()=>{olderPages.value=[];loadMoreError.value=``});return{error:resource.loadError,hasMoreBefore,loadMore,loadMoreError,loading:resource.isLoading,loadingMore,reload,turns}}var archivedVibe64SessionsEmits=[`loading-changed`];var archivedAtFormatter=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`});var archivedVibe64SessionsProps={description:{default:``,type:String},emptyText:{default:``,type:String},emptyTitle:{default:`No sessions`,type:String},showRefresh:{default:true,type:Boolean},title:{default:``,type:String}};function useArchivedVibe64Sessions(emit){const paths=usePaths();const projectSlug=useVibe64ProjectSlug();const sessionsApiPath=computed(()=>paths.api(VIBE64_ARCHIVED_SESSIONS_API_SUFFIX,{surface:`app`}));const sessionListResource=useEndpointResource({fallbackLoadError:`Archived sessions could not be loaded.`,path:sessionsApiPath,queryKey:computed(()=>[...vibe64SessionsQueryKey(`app`,ROUTE_VISIBILITY_PUBLIC,projectSlug.value),`archived`]),requestRecoveryLabel:`Archived sessions`});const loading=computed(()=>Boolean(sessionListResource.isLoading.value));const error=computed(()=>String(sessionListResource.loadError.value||``));const sessions=computed(()=>{const payload=sessionListResource.data.value;return(Array.isArray(payload?.sessions)?payload.sessions:[]).map(enrichVibe64SessionForDisplay).filter(isArchivedVibe64Session)});watch(loading,isLoading=>{emit(`loading-changed`,isLoading)},{immediate:true});return{unavailableSessions:computed(()=>sessionListResource.data.value?.unavailableSessions||[]),error,loadSessions,loading,formatArchivedAt,sessionRoute,sessions};async function loadSessions(){await sessionListResource.reload()}function sessionRoute(session={}){return archivedSessionDetailRoute({projectSlug:projectSlug.value,sessionId:session.sessionId})}}function useArchivedVibe64SessionDetail(){const route=useRoute();const paths=usePaths();const projectSlug=useVibe64ProjectSlug(route);const sessionId=computed(()=>firstRouteParam(route.params.sessionId));const sessionsApiPath=computed(()=>paths.api(VIBE64_SESSIONS_API_SUFFIX,{surface:`app`}));const sessionPath=computed(()=>sessionId.value?vibe64SessionPath(sessionsApiPath.value,sessionId.value):``);const sessionResource=useEndpointResource({enabled:computed(()=>Boolean(sessionId.value)),fallbackLoadError:`Archived session could not be loaded.`,path:sessionPath,queryKey:computed(()=>[...vibe64SessionQueryKey(`app`,ROUTE_VISIBILITY_PUBLIC,projectSlug.value),`archive-detail`,sessionId.value]),readQuery:computed(()=>projectSlug.value?{projectSlug:projectSlug.value}:null),requestRecoveryLabel:`Archived session`});const session=computed(()=>{const payload=sessionResource.data.value;if(!payload||typeof payload!==`object`||Array.isArray(payload))return null;if(String(payload.sessionId||``).trim()!==sessionId.value)return null;const enrichedSession=enrichVibe64SessionForDisplay(payload);return isArchivedVibe64Session(enrichedSession)?enrichedSession:null});return{backTo:computed(()=>({path:`${projectAppPath(projectSlug.value)}/dashboard/history`})),conversationLog:proxyRefs(useArchivedVibe64ConversationHistory({active:computed(()=>Boolean(session.value)),projectSlug,session,sessionsApiPath})),error:computed(()=>String(sessionResource.loadError.value||``)),loading:computed(()=>Boolean(sessionResource.isLoading.value||sessionResource.isInitialLoading?.value)),reload:sessionResource.reload,session,sessionId,sessionsApiPath,projectSlug}}function formatArchivedAt(value=``){const date=new Date(String(value||``));return Number.isNaN(date.getTime())?`time unavailable`:archivedAtFormatter.format(date)}function archivedSessionDetailRoute({projectSlug=``,sessionId=``}={}){return{path:`${projectAppPath(projectSlug)}/dashboard/history/${encodeURIComponent(String(sessionId||``).trim())}`}}function firstRouteParam(value){return String(Array.isArray(value)?value[0]:value||``).trim()}function metadataValue(session={},name=``){return String(session.metadata?.[name]||``).trim()}function archiveFactRows(session={}){return[{icon:mdiSourceBranch,label:`Branch`,value:session.branch||metadataValue(session,`source_recovery_branch`)},{icon:mdiSourceCommit,label:`Head`,value:metadataValue(session,`source_recovery_head`)||metadataValue(session,`base_commit`)},{icon:mdiFileDocumentOutline,label:`Saved patch`,value:metadataValue(session,`source_recovery_patch_artifact`)||`No saved patch`},{icon:mdiFileDocumentOutline,label:`Untracked files`,value:metadataValue(session,`source_recovery_untracked_artifact`)||`No saved untracked archive`}].filter(row=>row.value)}export{useArchivedVibe64Sessions as a,useArchivedVibe64SessionDetail as i,archivedVibe64SessionsEmits as n,archivedVibe64SessionsProps as r,archiveFactRows as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ht as watch,On as unref,g as computed,gn as reactive,hn as proxyRefs}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{r as useShellWebErrorRuntime}from"./error-W1ZAEk4a.js";import{A as useJskitText,C as resolveEnabledRef,S as ROUTE_VISIBILITY_WORKSPACE,_ as resolveApiSuffix,b as resolveQueryKey,d as asPlainObject,f as ensureAccessModeCompatibility,g as resolveAccessModeEnabled,h as normalizePermissions,l as toUiFieldErrors,m as normalizeOwnershipFilter,p as normalizeAccessMode,r as useOperationRealtime,t as useEndpointResource,tt as useQueryClient,v as resolveEnabled,y as resolvePermissionAccess}from"./useEndpointResource-7-YDfAxX.js";import{o as normalizeSurfaceId}from"./returnToPath-gKtcu91D.js";import{f as normalizeText}from"./normalize-BNAdWJYg.js";import{C as validateSchemaPayload,d as getHttpWebClient,m as createValidationFailure,v as hasPermission,y as normalizePermissionList}from"./vibe64ProjectScope.local-l5_-E6pq.js";import{n as resolveScopedRouteBase}from"./surface-DzO5xqc8.js";import{c as useWebPlacementContext,r as resolveSurfaceDefinitionFromPlacementContext}from"./placement-DYM3JJ-F.js";import{r as useSurfaceRouteContext,t as usePaths}from"./usePaths-Y6UuQxmI.js";import{t as useUiFeedback}from"./useUiFeedback-Bd3rao6E.js";var{t:t$3,text:text$1}=useJskitText();function validateOperationInput({input,rawPayload={},fieldBag=null,feedback=null,validationMessage=``}={}){if(!input)return{ok:true,parsedInput:rawPayload};try{return{ok:true,parsedInput:validateSchemaPayload(input,rawPayload,{phase:`input`,context:`operation input`})}}catch(error){if(!error?.fieldErrors||typeof error.fieldErrors!==`object`)throw error;const fieldErrorCodes=error.fieldErrorCodes||error.details?.fieldErrorCodes;const failure={...createValidationFailure({error:text$1(validationMessage)||t$3(`jskit.http.feedback.validationFailed`),code:`validation_failed`,fieldErrors:error?.fieldErrors}),...fieldErrorCodes?{fieldErrorCodes}:{}};fieldBag?.apply?.(toUiFieldErrors(failure));feedback?.error?.(failure,failure.error);return{ok:false,failure,parsedInput:null}}}var{t:t$2,text}=useJskitText();function useCommandCore({model,resource,writeMethod=`POST`,canRun,fieldBag,feedback,input,buildRawPayload,buildCommandPayload,buildCommandOptions,onRunSuccess,onRunError,suppressSuccessMessage=false,messages={}}={}){const queryClient=useQueryClient();const normalizedWriteMethod=String(writeMethod||`POST`).trim().toUpperCase();const running=resource?.isSaving;const fieldErrors=fieldBag?.errors;const message=feedback?.message;const messageType=feedback?.messageType;async function run(context={}){if(!canRun?.value||running?.value)return null;feedback?.clear?.();fieldBag?.clear?.();const rawPayload=typeof buildRawPayload===`function`?buildRawPayload(model,{queryClient,resource,context}):{};const validationResult=validateOperationInput({input,rawPayload,fieldBag,feedback,validationMessage:text(messages.validation)||t$2(`jskit.http.feedback.validationFailed`)});if(!validationResult.ok)return null;const{parsedInput}=validationResult;const payload=typeof buildCommandPayload===`function`?buildCommandPayload(parsedInput,{rawPayload,queryClient,resource,context}):normalizedWriteMethod===`DELETE`?void 0:parsedInput;const options=typeof buildCommandOptions===`function`?buildCommandOptions(parsedInput,{rawPayload,queryClient,resource,context}):{};try{const response=await resource.save(payload,options);if(typeof onRunSuccess===`function`)await onRunSuccess(response,{parsed:parsedInput,rawPayload,payload,options,queryClient,resource,context});if(!suppressSuccessMessage)feedback?.success?.(text(messages.success)||t$2(`jskit.http.feedback.completed`));return response}catch(error){fieldBag?.apply?.(toUiFieldErrors(error));if(typeof onRunError===`function`)await onRunError(error,{parsed:parsedInput,rawPayload,payload,options,queryClient,resource,context});feedback?.error?.(error,text(messages.error)||t$2(`jskit.http.feedback.actionFailed`));throw error}}return Object.freeze({running,fieldErrors,message,messageType,run})}var{t:t$1}=useJskitText();function asPermissionList(value){if(Array.isArray(value))return value;if(value===void 0||value===null||value===``)return[];return[value]}function useAccess({enabled=true,access=`always`,hasPermissionRequirements=false}={}){const normalizedAccessMode=normalizeAccessMode(access);const accessRequired=resolveAccessModeEnabled(normalizedAccessMode,{hasPermissionRequirements:hasPermissionRequirements===true});const{context:placementContext}=useWebPlacementContext();const queryEnabled=computed(()=>resolveEnabledRef(enabled)&&accessRequired);const hasPlacementPermissions=computed(()=>{const source=placementContext.value;if(!source||typeof source!==`object`)return false;return Object.hasOwn(source,`permissions`)});const placementPermissions=computed(()=>normalizePermissionList(placementContext.value?.permissions));const permissions=computed(()=>{if(!queryEnabled.value||!hasPlacementPermissions.value)return[];return placementPermissions.value});const permissionsUnavailableError=computed(()=>{if(!queryEnabled.value||hasPlacementPermissions.value)return``;return t$1(`jskit.http.access.permissionsUnavailable`)});const awaitingPlacementPermissions=computed(()=>queryEnabled.value&&!hasPlacementPermissions.value);function can(permission){return hasPermission(permissions.value,permission)}function canAny(requiredPermissions){const list=asPermissionList(requiredPermissions);if(list.length<1)return true;for(const entry of list)if(can(entry))return true;return false}function canAll(requiredPermissions){const list=asPermissionList(requiredPermissions);if(list.length<1)return true;for(const entry of list)if(!can(entry))return false;return true}return Object.freeze({accessMode:normalizedAccessMode,accessRequired,permissions,permissionsUnavailableError,awaitingPlacementPermissions,can,canAny,canAll})}var ROUTE_PARAM_NAME_PATTERN=/^[A-Za-z][A-Za-z0-9_]*$/;function normalizeRouteParamName(value=``,{context=`http-web route param`}={}){const normalizedValue=String(value||``).trim();if(!normalizedValue)throw new TypeError(`${context} must be a non-empty route parameter name.`);if(!ROUTE_PARAM_NAME_PATTERN.test(normalizedValue))throw new TypeError(`${context} "${normalizedValue}" is invalid. Use letters, numbers, and underscores only.`);return normalizedValue}function toRouteParamValue(value){if(Array.isArray(value))return toRouteParamValue(value[0]);if(value==null)return``;return String(value).trim()}function resolveRouteSourceValue(source=null){if(typeof source===`function`)return source();return unref(source)}function resolveRouteParamsSource(source=null){return asPlainObject(resolveRouteSourceValue(source))}function normalizeRouteParamNameList(value=[]){return(Array.isArray(value)?value:[]).map(entry=>String(entry||``).trim()).filter(Boolean)}function resolveRouteParamNamesSource(source=[]){return normalizeRouteParamNameList(resolveRouteSourceValue(source))}function normalizeRoutePathname(value=``){const sanitizedPathname=String(value||``).trim().split(/[?#]/u,1)[0]||``;if(!sanitizedPathname)return`/`;return sanitizedPathname.startsWith(`/`)?sanitizedPathname:`/${sanitizedPathname}`}function resolveRoutePathnameSource(source=``){return normalizeRoutePathname(resolveRouteSourceValue(source))}function segmentMatchesParamValue(segment=``,paramValue=``){const normalizedSegment=String(segment||``).trim();const normalizedParamValue=toRouteParamValue(paramValue);if(!normalizedSegment||!normalizedParamValue)return false;if(normalizedSegment===encodeURIComponent(normalizedParamValue))return true;try{return decodeURIComponent(normalizedSegment)===normalizedParamValue}catch{return false}}function findRouteParamSegmentIndex(segments=[],paramValue=``,fromIndex=0){const source=Array.isArray(segments)?segments:[];const cursor=Number.isInteger(fromIndex)&&fromIndex>0?fromIndex:0;for(let index=cursor;index<source.length;index+=1)if(segmentMatchesParamValue(source[index],paramValue))return index;return-1}function normalizePathPrefix(segments=[],endIndex=-1){const source=Array.isArray(segments)?segments:[];if(!Number.isInteger(endIndex)||endIndex<0)return`/`;return`/${source.slice(0,endIndex+1).join(`/`)}`}function resolveAnchorEndIndex(segmentIndex=-1,totalSegments=0,anchorMode=`at`){const normalizedSegmentIndex=Number.isInteger(segmentIndex)?segmentIndex:-1;if(normalizedSegmentIndex<0)return-1;const normalizedTotalSegments=Number.isInteger(totalSegments)&&totalSegments>0?totalSegments:0;const normalizedMode=String(anchorMode||`at`).trim().toLowerCase();if(normalizedMode===`before`)return normalizedSegmentIndex-1;if(normalizedMode===`after`)return normalizedTotalSegments>0?Math.min(normalizedSegmentIndex+1,normalizedTotalSegments-1):normalizedSegmentIndex+1;return normalizedSegmentIndex}function resolveScopedRoutePathname({currentPathname=`/`,params={},orderedParamNames=[],anchorParamName=``,anchorParamValue=``,anchorMode=`at`}={}){const normalizedCurrentPathname=resolveRoutePathnameSource(currentPathname);const normalizedAnchorParamName=String(anchorParamName||``).trim();if(!normalizedAnchorParamName)return normalizedCurrentPathname;const sourceParams=asPlainObject(params);const segments=normalizedCurrentPathname.split(`/`).filter(Boolean);if(segments.length<1)return normalizedCurrentPathname;const paramNames=resolveRouteParamNamesSource(orderedParamNames);let cursor=0;for(const paramName of paramNames){const segmentIndex=findRouteParamSegmentIndex(segments,sourceParams[paramName],cursor);if(segmentIndex<0)continue;if(paramName===normalizedAnchorParamName)return normalizePathPrefix(segments,resolveAnchorEndIndex(segmentIndex,segments.length,anchorMode));cursor=segmentIndex+1}const fallbackAnchorValue=toRouteParamValue(anchorParamValue)||toRouteParamValue(sourceParams[normalizedAnchorParamName]);if(!fallbackAnchorValue)return normalizedCurrentPathname;const fallbackSegmentIndex=findRouteParamSegmentIndex(segments,fallbackAnchorValue,0);if(fallbackSegmentIndex<0)return normalizedCurrentPathname;return normalizePathPrefix(segments,resolveAnchorEndIndex(fallbackSegmentIndex,segments.length,anchorMode))}function resolveRouteTemplatePath(routeTemplate=``,params={}){const normalizedTemplate=String(routeTemplate||``).trim();if(!normalizedTemplate)return``;const source=asPlainObject(params);const missingParams=[];const resolvedPath=normalizedTemplate.replace(/:([A-Za-z][A-Za-z0-9_]*)/g,(_,key)=>{const value=toRouteParamValue(source[key]);if(!value){missingParams.push(key);return`:${key}`}return encodeURIComponent(value)});if(missingParams.length>0)return``;return resolvedPath}function resolveRouteTemplateLocation(routeTemplate=``,{params={},currentPathname=`/`}={}){const resolvedTemplatePath=resolveRouteTemplatePath(routeTemplate,params);if(!resolvedTemplatePath)return``;if(resolvedTemplatePath.startsWith(`/`))return resolvedTemplatePath;const normalizedCurrentPathname=resolveRoutePathnameSource(currentPathname);const basePathname=normalizedCurrentPathname.endsWith(`/`)?normalizedCurrentPathname:`${normalizedCurrentPathname}/`;const resolvedPathname=new URL(resolvedTemplatePath,`https://jskit.local${basePathname}`).pathname;if(resolvedPathname.length>1&&resolvedPathname.endsWith(`/`))return resolvedPathname.slice(0,-1);return resolvedPathname}function createRouteTemplateResolver({recordIdParam,routeParams=null,routeParamNames=null,routePath=``,routeRecordId=null,anchorMode=`at`,anchorOnTargetRecord=false,fillRecordId=true}={}){function resolveCurrentRecordId(currentRouteParams=resolveRouteParamsSource(routeParams)){const explicitRecordId=toRouteParamValue(resolveRouteSourceValue(routeRecordId));if(explicitRecordId)return explicitRecordId;return toRouteParamValue(currentRouteParams[recordIdParam])}function resolveTemplatePath(urlTemplate=``,extraParams={}){const normalizedTemplate=String(urlTemplate||``).trim();if(!normalizedTemplate)return``;const currentRouteParams=resolveRouteParamsSource(routeParams);const sourceParams={...currentRouteParams,...asPlainObject(extraParams)};const currentRecordId=resolveCurrentRecordId(currentRouteParams);const targetRecordId=toRouteParamValue(sourceParams[recordIdParam])||currentRecordId;if(fillRecordId)sourceParams[recordIdParam]=targetRecordId;return resolveRouteTemplateLocation(normalizedTemplate,{params:sourceParams,currentPathname:resolveScopedRoutePathname({currentPathname:routePath,params:currentRouteParams,orderedParamNames:routeParamNames,anchorParamName:recordIdParam,anchorParamValue:anchorOnTargetRecord?targetRecordId:currentRecordId,anchorMode})})}return Object.freeze({resolveRecordId:()=>resolveCurrentRecordId(),resolveTemplatePath})}function extractRouteParamNames(pathTemplate=``){const normalizedTemplate=String(pathTemplate||``).trim();if(!normalizedTemplate)return[];const names=[];const seen=new Set;const pattern=/:([A-Za-z][A-Za-z0-9_]*)/g;let match=null;while((match=pattern.exec(normalizedTemplate))!=null){const name=String(match[1]||``).trim();if(!name||seen.has(name))continue;seen.add(name);names.push(name)}return names}function resolveRouteParamNamesInOrder(route=null){const sourceRoute=route&&typeof route===`object`?route:{};const matched=Array.isArray(sourceRoute.matched)?sourceRoute.matched:[];const names=[];const seen=new Set;for(const entry of matched){const entryPath=String(entry?.path||``).trim();if(!entryPath)continue;for(const name of extractRouteParamNames(entryPath)){if(seen.has(name))continue;seen.add(name);names.push(name)}}if(names.length>0)return names;return Object.keys(asPlainObject(sourceRoute.params)).map(entry=>String(entry||``).trim()).filter(Boolean)}var{t}=useJskitText();function resolveScopedRouteParamNames(placementContext=null,surfaceId=``){const routeBase=resolveSurfaceDefinitionFromPlacementContext(placementContext,surfaceId)?.routeBase||`/`;return extractRouteParamNames(resolveScopedRouteBase(routeBase))}function useScopeRuntime({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,accessMode=`auto`,hasPermissionRequirements=false}={}){const normalizedOwnershipFilter=normalizeOwnershipFilter(ownershipFilter);const normalizedAccessMode=ensureAccessModeCompatibility({accessMode,hasPermissionRequirements,caller:`useScopeRuntime`});const accessRequired=resolveAccessModeEnabled(normalizedAccessMode,{hasPermissionRequirements});const routeContext=useSurfaceRouteContext();const paths=usePaths({routeContext});const resolvedSurfaceId=computed(()=>{const explicitSurfaceId=normalizeSurfaceId(surfaceId);if(explicitSurfaceId)return explicitSurfaceId;return normalizeSurfaceId(routeContext.currentSurfaceId.value)});const scopedRouteParamNames=computed(()=>resolveScopedRouteParamNames(routeContext.placementContext.value,resolvedSurfaceId.value));const routeScopeParams=computed(()=>{const source=paths.routeParams.value;const next={};for(const paramName of scopedRouteParamNames.value){const paramValue=toRouteParamValue(source[paramName]);if(paramValue)next[paramName]=paramValue}return Object.freeze(next)});const missingScopedRouteParamNames=computed(()=>scopedRouteParamNames.value.filter(paramName=>!routeScopeParams.value[paramName]));const requiresScopedRouteParams=computed(()=>scopedRouteParamNames.value.length>0);const hasRequiredRouteScope=computed(()=>missingScopedRouteParamNames.value.length<1);const scopeParamValue=computed(()=>{const[primaryScopeParamName=``]=scopedRouteParamNames.value;return primaryScopeParamName?routeScopeParams.value[primaryScopeParamName]||``:``});const routeScopeError=computed(()=>{if(!requiresScopedRouteParams.value||hasRequiredRouteScope.value)return``;const missingParams=missingScopedRouteParamNames.value.join(`, `);return t(`jskit.http.access.routeParamsRequired`,{params:missingParams,surface:resolvedSurfaceId.value||`<unknown>`})});const accessRuntime=useAccess({enabled:computed(()=>accessRequired&&hasRequiredRouteScope.value),access:normalizedAccessMode,hasPermissionRequirements});function resolveApiPath(apiSuffix=``,context={}){if(routeScopeError.value)return``;const suffix=resolveApiSuffix(apiSuffix,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter,...asPlainObject(context)});return paths.api(suffix,{surface:resolvedSurfaceId.value,params:routeScopeParams.value})}function requireRouteScope(caller=`useScopeRuntime`){if(routeScopeError.value)throw new Error(`${caller}: ${routeScopeError.value}`)}return Object.freeze({normalizedOwnershipFilter,requiresScopedRouteParams:requiresScopedRouteParams.value,resolvedSurfaceId,accessMode:normalizedAccessMode,accessRequired,routeContext,scopedRouteParamNames,routeScopeParams,scopeParamValue,hasRequiredRouteScope,routeScopeError,access:accessRuntime,resolveApiPath,requireRouteScope})}function normalizePermissionSets(permissionSets={}){const source=permissionSets&&typeof permissionSets===`object`&&!Array.isArray(permissionSets)?permissionSets:{};const normalized={};for(const[key,value]of Object.entries(source))normalized[key]=normalizePermissions(value);return normalized}function hasAnyPermissions(permissionSets={}){for(const list of Object.values(permissionSets))if(Array.isArray(list)&&list.length>0)return true;return false}function useOperationScope({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,access=`auto`,apiSuffix=``,model,readEnabled=true,queryKeyFactory=null,permissionSets={},realtime=null}={}){const normalizedPermissionSets=normalizePermissionSets(permissionSets);const scopeRuntime=useScopeRuntime({ownershipFilter,surfaceId,accessMode:access,hasPermissionRequirements:hasAnyPermissions(normalizedPermissionSets)});const normalizedOwnershipFilter=scopeRuntime.normalizedOwnershipFilter;const routeContext=scopeRuntime.routeContext;const scopeParamValue=scopeRuntime.scopeParamValue;const hasRequiredRouteScope=scopeRuntime.hasRequiredRouteScope;const accessRuntime=scopeRuntime.access;const apiPath=computed(()=>scopeRuntime.resolveApiPath(apiSuffix,{model}));const queryEnabled=computed(()=>resolveEnabled(readEnabled,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter,model}));const queryKey=computed(()=>resolveQueryKey(queryKeyFactory,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter}));const realtimeBinding=useOperationRealtime({realtime,queryKey:typeof queryKeyFactory===`function`?queryKey:null,enabled:computed(()=>hasRequiredRouteScope.value&&Boolean(apiPath.value))});function queryCanRun(accessGate=true){return computed(()=>queryEnabled.value&&hasRequiredRouteScope.value&&Boolean(apiPath.value)&&Boolean(unref(accessGate)))}function permissionGate(key=``){const list=normalizedPermissionSets[String(key||``)]||[];return computed(()=>resolvePermissionAccess(accessRuntime,list))}function loadError(baseError=``){return computed(()=>{if(scopeRuntime.routeScopeError.value)return scopeRuntime.routeScopeError.value;const permissionsError=String(accessRuntime.permissionsUnavailableError.value||``).trim();if(permissionsError)return permissionsError;if(baseError===void 0||baseError===null||baseError===``)return``;return String(unref(baseError)||``).trim()})}function isLoading(baseLoading=false){return computed(()=>Boolean(unref(baseLoading))||accessRuntime.awaitingPlacementPermissions.value)}return Object.freeze({scopeRuntime,routeContext,normalizedOwnershipFilter,scopeParamValue,hasRequiredRouteScope,access:accessRuntime,apiPath,queryEnabled,queryKey,queryCanRun,realtime:realtimeBinding,permissionGate,loadError,isLoading})}function normalizeFieldErrorKeys(keys){return Array.isArray(keys)?keys.map(entry=>String(entry||``).trim()).filter(Boolean):[]}function useFieldErrorBag(keys=[]){const normalizedKeys=normalizeFieldErrorKeys(keys);const hasFixedKeys=normalizedKeys.length>0;const errors=reactive(Object.fromEntries(normalizedKeys.map(key=>[key,``])));function clear(){const keysToClear=hasFixedKeys?normalizedKeys:Object.keys(errors);for(const key of keysToClear)errors[key]=``}function apply(source={}){const fieldErrorMap=source&&typeof source===`object`?source:{};if(hasFixedKeys){for(const key of normalizedKeys)errors[key]=String(fieldErrorMap[key]||``);return}clear();for(const[field,message]of Object.entries(fieldErrorMap)){const key=String(field||``).trim();if(!key)continue;errors[key]=String(message||``)}}function set(field,message){const key=String(field||``).trim();if(!key)return;if(hasFixedKeys&&!(key in errors))return;errors[key]=String(message||``)}return Object.freeze({errors,clear,apply,set})}function normalizeMessage(value){return String(value||``).trim()}function setupOperationErrorReporting({enabled=true,source=`http-web.operation`,loadError=null,notFoundError=null,loadActionFactory=null,notFoundActionFactory=null,loadChannel=``,notFoundChannel=``,loadSeverity=`error`,notFoundSeverity=`warning`,dedupeWindowMs=2e3}={}){if(!enabled)return;const runtime=useShellWebErrorRuntime();const normalizedSource=normalizeMessage(source)||`http-web.operation`;function watchMessage(value,{kind=`load`,channel=``,intent=`resource-load`,severity=`error`,actionFactory=null}={}){let lastMessage=``;let lastPresentationId=``;watch(()=>normalizeMessage(value?.value),nextMessage=>{if(!nextMessage){lastMessage=``;if(lastPresentationId){runtime.dismiss(lastPresentationId);lastPresentationId=``}return}if(nextMessage===lastMessage)return;lastMessage=nextMessage;const action=typeof actionFactory===`function`?actionFactory({message:nextMessage,kind}):null;const reportResult=runtime.report({source:normalizedSource,message:nextMessage,intent,severity,channel,action,dedupeKey:`${normalizedSource}:${kind}:${nextMessage}`,dedupeWindowMs});const nextPresentationId=String(reportResult?.presentationId||``).trim();if(nextPresentationId){if(lastPresentationId&&lastPresentationId!==nextPresentationId)runtime.dismiss(lastPresentationId);lastPresentationId=nextPresentationId}},{immediate:true})}if(loadError)watchMessage(loadError,{kind:`load`,channel:loadChannel,intent:`resource-load`,severity:loadSeverity,actionFactory:loadActionFactory});if(notFoundError)watchMessage(notFoundError,{kind:`not-found`,channel:notFoundChannel,intent:`resource-load`,severity:notFoundSeverity,actionFactory:notFoundActionFactory})}function setupRouteChangeCleanup({enabled=true,route=null,feedback=null,fieldBag=null,onClear=null}={}){if(!enabled)return;watch(()=>route?.fullPath,()=>{feedback?.clear?.();fieldBag?.clear?.();onClear?.()})}var CRUD_API_ACCESS_AUTHENTICATED=`authenticated`;var CRUD_API_ACCESS_PUBLIC=`public`;var CRUD_API_ACCESS_VALUES=Object.freeze([CRUD_API_ACCESS_AUTHENTICATED,CRUD_API_ACCESS_PUBLIC]);var publicCrudClients=new WeakSet;function normalizeCrudApiAccess(value=``){const normalized=normalizeText(value).toLowerCase()||`authenticated`;if(CRUD_API_ACCESS_VALUES.includes(normalized))return normalized;throw new TypeError(`CRUD resource apiAccess must be one of: ${CRUD_API_ACCESS_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function resolveCrudHttpClient(resource=null,{client=null}={}){const activeClient=client||getHttpWebClient();if(!activeClient||typeof activeClient.request!==`function`)throw new TypeError(`resolveCrudHttpClient requires a client with request().`);if(normalizeCrudApiAccess(resource?.apiAccess)!==`public`)return activeClient;if(publicCrudClients.has(activeClient))return activeClient;const publicClient=Object.freeze({request(url,options={}){const requestOptions=options&&typeof options===`object`&&!Array.isArray(options)?options:{};return activeClient.request(url,{...requestOptions,csrf:false})}});publicCrudClients.add(publicClient);return publicClient}function useCommand({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,access=`auto`,apiSuffix=``,runPermissions=[],writeMethod=`POST`,client=null,resource:commandResource=null,transport=null,placementSource=`http-web.command`,fallbackRunError=`jskit.http.feedback.actionFailed`,fieldErrorKeys=[],clearOnRouteChange=true,model,input,buildRawPayload,buildCommandPayload,buildCommandOptions,onRunSuccess,onRunError,suppressSuccessMessage=false,messages={},realtime=null}={}){const operationScope=useOperationScope({ownershipFilter,surfaceId,access,apiSuffix,model,readEnabled:false,permissionSets:{run:runPermissions},realtime});const routeContext=operationScope.routeContext;const canRun=operationScope.permissionGate(`run`);const endpointResource=useEndpointResource({path:operationScope.apiPath,enabled:false,client:resolveCrudHttpClient(commandResource,{client}),writeMethod,transport,fallbackSaveError:fallbackRunError});const feedback=useUiFeedback({source:`${placementSource}.feedback`});const fieldBag=useFieldErrorBag(fieldErrorKeys);const command=useCommandCore({model,resource:endpointResource,writeMethod,canRun,fieldBag,feedback,input,buildRawPayload,buildCommandPayload,buildCommandOptions,onRunSuccess,onRunError,suppressSuccessMessage:Boolean(suppressSuccessMessage),messages:{validation:`jskit.http.feedback.fixInvalidValues`,success:`jskit.http.feedback.completed`,error:String(fallbackRunError||`jskit.http.feedback.actionFailed`),...messages&&typeof messages===`object`?messages:{}}});setupRouteChangeCleanup({enabled:clearOnRouteChange,route:routeContext.route,feedback,fieldBag});const loadError=operationScope.loadError();const isLoading=operationScope.isLoading();setupOperationErrorReporting({source:`${placementSource}.load`,loadError});return proxyRefs({canRun,isLoading,loadError,isRunning:command.running,fieldErrors:command.fieldErrors,message:command.message,messageType:command.messageType,run:command.run,resource:endpointResource})}export{useOperationScope as a,resolveRouteParamNamesInOrder as c,validateOperationInput as d,useFieldErrorBag as i,toRouteParamValue as l,setupOperationErrorReporting as n,createRouteTemplateResolver as o,setupRouteChangeCleanup as r,normalizeRouteParamName as s,useCommand as t,useAccess as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{H as hasInjectionContext,Ht as watch,J as inject,On as unref,Tn as toRefs,_n as readonly,bn as shallowReadonly,g as computed,gn as reactive,pn as onScopeDispose,un as isRef,yn as shallowReactive}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{f as normalizeText,n as hasValue,r as isRecord$1}from"./normalize-BNAdWJYg.js";import{A as resolveFieldErrors,b as isGenericHttpErrorMessage,d as getHttpWebClient}from"./vibe64ProjectScope.local-l5_-E6pq.js";import{n as useRealtimeEvent}from"./useRealtimeEvent-BNXVwzFG.js";var VUE_QUERY_CLIENT=`VUE_QUERY_CLIENT`;function getClientKey(key){const suffix=key?`:${key}`:``;return`${VUE_QUERY_CLIENT}${suffix}`}function updateState(state,update){Object.keys(state).forEach(key=>{state[key]=update[key]})}function _cloneDeep(value,customize,currentKey=``,currentLevel=0){if(customize){const result=customize(value,currentKey,currentLevel);if(result===void 0&&isRef(value))return result;if(result!==void 0)return result}if(Array.isArray(value))return value.map((val,index)=>_cloneDeep(val,customize,String(index),currentLevel+1));if(typeof value===`object`&&isPlainObject$1(value)){const entries=Object.entries(value).map(([key,val])=>[key,_cloneDeep(val,customize,key,currentLevel+1)]);return Object.fromEntries(entries)}return value}function cloneDeep(value,customize){return _cloneDeep(value,customize)}function cloneDeepUnref(obj,unrefGetters=false){return cloneDeep(obj,(val,key,level)=>{if(level===1&&key===`queryKey`)return cloneDeepUnref(val,true);if(unrefGetters&&isFunction(val))return cloneDeepUnref(val(),unrefGetters);if(isRef(val))return cloneDeepUnref(unref(val),unrefGetters)})}function isPlainObject$1(value){if(Object.prototype.toString.call(value)!==`[object Object]`)return false;const prototype=Object.getPrototypeOf(value);return prototype===null||prototype===Object.prototype}function isFunction(value){return typeof value===`function`}function useQueryClient(id=``){if(!hasInjectionContext())throw new Error(`vue-query hooks can only be used inside setup() function or functions that support injection context.`);const key=getClientKey(id);const queryClient=inject(key);if(!queryClient)throw new Error(`No 'queryClient' found in Vue context, use 'VueQueryPlugin' to properly initialize the library.`);return queryClient}var defaultTimeoutProvider={setTimeout:(callback,delay)=>setTimeout(callback,delay),clearTimeout:timeoutId=>clearTimeout(timeoutId),setInterval:(callback,delay)=>setInterval(callback,delay),clearInterval:intervalId=>clearInterval(intervalId)};var TimeoutManager=class{#provider=defaultTimeoutProvider;#providerCalled=false;setTimeoutProvider(provider){this.#provider=provider}setTimeout(callback,delay){return this.#provider.setTimeout(callback,delay)}clearTimeout(timeoutId){this.#provider.clearTimeout(timeoutId)}setInterval(callback,delay){return this.#provider.setInterval(callback,delay)}clearInterval(intervalId){this.#provider.clearInterval(intervalId)}};var timeoutManager=new TimeoutManager;function systemSetTimeoutZero(callback){setTimeout(callback,0)}var isServer$1=typeof window===`undefined`||`Deno`in globalThis;function noop(){}function functionalUpdate(updater,input){return typeof updater===`function`?updater(input):updater}function isValidTimeout(value){return typeof value===`number`&&value>=0&&value!==Infinity}function timeUntilStale(updatedAt,staleTime){return Math.max(updatedAt+(staleTime||0)-Date.now(),0)}function resolveQueryValue(value,query){return typeof value===`function`?value(query):value}function matchQuery(filters,query){const{type=`all`,exact,fetchStatus,predicate,queryKey,stale}=filters;if(queryKey){if(exact){if(query.queryHash!==hashQueryKeyByOptions(queryKey,query.options))return false}else if(!partialMatchKey(query.queryKey,queryKey))return false}if(type!==`all`){const isActive=query.isActive();if(type===`active`&&!isActive)return false;if(type===`inactive`&&isActive)return false}if(typeof stale===`boolean`&&query.isStale()!==stale)return false;if(fetchStatus&&fetchStatus!==query.state.fetchStatus)return false;if(predicate&&!predicate(query))return false;return true}function matchMutation(filters,mutation){const{exact,status,predicate,mutationKey}=filters;if(mutationKey){if(!mutation.options.mutationKey)return false;if(exact){if(hashKey(mutation.options.mutationKey)!==hashKey(mutationKey))return false}else if(!partialMatchKey(mutation.options.mutationKey,mutationKey))return false}if(status&&mutation.state.status!==status)return false;if(predicate&&!predicate(mutation))return false;return true}function hashQueryKeyByOptions(queryKey,options){return(options?.queryKeyHashFn||hashKey)(queryKey)}function hashKey(queryKey){return JSON.stringify(queryKey,(_,val)=>isPlainObject(val)?Object.keys(val).sort().reduce((result,key)=>{result[key]=val[key];return result},{}):val)}function partialMatchKey(a,b){if(a===b)return true;if(typeof a!==typeof b)return false;if(a&&b&&typeof a===`object`&&typeof b===`object`){if(Array.isArray(a)&&Array.isArray(b)){if(b.length>a.length)return false;for(let i=0;i<b.length;i++)if(!partialMatchKey(a[i],b[i]))return false;return true}const bKeys=Object.keys(b);for(const key of bKeys)if(!partialMatchKey(a[key],b[key]))return false;return true}return false}var hasOwn=Object.prototype.hasOwnProperty;function replaceEqualDeep(a,b,depth=0){if(a===b)return a;if(depth>500)return b;const array=isPlainArray(a)&&isPlainArray(b);if(!array&&!(isPlainObject(a)&&isPlainObject(b)))return b;const aSize=(array?a:Object.keys(a)).length;const bItems=array?b:Object.keys(b);const bSize=bItems.length;const copy=array?new Array(bSize):{};let equalItems=0;for(let i=0;i<bSize;i++){const key=array?i:bItems[i];const aItem=a[key];const bItem=b[key];if(aItem===bItem){copy[key]=aItem;if(array?i<aSize:hasOwn.call(a,key))equalItems++;continue}if(aItem===null||bItem===null||typeof aItem!==`object`||typeof bItem!==`object`){copy[key]=bItem;continue}const v=replaceEqualDeep(aItem,bItem,depth+1);copy[key]=v;if(v===aItem)equalItems++}return aSize===bSize&&equalItems===aSize?a:copy}function shallowEqualObjects(a,b){if(!b||Object.keys(a).length!==Object.keys(b).length)return false;for(const key in a)if(a[key]!==b[key])return false;return true}function isPlainArray(value){return Array.isArray(value)&&value.length===Object.keys(value).length}function isPlainObject(o){if(!hasObjectPrototype(o))return false;const objectPrototype=Object.getPrototypeOf(o);const ctor=objectPrototype?.constructor;if(ctor===void 0)return true;if(typeof ctor!==`function`)return false;const prot=ctor.prototype;if(!hasObjectPrototype(prot))return false;if(!prot.hasOwnProperty(`isPrototypeOf`))return false;if(objectPrototype!==Object.prototype)return false;return true}function hasObjectPrototype(o){return Object.prototype.toString.call(o)===`[object Object]`}function sleep(timeout){return new Promise(resolve=>{timeoutManager.setTimeout(resolve,timeout)})}function replaceData(prevData,data,options){if(typeof options.structuralSharing===`function`)return options.structuralSharing(prevData,data);else if(options.structuralSharing!==false)return replaceEqualDeep(prevData,data);return data}function addToEnd(items,item,max=0){const newItems=[...items,item];return max&&newItems.length>max?newItems.slice(1):newItems}function addToStart(items,item,max=0){const newItems=[item,...items];return max&&newItems.length>max?newItems.slice(0,-1):newItems}var skipToken=Symbol();function ensureQueryFn(options,fetchOptions){if(!options.queryFn&&fetchOptions?.initialPromise)return()=>fetchOptions.initialPromise;if(!options.queryFn||options.queryFn===skipToken)return()=>Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`));return options.queryFn}function shouldThrowError(throwOnError,params){if(typeof throwOnError===`function`)return throwOnError(...params);return!!throwOnError}function addConsumeAwareSignal(object,getSignal,onCancelled){let consumed=false;let signal;Object.defineProperty(object,"signal",{enumerable:true,get:()=>{signal??=getSignal();if(consumed)return signal;consumed=true;if(signal.aborted)onCancelled();else signal.addEventListener(`abort`,onCancelled,{once:true});return signal}});return object}var isServerFn=()=>isServer$1;var isServer=()=>isServerFn();var environmentManager={isServer,setIsServer(isServerValue){isServerFn=isServerValue}};var Subscribable=class{constructor(){this.listeners=new Set;this.subscribe=this.subscribe.bind(this)}subscribe(listener){this.listeners.add(listener);this.onSubscribe();return()=>{this.listeners.delete(listener);this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var FocusManager=class extends Subscribable{#focused;#cleanup;#setup;constructor(){super();this.#setup=onFocus=>{if(typeof window!==`undefined`&&window.addEventListener){const listener=()=>onFocus();window.addEventListener(`visibilitychange`,listener,false);return()=>{window.removeEventListener(`visibilitychange`,listener)}}}}onSubscribe(){if(!this.#cleanup)this.setEventListener(this.#setup)}onUnsubscribe(){if(!this.hasListeners()){this.#cleanup?.();this.#cleanup=void 0}}setEventListener(setup){this.#setup=setup;this.#cleanup?.();this.#cleanup=setup(focused=>{if(typeof focused===`boolean`)this.setFocused(focused);else this.onFocus()})}setFocused(focused){if(this.#focused!==focused){this.#focused=focused;this.onFocus()}}onFocus(){const isFocused=this.isFocused();this.listeners.forEach(listener=>{listener(isFocused)})}isFocused(){if(typeof this.#focused===`boolean`)return this.#focused;return globalThis.document?.visibilityState!==`hidden`}};var focusManager=new FocusManager;var defaultScheduler=systemSetTimeoutZero;function createNotifyManager(){let queue=[];let transactions=0;let notifyFn=callback=>{callback()};let batchNotifyFn=callback=>{callback()};let scheduleFn=defaultScheduler;const schedule=callback=>{if(transactions)queue.push(callback);else scheduleFn(()=>{notifyFn(callback)})};const flush=()=>{const originalQueue=queue;queue=[];if(originalQueue.length)scheduleFn(()=>{batchNotifyFn(()=>{originalQueue.forEach(callback=>{notifyFn(callback)})})})};return{batch:callback=>{let result;transactions++;try{result=callback()}finally{transactions--;if(!transactions)flush()}return result},batchCalls:callback=>{return(...args)=>{schedule(()=>{callback(...args)})}},schedule,setNotifyFunction:fn=>{notifyFn=fn},setBatchNotifyFunction:fn=>{batchNotifyFn=fn},setScheduler:fn=>{scheduleFn=fn}}}var notifyManager=createNotifyManager();var OnlineManager=class extends Subscribable{#online=true;#cleanup;#setup;constructor(){super();this.#setup=onOnline=>{if(typeof window!==`undefined`&&window.addEventListener){const onlineListener=()=>onOnline(true);const offlineListener=()=>onOnline(false);window.addEventListener(`online`,onlineListener,false);window.addEventListener(`offline`,offlineListener,false);return()=>{window.removeEventListener(`online`,onlineListener);window.removeEventListener(`offline`,offlineListener)}}}}onSubscribe(){if(!this.#cleanup)this.setEventListener(this.#setup)}onUnsubscribe(){if(!this.hasListeners()){this.#cleanup?.();this.#cleanup=void 0}}setEventListener(setup){this.#setup=setup;this.#cleanup?.();this.#cleanup=setup(this.setOnline.bind(this))}setOnline(online){if(this.#online!==online){this.#online=online;this.listeners.forEach(listener=>{listener(online)})}}isOnline(){return this.#online}};var onlineManager=new OnlineManager;function defaultRetryDelay(failureCount){return Math.min(1e3*2**failureCount,3e4)}function canFetch(networkMode){return(networkMode??`online`)===`online`?onlineManager.isOnline():true}var CancelledError=class extends Error{constructor(options){super(`CancelledError`);this.revert=options?.revert;this.silent=options?.silent}};function createRetryer(config){let isRetryCancelled=false;let failureCount=0;let continueFn;let status=`pending`;let promiseResolve;let promiseReject;const promise=new Promise((resolve,reject)=>{promiseResolve=resolve;promiseReject=reject});promise.catch(noop);const isResolved=()=>status!==`pending`;const cancel=cancelOptions=>{if(!isResolved()){const error=new CancelledError(cancelOptions);reject(error);config.onCancel?.(error)}};const cancelRetry=()=>{isRetryCancelled=true};const continueRetry=()=>{isRetryCancelled=false};const canContinue=()=>focusManager.isFocused()&&(config.networkMode===`always`||onlineManager.isOnline())&&config.canRun();const canStart=()=>canFetch(config.networkMode)&&config.canRun();const resolve=value=>{if(!isResolved()){continueFn?.();status=`resolved`;promiseResolve(value)}};const reject=value=>{if(!isResolved()){continueFn?.();status=`rejected`;promiseReject(value)}};const pause=()=>{return new Promise(continueResolve=>{continueFn=value=>{if(isResolved()||canContinue())continueResolve(value)};config.onPause?.()}).then(()=>{continueFn=void 0;if(!isResolved())config.onContinue?.()})};const run=()=>{if(isResolved())return;let promiseOrValue;const initialPromise=failureCount===0?config.initialPromise:void 0;try{promiseOrValue=initialPromise??config.fn()}catch(error){promiseOrValue=Promise.reject(error)}Promise.resolve(promiseOrValue).then(resolve).catch(error=>{if(isResolved())return;const retry=config.retry??(isServer()?0:3);const retryDelay=config.retryDelay??defaultRetryDelay;const delay=typeof retryDelay===`function`?retryDelay(failureCount,error):retryDelay;const shouldRetry=retry===true||typeof retry===`number`&&failureCount<retry||typeof retry===`function`&&retry(failureCount,error);if(isRetryCancelled||!shouldRetry){reject(error);return}failureCount++;config.onFail?.(failureCount,error);sleep(delay).then(()=>{return canContinue()?void 0:pause()}).then(()=>{if(isRetryCancelled)reject(error);else run()})})};return{promise,status:()=>status,cancel,continue:()=>{continueFn?.();return promise},cancelRetry,continueRetry,canStart,start:()=>{if(canStart())run();else pause().then(run);return promise}}}var Removable=class{#gcTimeout;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout();if(isValidTimeout(this.gcTime))this.#gcTimeout=timeoutManager.setTimeout(()=>{this.optionalRemove()},this.gcTime)}updateGcTime(newGcTime){this.gcTime=Math.max(this.gcTime||0,newGcTime??(isServer()?Infinity:3e5))}clearGcTimeout(){if(this.#gcTimeout!==void 0){timeoutManager.clearTimeout(this.#gcTimeout);this.#gcTimeout=void 0}}};function infiniteQueryBehavior(pages){return{onFetch:(context,query)=>{const options=context.options;const direction=context.fetchOptions?.meta?.fetchMore?.direction;const oldPages=context.state.data?.pages||[];const oldPageParams=context.state.data?.pageParams||[];let result={pages:[],pageParams:[]};let currentPage=0;const fetchFn=async()=>{let cancelled=false;const addSignalProperty=object=>{addConsumeAwareSignal(object,()=>context.signal,()=>cancelled=true)};const queryFn=ensureQueryFn(context.options,context.fetchOptions);const fetchPage=async(data,param,previous)=>{if(cancelled)return Promise.reject(context.signal.reason);if(param==null&&data.pages.length)return Promise.resolve(data);const createQueryFnContext=()=>{const queryFnContext={client:context.client,queryKey:context.queryKey,pageParam:param,direction:previous?`backward`:`forward`,meta:context.options.meta};addSignalProperty(queryFnContext);return queryFnContext};const queryFnContext=createQueryFnContext();const page=await queryFn(queryFnContext);const{maxPages}=context.options;const addTo=previous?addToStart:addToEnd;return{pages:addTo(data.pages,page,maxPages),pageParams:addTo(data.pageParams,param,maxPages)}};if(direction&&oldPages.length){const previous=direction===`backward`;const pageParamFn=previous?getPreviousPageParam:getNextPageParam;const oldData={pages:oldPages,pageParams:oldPageParams};result=await fetchPage(oldData,pageParamFn(options,oldData),previous)}else{const remainingPages=pages??oldPages.length;do{const param=currentPage===0?oldPageParams[0]??options.initialPageParam:getNextPageParam(options,result);if(currentPage>0&¶m==null)break;result=await fetchPage(result,param);currentPage++}while(currentPage<remainingPages)}return result};if(context.options.persister)context.fetchFn=()=>{return context.options.persister?.(fetchFn,{client:context.client,queryKey:context.queryKey,meta:context.options.meta,signal:context.signal},query)};else context.fetchFn=fetchFn}}}function getNextPageParam(options,{pages,pageParams}){const lastIndex=pages.length-1;return pages.length>0?options.getNextPageParam(pages[lastIndex],pages,pageParams[lastIndex],pageParams):void 0}function getPreviousPageParam(options,{pages,pageParams}){return pages.length>0?options.getPreviousPageParam?.(pages[0],pages,pageParams[0],pageParams):void 0}function hasNextPage(options,data){if(!data)return false;return getNextPageParam(options,data)!=null}function hasPreviousPage(options,data){if(!data||!options.getPreviousPageParam)return false;return getPreviousPageParam(options,data)!=null}var Query=class extends Removable{#queryType;#initialState;#revertState;#cache;#client;#retryer;#defaultOptions;#abortSignalConsumed;constructor(config){super();this.#abortSignalConsumed=false;this.#defaultOptions=config.defaultOptions;this.setOptions(config.options);this.observers=[];this.#client=config.client;this.#cache=this.#client.getQueryCache();this.queryKey=config.queryKey;this.queryHash=config.queryHash;this.#initialState=getDefaultState$1(this.options);this.state=config.state??this.#initialState;this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#queryType}get promise(){return this.#retryer?.promise}setOptions(options){this.options={...this.#defaultOptions,...options};if(options?._type)this.#queryType=options._type;this.updateGcTime(this.options.gcTime);if(this.state&&this.state.data===void 0){const defaultState=getDefaultState$1(this.options);if(defaultState.data!==void 0){this.setState(successState(defaultState.data,defaultState.dataUpdatedAt));this.#initialState=defaultState}}}optionalRemove(){if(!this.observers.length&&this.state.fetchStatus===`idle`)this.#cache.remove(this)}setData(newData,options){const data=replaceData(this.state.data,newData,this.options);this.#dispatch({data,type:`success`,dataUpdatedAt:options?.updatedAt,manual:options?.manual});return data}setState(state){this.#dispatch({type:`setState`,state})}cancel(options){const promise=this.#retryer?.promise;this.#retryer?.cancel(options);return promise?promise.then(noop).catch(noop):Promise.resolve()}destroy(){super.destroy();this.cancel({silent:true})}get resetState(){return this.#initialState}reset(){this.destroy();this.setState(this.resetState)}isActive(){return this.observers.some(observer=>resolveQueryValue(observer.options.enabled,this)!==false)}isDisabled(){if(this.getObserversCount()>0)return!this.isActive();return this.options.queryFn===skipToken||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){if(this.getObserversCount()>0)return this.observers.some(observer=>resolveQueryValue(observer.options.staleTime,this)===`static`);return false}isStale(){if(this.getObserversCount()>0)return this.observers.some(observer=>observer.getCurrentResult().isStale);return this.state.data===void 0||this.state.isInvalidated}isStaleByTime(staleTime=0){if(this.state.data===void 0)return true;if(staleTime===`static`)return false;if(this.state.isInvalidated)return true;return!timeUntilStale(this.state.dataUpdatedAt,staleTime)}onFocus(){this.observers.find(x=>x.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:false});this.#retryer?.continue()}onOnline(){this.observers.find(x=>x.shouldFetchOnReconnect())?.refetch({cancelRefetch:false});this.#retryer?.continue()}addObserver(observer){if(!this.observers.includes(observer)){this.observers.push(observer);this.clearGcTimeout();this.#cache.notify({type:`observerAdded`,query:this,observer})}}removeObserver(observer){const index=this.observers.indexOf(observer);if(index!==-1){this.observers.splice(index,1);if(!this.observers.length){if(this.#retryer){if(this.#abortSignalConsumed||this.state.fetchStatus===`paused`&&this.state.status===`pending`)this.#retryer.cancel({revert:true});else this.#retryer.cancelRetry()}this.scheduleGc()}this.#cache.notify({type:`observerRemoved`,query:this,observer})}}getObserversCount(){return this.observers.length}invalidate(){if(!this.state.isInvalidated)this.#dispatch({type:`invalidate`})}async fetch(options,fetchOptions){if(this.state.fetchStatus!==`idle`&&this.#retryer?.status()!==`rejected`){if(this.state.data!==void 0&&fetchOptions?.cancelRefetch)this.cancel({silent:true});else if(this.#retryer){this.#retryer.continueRetry();return this.#retryer.promise}}if(options)this.setOptions(options);if(!this.options.queryFn){const observer=this.observers.find(x=>x.options.queryFn);if(observer)this.setOptions(observer.options)}const abortController=new AbortController;const addSignalProperty=object=>{Object.defineProperty(object,"signal",{enumerable:true,get:()=>{this.#abortSignalConsumed=true;return abortController.signal}})};const fetchFn=()=>{const queryFn=ensureQueryFn(this.options,fetchOptions);const createQueryFnContext=()=>{const queryFnContext={client:this.#client,queryKey:this.queryKey,meta:this.meta};addSignalProperty(queryFnContext);return queryFnContext};const queryFnContext=createQueryFnContext();this.#abortSignalConsumed=false;if(this.options.persister)return this.options.persister(queryFn,queryFnContext,this);return queryFn(queryFnContext)};const createFetchContext=()=>{const context={fetchOptions,options:this.options,queryKey:this.queryKey,client:this.#client,state:this.state,fetchFn};addSignalProperty(context);return context};const context=createFetchContext();(this.#queryType===`infinite`?infiniteQueryBehavior(this.options.pages):this.options.behavior)?.onFetch(context,this);this.#revertState=this.state;if(this.state.fetchStatus===`idle`||this.state.fetchMeta!==context.fetchOptions?.meta)this.#dispatch({type:`fetch`,meta:context.fetchOptions?.meta});const retryer=this.#retryer=createRetryer({initialPromise:fetchOptions?.initialPromise,fn:context.fetchFn,onCancel:error=>{if(error instanceof CancelledError&&error.revert)this.setState({...this.#revertState,fetchStatus:`idle`});abortController.abort()},onFail:(failureCount,error)=>{this.#dispatch({type:`failed`,failureCount,error})},onPause:()=>{this.#dispatch({type:`pause`})},onContinue:()=>{this.#dispatch({type:`continue`})},retry:context.options.retry,retryDelay:context.options.retryDelay,networkMode:context.options.networkMode,canRun:()=>true});try{const data=await retryer.start();if(data===void 0)throw new Error(`${this.queryHash} data is undefined`);this.setData(data);this.#cache.config.onSuccess?.(data,this);this.#cache.config.onSettled?.(data,this.state.error,this);return data}catch(error){if(error instanceof CancelledError){if(error.silent)return this.#retryer.promise;else if(error.revert){if(this.state.data===void 0)throw error;return this.state.data}}this.#dispatch({type:`error`,error});this.#cache.config.onError?.(error,this);this.#cache.config.onSettled?.(this.state.data,error,this);throw error}finally{if(this.#retryer===retryer)this.#retryer=void 0;this.scheduleGc()}}#dispatch(action){const reducer=state=>{switch(action.type){case`failed`:return{...state,fetchFailureCount:action.failureCount,fetchFailureReason:action.error};case`pause`:return{...state,fetchStatus:`paused`};case`continue`:return{...state,fetchStatus:`fetching`};case`fetch`:return{...state,...fetchState(state.data,this.options),fetchMeta:action.meta??null};case`success`:const newState={...state,...successState(action.data,action.dataUpdatedAt),dataUpdateCount:state.dataUpdateCount+1,...!action.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};this.#revertState=action.manual?newState:void 0;return newState;case`error`:const error=action.error;return{...state,error,errorUpdateCount:state.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:state.fetchFailureCount+1,fetchFailureReason:error,fetchStatus:`idle`,status:`error`,isInvalidated:true};case`invalidate`:return{...state,isInvalidated:true};case`setState`:return{...state,...action.state}}};this.state=reducer(this.state);notifyManager.batch(()=>{this.observers.slice().forEach(observer=>{observer.onQueryUpdate()});this.#cache.notify({query:this,type:`updated`,action})})}};function fetchState(data,options){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:canFetch(options.networkMode)?`fetching`:`paused`,...data===void 0&&{error:null,status:`pending`}}}function successState(data,dataUpdatedAt){return{data,dataUpdatedAt:dataUpdatedAt??Date.now(),error:null,isInvalidated:false,status:`success`}}function getDefaultState$1(options){const data=typeof options.initialData===`function`?options.initialData():options.initialData;const hasData=data!==void 0;const initialDataUpdatedAt=hasData?typeof options.initialDataUpdatedAt===`function`?options.initialDataUpdatedAt():options.initialDataUpdatedAt:0;return{data,dataUpdateCount:0,dataUpdatedAt:hasData?initialDataUpdatedAt??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:false,status:hasData?`success`:`pending`,fetchStatus:`idle`}}var QueryObserver=class extends Subscribable{#client;#currentQuery=void 0;#currentQueryInitialState=void 0;#currentResult=void 0;#currentResultState;#currentResultOptions;#selectError;#selectFn;#selectResult;#lastQueryWithDefinedData;#staleTimeoutId;#refetchIntervalId;#currentRefetchInterval;#trackedProps=new Set;constructor(client,options){super();this.options=options;this.#client=client;this.#selectError=null;this.bindMethods();this.setOptions(options)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){if(this.listeners.size===1){this.#currentQuery.addObserver(this);if(shouldFetchOnMount(this.#currentQuery,this.options))this.#executeFetch();else this.updateResult();this.#updateTimers()}}onUnsubscribe(){if(!this.hasListeners())this.destroy()}shouldFetchOnReconnect(){return shouldFetchOn(this.#currentQuery,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return shouldFetchOn(this.#currentQuery,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set;this.#clearStaleTimeout();this.#clearRefetchInterval();this.#currentQuery.removeObserver(this)}setOptions(options){const prevOptions=this.options;const prevQuery=this.#currentQuery;this.options=this.#client.defaultQueryOptions(options);if(this.options.enabled!==void 0&&typeof this.options.enabled!==`boolean`&&typeof this.options.enabled!==`function`&&typeof resolveQueryValue(this.options.enabled,this.#currentQuery)!==`boolean`)throw new Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#updateQuery();this.#currentQuery.setOptions(this.options);if(prevOptions._defaulted&&!shallowEqualObjects(this.options,prevOptions))this.#client.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#currentQuery,observer:this});const mounted=this.hasListeners();if(mounted&&shouldFetchOptionally(this.#currentQuery,prevQuery,this.options,prevOptions))this.#executeFetch();this.updateResult();if(mounted&&(this.#currentQuery!==prevQuery||resolveQueryValue(this.options.enabled,this.#currentQuery)!==resolveQueryValue(prevOptions.enabled,this.#currentQuery)||resolveQueryValue(this.options.staleTime,this.#currentQuery)!==resolveQueryValue(prevOptions.staleTime,this.#currentQuery)))this.#updateStaleTimeout();const nextRefetchInterval=this.#computeRefetchInterval();if(mounted&&(this.#currentQuery!==prevQuery||resolveQueryValue(this.options.enabled,this.#currentQuery)!==resolveQueryValue(prevOptions.enabled,this.#currentQuery)||nextRefetchInterval!==this.#currentRefetchInterval))this.#updateRefetchInterval(nextRefetchInterval)}getOptimisticResult(options){const query=this.#client.getQueryCache().build(this.#client,options);const result=this.createResult(query,options);if(!shallowEqualObjects(this.getCurrentResult(),result)){this.#currentResult=result;this.#currentResultOptions=this.options;this.#currentResultState=this.#currentQuery.state}return result}getCurrentResult(){return this.#currentResult}trackResult(result,onPropTracked){return new Proxy(result,{get:(target,key)=>{this.trackProp(key);onPropTracked?.(key);return Reflect.get(target,key)}})}trackProp(key){this.#trackedProps.add(key)}getCurrentQuery(){return this.#currentQuery}refetch({...options}={}){return this.fetch({...options})}fetchOptimistic(options){const defaultedOptions=this.#client.defaultQueryOptions(options);const query=this.#client.getQueryCache().build(this.#client,defaultedOptions);let unsubscribe=()=>{};let resolveEarly;const cachePromise=new Promise(resolve=>{resolveEarly=resolve;unsubscribe=this.#client.getQueryCache().subscribe(event=>{if(event.type===`updated`&&event.query.queryHash===query.queryHash&&query.state.data!==void 0){unsubscribe();resolve(this.createResult(query,defaultedOptions))}})});return Promise.race([query.fetch().then(()=>{const result=this.createResult(query,defaultedOptions);resolveEarly?.(result);return result}).finally(()=>{unsubscribe()}),cachePromise])}fetch(fetchOptions){return this.#executeFetch({...fetchOptions,cancelRefetch:fetchOptions.cancelRefetch??true}).then(()=>{this.updateResult();return this.#currentResult})}#executeFetch(fetchOptions){this.#updateQuery();let promise=this.#currentQuery.fetch(this.options,fetchOptions);if(!fetchOptions?.throwOnError)promise=promise.catch(noop);return promise}#shouldScheduleTimer(timeout){return!isServer()&&resolveQueryValue(this.options.enabled,this.#currentQuery)!==false&&isValidTimeout(timeout)}#updateStaleTimeout(){this.#clearStaleTimeout();const staleTime=resolveQueryValue(this.options.staleTime,this.#currentQuery);if(this.#currentResult.isStale||!this.#shouldScheduleTimer(staleTime))return;const timeout=timeUntilStale(this.#currentResult.dataUpdatedAt,staleTime)+1;this.#staleTimeoutId=timeoutManager.setTimeout(()=>{if(!this.#currentResult.isStale)this.updateResult()},timeout)}#computeRefetchInterval(){return resolveQueryValue(this.options.refetchInterval,this.#currentQuery)??false}#updateRefetchInterval(nextInterval){this.#clearRefetchInterval();this.#currentRefetchInterval=nextInterval;if(this.#currentRefetchInterval===0||!this.#shouldScheduleTimer(this.#currentRefetchInterval))return;this.#refetchIntervalId=timeoutManager.setInterval(()=>{if(this.options.refetchIntervalInBackground||focusManager.isFocused())this.#executeFetch()},this.#currentRefetchInterval)}#updateTimers(){this.#updateStaleTimeout();this.#updateRefetchInterval(this.#computeRefetchInterval())}#clearStaleTimeout(){if(this.#staleTimeoutId!==void 0){timeoutManager.clearTimeout(this.#staleTimeoutId);this.#staleTimeoutId=void 0}}#clearRefetchInterval(){if(this.#refetchIntervalId!==void 0){timeoutManager.clearInterval(this.#refetchIntervalId);this.#refetchIntervalId=void 0}}createResult(query,options){const prevQuery=this.#currentQuery;const prevOptions=this.options;const prevResult=this.#currentResult;const prevResultState=this.#currentResultState;const prevResultOptions=this.#currentResultOptions;const queryInitialState=query!==prevQuery?query.state:this.#currentQueryInitialState;const{state}=query;let newState={...state};let isPlaceholderData=false;let data;if(options._optimisticResults){const mounted=this.hasListeners();const fetchOnMount=!mounted&&shouldFetchOnMount(query,options);const fetchOptionally=mounted&&shouldFetchOptionally(query,prevQuery,options,prevOptions);if(fetchOnMount||fetchOptionally)newState={...newState,...fetchState(state.data,query.options)};if(options._optimisticResults===`isRestoring`)newState.fetchStatus=`idle`}let{error,errorUpdatedAt,status}=newState;data=newState.data;let skipSelect=false;if(options.placeholderData!==void 0&&data===void 0&&status===`pending`){let placeholderData;if(prevResult?.isPlaceholderData&&options.placeholderData===prevResultOptions?.placeholderData){placeholderData=prevResult.data;skipSelect=true}else placeholderData=typeof options.placeholderData===`function`?options.placeholderData(this.#lastQueryWithDefinedData?.state.data,this.#lastQueryWithDefinedData):options.placeholderData;if(placeholderData!==void 0){status=`success`;data=replaceData(prevResult?.data,placeholderData,options);isPlaceholderData=true}}if(options.select&&data!==void 0&&!skipSelect){if(prevResult&&data===prevResultState?.data&&options.select===this.#selectFn)data=this.#selectResult;else try{this.#selectFn=options.select;data=options.select(data);data=replaceData(prevResult?.data,data,options);this.#selectResult=data;this.#selectError=null}catch(selectError){this.#selectError=selectError}}else if(data===void 0)this.#selectError=null;if(this.#selectError){error=this.#selectError;data=this.#selectResult;errorUpdatedAt=Date.now();status=`error`;isPlaceholderData=false}const isFetching=newState.fetchStatus===`fetching`;const isPending=status===`pending`;const isError=status===`error`;const isLoading=isPending&&isFetching;const hasData=data!==void 0;return{status,fetchStatus:newState.fetchStatus,isPending,isSuccess:status===`success`,isError,isInitialLoading:isLoading,isLoading,data,dataUpdatedAt:newState.dataUpdatedAt,error,errorUpdatedAt,failureCount:newState.fetchFailureCount,failureReason:newState.fetchFailureReason,errorUpdateCount:newState.errorUpdateCount,isFetched:query.isFetched(),isFetchedAfterMount:newState.dataUpdateCount>queryInitialState.dataUpdateCount||newState.errorUpdateCount>queryInitialState.errorUpdateCount,isFetching,isRefetching:isFetching&&!isPending,isLoadingError:isError&&!hasData,isPaused:newState.fetchStatus===`paused`,isPlaceholderData,isRefetchError:isError&&hasData,isStale:isStale(query,options),refetch:this.refetch,isEnabled:resolveQueryValue(options.enabled,query)!==false}}updateResult(){const prevResult=this.#currentResult;const nextResult=this.createResult(this.#currentQuery,this.options);this.#currentResultState=this.#currentQuery.state;this.#currentResultOptions=this.options;if(this.#currentResultState.data!==void 0)this.#lastQueryWithDefinedData=this.#currentQuery;if(shallowEqualObjects(nextResult,prevResult))return;this.#currentResult=nextResult;const shouldNotifyListeners=()=>{if(!prevResult)return true;const{notifyOnChangeProps}=this.options;const notifyOnChangePropsValue=typeof notifyOnChangeProps===`function`?notifyOnChangeProps():notifyOnChangeProps;if(notifyOnChangePropsValue===`all`||!notifyOnChangePropsValue&&!this.#trackedProps.size)return true;const includedProps=new Set(notifyOnChangePropsValue??this.#trackedProps);if(this.options.throwOnError)includedProps.add(`error`);return Object.keys(this.#currentResult).some(key=>{const typedKey=key;return this.#currentResult[typedKey]!==prevResult[typedKey]&&includedProps.has(typedKey)})};const notifyListeners=shouldNotifyListeners();notifyManager.batch(()=>{if(notifyListeners)this.listeners.forEach(listener=>{listener(this.#currentResult)});this.#client.getQueryCache().notify({query:this.#currentQuery,type:`observerResultsUpdated`})})}#updateQuery(){const query=this.#client.getQueryCache().build(this.#client,this.options);if(query===this.#currentQuery)return;const prevQuery=this.#currentQuery;this.#currentQuery=query;this.#currentQueryInitialState=query.state;if(this.hasListeners()){prevQuery?.removeObserver(this);query.addObserver(this)}}onQueryUpdate(){this.updateResult();if(this.hasListeners())this.#updateTimers()}};function shouldLoadOnMount(query,options){return resolveQueryValue(options.enabled,query)!==false&&query.state.data===void 0&&!(query.state.status===`error`&&resolveQueryValue(options.retryOnMount,query)===false)}function shouldFetchOnMount(query,options){return shouldLoadOnMount(query,options)||query.state.data!==void 0&&shouldFetchOn(query,options,options.refetchOnMount)}function shouldFetchOn(query,options,field){if(resolveQueryValue(options.enabled,query)!==false&&resolveQueryValue(options.staleTime,query)!==`static`){const value=resolveQueryValue(field,query);return value===`always`||value!==false&&isStale(query,options)}return false}function shouldFetchOptionally(query,prevQuery,options,prevOptions){return(query!==prevQuery||resolveQueryValue(prevOptions.enabled,query)===false)&&(!options.suspense||query.state.status!==`error`)&&isStale(query,options)}function isStale(query,options){return resolveQueryValue(options.enabled,query)!==false&&query.isStaleByTime(resolveQueryValue(options.staleTime,query))}var Mutation=class extends Removable{#client;#observers;#mutationCache;#retryer;constructor(config){super();this.#client=config.client;this.mutationId=config.mutationId;this.#mutationCache=config.mutationCache;this.#observers=[];this.state=config.state||getDefaultState();this.setOptions(config.options);this.scheduleGc()}setOptions(options){this.options=options;this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(observer){if(!this.#observers.includes(observer)){this.#observers.push(observer);this.clearGcTimeout();this.#mutationCache.notify({type:`observerAdded`,mutation:this,observer})}}removeObserver(observer){this.#observers=this.#observers.filter(x=>x!==observer);this.scheduleGc();this.#mutationCache.notify({type:`observerRemoved`,mutation:this,observer})}optionalRemove(){if(!this.#observers.length){if(this.state.status===`pending`)this.scheduleGc();else this.#mutationCache.remove(this)}}continue(){return this.#retryer?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(variables){const onContinue=()=>{this.#dispatch({type:`continue`})};const mutationFnContext={client:this.#client,meta:this.options.meta,mutationKey:this.options.mutationKey};const retryer=this.#retryer=createRetryer({fn:()=>{if(!this.options.mutationFn)return Promise.reject(new Error(`No mutationFn found`));return this.options.mutationFn(variables,mutationFnContext)},onFail:(failureCount,error)=>{this.#dispatch({type:`failed`,failureCount,error})},onPause:()=>{this.#dispatch({type:`pause`})},onContinue,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#mutationCache.canRun(this)});const restored=this.state.status===`pending`;const isPaused=!retryer.canStart();try{if(restored)onContinue();else{this.#dispatch({type:`pending`,variables,isPaused});if(this.#mutationCache.config.onMutate)await this.#mutationCache.config.onMutate(variables,this,mutationFnContext);const context=await this.options.onMutate?.(variables,mutationFnContext);if(context!==this.state.context)this.#dispatch({type:`pending`,context,variables,isPaused})}const data=await retryer.start();await this.#mutationCache.config.onSuccess?.(data,variables,this.state.context,this,mutationFnContext);await this.options.onSuccess?.(data,variables,this.state.context,mutationFnContext);await this.#mutationCache.config.onSettled?.(data,null,this.state.variables,this.state.context,this,mutationFnContext);await this.options.onSettled?.(data,null,variables,this.state.context,mutationFnContext);this.#dispatch({type:`success`,data});return data}catch(error){try{await this.#mutationCache.config.onError?.(error,variables,this.state.context,this,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.options.onError?.(error,variables,this.state.context,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.#mutationCache.config.onSettled?.(void 0,error,this.state.variables,this.state.context,this,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,error,variables,this.state.context,mutationFnContext)}catch(e){Promise.reject(e)}this.#dispatch({type:`error`,error});throw error}finally{if(this.#retryer===retryer)this.#retryer=void 0;this.#mutationCache.runNext(this)}}#dispatch(action){const reducer=state=>{switch(action.type){case`failed`:return{...state,failureCount:action.failureCount,failureReason:action.error};case`pause`:return{...state,isPaused:true};case`continue`:return{...state,isPaused:false};case`pending`:return{...state,context:action.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:action.isPaused,status:`pending`,variables:action.variables,submittedAt:Date.now()};case`success`:return{...state,data:action.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:false};case`error`:return{...state,data:void 0,error:action.error,failureCount:state.failureCount+1,failureReason:action.error,isPaused:false,status:`error`}}};this.state=reducer(this.state);notifyManager.batch(()=>{this.#observers.forEach(observer=>{observer.onMutationUpdate(action)});this.#mutationCache.notify({mutation:this,type:`updated`,action})})}};function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:false,status:`idle`,variables:void 0,submittedAt:0}}var MutationObserver=class extends Subscribable{#client;#currentResult=void 0;#currentMutation;#mutateOptions;constructor(client,options){super();this.#client=client;this.setOptions(options);this.bindMethods();this.#updateResult()}bindMethods(){this.mutate=this.mutate.bind(this);this.reset=this.reset.bind(this)}setOptions(options){const prevOptions=this.options;this.options=this.#client.defaultMutationOptions(options);if(!shallowEqualObjects(this.options,prevOptions))this.#client.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#currentMutation,observer:this});if(prevOptions?.mutationKey&&this.options.mutationKey&&hashKey(prevOptions.mutationKey)!==hashKey(this.options.mutationKey))this.reset();else if(this.#currentMutation?.state.status===`pending`)this.#currentMutation.setOptions(this.options)}onSubscribe(){if(this.listeners.size===1&&this.#currentMutation){this.#currentMutation.addObserver(this);this.#updateResult()}}onUnsubscribe(){if(!this.hasListeners())this.#currentMutation?.removeObserver(this)}onMutationUpdate(action){this.#updateResult();this.#notify(action)}getCurrentResult(){return this.#currentResult}reset(){this.#currentMutation?.removeObserver(this);this.#currentMutation=void 0;this.#updateResult();this.#notify()}mutate(variables,options){this.#mutateOptions=options;this.#currentMutation?.removeObserver(this);this.#currentMutation=this.#client.getMutationCache().build(this.#client,this.options);this.#currentMutation.addObserver(this);return this.#currentMutation.execute(variables)}#updateResult(){const state=this.#currentMutation?.state??getDefaultState();this.#currentResult={...state,isPending:state.status===`pending`,isSuccess:state.status===`success`,isError:state.status===`error`,isIdle:state.status===`idle`,mutate:this.mutate,reset:this.reset}}#notify(action){notifyManager.batch(()=>{if(this.#mutateOptions&&this.hasListeners()){const variables=this.#currentResult.variables;const onMutateResult=this.#currentResult.context;const context={client:this.#client,meta:this.options.meta,mutationKey:this.options.mutationKey};if(action?.type===`success`){try{this.#mutateOptions.onSuccess?.(action.data,variables,onMutateResult,context)}catch(e){Promise.reject(e)}try{this.#mutateOptions.onSettled?.(action.data,null,variables,onMutateResult,context)}catch(e){Promise.reject(e)}}else if(action?.type===`error`){try{this.#mutateOptions.onError?.(action.error,variables,onMutateResult,context)}catch(e){Promise.reject(e)}try{this.#mutateOptions.onSettled?.(void 0,action.error,variables,onMutateResult,context)}catch(e){Promise.reject(e)}}}this.listeners.forEach(listener=>{listener(this.#currentResult)})})}};function useBaseQuery(Observer,options,queryClient){const client=queryClient||useQueryClient();const defaultedOptions=computed(()=>{let resolvedOptions=options;if(typeof resolvedOptions===`function`)resolvedOptions=resolvedOptions();const clonedOptions=cloneDeepUnref(resolvedOptions);if(typeof clonedOptions.enabled===`function`)clonedOptions.enabled=clonedOptions.enabled();const defaulted=client.defaultQueryOptions(clonedOptions);defaulted._optimisticResults=client.isRestoring?.value?`isRestoring`:`optimistic`;return defaulted});const observer=new Observer(client,defaultedOptions.value);const state=defaultedOptions.value.shallow?shallowReactive(observer.getCurrentResult()):reactive(observer.getCurrentResult());let unsubscribe=()=>{};if(client.isRestoring)watch(client.isRestoring,isRestoring=>{if(!isRestoring){unsubscribe();unsubscribe=observer.subscribe(result=>{updateState(state,result)})}},{immediate:true});const updater=()=>{observer.setOptions(defaultedOptions.value);updateState(state,observer.getCurrentResult())};watch(defaultedOptions,updater);onScopeDispose(()=>{unsubscribe()});const refetch=(...args)=>{updater();return state.refetch(...args)};const suspense=()=>{return new Promise((resolve,reject)=>{let stopWatch=()=>{};const run=()=>{if(defaultedOptions.value.enabled!==false){observer.setOptions(defaultedOptions.value);const optimisticResult=observer.getOptimisticResult(defaultedOptions.value);if(optimisticResult.isStale){stopWatch();observer.fetchOptimistic(defaultedOptions.value).then(resolve,error=>{if(shouldThrowError(defaultedOptions.value.throwOnError,[error,observer.getCurrentQuery()]))reject(error);else resolve(observer.getCurrentResult())})}else{stopWatch();resolve(optimisticResult)}}};run();stopWatch=watch(defaultedOptions,run)})};watch(()=>state.error,error=>{if(state.isError&&!state.isFetching&&shouldThrowError(defaultedOptions.value.throwOnError,[error,observer.getCurrentQuery()]))throw error});const readonlyState=defaultedOptions.value.shallow?shallowReadonly(state):readonly(state);const object=toRefs(readonlyState);for(const key in state)if(typeof state[key]===`function`)object[key]=state[key];object.suspense=suspense;object.refetch=refetch;return object}function useQuery(options,queryClient){return useBaseQuery(QueryObserver,options,queryClient)}function useMutation(options,queryClient){const client=queryClient||useQueryClient();const defaultedOptions=computed(()=>{const resolvedOptions=typeof options===`function`?options():options;return client.defaultMutationOptions(cloneDeepUnref(resolvedOptions))});const observer=new MutationObserver(client,defaultedOptions.value);const state=defaultedOptions.value.shallow?shallowReactive(observer.getCurrentResult()):reactive(observer.getCurrentResult());const unsubscribe=observer.subscribe(result=>{updateState(state,result)});const mutate=(...args)=>{observer.mutate(args[0],args[1]).catch(()=>{})};watch(defaultedOptions,()=>{observer.setOptions(defaultedOptions.value)});onScopeDispose(()=>{unsubscribe()});const readonlyState=defaultedOptions.value.shallow?shallowReadonly(state):readonly(state);const resultRefs=toRefs(readonlyState);watch(()=>state.error,error=>{if(error&&shouldThrowError(defaultedOptions.value.throwOnError,[error]))throw error});return{...resultRefs,mutate,mutateAsync:state.mutate,reset:state.reset}}var MESSAGE_KEY_PREFIX=`jskit.`;function isRecord(value){return Boolean(value)&&typeof value===`object`&&!Array.isArray(value)}function messageKeyForCode(code=``){const normalized=String(code||``).trim();if(!normalized)return``;return normalized.includes(`.`)?`${MESSAGE_KEY_PREFIX}${normalized}`:`${MESSAGE_KEY_PREFIX}errors.${normalized}`}function catalogMessage(catalog,key=``){let current=catalog;for(const segment of String(key||``).split(`.`)){if(!isRecord(current)||!Object.hasOwn(current,segment))return;current=current[segment]}return typeof current===`string`?current:void 0}function mergeCatalogs(...catalogs){const merged={};for(const catalog of catalogs){if(!isRecord(catalog))continue;for(const[name,value]of Object.entries(catalog))merged[name]=isRecord(value)&&isRecord(merged[name])?mergeCatalogs(merged[name],value):value}return merged}function placeholderEnd(template,start){let index=start+1;let quoted=false;while(index<template.length){const char=template[index];if(char===`'`)quoted=!quoted;else if(char===`}`&&!quoted)return index;index+=1}throw new SyntaxError(`Unclosed placeholder in message: ${template}`)}function parseMessage(template=``){const source=String(template);const choices=[[]];let text=``;const flush=()=>{if(text){choices.at(-1).push({text});text=``}};let index=0;while(index<source.length){const char=source[index];if(char===`{`){const end=placeholderEnd(source,index);const body=source.slice(index+1,end).trim();flush();choices.at(-1).push(body.startsWith(`'`)?{text:body.slice(1,-1)}:{param:body});index=end+1;continue}if(char===`|`){flush();choices.push([]);index+=1;continue}text+=char;index+=1}flush();if(choices.length>1)for(const parts of choices){if(parts[0]?.text!==void 0)parts[0]={text:parts[0].text.trimStart()};const last=parts.length-1;if(parts[last]?.text!==void 0)parts[last]={text:parts[last].text.trimEnd()}}return choices}function pluralChoice(count,choices){const value=Math.abs(Number(count));if(choices===2)return value?value>1?1:0:1;return value?Math.min(value,2):0}function formatMessage(template=``,params={}){const values=isRecord(params)?params:{};const choices=parseMessage(template);const count=values.count??values.n;return choices[choices.length>1&&Number.isFinite(Number(count))?Math.min(pluralChoice(count,choices.length),choices.length-1):0].map(part=>part.param===void 0?part.text:String(values[part.param]??``)).join(``)}var jskit$1={"errors":{"internal_server_error":`Internal server error.`,"request_failed":`Request failed.`,"validation_failed":`Validation failed.`,"FST_ERR_VALIDATION":`Validation failed.`,"not_found":`Not found.`,"conflict":`Conflict.`,"domain_validation_failed":`Domain validation failed.`,"AUTHENTICATION_REQUIRED":`Authentication required.`,"PERMISSION_DENIED":`Forbidden.`,"ACTION_AUTHENTICATION_REQUIRED":`Authentication required.`,"ACTION_CHANNEL_FORBIDDEN":`Forbidden.`,"ACTION_PERMISSION_DENIED":`Forbidden.`,"ACTION_SURFACE_FORBIDDEN":`Forbidden.`,"ACTION_NOT_FOUND":`Not found.`,"ACTION_VALIDATION_FAILED":`Validation failed.`,"ACTION_IDEMPOTENCY_KEY_REQUIRED":`Validation failed.`,"ACTION_ID_REQUIRED":`Validation failed.`,"ACTION_STREAM_KIND_REQUIRED":`Validation failed.`,"ACTION_VERSION_INVALID":`Validation failed.`,"ACTION_OUTPUT_VALIDATION_FAILED":`Action output validation failed.`,"unsupported_media_type":`Content-Type must be {contentType}.`},"kernel":{"validation":{"required":`must have required property '{missingProperty}'`,"type":`must be {type}`,"minLength":`must NOT have fewer than {limit} characters`,"maxLength":`must NOT have more than {limit} characters`,"minimum":`must be >= {limit}`,"maximum":`must be <= {limit}`,"exclusiveMinimum":`must be > {limit}`,"exclusiveMaximum":`must be < {limit}`,"multipleOf":`must be multiple of {multipleOf}`,"pattern":`must match pattern "{pattern}"`,"format":`must match format "{format}"`,"enum":`must be equal to one of the allowed values`,"const":`must be equal to constant`,"minItems":`must NOT have fewer than {limit} items`,"maxItems":`must NOT have more than {limit} items`,"additionalItems":`must NOT have more than {limit} items`,"uniqueItems":`must NOT have duplicate items (items ## {j} and {i} are identical)`,"minProperties":`must NOT have fewer than {limit} properties`,"maxProperties":`must NOT have more than {limit} properties`,"additionalProperties":`must NOT have additional properties`,"propertyNames":`property name must be valid`,"oneOf":`must match exactly one schema in oneOf`,"anyOf":`must match a schema in anyOf`,"not":`must NOT be valid`,"if":`must match "{failingKeyword}" schema`,"invalid":`Invalid value.`,"schemaFailed":`Schema validation failed.`,"recordIdInvalid":`Record id must be a canonical positive integer string.`,"field":{"required":`Field is required`,"typeCastFailed":`Value could not be cast to the required type.`,"notNullable":`Field cannot be null`,"minLength":`Length must be at least {min} characters.`,"maxLength":`Length must be no more than {max} characters.`,"minValue":`Value must be at least {min}.`,"maxValue":`Value must be no more than {max}.`,"pattern":`Value does not match the required pattern.`,"enumValue":`Value must match one of the allowed enum values.`,"notAllowed":`Field not allowed`,"strictBoolean":`Value must be a boolean.`,"rangeExceeded":`Numeric value is out of the allowed character range.`,"notEmpty":`Field cannot be empty.`}},"action":{"versionInvalid":`version must be an integer >= 1.`,"idRequired":`actionId is required.`,"idempotencyKeyRequired":`Idempotency key is required for this action.`},"route":{"handlerUnavailable":`Route handler is not available in this runtime profile.`},"surface":{"pathNotServed":`Path {path} is not served by {surface} surface server.`},"moduleLoad":{"appModuleNotDownloaded":`App module did not download. The app may have been updated, or the network request failed.`,"appModuleFailed":`App module could not load.`,"pageNotDownloaded":`Page did not download. The app may have been updated, or the network request failed.`,"pageFailed":`Page could not load.`,"notDownloaded":`{label} did not download. The app may have been updated, or the network request failed.`,"failed":`{label} could not load.`,"reloadUnavailable":`The app cannot reload because the app server is not reachable. Restart the server, then click Retry or Reload.`}}};var en_default$1={jskit:jskit$1};var CLIENT_I18N_GLOBAL_KEY=`__JSKIT_CLIENT_I18N__`;var ENGLISH=`en`;function registry(){if(!globalThis[CLIENT_I18N_GLOBAL_KEY])globalThis[CLIENT_I18N_GLOBAL_KEY]={english:{},i18n:null};return globalThis[CLIENT_I18N_GLOBAL_KEY]}function mergeEnglishIntoI18n(){const{english,i18n}=registry();if(i18n)i18n.global.setLocaleMessage(ENGLISH,mergeCatalogs(english,i18n.global.getLocaleMessage(ENGLISH)))}function registerJskitMessages(catalog={}){const state=registry();state.english=mergeCatalogs(state.english,catalog);mergeEnglishIntoI18n()}function setJskitI18n(i18n=null){if(i18n&&(i18n.mode!==`composition`||typeof i18n.global?.t!==`function`))throw new TypeError(`JSKIT needs a vue-i18n instance created with createI18n({ legacy: false }).`);registry().i18n=i18n||null;mergeEnglishIntoI18n()}function activeLocale(){const locale=registry().i18n?.global.locale;return(typeof locale===`object`&&locale?locale.value:locale)||void 0}function pluralOptions(params){const count=Number(params?.count??params?.n);return Number.isFinite(count)?{plural:count}:{}}function t$1(key=``,params={},{locale}={}){const{english,i18n}=registry();if(i18n){const composer=i18n.global;if(composer.te(key,locale))return composer.t(key,params,locale?{...pluralOptions(params),locale}:pluralOptions(params));if(composer.te(key,ENGLISH))return composer.t(key,params,{...pluralOptions(params),locale:ENGLISH})}const message=catalogMessage(english,key);return message===void 0?key:formatMessage(message,params)}function hasMessage(key=``){const{english,i18n}=registry();return catalogMessage(english,key)!==void 0||Boolean(i18n?.global.te(key))}function text$1(value,options){if(value&&typeof value===`object`){const key=String(value.key||``);return key&&hasMessage(key)?t$1(key,value.params,options):String(value.fallback??``)}const label=String(value??``);return label&&!/\s/u.test(label)&&hasMessage(label)?t$1(label,{},options):label}function codedMessage(code,params={},sentEnglish=``){const key=messageKeyForCode(code);const english=key?catalogMessage(registry().english,key):void 0;if(english===void 0||sentEnglish&&formatMessage(english,params)!==sentEnglish)return``;return t$1(key,params)}function serverMessage$1(source,fallback=``){const sent=String(source?.message||``);if(!sent&&fallback)return fallback;return codedMessage(source?.code,source?.params,sent)||codedMessage(source?.messageCode,source?.messageParams,sent)||sent||fallback}function fieldErrorMessages$1(error){const fieldErrors=error?.fieldErrors||error?.details?.fieldErrors||{};const fieldErrorCodes=error?.fieldErrorCodes||error?.details?.fieldErrorCodes||{};const messages={};for(const[field,sent]of Object.entries(fieldErrors)){const coded=fieldErrorCodes[field];messages[field]=coded&&codedMessage(coded.code,coded.params,String(sent||``))||sent}return messages}function validDate(value){const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?null:date}function formatDate(value,options){return validDate(value)?.toLocaleDateString(activeLocale(),options)??``}function formatTime(value,options){return validDate(value)?.toLocaleTimeString(activeLocale(),options)??``}function formatDateTime(value,options){return validDate(value)?.toLocaleString(activeLocale(),options)??``}function formatNumber(value,options){const number=Number(value);return Number.isFinite(number)?number.toLocaleString(activeLocale(),options):``}var RELATIVE_UNITS=[[`year`,31536e3],[`month`,2592e3],[`week`,604800],[`day`,86400],[`hour`,3600],[`minute`,60],[`second`,1]];function formatRelativeTime(value,{now=Date.now(),...options}={}){const date=validDate(value);if(!date)return``;const seconds=Math.round((date.getTime()-Number(now))/1e3);const[unit,size]=RELATIVE_UNITS.find(([,unitSeconds])=>Math.abs(seconds)>=unitSeconds)||RELATIVE_UNITS.at(-1);return new Intl.RelativeTimeFormat(activeLocale(),{numeric:`auto`,...options}).format(Math.round(seconds/size),unit)}function useJskitText(){return{t:t$1,text:text$1,hasMessage,errorMessage:serverMessage$1,serverMessage:serverMessage$1,fieldErrorMessages:fieldErrorMessages$1,formatDate,formatTime,formatDateTime,formatNumber,formatRelativeTime,get locale(){return activeLocale()}}}registerJskitMessages(en_default$1);var AUTH_POLICY_PUBLIC=`public`;var AUTH_POLICY_AUTHENTICATED=`authenticated`;var ROUTE_VISIBILITY_PUBLIC=AUTH_POLICY_PUBLIC;var ROUTE_VISIBILITY_USER=`user`;function resolveEnabledRef(value){if(value===void 0)return true;if(typeof value===`function`)return Boolean(value());return Boolean(unref(value))}function resolveTextRef(value){return String(unref(value)||``).trim()}var ROUTE_VISIBILITY_LEVELS=Object.freeze([ROUTE_VISIBILITY_PUBLIC,ROUTE_VISIBILITY_USER]);var ROUTE_VISIBILITY_LEVEL_SET=new Set(ROUTE_VISIBILITY_LEVELS);var ROUTE_VISIBILITY_WORKSPACE=`workspace`;var ROUTE_VISIBILITY_WORKSPACE_USER=`workspace_user`;var ROUTE_VISIBILITY_TOKENS=Object.freeze([ROUTE_VISIBILITY_PUBLIC,ROUTE_VISIBILITY_USER,ROUTE_VISIBILITY_WORKSPACE,ROUTE_VISIBILITY_WORKSPACE_USER]);var ROUTE_VISIBILITY_TOKEN_SET=new Set(ROUTE_VISIBILITY_TOKENS);var OWNERSHIP_FILTER_VALUES=ROUTE_VISIBILITY_TOKENS;var SCOPED_OWNERSHIP_FILTER_SET=new Set([ROUTE_VISIBILITY_WORKSPACE,ROUTE_VISIBILITY_WORKSPACE_USER]);var ACCESS_MODE_VALUES=Object.freeze([`auto`,`always`,`never`]);function asPlainObject(value){if(!value||typeof value!==`object`||Array.isArray(value))return{};return value}function normalizePermissions(value){if(Array.isArray(value))return value.map(entry=>String(entry||``).trim()).filter(Boolean);const one=String(value||``).trim();return one?[one]:[]}function resolvePermissionAccess(access,normalizedPermissions=[]){if(normalizedPermissions.length<1)return true;return access.canAny(normalizedPermissions)}function normalizeAccessMode(value=`auto`){const normalized=String(value||`auto`).trim().toLowerCase();if(ACCESS_MODE_VALUES.includes(normalized))return normalized;throw new TypeError(`access must be one of: ${ACCESS_MODE_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function resolveAccessModeEnabled(accessMode=`auto`,{hasPermissionRequirements=false}={}){const normalizedMode=normalizeAccessMode(accessMode);if(normalizedMode===`always`)return true;if(normalizedMode===`never`)return false;return hasPermissionRequirements===true}function ensureAccessModeCompatibility({accessMode=`auto`,hasPermissionRequirements=false,caller=`http-web`}={}){const normalizedMode=normalizeAccessMode(accessMode);if(normalizedMode===`never`&&hasPermissionRequirements)throw new TypeError(`${caller} cannot use access:\"never\" when permission requirements are configured.`);return normalizedMode}function resolveApiSuffix(apiSuffix,context={}){if(typeof apiSuffix===`function`)return resolveTextRef(apiSuffix(context));return resolveTextRef(apiSuffix)}function resolveEnabled(value,context={}){if(typeof value===`function`)return Boolean(value(context));return resolveEnabledRef(value)}function normalizeOwnershipFilter(value=ROUTE_VISIBILITY_WORKSPACE){const normalized=String(value||`workspace`).trim().toLowerCase();if(OWNERSHIP_FILTER_VALUES.includes(normalized))return normalized;throw new TypeError(`ownershipFilter must be one of: ${OWNERSHIP_FILTER_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function isScopedOwnershipFilter(ownershipFilter){return SCOPED_OWNERSHIP_FILTER_SET.has(ownershipFilter)}function resolveQueryKey(queryKeyFactory,{surfaceId=``,scopeParamValue=``,ownershipFilter=ROUTE_VISIBILITY_WORKSPACE}={}){if(typeof queryKeyFactory!==`function`)throw new TypeError(`queryKeyFactory is required.`);if(isScopedOwnershipFilter(ownershipFilter))return queryKeyFactory(surfaceId,scopeParamValue,ownershipFilter);return queryKeyFactory(surfaceId,ownershipFilter)}function resolveResourceMessages(resource,defaults={}){const defaultMessages=asPlainObject(defaults);const resourceMessages=asPlainObject(asPlainObject(resource).messages);return{...defaultMessages,...resourceMessages}}var jskit={"http":{"access":{"permissionsUnavailable":`Permissions are unavailable in placement context.`,"routeParamsRequired":`Route parameters {params} are required for surface "{surface}".`},"actions":{"actions":`Actions`,"apply":`Apply`,"cancel":`Cancel`,"clear":`Clear`,"clearAll":`Clear all`,"close":`Close`,"delete":`Delete`,"deleting":`Deleting…`,"edit":`Edit`,"loadMore":`Load more`,"loadingMore":`Loading more…`,"more":`More`,"open":`Open`,"refresh":`Refresh`,"refreshing":`Refreshing…`,"retry":`Retry`,"retrying":`Retrying…`,"running":`{label}…`,"save":`Save`,"saving":`Saving…`},"crud":{"bulk":{"actions":`Bulk actions`,"selected":`{count} selected`,"selection":`Selection`},"delete":{"button":`Delete {resource}`,"description":`This permanently deletes this {resource}. This action cannot be undone.`,"failed":`Unable to delete record.`,"listRouteUnavailable":`Deleted the record, but the generated list route is unavailable.`,"title":`Delete {resource}?`},"filters":{"calendar":`{label} calendar`,"chipDate":`{label}: {date}`,"chipFrom":`{label}: from {from}`,"chipRange":`{label}: {from} to {to}`,"chipTo":`{label}: to {to}`,"dateRange":`{label} date range`,"enterId":`Enter id`,"enterIds":`Enter ids`,"option":`Option`,"optionValue":`{label} {value}`,"optionsLoadFailed":`Unable to load filter options ({path}).`,"rangeFrom":`{label} from`,"rangeMax":`{label} max`,"rangeMin":`{label} min`,"rangeTo":`{label} to`,"selectDate":`Select date`,"selectEndDate":`Select end date`,"selectStartDate":`Select start date`,"title":`Filters`},"list":{"emptyBody":`Create the first record to start using this workflow.`,"loadErrorBody":`Check the connection and try again.`,"loadFailed":`Unable to load records.`,"newRecord":`New record`,"selectRecord":`Select {title}`,"selectVisibleRows":`Select visible rows`},"lookup":{"optionsLoadFailed":`Unable to load lookup options ({path}).`},"no":`No`,"parent":{"loadFailed":`Unable to load parent record.`,"notFound":`Parent record not found.`,"recordWithId":`{label} #{id}`},"record":`Record`,"recordNotFound":`Record not found.`,"records":`Records`,"view":{"backTo":`Back to {resources}`,"loadFailed":`Unable to load record.`,"notFound":`This {resource} could not be found.`},"yes":`Yes`},"feedback":{"actionFailed":`Unable to complete action.`,"completed":`Completed.`,"fixInvalidValues":`Fix invalid values and try again.`,"requestFailed":`Request failed.`,"saveFailed":`Unable to save.`,"saved":`Saved.`,"validationFailed":`Validation failed.`},"list":{"label":`List`,"loadFailed":`Unable to load list.`,"search":`Search`},"resource":{"label":`Resource`,"loadFailed":`Unable to load resource.`,"saveFailed":`Unable to save resource.`},"selectField":{"unavailableOption":`Unavailable option`}}};var en_default={jskit};registerJskitMessages(en_default);var{t,text,serverMessage,fieldErrorMessages}=useJskitText();function toUiErrorMessage(error,fallbackMessage=``,defaultMessage=``){const normalizedFallback=text(fallbackMessage).trim();const normalizedMessage=String(error?.message||``).trim();if(normalizedMessage&&!isGenericHttpErrorMessage(error))return serverMessage(error).trim();if(normalizedFallback)return normalizedFallback;if(normalizedMessage)return serverMessage(error).trim();return text(defaultMessage).trim()||t(`jskit.http.feedback.requestFailed`)}function toQueryErrorMessage(error,fallbackMessage=``,defaultMessage=``){return error?toUiErrorMessage(error,fallbackMessage,defaultMessage):``}function toUiFieldErrors(error){return fieldErrorMessages({fieldErrors:resolveFieldErrors(error),fieldErrorCodes:error?.fieldErrorCodes||error?.details?.fieldErrorCodes})}function hasResolvedQueryData({query=null,data=null}={}){const querySucceeded=Boolean(unref(query?.isSuccess));const hasDataPayload=unref(data)!=null;return querySucceeded||hasDataPayload}function mergeQueryMeta(queryOptions=null,meta={}){const sourceOptions=isRecord$1(queryOptions)?queryOptions:{};const sourceMeta=isRecord$1(sourceOptions.meta)?sourceOptions.meta:{};return{...sourceOptions,meta:{...sourceMeta,...meta,jskit:{...isRecord$1(sourceMeta.jskit)?sourceMeta.jskit:{},...isRecord$1(meta.jskit)?meta.jskit:{}}}}}var REQUEST_RECOVERY_META_KEYS=Object.freeze({label:`requestRecoveryLabel`,source:`requestRecoverySource`,dedupeKey:`requestRecoveryDedupeKey`,method:`requestRecoveryMethod`,dedupeWindowMs:`requestRecoveryDedupeWindowMs`});var DISABLED_REQUEST_RECOVERY_META=Object.freeze({jskit:Object.freeze({requestRecovery:false})});function normalizeRequestRecoveryInput(requestRecovery=null){if(typeof requestRecovery===`string`)return{label:requestRecovery};const source=isRecord$1(requestRecovery)?requestRecovery:{};for(const key of Object.keys(source))if(key!==`enabled`&&!Object.hasOwn(REQUEST_RECOVERY_META_KEYS,key))throw new TypeError(`requestRecovery.${key} is not supported; use ${Object.keys(REQUEST_RECOVERY_META_KEYS).join(`, `)} or enabled.`);return source}function normalizeRequestRecoveryValue(name,value){if(name===`dedupeWindowMs`){const numberValue=value==null||value===``?NaN:Number(value);return Number.isFinite(numberValue)?Math.max(0,numberValue):null}const text=normalizeText(value);if(!text)return null;return name===`method`?text.toUpperCase():text}function buildRequestRecoveryMeta(requestRecovery=null,defaults={}){if(requestRecovery===false)return DISABLED_REQUEST_RECOVERY_META;const source=normalizeRequestRecoveryInput(requestRecovery);if(source.enabled===false)return DISABLED_REQUEST_RECOVERY_META;const fallback=isRecord$1(defaults)?defaults:{};const jskit={};for(const[name,metaKey]of Object.entries(REQUEST_RECOVERY_META_KEYS)){const value=normalizeRequestRecoveryValue(name,source[name])??normalizeRequestRecoveryValue(name,fallback[name]);if(value!==null)jskit[metaKey]=value}return Object.keys(jskit).length>0?{jskit}:{}}function mergeRequestRecoveryQueryMeta(queryOptions=null,requestRecovery=null,defaults={}){const sourceOptions=isRecord$1(queryOptions)?queryOptions:{};let meta;if(requestRecovery==null){const presetMeta=isRecord$1(sourceOptions.meta?.jskit)?sourceOptions.meta.jskit:{};if(presetMeta.requestRecovery===false)return sourceOptions;const fallback=isRecord$1(defaults)?defaults:{};const unsetDefaults={};for(const[name,metaKey]of Object.entries(REQUEST_RECOVERY_META_KEYS))if(!hasValue(presetMeta[metaKey]))unsetDefaults[name]=fallback[name];meta=buildRequestRecoveryMeta(null,unsetDefaults)}else meta=buildRequestRecoveryMeta(requestRecovery,defaults);return Object.keys(meta).length>0?mergeQueryMeta(sourceOptions,meta):sourceOptions}function normalizeRealtimeOptions(value={}){if(value===null||value===void 0||value===false)return{};if(typeof value!==`object`||Array.isArray(value))throw new TypeError(`realtime must be an object when configured.`);return value}function hasRealtimeEventConfig(value={}){const source=normalizeRealtimeOptions(value);return Object.hasOwn(source,`event`)||Object.hasOwn(source,`events`)}function resolveOperationRealtimeOptions({realtime=void 0,fallbackRealtime=null}={}){if(realtime===false)return null;const fallback=normalizeRealtimeOptions(fallbackRealtime);const explicit=realtime==null?{}:normalizeRealtimeOptions(realtime);if(hasRealtimeEventConfig(explicit)||!hasRealtimeEventConfig(fallback))return Object.keys(explicit).length>0?explicit:null;return Object.freeze({...fallback,...explicit})}function toQueryKeyList(value){const resolved=typeof value===`function`?value():unref(value);if(!Array.isArray(resolved)||resolved.length<1)return[];if(Array.isArray(resolved[0]))return resolved.filter(entry=>Array.isArray(entry)&&entry.length>0).map(entry=>Object.freeze([...entry]));return[Object.freeze([...resolved])]}function useRealtimeQueryInvalidation({event=``,enabled=true,matches=null,queryKey=null,onEvent=null}={}){const queryClient=useQueryClient();const normalizedEvent=computed(()=>normalizeText(unref(event)));const active=computed(()=>resolveEnabledRef(enabled)&&Boolean(normalizedEvent.value));const listener=useRealtimeEvent({event:normalizedEvent,enabled:active,matches,onEvent:async context=>{if(typeof onEvent===`function`)await onEvent(context);const keys=toQueryKeyList(queryKey);for(const key of keys)await queryClient.invalidateQueries({queryKey:key})}});return Object.freeze({active:listener.active})}function useOperationRealtime({realtime=null,queryKey=null,enabled=true}={}){const source=normalizeRealtimeOptions(realtime);const eventList=[];if(Object.hasOwn(source,`event`)){const normalizedEvent=normalizeText(source.event);if(normalizedEvent)eventList.push(normalizedEvent)}if(Object.hasOwn(source,`events`)){if(!Array.isArray(source.events))throw new TypeError(`realtime.events must be an array when configured.`);for(const entry of source.events){const normalizedEvent=normalizeText(entry);if(!normalizedEvent||eventList.includes(normalizedEvent))continue;eventList.push(normalizedEvent)}}if(eventList.length<1)return null;const matches=typeof source.matches===`function`?source.matches:null;const onEvent=typeof source.onEvent===`function`?source.onEvent:null;const resolvedQueryKey=Object.hasOwn(source,`queryKey`)?source.queryKey:queryKey;const active=computed(()=>{const sourceEnabled=Object.hasOwn(source,`enabled`)?source.enabled:true;return resolveEnabledRef(enabled)&&resolveEnabledRef(sourceEnabled)});const bindings=eventList.map(event=>useRealtimeQueryInvalidation({event,enabled:active,matches,queryKey:resolvedQueryKey,onEvent}));return Object.freeze({active:computed(()=>bindings.some(binding=>Boolean(binding?.active?.value)))})}function buildEndpointReadRequestOptions({method=`GET`,query=null,transport=null}={}){const requestOptions={method:String(method||`GET`).toUpperCase()};const normalizedQuery=resolveRequestQuery(query);if(normalizedQuery)requestOptions.query=normalizedQuery;if(transport&&typeof transport===`object`)requestOptions.transport=transport;return requestOptions}function resolveRequestQuery(value=null){const source=unref(value);if(!source||typeof source!==`object`||Array.isArray(source))return null;return source}function buildEndpointWriteRequestOptions({method=`PATCH`,body=void 0,options=null,transport=null}={}){const requestOptions={method:String(method||`PATCH`).toUpperCase(),...asPlainObject(options)};if(body!==void 0)requestOptions.body=body;if(transport&&typeof transport===`object`)requestOptions.transport=transport;return requestOptions}function useEndpointResource({queryKey,path=``,enabled=true,client=null,readMethod=`GET`,writeMethod=`PATCH`,readQuery=null,transport=null,refreshOnPull=false,realtime=null,queryOptions=null,mutationOptions=null,requestRecovery=null,requestRecoveryLabel=``,fallbackLoadError=`jskit.http.resource.loadFailed`,fallbackSaveError=`jskit.http.resource.saveFailed`}={}){const activeClient=client||getHttpWebClient();if(!activeClient||typeof activeClient.request!==`function`)throw new TypeError(`useEndpointResource requires a client with request().`);const normalizedPath=computed(()=>resolveTextRef(path));const queryEnabled=computed(()=>resolveEnabledRef(enabled)&&Boolean(normalizedPath.value));const query=useQuery({queryKey,queryFn:({signal})=>{const requestPath=normalizedPath.value;if(!requestPath)throw new Error(`Resource path is required.`);return activeClient.request(requestPath,{...buildEndpointReadRequestOptions({method:readMethod,query:readQuery,transport}),signal})},enabled:queryEnabled,...mergeRequestRecoveryQueryMeta(refreshOnPull?mergeQueryMeta(asPlainObject(queryOptions),{jskit:{refreshOnPull:true}}):asPlainObject(queryOptions),requestRecovery,{label:requestRecoveryLabel,method:readMethod})});const realtimeBinding=useOperationRealtime({realtime,queryKey,enabled:queryEnabled});const mutation=useMutation({mutationFn:async(request={})=>{const options=asPlainObject(request);const requestPath=resolveTextRef(options.path||normalizedPath.value);if(!requestPath)throw new Error(`Resource path is required.`);const method=String(options.method||writeMethod||`PATCH`).toUpperCase();const body=Object.hasOwn(options,`body`)?options.body:options.payload;return activeClient.request(requestPath,buildEndpointWriteRequestOptions({method,body,options:options.options,transport}))},...asPlainObject(mutationOptions)});const data=computed(()=>query.data.value);const hasResolvedData=computed(()=>hasResolvedQueryData({query,data}));const isInitialLoading=computed(()=>Boolean(queryEnabled.value&&query.isPending.value&&!hasResolvedData.value));const isFetching=computed(()=>Boolean(queryEnabled.value&&query.isFetching.value));const isRefetching=computed(()=>Boolean(isFetching.value&&!isInitialLoading.value));const isLoading=computed(()=>Boolean(isInitialLoading.value||isFetching.value));const isSaving=computed(()=>Boolean(mutation.isPending.value));const loadError=computed(()=>toQueryErrorMessage(query.error.value,fallbackLoadError));const saveError=computed(()=>toQueryErrorMessage(mutation.error.value,fallbackSaveError));async function reload(){return query.refetch()}async function save(payload,options={}){return mutation.mutateAsync({...asPlainObject(options),payload})}return Object.freeze({query,mutation,data,isInitialLoading,isFetching,isRefetching,isLoading,isSaving,loadError,saveError,realtime:realtimeBinding,reload,save})}export{resolveQueryValue as $,useJskitText as A,hasPreviousPage as B,resolveEnabledRef as C,ROUTE_VISIBILITY_PUBLIC as D,AUTH_POLICY_PUBLIC as E,useBaseQuery as F,environmentManager as G,notifyManager as H,Mutation as I,hashQueryKeyByOptions as J,functionalUpdate as K,QueryObserver as L,formatMessage as M,useMutation as N,registerJskitMessages as O,useQuery as P,partialMatchKey as Q,Query as R,ROUTE_VISIBILITY_WORKSPACE as S,AUTH_POLICY_AUTHENTICATED as T,focusManager as U,onlineManager as V,Subscribable as W,matchQuery as X,matchMutation as Y,noop as Z,resolveApiSuffix as _,mergeQueryMeta as a,resolveQueryKey as b,toUiErrorMessage as c,asPlainObject as d,skipToken as et,ensureAccessModeCompatibility as f,resolveAccessModeEnabled as g,normalizePermissions as h,useRealtimeQueryInvalidation as i,catalogMessage as j,setJskitI18n as k,toUiFieldErrors as l,normalizeOwnershipFilter as m,resolveOperationRealtimeOptions as n,cloneDeepUnref as nt,mergeRequestRecoveryQueryMeta as o,normalizeAccessMode as p,hashKey as q,useOperationRealtime as r,getClientKey as rt,toQueryErrorMessage as s,useEndpointResource as t,useQueryClient as tt,en_default as u,resolveEnabled as v,resolveTextRef as w,resolveResourceMessages as x,resolvePermissionAccess as y,hasNextPage as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{On as unref,g as computed}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{g as useRoute}from"./useApi-BPuI6ZR9-CFWU1m37.js";import{o as normalizeSurfaceId,r as normalizePathname}from"./returnToPath-gKtcu91D.js";import{f as normalizeText}from"./normalize-BNAdWJYg.js";import{n as resolveLinkPath}from"./linkPath-Ch9eft18.js";import{t as resolveScopedApiBasePath}from"./surface-DzO5xqc8.js";import{c as useWebPlacementContext,i as resolveSurfaceIdFromPlacementPathname,o as resolveSurfaceRootPathFromPlacementContext,r as resolveSurfaceDefinitionFromPlacementContext}from"./placement-DYM3JJ-F.js";import{t as resolveRuntimePathname}from"./pathname-Bb895US8.js";function useSurfaceRouteContext(){const route=useRoute();const{context:placementContext,mergeContext:mergePlacementContext}=useWebPlacementContext();const routePath=computed(()=>resolveRuntimePathname(route?.path));const currentSurfaceId=computed(()=>resolveSurfaceIdFromPlacementPathname(placementContext.value,routePath.value));return Object.freeze({route,routePath,placementContext,mergePlacementContext,currentSurfaceId})}function normalizeRouteParams(params=null){if(!params||typeof params!==`object`||Array.isArray(params))return{};const output={};for(const[rawKey,rawValue]of Object.entries(params)){const key=normalizeText(rawKey);if(!key)continue;const value=Array.isArray(rawValue)?rawValue[0]:rawValue;const normalizedValue=normalizeText(value);if(normalizedValue)output[key]=normalizedValue}return output}function materializeSurfaceRouteBase(routeBaseTemplate=`/`,{params={},strictParams=true,surface=``}={}){const normalizedParams=normalizeRouteParams(params);const missingParams=new Set;const outputPath=String(routeBaseTemplate||`/`).replace(/:([A-Za-z0-9_]+)/g,(_full,rawName)=>{const paramName=String(rawName||``).trim();const paramValue=normalizedParams[paramName];if(!paramValue){missingParams.add(paramName);return`:${paramName}`}return encodeURIComponent(paramValue)});if(strictParams&&missingParams.size>0){const surfaceLabel=String(surface||``).trim()||`(default)`;const missing=[...missingParams].sort().join(`, `);throw new Error(`Missing required surface route params for "${surfaceLabel}": ${missing}.`)}return outputPath}function resolveSurfaceBasePath(context=null,surface=``,{params={},strictParams=true}={}){const normalizedSurface=normalizeSurfaceId(surface);if(normalizedSurface&&resolveSurfaceDefinitionFromPlacementContext(context,normalizedSurface))return materializeSurfaceRouteBase(resolveSurfaceRootPathFromPlacementContext(context,normalizedSurface),{params,strictParams,surface:normalizedSurface});if(!normalizedSurface)return`/`;return normalizePathname(`/${normalizedSurface}`)}function resolveShellLinkPath({context=null,surface=``,explicitTo=``,relativePath=`/`,surfaceRelativePath=``,params={},strictParams=true}={}){const explicitTarget=String(explicitTo||``).trim();if(explicitTarget)return explicitTarget;const normalizedSurface=normalizeSurfaceId(surface);const nextRelativePath=String(surfaceRelativePath||``).trim()||String(relativePath||``).trim()||`/`;const nextSurfaceBasePath=resolveSurfaceBasePath(context,normalizedSurface,{params,strictParams});return resolveLinkPath(nextSurfaceBasePath,nextRelativePath)}function useShellLinkResolver({surface=``}={}){const{context:placementContext}=useWebPlacementContext();function resolve(relativePath=`/`,options={}){return resolveShellLinkPath({context:placementContext.value,surface:String(unref(options.surface??surface)||``),explicitTo:options.explicitTo,relativePath,surfaceRelativePath:options.surfaceRelativePath,params:options.params,strictParams:options.strictParams!==false})}return Object.freeze({resolve})}function normalizePathSuffix(value=``){const raw=normalizeText(unref(value));if(!raw)return``;return raw.startsWith(`/`)?raw:`/${raw}`}function resolveSurfaceId(value,fallback=``){const normalized=normalizeText(unref(value)).toLowerCase();if(normalized&&normalized!==`*`)return normalized;const normalizedFallback=normalizeText(unref(fallback)).toLowerCase();if(normalizedFallback&&normalizedFallback!==`*`)return normalizedFallback;return``}function resolveDefaultSurfaceIdFromPlacementContext(placementContext=null){return resolveSurfaceId(placementContext?.surfaceConfig?.defaultSurfaceId,``)}function resolveRouteParams(baseParams={},overrideParams=null){return{...normalizeRouteParams(baseParams),...normalizeRouteParams(overrideParams)}}function usePaths({routeContext:sourceRouteContext=null}={}){const routeContext=sourceRouteContext||useSurfaceRouteContext();const shellLinkResolver=useShellLinkResolver();const routeParams=computed(()=>normalizeRouteParams(routeContext.route?.params));function page(relativePath=`/`,options={}){const source=options&&typeof options===`object`&&!Array.isArray(options)?options:{};const surface=resolveSurfaceId(source.surface,routeContext.currentSurfaceId.value)||resolveDefaultSurfaceIdFromPlacementContext(routeContext.placementContext.value);if(!surface)return``;return shellLinkResolver.resolve(relativePath,{surface,explicitTo:source.explicitTo,surfaceRelativePath:source.surfaceRelativePath,params:resolveRouteParams(routeParams.value,source.params),strictParams:source.strictParams!==false})}function api(relativePath=``,options={}){const source=options&&typeof options===`object`&&!Array.isArray(options)?options:{};const surface=resolveSurfaceId(source.surface,routeContext.currentSurfaceId.value)||resolveDefaultSurfaceIdFromPlacementContext(routeContext.placementContext.value);const suffix=normalizePathSuffix(relativePath);if(!suffix)throw new TypeError(`usePaths().api(relativePath) requires a non-empty relativePath.`);const routeBase=resolveSurfaceDefinitionFromPlacementContext(routeContext.placementContext.value,surface)?.routeBase||`/`;return resolveScopedApiBasePath({routeBase,relativePath:suffix,params:resolveRouteParams(routeParams.value,source.params),strictParams:source.strictParams!==false})}return Object.freeze({route:routeContext.route,placementContext:routeContext.placementContext,currentSurfaceId:routeContext.currentSurfaceId,routeParams,page,api})}export{resolveShellLinkPath as n,useSurfaceRouteContext as r,usePaths as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{vn as ref}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{r as useShellWebErrorRuntime}from"./error-W1ZAEk4a.js";import{c as toUiErrorMessage}from"./useEndpointResource-
|
|
1
|
+
import{vn as ref}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{r as useShellWebErrorRuntime}from"./error-W1ZAEk4a.js";import{c as toUiErrorMessage}from"./useEndpointResource-7-YDfAxX.js";function useUiFeedback({initialType=`success`,source=`http-web.ui-feedback`,successChannel=``,errorChannel=``,dedupeWindowMs=2e3}={}){const message=ref(``);const messageType=ref(String(initialType||`success`));const errorRuntime=useShellWebErrorRuntime();const normalizedSource=String(source||``).trim()||`http-web.ui-feedback`;let lastErrorPresentation=null;function rememberErrorPresentation(reportResult=null){const presentationId=String(reportResult?.presentationId||``).trim();const presenterId=String(reportResult?.decision?.presenterId||``).trim();if(!presentationId||!presenterId)return;lastErrorPresentation=Object.freeze({presentationId,presenterId})}function dismissLastErrorPresentation(){if(!lastErrorPresentation)return;errorRuntime.dismiss(lastErrorPresentation.presentationId,{presenterId:lastErrorPresentation.presenterId});lastErrorPresentation=null}function clear(){message.value=``}function success(nextMessage=``){messageType.value=`success`;const normalizedMessage=String(nextMessage||``).trim();message.value=normalizedMessage;dismissLastErrorPresentation();if(!normalizedMessage)return;errorRuntime.report({source:normalizedSource,message:normalizedMessage,intent:`action-feedback`,severity:`success`,channel:successChannel,dedupeKey:`${normalizedSource}:success:${normalizedMessage}`,dedupeWindowMs})}function error(errorValue,fallbackMessage=``){messageType.value=`error`;message.value=toUiErrorMessage(errorValue,fallbackMessage);if(!message.value)return;const reportResult=errorRuntime.report({source:normalizedSource,message:message.value,cause:errorValue||null,intent:`action-feedback`,severity:`error`,channel:errorChannel,dedupeKey:`${normalizedSource}:error:${message.value}`,dedupeWindowMs});if(!reportResult?.skipped)rememberErrorPresentation(reportResult)}return Object.freeze({message,messageType,clear,success,error})}export{useUiFeedback as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ht as watch,g as computed,pn as onScopeDispose,vn as ref,xn as shallowRef}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{d as getHttpWebClient}from"./vibe64ProjectScope.local-l5_-E6pq.js";import{n as normalizeConversationTurn$1}from"./conversation-DG9lp25w.js";import{n as useRealtimeEvent}from"./useRealtimeEvent-BNXVwzFG.js";import{t as usePaths}from"./usePaths-Y6UuQxmI.js";import{o as normalizeVibe64ConversationAttachments}from"./shared-TUhK_uYM.js";import{n as useVibe64ProjectSlug}from"./useVibe64ProjectScope-DXjsKKhl.js";import{F as vibe64SessionPath,P as vibe64SessionEventMatchesScope,o as VIBE64_SESSIONS_API_SUFFIX,s as VIBE64_SESSION_CHANGED_EVENT}from"./vibe64SessionRequestConfig-xIx-5jxQ.js";import{C as readRefOrGetterValue}from"./index-CGz4Yow6.js";import{t as connectorDefinitions}from"./english-definitions-DeiQ-jTT.js";var CONVERSATION_LOG_REALTIME_REASONS=new Set([`project-message-changed`,`conversation-rewound`,`session-assistant-selection-updated`,`assistant-stream`,`integration-setup-skipped`,`integration-setup-completed`,`assistant-response-bundle`,`codex-app-server-agent-result`,`codex-app-server-agent-result-invalid`,`codex-app-server-agent-result-missing`,`codex-app-server-agent-result-provider-failed`,`codex-app-server-commentary`,`codex-app-server-final-assistant-message`,`codex-app-server-live-progress`,`codex-app-server-reasoning-summary`,`codex-app-server-terminal-assistant-message`,`codex-app-server-terminal-thinking-message`,`codex-app-server-terminal-user-message`,`codex-turn-outcome`,`codex-app-server-message-delivered`,`opencode-credential-failure`,`opencode-provider-failure`,`opencode-server-assistant-message`,`opencode-server-message-delivered`,`opencode-server-reasoning`,`opencode-server-tool`,`opencode-server-turn-idle`,`claude-stream-turn-idle`,`claude-stream-message`,`claude-stream-message-delivered`,`session-agent-message-cancelled`,`session-agent-message-accepted`,`session-agent-message-delivered`,`session-agent-message-failed`]);function normalizeConversationTurn(turn={},index=0){const normalized=normalizeConversationTurn$1(turn,index,{normalizeAttachments:normalizeVibe64ConversationAttachments});return normalized&&{...normalized,...isRecord(turn.integrationSetup)?{integrationSetup:turn.integrationSetup}:{}}}function isRecord(value){return Boolean(value&&typeof value===`object`&&!Array.isArray(value))}function normalizeConversationLog(payload={},options={}){return conversationTurnsWithPending((Array.isArray(payload?.conversationLog)?payload.conversationLog:[]).map((turn,index)=>normalizeConversationTurn(turn,index)).filter(Boolean),options.pending)}function conversationTurnsWithPending(turns,pending){const pendingTurnIndex=pending===true?turns.length-1:-1;return turns.map((turn,index)=>{if(index===pendingTurnIndex&&turn.user&&!turn.assistant)return{...turn,pending:true};return turn})}function sessionAgentTurnActive(session={}){return(session&&typeof session===`object`&&!Array.isArray(session)?session:{}).agentSession?.turn?.active===true}function conversationLogRealtimeShouldRefresh({payload={}}={},sessionId=``){const normalizedSessionId=String(sessionId||``).trim();const changedSessionId=String(payload.sessionId||payload.entityId||``).trim();if(!normalizedSessionId||changedSessionId!==normalizedSessionId)return false;const reason=String(payload.reason||``).trim();return Boolean(payload.conversationStream)||!reason||CONVERSATION_LOG_REALTIME_REASONS.has(reason)}function conversationLogCompletedTurnKey(session={}){const source=isRecord(session)?session:{};const turn=isRecord(source.agentSession?.turn)?source.agentSession.turn:{};const sessionId=String(source.sessionId||``).trim();const turnId=String(turn.id||``).trim();const revision=Number(source.revision);if(!sessionId||!turnId||turn.active!==false||!Number.isSafeInteger(revision)||revision<0)return``;return`${sessionId}|${revision}|${turnId}`}function useConversationIntegrationActions({turns,enabled,sessionId,projectSlug,sessionsApiPath,reloadConversationLog,httpClient}){const integrationActionPending=shallowRef(null);const integrationActionError=ref(null);const integrationConnections=shallowRef({});function connectIntegrationRequest(request={}){return runIntegrationRequestAction(request,`connect`)}function checkIntegrationRequest(request={}){return runIntegrationRequestAction(request,`status`)}function cancelIntegrationRequest(request={}){return runIntegrationRequestAction(request,`cancel`)}function skipIntegrationRequest(request={}){return runIntegrationRequestAction(request,`skip`)}function resumeIntegrationRequest(request={}){return runIntegrationRequestAction(request,`resume`)}async function runIntegrationRequestAction(request,action){const turn=turns.value.find(entry=>entry.turnId===request.turnId);if(!enabled.value||request.sessionId!==sessionId.value||integrationActionPending.value||turn?.integrationSetup?.outcome!==(action===`resume`?`completed`:`pending`)||turn.integrationSetup.requestId!==request.requestId)return false;const selection={sessionId:sessionId.value,turnId:request.turnId,requestId:request.requestId};integrationActionPending.value=selection;integrationActionError.value=null;try{if([`connect`,`cancel`,`status`].includes(action)){const path=vibe64SessionPath(sessionsApiPath.value,selection.sessionId,`/integrations`);const config=await httpClient.request(path);if(integrationActionPending.value!==selection||sessionId.value!==selection.sessionId)return false;const integrationId=turn.integrationSetup.integrationId;const integration=config?.configuration?.integrations?.[integrationId];if(!integration)throw new Error(`Choose Configure to set up this integration first.`);if(connectorDefinitions.some(provider=>provider.id===integration.provider&&(provider.configurationOnly||provider.configurationOnlyForSettings?.(integration?.settings||{})))){integrationConnections.value={...integrationConnections.value,[selection.requestId]:{status:`configuration-only`}};return true}if(integration.accountMode===`per-user`)throw new Error(`Each app user connects their account inside the application. Choose Configure for setup instructions.`);const endpoint=`${path}/${encodeURIComponent(integrationId)}/setup`;const previous=integrationConnections.value[selection.requestId];if(action===`cancel`&&!previous?.attemptId)return false;let connection=await httpClient.request(endpoint,{method:`POST`,body:{operation:action,...action===`cancel`?{attemptId:previous.attemptId}:{setupRequest:{turnId:selection.turnId,requestId:selection.requestId,configurationHash:config.baseHash}}}});if(integrationActionPending.value!==selection||sessionId.value!==selection.sessionId)return false;if(action===`cancel`){connection=await httpClient.request(endpoint,{method:`POST`,body:{operation:`status`}});if(integrationActionPending.value!==selection||sessionId.value!==selection.sessionId)return false}integrationConnections.value={...integrationConnections.value,[selection.requestId]:connection};if(connection.integrationSetup?.outcome===`completed`&&connection.integrationSetup.continuation?.status!==`accepted`){const resumed=await httpClient.request(vibe64SessionPath(sessionsApiPath.value,selection.sessionId,`/integration-setup/resume`),{method:`POST`,body:{turnId:selection.turnId,requestId:selection.requestId}});if(resumed?.ok!==true)throw new Error(resumed?.error||`Assistant continuation is not yet confirmed.`)}if(integrationActionPending.value===selection&&sessionId.value===selection.sessionId)await reloadConversationLog();return true}const result=await httpClient.request(vibe64SessionPath(sessionsApiPath.value,selection.sessionId,`/integration-setup/${action}`),{method:`POST`,body:{turnId:selection.turnId,requestId:selection.requestId}});if(result?.ok!==true)throw new Error(result?.error||`Could not update integration setup.`);if(integrationActionPending.value===selection&&sessionId.value===selection.sessionId)await reloadConversationLog();return true}catch(error){if(sessionId.value===selection.sessionId&&integrationActionPending.value===selection){integrationActionError.value={turnId:selection.turnId,message:String(error?.message||`Could not update integration setup.`)};if(action===`resume`||action===`connect`||action===`status`)await reloadConversationLog()}return false}finally{if(sessionId.value===selection.sessionId&&integrationActionPending.value===selection)integrationActionPending.value=null}}onScopeDispose(()=>{integrationActionPending.value=null});watch([sessionId,projectSlug],()=>{integrationActionPending.value=null;integrationActionError.value=null;integrationConnections.value={}});return{integrationConnections,connectIntegrationRequest,checkIntegrationRequest,cancelIntegrationRequest,integrationActionPending,integrationActionError,skipIntegrationRequest,resumeIntegrationRequest}}function useVibe64ConversationLog({active=true,projectSlug:projectSlugInput,sessionsApiPath:sessionsApiPathInput,session,conversation}={}){const paths=usePaths();const httpClient=getHttpWebClient();const projectSlug=projectSlugInput===void 0?useVibe64ProjectSlug():computed(()=>readRefOrGetterValue(projectSlugInput));const currentSession=computed(()=>readRefOrGetterValue(session)||null);const sessionId=computed(()=>String(currentSession.value?.sessionId||``).trim());const enabled=computed(()=>Boolean(readRefOrGetterValue(active)!==false&&sessionId.value));const sessionsApiPath=computed(()=>readRefOrGetterValue(sessionsApiPathInput)||paths.api(`/vibe64/sessions`,{surface:`app`}));const turns=computed(()=>conversationTurnsWithPending(conversation.turns.value,sessionAgentTurnActive(currentSession.value)));const integrationActions=useConversationIntegrationActions({turns,enabled,sessionId,projectSlug,sessionsApiPath,reloadConversationLog:conversation.reload,httpClient});let realtimeCompletionKey=``;const realtime=useRealtimeEvent({enabled,event:VIBE64_SESSION_CHANGED_EVENT,matches:context=>([`session-assistant-selection-updated`,`integration-setup-skipped`,`integration-setup-completed`].includes(context?.payload?.reason)||conversationLogCompletedTurnKey(context?.payload))&&conversationLogRealtimeShouldRefresh(context,sessionId.value)&&vibe64SessionEventMatchesScope(context?.payload,{projectSlug:projectSlug.value}),onEvent:({payload={}}={})=>{realtimeCompletionKey=conversationLogCompletedTurnKey(payload)||realtimeCompletionKey;return payload.reason===`session-assistant-selection-updated`?conversation.reload({resubscribe:true}):conversation.reload()}});watch(()=>conversationLogCompletedTurnKey(currentSession.value),key=>{if(!enabled.value||!key)return;if(key===realtimeCompletionKey){realtimeCompletionKey=``;return}conversation.reload()?.catch(()=>{})},{flush:`post`});return{...integrationActions,turns,error:conversation.error,errorReloadable:computed(()=>conversation.accessDenied?.value===false),hasMoreBefore:conversation.hasMoreBefore,loadMore:conversation.loadMore,loadMoreError:conversation.loadMoreError,loading:conversation.loading,initializing:computed(()=>!conversation.snapshot.value&&conversation.loading.value),loadingMore:conversation.loadingMore,reload:conversation.reload,realtime,visible:computed(()=>Boolean(conversation.loading.value||conversation.error.value||turns.value.length))}}export{useVibe64ConversationLog as n,normalizeConversationLog as t};
|
package/dist/assets/{useVibe64DatabaseTools-BE_yXZFn.js → useVibe64DatabaseTools-DKV-TeNJ.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{H as hasInjectionContext,J as inject,On as unref,g as computed}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{
|
|
1
|
+
import{H as hasInjectionContext,J as inject,On as unref,g as computed}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{D as ROUTE_VISIBILITY_PUBLIC,t as useEndpointResource}from"./useEndpointResource-7-YDfAxX.js";import{n as VIBE64_ASSISTANT_VIEWER_KEY}from"./vibe64AssistantHost-CP6oxv5b.js";import{C as VIBE64_CONNECTIONS_CHANGED_EVENT,S as VIBE64_ACCOUNTS_CHANGED_EVENT}from"./client-CCZIu6yc.js";import{t as usePaths}from"./usePaths-Y6UuQxmI.js";import{t as useCommand}from"./useCommand-CVuya6vG.js";var VIBE64_DATABASE_LAYOUT_CHANGED_EVENT=`vibe64.database.layout.changed`;var DATABASE_API_SUFFIX=`/vibe64/database`;var DATABASE_SURFACE=`app`;function encodeSegment(value=``){return encodeURIComponent(String(value||``).trim())}function databaseSessionPath(apiPath=``,sessionId=``,suffix=``){return`${apiPath}/sessions/${encodeSegment(sessionId)}${suffix}`}function useVibe64DatabaseTools({active=true,projectSlug=``,sessionId=``}={}){const paths=usePaths();const viewer=hasInjectionContext()?inject(VIBE64_ASSISTANT_VIEWER_KEY,{actorKey:`local`}):{actorKey:`local`};const actorKey=computed(()=>unref(viewer)?.actorKey||``);const normalizedSessionId=computed(()=>String(unref(sessionId)||``).trim());const normalizedProjectSlug=computed(()=>String(unref(projectSlug)||``).trim());const enabled=computed(()=>Boolean(unref(active)&&normalizedSessionId.value&&actorKey.value));const apiPath=computed(()=>paths.api(DATABASE_API_SUFFIX,{surface:DATABASE_SURFACE}));const sessionPath=computed(()=>databaseSessionPath(apiPath.value,normalizedSessionId.value));const stateResource=useEndpointResource({enabled,fallbackLoadError:`The session database workspace could not be loaded.`,path:computed(()=>enabled.value?sessionPath.value:``),queryKey:computed(()=>[`vibe64`,`database`,normalizedProjectSlug.value,normalizedSessionId.value,actorKey.value,`state`]),realtime:{events:[VIBE64_DATABASE_LAYOUT_CHANGED_EVENT,VIBE64_ACCOUNTS_CHANGED_EVENT,VIBE64_CONNECTIONS_CHANGED_EVENT],matches:({event,payload={}}={})=>event!==`vibe64.database.layout.changed`||payload.projectSlug===normalizedProjectSlug.value&&payload.sessionId===normalizedSessionId.value},requestRecoveryLabel:`Session database`});function databaseCommand({fallback,method=`POST`,placement,success=`Completed.`,suppressSuccessMessage=false}={}){return useCommand({access:`never`,apiSuffix:DATABASE_API_SUFFIX,buildCommandOptions:(_input,{context})=>({method:context.method||method,path:context.path||sessionPath.value}),buildRawPayload:(_model,{context})=>context.payload||{},fallbackRunError:fallback,messages:{error:fallback,success},ownershipFilter:ROUTE_VISIBILITY_PUBLIC,placementSource:`vibe64.database.${placement}`,suppressSuccessMessage,surfaceId:DATABASE_SURFACE,writeMethod:method})}const refreshCommand=databaseCommand({fallback:`The database schema could not be refreshed.`,placement:`schema.refresh`,success:`Database schema refreshed.`});const queryCommand=databaseCommand({fallback:`The SQL statement could not be run.`,placement:`query.run`,success:`SQL statement completed.`});const defaultQueryCommand=databaseCommand({fallback:`The table data could not be loaded.`,placement:`query.default`,suppressSuccessMessage:true});const cancelCommand=databaseCommand({fallback:`The database query could not be cancelled.`,placement:`query.cancel`,suppressSuccessMessage:true});const updateCommand=databaseCommand({fallback:`The database value could not be saved.`,method:`PATCH`,placement:`cell.update`,success:`Database value saved.`});const insertCommand=databaseCommand({fallback:`The database row could not be inserted.`,placement:`row.insert`,success:`Database row inserted.`});const deleteCommand=databaseCommand({fallback:`The database row could not be deleted.`,placement:`row.delete`,success:`Database row deleted.`});const lookupCommand=databaseCommand({fallback:`The lookup table could not be searched.`,placement:`lookup.search`,suppressSuccessMessage:true});const layoutCommand=databaseCommand({fallback:`The ERD layout could not be saved.`,method:`PUT`,placement:`layout.save`,suppressSuccessMessage:true});const overviewCommand=databaseCommand({fallback:`The main actor grouping could not be saved.`,method:`PUT`,placement:`overview.save`,success:`Main actors saved in project source.`});const snippetCommand=databaseCommand({fallback:`The SQL snippet could not be saved.`,method:`PUT`,placement:`snippet.save`,success:`SQL snippet saved.`});const snippetDeleteCommand=databaseCommand({fallback:`The SQL snippet could not be deleted.`,method:`DELETE`,placement:`snippet.delete`,success:`SQL snippet deleted.`});const assistantCommand=databaseCommand({fallback:`The database copilot could not answer.`,placement:`assistant.ask`,suppressSuccessMessage:true});async function reload(){if(enabled.value)return stateResource.reload()}async function refreshSchema(){const result=await refreshCommand.run({path:`${sessionPath.value}/schema/refresh`});await reload();return result}function runQuery(payload={}){return(payload.automatic===true?defaultQueryCommand:queryCommand).run({path:`${sessionPath.value}/queries`,payload})}function cancelQuery(queryId=``){return cancelCommand.run({path:`${sessionPath.value}/queries/${encodeSegment(queryId)}/cancel`})}function updateCell(payload={}){return updateCommand.run({path:`${sessionPath.value}/cells`,payload})}function insertRow(payload={}){return insertCommand.run({path:`${sessionPath.value}/rows`,payload})}function deleteRow(payload={}){return deleteCommand.run({path:`${sessionPath.value}/rows/delete`,payload})}function searchLookup(payload={}){return lookupCommand.run({path:`${sessionPath.value}/lookups/search`,payload})}function saveLayout(layout={}){return layoutCommand.run({path:`${sessionPath.value}/layout`,payload:{layout}})}async function saveOverview(payload){const result=await overviewCommand.run({path:`${sessionPath.value}/overview`,payload});if(result?.ok!==false)await reload();return result}function saveSnippet(snippet={}){return snippetCommand.run({path:`${sessionPath.value}/snippets`,payload:{snippet}})}function deleteSnippet(snippetId=``){return snippetDeleteCommand.run({path:`${sessionPath.value}/snippets/${encodeSegment(snippetId)}`})}return{assistantCommand,assistantEndpoint:computed(()=>`${sessionPath.value}/assistant`),assistantBusy:computed(()=>assistantCommand.isRunning===true),cancelQuery,cancelling:computed(()=>cancelCommand.isRunning===true),deleteRow,deleteSnippet,deleting:computed(()=>deleteCommand.isRunning===true),error:stateResource.loadError,insertRow,inserting:computed(()=>insertCommand.isRunning===true),layoutSaving:computed(()=>layoutCommand.isRunning===true),loading:stateResource.isLoading,lookupBusy:computed(()=>lookupCommand.isRunning===true),refreshSchema,refreshing:computed(()=>refreshCommand.isRunning===true),reload,runQuery,running:computed(()=>queryCommand.isRunning===true||defaultQueryCommand.isRunning===true),saveLayout,saveOverview,saveSnippet,searchLookup,state:computed(()=>actorKey.value?stateResource.data.value||null:null),updateCell,updating:computed(()=>updateCommand.isRunning===true)}}export{databaseSessionPath as n,useVibe64DatabaseTools as r,DATABASE_API_SUFFIX as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{J as inject,L as getCurrentInstance,g as computed,gt as provide}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{g as useRoute}from"./useApi-BPuI6ZR9-CFWU1m37.js";import{o as projectSlugFromRoute}from"./vibe64ProjectScope.local-
|
|
1
|
+
import{J as inject,L as getCurrentInstance,g as computed,gt as provide}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{g as useRoute}from"./useApi-BPuI6ZR9-CFWU1m37.js";import{o as projectSlugFromRoute}from"./vibe64ProjectScope.local-l5_-E6pq.js";var VIBE64_OPENED_PROJECT_SLUG_KEY=Symbol(`vibe64.opened-project-slug`);function provideVibe64OpenedProjectSlug(route=useRoute()){const slug=projectSlugFromRoute(route);provide(VIBE64_OPENED_PROJECT_SLUG_KEY,computed(()=>slug))}function useVibe64ProjectSlug(route=useRoute()){return(getCurrentInstance()?inject(VIBE64_OPENED_PROJECT_SLUG_KEY,null):null)||computed(()=>projectSlugFromRoute(route))}export{useVibe64ProjectSlug as n,provideVibe64OpenedProjectSlug as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ht as watch,On as unref,g as computed,hn as proxyRefs,pn as onScopeDispose,vn as ref}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{D as ROUTE_VISIBILITY_PUBLIC,t as useEndpointResource,tt as useQueryClient}from"./useEndpointResource-7-YDfAxX.js";import{_ as useRouter,g as useRoute}from"./useApi-BPuI6ZR9-CFWU1m37.js";import{o as projectSlugFromRoute}from"./vibe64ProjectScope.local-l5_-E6pq.js";import{n as useRealtimeEvent}from"./useRealtimeEvent-BNXVwzFG.js";import{t as usePaths}from"./usePaths-Y6UuQxmI.js";import{t as useCommand}from"./useCommand-CVuya6vG.js";import{t as useUiFeedback}from"./useUiFeedback-Bd3rao6E.js";import{b as VIBE64_PROJECT_CHANGED_EVENT}from"./studioGateApi-mkX1eOTX.js";import{n as useVibe64ProjectSlug}from"./useVibe64ProjectScope-DXjsKKhl.js";import{n as vibe64RealtimeOriginPayload}from"./vibe64BrowserTabOrigin-SF9E31vi.js";import{B as vibe64SessionsQueryKey,F as vibe64SessionPath,P as vibe64SessionEventMatchesScope,a as VIBE64_CURRENT_SESSION_API_SUFFIX,o as VIBE64_SESSIONS_API_SUFFIX,s as VIBE64_SESSION_CHANGED_EVENT,z as vibe64SessionQueryKey}from"./vibe64SessionRequestConfig-xIx-5jxQ.js";import{C as readRefOrGetterValue}from"./index-CGz4Yow6.js";import{i as vibe64SessionDisplayTitle,o as vibe64SessionRevision,r as shortVibe64SessionId,t as isArchivedVibe64Session}from"./vibe64SessionViewModel-B0cCumM8.js";import{i as vibe64SessionDebugSummary,n as vibe64SessionDebugError,r as vibe64SessionDebugLog,t as vibe64SessionDebugDurationMs}from"./vibe64SessionDebugLog-C06bcdUN.js";import{n as enrichVibe64SessionForDisplay,r as visibleVibe64Sessions}from"./vibe64SessionPanelModel-DoorGDCG.js";import{n as useVibe64SessionSelection,t as selectedSessionIdFromRoute}from"./useVibe64SessionSelection-N8wX5oqo.js";function refetchEndpointResource(resource){if(typeof resource?.query?.refetch===`function`)return resource.query.refetch({cancelRefetch:false});return resource?.reload?.()}function plainObjectValue(value=null){return value&&typeof value===`object`&&!Array.isArray(value)?value:{}}function sessionChangedReason(payload={}){return String(payload?.reason||``).trim()}function sessionRevision(value){const revision=Number(value);return Number.isSafeInteger(revision)&&revision>=0?revision:null}function agentTurnRealtimeOverlayFromPayload(payload={},selectedSessionId=``){const changedSessionId=String(payload?.sessionId||payload?.entityId||``).trim();if(!changedSessionId||changedSessionId!==String(selectedSessionId||``).trim())return null;const agentSession=plainObjectValue(payload.agentSession);const turn=plainObjectValue(agentSession.turn);const run=plainObjectValue(payload.agentRun);const revision=sessionRevision(payload.revision);if(revision===null||!Object.keys(turn).length&&!Object.keys(run).length)return null;const active=turn.active===true||run.active===true;return{active,agentRun:{...run,active},agentSession:{...agentSession,turn:{...turn,active}},reason:sessionChangedReason(payload),revision,sessionId:changedSessionId}}function latestAgentTurnRealtimeOverlay(current=null,candidate=null){if(!candidate)return current;if(!current||candidate.revision>current.revision)return candidate;return current}function mergeAgentRunOverlay(agentRuns=[],overlayRun={}){const runs=Array.isArray(agentRuns)?agentRuns:[];const runId=String(overlayRun.id||``).trim();if(!runId)return runs;const nextRun={...overlayRun,id:runId};const index=runs.findIndex(run=>String(run?.id||``).trim()===runId);if(index<0)return[...runs,nextRun];return runs.map((run,runIndex)=>runIndex===index?{...run,...nextRun}:run)}function sessionWithAgentTurnRealtimeOverlay(session=null,overlay=null){const currentRevision=sessionRevision(session?.revision);if(!session||!overlay||session?.ok===false||session.sessionId!==overlay.sessionId||currentRevision!==null&&overlay.revision<=currentRevision)return session;const overlayAgentSession=plainObjectValue(overlay.agentSession);return{...session,agentRuns:mergeAgentRunOverlay(session.agentRuns,plainObjectValue(overlay.agentRun)),agentSession:{...plainObjectValue(session.agentSession),...overlayAgentSession,thread:{...plainObjectValue(session.agentSession?.thread),...plainObjectValue(overlayAgentSession.thread)},turn:{...plainObjectValue(session.agentSession?.turn),...plainObjectValue(overlayAgentSession.turn),active:overlay.active===true}},revision:overlay.revision}}function sessionRecordHasDetailProjection(session=null){return Boolean(session&&typeof session===`object`&&Object.hasOwn(session,`agentSession`))}function sessionRecordHasActiveAgentWork(session=null){return(session?.agentSession?.turn?.active??session?.agentActivity?.active)===true}function sessionRecordMatchesId(session=null,sessionId=``){const normalizedSessionId=String(sessionId||``).trim();return Boolean(normalizedSessionId&&session?.sessionId===normalizedSessionId&&session?.ok!==false)}function latestSessionDetailRecord(current=null,candidate=null,sessionId=``){if(!sessionRecordMatchesId(candidate,sessionId))return current;if(!sessionRecordMatchesId(current,sessionId))return candidate;const currentRevision=vibe64SessionRevision(current);const candidateRevision=vibe64SessionRevision(candidate);if(currentRevision!==null&&candidateRevision!==null&&candidateRevision<currentRevision)return current;return candidate}function mountedSessionRecord(detailSession=null,listSession=null,sessionId=``){const normalizedSessionId=String(sessionId||``).trim();const listSessionMatches=sessionRecordMatchesId(listSession,normalizedSessionId);if(!sessionRecordMatchesId(detailSession,normalizedSessionId))return listSessionMatches?listSession:null;const detailRevision=vibe64SessionRevision(detailSession);const listRevision=vibe64SessionRevision(listSession);if(listSessionMatches&&listRevision!==null&&detailRevision!==null&&listRevision>detailRevision){if(sessionRecordHasDetailProjection(detailSession)&&!sessionRecordHasDetailProjection(listSession))return detailSession;return listSession}return detailSession}function mountedSessionDetailRefreshReason(detailSession=null,listSession=null,sessionId=``){const normalizedSessionId=String(sessionId||``).trim();if(!sessionRecordMatchesId(detailSession,normalizedSessionId)||!sessionRecordMatchesId(listSession,normalizedSessionId))return``;const detailRevision=vibe64SessionRevision(detailSession);const listRevision=vibe64SessionRevision(listSession);if(listRevision!==null&&detailRevision!==null&&listRevision>detailRevision&&sessionRecordHasDetailProjection(detailSession)&&!sessionRecordHasDetailProjection(listSession))return`newer_summary_without_detail`;return``}function mountedSessionDetailLoadState({detailSession=null,fetching=false,listSession=null,loadError=``,loading=false,sessionId=``}={}){const normalizedSessionId=String(sessionId||``).trim();const hasDetail=sessionRecordMatchesId(detailSession,normalizedSessionId);const hasSummary=sessionRecordMatchesId(listSession,normalizedSessionId);const error=String(loadError||``).trim();if(!normalizedSessionId)return{error:``,label:``,loading:false,ready:false,restoring:false,sessionId:``,state:`summaryOnly`};if(error&&!hasDetail)return{error,label:`Session could not load.`,loading:false,ready:false,restoring:false,sessionId:normalizedSessionId,state:`detailError`};if(hasDetail)return{error:``,label:``,loading:false,ready:true,refreshing:Boolean(fetching||loading),restoring:false,sessionId:normalizedSessionId,state:`detailReady`};if(loading||fetching)return{error:``,label:`Loading session...`,loading:true,ready:false,restoring:false,sessionId:normalizedSessionId,state:`detailLoading`};return{error:``,label:hasSummary?`Session could not load.`:`Loading session...`,loading:false,ready:false,restoring:false,sessionId:normalizedSessionId,state:`summaryOnly`}}function mountedSessionRealtimeShouldRefresh({payload={}}={},sessionId=``,read=`includeDetail`){const changedSessionId=String(payload.sessionId||payload.entityId||``).trim();if(!changedSessionId||changedSessionId!==String(sessionId||``).trim())return false;return payload?.clientRefresh?.[read]!==false}function useVibe64SessionDialogs({beginArchive=()=>null,finishArchive=()=>null,isSelectedSessionArchived,refreshSessionData=async()=>null,selectedSessionId,selectedSessionTitle,sessionsApiPath}={}){const archiveDialogOpen=ref(false);const archiveDialogSessionId=ref(``);const archiveDialogSessionTitle=ref(``);const archivingSessionId=ref(``);const resolvedSessionsApiPath=computed(()=>String(readRefOrGetterValue(sessionsApiPath)||``));const archiveCommand=useCommand({access:`never`,apiSuffix:VIBE64_SESSIONS_API_SUFFIX,buildRawPayload:()=>vibe64RealtimeOriginPayload(),buildCommandOptions:(_payload,{context})=>({method:`POST`,path:vibe64SessionPath(resolvedSessionsApiPath.value,context?.sessionId,`/archive`)}),fallbackRunError:`Vibe64 session could not be archived.`,messages:{error:`Vibe64 session could not be archived.`,success:`Vibe64 session archived.`},onRunSuccess:async response=>{if(response?.ok!==true)throw new Error(response?.errors?.[0]?.message||response?.error||`Vibe64 session could not be archived.`)},ownershipFilter:ROUTE_VISIBILITY_PUBLIC,placementSource:`vibe64.sessions.archive`,surfaceId:`app`,writeMethod:`POST`});function clearArchiveDialog(){archiveDialogOpen.value=false;archiveDialogSessionId.value=``;archiveDialogSessionTitle.value=``}function requestArchiveSelectedSession(){if(!unref(selectedSessionId)||archivingSessionId.value||archiveCommand.isRunning||unref(isSelectedSessionArchived))return;archiveDialogSessionId.value=unref(selectedSessionId);archiveDialogSessionTitle.value=unref(selectedSessionTitle);archiveDialogOpen.value=true}function cancelArchiveSession(){if(!archiveCommand.isRunning)clearArchiveDialog()}async function confirmArchiveSession(){if(!archiveDialogSessionId.value||archivingSessionId.value||archiveCommand.isRunning)return false;const sessionId=archiveDialogSessionId.value;archivingSessionId.value=sessionId;clearArchiveDialog();const archiveScope=beginArchive(sessionId);let succeeded=false;try{const response=await archiveCommand.run({sessionId});succeeded=response?.ok===true;return response}catch{return false}finally{finishArchive(sessionId,succeeded,archiveScope);if(archivingSessionId.value===sessionId)archivingSessionId.value=``;refreshSessionData({reason:`archive-session`}).catch(()=>null)}}return{archiving:computed(()=>Boolean(archivingSessionId.value)),archivingSessionId,cancel:cancelArchiveSession,command:archiveCommand,confirm:confirmArchiveSession,open:archiveDialogOpen,request:requestArchiveSelectedSession,sessionId:archiveDialogSessionId,sessionTitle:archiveDialogSessionTitle}}function createVibe64CurrentSessionPublisher({onError=()=>null,publish}={}){if(typeof publish!==`function`)throw new TypeError(`Current Vibe64 session publisher requires publish().`);let pendingPublication=null;let publicationChain=Promise.resolve();let lastPublishedIdentity=null;let stopped=false;function request(publication={}){if(stopped)return publicationChain;const apiPath=String(publication?.apiPath||``);const sessionId=String(publication?.sessionId||``).trim();pendingPublication={apiPath,identity:JSON.stringify([apiPath,sessionId]),sessionId};publicationChain=publicationChain.catch(()=>null).then(async()=>{const publication=pendingPublication;pendingPublication=null;if(stopped||!publication)return;if(publication.identity===lastPublishedIdentity)return;try{await publish({apiPath:publication.apiPath,sessionId:publication.sessionId});lastPublishedIdentity=publication.identity}catch(error){onError(error,publication)}});return publicationChain}function stop(){stopped=true;pendingPublication=null}return Object.freeze({request,stop})}function sessionArchiveOperation(session){try{return JSON.parse(session?.metadata?.session_archive_operation||`null`)}catch{return{status:`failed`,error:`Session archive state could not be read.`}}}function sessionArchiveState(session){const operation=sessionArchiveOperation(session);const failed=operation?.status===`failed`;return{archiveError:failed?operation.error:``,archiving:!failed&&(operation?.status===`running`||session?.metadata?.session_closing_reason===`archived`),operation}}function sessionIdExistsInList(sessionId=``,nextSessions=[]){const normalizedSessionId=String(sessionId||``).trim();return Boolean(normalizedSessionId)&&nextSessions.some(session=>session.sessionId===normalizedSessionId)}function renewedSuccessorSessionId({predecessorSessionId=``,sessions=[]}={}){const predecessorId=String(predecessorSessionId||``).trim();if(!predecessorId)return``;const matches=sessions.filter(session=>String(session?.metadata?.renewed_from||``).trim()===predecessorId);return matches.length===1?String(matches[0]?.sessionId||``).trim():``}function routeQueryWithoutUnlistedSession({route={},projectSlug=``,sessions=[]}={}){const routeSessionId=selectedSessionIdFromRoute(route);if(!routeSessionId||projectSlugFromRoute(route)!==projectSlug||sessionIdExistsInList(routeSessionId,sessions))return null;const{session:_session,conversation:_conversation,chat:_chat,...query}=route.query||{};return query}function shouldPreserveSelectedSessionDuringRefresh({createSessionRunning=false,currentSessionId=``,nextSessions=[],sessionListLoading=false}={}){const normalizedSessionId=String(currentSessionId||``).trim();if(!normalizedSessionId||sessionIdExistsInList(normalizedSessionId,nextSessions))return false;return Boolean(sessionListLoading||createSessionRunning)}function selectedSessionIdForCurrentAlias({createSessionRunning=false,selectedSessionId=``,sessionListLoaded=true,sessionListLoadError=``,sessionListLoading=false,sessions=[]}={}){if(!sessionListLoaded||sessionListLoading||String(sessionListLoadError||``).trim())return null;const normalizedSessionId=String(selectedSessionId||``).trim();if(sessionIdExistsInList(normalizedSessionId,sessions))return normalizedSessionId;if(sessions.length>0||createSessionRunning)return null;return``}function sessionListRealtimeShouldRefresh({payload={}}={},projectSlug=``){return vibe64SessionEventMatchesScope(payload,{projectSlug})&&payload?.clientRefresh?.includeList!==false}function useVibe64SessionData(){const queryClient=useQueryClient();const projectSlug=useVibe64ProjectSlug();const route=useRoute();const router=useRouter();const paths=usePaths();const selectionScope=computed(()=>String(projectSlug.value||``).trim());const sessionSelection=useVibe64SessionSelection({projectSlug});const selectedSessionId=sessionSelection.selectedId;const sessionsApiPath=computed(()=>paths.api(VIBE64_SESSIONS_API_SUFFIX,{surface:`app`}));const currentSessionApiPath=computed(()=>paths.api(VIBE64_CURRENT_SESSION_API_SUFFIX,{surface:`app`}));const sessionListQueryKey=computed(()=>vibe64SessionsQueryKey(`app`,ROUTE_VISIBILITY_PUBLIC,projectSlug.value));const sessionListResource=useEndpointResource({fallbackLoadError:`Vibe64 sessions could not be loaded.`,path:sessionsApiPath,queryKey:sessionListQueryKey,readQuery:{limit:20},queryOptions:{refetchOnMount:false,refetchOnWindowFocus:false},requestRecoveryLabel:`Vibe64 sessions`,realtime:{events:[VIBE64_SESSION_CHANGED_EVENT,VIBE64_PROJECT_CHANGED_EVENT,`connect`],matches:event=>sessionListRealtimeShouldRefresh(event,projectSlug.value)}});const sessionList=proxyRefs({unavailableItems:computed(()=>sessionListResource.data.value?.unavailableSessions||[]),items:computed(()=>{const payload=sessionListResource.data.value||{};return Array.isArray(payload.sessions)?payload.sessions:[]}),loadError:computed(()=>sessionListResource.loadError.value),isInitialLoading:computed(()=>sessionListResource.isInitialLoading.value),isLoading:computed(()=>sessionListResource.isLoading.value),pages:computed(()=>{const payload=sessionListResource.data.value;return payload&&typeof payload===`object`&&!Array.isArray(payload)?[payload]:[]}),reload:sessionListResource.reload,resource:sessionListResource});let emptySessionListObservedForProject=``;const createSessionCommand=useCommand({access:`never`,apiSuffix:VIBE64_SESSIONS_API_SUFFIX,buildCommandOptions:(_model,{context})=>({method:`POST`,path:context?.apiPath}),buildRawPayload:(_model,{context})=>vibe64RealtimeOriginPayload({assistantSelection:context?.assistantSelection||{},...context?.repositoryBranch?{repositoryBranch:context.repositoryBranch}:{},...context?.pullRequestNumber?{pullRequestNumber:context.pullRequestNumber}:{}}),fallbackRunError:`Vibe64 session could not be created.`,messages:{error:`Vibe64 session could not be created.`,success:`Vibe64 session created.`},ownershipFilter:ROUTE_VISIBILITY_PUBLIC,placementSource:`vibe64.sessions.create`,surfaceId:`app`,writeMethod:`POST`});const createSessionRunning=ref(false);const updateCurrentSessionCommand=useCommand({access:`never`,apiSuffix:VIBE64_CURRENT_SESSION_API_SUFFIX,buildCommandOptions:(_model,{context})=>({method:`PUT`,path:String(context?.apiPath||``)}),buildRawPayload:(_model,{context})=>({sessionId:String(context?.sessionId||``).trim()}),fallbackRunError:`The current session shortcut could not be updated.`,messages:{error:`The current session shortcut could not be updated.`},ownershipFilter:ROUTE_VISIBILITY_PUBLIC,placementSource:`vibe64.sessions.current.update`,suppressSuccessMessage:true,surfaceId:`app`,writeMethod:`PUT`});const currentSessionPublisher=createVibe64CurrentSessionPublisher({async publish({apiPath,sessionId}){const response=await updateCurrentSessionCommand.run({apiPath,sessionId});if(!response||response.ok===false)throw new Error(String(response?.error||`The current session shortcut could not be updated.`))},onError(error,publication){vibe64SessionDebugLog(`client.sessionData.currentSession.error`,{error:vibe64SessionDebugError(error),sessionId:publication.sessionId})}});let sessionDataDisposed=false;onScopeDispose(()=>{sessionDataDisposed=true;currentSessionPublisher.stop()});const archiveAttempts=ref({});const agentActivityBySessionId=ref({});const sessions=computed(()=>{const items=new Map((sessionList.items||[]).map(session=>[session.sessionId,session]));for(const[id,attempt]of Object.entries(archiveAttempts.value))if(attempt.succeeded)items.delete(id);else items.set(id,{...items.get(id)||attempt.session,archiving:true,archiveStartedAt:attempt.startedAt});return visibleVibe64Sessions([...items.values()]).map(session=>{const archiveState=sessionArchiveState(session);return{...session,agentActivity:latestAgentTurnRealtimeOverlay(session.agentActivity,agentActivityBySessionId.value[session.sessionId]),archiveOperation:archiveState.operation,archiveStartedAt:archiveState.operation?.startedAt||session.archiveStartedAt,archiveError:archiveState.archiveError,archiving:Boolean(session.archiving||archiveState.archiving)}})});const availableSessions=computed(()=>sessions.value.filter(session=>!session.archiving));const selectedListSession=computed(()=>{return sessions.value.find(session=>session.sessionId===selectedSessionId.value)||null});const selectedSessionMissing=computed(()=>{const selectedId=String(selectedSessionId.value||``).trim();if(!selectedId||sessionList.pages.length<1||String(sessionList.loadError||``).trim()||sessionIdExistsInList(selectedId,sessions.value))return false;return true});const selectionRenewalPredecessorId=computed(()=>{const selectedId=String(selectedSessionId.value||``).trim();if(!selectedId||sessionList.pages.length<1||String(sessionList.loadError||``).trim())return``;if(sessionList.unavailableItems.some(session=>session.sessionId===selectedId))return``;if(selectedSessionMissing.value)return selectedId;return String(selectedListSession.value?.metadata?.renewed_from||``).trim()});const selectionRenewalPath=computed(()=>selectionRenewalPredecessorId.value?vibe64SessionPath(sessionsApiPath.value,selectionRenewalPredecessorId.value,`/renewal`):``);const selectionRenewalResource=useEndpointResource({enabled:computed(()=>Boolean(selectionRenewalPredecessorId.value)),fallbackLoadError:`The selected session renewal could not be checked.`,path:selectionRenewalPath,queryKey:computed(()=>[...vibe64SessionQueryKey(`app`,ROUTE_VISIBILITY_PUBLIC,projectSlug.value),selectionRenewalPredecessorId.value,`renewal`]),queryOptions:{refetchOnMount:`always`,refetchOnWindowFocus:false},readMethod:`GET`,realtime:{event:VIBE64_SESSION_CHANGED_EVENT,matches:({payload={}}={})=>mountedSessionRealtimeShouldRefresh({payload},selectionRenewalPredecessorId.value)},requestRecoveryLabel:`Selected session renewal`});const creationOptions=computed(()=>sessionList.pages?.[0]?.creation||{});const selectedSession=computed(()=>enrichVibe64SessionForDisplay(selectedListSession.value));const isSelectedSessionArchived=computed(()=>isArchivedVibe64Session(selectedSession.value||{}));const canCreateSession=computed(()=>{return creationOptions.value.canCreate===true});const createSessionVisible=computed(()=>creationOptions.value.showCreateAction===true);const createSessionTitle=computed(()=>{if(creationOptions.value.disabledReason)return String(creationOptions.value.disabledReason);if(creationOptions.value.canCreate!==true)return`Session creation is unavailable.`;return`Create a new Vibe64 session`});const selectedSessionTitle=computed(()=>{return vibe64SessionDisplayTitle(selectedSession.value||{})||`Session ${shortVibe64SessionId(selectedSessionId.value)}`});async function refreshSessionList(){return refetchEndpointResource(sessionListResource)}let refreshSessionDataInFlight=null;async function refreshSessionData(options={}){const reason=typeof options===`string`?options:String(options?.reason||``);if(refreshSessionDataInFlight){vibe64SessionDebugLog(`client.sessionData.refresh.join`,{reason,selectedSessionId:String(selectedSessionId.value||``)});return refreshSessionDataInFlight}const startedAtMs=Date.now();vibe64SessionDebugLog(`client.sessionData.refresh.start`,{reason,selectedSessionId:String(selectedSessionId.value||``)});refreshSessionDataInFlight=refreshSessionList();try{const result=await refreshSessionDataInFlight;vibe64SessionDebugLog(`client.sessionData.refresh.done`,{durationMs:vibe64SessionDebugDurationMs(startedAtMs),reason,selectedSessionId:String(selectedSessionId.value||``),sessionCount:sessions.value.length});return result}catch(error){vibe64SessionDebugLog(`client.sessionData.refresh.error`,{durationMs:vibe64SessionDebugDurationMs(startedAtMs),error:vibe64SessionDebugError(error),reason,selectedSessionId:String(selectedSessionId.value||``)});throw error}finally{refreshSessionDataInFlight=null}}function refreshSessionDataInBackground(options={}){refreshSessionData(options).catch(()=>{})}function selectSessionId(sessionId=``){const normalizedSessionId=String(sessionId||``).trim();if(sessions.value.some(session=>session.sessionId===normalizedSessionId&&session.archiving))return;vibe64SessionDebugLog(`client.sessionData.selectSession`,{fromSessionId:String(selectedSessionId.value||``),toSessionId:normalizedSessionId});if(normalizedSessionId)emptySessionListObservedForProject=``;sessionSelection.select(normalizedSessionId)}function clearSelectedSession(){emptySessionListObservedForProject=selectionScope.value;sessionSelection.clear()}function selectPreviousSession(sessionId){const navigation=sessions.value;const index=navigation.findIndex(session=>session.sessionId===sessionId);selectSessionId(navigation.slice(0,Math.max(0,index)).filter(session=>!session.archiving).at(-1)?.sessionId||availableSessions.value.at(-1)?.sessionId||``)}const archive=proxyRefs(useVibe64SessionDialogs({beginArchive(sessionId){archiveAttempts.value[sessionId]={startedAt:new Date().toISOString(),session:sessions.value.find(session=>session.sessionId===sessionId)};if(selectedSessionId.value===sessionId)selectPreviousSession(sessionId);return projectSlug.value},finishArchive(sessionId,succeeded,archiveProject){if(projectSlug.value!==archiveProject)return;if(succeeded)archiveAttempts.value[sessionId]={succeeded:true};else{delete archiveAttempts.value[sessionId];if(!selectedSessionId.value)selectSessionId(sessionId)}},isSelectedSessionArchived,refreshSessionData,selectedSessionId,selectedSessionTitle,sessionsApiPath}));const archiveFeedback=useUiFeedback({source:`vibe64.sessions.archive.remote`});const shownArchiveFailures=new Set;watch(projectSlug,()=>{archiveAttempts.value={};agentActivityBySessionId.value={};shownArchiveFailures.clear()});useRealtimeEvent({event:VIBE64_SESSION_CHANGED_EVENT,matches:({payload={}}={})=>vibe64SessionEventMatchesScope(payload,{projectSlug:projectSlug.value}),onEvent:({payload={}}={})=>{const id=String(payload.sessionId||``);if(!id)return;const activity=agentTurnRealtimeOverlayFromPayload(payload,id);if(activity)agentActivityBySessionId.value[id]=latestAgentTurnRealtimeOverlay(agentActivityBySessionId.value[id],{active:activity.active,revision:activity.revision});if(payload.reason===`session-archiving`){const session=sessions.value.find(item=>item.sessionId===id);if(session)archiveAttempts.value[id]={session,startedAt:archiveAttempts.value[id]?.startedAt||new Date().toISOString()};if(selectedSessionId.value===id)selectPreviousSession(id)}else if(payload.reason===`session-archived`)archiveAttempts.value[id]={succeeded:true};else if(payload.reason===`session-archive-failed`){delete archiveAttempts.value[id];if(!selectedSessionId.value)selectSessionId(id)}}});watch(()=>sessionList.items,items=>{for(const id of Object.keys(agentActivityBySessionId.value))if(!items.some(session=>session.sessionId===id))delete agentActivityBySessionId.value[id];for(const[id,attempt]of Object.entries(archiveAttempts.value)){if(attempt.succeeded||archive.archivingSessionId===id)continue;const session=items.find(item=>item.sessionId===id);if(!session||!sessionArchiveState(session).archiving)delete archiveAttempts.value[id]}});watch(sessions,items=>{for(const session of items){const key=`${session.sessionId}:${session.metadata?.session_archive_operation}`;if(!session.archiveError||shownArchiveFailures.has(key))continue;shownArchiveFailures.add(key);if(archive.archivingSessionId!==session.sessionId)archiveFeedback.error(new Error(session.archiveError))}},{immediate:true});let createSessionInFlight=null;async function createSession(assistantSelection={},{pullRequestNumber,repositoryBranch}={}){if(createSessionInFlight)return createSessionInFlight;const startedAtMs=Date.now();const creationProjectSlug=String(projectSlug.value||``).trim();const creationApiPath=sessionsApiPath.value;const creationQueryKey=[...sessionListQueryKey.value];vibe64SessionDebugLog(`client.sessionData.createSession.start`);createSessionRunning.value=true;createSessionInFlight=(async()=>{try{const response=await createSessionCommand.run({assistantSelection,pullRequestNumber,repositoryBranch,apiPath:creationApiPath});if(!sessionDataDisposed&&creationProjectSlug===String(projectSlug.value||``).trim()){if(response?.creation&&response?.limits)queryClient.setQueryData(creationQueryKey,currentPayload=>{if(!currentPayload||typeof currentPayload!==`object`||Array.isArray(currentPayload))return currentPayload;const currentSessions=Array.isArray(currentPayload.sessions)?currentPayload.sessions:[];const createdSession=response.sessionId?Object.fromEntries(Object.entries(response).filter(([key])=>![`creation`,`limits`,`ok`].includes(key))):null;return{...currentPayload,creation:response.creation,limits:response.limits,...createdSession&&!currentSessions.some(item=>item?.sessionId===createdSession.sessionId)?{sessions:[...currentSessions,createdSession]}:{}}});if(response?.sessionId)selectSessionId(response.sessionId);refreshSessionDataInBackground({reason:`create-session`})}vibe64SessionDebugLog(`client.sessionData.createSession.done`,{...vibe64SessionDebugSummary(response||{}),code:String(response?.code||response?.errors?.[0]?.code||``),durationMs:vibe64SessionDebugDurationMs(startedAtMs),ok:response?.ok!==false});return response}catch(error){vibe64SessionDebugLog(`client.sessionData.createSession.error`,{durationMs:vibe64SessionDebugDurationMs(startedAtMs),error:vibe64SessionDebugError(error)});throw error}finally{createSessionRunning.value=false;createSessionInFlight=null}})();return createSessionInFlight}function dropUnlistedRouteSession(){const query=routeQueryWithoutUnlistedSession({route,projectSlug:projectSlug.value,sessions:sessions.value});if(query)router.replace({path:route.path,hash:route.hash,query}).catch(()=>null)}let pendingRenewalNavigation=null;function syncRenewalSuccessorUrl(predecessorId,successorId){if(selectedSessionIdFromRoute(route)!==predecessorId)return;const capturedProject=String(projectSlug.value||``).trim();const capturedApiPath=sessionsApiPath.value;const predecessorUrl=route.fullPath;if(pendingRenewalNavigation?.predecessorUrl===predecessorUrl&&pendingRenewalNavigation?.successorId===successorId)return;const sameRenewal=()=>{const renewal=selectionRenewalResource.data.value?.renewal;return!sessionDataDisposed&&String(projectSlug.value||``).trim()===capturedProject&&sessionsApiPath.value===capturedApiPath&&selectedSessionId.value===successorId&&!selectionRenewalResource.loadError?.value&&!selectionRenewalResource.isInitialLoading?.value&&!selectionRenewalResource.isLoading?.value&&renewal?.status===`completed`&&String(renewal.sessionId||``).trim()===predecessorId&&String(renewal.successor?.sessionId||``).trim()===successorId&&renewedSuccessorSessionId({predecessorSessionId:predecessorId,sessions:availableSessions.value})===successorId};if(!sameRenewal())return;const target={path:route.path,hash:route.hash,query:{...route.query,session:successorId}};const targetUrl=router.resolve(target).fullPath;const navigation={predecessorUrl,successorId};const removeGuard=router.beforeResolve(to=>{if(to.fullPath===targetUrl&&(!sameRenewal()||route.fullPath!==predecessorUrl))return false});pendingRenewalNavigation=navigation;(async()=>{try{await router.replace(target)}catch(error){if(sameRenewal())vibe64SessionDebugLog(`client.sessionData.renewalNavigation.error`,{error:vibe64SessionDebugError(error),sessionId:successorId})}finally{removeGuard();if(pendingRenewalNavigation===navigation)pendingRenewalNavigation=null}})()}const selectionReconciliationState=computed(()=>{const nextSessions=availableSessions.value;return{createSessionRunning:createSessionRunning.value,currentSessionApiPath:currentSessionApiPath.value,selectionScope:selectionScope.value,selectionRenewal:selectionRenewalResource.data.value?.renewal||null,selectionRenewalLoadError:String(selectionRenewalResource.loadError?.value||``),selectionRenewalLoaded:Boolean(selectionRenewalResource.data.value&&typeof selectionRenewalResource.data.value===`object`&&!Array.isArray(selectionRenewalResource.data.value)),selectionRenewalLoading:Boolean(selectionRenewalResource.isInitialLoading?.value||selectionRenewalResource.isLoading?.value),selectionRenewalPredecessorId:selectionRenewalPredecessorId.value,projectSlug:String(projectSlug.value||``).trim(),selectedSessionMissing:selectedSessionMissing.value,nextSessions,selectedSessionId:String(selectedSessionId.value||``),sessionListInitialLoading:sessionList.isInitialLoading,sessionListLoaded:sessionList.pages.length>0,sessionListLoadError:String(sessionList.loadError||``),sessionListLoading:sessionList.isLoading}});watch(selectionReconciliationState,state=>{const nextSessions=state.nextSessions;if(sessions.value.some(session=>session.sessionId===state.selectedSessionId&&session.archiving)){selectPreviousSession(state.selectedSessionId);return}vibe64SessionDebugLog(`client.sessionData.sessions.changed`,{selectedSessionId:String(selectedSessionId.value||``),sessionCount:nextSessions.length});if(state.sessionListInitialLoading||state.sessionListLoadError||shouldPreserveSelectedSessionDuringRefresh({createSessionRunning:state.createSessionRunning,currentSessionId:state.selectedSessionId,nextSessions,sessionListLoading:state.sessionListLoading}))return;if(!state.selectedSessionId&&nextSessions.length===0)emptySessionListObservedForProject=state.selectionScope;if(state.selectionRenewalPredecessorId){if(state.selectionRenewalLoading||state.selectionRenewalLoadError||!state.selectionRenewalLoaded)return;const selectionRenewal=state.selectionRenewal;if(selectionRenewal&&String(selectionRenewal.sessionId||``).trim()===state.selectionRenewalPredecessorId){const renewalStatus=String(selectionRenewal.status||``).trim();if(renewalStatus===`completed`){const renewedSuccessorId=renewedSuccessorSessionId({predecessorSessionId:state.selectionRenewalPredecessorId,sessions:nextSessions});if(state.selectedSessionMissing){if(renewedSuccessorId)sessionSelection.selectAvailableId(nextSessions,{fallbackId:renewedSuccessorId,getId:session=>session.sessionId})}if(renewedSuccessorId&&selectedSessionId.value===renewedSuccessorId)syncRenewalSuccessorUrl(state.selectionRenewalPredecessorId,renewedSuccessorId);if(state.selectedSessionMissing)return}else if(state.selectedSessionMissing&&[`failed`,`running`].includes(renewalStatus))return;if([`failed`,`running`].includes(renewalStatus)){sessionSelection.select(state.selectionRenewalPredecessorId);return}}}if(!state.selectionRenewalPredecessorId)dropUnlistedRouteSession();if(!state.selectedSessionId&&emptySessionListObservedForProject===state.selectionScope)return;sessionSelection.selectAvailableId(nextSessions,{fallbackId:nextSessions.at(-1)?.sessionId||``,getId:session=>session.sessionId})},{immediate:true});watch(selectionReconciliationState,state=>{const publicationSessionId=selectedSessionIdForCurrentAlias({createSessionRunning:state.createSessionRunning,selectedSessionId:state.selectedSessionId,sessionListLoaded:state.sessionListLoaded,sessionListLoadError:state.sessionListLoadError,sessionListLoading:state.sessionListLoading,sessions:state.nextSessions});if(publicationSessionId===null||!state.currentSessionApiPath)return;currentSessionPublisher.request({apiPath:state.currentSessionApiPath,sessionId:publicationSessionId})},{flush:`post`,immediate:true});return{archive,canCreateSession,clearSelectedSession,createSession,createSessionCommand,createSessionRunning,createSessionVisible,createSessionTitle,isSelectedSessionArchived,refreshSessionData,selectSessionId,selectedSession,selectedSessionId,selectedSessionTitle,sessionList,sessions,sessionsApiPath,shortSessionId:shortVibe64SessionId}}export{mountedSessionDetailRefreshReason as a,sessionRecordHasActiveAgentWork as c,sessionWithAgentTurnRealtimeOverlay as d,refetchEndpointResource as f,mountedSessionDetailLoadState as i,agentTurnRealtimeOverlayFromPayload as l,useVibe64SessionData as n,mountedSessionRealtimeShouldRefresh as o,latestSessionDetailRecord as r,mountedSessionRecord as s,sessionListRealtimeShouldRefresh as t,latestAgentTurnRealtimeOverlay as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ht as watch,On as unref,g as computed,vn as ref}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{g as useRoute}from"./useApi-BPuI6ZR9-CFWU1m37.js";import{n as useVibe64ProjectSlug}from"./useVibe64ProjectScope-DXjsKKhl.js";import{f as selectedSessionStorageKey}from"./vibe64SessionRequestConfig-xIx-5jxQ.js";function browserSessionStorage(){if(typeof window===`undefined`||!window.sessionStorage)return null;return window.sessionStorage}function readStoredValue(storageKey=``){try{return String(browserSessionStorage()?.getItem(storageKey)||``)}catch{return``}}function writeStoredValue(storageKey=``,value=``){try{const storage=browserSessionStorage();if(!storage)return;const normalizedValue=String(value||``).trim();if(normalizedValue){storage.setItem(storageKey,normalizedValue);return}storage.removeItem(storageKey)}catch{}}function readStorageKey(storageKey=``){return String(typeof storageKey===`function`?storageKey():unref(storageKey)||``).trim()}function readPreferredId(preferredId=``){return String(typeof preferredId===`function`?preferredId():unref(preferredId)||``).trim()}function useStoredSelection({preferredId=``,storageKey=``,enabled=true}={}){const selectionEnabled=computed(()=>Boolean(typeof enabled===`function`?enabled():unref(enabled)));const activeStorageKey=computed(()=>readStorageKey(storageKey));const activePreferredId=computed(()=>readPreferredId(preferredId));const selectedId=ref(selectionEnabled.value?activePreferredId.value||readStoredValue(activeStorageKey.value):``);function select(id=``){if(!selectionEnabled.value)return;selectedId.value=String(id||``).trim();writeStoredValue(activeStorageKey.value,selectedId.value)}function clear(){select(``)}function selectAvailableId(items=[],{fallbackId=``,getId=item=>item?.id}={}){if(!selectionEnabled.value)return``;if(items.length===0){clear();return``}const itemIds=items.map(item=>String(getId(item)||``).trim()).filter(Boolean);if(itemIds.includes(selectedId.value)){select(selectedId.value);return selectedId.value}const preferredSelectionId=activePreferredId.value;if(itemIds.includes(preferredSelectionId)){select(preferredSelectionId);return selectedId.value}const rememberedId=readStoredValue(activeStorageKey.value);select(itemIds.includes(rememberedId)?rememberedId:String(fallbackId||``).trim());return selectedId.value}function capture(){const key=activeStorageKey.value;const admitted=selectionEnabled.value;return Object.freeze({select(id=``){if(!admitted)return;const value=String(id||``).trim();writeStoredValue(key,value);if(selectionEnabled.value&&activeStorageKey.value===key)selectedId.value=value}})}watch(selectionEnabled,nextEnabled=>{selectedId.value=nextEnabled?activePreferredId.value||readStoredValue(activeStorageKey.value):``},{flush:`sync`});watch(activeStorageKey,nextStorageKey=>{if(selectionEnabled.value)selectedId.value=activePreferredId.value||readStoredValue(nextStorageKey)});watch(activePreferredId,nextPreferredId=>{if(selectionEnabled.value&&nextPreferredId)selectedId.value=nextPreferredId});return{capture,clear,select,selectAvailableId,selectedId}}function selectedSessionIdFromRoute(route={}){const rawValue=route?.query?.session;const value=Array.isArray(rawValue)?rawValue[0]:rawValue;return String(value||``).trim()}function useVibe64SessionSelection({projectSlug=useVibe64ProjectSlug(),route=useRoute()}={}){return useStoredSelection({preferredId:computed(()=>selectedSessionIdFromRoute(route)),storageKey:computed(()=>selectedSessionStorageKey(unref(projectSlug)))})}export{useVibe64SessionSelection as n,selectedSessionIdFromRoute as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ht as watch,On as unref,g as computed,pn as onScopeDispose,vn as ref}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{t as useEndpointResource}from"./useEndpointResource-
|
|
1
|
+
import{Ht as watch,On as unref,g as computed,pn as onScopeDispose,vn as ref}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{t as useEndpointResource}from"./useEndpointResource-7-YDfAxX.js";import{n as useRealtimeEvent}from"./useRealtimeEvent-BNXVwzFG.js";import{t as usePaths}from"./usePaths-Y6UuQxmI.js";import{n as useVibe64ProjectSlug}from"./useVibe64ProjectScope-DXjsKKhl.js";var SYSTEM_GRAPH_API_SUFFIX=`/vibe64/system-graph`;var SYSTEM_GRAPH_SURFACE=`app`;function encodeSegment(value=``){return encodeURIComponent(String(value||``).trim())}function systemSessionPath(apiPath=``,sessionId=``,suffix=``){return`${apiPath}/sessions/${encodeSegment(sessionId)}${suffix}`}function systemQueryKey(projectSlug,sessionId=``,resource=``){return[`vibe64`,`system-graph`,projectSlug,String(sessionId||``),resource]}function cityAvailable(status={},kind=``){return status?.cities?.[kind]?.available===true}function useVibe64SystemGraph({active=true,reloadVersion=0,sessionId=``}={}){const paths=usePaths();const projectSlug=useVibe64ProjectSlug();const normalizedSessionId=computed(()=>String(unref(sessionId)||``).trim());const enabled=computed(()=>Boolean(unref(active)&&normalizedSessionId.value));const apiPath=computed(()=>paths.api(SYSTEM_GRAPH_API_SUFFIX,{surface:SYSTEM_GRAPH_SURFACE}));const sessionPath=computed(()=>systemSessionPath(apiPath.value,normalizedSessionId.value));const statusResource=useEndpointResource({enabled,fallbackLoadError:`Architecture index status could not be loaded.`,path:computed(()=>`${sessionPath.value}/status`),queryKey:computed(()=>systemQueryKey(projectSlug.value,normalizedSessionId.value,`status`)),queryOptions:{refetchOnWindowFocus:false,retry:false},requestRecoveryLabel:`Architecture index status`});const systemStatus=computed(()=>statusResource.data.value||{});const architectureEnabled=computed(()=>enabled.value&&cityAvailable(systemStatus.value,`machine`));const architectureResource=useEndpointResource({enabled:architectureEnabled,fallbackLoadError:`Architecture could not be loaded.`,path:computed(()=>`${sessionPath.value}/architecture`),queryKey:computed(()=>systemQueryKey(projectSlug.value,normalizedSessionId.value,`architecture`)),queryOptions:{refetchOnWindowFocus:false,retry:false},requestRecoveryLabel:`Architecture`});const refreshResource=useEndpointResource({enabled:false,fallbackSaveError:`Architecture analysis could not be refreshed.`,path:computed(()=>`${sessionPath.value}/refresh`),queryKey:computed(()=>systemQueryKey(projectSlug.value,normalizedSessionId.value,`refresh`)),requestRecoveryLabel:`Refresh architecture analysis`,writeMethod:`POST`});const cancelResource=useEndpointResource({enabled:false,path:computed(()=>`${sessionPath.value}/refresh/cancel`),queryKey:computed(()=>systemQueryKey(projectSlug.value,normalizedSessionId.value,`refresh-cancel`)),writeMethod:`POST`,fallbackSaveError:`Architecture cancellation could not be confirmed.`});const refreshStatusResource=useEndpointResource({enabled,path:computed(()=>`${sessionPath.value}/refresh/status`),queryKey:computed(()=>systemQueryKey(projectSlug.value,normalizedSessionId.value,`refresh-status`)),queryOptions:{refetchOnMount:`always`,refetchOnWindowFocus:false,retry:false},realtime:{event:`vibe64.session.changed`,matches:({payload={}}={})=>payload.projectSlug===projectSlug.value&&payload.sessionId===normalizedSessionId.value&&payload.reason===`architecture-refresh`},fallbackLoadError:`Analysis progress is unavailable.`});const localRefreshOutput=ref(``);const scan=computed(()=>refreshStatusResource.data.value?.refresh||null);const refreshing=computed(()=>scan.value?.status===`running`||refreshResource.isSaving.value);const clock=ref(Date.now());let timer;watch(()=>enabled.value&&refreshing.value,running=>{clearInterval(timer);clock.value=Date.now();if(running)timer=setInterval(()=>{clock.value=Date.now()},1e3)},{immediate:true});onScopeDispose(()=>clearInterval(timer));useRealtimeEvent({enabled,event:`connect`,onEvent:()=>reload()});watch(()=>`${scan.value?.id}:${scan.value?.startedAt}:${scan.value?.status}`,()=>{const status=scan.value?.status;if(status===`running`&&!refreshResource.isSaving.value){refreshResource.mutation.reset();cancelResource.mutation.reset();localRefreshOutput.value=``}if(enabled.value&&status&&status!==`running`)reload()});const loading=computed(()=>Boolean(architectureResource.isLoading.value||statusResource.isLoading.value));const error=computed(()=>cancelResource.saveError.value||(scan.value?.status===`failed`?scan.value.message:``)||(scan.value?.status!==`running`?refreshResource.saveError.value:``)||architectureResource.loadError.value||statusResource.loadError.value||``);async function reload(){if(!enabled.value)return;await Promise.all([refreshStatusResource.reload(),statusResource.reload()]);if(architectureEnabled.value)await architectureResource.reload()}watch([enabled,sessionPath,projectSlug],([isEnabled])=>{if(isEnabled)refreshStatusResource.reload()},{immediate:true});let lastReloadVersion=0;watch([enabled,()=>unref(reloadVersion)],([isEnabled,version])=>{if(isEnabled&&version!==lastReloadVersion){lastReloadVersion=version;reload()}},{immediate:true});async function refresh(){if(refreshing.value)return null;localRefreshOutput.value=``;try{const result=await refreshResource.save({},{method:`POST`,options:{timeoutMs:6e5}});await reload();return result}catch(error){localRefreshOutput.value=String(error?.details?.commandOutput||``);await refreshStatusResource.reload();if(!refreshResource.saveError.value)throw error;return null}}return{architecture:computed(()=>architectureResource.data.value?.architecture||null),cancelRefresh:()=>cancelResource.save({},{method:`POST`}),error,loading,refresh,refreshing,refreshProgress:computed(()=>{if(!refreshing.value)return null;const progress=scan.value;const elapsedSeconds=progress?.status===`running`?Math.max(0,Math.floor((clock.value-progress.startedAt)/1e3)):0;return{message:refreshStatusResource.loadError.value?`Analysis continues; progress unavailable.`:progress?.status===`running`?progress.message:`Starting project analysis…`,elapsedSeconds}}),refreshOutput:computed(()=>scan.value?.commandOutput||localRefreshOutput.value),reload,systemStatus}}export{useVibe64SystemGraph as t};
|