@protobase/ui 0.113.1 → 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.
Files changed (192) hide show
  1. package/dist/account/messages.d.ts +2 -2
  2. package/dist/app/app.d.ts +4 -1
  3. package/dist/app/app.js +9 -7
  4. package/dist/app/charts/messages.d.ts +2 -2
  5. package/dist/app/comments/messages.d.ts +2 -2
  6. package/dist/app/confirm-sign-in-messages.d.ts +2 -2
  7. package/dist/app/create/messages.d.ts +2 -2
  8. package/dist/app/delete/messages.d.ts +2 -2
  9. package/dist/app/displays/messages.d.ts +2 -2
  10. package/dist/app/displays/virtual-cards.js +1 -0
  11. package/dist/app/embedded-list/messages.d.ts +2 -2
  12. package/dist/app/export/messages.d.ts +2 -2
  13. package/dist/app/field-messages.d.ts +2 -2
  14. package/dist/app/field-types/workflow/messages.d.ts +2 -2
  15. package/dist/app/field-types/workflow-page/messages.d.ts +2 -2
  16. package/dist/app/field-types/workflow-run/messages.d.ts +2 -2
  17. package/dist/app/first-frame.d.ts +13 -0
  18. package/dist/app/first-frame.js +23 -0
  19. package/dist/app/focus/messages.d.ts +2 -2
  20. package/dist/app/gallery/gallery-layout.d.ts +2 -2
  21. package/dist/app/gallery/messages.d.ts +2 -2
  22. package/dist/app/hand-order/messages.d.ts +2 -2
  23. package/dist/app/import/messages.d.ts +2 -2
  24. package/dist/app/index.html +0 -17
  25. package/dist/app/list-messages.d.ts +2 -2
  26. package/dist/app/main.js +19 -7
  27. package/dist/app/messages.d.ts +2 -2
  28. package/dist/app/pages/messages.d.ts +2 -2
  29. package/dist/app/record-chart/messages.d.ts +2 -2
  30. package/dist/app/record-messages.d.ts +2 -2
  31. package/dist/app/record-mode/shown-layout.d.ts +1 -1
  32. package/dist/app/record-row/messages.d.ts +2 -2
  33. package/dist/app/record-row/record-row.js +1 -0
  34. package/dist/app/refresh-mark.d.ts +2 -1
  35. package/dist/app/refresh-mark.js +3 -1
  36. package/dist/app/reveal-when-loaded.d.ts +8 -2
  37. package/dist/app/reveal-when-loaded.js +12 -5
  38. package/dist/app/runtime/messages.d.ts +2 -2
  39. package/dist/app/saved/messages.d.ts +2 -2
  40. package/dist/app/searches/messages.d.ts +2 -2
  41. package/dist/app/splash-hold.d.ts +0 -1
  42. package/dist/app/splash-hold.js +1 -1
  43. package/dist/app/start-screen.d.ts +0 -9
  44. package/dist/app/start-screen.js +1 -10
  45. package/dist/app/ui-ready.d.ts +11 -0
  46. package/dist/app/ui-ready.js +12 -0
  47. package/dist/app-shell/app-shell.js +3 -1
  48. package/dist/app-shell/close-sidebar.d.ts +10 -0
  49. package/dist/app-shell/close-sidebar.js +17 -0
  50. package/dist/app-shell/drawer.d.ts +7 -1
  51. package/dist/app-shell/drawer.js +26 -7
  52. package/dist/app-shell/index.d.ts +2 -1
  53. package/dist/app-shell/index.js +2 -1
  54. package/dist/app-shell/messages.d.ts +2 -2
  55. package/dist/app-shell/top-bar.js +4 -4
  56. package/dist/assistant-dock/messages.d.ts +2 -2
  57. package/dist/auth/messages.d.ts +2 -2
  58. package/dist/calls/messages.d.ts +2 -2
  59. package/dist/chat/messages.d.ts +2 -2
  60. package/dist/data/query-keys.d.ts +6 -0
  61. package/dist/data/query-keys.js +10 -0
  62. package/dist/data/start-cache/cached-plugins.d.ts +6 -0
  63. package/dist/data/start-cache/cached-plugins.js +10 -0
  64. package/dist/data-grid/data-grid.js +1 -0
  65. package/dist/data-grid/messages.d.ts +2 -2
  66. package/dist/data-grid/row-source.d.ts +5 -0
  67. package/dist/data-grid/use-paged-rows.d.ts +5 -3
  68. package/dist/data-grid/use-paged-rows.js +21 -6
  69. package/dist/filter-panel/messages.d.ts +2 -2
  70. package/dist/index.d.ts +4 -1
  71. package/dist/index.js +4 -1
  72. package/dist/inline-child-table/messages.d.ts +2 -2
  73. package/dist/live/grid-loader.d.ts +1 -0
  74. package/dist/live/grid-loader.js +3 -1
  75. package/dist/live/use-live-rows.js +1 -0
  76. package/dist/mocks/orders.d.ts +1 -1
  77. package/dist/notifications/bell/messages.d.ts +2 -2
  78. package/dist/organizations/members-page.js +13 -7
  79. package/dist/organizations/messages.d.ts +2 -2
  80. package/dist/organizations/use-organizations.d.ts +4 -1
  81. package/dist/organizations/use-organizations.js +25 -19
  82. package/dist/package.js +1 -1
  83. package/dist/plugins/plugin-source.d.ts +24 -4
  84. package/dist/plugins/plugin-source.js +48 -14
  85. package/dist/plugins/use-plugin-loads.d.ts +3 -1
  86. package/dist/plugins/use-plugin-loads.js +24 -7
  87. package/dist/primitives/skeleton.js +1 -0
  88. package/dist/roles/use-active-role.d.ts +4 -1
  89. package/dist/roles/use-active-role.js +18 -13
  90. package/dist/shell/assets/api-provider-BJJrOoO4.js +2 -0
  91. package/dist/shell/assets/app-VoTi41IN.js +16 -0
  92. package/dist/shell/assets/badge-OU9hb6yQ.js +2 -0
  93. package/dist/shell/assets/checkbox-DFfK432Y.js +2 -0
  94. package/dist/shell/assets/createLucideIcon-DGm8SdFI.js +2 -0
  95. package/dist/shell/assets/display-value-CIH2qfgQ.js +2 -0
  96. package/dist/shell/assets/{field-badge-3QmjR1r3.js → field-badge-DX2Mc_fH.js} +2 -2
  97. package/dist/shell/assets/{graph-view-CIk96BRv.js → graph-view-CY9LPr0B.js} +2 -2
  98. package/dist/shell/assets/{html-viewer-ATz2AVBi.js → html-viewer-BPGMH_GA.js} +2 -2
  99. package/dist/shell/assets/{in-place-form-frfvnKaj.js → in-place-form-RWSQGEg4.js} +2 -2
  100. package/dist/shell/assets/index-Bzb-O7ER.js +2 -0
  101. package/dist/shell/assets/index-HnFovy2Q.css +2 -0
  102. package/dist/shell/assets/{intl-cache-bXVNV0Yq.js → intl-cache-D4doUjK1.js} +2 -2
  103. package/dist/shell/assets/{lib-d3-interpolate-Cl0dHO4f.js → lib-d3-interpolate-D3u38iyJ.js} +2 -2
  104. package/dist/shell/assets/{lib-d3-transition-DUHAGQ8z.js → lib-d3-transition-BUpPvFvt.js} +2 -2
  105. package/dist/shell/assets/{lib-d3-zoom-gQh2osrj.js → lib-d3-zoom-BF7SPKNh.js} +2 -2
  106. package/dist/shell/assets/{lib-vis.gl-react-maplibre-CU7gWYjg.js → lib-vis.gl-react-maplibre-C7-0xNFC.js} +2 -2
  107. package/dist/shell/assets/{lib-xyflow-react-DGg_5r7u.js → lib-xyflow-react-CKyW7szC.js} +2 -2
  108. package/dist/shell/assets/maplibre-9ViQO48S.js +2 -0
  109. package/dist/shell/assets/{markdown-content-mNJHzGOa.js → markdown-content-DTB9RQDs.js} +2 -2
  110. package/dist/shell/assets/{record-map-BsXXSshB.js → record-map-CVqCWtfe.js} +2 -2
  111. package/dist/shell/assets/{records-map-D8EBzOu8.js → records-map-ClYSxrVR.js} +2 -2
  112. package/dist/shell/assets/{run-trace-view-Tf6Jwd46.js → run-trace-view-CN16MiXg.js} +2 -2
  113. package/dist/shell/assets/search-picker-BGpvJQRD.js +2 -0
  114. package/dist/shell/assets/shared-protobase-ui-BC8LqGQB.js +2 -0
  115. package/dist/shell/assets/step-catalog-CZY0ZpCC.js +2 -0
  116. package/dist/shell/assets/step-panel-DhD80lsJ.js +2 -0
  117. package/dist/shell/assets/use-app-address-B4Uk3nWy.js +2 -0
  118. package/dist/shell/assets/{use-meta-BqEqOLNe.js → use-meta-D5kYywHm.js} +2 -2
  119. package/dist/shell/assets/{use-sibling-page-Dm7aUfaa.js → use-sibling-page-BJ81HcOP.js} +3 -3
  120. package/dist/shell/assets/value-badge-Dpd8dRqq.js +2 -0
  121. package/dist/shell/assets/{vendor-WWp_xlp2.js → vendor-3etemhgS.js} +4 -4
  122. package/dist/shell/assets/{workflow-canvas-B8ciy9xI.js → workflow-canvas-C1nGpi5w.js} +2 -2
  123. package/dist/shell/assets/{workflow-graph-editor-QT-3e-M9.js → workflow-graph-editor-DAJa4lq6.js} +2 -2
  124. package/dist/shell/assets/workflow-workbench-HramVZEJ.js +4 -0
  125. package/dist/shell/assets/{workflows-Bku4o2su.js → workflows-DlvOln9v.js} +2 -2
  126. package/dist/shell/assets/{workflows-start-kl7rSSay.js → workflows-start-QUKfwFqf.js} +2 -2
  127. package/dist/shell/index.html +16 -19
  128. package/dist/shell/protobase.shell.json +2 -2
  129. package/dist/shell/protobase.sw.js +2 -2
  130. package/dist/shell-source-maps/assets/api-provider-BJJrOoO4.js.map +1 -0
  131. package/dist/shell-source-maps/assets/app-VoTi41IN.js.map +1 -0
  132. package/dist/shell-source-maps/assets/{badge-ChHXC28D.js.map → badge-OU9hb6yQ.js.map} +1 -1
  133. package/dist/shell-source-maps/assets/{checkbox-COOOlJPG.js.map → checkbox-DFfK432Y.js.map} +1 -1
  134. package/dist/shell-source-maps/assets/createLucideIcon-DGm8SdFI.js.map +1 -0
  135. package/dist/shell-source-maps/assets/display-value-CIH2qfgQ.js.map +1 -0
  136. package/dist/shell-source-maps/assets/{field-badge-3QmjR1r3.js.map → field-badge-DX2Mc_fH.js.map} +1 -1
  137. package/dist/shell-source-maps/assets/{graph-view-CIk96BRv.js.map → graph-view-CY9LPr0B.js.map} +1 -1
  138. package/dist/shell-source-maps/assets/{html-viewer-ATz2AVBi.js.map → html-viewer-BPGMH_GA.js.map} +1 -1
  139. package/dist/shell-source-maps/assets/{in-place-form-frfvnKaj.js.map → in-place-form-RWSQGEg4.js.map} +1 -1
  140. package/dist/shell-source-maps/assets/index-Bzb-O7ER.js.map +1 -0
  141. package/dist/shell-source-maps/assets/{intl-cache-bXVNV0Yq.js.map → intl-cache-D4doUjK1.js.map} +1 -1
  142. package/dist/shell-source-maps/assets/{lib-d3-interpolate-Cl0dHO4f.js.map → lib-d3-interpolate-D3u38iyJ.js.map} +1 -1
  143. package/dist/shell-source-maps/assets/{lib-d3-transition-DUHAGQ8z.js.map → lib-d3-transition-BUpPvFvt.js.map} +1 -1
  144. package/dist/shell-source-maps/assets/{lib-d3-zoom-gQh2osrj.js.map → lib-d3-zoom-BF7SPKNh.js.map} +1 -1
  145. 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
  146. package/dist/shell-source-maps/assets/{lib-xyflow-react-DGg_5r7u.js.map → lib-xyflow-react-CKyW7szC.js.map} +1 -1
  147. package/dist/shell-source-maps/assets/{maplibre-BufRSV4y.js.map → maplibre-9ViQO48S.js.map} +1 -1
  148. package/dist/shell-source-maps/assets/{markdown-content-mNJHzGOa.js.map → markdown-content-DTB9RQDs.js.map} +1 -1
  149. package/dist/shell-source-maps/assets/{record-map-BsXXSshB.js.map → record-map-CVqCWtfe.js.map} +1 -1
  150. package/dist/shell-source-maps/assets/{records-map-D8EBzOu8.js.map → records-map-ClYSxrVR.js.map} +1 -1
  151. package/dist/shell-source-maps/assets/{run-trace-view-Tf6Jwd46.js.map → run-trace-view-CN16MiXg.js.map} +1 -1
  152. package/dist/shell-source-maps/assets/{search-picker-BHmYOFF8.js.map → search-picker-BGpvJQRD.js.map} +1 -1
  153. package/dist/shell-source-maps/assets/shared-protobase-ui-BC8LqGQB.js.map +1 -0
  154. package/dist/shell-source-maps/assets/{step-catalog-DZNovnPL.js.map → step-catalog-CZY0ZpCC.js.map} +1 -1
  155. package/dist/shell-source-maps/assets/{step-panel-3aRZ2Dlj.js.map → step-panel-DhD80lsJ.js.map} +1 -1
  156. package/dist/shell-source-maps/assets/{use-app-address-B6k3dkV0.js.map → use-app-address-B4Uk3nWy.js.map} +1 -1
  157. package/dist/shell-source-maps/assets/{use-meta-BqEqOLNe.js.map → use-meta-D5kYywHm.js.map} +1 -1
  158. package/dist/shell-source-maps/assets/{use-sibling-page-Dm7aUfaa.js.map → use-sibling-page-BJ81HcOP.js.map} +1 -1
  159. package/dist/shell-source-maps/assets/{value-badge-BKLV4otJ.js.map → value-badge-Dpd8dRqq.js.map} +1 -1
  160. package/dist/shell-source-maps/assets/{vendor-WWp_xlp2.js.map → vendor-3etemhgS.js.map} +1 -1
  161. package/dist/shell-source-maps/assets/{workflow-canvas-B8ciy9xI.js.map → workflow-canvas-C1nGpi5w.js.map} +1 -1
  162. package/dist/shell-source-maps/assets/{workflow-graph-editor-QT-3e-M9.js.map → workflow-graph-editor-DAJa4lq6.js.map} +1 -1
  163. package/dist/shell-source-maps/assets/{workflow-workbench-C5eHhxQh.js.map → workflow-workbench-HramVZEJ.js.map} +1 -1
  164. package/dist/shell-source-maps/assets/{workflows-Bku4o2su.js.map → workflows-DlvOln9v.js.map} +1 -1
  165. package/dist/shell-source-maps/assets/{workflows-start-kl7rSSay.js.map → workflows-start-QUKfwFqf.js.map} +1 -1
  166. package/dist/status/messages.d.ts +2 -2
  167. package/dist/styles.css +14 -0
  168. package/package.json +5 -5
  169. package/dist/app/hold-start-for-first-loads.d.ts +0 -12
  170. package/dist/app/hold-start-for-first-loads.js +0 -43
  171. package/dist/shell/assets/api-provider-CcDtTh0D.js +0 -2
  172. package/dist/shell/assets/app-C1xWr51x.js +0 -16
  173. package/dist/shell/assets/badge-ChHXC28D.js +0 -2
  174. package/dist/shell/assets/checkbox-COOOlJPG.js +0 -2
  175. package/dist/shell/assets/display-value-fDiKbfJO.js +0 -2
  176. package/dist/shell/assets/index-BkCaPeOq.css +0 -2
  177. package/dist/shell/assets/index-C4cMQVG2.js +0 -2
  178. package/dist/shell/assets/maplibre-BufRSV4y.js +0 -2
  179. package/dist/shell/assets/messages-ClKBpZlk.js +0 -2
  180. package/dist/shell/assets/search-picker-BHmYOFF8.js +0 -2
  181. package/dist/shell/assets/shared-protobase-ui-C1jBhoci.js +0 -2
  182. package/dist/shell/assets/step-catalog-DZNovnPL.js +0 -2
  183. package/dist/shell/assets/step-panel-3aRZ2Dlj.js +0 -2
  184. package/dist/shell/assets/use-app-address-B6k3dkV0.js +0 -2
  185. package/dist/shell/assets/value-badge-BKLV4otJ.js +0 -2
  186. package/dist/shell/assets/workflow-workbench-C5eHhxQh.js +0 -4
  187. package/dist/shell-source-maps/assets/api-provider-CcDtTh0D.js.map +0 -1
  188. package/dist/shell-source-maps/assets/app-C1xWr51x.js.map +0 -1
  189. package/dist/shell-source-maps/assets/display-value-fDiKbfJO.js.map +0 -1
  190. package/dist/shell-source-maps/assets/index-C4cMQVG2.js.map +0 -1
  191. package/dist/shell-source-maps/assets/messages-ClKBpZlk.js.map +0 -1
  192. package/dist/shell-source-maps/assets/shared-protobase-ui-C1jBhoci.js.map +0 -1
