@ai4b-team/fsaos-gateway-sdk 5.7.0 → 5.8.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/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import React, { createElement, useMemo, useState, useRef, useEffect, useSyncExternalStore, useCallback, useLayoutEffect } from 'react';
2
- import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueryClient, useMutation as useMutation$1 } from '@tanstack/react-query';
1
+ import React, { createElement, useSyncExternalStore, useMemo, useState, useRef, useEffect, useCallback, useLayoutEffect } from 'react';
2
+ import { QueryClient, QueryClientProvider, useQuery, useQueries, useInfiniteQuery, useQueryClient, useMutation as useMutation$1 } from '@tanstack/react-query';
3
3
  export { QueryClientProvider } from '@tanstack/react-query';
4
4
  import { createClient } from '@supabase/supabase-js';
5
5
  import * as ReactDOM from 'react-dom';
@@ -111,6 +111,7 @@ __export(src_exports, {
111
111
  itemsFilterFromQueryFilter: () => itemsFilterFromQueryFilter,
112
112
  listChildren: () => listChildren,
113
113
  listInvitations: () => listInvitations,
114
+ loadCompiledBundle: () => loadCompiledBundle,
114
115
  loadMounts: () => loadMounts,
115
116
  loadPublishedBundle: () => loadPublishedBundle,
116
117
  mount: () => mount2,
@@ -173,6 +174,7 @@ __export(src_exports, {
173
174
  useChannelMessages: () => useChannelMessages,
174
175
  useChannels: () => useChannels,
175
176
  useChildren: () => useChildren,
177
+ useCompiledComponent: () => useCompiledComponent,
176
178
  useComponent: () => useComponent,
177
179
  useCreate: () => useCreate,
178
180
  useCreateAgent: () => useCreateAgent,
@@ -711,7 +713,7 @@ function resetGatewayReads() {
711
713
  }
712
714
  function isScheduledRead(method, params) {
713
715
  if (method === "query") return !("materialize" in params);
714
- return ["read", "list", "search", "resolve", "resolve-items", "get-channel-messages", "list-memberships", "message-replies"].includes(method);
716
+ return ["read", "list", "search", "resolve", "resolve-items", "get-channel-messages", "list-memberships", "message-replies", "check-item-access"].includes(method);
715
717
  }
716
718
  function readRequestKey(value) {
717
719
  if (Array.isArray(value)) return `[${value.map(readRequestKey).join(",")}]`;
@@ -734,18 +736,18 @@ function scheduleRead(key, method, options, run) {
734
736
  };
735
737
  jobs.set(key, job);
736
738
  waiting.push(job);
737
- const pending4 = job;
739
+ const pending5 = job;
738
740
  job.timer = setTimeout(() => {
739
- pending4.controller.abort();
741
+ pending5.controller.abort();
740
742
  const error = new Error("The read timed out. Please retry.");
741
743
  error.name = "TimeoutError";
742
- for (const consumer of pending4.consumers) {
744
+ for (const consumer of pending5.consumers) {
743
745
  consumer.detach();
744
746
  consumer.reject(error);
745
747
  }
746
- pending4.consumers.clear();
747
- if (jobs.get(pending4.key) === pending4) jobs.delete(pending4.key);
748
- discardQueued(pending4);
748
+ pending5.consumers.clear();
749
+ if (jobs.get(pending5.key) === pending5) jobs.delete(pending5.key);
750
+ discardQueued(pending5);
749
751
  }, config.timeoutMs);
750
752
  } else if (rank[options.priority ?? "normal"] < rank[job.priority]) {
751
753
  job.priority = options.priority ?? "normal";
@@ -968,8 +970,8 @@ function refreshQuery(client2, queryKey, options = {}) {
968
970
  queued = /* @__PURE__ */ new Map();
969
971
  trailing.set(client2, queued);
970
972
  }
971
- const pending4 = queued.get(hash);
972
- if (pending4) return pending4;
973
+ const pending5 = queued.get(hash);
974
+ if (pending5) return pending5;
973
975
  const queue = queued;
974
976
  const next = Promise.allSettled(running2).then(() => {
975
977
  queue.delete(hash);
@@ -1028,6 +1030,52 @@ function clearArrangementRefreshes(client2) {
1028
1030
  pending2.get(client2)?.forEach(clearTimeout);
1029
1031
  pending2.delete(client2);
1030
1032
  }
1033
+
1034
+ // src/permission-cache.ts
1035
+ var pending3 = /* @__PURE__ */ new WeakMap();
1036
+ var accessEdges = /* @__PURE__ */ new Set(["shared_with", "has_member", "member_of", "owned_by"]);
1037
+ function invalidate(client2, query) {
1038
+ let timers = pending3.get(client2);
1039
+ if (!timers) {
1040
+ timers = /* @__PURE__ */ new Map();
1041
+ pending3.set(client2, timers);
1042
+ }
1043
+ if (timers.has(query)) return;
1044
+ void client2.cancelQueries({ queryKey: query.queryKey, exact: true });
1045
+ void client2.invalidateQueries({ queryKey: query.queryKey, exact: true, refetchType: "none" });
1046
+ if (!query.isActive()) return;
1047
+ timers.set(query, setTimeout(() => {
1048
+ timers.delete(query);
1049
+ if (client2.getQueryCache().get(query.queryHash) !== query || !query.isActive()) return;
1050
+ void refreshQuery(client2, query.queryKey, { exact: true });
1051
+ }, 250));
1052
+ }
1053
+ function handlePermissionChange(client2, event, type) {
1054
+ const edge = type === "ccm_change";
1055
+ if (edge && !accessEdges.has(event.edge_type)) return;
1056
+ const paths = [event.path, event.old_path, event.source_path].filter((path) => typeof path === "string");
1057
+ const ids = [event.item_id, event.source_item_id, event.source_id, event.target_item_id, event.target_id].filter(Boolean);
1058
+ if (!paths.length && !ids.length) return;
1059
+ for (const query of client2.getQueryCache().findAll({ queryKey: ["vfs"] })) {
1060
+ const meta = query.meta?.permissionQuery;
1061
+ if (!meta?.scope) continue;
1062
+ const direct = Boolean(meta.itemId && ids.includes(meta.itemId));
1063
+ const ancestor = Boolean(meta.path && paths.some((path) => isChannelPath(meta.path, path)));
1064
+ const scope = meta.scope;
1065
+ const scoped = paths.some((path) => isChannelPath(path, scope) || isChannelPath(scope, path)) || [event.scope_item_id, event.account_item_id, event.space_item_id].some((id) => id && meta.scopeIds.includes(id));
1066
+ const inherited = scoped && (event.item_type === "member" || event.item_type === "principal" || edge);
1067
+ if (direct || ancestor || !meta.targetLookup && inherited) invalidate(client2, query);
1068
+ }
1069
+ }
1070
+ function refreshPermissionsAfterReconnect(client2) {
1071
+ for (const query of client2.getQueryCache().findAll({ queryKey: ["vfs"] })) {
1072
+ if (query.meta?.permissionQuery) invalidate(client2, query);
1073
+ }
1074
+ }
1075
+ function clearPermissionRefreshes(client2) {
1076
+ pending3.get(client2)?.forEach((timer) => clearTimeout(timer));
1077
+ pending3.delete(client2);
1078
+ }
1031
1079
  var client = null;
1032
1080
  registerCleanup(() => {
1033
1081
  if (!client) return;
@@ -1068,7 +1116,7 @@ var queryClient = new Proxy({}, {
1068
1116
  });
1069
1117
 
1070
1118
  // src/item-query-realtime.ts
1071
- var pending3 = /* @__PURE__ */ new WeakMap();
1119
+ var pending4 = /* @__PURE__ */ new WeakMap();
1072
1120
  function listingFilter(query) {
1073
1121
  return query.meta?.infiniteItemsRealtime?.filter;
1074
1122
  }
@@ -1107,10 +1155,10 @@ function affectsListing(query, filter, event) {
1107
1155
  return hasPath || Boolean(filter.parent_id && event.parent_id === filter.parent_id);
1108
1156
  }
1109
1157
  function schedule(client2, query) {
1110
- let timers = pending3.get(client2);
1158
+ let timers = pending4.get(client2);
1111
1159
  if (!timers) {
1112
1160
  timers = /* @__PURE__ */ new Map();
1113
- pending3.set(client2, timers);
1161
+ pending4.set(client2, timers);
1114
1162
  }
1115
1163
  const previous = timers.get(query.queryHash);
1116
1164
  if (previous) clearTimeout(previous);
@@ -1133,8 +1181,8 @@ function refreshInfiniteItemsAfterReconnect(client2) {
1133
1181
  }
1134
1182
  }
1135
1183
  function clearInfiniteItemsRefreshes(client2) {
1136
- pending3.get(client2)?.forEach(clearTimeout);
1137
- pending3.delete(client2);
1184
+ pending4.get(client2)?.forEach(clearTimeout);
1185
+ pending4.delete(client2);
1138
1186
  }
1139
1187
 
1140
1188
  // src/items-selection.ts
@@ -1484,6 +1532,7 @@ function catchUpAfterGap(reason) {
1484
1532
  const qc = getQueryClient();
1485
1533
  refreshInfiniteItemsAfterReconnect(qc);
1486
1534
  reconnectArrangements(qc);
1535
+ refreshPermissionsAfterReconnect(qc);
1487
1536
  for (const sub of activePaths.values()) {
1488
1537
  void qc.invalidateQueries({ queryKey: vfsKeys.item(sub.path) });
1489
1538
  void qc.invalidateQueries({ queryKey: vfsKeys.children(sub.path) });
@@ -1521,6 +1570,9 @@ function handleMessage(raw) {
1521
1570
  if (msg.type === "event" || msg.event_type) {
1522
1571
  const eventType = msg.event_type || "message";
1523
1572
  const data = msg.data || msg;
1573
+ if (eventType === "vfs_change" || eventType === "ccm_change") {
1574
+ handlePermissionChange(getQueryClient(), data, eventType);
1575
+ }
1524
1576
  if (eventType === "vfs_change") {
1525
1577
  handleInfiniteItemsChange(getQueryClient(), data);
1526
1578
  handleArrangementChange(getQueryClient(), data);
@@ -1650,6 +1702,7 @@ function disconnectSSE() {
1650
1702
  log("disconnectSSE: tearing down");
1651
1703
  clearInfiniteItemsRefreshes(getQueryClient());
1652
1704
  clearArrangementRefreshes(getQueryClient());
1705
+ clearPermissionRefreshes(getQueryClient());
1653
1706
  intentionalClose = true;
1654
1707
  stopPing();
1655
1708
  if (ws) {
@@ -3020,13 +3073,13 @@ function watchChannelTranscript(client2, key, channel, limit) {
3020
3073
  let timer;
3021
3074
  let running2 = false;
3022
3075
  let stopped = false;
3023
- const pending4 = /* @__PURE__ */ new Map();
3076
+ const pending5 = /* @__PURE__ */ new Map();
3024
3077
  const current = () => client2.getQueryData(key);
3025
3078
  const query = () => client2.getQueryCache().find({ queryKey: key, exact: true });
3026
3079
  const reload = () => refreshQuery(client2, key, { exact: true });
3027
3080
  const read = (after_seq, before_seq) => fetchChannelMessagesPage(channel, { transcriptOnly: true, limit, after_seq, before_seq });
3028
3081
  const schedule2 = () => {
3029
- if (stopped || running2 || timer || !pending4.size) return;
3082
+ if (stopped || running2 || timer || !pending5.size) return;
3030
3083
  timer = setTimeout(() => {
3031
3084
  timer = void 0;
3032
3085
  void flush();
@@ -3034,8 +3087,8 @@ function watchChannelTranscript(client2, key, channel, limit) {
3034
3087
  };
3035
3088
  const flush = async () => {
3036
3089
  running2 = true;
3037
- const changes = [...pending4.values()];
3038
- pending4.clear();
3090
+ const changes = [...pending5.values()];
3091
+ pending5.clear();
3039
3092
  const owner = query();
3040
3093
  try {
3041
3094
  if (owner?.state.fetchStatus === "fetching") await owner.promise?.catch(() => void 0);
@@ -3109,15 +3162,15 @@ function watchChannelTranscript(client2, key, channel, limit) {
3109
3162
  };
3110
3163
  const stop = subscribeToEvents("vfs_change", (change) => {
3111
3164
  const id = change.item_id ?? change.path;
3112
- const previous = pending4.get(id);
3113
- pending4.set(id, previous && (previous.inserted || isNewPost(previous, channel)) && actionOf(change) === "update" && previous.path === change.path ? { ...change, inserted: true } : change);
3165
+ const previous = pending5.get(id);
3166
+ pending5.set(id, previous && (previous.inserted || isNewPost(previous, channel)) && actionOf(change) === "update" && previous.path === change.path ? { ...change, inserted: true } : change);
3114
3167
  schedule2();
3115
3168
  }, (change) => channelMessageChange(change, channel, void 0, []) || !!change.old_path && channelMessageChange({ ...change, path: change.old_path }, channel, void 0, []) || change.item_type === "message" && !!change.parent_id && isChannelPath(change.path, channel) && !!current()?.pages.some((page) => page.messages.some((root) => root.id === change.parent_id)));
3116
3169
  watch = { users: 0, stop: () => {
3117
3170
  stopped = true;
3118
3171
  stop();
3119
3172
  if (timer) clearTimeout(timer);
3120
- pending4.clear();
3173
+ pending5.clear();
3121
3174
  } };
3122
3175
  entries.set(hash, watch);
3123
3176
  }
@@ -3163,7 +3216,7 @@ function watchChannels(client2, key, normalize) {
3163
3216
  running2 = true;
3164
3217
  const reload = inventory;
3165
3218
  inventory = false;
3166
- const pending4 = [...channels];
3219
+ const pending5 = [...channels];
3167
3220
  const checkRename = new Set(renames);
3168
3221
  renames.clear();
3169
3222
  channels.clear();
@@ -3171,7 +3224,7 @@ function watchChannels(client2, key, normalize) {
3171
3224
  if (reload) {
3172
3225
  await refreshQuery(client2, key, { exact: true });
3173
3226
  } else {
3174
- const results = await Promise.allSettled(pending4.map(async (id) => {
3227
+ const results = await Promise.allSettled(pending5.map(async (id) => {
3175
3228
  const owner = client2.getQueryCache().find({ queryKey: key, exact: true });
3176
3229
  if (!owner) return;
3177
3230
  const result = await gatewayCall("read", { id });
@@ -3303,6 +3356,92 @@ function watchMessageReplies(client2, key, target) {
3303
3356
  }
3304
3357
  };
3305
3358
  }
3359
+ var actions = /* @__PURE__ */ new Set(["view", "edit", "delete", "admin"]);
3360
+ var uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3361
+ function targetFromRead(response) {
3362
+ const raw = response.item ?? response;
3363
+ const id = raw.id ?? raw.item_id;
3364
+ const path = raw.path ?? raw.item_path;
3365
+ if (response.success !== true || typeof id !== "string" || !uuid.test(id)) {
3366
+ throw new Error("PERMISSION_TARGET_UNAVAILABLE");
3367
+ }
3368
+ return { id, ...typeof path === "string" ? { path } : {} };
3369
+ }
3370
+ function usePermissions(item, requested) {
3371
+ useSyncExternalStore(subscribeScope, getScopeVersion, getScopeVersion);
3372
+ const epoch = useSyncExternalStore(subscribeSession, getSessionVersion, getSessionVersion);
3373
+ const mounts = useSyncExternalStore(subscribeMounts, getMountVersion, getMountVersion);
3374
+ const scope = getScope();
3375
+ const principal = getSessionEntry()?.principal_id;
3376
+ const target = item?.trim() ?? "";
3377
+ const wanted = [...new Set(requested ?? [])].sort();
3378
+ const directId = uuid.test(target);
3379
+ const validTarget = directId || (target.startsWith("/root/") || target === "/root");
3380
+ const invalid = wanted.some((action) => !actions.has(action)) || Boolean(target && !validTarget);
3381
+ const enabled2 = Boolean(scope && principal && target && wanted.length && !invalid);
3382
+ const root = ["vfs", scope ?? "__unscoped__", "permissions", principal ?? "__anonymous__", epoch, mounts];
3383
+ const scopeIds = [...new Set([getAnchorRef()?.id, ...getMounts().map((mount3) => mount3.id)].filter((id) => Boolean(id)))];
3384
+ const targetKey = [...root, "target", target];
3385
+ const identity = useQuery({
3386
+ queryKey: targetKey,
3387
+ queryFn: async ({ signal: signal2 }) => {
3388
+ if (!enabled2 || !scope) throw new Error("PERMISSION_CONTEXT_REQUIRED");
3389
+ return targetFromRead(await gatewayCall("read", { path: target, _scope_path: scope }, { signal: signal2 }));
3390
+ },
3391
+ enabled: enabled2 && !directId,
3392
+ staleTime: Infinity,
3393
+ gcTime: 0,
3394
+ retry: false,
3395
+ refetchOnWindowFocus: false,
3396
+ refetchOnReconnect: false,
3397
+ refetchOnMount: false,
3398
+ meta: { permissionQuery: { scope, scopeIds, path: target, targetLookup: true } }
3399
+ });
3400
+ const resolved = directId ? { id: target } : identity.data;
3401
+ const identityReady = directId || identity.isSuccess && !identity.isFetching && !identity.isStale;
3402
+ const checks = useQueries({ queries: wanted.filter((action) => actions.has(action)).map((action) => ({
3403
+ queryKey: [...root, "check", resolved?.id ?? target, action],
3404
+ queryFn: async ({ signal: signal2 }) => {
3405
+ if (!enabled2 || !scope || !resolved) throw new Error("PERMISSION_CONTEXT_REQUIRED");
3406
+ const result = await gatewayCall("check-item-access", { id: resolved.id, action, _scope_path: scope }, { signal: signal2 });
3407
+ if (result.success !== true || typeof result.allowed !== "boolean") throw new Error("PERMISSION_RESPONSE_INVALID");
3408
+ return result.allowed;
3409
+ },
3410
+ enabled: enabled2 && identityReady && Boolean(resolved),
3411
+ staleTime: Infinity,
3412
+ gcTime: 0,
3413
+ retry: false,
3414
+ refetchOnWindowFocus: false,
3415
+ refetchOnReconnect: false,
3416
+ refetchOnMount: false,
3417
+ meta: { permissionQuery: { scope, scopeIds, itemId: resolved?.id, path: resolved?.path ?? (directId ? void 0 : target) } }
3418
+ })) });
3419
+ const error = invalid ? new Error("PERMISSION_INPUT_INVALID") : !directId && identity.error || checks.find((check) => check.error)?.error || null;
3420
+ const verified = enabled2 && identityReady && !error;
3421
+ const supported = wanted.filter((action) => actions.has(action));
3422
+ const data = Object.fromEntries(wanted.map((action) => {
3423
+ const check = checks[supported.indexOf(action)];
3424
+ return [action, Boolean(verified && check?.isSuccess && !check.isFetching && !check.isStale && check.data === true)];
3425
+ }));
3426
+ return {
3427
+ data,
3428
+ loading: Boolean(enabled2 && (!directId && identity.isFetching || checks.some((check) => check.isFetching || check.isPending)) && !error),
3429
+ error,
3430
+ /** Explicit refresh for a user action; no automatic retry or polling. */
3431
+ refetch: async () => {
3432
+ if (!enabled2) return;
3433
+ if (!directId && (!identity.data || identity.isError)) {
3434
+ await identity.refetch();
3435
+ return;
3436
+ }
3437
+ await Promise.all(checks.map((check) => check.refetch()));
3438
+ }
3439
+ };
3440
+ }
3441
+ function usePermission(action, item) {
3442
+ const result = usePermissions(item, action ? [action] : []);
3443
+ return { ...result, data: { allowed: Boolean(action && result.data[action]) } };
3444
+ }
3306
3445
 
3307
3446
  // src/hooks.ts
3308
3447
  function useScopeKey() {
@@ -3511,7 +3650,7 @@ function useIncrementalItems(filter, options = {}) {
3511
3650
  let wasConnected = false;
3512
3651
  let missed = false;
3513
3652
  let generation = 0;
3514
- const pending4 = /* @__PURE__ */ new Map();
3653
+ const pending5 = /* @__PURE__ */ new Map();
3515
3654
  const reconcile = () => {
3516
3655
  const started = generation;
3517
3656
  void refetch.current().then((result) => {
@@ -3528,18 +3667,18 @@ function useIncrementalItems(filter, options = {}) {
3528
3667
  delete upserts[path];
3529
3668
  return { identity, upserts, deleted: new Set(state.deleted).add(path) };
3530
3669
  });
3531
- const earlier = pending4.get("__reconcile__");
3670
+ const earlier = pending5.get("__reconcile__");
3532
3671
  if (earlier) clearTimeout(earlier);
3533
- pending4.set("__reconcile__", setTimeout(() => {
3534
- pending4.delete("__reconcile__");
3672
+ pending5.set("__reconcile__", setTimeout(() => {
3673
+ pending5.delete("__reconcile__");
3535
3674
  reconcile();
3536
3675
  }, 250));
3537
3676
  };
3538
3677
  const readOne = (path) => {
3539
- const earlier = pending4.get(path);
3678
+ const earlier = pending5.get(path);
3540
3679
  if (earlier) clearTimeout(earlier);
3541
- pending4.set(path, setTimeout(() => {
3542
- pending4.delete(path);
3680
+ pending5.set(path, setTimeout(() => {
3681
+ pending5.delete(path);
3543
3682
  void client2.fetchQuery({ queryKey: vfsKeys.item(path), queryFn: () => fetchVfsItem(path), staleTime: 0 }).then((item) => {
3544
3683
  if (stopped) return;
3545
3684
  if (!item || !itemMatchesIncrementalFilter(item, selected)) {
@@ -3602,7 +3741,7 @@ function useIncrementalItems(filter, options = {}) {
3602
3741
  stopped = true;
3603
3742
  stopEvents();
3604
3743
  stopConnection();
3605
- pending4.forEach(clearTimeout);
3744
+ pending5.forEach(clearTimeout);
3606
3745
  };
3607
3746
  }, [client2, identity]);
3608
3747
  return { ...query, allItems };
@@ -4358,15 +4497,15 @@ async function readPublishedBundle(componentId, releaseItemId, version) {
4358
4497
  return { status: "ready", releaseItemId, version, script, stylesheet: stylesheet?.trim() ? stylesheet : null };
4359
4498
  }
4360
4499
  function publishedBundle(componentId, releaseItemId, version) {
4361
- let pending4 = publishedBundles.get(releaseItemId);
4362
- if (!pending4) {
4363
- pending4 = readPublishedBundle(componentId, releaseItemId, version);
4364
- publishedBundles.set(releaseItemId, pending4);
4365
- pending4.catch(() => {
4366
- if (publishedBundles.get(releaseItemId) === pending4) publishedBundles.delete(releaseItemId);
4500
+ let pending5 = publishedBundles.get(releaseItemId);
4501
+ if (!pending5) {
4502
+ pending5 = readPublishedBundle(componentId, releaseItemId, version);
4503
+ publishedBundles.set(releaseItemId, pending5);
4504
+ pending5.catch(() => {
4505
+ if (publishedBundles.get(releaseItemId) === pending5) publishedBundles.delete(releaseItemId);
4367
4506
  });
4368
4507
  }
4369
- return pending4;
4508
+ return pending5;
4370
4509
  }
4371
4510
  function loadPublishedBundle(source) {
4372
4511
  const live = liveRelease(source);
@@ -4461,6 +4600,143 @@ function usePublishedComponent(item) {
4461
4600
  version: onScreen?.version ?? null
4462
4601
  };
4463
4602
  }
4603
+ var COMPILED_BUILD_LIMIT = 512 * 1024;
4604
+ var compiledBundles = /* @__PURE__ */ new Map();
4605
+ var compiledComponents = /* @__PURE__ */ new Map();
4606
+ registerCleanup(() => {
4607
+ compiledBundles.clear();
4608
+ compiledComponents.clear();
4609
+ });
4610
+ var compiledKey = (fileId, sha256) => `${fileId}:${sha256.toLowerCase()}`;
4611
+ async function readCompiledBundle(build) {
4612
+ const opened = await gatewayCall("open", {
4613
+ id: build.fileId,
4614
+ mode: "render",
4615
+ ...build.scopePath ? { _scope_path: build.scopePath } : {}
4616
+ });
4617
+ const url = plainRecord(plainRecord(opened.render).props).url;
4618
+ if (opened.item_id !== build.fileId || opened.item_type !== "file" || typeof url !== "string" || !url) {
4619
+ throw new Error("The compiled build could not be opened.");
4620
+ }
4621
+ const response = await fetch(url, { credentials: "omit", referrerPolicy: "no-referrer" });
4622
+ if (!response.ok) {
4623
+ throw new Error(`Failed to read the compiled build: ${response.status} ${response.statusText}`.trim());
4624
+ }
4625
+ const bytes = await response.arrayBuffer();
4626
+ if (bytes.byteLength > COMPILED_BUILD_LIMIT) throw new Error("The compiled build is too large to run.");
4627
+ const digest = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))).map((byte) => byte.toString(16).padStart(2, "0")).join("");
4628
+ if (digest !== build.sha256.toLowerCase()) {
4629
+ throw new Error("The compiled build does not match the bytes it was shown with.");
4630
+ }
4631
+ let parsed;
4632
+ try {
4633
+ parsed = JSON.parse(new TextDecoder().decode(bytes));
4634
+ } catch {
4635
+ throw new Error("The compiled build is not a build file.");
4636
+ }
4637
+ const { js, css, scope } = plainRecord(parsed);
4638
+ if (typeof js !== "string" || !js || css != null && typeof css !== "string" || scope != null && (typeof scope !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(scope))) {
4639
+ throw new Error("The compiled build is not a build file.");
4640
+ }
4641
+ return {
4642
+ script: js,
4643
+ stylesheet: typeof css === "string" && css.trim() ? css : null,
4644
+ scopeClass: typeof scope === "string" ? `fsaos-c-${scope}` : null
4645
+ };
4646
+ }
4647
+ function loadCompiledBundle(build) {
4648
+ if (!build.fileId || !/^[0-9a-f]{64}$/i.test(build.sha256 || "")) {
4649
+ return Promise.reject(new Error("A compiled build is named by its file and the SHA-256 of its bytes."));
4650
+ }
4651
+ const key = compiledKey(build.fileId, build.sha256);
4652
+ let pending5 = compiledBundles.get(key);
4653
+ if (!pending5) {
4654
+ pending5 = readCompiledBundle(build);
4655
+ compiledBundles.set(key, pending5);
4656
+ pending5.catch(() => {
4657
+ if (compiledBundles.get(key) === pending5) compiledBundles.delete(key);
4658
+ });
4659
+ }
4660
+ return pending5;
4661
+ }
4662
+ function useCompiledComponent(build) {
4663
+ const [onScreen, setOnScreen] = useState(null);
4664
+ const [status, setStatus] = useState("loading");
4665
+ const [error, setError] = useState(null);
4666
+ const shown = useRef(null);
4667
+ const fileId = build?.fileId || null;
4668
+ const sha256 = build?.sha256 || null;
4669
+ const scopePath = build?.scopePath;
4670
+ useEffect(() => {
4671
+ if (!fileId || !sha256) {
4672
+ if (shown.current?.cssKey) releaseComponentCss(shown.current.cssKey);
4673
+ shown.current = null;
4674
+ setOnScreen(null);
4675
+ setError(null);
4676
+ setStatus("loading");
4677
+ return;
4678
+ }
4679
+ const key = compiledKey(fileId, sha256);
4680
+ if (shown.current?.key === key) return;
4681
+ let cancelled = false;
4682
+ setError(null);
4683
+ if (!shown.current) setStatus("loading");
4684
+ (async () => {
4685
+ let heldCssKey = null;
4686
+ try {
4687
+ const bundle = await loadCompiledBundle({ fileId, sha256, scopePath });
4688
+ if (cancelled) return;
4689
+ let resolved = compiledComponents.get(key);
4690
+ if (!resolved) {
4691
+ resolved = evaluateBundle(bundle.script);
4692
+ if (!resolved) {
4693
+ throw new Error(
4694
+ "The compiled build did not hand over a component. Expected window.__FSAOS_COMPONENT__ (what the compile emits) or a __FSAOS_REGISTER__(Component) call."
4695
+ );
4696
+ }
4697
+ if (typeof resolved !== "function") {
4698
+ throw new Error(`The compiled build handed over something that is not a React component (${typeof resolved}).`);
4699
+ }
4700
+ compiledComponents.set(key, resolved);
4701
+ }
4702
+ const cssKey = bundle.stylesheet ? `compiled:${key}` : null;
4703
+ if (cssKey) {
4704
+ heldCssKey = cssKey;
4705
+ await holdComponentCss(cssKey, async () => bundle.stylesheet);
4706
+ }
4707
+ if (cancelled) {
4708
+ if (heldCssKey) releaseComponentCss(heldCssKey);
4709
+ return;
4710
+ }
4711
+ const previousCssKey = shown.current?.cssKey ?? null;
4712
+ shown.current = { key, cssKey };
4713
+ heldCssKey = null;
4714
+ setOnScreen({ Component: resolved, key, scopeClass: bundle.scopeClass });
4715
+ setStatus("ready");
4716
+ if (previousCssKey) releaseComponentCss(previousCssKey);
4717
+ } catch (err) {
4718
+ if (heldCssKey) releaseComponentCss(heldCssKey);
4719
+ if (cancelled) return;
4720
+ setError(err instanceof Error ? err : new Error(String(err)));
4721
+ if (!shown.current) setStatus("error");
4722
+ }
4723
+ })();
4724
+ return () => {
4725
+ cancelled = true;
4726
+ };
4727
+ }, [fileId, sha256, scopePath]);
4728
+ useEffect(() => () => {
4729
+ if (shown.current?.cssKey) releaseComponentCss(shown.current.cssKey);
4730
+ shown.current = null;
4731
+ }, []);
4732
+ return {
4733
+ Component: onScreen?.Component ?? null,
4734
+ /** The class to put on the element that wraps the component (see `CompiledBundle.scopeClass`). */
4735
+ scopeClass: onScreen?.scopeClass ?? null,
4736
+ status,
4737
+ error
4738
+ };
4739
+ }
4464
4740
  var THEME_PROPERTIES = [
4465
4741
  "--color-primary",
4466
4742
  "--color-secondary",
@@ -4490,16 +4766,6 @@ function useTheme() {
4490
4766
  }, []);
4491
4767
  return { data: themeData, loading: false, error: null };
4492
4768
  }
4493
- function usePermission(_action, _path) {
4494
- return { data: { allowed: true }, loading: false, error: null };
4495
- }
4496
- function usePermissions(_path, actions) {
4497
- const perms = {};
4498
- (actions || []).forEach((a) => {
4499
- perms[a] = true;
4500
- });
4501
- return { data: perms, loading: false, error: null };
4502
- }
4503
4769
  var _principalIdCache = null;
4504
4770
  var _principalIdPromise = null;
4505
4771
  var _principalListeners = /* @__PURE__ */ new Set();
@@ -5596,7 +5862,7 @@ function usePersonalItemOrder(key, items, space) {
5596
5862
  return [...unplaced, ...arranged.filter((item) => savedIds.has(item.id))];
5597
5863
  }, [key, items, query.applyTo, query.order]);
5598
5864
  const client2 = useQueryClient();
5599
- const pending4 = useRef(false);
5865
+ const pending5 = useRef(false);
5600
5866
  const ready = Boolean(supported && !query.error && query.arrangement?.item_id && query.resolutionLevel === "member" && query.arrangement.write_target_id === query.arrangement.item_id);
5601
5867
  const mutation = useMutation$1({
5602
5868
  mutationFn: async (change) => {
@@ -5614,7 +5880,7 @@ function usePersonalItemOrder(key, items, space) {
5614
5880
  if (!ready || !scopePath || identity !== activeIdentity.current || generation !== getScopeVersion() || getScope() !== mountedScope) {
5615
5881
  throw new Error("Personal order is not available in this Space");
5616
5882
  }
5617
- if (pending4.current) throw new Error("An order change is already being saved");
5883
+ if (pending5.current) throw new Error("An order change is already being saved");
5618
5884
  const visibleIds = items.map((item) => item.id);
5619
5885
  if (ids.length !== visibleIds.length || new Set(ids).size !== visibleIds.length || visibleIds.some((id) => !ids.includes(id))) throw new Error("Order must include each displayed item exactly once");
5620
5886
  const cached = client2.getQueryData(query.arrangementQueryKey);
@@ -5627,7 +5893,7 @@ function usePersonalItemOrder(key, items, space) {
5627
5893
  let index = 0;
5628
5894
  const saved = (query.order ?? []).map((id) => visible.has(id) ? ids[index++] : id);
5629
5895
  const order = [...saved, ...ids.slice(index)];
5630
- pending4.current = true;
5896
+ pending5.current = true;
5631
5897
  try {
5632
5898
  return await mutation.mutateAsync({
5633
5899
  ids: order,
@@ -5636,7 +5902,7 @@ function usePersonalItemOrder(key, items, space) {
5636
5902
  queryKey: query.arrangementQueryKey
5637
5903
  });
5638
5904
  } finally {
5639
- pending4.current = false;
5905
+ pending5.current = false;
5640
5906
  }
5641
5907
  }
5642
5908
  return {
@@ -7384,7 +7650,7 @@ function usePersonalSections(contextId, collection) {
7384
7650
  meta: { arrangementRealtime: true, personalSections: true },
7385
7651
  structuralSharing: (previous, next) => newestSnapshot(previous, next)
7386
7652
  });
7387
- const pending4 = useRef(false);
7653
+ const pending5 = useRef(false);
7388
7654
  const mutation = useMutation$1({ mutationFn: async (write) => {
7389
7655
  const data = await call(write.scope, write.context, write.collection, {
7390
7656
  ...write.change,
@@ -7397,12 +7663,12 @@ function usePersonalSections(contextId, collection) {
7397
7663
  if (!scopePath || !contextId || generation !== getScopeVersion() || getScope() !== scopePath || !query.data || query.error) {
7398
7664
  throw new Error("Select the Space again before changing sections");
7399
7665
  }
7400
- if (pending4.current) throw new Error("A section change is still being saved");
7401
- pending4.current = true;
7666
+ if (pending5.current) throw new Error("A section change is still being saved");
7667
+ pending5.current = true;
7402
7668
  try {
7403
7669
  return await mutation.mutateAsync({ change: value, scope: scopePath, context: contextId, collection, version: query.data.version });
7404
7670
  } finally {
7405
- pending4.current = false;
7671
+ pending5.current = false;
7406
7672
  }
7407
7673
  }
7408
7674
  function destination(sectionId) {
@@ -7425,6 +7691,6 @@ function usePersonalSections(contextId, collection) {
7425
7691
  // src/index.ts
7426
7692
  __registerSdkExports(src_exports);
7427
7693
 
7428
- export { CHANNEL_AI_MODES, ComponentRenderer, EnforcementDeniedError, FormSubmissionError, GatewayRequestError, HostSessionUnavailableError, InteractionTrackingError, KernelProvider, acceptInvitation, acceptInvite, answerInput, assignPersonalSection, auth, awaitAnchorReady, awaitScopeReady, callTool, cancelInvitation, cancelQueuedTurn, cancelTurn, clearCachedToken, clearSession, configureGatewayReads, connectHostSession, createAgent, createInvitation, createItem, disconnectSSE, disposeVfsRealtimeWs, electHomeAnchor, emitEvent, fetchChannelMessages, fetchChannelMessagesPage, fetchChannelMessagesWithCards, fetchEdgesForItem, fetchItemHistory, fetchItemVersions, fetchItems, fetchMemberFocus, fetchMessageReplies, fetchMessageReplyContexts, fetchOpenEnvelope, fetchRecentActivity, fetchResolvedItems, fetchTimelineHistory, fetchTurnQueueEntries, fetchTypeDefinitions, fetchVfsChildren, fetchVfsChildrenPage, fetchVfsItem, fetchVfsItemById, fetchVfsTree, filePurchaseNextUrl, funnelCheckoutLink, gatewayCall, getAccessToken, getAnchor, getAnchorRef, getAnchorVersion, getAssetUrl, getDefaultSort, getFilePurchase, getHomeAnchor, getInvitation, getMountVersion, getMounts, getPathSubscriptionState, getQueryClient, getRequiredFormFields, getScope, getScopeVersion, getServerClockOffsetMs, getServerClockSyncedAt, getSessionEntry, hasServerClock, initSession, initVfsRealtimeWs, initializeFsaos, initializeWorkspace, interpretSchema, invalidateAllVfs, invalidateChannelMessages, invalidateChildren, invalidateItem, invalidateOpenEnvelope, invalidatePathAndParent, invalidateSubtree, invalidateTypes, inviteMember, isAnchorReady, isChannelPath, isListableItemsFilter, isScopeReady, itemsFilterFromQueryFilter, listChildren, listInvitations, loadMounts, loadPublishedBundle, mount2 as mount, mountRealtimeScope, normalizeItem, onConnectionStateChange, pathSubscriptionMatches, personalSectionsKey, ping, pushChanges, queryClient, readItem, refreshQuery, registerCleanup, rejectInvitation, replaceMounts, resendInvitation, resetAllSdkState, resolvePrincipalId, resubscribePath, seatMember, selectMount, sendMessage2 as sendMessage, serveHostSession, serverDeadlinePassed, serverMsUntil, serverNow, setAnchor, setCachedToken, setQueryClient, setScope, setupRequireShim, signal, startFileCheckout, startTracking, steerTurn, submitForm, subscribeAnchor, subscribeArtifactStream, subscribeMounts, subscribeScope, subscribeToEvents, subscribeToPath, subscribeToScope, trackAction, trackEvent, trackPageView, unmountRealtimeScope, updateItem, uploadFile, useAcceptInvite, useAccounts, useAgentTimeline, useAllChannels, useAnswerInput, useArrangement, useArtifactStream, useAsset, useAuth, useChannelMessages, useChannels, useChildren, useComponent, useCreate, useCreateAgent, useDelete, useDmChannels, useEdges, useEventStream, useFileUpload, useIncrementalItems, useInfiniteChannelMessages, useInfiniteChildren, useInfiniteItems, useInviteMember, useItem, useItemById, useItemHistory, useItemVersions, useItems, useLink, useList, useMemberFocus, useMessageReplies, useMintedAsset, useMounts, useMove, useMutation, useNotifications, useOpen, usePermission, usePermissions, usePersonalItemOrder, usePersonalSections, usePinnedItems, usePrincipal, usePublishedComponent, useRealtimeQuery, useRecentActivity, useResolve, useResolvedItems, useScope, useScopeReady, useSearch, useSeatMember, useTheme, useTimelineHistory, useTree, useType, useTypeHelpers, useTypes, useUnreadCounts, useUpdate, useUpdatePrincipal, vfsKeys, waitForPathReady };
7694
+ export { CHANNEL_AI_MODES, ComponentRenderer, EnforcementDeniedError, FormSubmissionError, GatewayRequestError, HostSessionUnavailableError, InteractionTrackingError, KernelProvider, acceptInvitation, acceptInvite, answerInput, assignPersonalSection, auth, awaitAnchorReady, awaitScopeReady, callTool, cancelInvitation, cancelQueuedTurn, cancelTurn, clearCachedToken, clearSession, configureGatewayReads, connectHostSession, createAgent, createInvitation, createItem, disconnectSSE, disposeVfsRealtimeWs, electHomeAnchor, emitEvent, fetchChannelMessages, fetchChannelMessagesPage, fetchChannelMessagesWithCards, fetchEdgesForItem, fetchItemHistory, fetchItemVersions, fetchItems, fetchMemberFocus, fetchMessageReplies, fetchMessageReplyContexts, fetchOpenEnvelope, fetchRecentActivity, fetchResolvedItems, fetchTimelineHistory, fetchTurnQueueEntries, fetchTypeDefinitions, fetchVfsChildren, fetchVfsChildrenPage, fetchVfsItem, fetchVfsItemById, fetchVfsTree, filePurchaseNextUrl, funnelCheckoutLink, gatewayCall, getAccessToken, getAnchor, getAnchorRef, getAnchorVersion, getAssetUrl, getDefaultSort, getFilePurchase, getHomeAnchor, getInvitation, getMountVersion, getMounts, getPathSubscriptionState, getQueryClient, getRequiredFormFields, getScope, getScopeVersion, getServerClockOffsetMs, getServerClockSyncedAt, getSessionEntry, hasServerClock, initSession, initVfsRealtimeWs, initializeFsaos, initializeWorkspace, interpretSchema, invalidateAllVfs, invalidateChannelMessages, invalidateChildren, invalidateItem, invalidateOpenEnvelope, invalidatePathAndParent, invalidateSubtree, invalidateTypes, inviteMember, isAnchorReady, isChannelPath, isListableItemsFilter, isScopeReady, itemsFilterFromQueryFilter, listChildren, listInvitations, loadCompiledBundle, loadMounts, loadPublishedBundle, mount2 as mount, mountRealtimeScope, normalizeItem, onConnectionStateChange, pathSubscriptionMatches, personalSectionsKey, ping, pushChanges, queryClient, readItem, refreshQuery, registerCleanup, rejectInvitation, replaceMounts, resendInvitation, resetAllSdkState, resolvePrincipalId, resubscribePath, seatMember, selectMount, sendMessage2 as sendMessage, serveHostSession, serverDeadlinePassed, serverMsUntil, serverNow, setAnchor, setCachedToken, setQueryClient, setScope, setupRequireShim, signal, startFileCheckout, startTracking, steerTurn, submitForm, subscribeAnchor, subscribeArtifactStream, subscribeMounts, subscribeScope, subscribeToEvents, subscribeToPath, subscribeToScope, trackAction, trackEvent, trackPageView, unmountRealtimeScope, updateItem, uploadFile, useAcceptInvite, useAccounts, useAgentTimeline, useAllChannels, useAnswerInput, useArrangement, useArtifactStream, useAsset, useAuth, useChannelMessages, useChannels, useChildren, useCompiledComponent, useComponent, useCreate, useCreateAgent, useDelete, useDmChannels, useEdges, useEventStream, useFileUpload, useIncrementalItems, useInfiniteChannelMessages, useInfiniteChildren, useInfiniteItems, useInviteMember, useItem, useItemById, useItemHistory, useItemVersions, useItems, useLink, useList, useMemberFocus, useMessageReplies, useMintedAsset, useMounts, useMove, useMutation, useNotifications, useOpen, usePermission, usePermissions, usePersonalItemOrder, usePersonalSections, usePinnedItems, usePrincipal, usePublishedComponent, useRealtimeQuery, useRecentActivity, useResolve, useResolvedItems, useScope, useScopeReady, useSearch, useSeatMember, useTheme, useTimelineHistory, useTree, useType, useTypeHelpers, useTypes, useUnreadCounts, useUpdate, useUpdatePrincipal, vfsKeys, waitForPathReady };
7429
7695
  //# sourceMappingURL=index.js.map
7430
7696
  //# sourceMappingURL=index.js.map