@ai4b-team/fsaos-gateway-sdk 5.6.2 → 5.7.1

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/iife/ui.js CHANGED
@@ -1,3 +1,3 @@
1
- /* @fsaos/ui v2.0.0 — FSAOS UI Primitives — 2026-11-16T02:47:59.504Z */
1
+ /* @fsaos/ui v2.0.0 — FSAOS UI Primitives — 2026-11-16T04:34:20.646Z */
2
2
  "use strict";var __FSAOS_UI__=(()=>{var m=Object.create;var r=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var f=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty;var y=(e,i)=>()=>(i||e((i={exports:{}}).exports,i),i.exports),N=(e,i)=>{for(var a in i)r(e,a,{get:i[a],enumerable:!0})},s=(e,i,a,l)=>{if(i&&typeof i=="object"||typeof i=="function")for(let t of u(i))!h.call(e,t)&&t!==a&&r(e,t,{get:()=>i[t],enumerable:!(l=g(i,t))||l.enumerable});return e};var x=(e,i,a)=>(a=e!=null?m(f(e)):{},s(i||!e||!e.__esModule?r(a,"default",{value:e,enumerable:!0}):a,e)),b=e=>s(r({},"__esModule",{value:!0}),e);var d=y((V,c)=>{c.exports=React});var P={};N(P,{Badge:()=>z,Breadcrumbs:()=>A,Button:()=>D,Card:()=>w,DataView:()=>R,Detail:()=>_,Empty:()=>I,FilePreview:()=>O,Form:()=>F,Grid:()=>k,Image:()=>G,Link:()=>E,Page:()=>v,Router:()=>T,Sidebar:()=>S,Spinner:()=>B,Stack:()=>C,Table:()=>j,Tabs:()=>W,Video:()=>H});var n=x(d(),1);function o(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function v(e){return(0,n.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function C(e){let i=e.direction||"vertical";return(0,n.createElement)("div",{style:{display:"flex",flexDirection:i==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function k(e){return(0,n.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function S(e){return(0,n.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function w(e){return(0,n.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function z(e){return(0,n.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function B(e){let i=e.size||"1.5rem";return(0,n.createElement)("div",{style:{width:i,height:i,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function D(e){return(0,n.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function I(e){return(0,n.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,n.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,n.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,n.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function R(e){return(0,n.createElement)("div",{className:e.className||""},e.children)}function j(e){return(0,n.createElement)("table",{className:e.className||""},e.children)}function F(e){return(0,n.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function _(e){return(0,n.createElement)("div",{className:e.className||""},e.children)}function T(e){return(0,n.createElement)("div",null,e.children)}function E(e){return(0,n.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function W(e){return(0,n.createElement)("div",{className:e.className||""},e.children)}function A(e){return(0,n.createElement)("nav",{className:e.className||""},e.children)}function G(e){return(0,n.createElement)("img",{src:e.src||(e.path?o()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function H(e){return(0,n.createElement)("video",{src:e.src||(e.path?o()+e.path:""),controls:!0,className:e.className||""})}function O(e){return(0,n.createElement)("div",{className:e.className||""},e.children||"File preview")}return b(P);})();
3
3
  //# sourceMappingURL=ui.js.map
package/dist/index.cjs CHANGED
@@ -92,6 +92,8 @@ __export(src_exports, {
92
92
  fetchVfsItem: () => fetchVfsItem,
93
93
  fetchVfsItemById: () => fetchVfsItemById,
94
94
  fetchVfsTree: () => fetchVfsTree,
95
+ filePurchaseNextUrl: () => filePurchaseNextUrl,
96
+ funnelCheckoutLink: () => funnelCheckoutLink,
95
97
  gatewayCall: () => gatewayCall,
96
98
  getAccessToken: () => getAccessToken,
97
99
  getAnchor: () => getAnchor,
@@ -99,6 +101,7 @@ __export(src_exports, {
99
101
  getAnchorVersion: () => getAnchorVersion,
100
102
  getAssetUrl: () => getAssetUrl,
101
103
  getDefaultSort: () => getDefaultSort,
104
+ getFilePurchase: () => getFilePurchase,
102
105
  getHomeAnchor: () => getHomeAnchor,
103
106
  getInvitation: () => getInvitation,
104
107
  getMountVersion: () => getMountVersion,
@@ -166,6 +169,7 @@ __export(src_exports, {
166
169
  setScope: () => setScope,
167
170
  setupRequireShim: () => setupRequireShim,
168
171
  signal: () => signal,
172
+ startFileCheckout: () => startFileCheckout,
169
173
  startTracking: () => startTracking,
170
174
  steerTurn: () => steerTurn,
171
175
  submitForm: () => submitForm,
@@ -732,7 +736,7 @@ function resetGatewayReads() {
732
736
  }
733
737
  function isScheduledRead(method, params) {
734
738
  if (method === "query") return !("materialize" in params);
735
- return ["read", "list", "search", "resolve", "resolve-items", "get-channel-messages", "list-memberships", "message-replies"].includes(method);
739
+ return ["read", "list", "search", "resolve", "resolve-items", "get-channel-messages", "list-memberships", "message-replies", "check-item-access"].includes(method);
736
740
  }
737
741
  function readRequestKey(value) {
738
742
  if (Array.isArray(value)) return `[${value.map(readRequestKey).join(",")}]`;
@@ -755,18 +759,18 @@ function scheduleRead(key, method, options, run) {
755
759
  };
756
760
  jobs.set(key, job);
757
761
  waiting.push(job);
758
- const pending4 = job;
762
+ const pending5 = job;
759
763
  job.timer = setTimeout(() => {
760
- pending4.controller.abort();
764
+ pending5.controller.abort();
761
765
  const error = new Error("The read timed out. Please retry.");
762
766
  error.name = "TimeoutError";
763
- for (const consumer of pending4.consumers) {
767
+ for (const consumer of pending5.consumers) {
764
768
  consumer.detach();
765
769
  consumer.reject(error);
766
770
  }
767
- pending4.consumers.clear();
768
- if (jobs.get(pending4.key) === pending4) jobs.delete(pending4.key);
769
- discardQueued(pending4);
771
+ pending5.consumers.clear();
772
+ if (jobs.get(pending5.key) === pending5) jobs.delete(pending5.key);
773
+ discardQueued(pending5);
770
774
  }, config.timeoutMs);
771
775
  } else if (rank[options.priority ?? "normal"] < rank[job.priority]) {
772
776
  job.priority = options.priority ?? "normal";
@@ -989,8 +993,8 @@ function refreshQuery(client2, queryKey, options = {}) {
989
993
  queued = /* @__PURE__ */ new Map();
990
994
  trailing.set(client2, queued);
991
995
  }
992
- const pending4 = queued.get(hash);
993
- if (pending4) return pending4;
996
+ const pending5 = queued.get(hash);
997
+ if (pending5) return pending5;
994
998
  const queue = queued;
995
999
  const next = Promise.allSettled(running2).then(() => {
996
1000
  queue.delete(hash);
@@ -1049,6 +1053,52 @@ function clearArrangementRefreshes(client2) {
1049
1053
  pending2.get(client2)?.forEach(clearTimeout);
1050
1054
  pending2.delete(client2);
1051
1055
  }
1056
+
1057
+ // src/permission-cache.ts
1058
+ var pending3 = /* @__PURE__ */ new WeakMap();
1059
+ var accessEdges = /* @__PURE__ */ new Set(["shared_with", "has_member", "member_of", "owned_by"]);
1060
+ function invalidate(client2, query) {
1061
+ let timers = pending3.get(client2);
1062
+ if (!timers) {
1063
+ timers = /* @__PURE__ */ new Map();
1064
+ pending3.set(client2, timers);
1065
+ }
1066
+ if (timers.has(query)) return;
1067
+ void client2.cancelQueries({ queryKey: query.queryKey, exact: true });
1068
+ void client2.invalidateQueries({ queryKey: query.queryKey, exact: true, refetchType: "none" });
1069
+ if (!query.isActive()) return;
1070
+ timers.set(query, setTimeout(() => {
1071
+ timers.delete(query);
1072
+ if (client2.getQueryCache().get(query.queryHash) !== query || !query.isActive()) return;
1073
+ void refreshQuery(client2, query.queryKey, { exact: true });
1074
+ }, 250));
1075
+ }
1076
+ function handlePermissionChange(client2, event, type) {
1077
+ const edge = type === "ccm_change";
1078
+ if (edge && !accessEdges.has(event.edge_type)) return;
1079
+ const paths = [event.path, event.old_path, event.source_path].filter((path) => typeof path === "string");
1080
+ const ids = [event.item_id, event.source_item_id, event.source_id, event.target_item_id, event.target_id].filter(Boolean);
1081
+ if (!paths.length && !ids.length) return;
1082
+ for (const query of client2.getQueryCache().findAll({ queryKey: ["vfs"] })) {
1083
+ const meta = query.meta?.permissionQuery;
1084
+ if (!meta?.scope) continue;
1085
+ const direct = Boolean(meta.itemId && ids.includes(meta.itemId));
1086
+ const ancestor = Boolean(meta.path && paths.some((path) => isChannelPath(meta.path, path)));
1087
+ const scope = meta.scope;
1088
+ 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));
1089
+ const inherited = scoped && (event.item_type === "member" || event.item_type === "principal" || edge);
1090
+ if (direct || ancestor || !meta.targetLookup && inherited) invalidate(client2, query);
1091
+ }
1092
+ }
1093
+ function refreshPermissionsAfterReconnect(client2) {
1094
+ for (const query of client2.getQueryCache().findAll({ queryKey: ["vfs"] })) {
1095
+ if (query.meta?.permissionQuery) invalidate(client2, query);
1096
+ }
1097
+ }
1098
+ function clearPermissionRefreshes(client2) {
1099
+ pending3.get(client2)?.forEach((timer) => clearTimeout(timer));
1100
+ pending3.delete(client2);
1101
+ }
1052
1102
  var client = null;
1053
1103
  registerCleanup(() => {
1054
1104
  if (!client) return;
@@ -1089,7 +1139,7 @@ var queryClient = new Proxy({}, {
1089
1139
  });
1090
1140
 
1091
1141
  // src/item-query-realtime.ts
1092
- var pending3 = /* @__PURE__ */ new WeakMap();
1142
+ var pending4 = /* @__PURE__ */ new WeakMap();
1093
1143
  function listingFilter(query) {
1094
1144
  return query.meta?.infiniteItemsRealtime?.filter;
1095
1145
  }
@@ -1128,10 +1178,10 @@ function affectsListing(query, filter, event) {
1128
1178
  return hasPath || Boolean(filter.parent_id && event.parent_id === filter.parent_id);
1129
1179
  }
1130
1180
  function schedule(client2, query) {
1131
- let timers = pending3.get(client2);
1181
+ let timers = pending4.get(client2);
1132
1182
  if (!timers) {
1133
1183
  timers = /* @__PURE__ */ new Map();
1134
- pending3.set(client2, timers);
1184
+ pending4.set(client2, timers);
1135
1185
  }
1136
1186
  const previous = timers.get(query.queryHash);
1137
1187
  if (previous) clearTimeout(previous);
@@ -1154,8 +1204,8 @@ function refreshInfiniteItemsAfterReconnect(client2) {
1154
1204
  }
1155
1205
  }
1156
1206
  function clearInfiniteItemsRefreshes(client2) {
1157
- pending3.get(client2)?.forEach(clearTimeout);
1158
- pending3.delete(client2);
1207
+ pending4.get(client2)?.forEach(clearTimeout);
1208
+ pending4.delete(client2);
1159
1209
  }
1160
1210
 
1161
1211
  // src/items-selection.ts
@@ -1505,6 +1555,7 @@ function catchUpAfterGap(reason) {
1505
1555
  const qc = getQueryClient();
1506
1556
  refreshInfiniteItemsAfterReconnect(qc);
1507
1557
  reconnectArrangements(qc);
1558
+ refreshPermissionsAfterReconnect(qc);
1508
1559
  for (const sub of activePaths.values()) {
1509
1560
  void qc.invalidateQueries({ queryKey: vfsKeys.item(sub.path) });
1510
1561
  void qc.invalidateQueries({ queryKey: vfsKeys.children(sub.path) });
@@ -1542,6 +1593,9 @@ function handleMessage(raw) {
1542
1593
  if (msg.type === "event" || msg.event_type) {
1543
1594
  const eventType = msg.event_type || "message";
1544
1595
  const data = msg.data || msg;
1596
+ if (eventType === "vfs_change" || eventType === "ccm_change") {
1597
+ handlePermissionChange(getQueryClient(), data, eventType);
1598
+ }
1545
1599
  if (eventType === "vfs_change") {
1546
1600
  handleInfiniteItemsChange(getQueryClient(), data);
1547
1601
  handleArrangementChange(getQueryClient(), data);
@@ -1671,6 +1725,7 @@ function disconnectSSE() {
1671
1725
  log("disconnectSSE: tearing down");
1672
1726
  clearInfiniteItemsRefreshes(getQueryClient());
1673
1727
  clearArrangementRefreshes(getQueryClient());
1728
+ clearPermissionRefreshes(getQueryClient());
1674
1729
  intentionalClose = true;
1675
1730
  stopPing();
1676
1731
  if (ws) {
@@ -3041,13 +3096,13 @@ function watchChannelTranscript(client2, key, channel, limit) {
3041
3096
  let timer;
3042
3097
  let running2 = false;
3043
3098
  let stopped = false;
3044
- const pending4 = /* @__PURE__ */ new Map();
3099
+ const pending5 = /* @__PURE__ */ new Map();
3045
3100
  const current = () => client2.getQueryData(key);
3046
3101
  const query = () => client2.getQueryCache().find({ queryKey: key, exact: true });
3047
3102
  const reload = () => refreshQuery(client2, key, { exact: true });
3048
3103
  const read = (after_seq, before_seq) => fetchChannelMessagesPage(channel, { transcriptOnly: true, limit, after_seq, before_seq });
3049
3104
  const schedule2 = () => {
3050
- if (stopped || running2 || timer || !pending4.size) return;
3105
+ if (stopped || running2 || timer || !pending5.size) return;
3051
3106
  timer = setTimeout(() => {
3052
3107
  timer = void 0;
3053
3108
  void flush();
@@ -3055,8 +3110,8 @@ function watchChannelTranscript(client2, key, channel, limit) {
3055
3110
  };
3056
3111
  const flush = async () => {
3057
3112
  running2 = true;
3058
- const changes = [...pending4.values()];
3059
- pending4.clear();
3113
+ const changes = [...pending5.values()];
3114
+ pending5.clear();
3060
3115
  const owner = query();
3061
3116
  try {
3062
3117
  if (owner?.state.fetchStatus === "fetching") await owner.promise?.catch(() => void 0);
@@ -3130,15 +3185,15 @@ function watchChannelTranscript(client2, key, channel, limit) {
3130
3185
  };
3131
3186
  const stop = subscribeToEvents("vfs_change", (change) => {
3132
3187
  const id = change.item_id ?? change.path;
3133
- const previous = pending4.get(id);
3134
- pending4.set(id, previous && (previous.inserted || isNewPost(previous, channel)) && actionOf(change) === "update" && previous.path === change.path ? { ...change, inserted: true } : change);
3188
+ const previous = pending5.get(id);
3189
+ pending5.set(id, previous && (previous.inserted || isNewPost(previous, channel)) && actionOf(change) === "update" && previous.path === change.path ? { ...change, inserted: true } : change);
3135
3190
  schedule2();
3136
3191
  }, (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)));
3137
3192
  watch = { users: 0, stop: () => {
3138
3193
  stopped = true;
3139
3194
  stop();
3140
3195
  if (timer) clearTimeout(timer);
3141
- pending4.clear();
3196
+ pending5.clear();
3142
3197
  } };
3143
3198
  entries.set(hash, watch);
3144
3199
  }
@@ -3184,7 +3239,7 @@ function watchChannels(client2, key, normalize) {
3184
3239
  running2 = true;
3185
3240
  const reload = inventory;
3186
3241
  inventory = false;
3187
- const pending4 = [...channels];
3242
+ const pending5 = [...channels];
3188
3243
  const checkRename = new Set(renames);
3189
3244
  renames.clear();
3190
3245
  channels.clear();
@@ -3192,7 +3247,7 @@ function watchChannels(client2, key, normalize) {
3192
3247
  if (reload) {
3193
3248
  await refreshQuery(client2, key, { exact: true });
3194
3249
  } else {
3195
- const results = await Promise.allSettled(pending4.map(async (id) => {
3250
+ const results = await Promise.allSettled(pending5.map(async (id) => {
3196
3251
  const owner = client2.getQueryCache().find({ queryKey: key, exact: true });
3197
3252
  if (!owner) return;
3198
3253
  const result = await gatewayCall("read", { id });
@@ -3324,6 +3379,92 @@ function watchMessageReplies(client2, key, target) {
3324
3379
  }
3325
3380
  };
3326
3381
  }
3382
+ var actions = /* @__PURE__ */ new Set(["view", "edit", "delete", "admin"]);
3383
+ var uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3384
+ function targetFromRead(response) {
3385
+ const raw = response.item ?? response;
3386
+ const id = raw.id ?? raw.item_id;
3387
+ const path = raw.path ?? raw.item_path;
3388
+ if (response.success !== true || typeof id !== "string" || !uuid.test(id)) {
3389
+ throw new Error("PERMISSION_TARGET_UNAVAILABLE");
3390
+ }
3391
+ return { id, ...typeof path === "string" ? { path } : {} };
3392
+ }
3393
+ function usePermissions(item, requested) {
3394
+ React.useSyncExternalStore(subscribeScope, getScopeVersion, getScopeVersion);
3395
+ const epoch = React.useSyncExternalStore(subscribeSession, getSessionVersion, getSessionVersion);
3396
+ const mounts = React.useSyncExternalStore(subscribeMounts, getMountVersion, getMountVersion);
3397
+ const scope = getScope();
3398
+ const principal = getSessionEntry()?.principal_id;
3399
+ const target = item?.trim() ?? "";
3400
+ const wanted = [...new Set(requested ?? [])].sort();
3401
+ const directId = uuid.test(target);
3402
+ const validTarget = directId || (target.startsWith("/root/") || target === "/root");
3403
+ const invalid = wanted.some((action) => !actions.has(action)) || Boolean(target && !validTarget);
3404
+ const enabled2 = Boolean(scope && principal && target && wanted.length && !invalid);
3405
+ const root = ["vfs", scope ?? "__unscoped__", "permissions", principal ?? "__anonymous__", epoch, mounts];
3406
+ const scopeIds = [...new Set([getAnchorRef()?.id, ...getMounts().map((mount3) => mount3.id)].filter((id) => Boolean(id)))];
3407
+ const targetKey = [...root, "target", target];
3408
+ const identity = reactQuery.useQuery({
3409
+ queryKey: targetKey,
3410
+ queryFn: async ({ signal: signal2 }) => {
3411
+ if (!enabled2 || !scope) throw new Error("PERMISSION_CONTEXT_REQUIRED");
3412
+ return targetFromRead(await gatewayCall("read", { path: target, _scope_path: scope }, { signal: signal2 }));
3413
+ },
3414
+ enabled: enabled2 && !directId,
3415
+ staleTime: Infinity,
3416
+ gcTime: 0,
3417
+ retry: false,
3418
+ refetchOnWindowFocus: false,
3419
+ refetchOnReconnect: false,
3420
+ refetchOnMount: false,
3421
+ meta: { permissionQuery: { scope, scopeIds, path: target, targetLookup: true } }
3422
+ });
3423
+ const resolved = directId ? { id: target } : identity.data;
3424
+ const identityReady = directId || identity.isSuccess && !identity.isFetching && !identity.isStale;
3425
+ const checks = reactQuery.useQueries({ queries: wanted.filter((action) => actions.has(action)).map((action) => ({
3426
+ queryKey: [...root, "check", resolved?.id ?? target, action],
3427
+ queryFn: async ({ signal: signal2 }) => {
3428
+ if (!enabled2 || !scope || !resolved) throw new Error("PERMISSION_CONTEXT_REQUIRED");
3429
+ const result = await gatewayCall("check-item-access", { id: resolved.id, action, _scope_path: scope }, { signal: signal2 });
3430
+ if (result.success !== true || typeof result.allowed !== "boolean") throw new Error("PERMISSION_RESPONSE_INVALID");
3431
+ return result.allowed;
3432
+ },
3433
+ enabled: enabled2 && identityReady && Boolean(resolved),
3434
+ staleTime: Infinity,
3435
+ gcTime: 0,
3436
+ retry: false,
3437
+ refetchOnWindowFocus: false,
3438
+ refetchOnReconnect: false,
3439
+ refetchOnMount: false,
3440
+ meta: { permissionQuery: { scope, scopeIds, itemId: resolved?.id, path: resolved?.path ?? (directId ? void 0 : target) } }
3441
+ })) });
3442
+ const error = invalid ? new Error("PERMISSION_INPUT_INVALID") : !directId && identity.error || checks.find((check) => check.error)?.error || null;
3443
+ const verified = enabled2 && identityReady && !error;
3444
+ const supported = wanted.filter((action) => actions.has(action));
3445
+ const data = Object.fromEntries(wanted.map((action) => {
3446
+ const check = checks[supported.indexOf(action)];
3447
+ return [action, Boolean(verified && check?.isSuccess && !check.isFetching && !check.isStale && check.data === true)];
3448
+ }));
3449
+ return {
3450
+ data,
3451
+ loading: Boolean(enabled2 && (!directId && identity.isFetching || checks.some((check) => check.isFetching || check.isPending)) && !error),
3452
+ error,
3453
+ /** Explicit refresh for a user action; no automatic retry or polling. */
3454
+ refetch: async () => {
3455
+ if (!enabled2) return;
3456
+ if (!directId && (!identity.data || identity.isError)) {
3457
+ await identity.refetch();
3458
+ return;
3459
+ }
3460
+ await Promise.all(checks.map((check) => check.refetch()));
3461
+ }
3462
+ };
3463
+ }
3464
+ function usePermission(action, item) {
3465
+ const result = usePermissions(item, action ? [action] : []);
3466
+ return { ...result, data: { allowed: Boolean(action && result.data[action]) } };
3467
+ }
3327
3468
 
3328
3469
  // src/hooks.ts
3329
3470
  function useScopeKey() {
@@ -3532,7 +3673,7 @@ function useIncrementalItems(filter, options = {}) {
3532
3673
  let wasConnected = false;
3533
3674
  let missed = false;
3534
3675
  let generation = 0;
3535
- const pending4 = /* @__PURE__ */ new Map();
3676
+ const pending5 = /* @__PURE__ */ new Map();
3536
3677
  const reconcile = () => {
3537
3678
  const started = generation;
3538
3679
  void refetch.current().then((result) => {
@@ -3549,18 +3690,18 @@ function useIncrementalItems(filter, options = {}) {
3549
3690
  delete upserts[path];
3550
3691
  return { identity, upserts, deleted: new Set(state.deleted).add(path) };
3551
3692
  });
3552
- const earlier = pending4.get("__reconcile__");
3693
+ const earlier = pending5.get("__reconcile__");
3553
3694
  if (earlier) clearTimeout(earlier);
3554
- pending4.set("__reconcile__", setTimeout(() => {
3555
- pending4.delete("__reconcile__");
3695
+ pending5.set("__reconcile__", setTimeout(() => {
3696
+ pending5.delete("__reconcile__");
3556
3697
  reconcile();
3557
3698
  }, 250));
3558
3699
  };
3559
3700
  const readOne = (path) => {
3560
- const earlier = pending4.get(path);
3701
+ const earlier = pending5.get(path);
3561
3702
  if (earlier) clearTimeout(earlier);
3562
- pending4.set(path, setTimeout(() => {
3563
- pending4.delete(path);
3703
+ pending5.set(path, setTimeout(() => {
3704
+ pending5.delete(path);
3564
3705
  void client2.fetchQuery({ queryKey: vfsKeys.item(path), queryFn: () => fetchVfsItem(path), staleTime: 0 }).then((item) => {
3565
3706
  if (stopped) return;
3566
3707
  if (!item || !itemMatchesIncrementalFilter(item, selected)) {
@@ -3623,7 +3764,7 @@ function useIncrementalItems(filter, options = {}) {
3623
3764
  stopped = true;
3624
3765
  stopEvents();
3625
3766
  stopConnection();
3626
- pending4.forEach(clearTimeout);
3767
+ pending5.forEach(clearTimeout);
3627
3768
  };
3628
3769
  }, [client2, identity]);
3629
3770
  return { ...query, allItems };
@@ -4379,15 +4520,15 @@ async function readPublishedBundle(componentId, releaseItemId, version) {
4379
4520
  return { status: "ready", releaseItemId, version, script, stylesheet: stylesheet?.trim() ? stylesheet : null };
4380
4521
  }
4381
4522
  function publishedBundle(componentId, releaseItemId, version) {
4382
- let pending4 = publishedBundles.get(releaseItemId);
4383
- if (!pending4) {
4384
- pending4 = readPublishedBundle(componentId, releaseItemId, version);
4385
- publishedBundles.set(releaseItemId, pending4);
4386
- pending4.catch(() => {
4387
- if (publishedBundles.get(releaseItemId) === pending4) publishedBundles.delete(releaseItemId);
4523
+ let pending5 = publishedBundles.get(releaseItemId);
4524
+ if (!pending5) {
4525
+ pending5 = readPublishedBundle(componentId, releaseItemId, version);
4526
+ publishedBundles.set(releaseItemId, pending5);
4527
+ pending5.catch(() => {
4528
+ if (publishedBundles.get(releaseItemId) === pending5) publishedBundles.delete(releaseItemId);
4388
4529
  });
4389
4530
  }
4390
- return pending4;
4531
+ return pending5;
4391
4532
  }
4392
4533
  function loadPublishedBundle(source) {
4393
4534
  const live = liveRelease(source);
@@ -4511,16 +4652,6 @@ function useTheme() {
4511
4652
  }, []);
4512
4653
  return { data: themeData, loading: false, error: null };
4513
4654
  }
4514
- function usePermission(_action, _path) {
4515
- return { data: { allowed: true }, loading: false, error: null };
4516
- }
4517
- function usePermissions(_path, actions) {
4518
- const perms = {};
4519
- (actions || []).forEach((a) => {
4520
- perms[a] = true;
4521
- });
4522
- return { data: perms, loading: false, error: null };
4523
- }
4524
4655
  var _principalIdCache = null;
4525
4656
  var _principalIdPromise = null;
4526
4657
  var _principalListeners = /* @__PURE__ */ new Set();
@@ -5617,7 +5748,7 @@ function usePersonalItemOrder(key, items, space) {
5617
5748
  return [...unplaced, ...arranged.filter((item) => savedIds.has(item.id))];
5618
5749
  }, [key, items, query.applyTo, query.order]);
5619
5750
  const client2 = reactQuery.useQueryClient();
5620
- const pending4 = React.useRef(false);
5751
+ const pending5 = React.useRef(false);
5621
5752
  const ready = Boolean(supported && !query.error && query.arrangement?.item_id && query.resolutionLevel === "member" && query.arrangement.write_target_id === query.arrangement.item_id);
5622
5753
  const mutation = reactQuery.useMutation({
5623
5754
  mutationFn: async (change) => {
@@ -5635,7 +5766,7 @@ function usePersonalItemOrder(key, items, space) {
5635
5766
  if (!ready || !scopePath || identity !== activeIdentity.current || generation !== getScopeVersion() || getScope() !== mountedScope) {
5636
5767
  throw new Error("Personal order is not available in this Space");
5637
5768
  }
5638
- if (pending4.current) throw new Error("An order change is already being saved");
5769
+ if (pending5.current) throw new Error("An order change is already being saved");
5639
5770
  const visibleIds = items.map((item) => item.id);
5640
5771
  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");
5641
5772
  const cached = client2.getQueryData(query.arrangementQueryKey);
@@ -5648,7 +5779,7 @@ function usePersonalItemOrder(key, items, space) {
5648
5779
  let index = 0;
5649
5780
  const saved = (query.order ?? []).map((id) => visible.has(id) ? ids[index++] : id);
5650
5781
  const order = [...saved, ...ids.slice(index)];
5651
- pending4.current = true;
5782
+ pending5.current = true;
5652
5783
  try {
5653
5784
  return await mutation.mutateAsync({
5654
5785
  ids: order,
@@ -5657,7 +5788,7 @@ function usePersonalItemOrder(key, items, space) {
5657
5788
  queryKey: query.arrangementQueryKey
5658
5789
  });
5659
5790
  } finally {
5660
- pending4.current = false;
5791
+ pending5.current = false;
5661
5792
  }
5662
5793
  }
5663
5794
  return {
@@ -6308,6 +6439,49 @@ async function submitForm(capabilityId, fields, options = {}) {
6308
6439
  }, fillId, pageUrl, identity, options.signal);
6309
6440
  return payload;
6310
6441
  }
6442
+
6443
+ // src/commerce.ts
6444
+ async function startFileCheckout(options) {
6445
+ return gatewayCall("commerce-file-sale", {
6446
+ action: "checkout",
6447
+ product_id: options.productId,
6448
+ expected_product_revision_id: options.productRevisionId,
6449
+ destination_id: options.destinationId,
6450
+ request_key: options.requestKey,
6451
+ _scope_path: options.scopePath,
6452
+ ...options.journey ? { journey: options.journey } : {}
6453
+ });
6454
+ }
6455
+ async function getFilePurchase(licenseId, scopePath) {
6456
+ return gatewayCall("commerce-file-sale", { action: "get", license_id: licenseId, _scope_path: scopePath });
6457
+ }
6458
+ function funnelCheckoutLink(options) {
6459
+ const host = new URL(options.hostOrigin);
6460
+ if (host.protocol !== "https:" && !(host.protocol === "http:" && host.hostname === "127.0.0.1") || host.username || host.password || host.search || host.hash || host.pathname !== "/") {
6461
+ throw new TypeError("hostOrigin must be an HTTPS origin or the local 127.0.0.1 app");
6462
+ }
6463
+ const page = new URL(options.pageUrl ?? window.location.href);
6464
+ if (page.protocol !== "https:" || page.username || page.password || page.hash || page.port) {
6465
+ throw new TypeError("The funnel must be a published HTTPS page");
6466
+ }
6467
+ const link = new URL("/v2/revven", host);
6468
+ link.search = new URLSearchParams({
6469
+ surface: "library",
6470
+ offer: options.productId,
6471
+ sale_page: page.href,
6472
+ sale_action: options.capabilityId
6473
+ }).toString();
6474
+ return link.href;
6475
+ }
6476
+ function filePurchaseNextUrl(receipt) {
6477
+ if (receipt.success !== true || receipt.state !== "ready" || !receipt.item_id || !receipt.file_id || !receipt.journey?.next_url) return null;
6478
+ const next = new URL(receipt.journey.next_url);
6479
+ const source = new URL(receipt.journey.return_url);
6480
+ if (next.protocol !== "https:" || source.protocol !== "https:" || next.origin !== source.origin || next.username || next.password || next.hash || next.searchParams.getAll("funnel_id").length !== 1 || next.searchParams.get("funnel_id") !== receipt.journey.funnel_id) {
6481
+ throw new Error("The purchase destination could not be verified");
6482
+ }
6483
+ return next.href;
6484
+ }
6311
6485
  function readItem(path) {
6312
6486
  return gatewayCall("read", { path });
6313
6487
  }
@@ -7362,7 +7536,7 @@ function usePersonalSections(contextId, collection) {
7362
7536
  meta: { arrangementRealtime: true, personalSections: true },
7363
7537
  structuralSharing: (previous, next) => newestSnapshot(previous, next)
7364
7538
  });
7365
- const pending4 = React.useRef(false);
7539
+ const pending5 = React.useRef(false);
7366
7540
  const mutation = reactQuery.useMutation({ mutationFn: async (write) => {
7367
7541
  const data = await call(write.scope, write.context, write.collection, {
7368
7542
  ...write.change,
@@ -7375,12 +7549,12 @@ function usePersonalSections(contextId, collection) {
7375
7549
  if (!scopePath || !contextId || generation !== getScopeVersion() || getScope() !== scopePath || !query.data || query.error) {
7376
7550
  throw new Error("Select the Space again before changing sections");
7377
7551
  }
7378
- if (pending4.current) throw new Error("A section change is still being saved");
7379
- pending4.current = true;
7552
+ if (pending5.current) throw new Error("A section change is still being saved");
7553
+ pending5.current = true;
7380
7554
  try {
7381
7555
  return await mutation.mutateAsync({ change: value, scope: scopePath, context: contextId, collection, version: query.data.version });
7382
7556
  } finally {
7383
- pending4.current = false;
7557
+ pending5.current = false;
7384
7558
  }
7385
7559
  }
7386
7560
  function destination(sectionId) {
@@ -7458,6 +7632,8 @@ exports.fetchVfsChildrenPage = fetchVfsChildrenPage;
7458
7632
  exports.fetchVfsItem = fetchVfsItem;
7459
7633
  exports.fetchVfsItemById = fetchVfsItemById;
7460
7634
  exports.fetchVfsTree = fetchVfsTree;
7635
+ exports.filePurchaseNextUrl = filePurchaseNextUrl;
7636
+ exports.funnelCheckoutLink = funnelCheckoutLink;
7461
7637
  exports.gatewayCall = gatewayCall;
7462
7638
  exports.getAccessToken = getAccessToken;
7463
7639
  exports.getAnchor = getAnchor;
@@ -7465,6 +7641,7 @@ exports.getAnchorRef = getAnchorRef;
7465
7641
  exports.getAnchorVersion = getAnchorVersion;
7466
7642
  exports.getAssetUrl = getAssetUrl;
7467
7643
  exports.getDefaultSort = getDefaultSort;
7644
+ exports.getFilePurchase = getFilePurchase;
7468
7645
  exports.getHomeAnchor = getHomeAnchor;
7469
7646
  exports.getInvitation = getInvitation;
7470
7647
  exports.getMountVersion = getMountVersion;
@@ -7532,6 +7709,7 @@ exports.setQueryClient = setQueryClient;
7532
7709
  exports.setScope = setScope;
7533
7710
  exports.setupRequireShim = setupRequireShim;
7534
7711
  exports.signal = signal;
7712
+ exports.startFileCheckout = startFileCheckout;
7535
7713
  exports.startTracking = startTracking;
7536
7714
  exports.steerTurn = steerTurn;
7537
7715
  exports.submitForm = submitForm;