@@ -2,15 +2,35 @@ import { PluginLoad, PluginLoader } from "./load-plugin.js";
2
2
  import { ReactNode } from "react";
3
3
  import { PluginRef } from "@protobase/client";
4
4
  //#region src/plugins/plugin-source.d.ts
5
- /** Where the app's plugins come from: each loaded once for the page, by whichever gate asks for it first. */
5
+ /**
6
+ * The event a host dispatches on `window` when the app's plugins changed where they are served, such as Protobase's
7
+ * official app once it has fetched a workspace's new plugin files: the app loads its plugins again and swaps them in
8
+ * where they draw, keeping what it shows meanwhile. Their components start afresh; the old code stays in memory.
9
+ */
10
+ export declare const pluginsChangedEvent = "protobase:plugins-changed";
11
+ /**
12
+ * Where the app's plugins come from: each loaded once for the page, by whichever gate asks for it first, or before the
13
+ * app's first render; `loaded` is a plugin's load once it has settled, read at once. `forget` drops every load, so each
14
+ * plugin loads again, and moves `revision` on, which `subscribe` tells.
15
+ */
6
16
  export type PluginSource = {
7
17
  load: (ref: PluginRef) => Promise<PluginLoad>;
18
+ loaded: (ref: PluginRef) => PluginLoad | undefined;
19
+ forget: () => void;
20
+ revision: () => number;
21
+ subscribe: (changed: () => void) => () => void;
8
22
  };
