@protobase/ui 0.113.0 → 0.114.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/messages.d.ts +2 -2
- package/dist/app/app.d.ts +4 -1
- package/dist/app/app.js +9 -7
- package/dist/app/change-confirm/messages.d.ts +2 -2
- package/dist/app/charts/messages.d.ts +2 -2
- package/dist/app/confirm-sign-in-messages.d.ts +2 -2
- package/dist/app/create/messages.d.ts +2 -2
- package/dist/app/delete/messages.d.ts +2 -2
- package/dist/app/displays/messages.d.ts +2 -2
- package/dist/app/displays/virtual-cards.js +1 -0
- package/dist/app/embedded-list/messages.d.ts +2 -2
- package/dist/app/export/messages.d.ts +2 -2
- package/dist/app/field-messages.d.ts +2 -2
- package/dist/app/field-types/workflow/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-page/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-run/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-status/messages.d.ts +2 -2
- package/dist/app/file-viewers/messages.d.ts +2 -2
- package/dist/app/first-frame.d.ts +13 -0
- package/dist/app/first-frame.js +23 -0
- package/dist/app/focus/messages.d.ts +2 -2
- package/dist/app/gallery/gallery-layout.d.ts +2 -2
- package/dist/app/gallery/messages.d.ts +2 -2
- package/dist/app/hand-order/messages.d.ts +2 -2
- package/dist/app/import/messages.d.ts +2 -2
- package/dist/app/index.html +0 -17
- package/dist/app/list-messages.d.ts +2 -2
- package/dist/app/main.js +19 -7
- package/dist/app/messages.d.ts +2 -2
- package/dist/app/pages/messages.d.ts +2 -2
- package/dist/app/record-chart/messages.d.ts +2 -2
- package/dist/app/record-messages.d.ts +2 -2
- package/dist/app/record-mode/shown-layout.d.ts +1 -1
- package/dist/app/record-row/messages.d.ts +2 -2
- package/dist/app/record-row/record-row.d.ts +3 -2
- package/dist/app/record-row/record-row.js +43 -27
- package/dist/app/record-row/row-window.d.ts +11 -0
- package/dist/app/record-row/row-window.js +15 -2
- package/dist/app/refresh-mark.d.ts +2 -1
- package/dist/app/refresh-mark.js +3 -1
- package/dist/app/related-cards/messages.d.ts +2 -2
- package/dist/app/reveal-when-loaded.d.ts +8 -2
- package/dist/app/reveal-when-loaded.js +12 -5
- package/dist/app/runtime/messages.d.ts +2 -2
- package/dist/app/saved/messages.d.ts +2 -2
- package/dist/app/searches/messages.d.ts +2 -2
- package/dist/app/splash-hold.d.ts +0 -1
- package/dist/app/splash-hold.js +1 -1
- package/dist/app/start-screen.d.ts +0 -9
- package/dist/app/start-screen.js +1 -10
- package/dist/app/ui-ready.d.ts +11 -0
- package/dist/app/ui-ready.js +12 -0
- package/dist/app-shell/app-shell.js +3 -1
- package/dist/app-shell/close-sidebar.d.ts +10 -0
- package/dist/app-shell/close-sidebar.js +17 -0
- package/dist/app-shell/drawer.d.ts +7 -1
- package/dist/app-shell/drawer.js +26 -7
- package/dist/app-shell/index.d.ts +2 -1
- package/dist/app-shell/index.js +2 -1
- package/dist/app-shell/messages.d.ts +2 -2
- package/dist/app-shell/top-bar.js +4 -4
- package/dist/assistant-dock/messages.d.ts +2 -2
- package/dist/auth/messages.d.ts +2 -2
- package/dist/calls/messages.d.ts +2 -2
- package/dist/compact-table/messages.d.ts +2 -2
- package/dist/data/query-keys.d.ts +6 -0
- package/dist/data/query-keys.js +10 -0
- package/dist/data/start-cache/cached-plugins.d.ts +6 -0
- package/dist/data/start-cache/cached-plugins.js +10 -0
- package/dist/data-grid/column-spec.d.ts +1 -1
- package/dist/data-grid/data-grid.js +1 -0
- package/dist/data-grid/messages.d.ts +2 -2
- package/dist/data-grid/row-source.d.ts +5 -0
- package/dist/data-grid/use-paged-rows.d.ts +5 -3
- package/dist/data-grid/use-paged-rows.js +21 -6
- package/dist/filter-panel/messages.d.ts +2 -2
- package/dist/focus-page/messages.d.ts +2 -2
- package/dist/index.d.ts +4 -1
- package/dist/index.js +4 -1
- package/dist/invitations/messages.d.ts +2 -2
- package/dist/live/grid-loader.d.ts +1 -0
- package/dist/live/grid-loader.js +3 -1
- package/dist/live/use-live-rows.js +1 -0
- package/dist/mailbox/messages.d.ts +2 -2
- package/dist/mocks/customers.d.ts +1 -1
- package/dist/mocks/invoices.d.ts +1 -1
- package/dist/mocks/orders.d.ts +3 -3
- package/dist/notifications/bell/messages.d.ts +2 -2
- package/dist/organizations/members-page.js +13 -7
- package/dist/organizations/messages.d.ts +2 -2
- package/dist/organizations/use-organizations.d.ts +4 -1
- package/dist/organizations/use-organizations.js +25 -19
- package/dist/package.js +1 -1
- package/dist/plugins/plugin-source.d.ts +24 -4
- package/dist/plugins/plugin-source.js +48 -14
- package/dist/plugins/use-plugin-loads.d.ts +3 -1
- package/dist/plugins/use-plugin-loads.js +24 -7
- package/dist/primitives/messages.d.ts +2 -2
- package/dist/primitives/skeleton.js +1 -0
- package/dist/record-view/messages.d.ts +2 -2
- package/dist/roles/use-active-role.d.ts +4 -1
- package/dist/roles/use-active-role.js +18 -13
- package/dist/shell/assets/api-provider-BJJrOoO4.js +2 -0
- package/dist/shell/assets/app-VoTi41IN.js +16 -0
- package/dist/shell/assets/badge-OU9hb6yQ.js +2 -0
- package/dist/shell/assets/checkbox-DFfK432Y.js +2 -0
- package/dist/shell/assets/createLucideIcon-DGm8SdFI.js +2 -0
- package/dist/shell/assets/display-value-CIH2qfgQ.js +2 -0
- package/dist/shell/assets/{field-badge-3QmjR1r3.js → field-badge-DX2Mc_fH.js} +2 -2
- package/dist/shell/assets/{graph-view-BcbWbnHO.js → graph-view-CY9LPr0B.js} +2 -2
- package/dist/shell/assets/{html-viewer-tGtSpy9M.js → html-viewer-BPGMH_GA.js} +2 -2
- package/dist/shell/assets/{in-place-form-B0EkP4B1.js → in-place-form-RWSQGEg4.js} +2 -2
- package/dist/shell/assets/index-Bzb-O7ER.js +2 -0
- package/dist/shell/assets/index-HnFovy2Q.css +2 -0
- package/dist/shell/assets/{intl-cache-bXVNV0Yq.js → intl-cache-D4doUjK1.js} +2 -2
- package/dist/shell/assets/{lib-d3-interpolate-Cl0dHO4f.js → lib-d3-interpolate-D3u38iyJ.js} +2 -2
- package/dist/shell/assets/{lib-d3-transition-DUHAGQ8z.js → lib-d3-transition-BUpPvFvt.js} +2 -2
- package/dist/shell/assets/{lib-d3-zoom-gQh2osrj.js → lib-d3-zoom-BF7SPKNh.js} +2 -2
- package/dist/shell/assets/{lib-vis.gl-react-maplibre-CU7gWYjg.js → lib-vis.gl-react-maplibre-C7-0xNFC.js} +2 -2
- package/dist/shell/assets/{lib-xyflow-react-DGg_5r7u.js → lib-xyflow-react-CKyW7szC.js} +2 -2
- package/dist/shell/assets/maplibre-9ViQO48S.js +2 -0
- package/dist/shell/assets/{markdown-content-DHKbAJjx.js → markdown-content-DTB9RQDs.js} +2 -2
- package/dist/shell/assets/{record-map-nGRmsk6x.js → record-map-CVqCWtfe.js} +2 -2
- package/dist/shell/assets/{records-map-D2flyaz3.js → records-map-ClYSxrVR.js} +2 -2
- package/dist/shell/assets/{run-trace-view-DfrAPeum.js → run-trace-view-CN16MiXg.js} +2 -2
- package/dist/shell/assets/search-picker-BGpvJQRD.js +2 -0
- package/dist/shell/assets/shared-protobase-ui-BC8LqGQB.js +2 -0
- package/dist/shell/assets/step-catalog-CZY0ZpCC.js +2 -0
- package/dist/shell/assets/step-panel-DhD80lsJ.js +2 -0
- package/dist/shell/assets/use-app-address-B4Uk3nWy.js +2 -0
- package/dist/shell/assets/{use-meta-BqEqOLNe.js → use-meta-D5kYywHm.js} +2 -2
- package/dist/shell/assets/{use-sibling-page-CiuiG-Tz.js → use-sibling-page-BJ81HcOP.js} +3 -3
- package/dist/shell/assets/value-badge-Dpd8dRqq.js +2 -0
- package/dist/shell/assets/{vendor-WWp_xlp2.js → vendor-3etemhgS.js} +4 -4
- package/dist/shell/assets/{workflow-canvas-DMP7SDWX.js → workflow-canvas-C1nGpi5w.js} +2 -2
- package/dist/shell/assets/{workflow-graph-editor-xpV8_qEl.js → workflow-graph-editor-DAJa4lq6.js} +2 -2
- package/dist/shell/assets/workflow-workbench-HramVZEJ.js +4 -0
- package/dist/shell/assets/{workflows-Bku4o2su.js → workflows-DlvOln9v.js} +2 -2
- package/dist/shell/assets/{workflows-start-kl7rSSay.js → workflows-start-QUKfwFqf.js} +2 -2
- package/dist/shell/index.html +16 -19
- package/dist/shell/protobase.shell.json +2 -2
- package/dist/shell/protobase.sw.js +2 -2
- package/dist/shell-source-maps/assets/api-provider-BJJrOoO4.js.map +1 -0
- package/dist/shell-source-maps/assets/app-VoTi41IN.js.map +1 -0
- package/dist/shell-source-maps/assets/{badge-ChHXC28D.js.map → badge-OU9hb6yQ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{checkbox-COOOlJPG.js.map → checkbox-DFfK432Y.js.map} +1 -1
- package/dist/shell-source-maps/assets/createLucideIcon-DGm8SdFI.js.map +1 -0
- package/dist/shell-source-maps/assets/display-value-CIH2qfgQ.js.map +1 -0
- package/dist/shell-source-maps/assets/{field-badge-3QmjR1r3.js.map → field-badge-DX2Mc_fH.js.map} +1 -1
- package/dist/shell-source-maps/assets/{graph-view-BcbWbnHO.js.map → graph-view-CY9LPr0B.js.map} +1 -1
- package/dist/shell-source-maps/assets/{html-viewer-tGtSpy9M.js.map → html-viewer-BPGMH_GA.js.map} +1 -1
- package/dist/shell-source-maps/assets/{in-place-form-B0EkP4B1.js.map → in-place-form-RWSQGEg4.js.map} +1 -1
- package/dist/shell-source-maps/assets/index-Bzb-O7ER.js.map +1 -0
- package/dist/shell-source-maps/assets/{intl-cache-bXVNV0Yq.js.map → intl-cache-D4doUjK1.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-d3-interpolate-Cl0dHO4f.js.map → lib-d3-interpolate-D3u38iyJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-d3-transition-DUHAGQ8z.js.map → lib-d3-transition-BUpPvFvt.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-d3-zoom-gQh2osrj.js.map → lib-d3-zoom-BF7SPKNh.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-vis.gl-react-maplibre-CU7gWYjg.js.map → lib-vis.gl-react-maplibre-C7-0xNFC.js.map} +1 -1
- package/dist/shell-source-maps/assets/{lib-xyflow-react-DGg_5r7u.js.map → lib-xyflow-react-CKyW7szC.js.map} +1 -1
- package/dist/shell-source-maps/assets/{maplibre-Y7X50Jfk.js.map → maplibre-9ViQO48S.js.map} +1 -1
- package/dist/shell-source-maps/assets/{markdown-content-DHKbAJjx.js.map → markdown-content-DTB9RQDs.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-map-nGRmsk6x.js.map → record-map-CVqCWtfe.js.map} +1 -1
- package/dist/shell-source-maps/assets/{records-map-D2flyaz3.js.map → records-map-ClYSxrVR.js.map} +1 -1
- package/dist/shell-source-maps/assets/{run-trace-view-DfrAPeum.js.map → run-trace-view-CN16MiXg.js.map} +1 -1
- package/dist/shell-source-maps/assets/{search-picker-CJcJetBh.js.map → search-picker-BGpvJQRD.js.map} +1 -1
- package/dist/shell-source-maps/assets/shared-protobase-ui-BC8LqGQB.js.map +1 -0
- package/dist/shell-source-maps/assets/{step-catalog-ZvQOXfSh.js.map → step-catalog-CZY0ZpCC.js.map} +1 -1
- package/dist/shell-source-maps/assets/{step-panel-B1yHz7OC.js.map → step-panel-DhD80lsJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-app-address-B6k3dkV0.js.map → use-app-address-B4Uk3nWy.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-meta-BqEqOLNe.js.map → use-meta-D5kYywHm.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-sibling-page-CiuiG-Tz.js.map → use-sibling-page-BJ81HcOP.js.map} +1 -1
- package/dist/shell-source-maps/assets/{value-badge-BKLV4otJ.js.map → value-badge-Dpd8dRqq.js.map} +1 -1
- package/dist/shell-source-maps/assets/{vendor-WWp_xlp2.js.map → vendor-3etemhgS.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-canvas-DMP7SDWX.js.map → workflow-canvas-C1nGpi5w.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-graph-editor-xpV8_qEl.js.map → workflow-graph-editor-DAJa4lq6.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-workbench-Djdd_ODh.js.map → workflow-workbench-HramVZEJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflows-Bku4o2su.js.map → workflows-DlvOln9v.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflows-start-kl7rSSay.js.map → workflows-start-QUKfwFqf.js.map} +1 -1
- package/dist/status/messages.d.ts +2 -2
- package/dist/styles.css +14 -0
- package/dist/users/messages.d.ts +2 -2
- package/package.json +5 -5
- package/dist/app/hold-start-for-first-loads.d.ts +0 -12
- package/dist/app/hold-start-for-first-loads.js +0 -43
- package/dist/shell/assets/api-provider-CcDtTh0D.js +0 -2
- package/dist/shell/assets/app-DG30qs8Q.js +0 -16
- package/dist/shell/assets/badge-ChHXC28D.js +0 -2
- package/dist/shell/assets/checkbox-COOOlJPG.js +0 -2
- package/dist/shell/assets/display-value-fDiKbfJO.js +0 -2
- package/dist/shell/assets/index-BkCaPeOq.css +0 -2
- package/dist/shell/assets/index-CZ013UoE.js +0 -2
- package/dist/shell/assets/maplibre-Y7X50Jfk.js +0 -2
- package/dist/shell/assets/messages-ClKBpZlk.js +0 -2
- package/dist/shell/assets/search-picker-CJcJetBh.js +0 -2
- package/dist/shell/assets/shared-protobase-ui-CVwqj5Cp.js +0 -2
- package/dist/shell/assets/step-catalog-ZvQOXfSh.js +0 -2
- package/dist/shell/assets/step-panel-B1yHz7OC.js +0 -2
- package/dist/shell/assets/use-app-address-B6k3dkV0.js +0 -2
- package/dist/shell/assets/value-badge-BKLV4otJ.js +0 -2
- package/dist/shell/assets/workflow-workbench-Djdd_ODh.js +0 -4
- package/dist/shell-source-maps/assets/api-provider-CcDtTh0D.js.map +0 -1
- package/dist/shell-source-maps/assets/app-DG30qs8Q.js.map +0 -1
- package/dist/shell-source-maps/assets/display-value-fDiKbfJO.js.map +0 -1
- package/dist/shell-source-maps/assets/index-CZ013UoE.js.map +0 -1
- package/dist/shell-source-maps/assets/messages-ClKBpZlk.js.map +0 -1
- package/dist/shell-source-maps/assets/shared-protobase-ui-CVwqj5Cp.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"api-provider-CcDtTh0D.js","names":["text","print","Loader2","backoff","pause","createContext","useContext","createContext","useContext","useCallback","useSyncExternalStore","createContext","useContext","useCallback","useState","useRef","useMemo","n","a","t","__toESM","require_react","require_jsx_runtime","QueryClient","focusManager","printFilter$1","QueryClientProvider","createParser","useQueryClient","messages","createLucideIcon","guestCallsPath","cn","functions","parseOptions","libraryType","field","schemaOf","model","member","call","text$1","relatedPage","orderBy","limit","order","span","count","pageToken","value","node","now","lift","next","child","options","literal","printFilter","ast","workflowTypesPath","systemPath","runnerRegistrationPath","runner","workflowRunsPath","workflowTraceAfterParam","workflowTraceRevisionParam","workflowRunTracePath","path","runId","held","encodeKey","key","parts","part","ignoreAbort","error","readEventStream","parser","onData","event","decoder","reader","body","signal","done","bridgeTokenParam","bridgeSocketPath","functionPath","token","devicesPath","id","appReadValue","filesPath","filePath","files","provider","storedFileRef","match","uri","appReadUrl","url","historyIdPattern","historyPath","base","statusPath","controlCharacter","statusTextProblem","text","heldStatus","status","ringNotice","declineWord","ringsPath","callsChannelEvent","__iconData","LoaderCircle","import_jsx_runtime","Spinner","hidden","className","variants","sizes","buttonClass","variant","size","Button","rest","disabled","loading","children","filterText","filter","labelEntries","entries","labels","relation","photosWire","photos","listWire","params","queryString","search","name","wire","isPath","isFileAtPath","originOf","baseUrl","fromOrigin","file","origin","withFileOrigin","record","photosWithOrigin","ApiError","problem","entry","PreconditionFailedError","isApiError","isProblem","readProblem","response","systemUrlOf","createTransport","systemUrl","doFetch","input","init","attempt","via","system","query","headers","raw","cache","metaVersion","accept","canonical","api","fileReadUrl","ref","link","headersOf","colon","line","fetchWithProgress","request","onProgress","empty","resolve","reject","backoff$1","pause$1","timer","ms","followLive","controller","cursor","failures","onEvent","handlers","follow","send","data","reason","retryDelay","sharedLive","subscribers","stop","each","subscriber","one","changes","encoder","lengthBytes","encodeBinaryFrame","head","header","bytes","frame","decodeBinaryFrame","end","isBytes","payload","ChannelRefusal","message","code","pingMs","openState","protocol","channelConnection","open","socket","wanted","lastRef","sentToken","heardAt","ping","retry","pending","dropPending","handover","fresh","current","connect","offered","onOpen","onMessage","waiting","onDown","sendNow","unlessDropped","notJoined","channelsClient","joined","byName","setStatus","listener","channel","tellPresence","change","forget","connection","join","reply","hear","server","release","handleOf","left","own","listen","set","off","joinedName","self","ack","listeners","encoded","resource","existing","bridgesClient","opened","socketUrl","expires_at","devicesClient","device","statusClient","workflowRunTraceClient","workflowTypesClient","runnerRegistrationClient","notificationHistoryClient","backoff","pause","recordCallsClient","ringsClient","callGuestsClient","longestListQuery","nameOf","systemSocketUrl","keyPath","callsPath","toPage","item","commentOf","comment","created_at","etagOf","storedOf","permissions","batchResultOf","result","createClient","list","get","create","update","patch","etag","remove","undelete","reveal","generate","history","pageSize","database_role","comments","mentionable","batchWrite","keyText","wireOps","ops","operation","facets","o","aggregate","series","histogram","map","seek","meta","invoke","method","type","upload","progress","formPath","form","formChallenge","submitForm","live","openSocket","protocols","bridges","devices","notifications","workflowTypes","workflowRunTrace","runnerRegistration","import_react","createFocusRefresh","paused","released","FocusRefreshContext","usePauseFocusRefresh","refresh","listenToWindowFocus","onFocus","keys","resources","startToken","page","range","granularity","buckets","position","zoom","fields","ids","read","userId","readsResource","ClientStartContext","isRestored","state","startedAt","restoredState","restored","queries","keepCachedOnFailure","client","useRestoredState","subscribe","changed","ApiContext","SourceClientsContext","ResourceClientContext","useClient","useResourceClient","useResourceClients","resourceClient","useSourceClients","clientOf","ClientProvider","ApiProvider","given","givenQueryClient","focusRefresh","queryClient","persistence","previous","version","fetch","onUnauthenticated","sourceClient","made","ready","sources","source","seen"],"sources":["../../../../schema/src/filter/profile.ts","../../../../schema/src/filter/lift.ts","../../../../schema/src/filter/print.ts","../../../../schema/src/workflows/workflow-types-path.ts","../../../../schema/src/workflows/runner-registration-path.ts","../../../../schema/src/workflows/workflow-trace-path.ts","../../../../schema/src/keys.ts","../../../../schema/src/assistant/event-stream.ts","../../../../schema/src/bridge-address.ts","../../../../schema/src/devices-path.ts","../../../../schema/src/files/app-read.ts","../../../../schema/src/history-path.ts","../../../../schema/src/status.ts","../../../../schema/src/calls/call-rings.ts","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/loader-circle.mjs","../../../src/primitives/messages.ts","../../../src/primitives/spinner.tsx","../../../src/primitives/button.tsx","../../../../client/src/query-string.ts","../../../../client/src/file-urls.ts","../../../../client/src/problem.ts","../../../../client/src/transport.ts","../../../../client/src/file-read-url.ts","../../../../client/src/upload-request.ts","../../../../client/src/live.ts","../../../../client/src/shared-live.ts","../../../../client/src/channel-binary-frame.ts","../../../../client/src/channel-types.ts","../../../../client/src/channel-connection.ts","../../../../client/src/channels.ts","../../../../client/src/bridges.ts","../../../../client/src/devices.ts","../../../../client/src/status.ts","../../../../client/src/workflow-trace.ts","../../../../client/src/workflow-types.ts","../../../../client/src/runner-registration.ts","../../../../client/src/notification-history.ts","../../../../client/src/record-calls.ts","../../../../client/src/rings.ts","../../../../client/src/call-guests.ts","../../../../client/src/client.ts","../../../src/data/focus-refresh.ts","../../../src/data/query-keys.ts","../../../src/data/start-cache/restored-state.ts","../../../src/data/api-provider.tsx"],"sourcesContent":["import type { FunctionSpec, Schema, ValueType } from 'aip-parsers/filter'\nimport type { FieldModel, ResourceModel } from '../model'\n\n/** Protobase's filter functions, declared through the library's registry. */\nexport const functions: Record<string, FunctionSpec> = {\n in: { params: [{ name: 'field', type: 'field' }], rest: { name: 'value', type: 'any' } },\n search: { params: [{ name: 'text', type: 'string' }] },\n similar: { params: [{ name: 'field', type: 'field', of: ['string'] }, { name: 'text', type: 'string' }] },\n regex: { params: [{ name: 'field', type: 'field', of: ['string'] }, { name: 'pattern', type: 'string' }] },\n isNull: { params: [{ name: 'field', type: 'field' }] },\n // Named here for the list of functions an unknown one's hint gives: only a list-style read of the API resolves it.\n related: { params: [{ name: 'field', type: 'field' }, { name: 'key', type: 'field' }], rest: { name: 'filter', type: 'any' } },\n now: { params: [], returns: 'timestamp' },\n}\n\nexport const parseOptions = { extensions: { arithmetic: 'now-offset' as const, durationUnits: true } }\n\n// Types whose value formats the library has no notion of (decimal, uuid, ...) map to `any`;\n// checkAgainstModel validates them.\nexport const libraryType = (field: FieldModel): ValueType => {\n switch (field.type) {\n case 'text':\n return 'string'\n case 'integer':\n case 'bigint':\n return 'integer'\n case 'boolean':\n case 'timestamp':\n case 'enum':\n return field.type\n default:\n return 'any'\n }\n}\n\nexport const schemaOf = (model: ResourceModel): Schema => ({\n fields: Object.fromEntries(\n Object.values(model.fields).map((field) => [\n field.name,\n {\n type: libraryType(field),\n filterable: field.filterable,\n sortable: field.sortable,\n aliases: field.aliases,\n ...(field.enumValues && { values: field.enumValues }),\n },\n ]),\n ),\n functions,\n})\n","import type { Expr as Generic, Operand } from 'aip-parsers/filter'\nimport type { CheckedFilter, FieldModel, FieldPath, FilterExpr, FilterOf, FilterValue, Literal, RelatedFilter } from '../model'\nimport { libraryType } from './profile'\n\ntype Field = FieldPath | FieldModel\ntype Node = FilterOf<Field, RelatedFilter>\n\n// Checked fields carry their type, so the evaluator converts quoted values by it.\nconst member = (field: Field, span: Node['span']): Operand =>\n 'path' in field\n ? { kind: 'member', path: field.path, span: field.span }\n : { kind: 'member', path: [field.name], field: { name: field.name, spec: { type: libraryType(field) } }, span }\n\nconst call = (name: string, args: Operand[], span: Node['span']): Generic => ({ kind: 'call', name, args, span })\n\nconst text = (value: string, span: Node['span']): Operand => ({ kind: 'string', value, span })\n\n// The parent page's arguments, each written only with the ones before it, as `related()` reads them\nconst relatedPage = ({ orderBy, limit, pageToken, span }: RelatedFilter): Operand[] => {\n if (orderBy === undefined && limit === undefined) return []\n const order = text(orderBy ?? '', span)\n if (limit === undefined) return [order]\n const count: Operand = { kind: 'number', value: limit, raw: String(limit), span }\n return pageToken === undefined ? [order, count] : [order, count, text(pageToken, span)]\n}\n\nconst value = (node: FilterValue): Operand => {\n if (node.kind !== 'now') return node\n const now: Operand = { kind: 'call', name: 'now', args: [], span: node.span }\n if (!node.offset) return now\n return { kind: 'binary', op: node.offset.sign, left: now, right: node.offset.duration, span: node.span }\n}\n\nexport type LiftOptions = {\n /** Rewrite `in` and `isNull` into plain comparisons and presence, for evaluation. */\n expand?: boolean\n}\n\n/** Protobase's filter shape as a generic AIP-160 expression, for checking, printing and evaluating. */\nexport const lift = (node: Node, options: LiftOptions = {}): Generic => {\n const next = (child: Node) => lift(child, options)\n switch (node.kind) {\n case 'and':\n case 'or':\n return { kind: node.kind, args: node.args.map(next), span: node.span }\n case 'not':\n return { kind: 'not', arg: next(node.arg), span: node.span }\n case 'compare':\n return { kind: 'compare', op: node.op, left: member(node.field, node.span), right: value(node.value), span: node.span }\n case 'has':\n return { kind: 'has', left: member(node.field, node.span), right: node.value, span: node.span }\n case 'present':\n return { kind: 'present', left: member(node.field, node.span), span: node.span }\n case 'in':\n if (options.expand) {\n const args = node.values.map((literal): Generic => ({ kind: 'compare', op: '=', left: member(node.field, node.span), right: literal, span: node.span }))\n return { kind: 'or', args, span: node.span }\n }\n return call('in', [member(node.field, node.span), ...node.values], node.span)\n case 'search':\n return call('search', [text(node.text, node.span)], node.span)\n case 'similar':\n return call('similar', [member(node.field, node.span), text(node.text, node.span)], node.span)\n case 'regex':\n return call('regex', [member(node.field, node.span), text(node.pattern, node.span)], node.span)\n case 'isNull':\n if (options.expand) return { kind: 'not', arg: { kind: 'present', left: member(node.field, node.span), span: node.span }, span: node.span }\n return call('isNull', [member(node.field, node.span)], node.span)\n case 'related':\n return { kind: 'call', name: 'related', args: [member(node.field, node.span), { kind: 'member', path: [node.resource, node.key], span: node.span }, ...(node.filter ? [next(node.filter)] : []), ...relatedPage(node)], span: node.span }\n }\n}\n\nexport type { CheckedFilter, FilterExpr, Literal }\n","import { printFilter as print } from 'aip-parsers/filter'\nimport type { FilterExpr } from '../model'\nimport { lift } from './lift'\n\n/** Canonical text, readable by `parseFilter`; OR groups inside AND are always parenthesised. */\nexport const printFilter = (ast: FilterExpr) => print(lift(ast))\n","/** The path of the app's workflow trigger and step types under the API's system path (`/api`), as the editor reads them. */\nexport const workflowTypesPath = (systemPath: string) => `${systemPath}/workflows/types`\n\n/**\n * A trigger or step type as the server lists it: `id` is a Task's `Resource` or the key of a definition's `trigger`,\n * `input` the JSON Schema of its input, and `available` false, with the `reason`, when this app cannot run it.\n */\nexport type WorkflowTypeEntry = { id: string; kind: string; label: string; description: string; input: Record<string, unknown>; output?: Record<string, unknown>; available: boolean; reason?: string; cache?: WorkflowCacheAdvice; writes?: boolean | 'by_input' }\n\n/**\n * A step type's cache advice: how much the workflow's author decides (`hidden` nothing, `switch` on or off, `force` and\n * `discouraged` forcing it on, the latter after its `disclaimer`), and the switch's default.\n */\nexport type WorkflowCacheAdvice = { choice: 'hidden' | 'switch' | 'force' | 'discouraged'; default?: boolean; disclaimer?: string }\n\n/** An email template of the app: its name, the languages it is sent in, and the JSON Schema of its data, which `app:mail.template` takes. */\nexport type WorkflowTemplateEntry = { name: string; languages: string[]; schema: Record<string, unknown> }\n\n/** The app's step types and triggers, `manual` among them, built-in and plugin types alike, and its email templates, none when it has none. */\nexport type WorkflowTypeList = { step_types: WorkflowTypeEntry[]; triggers: WorkflowTypeEntry[]; templates?: WorkflowTemplateEntry[] }\n","/** The name of the runner's id in its registration path. */\nexport const runnerRegistrationParam = 'runner'\n\n/** The route of a runner's registration under `<systemPath>/workflows/runners`, as the server serves it. */\nexport const runnerRegistrationRoute = `/:${runnerRegistrationParam}/registration` as const\n\n/** The path that issues a runner's one-time registration token, under the API's system path (`/api`). */\nexport const runnerRegistrationPath = (systemPath: string, runner: string) => `${systemPath}/workflows/runners/${encodeURIComponent(runner)}/registration`\n\n/**\n * What issuing a runner's registration token answers, once: the `pbr_once_...` token, valid until `expires_at`, the one\n * command that installs a runner with it on a machine, and the address of the runner's calls.\n */\nexport type RunnerRegistration = { token: string; expires_at: string; command: string; endpoint: string }\n","/** Where runs' traces are served under the API's system path (`/api`). */\nexport const workflowRunsPath = (systemPath: string) => `${systemPath}/workflows/runs`\n\n/** The name of the run's id in a trace path. */\nexport const workflowRunParam = 'run'\n\n/** The route of a run's trace under {@link workflowRunsPath}, as the server serves it. */\nexport const workflowRunTraceRoute = `/:${workflowRunParam}/trace` as const\n\n/** The query parameter of a trace path that skips the steps its reader has already: how many those are. */\nexport const workflowTraceAfterParam = 'after'\n\n/** The query parameter of a trace path with the `revision` of the steps its reader has, which `after` counts. */\nexport const workflowTraceRevisionParam = 'revision'\n\n/** The steps a reader of a trace has: how many, and the `revision` the read that gave the last of them answered. */\nexport type WorkflowTraceHeld = { after: number; revision: string }\n\n/**\n * The path of a run's trace, as the run's page reads it: with the steps it `held`, only the steps after them while they\n * are still the trace's first.\n */\nexport const workflowRunTracePath = (systemPath: string, runId: string, held?: WorkflowTraceHeld) => {\n const path = `${workflowRunsPath(systemPath)}/${encodeURIComponent(runId)}/trace`\n if (!held || held.after === 0) return path\n return `${path}?${new URLSearchParams({ [workflowTraceAfterParam]: String(held.after), [workflowTraceRevisionParam]: held.revision })}`\n}\n\n/** One step of a run's trace, as the runner wrote it, with every secret blanked out. */\nexport type WorkflowTraceStep = {\n scope: string\n seq: number\n state: string\n type: string\n status: 'succeeded' | 'retrying' | 'caught' | 'failed'\n attempt: number\n input?: unknown\n output?: unknown\n assigned?: Record<string, unknown>\n next: string | null\n resumeAt?: string | null\n error?: string | null\n cause?: string | null\n logs: { at: string; message: string }[]\n startedAt: string\n finishedAt: string\n recorded: boolean\n /** A Block's step: the block's run that gave its result. */\n run?: string\n /** A Block's step whose result an earlier run of it gave, kept in the cache. */\n reused?: true\n /** A Block's step that took the result of a run of it another visit had started with the same key. */\n joined?: true\n}\n\n/**\n * A run's trace: its steps in the order they ran from the step numbered `from` on, none when the run keeps no trace,\n * and the `revision` of all its steps up to the last, for the next read after them. `from` is the `after` asked, or 0\n * when the trace holds fewer steps than that, as when a run that keeps its trace only when it fails succeeds, or when\n * its first `after` steps are no longer those of the `revision` asked.\n */\nexport type WorkflowRunTrace = { from: number; steps: WorkflowTraceStep[]; revision: string }\n","import type { FieldType, KeyValue, ResourceModel } from './model'\n\n/** The field types a primary key part may have: `integer`, `bigint`, `uuid` or `text`. */\nexport type KeyType = Extract<FieldType, 'integer' | 'bigint' | 'uuid' | 'text'>\n\nconst integerPattern = /^-?\\d+$/\nconst uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nconst decodePart = (part: string, type: KeyType): string | number => {\n if (type === 'text') return part\n if (type === 'uuid') {\n if (!uuidPattern.test(part)) throw new Error('Invalid uuid key part')\n return part\n }\n if (!integerPattern.test(part)) throw new Error(`Invalid ${type} key part`)\n if (type === 'bigint') return part\n const value = Number(part)\n if (!Number.isSafeInteger(value)) throw new Error('Invalid integer key part')\n return value\n}\n\n/** Whether a column of `type` can hold `value`, such as a user id an owner field stores. */\nexport const fitsKeyType = (value: string, type: KeyType) => {\n if (type === 'text') return true\n if (type === 'uuid') return uuidPattern.test(value)\n if (!integerPattern.test(value)) return false\n if (type === 'bigint') return true\n const number = Number(value)\n return Number.isSafeInteger(number) && Math.abs(number) <= 2 ** 31 - 1\n}\n\nconst decodeComponent = (part: string) => {\n try {\n return decodeURIComponent(part)\n } catch (error) {\n if (error instanceof URIError) throw new Error('Malformed key encoding')\n throw error\n }\n}\n\n// A single key is its plain value; composite parts are percent-encoded and comma-joined.\nexport const encodeKey = (key: KeyValue | readonly KeyValue[]) => {\n if (!Array.isArray(key)) return String(key)\n const parts = key as readonly KeyValue[]\n if (parts.length === 1) return String(parts[0])\n return parts.map((part) => encodeURIComponent(String(part))).join(',')\n}\n\nexport const decodeKey = (encoded: string, types: readonly KeyType[]) => {\n if (types.length === 0) throw new Error('A key needs at least one part')\n if (types.length === 1) return decodePart(encoded, types[0]!)\n const parts = encoded.split(',')\n if (parts.length !== types.length) {\n throw new Error(`Expected ${types.length} key parts, got ${parts.length}`)\n }\n return parts.map((part, i) => decodePart(decodeComponent(part), types[i]!))\n}\n\nconst scalarKey = (type: FieldType | undefined): type is KeyType =>\n type === 'text' || type === 'integer' || type === 'bigint' || type === 'uuid'\n\n/**\n * Key part types of a resource's primary key. A relation part takes the key types of the\n * target resource (a composite target contributes one part per key column), so `resolve`\n * is required whenever a relation is part of the key.\n */\nexport const keyTypes = (\n model: ResourceModel,\n resolve?: (resource: string) => ResourceModel | undefined,\n seen: string[] = [],\n): KeyType[] =>\n model.primaryKey.flatMap((name) => {\n const field = model.fields[name]\n if (scalarKey(field?.type)) return [field.type]\n if (field?.type !== 'relation' || !field.relation) {\n throw new Error(`Unsupported primary key type for \"${name}\"`)\n }\n const { resource, columns } = field.relation\n if (!resolve) throw new Error(`keyTypes needs a resolver for relation \"${name}\" to \"${resource}\"`)\n const target = resolve(resource)\n if (!target) throw new Error(`Unknown resource \"${resource}\" for relation \"${name}\"`)\n if (seen.includes(target.name)) throw new Error(`Circular primary key through \"${resource}\"`)\n const types = keyTypes(target, resolve, [...seen, model.name])\n if (types.length !== columns.length) {\n throw new Error(`Relation \"${name}\" has ${columns.length} column(s) but \"${resource}\" has a ${types.length}-part key`)\n }\n return types\n })\n","import { createParser } from 'eventsource-parser'\n\n// A body from a fetch given the same signal is already errored with an AbortError when the listener cancels it\nconst ignoreAbort = (error: unknown) => {\n if (error instanceof DOMException && error.name === 'AbortError') return\n throw error\n}\n\n/**\n * Reads a `text/event-stream` body and calls `onData` with the data of every event, its `data:` lines joined by\n * newlines. Comments, event names and ids are skipped: the assistant protocol and chat completions only use data.\n * Aborting `signal` cancels the body and resolves.\n */\nexport const readEventStream = async (body: ReadableStream<Uint8Array>, onData: (data: string) => void, signal?: AbortSignal) => {\n const parser = createParser({ onEvent: (event) => onData(event.data) })\n const decoder = new TextDecoder()\n const reader = body.getReader()\n signal?.addEventListener('abort', () => void reader.cancel().catch(ignoreAbort), { once: true })\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n parser.feed(decoder.decode(value, { stream: true }))\n }\n // An event the body ends without a blank line after still counts\n parser.feed(`${decoder.decode()}\\n\\n`)\n}\n","/** The name of a bridge token in the query of the bridge's socket address. */\nexport const bridgeTokenParam = 'token'\n\n/** The address of the socket a bridge token opens, below the bridge function's own path, such as `/api/functions/console`. */\nexport const bridgeSocketPath = (functionPath: string, token: string) => `${functionPath}?${new URLSearchParams({ [bridgeTokenParam]: token })}`\n","/** The name of the device id in a device's path. */\nexport const deviceIdParam = 'id'\n\n/** The path of the caller's devices under the API's system path (`/api`), or of one of them by its id. */\nexport const devicesPath = (systemPath: string, id?: string) => `${systemPath}/notifications/devices${id === undefined ? '' : `/${encodeURIComponent(id)}`}`\n","/** The query parameter that asks a file link for its bytes from the app itself, never a redirect to the file's store. */\nexport const appReadParam = 'via'\n\nconst appReadValue = 'app'\n\n/** The largest file the app serves through such a read: a viewer reads documents, while images and video use the plain link. */\nexport const appReadMaxBytes = 10 * 1024 * 1024\n\n/** Where an API serves files, beside its system path (`/api`): `/api/files`. */\nexport const filesPath = (systemPath: string) => `${systemPath}/files`\n\n/** The address of a provider's file under `files`, a `filesPath`: `/api/files/private/acme/2992db9c-….jpg`. */\nexport const filePath = (files: string, provider: string, path: string) => `${files}/${provider}/${path}`\n\n/** The provider and path of a stored file value (`private:acme/2992db9c-….jpg?name=bike.png`); `undefined` for a URL. */\nexport const storedFileRef = (uri: string) => {\n const match = /^([a-z][a-z0-9-]*):([A-Za-z0-9_-][^?#]*)/.exec(uri)\n return match ? { provider: match[1]!, path: match[2]! } : undefined\n}\n\n/**\n * A link to a file on the app that answers with the bytes from the app's own origin, for a page that reads the file\n * with `fetch`: the plain link may redirect to a bucket that sends no CORS headers.\n */\nexport const appReadUrl = (url: string) => `${url}${url.includes('?') ? '&' : '?'}${appReadParam}=${appReadValue}`\n\n/** Whether a file request asks for an app read. */\nexport const isAppRead = (query: URLSearchParams) => query.get(appReadParam) === appReadValue\n","/** What an entry id looks like in every history store: it goes into a path, so no `/`, `.`, `?`, `#` or `%`. */\nexport const historyIdPattern = /^[A-Za-z0-9_-]{1,64}$/\n\n/** The name of the entry id in the path that marks one entry of the history read. */\nexport const historyIdParam = 'id'\n\n/**\n * The path of the caller's notification history under the API's system path (`/api`): the list itself, `unread` its\n * unread count, `read` marking all read, or `{ read: id }` marking one entry read. An id that could leave the history's\n * path, any but letters, digits, `_` and `-`, is refused.\n */\nexport const historyPath = (systemPath: string, part?: 'unread' | 'read' | { read: string }) => {\n const base = `${systemPath}/notifications/history`\n if (part === undefined) return base\n if (typeof part === 'string') return `${base}/${part}`\n if (!historyIdPattern.test(part.read)) throw new Error('A history entry id is letters, digits, \"_\" and \"-\" only')\n return `${base}/${part.read}/read`\n}\n","/** Whether a person may be reached: `automatic` says nothing, `busy` is a mark only, `do_not_disturb` holds their pushes. */\nexport const availabilities = ['automatic', 'busy', 'do_not_disturb'] as const\nexport type Availability = (typeof availabilities)[number]\n\n/** The most characters a custom status holds, counted as a person sees them, an emoji as one. */\nexport const maxStatusText = 100\n\n/** A person's status as the API answers it: `text` and `clearsAt` are `null` when not set. */\nexport type PersonStatus = { userId: string; availability: Availability; text: string | null; clearsAt: string | null }\n\n/** What a person sets: an availability, a custom text, and when it clears, an ISO time, `null` for never. */\nexport type StatusInput = { availability: Availability; text: string | null; clearsAt: string | null }\n\n/** The path of the status endpoints under the API's system path (`/api`): the caller's own, or `people` they share an organization with. */\nexport const statusPath = (systemPath: string, part?: 'people') => `${systemPath}/status${part === undefined ? '' : `/${part}`}`\n\n// Control characters, line breaks and tabs included: a status is one line of plain text.\nconst controlCharacter = /\\p{Cc}/u\n\n/** What is wrong with a custom status text, as a sentence to show; `undefined` when it may be set. */\nexport const statusTextProblem = (text: string) => {\n if (controlCharacter.test(text)) return 'A status is one line of text, without control characters'\n if ([...text].length > maxStatusText) return `A status is at most ${maxStatusText} characters`\n return\n}\n\n/** The status as it holds at `now`: none once its clear time has passed, or when it says nothing. */\nexport const heldStatus = <S extends Pick<PersonStatus, 'availability' | 'text' | 'clearsAt'>>(status: S | null | undefined, now = Date.now()): S | undefined => {\n if (!status) return\n if (status.clearsAt !== null && Date.parse(status.clearsAt) <= now) return\n if (status.availability === 'automatic' && status.text === null) return\n return status\n}\n","/**\n * A call that rings the signed-in user now, as the open pages of the app show it: the call, its record, who started\n * it, the ring's text, and how many milliseconds it still rings, by the server's clock.\n */\nexport type CallRing = {\n call: string\n resource: string\n /** The record's key as its URL has it. */\n key: string\n started_by: string\n title: string\n body: string | null\n remaining_ms: number\n}\n\n/**\n * The resource name of the notices the live stream sends a user when the calls that ring them change, keyed by the\n * user's id: no resource has a `$` in its name.\n */\nexport const ringNotice = '$rings'\n\n/** Decline, as a ring's path takes it. */\nexport const declineWord = 'decline'\n\n/**\n * The path of the calls that ring the caller under the API's system path (`/api`), or of declining the ring of one\n * call, `{ decline: call }`.\n */\nexport const ringsPath = (systemPath: string, part?: { decline: string }) => {\n const base = `${systemPath}/calls/rings`\n if (part === undefined) return base\n return `${base}/${encodeURIComponent(part.decline)}/${declineWord}`\n}\n\n/** The event a record's channel hears its calls on, from the server, with `{ items }` as `GET /{resource}/{key}:calls` answers. */\nexport const callsChannelEvent = 'calls'\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"loader-circle\",\n size: 24,\n node: [[\"path\", { d: \"M21 12a9 9 0 1 1-6.219-8.56\", key: \"13zald\" }]],\n aliases: [\"loader-2\"]\n};\n__iconData.node;\nconst LoaderCircle = createLucideIcon(__iconData);\n\nexport { __iconData, LoaderCircle as default };\n//# sourceMappingURL=loader-circle.mjs.map\n","import { messages } from '../locale/messages'\n\nexport const text = messages('primitives')\n","import { Loader2 } from 'lucide-react'\nimport { cn } from '../lib/cn'\nimport { text } from './messages'\n\n/** A spinning loader, named \"Loading\", or `hidden` from assistive technology where what it sits in already says it is busy. */\nexport const Spinner = ({ className, hidden = false }: { className?: string; hidden?: boolean }) => (\n <Loader2 {...(hidden ? { 'aria-hidden': true } : { 'aria-label': text('loading') })} className={cn('size-4 animate-spin', className)} />\n)\n","import type { ButtonHTMLAttributes, Ref } from 'react'\nimport { cn } from '../lib/cn'\nimport { Spinner } from './spinner'\n\nexport type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {\n variant?: 'primary' | 'secondary' | 'ghost' | 'danger'\n /** `icon` is a square of the height of `sm`, for a button with an icon alone. */\n size?: 'sm' | 'md' | 'icon'\n loading?: boolean\n ref?: Ref<HTMLButtonElement>\n}\n\nconst variants = {\n primary: 'bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm',\n secondary: 'bg-background text-foreground border border-border-strong hover:bg-muted shadow-sm',\n ghost: 'text-muted-foreground hover:bg-muted hover:text-foreground',\n danger: 'bg-background text-danger-text border border-border-strong hover:bg-danger-soft shadow-sm',\n}\n\nconst sizes = { sm: 'h-7 px-2.5 text-body gap-1.5', md: 'h-8 px-3 text-body gap-2', icon: 'size-7 text-body' }\n\n/** A button's classes, for a link that looks like one. */\nexport const buttonClass = ({ variant = 'secondary', size = 'md' }: Pick<ButtonProps, 'variant' | 'size'> = {}) =>\n cn(\n 'inline-flex shrink-0 items-center justify-center rounded-md font-medium transition-colors aria-disabled:cursor-not-allowed aria-disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-60 disabled:cursor-default',\n variants[variant],\n sizes[size],\n )\n\nexport const Button = ({ variant = 'secondary', size = 'md', loading, className, children, disabled, ...rest }: ButtonProps) => (\n <button\n type=\"button\"\n disabled={disabled || loading}\n aria-busy={loading || undefined}\n className={cn(buttonClass({ variant, size }), className)}\n {...rest}\n >\n {/* The button keeps its own name while busy, which aria-busy says */}\n {loading && <Spinner hidden className=\"size-3.5\" />}\n {children}\n </button>\n)\n","import { printFilter, type CardPhotosModel, type FilterExpr } from '@protobase/schema'\n\nexport type FilterInput = string | FilterExpr\n\nexport type ListParams = {\n filter?: FilterInput\n /** AIP-132 text, for example `created_at desc`. */\n orderBy?: string\n pageSize?: number\n pageToken?: string\n fields?: string[]\n /**\n * Names the records relations point at, in the same answer: `{ place_id: 'name' }` gives each place's `name` in the\n * page's `labels`. A record the caller cannot list, or whose field they cannot read, has no name there.\n */\n labels?: Record<string, string>\n /**\n * Brings each record's first photos in the same answer, as a cards display's `photos` names them: the `image` of the\n * records of `resource` whose relation `field` points at it, in `sort` order, at most ten. The caller gets those they\n * could list themselves.\n */\n photos?: CardPhotosModel\n count?: 'exact'\n /** The first `count` records per value of `field`, in the list's order, as one page with no next one (`limit_per`). */\n limitPer?: { field: string; count: number }\n /** `false` leaves each item's `etag` out, so the server reads only the selected `fields`. */\n etag?: false\n}\n\n/** What `map` asks for: the fields of the position, the map's zoom, and the bounding box in `filter`. */\nexport type MapParams = {\n latitude: string\n longitude: string\n zoom: number\n filter?: FilterInput\n orderBy?: string\n fields?: string[]\n /** As a list's `labels`. */\n labels?: Record<string, string>\n /** As a list's `photos`. */\n photos?: CardPhotosModel\n}\n\nexport const filterText = (filter: FilterInput | undefined) => (typeof filter === 'string' ? filter : filter && printFilter(filter))\n\ntype Wire = Record<string, string | number | undefined>\n\n/** `labels` as the API takes it: `relation.field` entries. */\nexport const labelEntries = (labels: Record<string, string> | undefined) => {\n const entries = Object.entries(labels ?? {}).map(([relation, field]) => `${relation}.${field}`)\n return entries.length > 0 ? entries : undefined\n}\n\n/** `photos` as the API takes it: a `resource.field.image` entry and the order of the photos. */\nexport const photosWire = (photos: CardPhotosModel | undefined) => ({\n photos: photos && `${photos.resource}.${photos.field}.${photos.image}`,\n photos_order_by: photos?.sort,\n})\n\n/** The snake_case parameters of `GET /{resource}` and the body of `POST /{resource}:search`. */\nexport const listWire = (params: ListParams = {}) => ({\n filter: filterText(params.filter) || undefined,\n order_by: params.orderBy,\n page_size: params.pageSize,\n page_token: params.pageToken || undefined,\n fields: params.fields?.join(','),\n labels: labelEntries(params.labels)?.join(','),\n ...photosWire(params.photos),\n count: params.count,\n limit_per: params.limitPer && `${params.limitPer.field}:${params.limitPer.count}`,\n etag: params.etag === false ? 'false' : undefined,\n})\n\nexport const queryString = (wire: Wire) => {\n const search = new URLSearchParams()\n for (const [name, value] of Object.entries(wire)) if (value !== undefined) search.set(name, String(value))\n const text = search.toString()\n return text ? `?${text}` : ''\n}\n","import type { RecordPhotos, StoredFile } from './types'\n\nconst isPath = (url: string) => url.startsWith('/') && !url.startsWith('//')\n\ntype FileAtPath = { uri: string; url: string; variants?: Record<string, { url: string }> }\n\n// A file field's value whose download URL is a path on the origin of the API that served it.\nconst isFileAtPath = (value: unknown): value is FileAtPath => {\n if (typeof value !== 'object' || value === null) return false\n const { uri, url } = value as { uri?: unknown; url?: unknown }\n return typeof uri === 'string' && typeof url === 'string' && isPath(url)\n}\n\n/** The origin of an absolute `baseUrl`; `undefined` for a path on the page's own origin. */\nexport const originOf = (baseUrl: string | undefined) => (baseUrl !== undefined && URL.canParse(baseUrl) ? new URL(baseUrl).origin : undefined)\n\nconst fromOrigin = (file: FileAtPath, origin: string): FileAtPath => ({\n ...file,\n url: `${origin}${file.url}`,\n ...(file.variants && {\n variants: Object.fromEntries(Object.entries(file.variants).map(([name, variant]) => [name, isPath(variant.url) ? { ...variant, url: `${origin}${variant.url}` } : variant])),\n }),\n})\n\n/**\n * Makes each file of a record download from `origin`, its variants too: the API answers a file's URL as a path on its\n * own origin, which a page on another origin, or code outside a page, cannot follow. Without an origin the record is\n * returned as it is.\n */\nexport const withFileOrigin = <T>(record: T, origin: string | undefined): T => {\n if (origin === undefined || typeof record !== 'object' || record === null) return record\n return Object.fromEntries(Object.entries(record).map(([name, value]) => [name, isFileAtPath(value) ? fromOrigin(value, origin) : value])) as T\n}\n\n/** Each record's photos, by key, every file downloading from `origin`, as `withFileOrigin` makes a record's. */\nexport const photosWithOrigin = (photos: RecordPhotos, origin: string | undefined): RecordPhotos =>\n origin === undefined ? photos : Object.fromEntries(Object.entries(photos).map(([key, files]) => [key, files.map((file) => (isFileAtPath(file) ? fromOrigin(file, origin) : file) as StoredFile)]))\n\n/**\n * The link of a stored file, or of its variant by that name when it has one (`fileUrl(listing.photo, 'card')`); the\n * file's own link otherwise, and `undefined` for a missing file or one without a link.\n */\nexport const fileUrl = (file: StoredFile, variant?: string) => {\n if ('missing' in file) return undefined\n return (variant === undefined ? undefined : file.variants?.[variant]?.url) ?? file.url\n}\n","export type ProblemError = {\n code?: string\n message: string\n hint?: string\n span?: { start: number; end: number }\n field?: string\n /** For an invalid field value, the limit it broke, such as `{ max: 200 }` or a decimal's `{ precision, scale }`. */\n params?: Record<string, unknown>\n parameter?: string\n /** The index of the operation in a batch that this error belongs to. */\n operation?: number\n}\n\nexport type ProblemDetails = {\n type: string\n title: string\n status: number\n detail?: string\n instance?: string\n /** The query parameter a filter or `order_by` error refers to. */\n parameter?: string\n errors?: ProblemError[]\n /** The index of the operation that failed, when the request was a batch. */\n operation?: number\n /** For a delete other records still point at: their resource, and its field pointing at the record, as far as the caller may know. */\n blockedBy?: { resource: string; field?: string }\n /** For a create refused by a resource's `.openExisting()` unique key: the key of the record holding those values, when the caller may read it. */\n existing?: { key: string }\n /** For `strong-sign-in-required`: how many minutes old the strong sign-in may be. */\n minutes?: number\n /** For a message that could not go out from the person's own mailbox: why, `not_linked` or `link_expired`. */\n code?: string\n /** For a mailbox link that expired: its mail provider, such as `gmail`. */\n provider?: string\n}\n\n/** A non-2xx response, parsed from `application/problem+json`. */\nexport class ApiError extends Error {\n constructor(readonly problem: ProblemDetails) {\n super(problem.detail ?? problem.title)\n this.name = 'ApiError'\n }\n\n get status() {\n return this.problem.status\n }\n\n /** The problem slug, for example `invalid-filter` or `precondition-failed`. */\n get slug() {\n return this.problem.type.split(':').at(-1) ?? ''\n }\n\n /** For a batch: the index of the operation that failed, so the UI can name it. */\n get operation() {\n return this.problem.operation ?? this.errors.find((entry) => entry.operation !== undefined)?.operation\n }\n\n /** For a delete other records still point at: their resource, and the field to filter its list by. */\n get blockedBy() {\n return this.problem.blockedBy\n }\n\n /** For a create refused by a resource's `.openExisting()` unique key: the record holding those values, when the caller may read it. */\n get existing() {\n return this.problem.existing\n }\n\n get errors() {\n return this.problem.errors ?? []\n }\n\n /** Filter errors carry the span of the offending text, so the UI can underline it. */\n get filterErrors() {\n return this.slug === 'invalid-filter' ? this.errors : []\n }\n}\n\n/** `412`: the record changed since it was read. */\nexport class PreconditionFailedError extends ApiError {\n constructor(problem: ProblemDetails) {\n super(problem)\n this.name = 'PreconditionFailedError'\n }\n}\n\nexport const isApiError = (error: unknown): error is ApiError => error instanceof ApiError\n\nconst isProblem = (body: unknown): body is ProblemDetails =>\n typeof body === 'object' && body !== null && 'type' in body && 'status' in body\n\n/** Turns a failed response into a typed error; bodies that are not problem+json become a generic problem. */\nexport const readProblem = async (response: Response) => {\n const isJson = response.headers.get('content-type')?.includes('json') ?? false\n const body: unknown = isJson ? await response.json() : undefined\n const problem = isProblem(body)\n ? body\n : { type: 'urn:protobase:problem:unknown', title: response.statusText || 'Request failed', status: response.status }\n return problem.status === 412 ? new PreconditionFailedError(problem) : new ApiError(problem)\n}\n","import type { SocketLike } from './channel-connection'\nimport { readProblem } from './problem'\n\nexport type ClientOptions = {\n /** Where `/api/v1` lives, without a trailing slash. Defaults to `/api/v1` on the current origin. */\n baseUrl?: string\n fetch?: typeof fetch\n headers?: () => Record<string, string>\n /** Called with the `X-Meta-Version` of every response; a change means `/meta` should be refetched. */\n onMetaVersion?: (version: string) => void\n /**\n * The bearer token for a request. Called with `refresh: true` when the server answered 401, so the\n * caller can fetch a new one; the request is then retried once.\n */\n token?: (options: { refresh: boolean }) => Promise<string | undefined>\n /** Called when a request is still 401 after the retry: the session is over. */\n onUnauthenticated?: () => void\n /** Opens the socket of `client.channel`; the global `WebSocket` by default. */\n webSocket?: (url: string, protocols: string[]) => SocketLike\n}\n\n/** The browser's fetch cache modes but `only-if-cached`, which fetch takes only with a same-origin mode the client never sends. */\nexport type CacheMode = Exclude<RequestCache, 'only-if-cached'>\n\nexport type Request = {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n path: string\n query?: string\n body?: unknown\n headers?: Record<string, string>\n /** Statuses other than 2xx that are an answer rather than an error. */\n accept?: number[]\n /** A system endpoint such as `/meta`: it lives beside the API (`/api/meta`), not inside it (`/api/v1`). */\n system?: boolean\n /** Sent as it is instead of a JSON `body`, such as a file. */\n raw?: Blob\n /** Sends this request instead of the client's fetch, such as one that reports upload progress. */\n via?: typeof fetch\n signal?: AbortSignal\n /** How the browser's HTTP cache treats the request, such as `no-store` for an answer only its caller may see. */\n cache?: CacheMode\n}\n\n/** Where the system endpoints beside the API live: `/api` for `/api/v1`. */\nexport const systemUrlOf = (baseUrl = '/api/v1') => baseUrl.replace(/\\/[^/]*$/, '')\n\nexport const createTransport = (options: ClientOptions = {}) => {\n const baseUrl = options.baseUrl ?? '/api/v1'\n const systemUrl = systemUrlOf(baseUrl)\n const doFetch = options.fetch ?? ((input, init) => fetch(input, init))\n\n return async ({ method, path, query = '', body, headers, accept = [], system, raw, via, signal, cache }: Request) => {\n const attempt = async (refresh: boolean) => {\n const token = await options.token?.({ refresh })\n return (via ?? doFetch)(`${system ? systemUrl : baseUrl}${path}${query}`, {\n method,\n headers: {\n ...(body !== undefined && { 'content-type': 'application/json' }),\n ...(token && { authorization: `Bearer ${token}` }),\n ...options.headers?.(),\n ...headers,\n },\n body: raw ?? (body === undefined ? undefined : JSON.stringify(body)),\n ...(signal && { signal }),\n ...(cache && { cache }),\n })\n }\n let response = await attempt(false)\n if (response.status === 401 && options.token) {\n response = await attempt(true)\n if (response.status === 401) options.onUnauthenticated?.()\n }\n const metaVersion = response.headers.get('x-meta-version')\n if (metaVersion) options.onMetaVersion?.(metaVersion)\n if (!response.ok && !accept.includes(response.status)) throw await readProblem(response)\n return response\n }\n}\n\nexport type Transport = ReturnType<typeof createTransport>\n","import { appReadUrl, filePath, filesPath, storedFileRef } from '@protobase/schema/internal'\n\n// With an absolute `systemUrl`, both in the form `URL` writes them, such as without a default port, a path link put on\n// that API's origin as the client does for a record's file links; with a path, both as they are.\nconst canonical = (url: string, systemUrl: string) => {\n if (!URL.canParse(systemUrl)) return { link: url, api: systemUrl }\n const api = new URL(systemUrl)\n return { link: new URL(url, api).href, api: `${api.origin}${api.pathname.replace(/\\/$/, '')}` }\n}\n\n/**\n * Where a page reads a stored file's bytes with `fetch` from the API at `systemUrl` (`/api`, or an absolute one), never\n * through a redirect to a bucket that sends no CORS headers. A file that API links under its own files is read through\n * that link; one it links elsewhere, such as a public file at a CDN's `publicUrl`, from its files by the stored `uri`. A\n * link with another scheme, such as `data:`, and a field's external URL are read as they are.\n */\nexport const fileReadUrl = (file: { uri: string; url: string }, systemUrl: string) => {\n if (!file.url.startsWith('/') && !/^https?:\\/\\//i.test(file.url)) return file.url\n const ref = storedFileRef(file.uri)\n if (!ref) return file.url\n const { link, api } = canonical(file.url, systemUrl)\n const files = filesPath(api)\n if (link.startsWith(`${files}/`)) return appReadUrl(link)\n return appReadUrl(filePath(files, ref.provider, ref.path))\n}\n","/** Bytes sent so far, of `total`. */\nexport type UploadProgress = (sent: number, total: number) => void\n\nconst headersOf = (raw: string) =>\n new Headers(raw.trim().split(/[\\r\\n]+/).filter(Boolean).map((line): [string, string] => {\n const colon = line.indexOf(':')\n return [line.slice(0, colon).trim(), line.slice(colon + 1).trim()]\n }))\n\n/**\n * A `fetch` that reports upload progress, through XMLHttpRequest since fetch cannot. It answers with an ordinary\n * Response; a network failure rejects with a TypeError, as fetch does.\n */\nexport const fetchWithProgress = (onProgress: UploadProgress): typeof fetch => (input, init = {}) =>\n new Promise<Response>((resolve, reject) => {\n const request = new XMLHttpRequest()\n request.open(init.method ?? 'GET', String(input))\n new Headers(init.headers).forEach((value, name) => request.setRequestHeader(name, value))\n request.responseType = 'blob'\n request.upload.onprogress = (event) => onProgress(event.loaded, event.lengthComputable ? event.total : event.loaded)\n request.onload = () => {\n const empty = request.status === 204 || request.status === 304\n resolve(new Response(empty ? null : (request.response as Blob), { status: request.status, statusText: request.statusText, headers: headersOf(request.getAllResponseHeaders()) }))\n }\n request.onerror = () => reject(new TypeError('Network request failed'))\n request.onabort = () => reject(new DOMException('The upload was aborted', 'AbortError'))\n init.signal?.addEventListener('abort', () => request.abort())\n request.send(init.body as XMLHttpRequestBodyInit | null)\n })\n","import { readEventStream } from '@protobase/schema/internal'\nimport { queryString } from './query-string'\nimport type { Transport } from './transport'\n\n/**\n * A record of a `.live()` resource that changed: its key, never its values. The key is empty for a resource live from\n * others (`.live({ reads })`), such as one backed by a view, when one of those changed: any of its records may have.\n */\nexport type LiveChange = { resource: string; key: string; operation: 'create' | 'update' | 'delete' | 'undelete' }\n\nexport type LiveHandlers = {\n /** The records that changed, in commit order, of the live resources the caller may read. */\n onChanges: (changes: LiveChange[]) => void\n /** Changes went by while the connection was down for longer than the server keeps them: read everything shown again. */\n onResync: () => void\n /** The stream failed, with why, or ended (`undefined`); it is followed again after a pause. */\n onRetry?: (error: unknown) => void\n}\n\ntype LiveEvent = { type: 'current' | 'resync'; cursor: string } | { type: 'changes'; cursor: string; changes: LiveChange[] }\n\nconst backoff = (attempt: number) => Math.min(30_000, 1000 * 2 ** attempt)\n\nconst pause = (ms: number, signal: AbortSignal) =>\n new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms)\n signal.addEventListener('abort', () => {\n clearTimeout(timer)\n resolve()\n }, { once: true })\n })\n\n/**\n * Follows `GET /api/live` until the returned function is called: a stream that ends or fails is followed again, after\n * a pause that grows with each failure, from the last event it had, so nothing in between is missed.\n */\nexport const followLive = (send: Transport, handlers: LiveHandlers, retryDelay: (attempt: number) => number = backoff) => {\n const controller = new AbortController()\n const { signal } = controller\n let cursor: string | undefined\n let failures = 0\n\n const onEvent = (event: LiveEvent) => {\n failures = 0\n cursor = event.cursor\n if (event.type === 'resync') handlers.onResync()\n if (event.type === 'changes') handlers.onChanges(event.changes)\n }\n\n const follow = async () => {\n const response = await send({ method: 'GET', path: '/live', query: queryString({ after: cursor }), headers: { accept: 'text/event-stream' }, system: true, signal })\n if (!response.body) throw new Error('The server answered the live stream without a body')\n await readEventStream(response.body, (data) => onEvent(JSON.parse(data) as LiveEvent), signal)\n }\n\n void (async () => {\n while (!signal.aborted) {\n const error = await follow().then(() => undefined, (reason: unknown) => reason)\n if (signal.aborted) return\n handlers.onRetry?.(error)\n await pause(retryDelay(failures++), signal)\n }\n })()\n return () => controller.abort()\n}\n","import type { LiveHandlers } from './live'\n\n/**\n * `client.live` for every caller of one client on one stream: the first caller opens it, each hears every event, and\n * the last to stop closes it. A page with many live views then holds one connection however many there are, which a\n * browser's six per host under HTTP/1.1 need.\n */\nexport const sharedLive = (follow: (handlers: LiveHandlers) => () => void) => {\n const subscribers = new Set<LiveHandlers>()\n let stop: (() => void) | undefined\n const each = (call: (handlers: LiveHandlers) => void) => {\n for (const handlers of [...subscribers]) call(handlers)\n }\n return (handlers: LiveHandlers) => {\n // Its own object, so a caller that passes the same handlers twice is two subscribers.\n const subscriber = { ...handlers }\n subscribers.add(subscriber)\n stop ??= follow({\n onChanges: (changes) => each((one) => one.onChanges(changes)),\n onResync: () => each((one) => one.onResync()),\n onRetry: (error) => each((one) => one.onRetry?.(error)),\n })\n return () => {\n if (!subscribers.delete(subscriber) || subscribers.size > 0) return\n stop?.()\n stop = undefined\n }\n }\n}\n","const encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\n// The header's byte length, a big-endian 32-bit integer.\nconst lengthBytes = 4\n\n/**\n * A binary frame of `/api/channels`, which carries a broadcast of bytes: the byte length of a JSON header, the header,\n * the message without its payload, then the payload's bytes.\n */\nexport const encodeBinaryFrame = (header: Record<string, unknown>, bytes: ArrayBuffer | ArrayBufferView): ArrayBuffer => {\n const head = encoder.encode(JSON.stringify(header))\n const body = bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n const frame = new Uint8Array(lengthBytes + head.length + body.length)\n new DataView(frame.buffer).setUint32(0, head.length)\n frame.set(head, lengthBytes)\n frame.set(body, lengthBytes + head.length)\n return frame.buffer\n}\n\n/** The message a binary frame from the server carries, its bytes as its `payload`. */\nexport const decodeBinaryFrame = (frame: ArrayBuffer): Record<string, unknown> => {\n const end = lengthBytes + new DataView(frame).getUint32(0)\n const header = JSON.parse(decoder.decode(new Uint8Array(frame, lengthBytes, end - lengthBytes))) as Record<string, unknown>\n return { ...header, payload: frame.slice(end) }\n}\n\n/** Whether a payload is bytes, sent as a binary frame. */\nexport const isBytes = (payload: unknown): payload is ArrayBuffer | ArrayBufferView => payload instanceof ArrayBuffer || ArrayBuffer.isView(payload)\n","/** Who sent a broadcast or tracks a presence, stamped by the server from their session: a user's id, `null` for a visitor. */\nexport type ChannelUser = string | number | null\n\n/** One connection's presence on a channel: its id, the same while it is tracked, its user and the state it tracks. */\nexport type PresenceEntry = { id: string; user: ChannelUser; state: unknown }\n\n/** What changed in a channel's presence: connections that started tracking, changed their state, or left. */\nexport type PresenceChange = { joins: PresenceEntry[]; updates: PresenceEntry[]; leaves: PresenceEntry[] }\n\n/** Why the server refused a message or ended a channel, such as `not-found` for a record the caller may not read. */\nexport type ChannelError = { code: string; message: string }\n\n/** A broadcast as a channel hears it, its payload JSON or, for bytes, an `ArrayBuffer`: with `server`, the app's own code sent it, and `user` is `null`. */\nexport type ChannelMessage = { event: string; payload: unknown; user: ChannelUser; server?: true }\n\n/**\n * Where a channel stands: `joining`, also while the connection is down; `joined`; `refused`, never joined, as for a\n * record there is none of or the caller may not read; `closed`, left by the server, as once the caller may no longer\n * read the record. A refused or closed channel is not joined again: leave it and take a new one.\n */\nexport type ChannelStatus = { state: 'joining' | 'joined' } | { state: 'refused' | 'closed'; error: ChannelError }\n\n/** What the server sends on `/api/channels`. */\nexport type ServerMessage =\n | { type: 'pong' }\n | { type: 'reply'; ref: string; ok: true; channel?: string }\n | { type: 'reply'; ref: string; ok: false; error: ChannelError }\n | { type: 'error'; error: ChannelError }\n | { type: 'presence'; channel: string; entries: PresenceEntry[] }\n | ({ type: 'presence_diff'; channel: string } & PresenceChange)\n | ({ type: 'broadcast'; channel: string } & ChannelMessage)\n | { type: 'closed'; channel: string; error: ChannelError }\n\n/** A refusal of the server, or `disconnected` for a message whose connection dropped before its reply. */\nexport class ChannelRefusal extends Error {\n constructor(readonly code: string, message: string) {\n super(message)\n this.name = 'ChannelRefusal'\n }\n}\n","import { decodeBinaryFrame, encodeBinaryFrame } from './channel-binary-frame'\nimport { ChannelRefusal, type ServerMessage } from './channel-types'\n\n/** The part of the browser's `WebSocket` a connection uses, which a test hands its own of. */\nexport type SocketLike = {\n readonly readyState: number\n binaryType: string\n send(data: string | ArrayBuffer): void\n close(code?: number): void\n onopen: ((event: unknown) => void) | null\n onmessage: ((event: { data: unknown }) => void) | null\n onclose: ((event: unknown) => void) | null\n}\n\nexport type ConnectionOptions = {\n /** The socket's `ws:` or `wss:` URL of `/api/channels`, read as it connects. */\n url: () => string\n /** The bearer token, when the client has one: offered as a subprotocol on opening, and handed over as it changes. */\n token?: () => Promise<string | undefined>\n socket: (url: string, protocols: string[]) => SocketLike\n /** How long to wait before connecting again after the `attempt`th failure in a row. */\n retryDelay: (attempt: number) => number\n /** The socket opened: join the channels again. */\n onOpen: () => void\n /** The socket dropped; it connects again by itself. */\n onDown: () => void\n onMessage: (message: ServerMessage) => void\n}\n\n/** How often the client pings, the server's `channelBounds.pingMs`; no pong in twice that drops the connection. */\nexport const pingMs = 5_000\n\nconst openState = 1\nconst protocol = 'protobase.channels'\n\ntype Pending = { resolve: (reply: Extract<ServerMessage, { type: 'reply'; ok: true }>) => void; reject: (error: unknown) => void }\n\n/**\n * The one socket of a client's channels: opened on `start`, connected again after a pause that grows with each failure\n * while it is wanted, closed on `stop`. It pings every `pingMs`, hands the server a token that changed, and drops a\n * socket that answered no ping in twice that, as one whose network went away.\n */\nexport const channelConnection = ({ url, token, socket: open, retryDelay, onOpen, onDown, onMessage }: ConnectionOptions) => {\n let socket: SocketLike | undefined\n let wanted = false\n let failures = 0\n let lastRef = 0\n let sentToken: string | undefined\n let heardAt = 0\n let ping: ReturnType<typeof setInterval> | undefined\n let retry: ReturnType<typeof setTimeout> | undefined\n const pending = new Map<string, Pending>()\n\n const dropPending = () => {\n for (const { reject } of pending.values()) reject(new ChannelRefusal('disconnected', 'The connection dropped before the server answered'))\n pending.clear()\n }\n\n const handover = async (current: SocketLike) => {\n const fresh = await token?.()\n if (socket !== current || current.readyState !== openState || fresh === undefined || fresh === sentToken) return\n sentToken = fresh\n current.send(JSON.stringify({ type: 'token', token: fresh }))\n }\n\n const connect = async () => {\n const offered = await token?.()\n if (!wanted || socket) return\n sentToken = offered\n const current = open(url(), offered === undefined ? [protocol] : [protocol, `bearer.${offered}`])\n socket = current\n current.binaryType = 'arraybuffer'\n current.onopen = () => {\n failures = 0\n heardAt = Date.now()\n ping = setInterval(() => {\n if (Date.now() - heardAt > 2 * pingMs) return current.close()\n current.send(JSON.stringify({ type: 'ping' }))\n void handover(current)\n }, pingMs)\n onOpen()\n }\n current.onmessage = ({ data }) => {\n heardAt = Date.now()\n if (typeof data !== 'string' && !(data instanceof ArrayBuffer)) return\n const message = (typeof data === 'string' ? JSON.parse(data) : decodeBinaryFrame(data)) as ServerMessage\n if (message.type !== 'reply') return onMessage(message)\n const waiting = pending.get(message.ref)\n pending.delete(message.ref)\n if (message.ok) waiting?.resolve(message)\n else waiting?.reject(new ChannelRefusal(message.error.code, message.error.message))\n }\n current.onclose = () => {\n if (socket !== current) return\n clearInterval(ping)\n socket = undefined\n dropPending()\n if (!wanted) return\n onDown()\n retry = setTimeout(() => {\n retry = undefined\n void connect()\n }, retryDelay(failures++))\n }\n }\n\n // With bytes, a binary frame of the message and them as its payload.\n const sendNow = (message: Record<string, unknown>, bytes?: ArrayBuffer | ArrayBufferView) => {\n if (socket?.readyState !== openState) return false\n socket.send(bytes === undefined ? JSON.stringify(message) : encodeBinaryFrame(message, bytes))\n return true\n }\n\n return {\n /** Opens the socket, unless it is open or opening. */\n start: () => {\n wanted = true\n if (!socket && retry === undefined) void connect()\n },\n /** Closes the socket for good, until the next `start`. */\n stop: () => {\n wanted = false\n clearTimeout(retry)\n retry = undefined\n clearInterval(ping)\n const current = socket\n socket = undefined\n dropPending()\n current?.close(1000)\n },\n /** Sends a message with a ref, and bytes as its payload if any, and resolves with its reply, or rejects with its refusal. */\n request: (message: Record<string, unknown>, bytes?: ArrayBuffer | ArrayBufferView) =>\n new Promise<Extract<ServerMessage, { type: 'reply'; ok: true }>>((resolve, reject) => {\n const ref = String(++lastRef)\n if (!sendNow({ ...message, ref }, bytes)) return reject(new ChannelRefusal('disconnected', 'The connection is down'))\n pending.set(ref, { resolve, reject })\n }),\n /** Sends a message that gets no reply, and bytes as its payload if any; `false` when the socket is not open. */\n post: sendNow,\n }\n}\n\nexport type ChannelConnection = ReturnType<typeof channelConnection>\n","import type { KeyValue } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { isBytes } from './channel-binary-frame'\nimport { channelConnection, type ConnectionOptions } from './channel-connection'\nimport { ChannelRefusal, type ChannelMessage, type ChannelStatus, type PresenceChange, type PresenceEntry, type ServerMessage } from './channel-types'\n\n/** A record's channel as one caller of `client.channel` holds it; `leave` lets it go. */\nexport type Channel = {\n status: () => ChannelStatus\n /** Follows the status until the returned function is called. */\n onStatus: (listener: (status: ChannelStatus) => void) => () => void\n /** The channel's presence now: every connection on it that tracks a state, this one included. */\n presence: () => PresenceEntry[]\n /** Follows the presence until the returned function is called: the whole of it, and what changed when a diff did it. */\n onPresence: (listener: (entries: PresenceEntry[], change?: PresenceChange) => void) => () => void\n /** Tracks this connection's state on the channel, or replaces it; applied once joined, and again after a reconnect. */\n track: (state: unknown) => Promise<void>\n untrack: () => Promise<void>\n /**\n * Broadcasts to the others on the channel: a JSON payload, or bytes in an `ArrayBuffer` or typed array, which the\n * others hear as an `ArrayBuffer`. With `self` this connection hears it too. With `ack` it resolves once the server\n * took it, or rejects with its `ChannelRefusal`; without, once it was sent.\n */\n send: (event: string, payload: unknown, options?: { self?: boolean; ack?: boolean }) => Promise<void>\n /** Hears the channel's broadcasts of `event` until the returned function is called. */\n on: (event: string, listener: (message: ChannelMessage) => void) => () => void\n /** Lets the channel go; the connection leaves it once every holder did, and closes once it holds no channel. */\n leave: () => void\n}\n\n// One record's channel on the connection, shared by every holder of it.\ntype Joined = {\n resource: string\n key: string\n name?: string\n status: ChannelStatus\n presence: Map<string, PresenceEntry>\n tracked?: { state: unknown }\n holders: number\n statusListeners: Set<(status: ChannelStatus) => void>\n presenceListeners: Set<(entries: PresenceEntry[], change?: PresenceChange) => void>\n eventListeners: Map<string, Set<(message: ChannelMessage) => void>>\n}\n\n// A message cut off by a drop is sent again once the socket is back and the channel joined; any other refusal stays one.\nconst unlessDropped = (error: unknown) => {\n if (error instanceof ChannelRefusal && error.code === 'disconnected') return\n throw error\n}\n\nconst notJoined = () => new ChannelRefusal('not-joined', 'The channel is not joined yet')\n\n/**\n * The client's channels of records (`/api/channels`), all on one socket, opened with the first channel and closed\n * after the last. A dropped socket connects again by itself, joins every channel again and tracks their states again.\n */\nexport const channelsClient = (options: Omit<ConnectionOptions, 'onOpen' | 'onDown' | 'onMessage'>) => {\n const joined = new Map<string, Joined>()\n const byName = new Map<string, Joined>()\n\n const setStatus = (channel: Joined, status: ChannelStatus) => {\n channel.status = status\n for (const listener of channel.statusListeners) listener(status)\n }\n const tellPresence = (channel: Joined, change?: PresenceChange) => {\n const entries = [...channel.presence.values()]\n for (const listener of channel.presenceListeners) listener(entries, change)\n }\n\n const forget = (id: string) => {\n joined.delete(id)\n if (joined.size === 0) connection.stop()\n }\n\n // A channel every holder left while joining stays until its join is answered, so a new holder reuses it instead of\n // joining twice, and the connection leaves it once the server joined it.\n const join = (channel: Joined) => {\n const id = `${channel.resource}/${channel.key}`\n connection\n .request({ type: 'join', resource: channel.resource, key: channel.key })\n .then((reply) => {\n if (joined.get(id) !== channel) return\n if (channel.holders === 0) {\n connection.post({ type: 'leave', channel: reply.channel! })\n return forget(id)\n }\n channel.name = reply.channel!\n byName.set(channel.name, channel)\n setStatus(channel, { state: 'joined' })\n if (channel.tracked) void connection.request({ type: 'track', channel: channel.name, state: channel.tracked.state }).catch(unlessDropped)\n })\n .catch((error: unknown) => {\n if (joined.get(id) === channel && channel.holders === 0 && error instanceof ChannelRefusal) return forget(id)\n if (!(error instanceof ChannelRefusal) || error.code === 'disconnected') return unlessDropped(error)\n setStatus(channel, { state: 'refused', error: { code: error.code, message: error.message } })\n })\n }\n\n const hear = (message: ServerMessage) => {\n if (message.type === 'pong' || message.type === 'reply' || message.type === 'error') return\n const channel = byName.get(message.channel)\n if (!channel) return\n if (message.type === 'presence') {\n channel.presence = new Map(message.entries.map((entry) => [entry.id, entry]))\n return tellPresence(channel)\n }\n if (message.type === 'presence_diff') {\n for (const entry of message.leaves) channel.presence.delete(entry.id)\n for (const entry of [...message.joins, ...message.updates]) channel.presence.set(entry.id, entry)\n return tellPresence(channel, { joins: message.joins, updates: message.updates, leaves: message.leaves })\n }\n if (message.type === 'broadcast') {\n const { event, payload, user, server } = message\n for (const listener of channel.eventListeners.get(event) ?? []) listener({ event, payload, user, ...(server && { server }) })\n return\n }\n byName.delete(message.channel)\n channel.presence.clear()\n tellPresence(channel)\n setStatus(channel, { state: 'closed', error: message.error })\n }\n\n const connection = channelConnection({\n ...options,\n onOpen: () => {\n for (const [id, channel] of joined) {\n if (channel.status.state !== 'joining') continue\n if (channel.holders === 0) forget(id)\n else join(channel)\n }\n },\n onDown: () => {\n byName.clear()\n for (const channel of joined.values()) if (channel.status.state === 'joined') setStatus(channel, { state: 'joining' })\n },\n onMessage: hear,\n })\n\n const release = (id: string, channel: Joined) => {\n channel.holders -= 1\n if (channel.holders > 0) return\n channel.tracked = undefined\n if (channel.status.state === 'joining') return\n if (channel.name !== undefined) {\n byName.delete(channel.name)\n connection.post({ type: 'leave', channel: channel.name })\n }\n forget(id)\n }\n\n const handleOf = (id: string, channel: Joined): Channel => {\n let left = false\n const own = new Set<() => void>()\n const listen = <T>(set: Set<T>, listener: T) => {\n set.add(listener)\n const off = () => {\n set.delete(listener)\n own.delete(off)\n }\n own.add(off)\n return off\n }\n const joinedName = () => (channel.status.state === 'joined' ? channel.name : undefined)\n return {\n status: () => channel.status,\n onStatus: (listener) => listen(channel.statusListeners, listener),\n presence: () => [...channel.presence.values()],\n onPresence: (listener) => listen(channel.presenceListeners, listener),\n track: async (state) => {\n channel.tracked = { state }\n const name = joinedName()\n if (name !== undefined) await connection.request({ type: 'track', channel: name, state })\n },\n untrack: async () => {\n channel.tracked = undefined\n const name = joinedName()\n if (name !== undefined) await connection.request({ type: 'untrack', channel: name })\n },\n send: async (event, payload, { self, ack } = {}) => {\n const name = joinedName()\n if (name === undefined) throw notJoined()\n // Bytes go as a binary frame, the message without the payload its header.\n const bytes = isBytes(payload) ? payload : undefined\n const message = { type: 'send', channel: name, event, ...(bytes === undefined && { payload }), ...(self && { self }) }\n if (ack) {\n await connection.request({ ...message, ack }, bytes)\n return\n }\n if (!connection.post(message, bytes)) throw new ChannelRefusal('disconnected', 'The connection is down')\n },\n on: (event, listener) => {\n const listeners = channel.eventListeners.get(event) ?? new Set()\n channel.eventListeners.set(event, listeners)\n return listen(listeners, listener)\n },\n leave: () => {\n if (left) return\n left = true\n for (const off of [...own]) off()\n release(id, channel)\n },\n }\n }\n\n return {\n /** The channel of the record with this key, joined as soon as the socket is open. */\n channel: (resource: string, key: KeyValue | readonly KeyValue[]): Channel => {\n const encoded = encodeKey(key)\n const id = `${resource}/${encoded}`\n const existing = joined.get(id)\n if (existing) {\n existing.holders += 1\n return handleOf(id, existing)\n }\n const channel: Joined = { resource, key: encoded, status: { state: 'joining' }, presence: new Map(), holders: 1, statusListeners: new Set(), presenceListeners: new Set(), eventListeners: new Map() }\n joined.set(id, channel)\n connection.start()\n join(channel)\n return handleOf(id, channel)\n },\n }\n}\n","import { bridgeSocketPath } from '@protobase/schema/internal'\nimport type { SocketLike } from './channel-connection'\nimport type { Transport } from './transport'\n\n/** What a bridge function answers when asked for a token. */\ntype BridgeToken = { token: string; open_by: string; expires_at: string }\n\n/** An open bridge: its socket, which passes `ArrayBuffer`s both ways, and when the server closes it. */\nexport type OpenedBridge = { socket: WebSocket; expiresAt: Date }\n\nexport type BridgesInput = {\n send: Transport\n /** The `ws:` or `wss:` URL of a path below the API's system path, such as `/functions/console?token=…`. */\n socketUrl: (path: string) => string\n socket: (url: string, protocols: string[]) => SocketLike\n}\n\n/**\n * The app's TCP bridges, functions made with `tcpBridge` on the server: `open(name, target)` asks the function\n * `/api/functions/<name>` for a token to `target`, then opens the bridge's socket with it, binary as `ArrayBuffer`s.\n * A target the caller may not reach rejects with an `ApiError` of status 404. The server closes the socket at\n * `expiresAt`; open the bridge again for more.\n */\nexport const bridgesClient = ({ send, socketUrl, socket }: BridgesInput) => ({\n open: async (name: string, target: string): Promise<OpenedBridge> => {\n const path = `/functions/${encodeURIComponent(name)}`\n const response = await send({ method: 'POST', path, system: true, body: { target } })\n const { token, expires_at } = (await response.json()) as BridgeToken\n const opened = socket(socketUrl(bridgeSocketPath(path, token)), [])\n opened.binaryType = 'arraybuffer'\n return { socket: opened as unknown as WebSocket, expiresAt: new Date(expires_at) }\n },\n})\n","import { devicesPath } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\n\n/**\n * A browser's push subscription as it registers it: its endpoint and keys, what it is, and the user whose click\n * started the registration, which the server refuses with a 409 when someone else is signed in by then.\n */\nexport type WebDeviceRegistration = { kind: 'web'; endpoint: string; keys: { p256dh: string; auth: string }; userAgent?: string; userId?: string }\n\n/**\n * An Android app's FCM registration token as it registers it, with the user whose tap started the registration, which\n * the server refuses as for a browser.\n */\nexport type FcmDeviceRegistration = { kind: 'fcm'; token: string; userAgent?: string; userId?: string }\n\n/**\n * An iOS app's APNs device token as it registers it: lowercase hex, the APNs environment its build registered in and\n * its bundle id, the topic APNs sends to; the user as for a browser.\n */\nexport type ApnsDeviceRegistration = { kind: 'apns'; token: string; environment: 'sandbox' | 'production'; appId: string; userAgent?: string; userId?: string }\n\n/** A mobile app's handle from a push relay as it registers it, never its own push token; the user as for a browser. */\nexport type RelayDeviceRegistration = { kind: 'relay'; handle: string; userAgent?: string; userId?: string }\n\n/** A device as the server answers it: never its token or keys. */\nexport type RegisteredDevice = { id: string; kind: 'web' | 'apns' | 'fcm' | 'relay'; createdAt: string; lastSeenAt: string }\n\n/**\n * The signed-in user's own devices (`/api/notifications/devices`): `register` adds or refreshes the device the request\n * comes from, and rejects with an `ApiError` of slug `device-held` when another user holds the browser's endpoint or the\n * app's token, or\n * `other-user` when the user it names is not the one signed in; `remove` removes one by its id.\n */\nexport const devicesClient = (send: Transport) => ({\n register: async (device: WebDeviceRegistration | FcmDeviceRegistration | ApnsDeviceRegistration | RelayDeviceRegistration): Promise<RegisteredDevice> => (await send({ method: 'POST', path: devicesPath(''), system: true, body: device })).json() as Promise<RegisteredDevice>,\n remove: async (id: string) => {\n await send({ method: 'DELETE', path: devicesPath('', id), system: true })\n },\n})\n\nexport type DevicesClient = ReturnType<typeof devicesClient>\n","import { statusPath, type PersonStatus, type StatusInput } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\n\nexport type { Availability, PersonStatus, StatusInput } from '@protobase/schema/internal'\n\n/**\n * People's own status (`/api/status`), in an app with `status: {}`: `own` the signed-in person's, `set` replaces it\n * and answers it, `clear` removes it, and `people` the statuses of everyone who shares an organization with them, those\n * without one left out. A status past its clear time is none. `set` rejects with an `ApiError` of slug\n * `invalid-status-text` for a text with control characters or over `maxStatusText` characters, and\n * `own-sign-in-only` for staff signed in as the person.\n */\nexport const statusClient = (send: Transport) => ({\n own: async (): Promise<PersonStatus | null> => ((await (await send({ method: 'GET', path: statusPath(''), system: true })).json()) as { status: PersonStatus | null }).status,\n set: async (status: StatusInput): Promise<PersonStatus | null> => ((await (await send({ method: 'PUT', path: statusPath(''), system: true, body: status })).json()) as { status: PersonStatus | null }).status,\n clear: async () => {\n await send({ method: 'DELETE', path: statusPath(''), system: true })\n },\n people: async (): Promise<PersonStatus[]> => ((await (await send({ method: 'GET', path: statusPath('', 'people'), system: true })).json()) as { statuses: PersonStatus[] }).statuses,\n})\n\nexport type StatusClient = ReturnType<typeof statusClient>\n","import { workflowRunTracePath, type WorkflowRunTrace, type WorkflowTraceHeld } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\n\nexport type { WorkflowRunTrace, WorkflowTraceHeld, WorkflowTraceStep } from '@protobase/schema/internal'\n\n/**\n * A workflow run's trace (`/api/workflows/runs/<id>/trace`): the steps it ran so far, in order, with their input,\n * output and logs; none when the run keeps no trace. With the steps it `held`, only the steps after them while they are\n * still the trace's first, as `WorkflowRunTrace` says. Rejects with an `ApiError` for a caller who may not read the run\n * or its trace.\n */\nexport const workflowRunTraceClient = (send: Transport) => async (runId: string, held?: WorkflowTraceHeld): Promise<WorkflowRunTrace> =>\n (await send({ method: 'GET', path: workflowRunTracePath('', runId, held), system: true })).json() as Promise<WorkflowRunTrace>\n","import { workflowTypesPath, type WorkflowTypeList } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\n\nexport type { WorkflowTypeEntry, WorkflowTypeList } from '@protobase/schema/internal'\n\n/**\n * The app's workflow trigger and step types (`/api/workflows/types`), with the JSON Schema of each one's input, in an\n * app with workflows: the graph editor draws its menus and forms from them. Rejects with an `ApiError` for a caller who\n * may not read workflows.\n */\nexport const workflowTypesClient = (send: Transport) => async (): Promise<WorkflowTypeList> =>\n (await send({ method: 'GET', path: workflowTypesPath(''), system: true })).json() as Promise<WorkflowTypeList>\n","import { runnerRegistrationPath, type RunnerRegistration } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\n\nexport type { RunnerRegistration } from '@protobase/schema/internal'\n\n/**\n * Issues a runner that never registered a new one-time registration token (`POST /api/workflows/runners/<id>/registration`),\n * valid one hour, which replaces the one issued before: `{ token, expires_at, command, endpoint }`, shown this once, with\n * the one command that installs the runner on a machine. Rejects with an `ApiError` for a caller who may not change the\n * runner (404), or a runner that registered or was revoked (409).\n */\nexport const runnerRegistrationClient = (send: Transport) => async (runner: string): Promise<RunnerRegistration> =>\n (await send({ method: 'POST', path: runnerRegistrationPath('', runner), system: true })).json() as Promise<RunnerRegistration>\n","import { historyPath } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\n\n/**\n * One of the signed-in user's inbox notifications, as the server answers it: `title` and `body` are plain text, `url` a\n * path on the app or an absolute URL on one of its origins, or `null`; `readAt` is `null` while it is unread.\n */\nexport type InboxNotification = { id: string; title: string; body: string | null; url: string | null; data: Record<string, unknown> | null; createdAt: string; readAt: string | null }\n\n/** A page of the history, newest first; `next` is the cursor of the page after it, `null` on the last one. */\nexport type InboxPage = { items: InboxNotification[]; next: string | null }\n\n/**\n * The signed-in user's own notification history (`/api/notifications/history`): `list` a page of it, `unread` how many\n * are unread (at most 100), `markRead` one of them by its id, and `markAllRead` those created up to `upTo`, the\n * `createdAt` of the newest one the user was shown.\n */\nexport const notificationHistoryClient = (send: Transport) => ({\n list: async ({ cursor, limit }: { cursor?: string; limit?: number } = {}): Promise<InboxPage> => {\n const params = new URLSearchParams({ ...(cursor !== undefined && { cursor }), ...(limit !== undefined && { limit: String(limit) }) })\n const query = params.size > 0 ? `?${params}` : ''\n return (await send({ method: 'GET', path: historyPath(''), query, system: true })).json() as Promise<InboxPage>\n },\n unread: async (): Promise<number> => ((await (await send({ method: 'GET', path: historyPath('', 'unread'), system: true })).json()) as { count: number }).count,\n markRead: async (id: string) => {\n await send({ method: 'POST', path: historyPath('', { read: id }), body: {}, system: true })\n },\n markAllRead: async (upTo: string) => {\n await send({ method: 'POST', path: historyPath('', 'read'), body: { upTo }, system: true })\n },\n})\n\nexport type NotificationHistoryClient = ReturnType<typeof notificationHistoryClient>\n","import type { KeyValue } from '@protobase/schema'\nimport { readEventStream } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\nimport type { ResourceRef } from './types'\n\n/** A call on a record, as its readers see it: who started it, when, when it ended, who is in it and who was removed. */\nexport type RecordCall = {\n id: string\n started_by: string\n started_at: string\n /** `null` while it goes on. */\n ended_at: string | null\n members: { member: string; joined_at: string }[]\n removed: { member: string; removed_at: string }[]\n}\n\nexport type RecordCallsHandlers = {\n /** The record's latest calls, newest first, the one going on first: at once, then whenever they change. */\n onCalls: (calls: RecordCall[]) => void\n /** The stream failed, with why, or ended (`undefined`); it is followed again after a pause. */\n onRetry?: (error: unknown) => void\n}\n\ntype Key = KeyValue | readonly KeyValue[]\n\nconst backoff = (attempt: number) => Math.min(30_000, 1000 * 2 ** attempt)\n\nconst pause = (ms: number, signal: AbortSignal) =>\n new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms)\n signal.addEventListener('abort', () => {\n clearTimeout(timer)\n resolve()\n }, { once: true })\n })\n\n/** A record's calls, for whoever may read the record (`GET /api/{resource}/{key}:calls`). `path` names the record's calls. */\nexport const recordCallsClient = (send: Transport, path: (resource: ResourceRef, key: Key) => string, retryDelay: (attempt: number) => number = backoff) => ({\n /** The record's latest calls, newest first, the one going on first. */\n calls: async (resource: ResourceRef, key: Key): Promise<RecordCall[]> => ((await (await send({ method: 'GET', path: path(resource, key) })).json()) as { items: RecordCall[] }).items,\n /** Follows the record's calls until the returned function is called; a stream that ends or fails is followed again. */\n watchCalls: (resource: ResourceRef, key: Key, handlers: RecordCallsHandlers) => {\n const controller = new AbortController()\n const { signal } = controller\n let failures = 0\n const follow = async () => {\n const response = await send({ method: 'GET', path: path(resource, key), query: '?watch=true', headers: { accept: 'text/event-stream' }, signal })\n if (!response.body) throw new Error('The server answered the calls stream without a body')\n await readEventStream(response.body, (data) => {\n failures = 0\n handlers.onCalls((JSON.parse(data) as { items: RecordCall[] }).items)\n }, signal)\n }\n void (async () => {\n while (!signal.aborted) {\n const error = await follow().then(() => undefined, (reason: unknown) => reason)\n if (signal.aborted) return\n handlers.onRetry?.(error)\n await pause(retryDelay(failures++), signal)\n }\n })()\n return () => controller.abort()\n },\n})\n","import { ringsPath, type CallRing } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\n\nexport type { CallRing } from '@protobase/schema/internal'\n\n/**\n * The calls that ring the signed-in user (`/api/calls/rings`), in an app with calls: `list` those ringing them now,\n * newest first, and `decline` stops one ringing them on every page they have open. Joining the call stops it too.\n */\nexport const ringsClient = (send: Transport) => ({\n list: async (): Promise<CallRing[]> => ((await (await send({ method: 'GET', path: ringsPath(''), system: true })).json()) as { items: CallRing[] }).items,\n decline: async (call: string) => {\n await send({ method: 'POST', path: ringsPath('', { decline: call }), system: true, body: {} })\n },\n})\n\nexport type RingsClient = ReturnType<typeof ringsClient>\n","import { guestCallsPath } from '@protobase/schema/internal'\nimport type { Transport } from './transport'\n\n/**\n * Whether the calls of the organization the signed-in user works in take guests (`/api/calls/guests/organization`):\n * `allowed` for any member, `setAllowed` for its owner or an admin. Turning them off revokes every guest link of its\n * calls and takes their guests out at once.\n */\nexport const callGuestsClient = (send: Transport) => ({\n allowed: async () => ((await (await send({ method: 'GET', path: guestCallsPath('', 'organization'), system: true })).json()) as { allowed: boolean }).allowed,\n setAllowed: async (allowed: boolean) => {\n await send({ method: 'PUT', path: guestCallsPath('', 'organization'), system: true, body: { allowed } })\n },\n})\n\nexport type CallGuestsClient = ReturnType<typeof callGuestsClient>\n","import type { KeyValue } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { labelEntries, listWire, photosWire, queryString, filterText, type FilterInput, type ListParams, type MapParams } from './query-string'\nimport { originOf, photosWithOrigin, withFileOrigin } from './file-urls'\nimport { createTransport, systemUrlOf, type CacheMode, type ClientOptions } from './transport'\nimport { fileReadUrl } from './file-read-url'\nimport { fetchWithProgress, type UploadProgress } from './upload-request'\nimport { followLive, type LiveHandlers } from './live'\nimport { sharedLive } from './shared-live'\nimport { channelsClient } from './channels'\nimport { bridgesClient } from './bridges'\nimport type { SocketLike } from './channel-connection'\nimport { devicesClient } from './devices'\nimport { statusClient } from './status'\nimport { workflowRunTraceClient } from './workflow-trace'\nimport { workflowTypesClient } from './workflow-types'\nimport { runnerRegistrationClient } from './runner-registration'\nimport { notificationHistoryClient } from './notification-history'\nimport { recordCallsClient } from './record-calls'\nimport { ringsClient } from './rings'\nimport { callGuestsClient } from './call-guests'\nimport type { Aggregate, AggregateParams, BatchOp, BatchResult, CommentPage, Facet, FormChallenge, FormProof, Histogram, HistoryChange, HistoryPage, ListPage, MapResult, MentionableUser, Meta, MetaResult, PublicForm, RecordComment, RecordOf, ResourceRef, Series, SeriesParams, Stored } from './types'\n\ntype Json = Record<string, any>\n\n// A proxy in front of an API refuses a long URL with a 431, and the headers count too, so a longer list goes by `:search`.\nconst longestListQuery = 4_000\n\nconst nameOf = (resource: ResourceRef) => (typeof resource === 'string' ? resource : resource.toModel().name)\n\n// `/api/channels` beside the API, as a WebSocket URL on the API's origin, the page's for a relative one.\n// The socket URL of a path below the API's system path, which is the base URL without its last segment (`/api`).\nconst systemSocketUrl = (baseUrl = '/api/v1', path: string) => {\n const url = new URL(`${baseUrl.replace(/\\/[^/]*$/, '')}${path}`, globalThis.location?.href)\n url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'\n return url.toString()\n}\n\nconst keyPath = (resource: ResourceRef, key: KeyValue | readonly KeyValue[]) => `/${nameOf(resource)}/${encodeKey(key)}`\n\n/** Where a record's calls are read and followed. */\nexport const callsPath = (resource: ResourceRef, key: KeyValue | readonly KeyValue[]) => `${keyPath(resource, key)}:calls`\n\nconst toPage = <T>(body: Json, response: Response, origin: string | undefined): ListPage<T> => ({\n items: (body.items as T[]).map((item) => withFileOrigin(item, origin)),\n nextPageToken: body.next_page_token,\n totalSizeEstimate: body.total_size_estimate,\n ...(body.prev_page_token !== undefined && { prevPageToken: body.prev_page_token }),\n ...(body.total_size !== undefined && { totalSize: body.total_size }),\n ...(body.labels !== undefined && { labels: body.labels }),\n ...(body.photos !== undefined && { photos: photosWithOrigin(body.photos, origin) }),\n ...(response.headers.get('x-protobase-warning') && { warning: response.headers.get('x-protobase-warning')! }),\n})\n\n/** How `invoke` calls a function: GET without a body, POST with one, unless `method` says otherwise. */\nexport type InvokeOptions = {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n /** Sent as JSON. */\n body?: unknown\n /** Below the function, such as `/42` for `/api/functions/<name>/42`. */\n path?: string\n query?: Record<string, string>\n headers?: Record<string, string>\n /** How the browser's HTTP cache treats the call, such as `no-store` so another user of the browser never gets the answer. */\n cache?: CacheMode\n}\n\n/** What `upload` answers: `value` is the ticket to send as the field's value in a create, update or batch write. */\nexport type UploadResult = {\n value: string\n /** The type is the one detected from the content. */\n file: { name: string; type: string; size: number }\n /** Values the field's processors computed for other fields; the write stores them with the file. */\n derived: Record<string, unknown>\n /** Set when the content's type differs from what the name or browser said: `photo.png` that is a JPEG. */\n corrected?: { from: string; to: string }\n}\n\nexport type UploadOptions = {\n /** Reports bytes sent; uses XMLHttpRequest where there is one, since fetch reports no upload progress. */\n onProgress?: UploadProgress\n signal?: AbortSignal\n}\n\n// A comment as the API sends it, its time in snake_case.\ntype CommentWire = Omit<RecordComment, 'createdAt'> & { created_at: string }\nconst commentOf = ({ created_at, ...comment }: CommentWire): RecordComment => ({ ...comment, createdAt: created_at })\n\nconst etagOf = (response: Response) => response.headers.get('etag') ?? ''\n\n/** A single-record response: the record without its `permissions` member, which travels beside it. */\nconst storedOf = async <T>(response: Response, origin: string | undefined): Promise<Stored<T>> => {\n const { permissions, ...record } = await response.json()\n return { record: withFileOrigin(record as T, origin), etag: etagOf(response), ...(permissions && { permissions }) }\n}\n\n// The records of a batch's results, each file downloading from the API's origin.\nconst batchResultOf = (body: Partial<BatchResult>, origin: string | undefined): BatchResult => ({\n results: (body.results ?? []).map((result) => {\n if (result.op === 'create' || result.op === 'update') return { ...result, record: withFileOrigin(result.record, origin) }\n if (result.op === 'reorder' || result.op === 'move') return { ...result, records: result.records.map((entry) => ({ ...entry, record: withFileOrigin(entry.record, origin) })) }\n return result\n }),\n})\n\n/**\n * The client of one API. With an absolute `baseUrl`, the URL of each file in a record it answers is absolute too, on\n * that API's origin; with a path, it stays the path the API answers.\n */\nexport const createClient = (options: ClientOptions = {}) => {\n const send = createTransport(options)\n const origin = originOf(options.baseUrl)\n\n /** Same as `list`, with the parameters in a JSON body, for long filters. */\n const search = async <R extends ResourceRef>(resource: R, params?: ListParams) => {\n const wire = listWire(params)\n const response = await send({\n method: 'POST',\n path: `/${nameOf(resource)}:search`,\n body: { ...wire, fields: params?.fields, labels: labelEntries(params?.labels) },\n })\n return toPage<RecordOf<R>>(await response.json(), response, origin)\n }\n\n const list = async <R extends ResourceRef>(resource: R, params?: ListParams) => {\n const query = queryString(listWire(params))\n if (query.length > longestListQuery) return search(resource, params)\n const response = await send({ method: 'GET', path: `/${nameOf(resource)}`, query })\n return toPage<RecordOf<R>>(await response.json(), response, origin)\n }\n\n const get = async <R extends ResourceRef>(resource: R, key: KeyValue | readonly KeyValue[]): Promise<Stored<RecordOf<R>>> => {\n return storedOf(await send({ method: 'GET', path: keyPath(resource, key) }), origin)\n }\n\n const create = async <R extends ResourceRef>(resource: R, body: Partial<RecordOf<R>>): Promise<Stored<RecordOf<R>> & { location: string }> => {\n const response = await send({ method: 'POST', path: `/${nameOf(resource)}`, body })\n return { record: withFileOrigin(await response.json(), origin), etag: etagOf(response), location: response.headers.get('location') ?? '' }\n }\n\n /** `etag` is what `get` returned; a stale one rejects with `PreconditionFailedError`. */\n const update = async <R extends ResourceRef>(\n resource: R,\n key: KeyValue | readonly KeyValue[],\n patch: Partial<RecordOf<R>>,\n etag: string,\n ): Promise<Stored<RecordOf<R>>> => {\n return storedOf(await send({ method: 'PATCH', path: keyPath(resource, key), body: patch, headers: { 'if-match': etag } }), origin)\n }\n\n /** `etag` is the version the user saw (`*` for any); a stale one rejects with `PreconditionFailedError`. */\n const remove = async (resource: ResourceRef, key: KeyValue | readonly KeyValue[], { etag }: { etag?: string } = {}) => {\n await send({ method: 'DELETE', path: keyPath(resource, key), headers: etag ? { 'if-match': etag } : undefined })\n }\n\n /** AIP-164: brings a soft-deleted record back. A record that is not deleted answers 409. */\n const undelete = async <R extends ResourceRef>(resource: R, key: KeyValue | readonly KeyValue[]): Promise<Stored<RecordOf<R>>> => {\n const response = await send({ method: 'POST', path: `${keyPath(resource, key)}:undelete` })\n return { record: withFileOrigin(await response.json(), origin), etag: etagOf(response) }\n }\n\n /** The value of a sensitive field of one record, which the record itself never carries. The server audits every call. */\n const reveal = async (resource: ResourceRef, key: KeyValue | readonly KeyValue[], field: string): Promise<unknown> => {\n const response = await send({ method: 'POST', path: `${keyPath(resource, key)}:reveal`, body: { field } })\n return ((await response.json()) as { value: unknown }).value\n }\n\n /**\n * Runs the record's AI action `action` (`a.ai`): the model writes the action's field from its prompt, as the caller.\n * Resolves to the record as written; a record changed while the model answered rejects with `PreconditionFailedError`.\n */\n const generate = async <R extends ResourceRef>(resource: R, key: KeyValue | readonly KeyValue[], action: string): Promise<Stored<RecordOf<R>>> =>\n storedOf(await send({ method: 'POST', path: `${keyPath(resource, key)}:generate`, body: { action } }), origin)\n\n /** A page of a record's changes, newest first, for a resource with `.history()`; `pageToken` is the previous page's `nextPageToken`. */\n const history = async (resource: ResourceRef, key: KeyValue | readonly KeyValue[], { pageSize, pageToken }: { pageSize?: number; pageToken?: string } = {}): Promise<HistoryPage> => {\n const query = queryString({ page_size: pageSize, page_token: pageToken || undefined })\n const body = (await (await send({ method: 'GET', path: `${keyPath(resource, key)}:history`, query })).json()) as { items: Array<Omit<HistoryChange, 'databaseRole'> & { database_role: string | null }>; next_page_token: string }\n return { items: body.items.map(({ database_role, ...change }) => ({ ...change, databaseRole: database_role })), nextPageToken: body.next_page_token }\n }\n\n /** A page of a record's comments, newest first, for a resource with `.comments()`; `pageToken` is the previous page's `nextPageToken`. */\n const comments = async (resource: ResourceRef, key: KeyValue | readonly KeyValue[], { pageSize, pageToken }: { pageSize?: number; pageToken?: string } = {}): Promise<CommentPage> => {\n const query = queryString({ page_size: pageSize, page_token: pageToken || undefined })\n const body = (await (await send({ method: 'GET', path: `${keyPath(resource, key)}:comments`, query })).json()) as { items: CommentWire[]; next_page_token: string }\n return { items: body.items.map(commentOf), nextPageToken: body.next_page_token }\n }\n\n /** Adds the caller's comment to a record, mentioning the users `mentions` names, who are emailed a link to it. */\n const comment = async (resource: ResourceRef, key: KeyValue | readonly KeyValue[], { body, mentions = [] }: { body: string; mentions?: string[] }): Promise<RecordComment> =>\n commentOf((await (await send({ method: 'POST', path: `${keyPath(resource, key)}:comments`, body: { body, mentions } })).json()) as CommentWire)\n\n /** The users a comment on a record may mention whose name contains `query`, at most 8, by name. */\n const mentionable = async (resource: ResourceRef, key: KeyValue | readonly KeyValue[], query: string): Promise<MentionableUser[]> => {\n const body = (await (await send({ method: 'GET', path: `${keyPath(resource, key)}:mentionable`, query: queryString({ q: query }) })).json()) as { items: MentionableUser[] }\n return body.items\n }\n\n /** Applies several writes atomically (`POST /api/v1:batchWrite`), for example a record and its lines on Save. */\n const batchWrite = async (ops: BatchOp[]): Promise<BatchResult> => {\n const keyText = (key: unknown) => (typeof key === 'object' && key !== null && '$ref' in key ? key : encodeKey(key as KeyValue | readonly KeyValue[]))\n const wireOps = ops.map((operation) => ({\n ...operation,\n resource: nameOf(operation.resource),\n ...('key' in operation && { key: keyText(operation.key) }),\n ...(operation.op === 'reorder' && { keys: operation.keys.map(keyText) }),\n ...(operation.op === 'move' && { after: operation.after && keyText(operation.after), ...(operation.before !== undefined && { before: operation.before && keyText(operation.before) }) }),\n }))\n const response = await send({ method: 'POST', path: ':batchWrite', body: { ops: wireOps } })\n return batchResultOf((await response.json()) as Partial<BatchResult>, origin)\n }\n\n /** `label` names a relation's values by that field of the records they point at, as a list's `labels` does. */\n const facets = async (resource: ResourceRef, field: string, o: { filter?: FilterInput; limit?: number; label?: string } = {}) => {\n const response = await send({\n method: 'GET',\n path: `/${nameOf(resource)}:facets`,\n query: queryString({ field, filter: filterText(o.filter) || undefined, limit: o.limit, label: o.label }),\n })\n return ((await response.json()) as { facets: Facet[] }).facets\n }\n\n /** Totals per value of a field, or per bucket of a date field (`:aggregate`). */\n const aggregate = async (resource: ResourceRef, params: AggregateParams): Promise<Aggregate> => {\n const response = await send({\n method: 'GET',\n path: `/${nameOf(resource)}:aggregate`,\n query: queryString({\n group_by: params.groupBy,\n filter: filterText(params.filter) || undefined,\n sum: params.sum,\n average: params.average,\n maximum: params.maximum,\n limit: params.limit,\n label: params.label,\n granularity: params.granularity,\n range: params.range,\n from: params.from,\n to: params.to,\n time_zone: params.timeZone,\n split_by: params.splitBy,\n split_limit: params.splitLimit,\n split_label: params.splitLabel,\n }),\n })\n const body = await response.json()\n return {\n groupBy: body.group_by,\n granularity: body.granularity,\n timeZone: body.time_zone,\n groups: body.groups,\n ...(body.split_by !== undefined && { splitBy: body.split_by, splits: body.splits }),\n }\n }\n\n const series = async (resource: ResourceRef, params: SeriesParams & { filter?: FilterInput }): Promise<Series> => {\n const response = await send({\n method: 'GET',\n path: `/${nameOf(resource)}:series`,\n query: queryString({\n field: params.field,\n range: params.range,\n from: params.from,\n to: params.to,\n granularity: params.granularity,\n time_zone: params.timeZone,\n filter: filterText(params.filter) || undefined,\n }),\n })\n const body = await response.json()\n return { field: body.field, granularity: body.granularity, timeZone: body.time_zone, points: body.points }\n }\n\n const histogram = async (resource: ResourceRef, field: string, o: { filter?: FilterInput; buckets?: number } = {}): Promise<Histogram> => {\n const response = await send({\n method: 'GET',\n path: `/${nameOf(resource)}:histogram`,\n query: queryString({ field, buckets: o.buckets, filter: filterText(o.filter) || undefined }),\n })\n return response.json()\n }\n\n /**\n * The records in a map's view, its bounding box being part of `filter`: the records themselves when few match or the\n * map is close, else buckets of them on a grid sized for `zoom`.\n */\n const map = async <R extends ResourceRef>(resource: R, params: MapParams): Promise<MapResult<RecordOf<R>>> => {\n const response = await send({\n method: 'GET',\n path: `/${nameOf(resource)}:map`,\n query: queryString({\n latitude: params.latitude,\n longitude: params.longitude,\n zoom: params.zoom,\n filter: filterText(params.filter) || undefined,\n order_by: params.orderBy,\n fields: params.fields?.join(','),\n labels: labelEntries(params.labels)?.join(','),\n ...photosWire(params.photos),\n }),\n })\n const body = await response.json()\n return {\n items: (body.items as RecordOf<R>[]).map((item) => withFileOrigin(item, origin)),\n buckets: body.buckets,\n totalSize: body.total_size,\n ...(body.labels !== undefined && { labels: body.labels }),\n ...(body.photos !== undefined && { photos: photosWithOrigin(body.photos, origin) }),\n }\n }\n\n /** The page that starts at row `position` of a sort (scrollbar jumps), with the tokens of its own neighbours. Past the end it is empty. */\n const seek = async <R extends ResourceRef>(resource: R, params: ListParams & { position: number }) => {\n const response = await send({ method: 'GET', path: `/${nameOf(resource)}:seek`, query: queryString({ ...listWire(params), position: params.position }) })\n return toPage<RecordOf<R>>(await response.json(), response, origin)\n }\n\n /** Pass the `etag` of the last result to get `{ status: 'unchanged' }` on a `304`; `signal` gives up waiting. */\n const meta = async (etag?: string, { signal }: { signal?: AbortSignal } = {}): Promise<MetaResult> => {\n const response = await send({ method: 'GET', path: '/meta', system: true, headers: etag ? { 'if-none-match': etag } : undefined, accept: [304], ...(signal && { signal }) })\n if (response.status === 304) return { status: 'unchanged' }\n return { status: 'modified', meta: (await response.json()) as Meta, etag: etagOf(response) }\n }\n\n /**\n * Calls one of the app's API functions, `/api/functions/<name>`, with the user's token. Resolves to its answer: parsed\n * JSON, text for `text/*` or no content type, a `Blob` of any other type (a PDF, an image), or `undefined` for a 204.\n * A problem rejects as from any other call.\n */\n const invoke = async <T = unknown>(name: string, { method, body, path = '', query, headers, cache }: InvokeOptions = {}): Promise<T> => {\n const response = await send({\n method: method ?? (body === undefined ? 'GET' : 'POST'),\n path: `/functions/${encodeURIComponent(name)}${path}`,\n query: query ? `?${new URLSearchParams(query)}` : '',\n body,\n headers,\n system: true,\n ...(cache && { cache }),\n })\n if (response.status === 204) return undefined as T\n const type = response.headers.get('content-type')\n if (type?.includes('json')) return response.json() as Promise<T>\n if (!type || type.startsWith('text/')) return response.text() as Promise<T>\n return response.blob() as Promise<T>\n }\n\n /**\n * Uploads a file for a file field (`POST /{resource}:upload`). Send `value` of the result as the field's value in a\n * create, update or batch write within 24 hours; the server detects the type and refuses one the field does not take.\n */\n const upload = async (resource: ResourceRef, field: string, file: Blob, { onProgress, signal }: UploadOptions = {}): Promise<UploadResult> => {\n const name = 'name' in file && typeof file.name === 'string' ? file.name : undefined\n const progress = onProgress && typeof XMLHttpRequest !== 'undefined' ? fetchWithProgress(onProgress) : undefined\n const response = await send({\n method: 'POST',\n path: `/${nameOf(resource)}:upload`,\n query: `?${new URLSearchParams({ field, ...(name !== undefined && { name }) })}`,\n raw: file,\n headers: { 'content-type': file.type || 'application/octet-stream' },\n ...(progress && { via: progress }),\n ...(signal && { signal }),\n })\n const result = (await response.json()) as UploadResult\n onProgress?.(file.size, file.size)\n return result\n }\n\n // Public forms live beside the API and need no token: anyone may send one.\n const formPath = (name: string) => `/forms/${encodeURIComponent(name)}`\n\n /** The public form `name` (`GET /api/forms/<name>`): its fields as `/meta` would give them, its title and thanks text. */\n const form = async (name: string): Promise<PublicForm> => (await send({ method: 'GET', path: formPath(name), system: true })).json()\n\n /** A fresh bot check for the public form `name`, to solve with `altcha-lib`'s `solveChallenge` before sending it. */\n const formChallenge = async (name: string): Promise<FormChallenge> => (await send({ method: 'GET', path: `${formPath(name)}:challenge`, system: true })).json()\n\n /**\n * Sends the public form `name`: creates its record from `values`, with the solved bot check. Rejects with `ApiError`\n * as a create does, a refused check as `bot-check-failed` and too many submissions as `too-many-submissions`.\n */\n const submitForm = async (name: string, values: Record<string, unknown>, proof: FormProof): Promise<void> => {\n await send({ method: 'POST', path: formPath(name), body: { values, proof }, system: true })\n }\n\n /**\n * Hears which records of the `.live()` resources the caller may read change, as they do, until the returned function\n * is called (`GET /api/live`); it connects again by itself.\n */\n const live = sharedLive((handlers: LiveHandlers) => followLive(send, handlers))\n\n /**\n * The channel of a record (`/api/channels`): who else is on it and what they track (presence), and the events they\n * send (broadcasts), for whoever may read the record. Every channel of the client shares one socket.\n */\n const openSocket = options.webSocket ?? ((url: string, protocols: string[]) => new WebSocket(url, protocols) as unknown as SocketLike)\n const { channel } = channelsClient({\n url: () => systemSocketUrl(options.baseUrl, '/channels'),\n ...(options.token && { token: () => options.token!({ refresh: false }) }),\n socket: openSocket,\n retryDelay: (attempt) => Math.min(30_000, 1000 * 2 ** attempt),\n })\n\n /** The app's TCP bridges, to services only its server reaches, over a WebSocket each (see `bridgesClient`). */\n const bridges = bridgesClient({ send, socketUrl: (path) => systemSocketUrl(options.baseUrl, path), socket: openSocket })\n\n /** The signed-in user's own devices, where they receive push (see `devicesClient`). */\n const devices = devicesClient(send)\n\n /** The signed-in user's own notification history, their inbox (see `notificationHistoryClient`). */\n const notifications = notificationHistoryClient(send)\n\n /** A record's calls, live with `watchCalls`, for whoever may read the record (see `recordCallsClient`). */\n const { calls, watchCalls } = recordCallsClient(send, callsPath)\n\n /** People's own status, and that of those who share an organization with the signed-in person (see `statusClient`). */\n const status = statusClient(send)\n\n /** The app's workflow trigger and step types, each with its input's JSON Schema (see `workflowTypesClient`). */\n const workflowTypes = workflowTypesClient(send)\n\n /** A workflow run's trace, the steps it ran with their input, output and logs (see `workflowRunTraceClient`). */\n const workflowRunTrace = workflowRunTraceClient(send)\n\n /** A runner's new one-time registration token, with the command that installs it (see `runnerRegistrationClient`). */\n const runnerRegistration = runnerRegistrationClient(send)\n\n /** The calls that ring the signed-in user, and declining one (see `ringsClient`). */\n const rings = ringsClient(send)\n\n /** Whether the calls of the organization the signed-in user works in take guests (see `callGuestsClient`). */\n const callGuests = callGuestsClient(send)\n\n /** Where a page reads the bytes of a file of `resource` with `fetch`, from this API's own origin (see `fileReadUrl`). */\n const readUrl = (_resource: ResourceRef, file: { uri: string; url: string }) => fileReadUrl(file, systemUrlOf(options.baseUrl))\n\n return { list, search, get, create, update, remove, undelete, generate, reveal, history, comments, comment, mentionable, batchWrite, facets, aggregate, series, histogram, map, seek, meta, invoke, upload, form, formChallenge, submitForm, live, channel, bridges, devices, notifications, status, calls, watchCalls, rings, callGuests, workflowTypes, workflowRunTrace, runnerRegistration, fileReadUrl: readUrl }\n}\n\nexport type Client = ReturnType<typeof createClient>\n","import { createContext, useContext, useEffect } from 'react'\n\n/**\n * Whether the data on screen refetches when the window regains focus: always, unless a form on screen holds unsaved\n * changes. A refetch under such a form would hand it a newer version of the record without the changes it was edited\n * from, so its Save would no longer find a conflict.\n */\nexport const createFocusRefresh = () => {\n let paused = 0\n return {\n refetchOnWindowFocus: () => (paused > 0 ? false : ('always' as const)),\n /** Whether a form on screen holds unsaved changes, so its record must not be read again under it. */\n paused: () => paused > 0,\n /** Holds the refetches until the returned function is called. */\n pause: () => {\n paused += 1\n let released = false\n return () => {\n if (released) return\n released = true\n paused -= 1\n }\n },\n }\n}\n\nexport type FocusRefresh = ReturnType<typeof createFocusRefresh>\n\nexport const FocusRefreshContext = createContext<FocusRefresh | null>(null)\n\n/** Holds the app's refetches on window focus while `paused`, such as while a form has unsaved changes. */\nexport const usePauseFocusRefresh = (paused: boolean) => {\n const refresh = useContext(FocusRefreshContext)\n useEffect(() => (paused && refresh ? refresh.pause() : undefined), [paused, refresh])\n}\n\n/**\n * Tells TanStack Query the window regained focus on a return to the browser tab, as by default, and on a return to the\n * browser window from another program, which leaves the tab visible.\n */\nexport const listenToWindowFocus = (onFocus: (focused?: boolean) => void) => {\n const listener = () => onFocus()\n window.addEventListener('visibilitychange', listener, false)\n window.addEventListener('focus', listener, false)\n return () => {\n window.removeEventListener('visibilitychange', listener)\n window.removeEventListener('focus', listener)\n }\n}\n","import type { PlanRead } from '@protobase/layout'\n\nexport const keys = {\n meta: ['meta'] as const,\n /** A source's `/meta`, as far as the app draws it: its URL, and the resources the app lists for it. */\n sourceMeta: (url: string, resources: readonly string[]) => ['source-meta', url, resources.join(',')] as const,\n /** Every `/meta` query of the source at `url`. */\n sourceMetas: (url: string) => ['source-meta', url] as const,\n list: (resource: string, filter: string, orderBy: string, pageSize: number, startToken: string) =>\n ['list', resource, filter, orderBy, pageSize, startToken] as const,\n page: (resource: string, filter: string, orderBy: string, pageSize: number, page: number) =>\n ['page', resource, filter, orderBy, pageSize, page] as const,\n /** Every `page` of one list. */\n pages: (resource: string, filter: string, orderBy: string) => ['page', resource, filter, orderBy] as const,\n /** A sidebar group's records; starts with `list`, so invalidating a resource's lists refreshes it too. */\n navRecent: (resource: string, filter: string, orderBy: string, pageSize: number) => ['list', resource, filter, orderBy, pageSize, 'nav-recent'] as const,\n first: (resource: string, filter: string, orderBy: string) => ['first-page', resource, filter, orderBy] as const,\n record: (resource: string, key: string) => ['record', resource, key] as const,\n /** The picture an API function draws for an `Image` block, at a size and theme. */\n image: (name: string, query: Record<string, string>) => ['image', name, query] as const,\n /** What a list row knows of a record, which its page shows until the record has loaded. */\n recordPreview: (resource: string, key: string) => ['record-preview', resource, key] as const,\n /** A record's changes; starts with `record`, so refreshing the record refreshes them too. */\n history: (resource: string, key: string, pageSize: number) => ['record', resource, key, 'history', pageSize] as const,\n /** A record's comments; starts with `record`, so refreshing the record refreshes them too. */\n comments: (resource: string, key: string) => ['record', resource, key, 'comments'] as const,\n /** The people a comment on a record may mention whose name contains `query`. */\n facets: (resource: string, field: string, filter: string) => ['facets', resource, field, filter] as const,\n series: (resource: string, field: string, range: string, granularity: string, filter: string) =>\n ['series', resource, field, range, granularity, filter] as const,\n aggregate: (resource: string, params: string) => ['aggregate', resource, params] as const,\n histogram: (resource: string, field: string, buckets: number, filter: string) => ['histogram', resource, field, buckets, filter] as const,\n /** The records or buckets a map shows; `filter` holds its bounding box. */\n map: (resource: string, position: string, zoom: number, filter: string, orderBy: string) => ['map', resource, position, zoom, filter, orderBy] as const,\n relatedLabel: (resource: string, id: string) => ['related-label', resource, id] as const,\n /** The fields a record pointed at is read with for its view to derive its title. */\n titleRow: (resource: string, id: string, fields: string) => ['title-row', resource, id, fields] as const,\n labels: (resource: string, ids: string) => ['labels', resource, ids] as const,\n /** The names of the records a `RecordPicker` holds. */\n pickedLabels: (resource: string, ids: string) => ['picked-labels', resource, ids] as const,\n count: (resource: string, filter: string) => ['count', resource, filter] as const,\n /**\n * A read of a page's read plan, as its address filled it, and every resource it reads: its own, then those of the\n * reads its `related()` terms carry.\n */\n planRead: (resources: readonly string[], read: PlanRead) => ['plan', resources[0]!, resources, read] as const,\n /** How many rows an export of the list would hold, exactly up to 10,000; starts with `list`, so it refreshes with the list. */\n exportCount: (resource: string, filter: string) => ['list', resource, filter, 'export-count'] as const,\n firstRecord: (resource: string, filter: string, orderBy: string) => ['first-record', resource, filter, orderBy] as const,\n pathValue: (resource: string, key: string, path: string) => ['path-value', resource, key, path] as const,\n /** Everything of the signed-in user's notification history. */\n inbox: ['inbox'] as const,\n /** How many of the user's notifications are unread. */\n inboxUnread: ['inbox', 'unread'] as const,\n /** The pages of the user's notification history. */\n inboxPages: ['inbox', 'pages'] as const,\n /** The people of the organization the session of this user works in (`useMembers`). */\n members: (userId: string) => ['members', userId] as const,\n /** The statuses of everyone who shares an organization with this user (`useStatuses`). */\n statuses: (userId: string) => ['statuses', userId] as const,\n /** This user's own status (`useOwnStatus`). */\n ownStatus: (userId: string) => ['statuses', userId, 'own'] as const,\n /** The calls ringing the signed-in user (`useRings`). */\n rings: ['call-rings'] as const,\n /** A record's calls, as its call mark shows them (`useRecordCalls`). */\n recordCalls: (resource: string, key: string) => ['record-calls', resource, key] as const,\n /** The app's workflow trigger and step types, as the workflow editor reads them (`useWorkflowTypes`). */\n workflowTypes: ['workflow-types'] as const,\n /** A workflow run's trace, as its page reads it (`useRunSteps`). */\n workflowRunTrace: (runId: string) => ['workflow-run-trace', runId] as const,\n /** A public form, as `/-/forms/<name>` draws it. */\n publicForm: (name: string) => ['public-form', name] as const,\n}\n\n/** Whether a query reads one of `resources`: one keyed by it, or a planned read that reads it through a `related()` term. */\nexport const readsResource = (key: readonly unknown[], resources: ReadonlySet<string>) =>\n resources.has(key[1] as string) || (key[0] === 'plan' && (key[2] as readonly string[]).some((resource) => resources.has(resource)))\n","import { useQueryClient, type Query, type QueryClient, type QueryState } from '@tanstack/react-query'\nimport { createContext, useCallback, useContext, useSyncExternalStore } from 'react'\n\n/** When the query client started: an answer older than this came from the start cache. */\nexport const ClientStartContext = createContext(0)\n\n/** The answer a query holds came from the start cache and has not been fetched again since the client started. */\nexport const isRestored = (state: Pick<QueryState, 'data' | 'dataUpdatedAt'>, startedAt: number) => state.data !== undefined && state.dataUpdatedAt < startedAt\n\n/**\n * What the page shows of the start cache: `stale` while a query on screen still holds a cached answer, `refreshing`\n * while one of those is being fetched again, `failed` once one could not be, as its fetch failed (see\n * `keepCachedOnFailure`) or waits for a network.\n */\nexport type RestoredState = 'fresh' | 'refreshing' | 'stale' | 'failed'\n\nexport const restoredState = (queries: readonly Pick<Query, 'state'>[], startedAt: number): RestoredState => {\n const restored = queries.filter((query) => isRestored(query.state, startedAt))\n if (restored.length === 0) return 'fresh'\n if (restored.some((query) => query.state.status === 'error' || query.state.fetchFailureCount > 0 || query.state.fetchStatus === 'paused')) return 'failed'\n if (restored.some((query) => query.state.fetchStatus === 'fetching')) return 'refreshing'\n return 'stale'\n}\n\n/**\n * Keeps a cached answer on screen when fetching it again fails, as a query keeps its data but turns to `error`, which\n * parts draw in place of the data: it stays a success, still stale, and the failure stays in its `fetchFailureCount`,\n * which `restoredState` shows beside the page's title instead.\n */\nexport const keepCachedOnFailure = (client: QueryClient, startedAt: number) =>\n client.getQueryCache().subscribe((event) => {\n if (event.type !== 'updated' || event.action.type !== 'error' || !isRestored(event.query.state, startedAt)) return\n event.query.setState({ status: 'success', error: null })\n })\n\n/** `restoredState` of the queries on screen, kept up to date as they refresh. */\nexport const useRestoredState = () => {\n const cache = useQueryClient().getQueryCache()\n const startedAt = useContext(ClientStartContext)\n const subscribe = useCallback((changed: () => void) => cache.subscribe(changed), [cache])\n const read = useCallback(() => restoredState(cache.findAll({ type: 'active' }), startedAt), [cache, startedAt])\n return useSyncExternalStore(subscribe, read, read)\n}\n","import { focusManager, QueryClient, QueryClientProvider } from '@tanstack/react-query'\nimport { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'\nimport { createClient, type Client, type ClientOptions, type SourceRef } from '@protobase/client'\nimport { createFocusRefresh, FocusRefreshContext, listenToWindowFocus } from './focus-refresh'\nimport type { MetaData } from './meta-data'\nimport { keys } from './query-keys'\nimport type { QueryPersistence } from './start-cache/query-persistence'\nimport { ClientStartContext, keepCachedOnFailure } from './start-cache/restored-state'\n\nconst ApiContext = createContext<Client | null>(null)\nconst SourceClientsContext = createContext<((source: SourceRef) => Client) | null>(null)\nconst ResourceClientContext = createContext<((resource: string) => Client | undefined) | null>(null)\n\n/** The API client: the app's own, or below `MetaGate` one that sends each resource's calls to the API that serves it. */\nexport const useClient = () => {\n const client = useContext(ApiContext)\n if (!client) throw new Error('useClient must be used inside ApiProvider')\n return client\n}\n\n/**\n * The client of the API that serves `resource`: a source's for a resource the app draws from one, the app's own\n * otherwise. A source's client calls that API's functions with `invoke`, where `useClient()` calls the app's own.\n */\nexport const useResourceClient = (resource: string) => {\n const own = useClient()\n return useContext(ResourceClientContext)?.(resource) ?? own\n}\n\n/** `useResourceClient` for any resource: the client of the API that serves each, for code that reaches several. */\nexport const useResourceClients = () => {\n const own = useClient()\n const resourceClient = useContext(ResourceClientContext)\n return useCallback((resource: string) => resourceClient?.(resource) ?? own, [own, resourceClient])\n}\n\n/** The client of a source's API, one per URL, with the signed-in user's token; for `MetaGate`. */\nexport const useSourceClients = () => {\n const clientOf = useContext(SourceClientsContext)\n if (!clientOf) throw new Error('useSourceClients must be used inside ApiProvider')\n return clientOf\n}\n\n/** Gives what is below it `client` from `useClient()`, and the client of a resource's API from `useResourceClient()`. */\nexport const ClientProvider = ({ client, resourceClient, children }: { client: Client; resourceClient: (resource: string) => Client | undefined; children: ReactNode }) => (\n <ApiContext.Provider value={client}>\n <ResourceClientContext.Provider value={resourceClient}>{children}</ResourceClientContext.Provider>\n </ApiContext.Provider>\n)\n\nexport type ApiProviderProps = {\n /** Defaults to `/api/v1` on the current origin. */\n baseUrl?: string\n /** A ready-made client, for tests; skips the meta-version watcher. */\n client?: Client\n /** Ready-made clients of the sources `/meta` names, by their URL, for stories and tests. */\n sources?: Record<string, Client>\n /** The `fetch` the built client uses, for tests that keep the meta-version watcher. */\n fetch?: ClientOptions['fetch']\n queryClient?: QueryClient\n /** The bearer token source, and what to do when the session is over; see `createAuthSession`. */\n token?: ClientOptions['token']\n onUnauthenticated?: () => void\n /** Keeps the cache's queries between starts, for someone signed in as themselves; see `createQueryPersistence`. */\n persistence?: QueryPersistence\n children: ReactNode\n}\n\n/**\n * Owns the query cache and the API client; refetches `/meta` whenever `X-Meta-Version` changes. The version is\n * compared only with the last one seen: it hashes the models and roles, while the `/meta` ETag hashes the whole\n * per-caller body, so the two never match. The data on screen refetches whenever the window regains focus, unless a\n * form holds unsaved changes (`usePauseFocusRefresh`). With `persistence`, it starts from the queries cached for its\n * owner, which refetch as they are used.\n */\nexport const ApiProvider = ({ baseUrl, client: given, sources, fetch, queryClient: givenQueryClient, token, onUnauthenticated, persistence, children }: ApiProviderProps) => {\n const [focusRefresh] = useState(createFocusRefresh)\n // The cached queries are in the client before anything below draws, so the first render shows them.\n const [{ queryClient, startedAt }] = useState(() => {\n const queryClient = givenQueryClient ?? new QueryClient({ defaultOptions: { queries: { staleTime: 30_000, retry: false, refetchOnWindowFocus: focusRefresh.refetchOnWindowFocus } } })\n persistence?.restore(queryClient)\n return { queryClient, startedAt: Date.now() }\n })\n useEffect(() => persistence?.subscribe(queryClient), [persistence, queryClient])\n useEffect(() => (persistence ? keepCachedOnFailure(queryClient, startedAt) : undefined), [persistence, queryClient, startedAt])\n useEffect(() => focusManager.setEventListener(listenToWindowFocus), [])\n const metaVersion = useRef<string | undefined>(undefined)\n const client = useMemo(\n () =>\n given ??\n createClient({\n baseUrl,\n fetch,\n token,\n onUnauthenticated,\n onMetaVersion: (version) => {\n const previous = metaVersion.current\n metaVersion.current = version\n if (previous === undefined || previous === version) return\n // A page that met another Protobase version keeps its `/meta` until it reloads (see `keepOnVersionChange`).\n if (queryClient.getQueryData<MetaData>(keys.meta)?.versionChange) return\n // An in-flight `/meta` refetch is reused, so a version that keeps moving costs one request, not a loop.\n void queryClient.invalidateQueries({ queryKey: keys.meta }, { cancelRefetch: false })\n },\n }),\n [given, baseUrl, fetch, queryClient, token, onUnauthenticated],\n )\n // A source's client sends the user's token, and refetches the source's `/meta` when its version moves. A 401 there\n // does not sign the user out of the app: it is that API's answer, which the source's resources show.\n const sourceClient = useMemo(() => {\n const made = new Map<string, Client>()\n return (source: SourceRef) => {\n const ready = sources?.[source.url] ?? made.get(source.url)\n if (ready) return ready\n let seen: string | undefined\n const client = createClient({\n baseUrl: source.url,\n fetch,\n token,\n onMetaVersion: (version) => {\n const previous = seen\n seen = version\n if (previous === undefined || previous === version) return\n void queryClient.invalidateQueries({ queryKey: keys.sourceMetas(source.url) }, { cancelRefetch: false })\n },\n })\n made.set(source.url, client)\n return client\n }\n }, [sources, fetch, token, queryClient])\n return (\n <QueryClientProvider client={queryClient}>\n <ApiContext.Provider value={client}>\n <SourceClientsContext.Provider value={sourceClient}>\n <FocusRefreshContext.Provider value={focusRefresh}>\n <ClientStartContext.Provider value={startedAt}>{children}</ClientStartContext.Provider>\n </FocusRefreshContext.Provider>\n </SourceClientsContext.Provider>\n </ApiContext.Provider>\n </QueryClientProvider>\n )\n}\n"],"ignoreList":[14],"mappings":"+wBAIA,IAAaiC,EAA0C,CACrD,GAAI,CAAE,OAAQ,CAAC,CAAE,KAAM,QAAS,KAAM,OAAQ,CAAC,EAAG,KAAM,CAAE,KAAM,QAAS,KAAM,KAAM,CAAE,EACvF,OAAQ,CAAE,OAAQ,CAAC,CAAE,K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