9
23
  /** A source that loads with `loader` and keeps each plugin's load, so one named before and after sign-in loads once. */
10
- export declare const createPluginSource: (loader: PluginLoader) => PluginSource;
11
- /** The app's plugin source, loading with `loader`: the page's `fetch` and `import()` by default. */
12
- export declare const PluginSourceProvider: ({ loader, children }: {
24
+ export declare const createPluginSource: (loader: PluginLoader, base?: () => string) => PluginSource;
25
+ /**
26
+ * Loads `refs` ahead of the app's first render, such as the plugins the start cache's `/meta` names, so the plugin gate
27
+ * draws the app with them at once; at most `waitMs`, after which the app starts and the slow ones arrive later.
28
+ */
29
+ export declare const preloadPlugins: (source: PluginSource, refs: readonly PluginRef[], waitMs: number) => Promise<undefined>;
30
+ /** The app's plugin source: `source` when the page made one before rendering, or one loading with `loader`, the page's `fetch` and `import()` by default. */
31
+ export declare const PluginSourceProvider: ({ loader, source: given, children }: {
13
32
  loader?: PluginLoader;
33
+ source?: PluginSource;
14
34
  children: ReactNode;
15
35
  }) => import("react").JSX.Element;
16
36
  export declare const usePluginSource: () => PluginSource;
@@ -1,23 +1,57 @@
1
1
  import { browserLoader, loadPlugin } from "./load-plugin.js";
2
- import { createContext, useContext, useMemo } from "react";
2
+ import { createContext, useContext, useEffect, useMemo } from "react";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  //#region src/plugins/plugin-source.tsx
5
+ /**
6
+ * The event a host dispatches on `window` when the app's plugins changed where they are served, such as Protobase's
7
+ * official app once it has fetched a workspace's new plugin files: the app loads its plugins again and swaps them in
8
+ * where they draw, keeping what it shows meanwhile. Their components start afresh; the old code stays in memory.
9
+ */
10
+ const pluginsChangedEvent = "protobase:plugins-changed";
5
11
  /** A source that loads with `loader` and keeps each plugin's load, so one named before and after sign-in loads once. */
6
- const createPluginSource = (loader) => {
12
+ const createPluginSource = (loader, base = () => window.location.href) => {
7
13
  const loads = /* @__PURE__ */ new Map();
8
- return { load: (ref) => {
9
- const key = JSON.stringify(ref);
10
- const known = loads.get(key);
11
- if (known) return known;
12
- const load = loadPlugin(ref, loader, window.location.href);
13
- loads.set(key, load);
14
- return load;
15
- } };
14
+ const settled = /* @__PURE__ */ new Map();
15
+ const listeners = /* @__PURE__ */ new Set();
16
+ let revision = 0;
17
+ return {
18
+ load: (ref) => {
19
+ const key = JSON.stringify(ref);
20
+ const known = loads.get(key);
21
+ if (known) return known;
22
+ const load = loadPlugin(ref, loader, base());
23
+ loads.set(key, load);
24
+ load.then((result) => settled.set(key, result));
25
+ return load;
26
+ },
27
+ loaded: (ref) => settled.get(JSON.stringify(ref)),
28
+ forget: () => {
29
+ loads.clear();
30
+ settled.clear();
31
+ revision += 1;
32
+ for (const changed of listeners) changed();
33
+ },
34
+ revision: () => revision,
35
+ subscribe: (changed) => {
36
+ listeners.add(changed);
37
+ return () => void listeners.delete(changed);
38
+ }
39
+ };
16
40
  };
41
+ /**
42
+ * Loads `refs` ahead of the app's first render, such as the plugins the start cache's `/meta` names, so the plugin gate
43
+ * draws the app with them at once; at most `waitMs`, after which the app starts and the slow ones arrive later.
44
+ */
45
+ const preloadPlugins = (source, refs, waitMs) => Promise.race([Promise.all(refs.map((ref) => source.load(ref))), new Promise((resolve) => setTimeout(resolve, waitMs))]).then(() => void 0);
17
46
  const PluginSourceContext = createContext(null);
18
- /** The app's plugin source, loading with `loader`: the page's `fetch` and `import()` by default. */
19
- const PluginSourceProvider = ({ loader = browserLoader, children }) => {
20
- const source = useMemo(() => createPluginSource(loader), [loader]);
47
+ /** The app's plugin source: `source` when the page made one before rendering, or one loading with `loader`, the page's `fetch` and `import()` by default. */
48
+ const PluginSourceProvider = ({ loader = browserLoader, source: given, children }) => {
49
+ const source = useMemo(() => given ?? createPluginSource(loader), [given, loader]);
50
+ useEffect(() => {
51
+ const changed = () => source.forget();
52
+ window.addEventListener(pluginsChangedEvent, changed);
53
+ return () => window.removeEventListener(pluginsChangedEvent, changed);
54
+ }, [source]);
21
55
  return /* @__PURE__ */ jsx(PluginSourceContext.Provider, {
22
56
  value: source,
23
57
  children
@@ -29,4 +63,4 @@ const usePluginSource = () => {
29
63
  return source;
30
64
  };
31
65
  //#endregion
32
- export { PluginSourceProvider, createPluginSource, usePluginSource };
66
+ export { PluginSourceProvider, createPluginSource, pluginsChangedEvent, preloadPlugins, usePluginSource };
@@ -6,12 +6,14 @@ import { PluginRef } from "@protobase/client";
6
6
  export declare const pluginWaitMs = 10000;
7
7
  type Loads = {
8
8
  key: string;
9
+ refs?: string;
9
10
  loads: PluginLoad[];
10
11
  settled: boolean;
11
12
  };
12
13
  /**
13
14
  * The plugins `refs` names, in their order, as they load. `settled` once every one has loaded or failed, or after
14
- * `pluginWaitMs`, so a slow plugin delays the app only that long. Without plugins it is settled at once.
15
+ * `pluginWaitMs`, so a slow plugin delays the app only that long. Without plugins it is settled at once, and so it is
16
+ * when the source has loaded every one already, as before the app's first render.
15
17
  */
16
18
  export declare const usePluginLoads: (refs: readonly PluginRef[], source: PluginSource) => Loads | {
17
19
  loads: PluginLoad[];
@@ -1,15 +1,18 @@
1
- import { useEffect, useState } from "react";
1
+ import { useEffect, useState, useSyncExternalStore } from "react";
2
2
  //#region src/plugins/use-plugin-loads.ts
3
3
  /** How long the app waits for its plugins before it draws without the ones still loading, which arrive later. */
4
4
  const pluginWaitMs = 1e4;
5
5
  const none = [];
6
6
  /**
7
7
  * The plugins `refs` names, in their order, as they load. `settled` once every one has loaded or failed, or after
8
- * `pluginWaitMs`, so a slow plugin delays the app only that long. Without plugins it is settled at once.
8
+ * `pluginWaitMs`, so a slow plugin delays the app only that long. Without plugins it is settled at once, and so it is
9
+ * when the source has loaded every one already, as before the app's first render.
9
10
  */
10
11
  const usePluginLoads = (refs, source) => {
11
- const key = JSON.stringify(refs);
12
- const [state, setState] = useState({
12
+ const revision = useSyncExternalStore(source.subscribe, source.revision, source.revision);
13
+ const named = JSON.stringify(refs);
14
+ const key = `${named}#${revision}`;
15
+ const [state, setState] = useState(() => loadedAlready(refs, source, key) ?? {
13
16
  key: "[]",
14
17
  loads: none,
15
18
  settled: true
@@ -22,10 +25,12 @@ const usePluginLoads = (refs, source) => {
22
25
  const publish = () => {
23
26
  if (!active) return;
24
27
  const loads = results.filter((load) => load !== void 0);
25
- setState({
28
+ const settled = waited || loads.length === refs.length;
29
+ setState((current) => current.refs === named && current.settled && !settled ? current : {
26
30
  key,
31
+ refs: named,
27
32
  loads,
28
- settled: waited || loads.length === refs.length
33
+ settled
29
34
  });
30
35
  };
31
36
  const timer = setTimeout(() => {
@@ -47,10 +52,22 @@ const usePluginLoads = (refs, source) => {
47
52
  loads: none,
48
53
  settled: true
49
54
  };
50
- return state.key === key ? state : {
55
+ if (state.key === key) return state;
56
+ if (state.refs === named && state.settled) return state;
57
+ return loadedAlready(refs, source, key) ?? {
51
58
  loads: none,
52
59
  settled: false
53
60
  };
54
61
  };
62
+ const loadedAlready = (refs, source, key) => {
63
+ if (refs.length === 0) return void 0;
64
+ const loads = refs.map((ref) => source.loaded(ref));
65
+ return loads.every((load) => load !== void 0) ? {
66
+ key,
67
+ refs: JSON.stringify(refs),
68
+ loads,
69
+ settled: true
70
+ } : void 0;
71
+ };
55
72
  //#endregion
56
73
  export { pluginWaitMs, usePluginLoads };
@@ -6,6 +6,7 @@ import { jsx } from "react/jsx-runtime";
6
6
  * load that quick shows no flash, then shimmers, or stays still when less motion is asked for.
7
7
  */
8
8
  const Skeleton = ({ className, style }) => /* @__PURE__ */ jsx("span", {
9
+ "data-placeholder": true,
9
10
  className: cn("block h-3 rounded bg-muted", skeletonMotion, className),
10
11
  style
11
12
  });
@@ -6,6 +6,9 @@ export type ActiveRoleState = {
6
6
  /** Acts with another role, then starts the app again, as a switch of organization does. */
7
7
  switchTo: (name: string) => void;
8
8
  };
9
- /** The role the session acts with, read while `enabled` (someone is signed in); a failed read or switch shows as a toast. */
9
+ /**
10
+ * The role the session acts with, read while `enabled` (someone is signed in) as a query, so the start cache keeps it and
11
+ * the app's first frame draws it; a failed read or switch shows as a toast.
12
+ */
10
13
  export declare const useActiveRole: (reopen: () => void, enabled?: boolean) => ActiveRoleState;
11
14
  //#endregion
@@ -1,27 +1,32 @@
1
1
  import { useAuth } from "../auth/auth-provider.js";
2
+ import { keys } from "../data/query-keys.js";
2
3
  import { useToast } from "../toasts/toast-provider.js";
3
4
  import { authMessage } from "../auth/auth-messages.js";
4
5
  import { text } from "./messages.js";
5
- import { useCallback, useEffect, useState } from "react";
6
+ import { useCallback, useEffect } from "react";
6
7
  import { AuthError } from "@protobase/client";
8
+ import { useQuery } from "@tanstack/react-query";
7
9
  //#region src/roles/use-active-role.ts
8
10
  const failureMessage = (failure, fallback) => failure instanceof AuthError ? authMessage(failure) : fallback;
9
- /** The role the session acts with, read while `enabled` (someone is signed in); a failed read or switch shows as a toast. */
11
+ /**
12
+ * The role the session acts with, read while `enabled` (someone is signed in) as a query, so the start cache keeps it and
13
+ * the app's first frame draws it; a failed read or switch shows as a toast.
14
+ */
10
15
  const useActiveRole = (reopen, enabled = true) => {
11
16
  const { session } = useAuth();
12
17
  const toast = useToast();
13
- const [current, setCurrent] = useState();
18
+ const role = useQuery({
19
+ queryKey: keys.activeRole,
20
+ queryFn: () => session.roles.current(),
21
+ enabled,
22
+ retry: false
23
+ });
14
24
  useEffect(() => {
15
- if (!enabled) return;
16
- session.roles.current().then(setCurrent, (failure) => toast.show({
25
+ if (role.error) toast.show({
17
26
  state: "error",
18
- title: failureMessage(failure, text("couldNotReadRoles"))
19
- }));
20
- }, [
21
- session,
22
- toast,
23
- enabled
24
- ]);
27
+ title: failureMessage(role.error, text("couldNotReadRoles"))
28
+ });
29
+ }, [role.error, toast]);
25
30
  const switchTo = useCallback((name) => void session.roles.switchTo(name).then(reopen, (failure) => toast.show({
26
31
  state: "error",
27
32
  title: failureMessage(failure, text("couldNotSwitch"))
@@ -31,7 +36,7 @@ const useActiveRole = (reopen, enabled = true) => {
31
36
  reopen
32
37
  ]);
33
38
  return {
34
- ...current && { current },
39
+ ...enabled && role.data && { current: role.data },
35
40
  switchTo
36
41
  };
37
42
  };
@@ -0,0 +1,2 @@
1
+ (function(){try{var e=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:{};e._sentryModuleMetadata=e._sentryModuleMetadata||{},e._sentryModuleMetadata[new e.Error().stack]=function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];if(n!=null)for(var r in n)n.hasOwnProperty(r)&&(e[r]=n[r])}return e}({},e._sentryModuleMetadata[new e.Error().stack],{"_sentryBundlerPluginAppKey:protobase-app":!0})}catch{}})();import{o as e}from"./rolldown-runtime-DFwUHQ4A.js";import{i as t,t as n}from"./react-CuiNlnus.js";import{Z as r,et as i,jt as a,nt as o,pt as s,rt as c}from"./vendor-3etemhgS.js";import{r as l,t as u}from"./createLucideIcon-DGm8SdFI.js";import{t as d}from"./call-guests-MJxXvcx-.js";import{t as f}from"./cn-B1sdg8aY.js";var p={in:{params:[{name:`field`,type:`field`}],rest:{name:`value`,type:`any`}},search:{params:[{name:`text`,type:`string`}]},similar:{params:[{name:`field`,type:`field`,of:[`string`]},{name:`text`,type:`string`}]},regex:{params:[{name:`field`,type:`field`,of:[`string`]},{name:`pattern`,type:`string`}]},isNull:{params:[{name:`field`,type:`field`}]},related:{params:[{name:`field`,type:`field`},{name:`key`,type:`field`}],rest:{name:`filter`,type:`any`}},now:{params:[],returns:`timestamp`}},m={extensions:{arithmetic:`now-offset`,durationUnits:!0}},h=e=>{switch(e.type){case`text`:return`string`;case`integer`:case`bigint`:return`integer`;case`boolean`:case`timestamp`:case`enum`:return e.type;default:return`any`}},g=e=>({fields:Object.fromEntries(Object.values(e.fields).map(e=>[e.name,{type:h(e),filterable:e.filterable,sortable:e.sortable,aliases:e.aliases,...e.enumValues&&{values:e.enumValues}}])),functions:p}),_=(e,t)=>`path`in e?{kind:`member`,path:e.path,span:e.span}:{kind:`member`,path:[e.name],field:{name:e.name,spec:{type:h(e)}},span:t},v=(e,t,n)=>({kind:`call`,name:e,args:t,span:n}),y=(e,t)=>({kind:`string`,value:e,span:t}),ee=({orderBy:e,limit:t,pageToken:n,span:r})=>{if(e===void 0&&t===void 0)return[];let i=y(e??``,r);if(t===void 0)return[i];let a={kind:`number`,value:t,raw:String(t),span:r};return n===void 0?[i,a]:[i,a,y(n,r)]},te=e=>{if(e.kind!==`now`)return e;let t={kind:`call`,name:`now`,args:[],span:e.span};return e.offset?{kind:`binary`,op:e.offset.sign,left:t,right:e.offset.duration,span:e.span}:t},b=(e,t={})=>{let n=e=>b(e,t);switch(e.kind){case`and`:case`or`:return{kind:e.kind,args:e.args.map(n),span:e.span};case`not`:return{kind:`not`,arg:n(e.arg),span:e.span};case`compare`:return{kind:`compare`,op:e.op,left:_(e.field,e.span),right:te(e.value),span:e.span};case`has`:return{kind:`has`,left:_(e.field,e.span),right:e.value,span:e.span};case`present`:return{kind:`present`,left:_(e.field,e.span),span:e.span};case`in`:return t.expand?{kind:`or`,args:e.values.map(t=>({kind:`compare`,op:`=`,left:_(e.field,e.span),right:t,span:e.span})),span:e.span}:v(`in`,[_(e.field,e.span),...e.values],e.span);case`search`:return v(`search`,[y(e.text,e.span)],e.span);case`similar`:return v(`similar`,[_(e.field,e.span),y(e.text,e.span)],e.span);case`regex`:return v(`regex`,[_(e.field,e.span),y(e.pattern,e.span)],e.span);case`isNull`:return t.expand?{kind:`not`,arg:{kind:`present`,left:_(e.field,e.span),span:e.span},span:e.span}:v(`isNull`,[_(e.field,e.span)],e.span);case`related`:return{kind:`call`,name:`related`,args:[_(e.field,e.span),{kind:`member`,path:[e.resource,e.key],span:e.span},...e.filter?[n(e.filter)]:[],...ee(e)],span:e.span}}},x=e=>a(b(e)),ne=e=>`${e}/workflows/types`,S=(e,t)=>`${e}/workflows/runners/${encodeURIComponent(t)}/registration`,C=e=>`${e}/workflows/runs`,re=`after`,ie=`revision`,ae=(e,t,n)=>{let r=`${C(e)}/${encodeURIComponent(t)}/trace`;return!n||n.after===0?r:`${r}?${new URLSearchParams({[re]:String(n.after),[ie]:n.revision})}`},w=e=>{if(!Array.isArray(e))return String(e);let t=e;return t.length===1?String(t[0]):t.map(e=>encodeURIComponent(String(e))).join(`,`)},oe=e=>{if(!(e instanceof DOMException&&e.name===`AbortError`))throw e},T=async(e,t,n)=>{let r=s({onEvent:e=>t(e.data)}),i=new TextDecoder,a=e.getReader();for(n?.addEventListener(`abort`,()=>void a.cancel().catch(oe),{once:!0});;){let{done:e,value:t}=await a.read();if(e)break;r.feed(i.decode(t,{stream:!0}))}r.feed(`${i.decode()}\n\n`)},se=`token`,ce=(e,t)=>`${e}?${new URLSearchParams({[se]:t})}`,E=(e,t)=>`${e}/notifications/devices${t===void 0?``:`/${encodeURIComponent(t)}`}`,le=`app`,ue=e=>`${e}/files`,de=(e,t,n)=>`${e}/${t}/${n}`,fe=e=>{let t=/^([a-z][a-z0-9-]*):([A-Za-z0-9_-][^?#]*)/.exec(e);return t?{provider:t[1],path:t[2]}:void 0},D=e=>`${e}${e.includes(`?`)?`&`:`?`}via=${le}`,pe=/^[A-Za-z0-9_-]{1,64}$/,O=(e,t)=>{let n=`${e}/notifications/history`;if(t===void 0)return n;if(typeof t==`string`)return`${n}/${t}`;if(!pe.test(t.read))throw Error(`A history entry id is letters, digits, "_" and "-" only`);return`${n}/${t.read}/read`},k=(e,t)=>`${e}/status${t===void 0?``:`/${t}`}`,me=/\p{Cc}/u,he=e=>{if(me.test(e))return`A status is one line of text, without control characters`;if([...e].length>100)return`A status is at most 100 characters`},ge=(e,t=Date.now())=>{if(e&&!(e.clearsAt!==null&&Date.parse(e.clearsAt)<=t)&&(e.availability!==`automatic`||e.text!==null))return e},_e=`$rings`,ve=`decline`,ye=(e,t)=>{let n=`${e}/calls/rings`;return t===void 0?n:`${n}/${encodeURIComponent(t.decline)}/${ve}`},be=`calls`,A=e(t(),1),j={meta:[`meta`],activeRole:[`session`,`active-role`],organizations:[`session`,`organizations`],organizationMembers:e=>[`session`,`members`,e],sourceMeta:(e,t)=>[`source-meta`,e,t.join(`,`)],sourceMetas:e=>[`source-meta`,e],list:(e,t,n,r,i)=>[`list`,e,t,n,r,i],page:(e,t,n,r,i)=>[`page`,e,t,n,r,i],pages:(e,t,n)=>[`page`,e,t,n],navRecent:(e,t,n,r)=>[`list`,e,t,n,r,`nav-recent`],first:(e,t,n)=>[`first-page`,e,t,n],record:(e,t)=>[`record`,e,t],image:(e,t)=>[`image`,e,t],recordPreview:(e,t)=>[`record-preview`,e,t],history:(e,t,n)=>[`record`,e,t,`history`,n],comments:(e,t)=>[`record`,e,t,`comments`],facets:(e,t,n)=>[`facets`,e,t,n],series:(e,t,n,r,i)=>[`series`,e,t,n,r,i],aggregate:(e,t)=>[`aggregate`,e,t],histogram:(e,t,n,r)=>[`histogram`,e,t,n,r],map:(e,t,n,r,i)=>[`map`,e,t,n,r,i],relatedLabel:(e,t)=>[`related-label`,e,t],titleRow:(e,t,n)=>[`title-row`,e,t,n],labels:(e,t)=>[`labels`,e,t],pickedLabels:(e,t)=>[`picked-labels`,e,t],count:(e,t)=>[`count`,e,t],planRead:(e,t)=>[`plan`,e[0],e,t],exportCount:(e,t)=>[`list`,e,t,`export-count`],firstRecord:(e,t,n)=>[`first-record`,e,t,n],pathValue:(e,t,n)=>[`path-value`,e,t,n],inbox:[`inbox`],inboxUnread:[`inbox`,`unread`],inboxPages:[`inbox`,`pages`],members:e=>[`members`,e],statuses:e=>[`statuses`,e],ownStatus:e=>[`statuses`,e,`own`],rings:[`call-rings`],recordCalls:(e,t)=>[`record-calls`,e,t],workflowTypes:[`workflow-types`],workflowRunTrace:e=>[`workflow-run-trace`,e],publicForm:e=>[`public-form`,e]},xe=(e,t)=>t.has(e[1])||e[0]===`plan`&&e[2].some(e=>t.has(e)),Se={name:`loader-circle`,size:24,node:[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]],aliases:[`loader-2`]};Se.node;var Ce=u(Se),we=l(`primitives`),M=e(n(),1),Te=({className:e,hidden:t=!1})=>(0,M.jsx)(Ce,{...t?{"aria-hidden":!0}:{"aria-label":we(`loading`)},className:f(`size-4 animate-spin`,e)}),Ee={primary:`bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm`,secondary:`bg-background text-foreground border border-border-strong hover:bg-muted shadow-sm`,ghost:`text-muted-foreground hover:bg-muted hover:text-foreground`,danger:`bg-background text-danger-text border border-border-strong hover:bg-danger-soft shadow-sm`},De={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`},Oe=({variant:e=`secondary`,size:t=`md`}={})=>f(`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`,Ee[e],De[t]),ke=({variant:e=`secondary`,size:t=`md`,loading:n,className:r,children:i,disabled:a,...o})=>(0,M.jsxs)(`button`,{type:`button`,disabled:a||n,"aria-busy":n||void 0,className:f(Oe({variant:e,size:t}),r),...o,children:[n&&(0,M.jsx)(Te,{hidden:!0,className:`size-3.5`}),i]}),N=e=>typeof e==`string`?e:e&&x(e),P=e=>{let t=Object.entries(e??{}).map(([e,t])=>`${e}.${t}`);return t.length>0?t:void 0},Ae=e=>({photos:e&&`${e.resource}.${e.field}.${e.image}`,photos_order_by:e?.sort}),F=(e={})=>({filter:N(e.filter)||void 0,order_by:e.orderBy,page_size:e.pageSize,page_token:e.pageToken||void 0,fields:e.fields?.join(`,`),labels:P(e.labels)?.join(`,`),...Ae(e.photos),count:e.count,limit_per:e.limitPer&&`${e.limitPer.field}:${e.limitPer.count}`,etag:e.etag===!1?`false`:void 0}),I=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))r!==void 0&&t.set(n,String(r));let n=t.toString();return n?`?${n}`:``},je=e=>e.startsWith(`/`)&&!e.startsWith(`//`),Me=e=>{if(typeof e!=`object`||!e)return!1;let{uri:t,url:n}=e;return typeof t==`string`&&typeof n==`string`&&je(n)},Ne=e=>e!==void 0&&URL.canParse(e)?new URL(e).origin:void 0,Pe=(e,t)=>({...e,url:`${t}${e.url}`,...e.variants&&{variants:Object.fromEntries(Object.entries(e.variants).map(([e,n])=>[e,je(n.url)?{...n,url:`${t}${n.url}`}:n]))}}),L=(e,t)=>t===void 0||typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Me(n)?Pe(n,t):n])),Fe=(e,t)=>t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,n.map(e=>Me(e)?Pe(e,t):e)])),R=class extends Error{problem;constructor(e){super(e.detail??e.title),this.problem=e,this.name=`ApiError`}get status(){return this.problem.status}get slug(){return this.problem.type.split(`:`).at(-1)??``}get operation(){return this.problem.operation??this.errors.find(e=>e.operation!==void 0)?.operation}get blockedBy(){return this.problem.blockedBy}get existing(){return this.problem.existing}get errors(){return this.problem.errors??[]}get filterErrors(){return this.slug===`invalid-filter`?this.errors:[]}},Ie=class extends R{constructor(e){super(e),this.name=`PreconditionFailedError`}},Le=e=>e instanceof R,Re=e=>typeof e==`object`&&!!e&&`type`in e&&`status`in e,ze=async e=>{let t=e.headers.get(`content-type`)?.includes(`json`)??!1?await e.json():void 0,n=Re(t)?t:{type:`urn:protobase:problem:unknown`,title:e.statusText||`Request failed`,status:e.status};return n.status===412?new Ie(n):new R(n)},Be=(e=`/api/v1`)=>e.replace(/\/[^/]*$/,``),Ve=(e={})=>{let t=e.baseUrl??`/api/v1`,n=Be(t),r=e.fetch??((e,t)=>fetch(e,t));return async({method:i,path:a,query:o=``,body:s,headers:c,accept:l=[],system:u,raw:d,via:f,signal:p,cache:m})=>{let h=async l=>{let h=await e.token?.({refresh:l});return(f??r)(`${u?n:t}${a}${o}`,{method:i,headers:{...s!==void 0&&{"content-type":`application/json`},...h&&{authorization:`Bearer ${h}`},...e.headers?.(),...c},body:d??(s===void 0?void 0:JSON.stringify(s)),...p&&{signal:p},...m&&{cache:m}})},g=await h(!1);g.status===401&&e.token&&(g=await h(!0),g.status===401&&e.onUnauthenticated?.());let _=g.headers.get(`x-meta-version`);if(_&&e.onMetaVersion?.(_),!g.ok&&!l.includes(g.status))throw await ze(g);return g}},He=(e,t)=>{if(!URL.canParse(t))return{link:e,api:t};let n=new URL(t);return{link:new URL(e,n).href,api:`${n.origin}${n.pathname.replace(/\/$/,``)}`}},Ue=(e,t)=>{if(!e.url.startsWith(`/`)&&!/^https?:\/\//i.test(e.url))return e.url;let n=fe(e.uri);if(!n)return e.url;let{link:r,api:i}=He(e.url,t),a=ue(i);return r.startsWith(`${a}/`)?D(r):D(de(a,n.provider,n.path))},We=e=>new Headers(e.trim().split(/[\r\n]+/).filter(Boolean).map(e=>{let t=e.indexOf(`:`);return[e.slice(0,t).trim(),e.slice(t+1).trim()]})),Ge=e=>(t,n={})=>new Promise((r,i)=>{let a=new XMLHttpRequest;a.open(n.method??`GET`,String(t)),new Headers(n.headers).forEach((e,t)=>a.setRequestHeader(t,e)),a.responseType=`blob`,a.upload.onprogress=t=>e(t.loaded,t.lengthComputable?t.total:t.loaded),a.onload=()=>{let e=a.status===204||a.status===304;r(new Response(e?null:a.response,{status:a.status,statusText:a.statusText,headers:We(a.getAllResponseHeaders())}))},a.onerror=()=>i(TypeError(`Network request failed`)),a.onabort=()=>i(new DOMException(`The upload was aborted`,`AbortError`)),n.signal?.addEventListener(`abort`,()=>a.abort()),a.send(n.body)}),Ke=e=>Math.min(3e4,1e3*2**e),qe=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(r),n()},{once:!0})}),Je=(e,t,n=Ke)=>{let r=new AbortController,{signal:i}=r,a,o=0,s=e=>{o=0,a=e.cursor,e.type===`resync`&&t.onResync(),e.type===`changes`&&t.onChanges(e.changes)},c=async()=>{let t=await e({method:`GET`,path:`/live`,query:I({after:a}),headers:{accept:`text/event-stream`},system:!0,signal:i});if(!t.body)throw Error(`The server answered the live stream without a body`);await T(t.body,e=>s(JSON.parse(e)),i)};return(async()=>{for(;!i.aborted;){let e=await c().then(()=>void 0,e=>e);if(i.aborted)return;t.onRetry?.(e),await qe(n(o++),i)}})(),()=>r.abort()},Ye=e=>{let t=new Set,n,r=e=>{for(let n of[...t])e(n)};return i=>{let a={...i};return t.add(a),n??=e({onChanges:e=>r(t=>t.onChanges(e)),onResync:()=>r(e=>e.onResync()),onRetry:e=>r(t=>t.onRetry?.(e))}),()=>{!t.delete(a)||t.size>0||(n?.(),n=void 0)}}},Xe=new TextEncoder,Ze=new TextDecoder,z=4,Qe=(e,t)=>{let n=Xe.encode(JSON.stringify(e)),r=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=new Uint8Array(z+n.length+r.length);return new DataView(i.buffer).setUint32(0,n.length),i.set(n,z),i.set(r,z+n.length),i.buffer},$e=e=>{let t=z+new DataView(e).getUint32(0);return{...JSON.parse(Ze.decode(new Uint8Array(e,z,t-z))),payload:e.slice(t)}},et=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),B=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`ChannelRefusal`}},tt=5e3,nt=1,rt=`protobase.channels`,it=({url:e,token:t,socket:n,retryDelay:r,onOpen:i,onDown:a,onMessage:o})=>{let s,c=!1,l=0,u=0,d,f=0,p,m,h=new Map,g=()=>{for(let{reject:e}of h.values())e(new B(`disconnected`,`The connection dropped before the server answered`));h.clear()},_=async e=>{let n=await t?.();s===e&&e.readyState===nt&&n!==void 0&&n!==d&&(d=n,e.send(JSON.stringify({type:`token`,token:n})))},v=async()=>{let u=await t?.();if(!c||s)return;d=u;let y=n(e(),u===void 0?[rt]:[rt,`bearer.${u}`]);s=y,y.binaryType=`arraybuffer`,y.onopen=()=>{l=0,f=Date.now(),p=setInterval(()=>{if(Date.now()-f>1e4)return y.close();y.send(JSON.stringify({type:`ping`})),_(y)},tt),i()},y.onmessage=({data:e})=>{if(f=Date.now(),typeof e!=`string`&&!(e instanceof ArrayBuffer))return;let t=typeof e==`string`?JSON.parse(e):$e(e);if(t.type!==`reply`)return o(t);let n=h.get(t.ref);h.delete(t.ref),t.ok?n?.resolve(t):n?.reject(new B(t.error.code,t.error.message))},y.onclose=()=>{s===y&&(clearInterval(p),s=void 0,g(),c&&(a(),m=setTimeout(()=>{m=void 0,v()},r(l++))))}},y=(e,t)=>s?.readyState===nt&&(s.send(t===void 0?JSON.stringify(e):Qe(e,t)),!0);return{start:()=>{c=!0,!s&&m===void 0&&v()},stop:()=>{c=!1,clearTimeout(m),m=void 0,clearInterval(p);let e=s;s=void 0,g(),e?.close(1e3)},request:(e,t)=>new Promise((n,r)=>{let i=String(++u);if(!y({...e,ref:i},t))return r(new B(`disconnected`,`The connection is down`));h.set(i,{resolve:n,reject:r})}),post:y}},at=e=>{if(!(e instanceof B&&e.code===`disconnected`))throw e},ot=()=>new B(`not-joined`,`The channel is not joined yet`),st=e=>{let t=new Map,n=new Map,r=(e,t)=>{e.status=t;for(let n of e.statusListeners)n(t)},i=(e,t)=>{let n=[...e.presence.values()];for(let r of e.presenceListeners)r(n,t)},a=e=>{t.delete(e),t.size===0&&c.stop()},o=e=>{let i=`${e.resource}/${e.key}`;c.request({type:`join`,resource:e.resource,key:e.key}).then(o=>{if(t.get(i)===e){if(e.holders===0)return c.post({type:`leave`,channel:o.channel}),a(i);e.name=o.channel,n.set(e.name,e),r(e,{state:`joined`}),e.tracked&&c.request({type:`track`,channel:e.name,state:e.tracked.state}).catch(at)}}).catch(n=>{if(t.get(i)===e&&e.holders===0&&n instanceof B)return a(i);if(!(n instanceof B)||n.code===`disconnected`)return at(n);r(e,{state:`refused`,error:{code:n.code,message:n.message}})})},s=e=>{if(e.type===`pong`||e.type===`reply`||e.type===`error`)return;let t=n.get(e.channel);if(t){if(e.type===`presence`)return t.presence=new Map(e.entries.map(e=>[e.id,e])),i(t);if(e.type===`presence_diff`){for(let n of e.leaves)t.presence.delete(n.id);for(let n of[...e.joins,...e.updates])t.presence.set(n.id,n);return i(t,{joins:e.joins,updates:e.updates,leaves:e.leaves})}if(e.type===`broadcast`){let{event:n,payload:r,user:i,server:a}=e;for(let e of t.eventListeners.get(n)??[])e({event:n,payload:r,user:i,...a&&{server:a}});return}n.delete(e.channel),t.presence.clear(),i(t),r(t,{state:`closed`,error:e.error})}},c=it({...e,onOpen:()=>{for(let[e,n]of t)n.status.state===`joining`&&(n.holders===0?a(e):o(n))},onDown:()=>{n.clear();for(let e of t.values())e.status.state===`joined`&&r(e,{state:`joining`})},onMessage:s}),l=(e,t)=>{--t.holders,!(t.holders>0)&&(t.tracked=void 0,t.status.state!==`joining`&&(t.name!==void 0&&(n.delete(t.name),c.post({type:`leave`,channel:t.name})),a(e)))},u=(e,t)=>{let n=!1,r=new Set,i=(e,t)=>{e.add(t);let n=()=>{e.delete(t),r.delete(n)};return r.add(n),n},a=()=>t.status.state===`joined`?t.name:void 0;return{status:()=>t.status,onStatus:e=>i(t.statusListeners,e),presence:()=>[...t.presence.values()],onPresence:e=>i(t.presenceListeners,e),track:async e=>{t.tracked={state:e};let n=a();n!==void 0&&await c.request({type:`track`,channel:n,state:e})},untrack:async()=>{t.tracked=void 0;let e=a();e!==void 0&&await c.request({type:`untrack`,channel:e})},send:async(e,t,{self:n,ack:r}={})=>{let i=a();if(i===void 0)throw ot();let o=et(t)?t:void 0,s={type:`send`,channel:i,event:e,...o===void 0&&{payload:t},...n&&{self:n}};if(r){await c.request({...s,ack:r},o);return}if(!c.post(s,o))throw new B(`disconnected`,`The connection is down`)},on:(e,n)=>{let r=t.eventListeners.get(e)??new Set;return t.eventListeners.set(e,r),i(r,n)},leave:()=>{if(!n){n=!0;for(let e of[...r])e();l(e,t)}}}};return{channel:(e,n)=>{let r=w(n),i=`${e}/${r}`,a=t.get(i);if(a)return a.holders+=1,u(i,a);let s={resource:e,key:r,status:{state:`joining`},presence:new Map,holders:1,statusListeners:new Set,presenceListeners:new Set,eventListeners:new Map};return t.set(i,s),c.start(),o(s),u(i,s)}}},ct=({send:e,socketUrl:t,socket:n})=>({open:async(r,i)=>{let a=`/functions/${encodeURIComponent(r)}`,{token:o,expires_at:s}=await(await e({method:`POST`,path:a,system:!0,body:{target:i}})).json(),c=n(t(ce(a,o)),[]);return c.binaryType=`arraybuffer`,{socket:c,expiresAt:new Date(s)}}}),lt=e=>({register:async t=>(await e({method:`POST`,path:E(``),system:!0,body:t})).json(),remove:async t=>{await e({method:`DELETE`,path:E(``,t),system:!0})}}),ut=e=>({own:async()=>(await(await e({method:`GET`,path:k(``),system:!0})).json()).status,set:async t=>(await(await e({method:`PUT`,path:k(``),system:!0,body:t})).json()).status,clear:async()=>{await e({method:`DELETE`,path:k(``),system:!0})},people:async()=>(await(await e({method:`GET`,path:k(``,`people`),system:!0})).json()).statuses}),dt=e=>async(t,n)=>(await e({method:`GET`,path:ae(``,t,n),system:!0})).json(),ft=e=>async()=>(await e({method:`GET`,path:ne(``),system:!0})).json(),pt=e=>async t=>(await e({method:`POST`,path:S(``,t),system:!0})).json(),mt=e=>({list:async({cursor:t,limit:n}={})=>{let r=new URLSearchParams({...t!==void 0&&{cursor:t},...n!==void 0&&{limit:String(n)}}),i=r.size>0?`?${r}`:``;return(await e({method:`GET`,path:O(``),query:i,system:!0})).json()},unread:async()=>(await(await e({method:`GET`,path:O(``,`unread`),system:!0})).json()).count,markRead:async t=>{await e({method:`POST`,path:O(``,{read:t}),body:{},system:!0})},markAllRead:async t=>{await e({method:`POST`,path:O(``,`read`),body:{upTo:t},system:!0})}}),ht=e=>Math.min(3e4,1e3*2**e),gt=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(r),n()},{once:!0})}),_t=(e,t,n=ht)=>({calls:async(n,r)=>(await(await e({method:`GET`,path:t(n,r)})).json()).items,watchCalls:(r,i,a)=>{let o=new AbortController,{signal:s}=o,c=0,l=async()=>{let n=await e({method:`GET`,path:t(r,i),query:`?watch=true`,headers:{accept:`text/event-stream`},signal:s});if(!n.body)throw Error(`The server answered the calls stream without a body`);await T(n.body,e=>{c=0,a.onCalls(JSON.parse(e).items)},s)};return(async()=>{for(;!s.aborted;){let e=await l().then(()=>void 0,e=>e);if(s.aborted)return;a.onRetry?.(e),await gt(n(c++),s)}})(),()=>o.abort()}}),vt=e=>({list:async()=>(await(await e({method:`GET`,path:ye(``),system:!0})).json()).items,decline:async t=>{await e({method:`POST`,path:ye(``,{decline:t}),system:!0,body:{}})}}),yt=e=>({allowed:async()=>(await(await e({method:`GET`,path:d(``,`organization`),system:!0})).json()).allowed,setAllowed:async t=>{await e({method:`PUT`,path:d(``,`organization`),system:!0,body:{allowed:t}})}}),bt=4e3,V=e=>typeof e==`string`?e:e.toModel().name,xt=(e=`/api/v1`,t)=>{let n=new URL(`${e.replace(/\/[^/]*$/,``)}${t}`,globalThis.location?.href);return n.protocol=n.protocol===`https:`?`wss:`:`ws:`,n.toString()},H=(e,t)=>`/${V(e)}/${w(t)}`,St=(e,t)=>`${H(e,t)}:calls`,U=(e,t,n)=>({items:e.items.map(e=>L(e,n)),nextPageToken:e.next_page_token,totalSizeEstimate:e.total_size_estimate,...e.prev_page_token!==void 0&&{prevPageToken:e.prev_page_token},...e.total_size!==void 0&&{totalSize:e.total_size},...e.labels!==void 0&&{labels:e.labels},...e.photos!==void 0&&{photos:Fe(e.photos,n)},...t.headers.get(`x-protobase-warning`)&&{warning:t.headers.get(`x-protobase-warning`)}}),W=({created_at:e,...t})=>({...t,createdAt:e}),G=e=>e.headers.get(`etag`)??``,K=async(e,t)=>{let{permissions:n,...r}=await e.json();return{record:L(r,t),etag:G(e),...n&&{permissions:n}}},Ct=(e,t)=>({results:(e.results??[]).map(e=>e.op===`create`||e.op===`update`?{...e,record:L(e.record,t)}:e.op===`reorder`||e.op===`move`?{...e,records:e.records.map(e=>({...e,record:L(e.record,t)}))}:e)}),q=(e={})=>{let t=Ve(e),n=Ne(e.baseUrl),r=async(e,r)=>{let i=F(r),a=await t({method:`POST`,path:`/${V(e)}:search`,body:{...i,fields:r?.fields,labels:P(r?.labels)}});return U(await a.json(),a,n)},i=async(e,i)=>{let a=I(F(i));if(a.length>bt)return r(e,i);let o=await t({method:`GET`,path:`/${V(e)}`,query:a});return U(await o.json(),o,n)},a=async(e,r)=>K(await t({method:`GET`,path:H(e,r)}),n),o=async(e,r)=>{let i=await t({method:`POST`,path:`/${V(e)}`,body:r});return{record:L(await i.json(),n),etag:G(i),location:i.headers.get(`location`)??``}},s=async(e,r,i,a)=>K(await t({method:`PATCH`,path:H(e,r),body:i,headers:{"if-match":a}}),n),c=async(e,n,{etag:r}={})=>{await t({method:`DELETE`,path:H(e,n),headers:r?{"if-match":r}:void 0})},l=async(e,r)=>{let i=await t({method:`POST`,path:`${H(e,r)}:undelete`});return{record:L(await i.json(),n),etag:G(i)}},u=async(e,n,r)=>(await(await t({method:`POST`,path:`${H(e,n)}:reveal`,body:{field:r}})).json()).value,d=async(e,r,i)=>K(await t({method:`POST`,path:`${H(e,r)}:generate`,body:{action:i}}),n),f=async(e,n,{pageSize:r,pageToken:i}={})=>{let a=I({page_size:r,page_token:i||void 0}),o=await(await t({method:`GET`,path:`${H(e,n)}:history`,query:a})).json();return{items:o.items.map(({database_role:e,...t})=>({...t,databaseRole:e})),nextPageToken:o.next_page_token}},p=async(e,n,{pageSize:r,pageToken:i}={})=>{let a=I({page_size:r,page_token:i||void 0}),o=await(await t({method:`GET`,path:`${H(e,n)}:comments`,query:a})).json();return{items:o.items.map(W),nextPageToken:o.next_page_token}},m=async(e,n,{body:r,mentions:i=[]})=>W(await(await t({method:`POST`,path:`${H(e,n)}:comments`,body:{body:r,mentions:i}})).json()),h=async(e,n,r)=>(await(await t({method:`GET`,path:`${H(e,n)}:mentionable`,query:I({q:r})})).json()).items,g=async e=>{let r=e=>typeof e==`object`&&e&&`$ref`in e?e:w(e),i=e.map(e=>({...e,resource:V(e.resource),...`key`in e&&{key:r(e.key)},...e.op===`reorder`&&{keys:e.keys.map(r)},...e.op===`move`&&{after:e.after&&r(e.after),...e.before!==void 0&&{before:e.before&&r(e.before)}}}));return Ct(await(await t({method:`POST`,path:`:batchWrite`,body:{ops:i}})).json(),n)},_=async(e,n,r={})=>(await(await t({method:`GET`,path:`/${V(e)}:facets`,query:I({field:n,filter:N(r.filter)||void 0,limit:r.limit,label:r.label})})).json()).facets,v=async(e,n)=>{let r=await(await t({method:`GET`,path:`/${V(e)}:aggregate`,query:I({group_by:n.groupBy,filter:N(n.filter)||void 0,sum:n.sum,average:n.average,maximum:n.maximum,limit:n.limit,label:n.label,granularity:n.granularity,range:n.range,from:n.from,to:n.to,time_zone:n.timeZone,split_by:n.splitBy,split_limit:n.splitLimit,split_label:n.splitLabel})})).json();return{groupBy:r.group_by,granularity:r.granularity,timeZone:r.time_zone,groups:r.groups,...r.split_by!==void 0&&{splitBy:r.split_by,splits:r.splits}}},y=async(e,n)=>{let r=await(await t({method:`GET`,path:`/${V(e)}:series`,query:I({field:n.field,range:n.range,from:n.from,to:n.to,granularity:n.granularity,time_zone:n.timeZone,filter:N(n.filter)||void 0})})).json();return{field:r.field,granularity:r.granularity,timeZone:r.time_zone,points:r.points}},ee=async(e,n,r={})=>(await t({method:`GET`,path:`/${V(e)}:histogram`,query:I({field:n,buckets:r.buckets,filter:N(r.filter)||void 0})})).json(),te=async(e,r)=>{let i=await(await t({method:`GET`,path:`/${V(e)}:map`,query:I({latitude:r.latitude,longitude:r.longitude,zoom:r.zoom,filter:N(r.filter)||void 0,order_by:r.orderBy,fields:r.fields?.join(`,`),labels:P(r.labels)?.join(`,`),...Ae(r.photos)})})).json();return{items:i.items.map(e=>L(e,n)),buckets:i.buckets,totalSize:i.total_size,...i.labels!==void 0&&{labels:i.labels},...i.photos!==void 0&&{photos:Fe(i.photos,n)}}},b=async(e,r)=>{let i=await t({method:`GET`,path:`/${V(e)}:seek`,query:I({...F(r),position:r.position})});return U(await i.json(),i,n)},x=async(e,{signal:n}={})=>{let r=await t({method:`GET`,path:`/meta`,system:!0,headers:e?{"if-none-match":e}:void 0,accept:[304],...n&&{signal:n}});return r.status===304?{status:`unchanged`}:{status:`modified`,meta:await r.json(),etag:G(r)}},ne=async(e,{method:n,body:r,path:i=``,query:a,headers:o,cache:s}={})=>{let c=await t({method:n??(r===void 0?`GET`:`POST`),path:`/functions/${encodeURIComponent(e)}${i}`,query:a?`?${new URLSearchParams(a)}`:``,body:r,headers:o,system:!0,...s&&{cache:s}});if(c.status===204)return;let l=c.headers.get(`content-type`);return l?.includes(`json`)?c.json():!l||l.startsWith(`text/`)?c.text():c.blob()},S=async(e,n,r,{onProgress:i,signal:a}={})=>{let o=`name`in r&&typeof r.name==`string`?r.name:void 0,s=i&&typeof XMLHttpRequest<`u`?Ge(i):void 0,c=await(await t({method:`POST`,path:`/${V(e)}:upload`,query:`?${new URLSearchParams({field:n,...o!==void 0&&{name:o}})}`,raw:r,headers:{"content-type":r.type||`application/octet-stream`},...s&&{via:s},...a&&{signal:a}})).json();return i?.(r.size,r.size),c},C=e=>`/forms/${encodeURIComponent(e)}`,re=async e=>(await t({method:`GET`,path:C(e),system:!0})).json(),ie=async e=>(await t({method:`GET`,path:`${C(e)}:challenge`,system:!0})).json(),ae=async(e,n,r)=>{await t({method:`POST`,path:C(e),body:{values:n,proof:r},system:!0})},oe=Ye(e=>Je(t,e)),T=e.webSocket??((e,t)=>new WebSocket(e,t)),{channel:se}=st({url:()=>xt(e.baseUrl,`/channels`),...e.token&&{token:()=>e.token({refresh:!1})},socket:T,retryDelay:e=>Math.min(3e4,1e3*2**e)}),ce=ct({send:t,socketUrl:t=>xt(e.baseUrl,t),socket:T}),E=lt(t),le=mt(t),{calls:ue,watchCalls:de}=_t(t,St),fe=ut(t),D=ft(t),pe=dt(t),O=pt(t);return{list:i,search:r,get:a,create:o,update:s,remove:c,undelete:l,generate:d,reveal:u,history:f,comments:p,comment:m,mentionable:h,batchWrite:g,facets:_,aggregate:v,series:y,histogram:ee,map:te,seek:b,meta:x,invoke:ne,upload:S,form:re,formChallenge:ie,submitForm:ae,live:oe,channel:se,bridges:ce,devices:E,notifications:le,status:fe,calls:ue,watchCalls:de,rings:vt(t),callGuests:yt(t),workflowTypes:D,workflowRunTrace:pe,runnerRegistration:O,fileReadUrl:(t,n)=>Ue(n,Be(e.baseUrl))}},wt=()=>{let e=0;return{refetchOnWindowFocus:()=>e>0?!1:`always`,paused:()=>e>0,pause:()=>{e+=1;let t=!1;return()=>{t||(t=!0,--e)}}}},J=(0,A.createContext)(null),Tt=e=>{let t=(0,A.useContext)(J);(0,A.useEffect)(()=>e&&t?t.pause():void 0,[e,t])},Et=e=>{let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),window.addEventListener(`focus`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t),window.removeEventListener(`focus`,t)}},Y=(0,A.createContext)(0),X=(e,t)=>e.data!==void 0&&e.dataUpdatedAt<t,Dt=(e,t)=>{let n=e.filter(e=>X(e.state,t));return n.length===0?`fresh`:n.some(e=>e.state.status===`error`||e.state.fetchFailureCount>0||e.state.fetchStatus===`paused`)?`failed`:n.some(e=>e.state.fetchStatus===`fetching`)?`refreshing`:`stale`},Ot=(e,t)=>e.getQueryCache().subscribe(e=>{e.type===`updated`&&e.action.type===`error`&&X(e.query.state,t)&&e.query.setState({status:`success`,error:null})}),kt=()=>{let e=c().getQueryCache(),t=(0,A.useContext)(Y),n=(0,A.useCallback)(t=>e.subscribe(t),[e]),r=(0,A.useCallback)(()=>Dt(e.findAll({type:`active`}),t),[e,t]);return(0,A.useSyncExternalStore)(n,r,r)},Z=(0,A.createContext)(null),At=(0,A.createContext)(null),Q=(0,A.createContext)(null),$=()=>{let e=(0,A.useContext)(Z);if(!e)throw Error(`useClient must be used inside ApiProvider`);return e},jt=e=>{let t=$();return(0,A.useContext)(Q)?.(e)??t},Mt=()=>{let e=$(),t=(0,A.useContext)(Q);return(0,A.useCallback)(n=>t?.(n)??e,[e,t])},Nt=()=>{let e=(0,A.useContext)(At);if(!e)throw Error(`useSourceClients must be used inside ApiProvider`);return e},Pt=({client:e,resourceClient:t,children:n})=>(0,M.jsx)(Z.Provider,{value:e,children:(0,M.jsx)(Q.Provider,{value:t,children:n})}),Ft=({baseUrl:e,client:t,sources:n,fetch:a,queryClient:s,token:c,onUnauthenticated:l,persistence:u,children:d})=>{let[f]=(0,A.useState)(wt),[{queryClient:p,startedAt:m}]=(0,A.useState)(()=>{let e=s??new r({defaultOptions:{queries:{staleTime:3e4,retry:!1,refetchOnWindowFocus:f.refetchOnWindowFocus}}});return u?.restore(e),{queryClient:e,startedAt:Date.now()}});(0,A.useEffect)(()=>u?.subscribe(p),[u,p]),(0,A.useEffect)(()=>u?Ot(p,m):void 0,[u,p,m]),(0,A.useEffect)(()=>i.setEventListener(Et),[]);let h=(0,A.useRef)(void 0),g=(0,A.useMemo)(()=>t??q({baseUrl:e,fetch:a,token:c,onUnauthenticated:l,onMetaVersion:e=>{let t=h.current;h.current=e,t!==void 0&&t!==e&&(p.getQueryData(j.meta)?.versionChange||p.invalidateQueries({queryKey:j.meta},{cancelRefetch:!1}))}}),[t,e,a,p,c,l]),_=(0,A.useMemo)(()=>{let e=new Map;return t=>{let r=n?.[t.url]??e.get(t.url);if(r)return r;let i,o=q({baseUrl:t.url,fetch:a,token:c,onMetaVersion:e=>{let n=i;i=e,n!==void 0&&n!==e&&p.invalidateQueries({queryKey:j.sourceMetas(t.url)},{cancelRefetch:!1})}});return e.set(t.url,o),o}},[n,a,c,p]);return(0,M.jsx)(o,{client:p,children:(0,M.jsx)(Z.Provider,{value:g,children:(0,M.jsx)(At.Provider,{value:_,children:(0,M.jsx)(J.Provider,{value:f,children:(0,M.jsx)(Y.Provider,{value:m,children:d})})})})})};export{x as A,xe as C,he as D,ge as E,p as M,m as N,T as O,g as P,j as S,_e as T,N as _,Mt as a,Te as b,X as c,Tt as d,q as f,ze as g,Le as h,jt as i,b as j,w as k,kt as l,Ie as m,Pt as n,Nt as o,R as p,$ as r,Y as s,Ft as t,J as u,ke as v,be as w,we as x,Oe as y};
2
+ //# debugId=4926b3a8-3b89-4282-9afd-90449820d851