"use strict";exports.id=6700,exports.ids=[6700],exports.modules={66700:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{AX:()=>L,B6:()=>K,Bd:()=>B,DJ:()=>E,LC:()=>W,O7:()=>J,Zb:()=>U,bP:()=>V,claimEmailInvitesViaCloud:()=>O,ensureCloudOrg:()=>v,fv:()=>F,getSharedCloudAdmin:()=>r,gx:()=>X,i9:()=>D,isSharedCloudReady:()=>n,mirrorCloudMembershipsForUser:()=>Q,p5:()=>M,p7:()=>A,redeemInviteViaCloud:()=>P,to:()=>I,zF:()=>q});var e=c(77598),f=c(34255),g=c(24516),h=c(58282),i=c(4160),j=c(61423),k=a([f,g,h,i,j]);function l(){}function m(a,b={}){try{let c=(0,g.getSecret)(a,{agent_id:b.agent_id,project_id:b.project_id});if(c)return c}catch{}return process.env[a]||null}function n(a={}){let b=m("SUPABASE_URL",a),c=m("SUPABASE_SERVICE_ROLE_KEY",a);return!!(b&&c)}function o(a,b={}){for(let[c,d]of Object.entries(b)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(c))throw Error(`Invalid filter column: ${c}`);a.searchParams.set(c,String(d).includes(".")?String(d):`eq.${d}`)}}function p({baseUrl:a,apikey:b,bearer:c,agentId:d=null}){let e=`${a.replace(/\/+$/g,"")}/rest/v1`;function f(a={}){return{Authorization:`Bearer ${c}`,apikey:b,Accept:"application/json",...a}}async function g(a){let b={};try{b=await a.json()}catch{}return b.message||b.error||a.statusText||`HTTP ${a.status}`}return{async select(a,{filters:b={},select:c="*",limit:i=100}={}){let j=new URL(`${e}/${a}`);j.searchParams.set("select",c),j.searchParams.set("limit",String(Math.min(Math.max(Number(i)||1,1),1e3))),o(j,b);let k=await (0,h.N)("shared_cloud_select",d)(j,{headers:f()});if(!k.ok)throw Error(`shared_cloud select(${a}) failed: ${await g(k)}`);return k.json()},async upsert(a,b,{onConflict:c}={}){let i=Array.isArray(b)?b:[b],j=new URL(`${e}/${a}`);c&&j.searchParams.set("on_conflict",String(c));let k=await (0,h.N)("shared_cloud_upsert",d)(j,{method:"POST",headers:f({"Content-Type":"application/json",Prefer:"resolution=merge-duplicates,return=representation"}),body:JSON.stringify(i)});if(!k.ok)throw Error(`shared_cloud upsert(${a}) failed: ${await g(k)}`);return k.json()},async delete(a,{filters:b}={}){if(!b||!Object.keys(b).length)throw Error("shared_cloud delete requires filters; bulk delete is blocked.");let c=new URL(`${e}/${a}`);o(c,b);let i=await (0,h.N)("shared_cloud_delete",d)(c,{method:"DELETE",headers:f({Prefer:"return=representation"})});if(!i.ok)throw Error(`shared_cloud delete(${a}) failed: ${await g(i)}`);return i.json()},async rpc(a,b={}){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))throw Error(`Invalid rpc function name: ${a}`);let c=new URL(`${e}/rpc/${a}`),i=await (0,h.N)("shared_cloud_rpc",d)(c,{method:"POST",headers:f({"Content-Type":"application/json"}),body:JSON.stringify(b??{})});if(!i.ok)throw Error(`shared_cloud rpc(${a}) failed: ${await g(i)}`);return i.json()}}}function q(a={}){let b=m("SUPABASE_URL",a),c=m("SUPABASE_ANON_KEY",a);return!!(b&&c)}function r(a={}){let b=m("SUPABASE_URL",a),c=m("SUPABASE_SERVICE_ROLE_KEY",a);if(!b||!c)throw Error("Shared cloud not configured: set SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.");return p({baseUrl:b,apikey:c,bearer:c,agentId:a.agent_id??null})}function s(a,b={}){if(l(),!a)throw Error("getSharedCloudUserClient: an access token (user JWT) is required");let c=m("SUPABASE_URL",b),d=m("SUPABASE_ANON_KEY",b);if(!c||!d)throw Error("Shared cloud (user) not configured: set SUPABASE_URL and SUPABASE_ANON_KEY.");return p({baseUrl:c,apikey:d,bearer:a,agentId:b.agent_id??null})}function t({serviceReady:a,userReady:b,accessToken:c}){return a?"admin":b&&c?"user":null}function u(a,b){let c=a?.session?.supabase_access_token||a?.accessToken||null,d=t({serviceReady:n(b),userReady:q(b),accessToken:c});return"admin"===d?{client:r(b),kind:d}:"user"===d?{client:s(c,b),kind:d}:{client:null,kind:null}}async function v(a,b={}){if(l(),!a?.id||!a?.slug||!a?.name)throw Error("ensureCloudOrg: id, slug, and name are required");if(!n(b))return!1;let c={id:a.id,slug:a.slug,name:a.name,plan:a.plan||"free"};return await r(b).upsert("organizations",c,{onConflict:"id"}),!0}[f,g,h,i,j]=k.then?(await k)():k,Object.freeze(["private","team","org","link"]);let Y=Object.freeze(["org","team","private"]),Z=Object.freeze(["dashboard_space","project"]),$=Object.freeze(["folder","file","artifact"]);function w(a,b){if(!Y.includes(a))throw Error(`${b}: invalid visibility "${a}" (expected one of ${Y.join("|")})`)}function x(a,b){if(!Z.includes(a))throw Error(`${b}: invalid space_type "${a}" (expected one of ${Z.join("|")})`)}function y(a,b){return(0,f.getDb)().prepare("SELECT * FROM shared_space_publications WHERE local_space_id = ? AND space_type = ?").get(a,b)||null}function z(a){let b=(0,f.getDb)(),c=b.prepare("SELECT id FROM shared_space_publications WHERE local_space_id = ? AND space_type = ?").get(a.local_space_id,a.space_type),d=c?.id||(0,f.newId)("spub");return b.prepare(`INSERT INTO shared_space_publications
       (id, local_space_id, space_type, org_id, cloud_space_id, slug, name,
        visibility, include_resource_metadata, resource_count, status, last_error,
        published_by, published_at, last_synced_at, unpublished_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
     ON CONFLICT(local_space_id, space_type) DO UPDATE SET
       org_id                    = excluded.org_id,
       cloud_space_id            = excluded.cloud_space_id,
       slug                      = excluded.slug,
       name                      = excluded.name,
       visibility                = excluded.visibility,
       include_resource_metadata = excluded.include_resource_metadata,
       resource_count            = excluded.resource_count,
       status                    = excluded.status,
       last_error                = excluded.last_error,
       published_by              = excluded.published_by,
       last_synced_at            = excluded.last_synced_at,
       unpublished_at            = excluded.unpublished_at`).run(d,a.local_space_id,a.space_type,a.org_id,a.cloud_space_id??null,a.slug??null,a.name??null,a.visibility,+!!a.include_resource_metadata,Number(a.resource_count)||0,a.status,a.last_error??null,a.published_by??null,a.published_at??(0,f.nowIso)(),a.last_synced_at??null,a.unpublished_at??null),d}function A(a,b="dashboard_space"){x(b,"getSharedSpaceStatus");let c=y(a,b);return c?{shared:"published"===c.status,status:c.status,space_type:c.space_type,local_space_id:c.local_space_id,cloud_space_id:c.cloud_space_id||null,slug:c.slug||null,name:c.name||null,visibility:c.visibility||null,include_resource_metadata:1===c.include_resource_metadata,resource_count:Number(c.resource_count)||0,last_error:c.last_error||null,published_by:c.published_by||null,published_at:c.published_at||null,last_synced_at:c.last_synced_at||null}:{shared:!1,status:"local",space_type:b,local_space_id:a,cloud_space_id:null,visibility:null,resource_count:0,last_synced_at:null}}function B({status:a,space_type:b}={}){let c=(0,f.getDb)(),d=[],e=[];a&&(d.push("status = ?"),e.push(a)),b&&(d.push("space_type = ?"),e.push(b));let g=`SELECT * FROM shared_space_publications ${d.length?`WHERE ${d.join(" AND ")}`:""} ORDER BY published_at DESC`;return c.prepare(g).all(...e)}async function C(a,{session:b,options:c,resources:d=null,include_resource_metadata:e=!1,excludedLocalOnly:g=0,target_type:h,target_id:j}){var k=a;if(!k||"object"!=typeof k)throw Error("shared space metadata must be an object");for(let a of["org_id","space_type","local_space_id","slug","name","visibility"])if(null==k[a]||""===k[a])throw Error(`shared space metadata missing required field: ${a}`);x(k.space_type,"validateSharedSpaceMetadata"),w(k.visibility,"validateSharedSpaceMetadata");let{org_id:l,space_type:m,local_space_id:o}=a;if(!n(c))throw Error(`publish ${m}: shared cloud is not configured. Set SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY (vault or env) before sharing.`);let p=r(c),q=null;try{let b=await p.upsert("shared_spaces",a,{onConflict:"org_id,space_type,local_space_id"});q=Array.isArray(b)?b[0]:b}catch(c){throw z({local_space_id:o,space_type:m,org_id:l,slug:a.slug,name:a.name,visibility:a.visibility,include_resource_metadata:e,status:"error",last_error:c.message,published_by:b?.user_id}),(0,i.appendComplianceAudit)({user_id:b?.user_id,org_id:l,action:`${m}.shared.publish.error`,action_target_id:j,action_target_type:h,status:"error",summary:`Failed to share ${m} ${o} to shared cloud`,meta:{visibility:a.visibility,error:c.message}}),c}let s=q?.id??null,t=0;if(e&&Array.isArray(d)&&s&&(await p.delete("shared_space_resources",{filters:{org_id:l,shared_space_id:s}}),d.length)){let a=d.map(a=>(function(a,b={}){if(!a||!a.local_resource_id)throw Error("mapProjectResourceMetadata: resource with local_resource_id is required");if(!b.org_id)throw Error("mapProjectResourceMetadata: org_id is required");if(!b.cloud_space_id)throw Error("mapProjectResourceMetadata: cloud_space_id is required");if(!$.includes(a.resource_type))throw Error(`mapProjectResourceMetadata: invalid resource_type "${a.resource_type}"`);return{org_id:b.org_id,shared_space_id:b.cloud_space_id,local_resource_id:String(a.local_resource_id),resource_type:a.resource_type,name:a.name||a.local_resource_id,path:a.path??null,mime_type:a.mime_type??null,kind:a.kind??null,size_bytes:"number"==typeof a.size_bytes?a.size_bytes:null,sha256:a.sha256??null,local_only:!!a.local_only,metadata:a.metadata??null}})(a,{org_id:l,cloud_space_id:s}));await p.upsert("shared_space_resources",a,{onConflict:"shared_space_id,resource_type,local_resource_id"}),t=a.length}return z({local_space_id:o,space_type:m,org_id:l,cloud_space_id:s,slug:a.slug,name:a.name,visibility:a.visibility,include_resource_metadata:e,resource_count:t,status:"published",published_by:b?.user_id,published_at:(0,f.nowIso)(),last_synced_at:(0,f.nowIso)()}),(0,i.appendComplianceAudit)({user_id:b?.user_id,org_id:l,action:`${m}.shared.published`,action_target_id:j,action_target_type:h,status:"success",summary:`Shared ${m} ${o} to shared cloud (visibility: ${a.visibility})`,meta:{visibility:a.visibility,cloud_space_id:s,resource_count:t,excluded_local_only:g}}),A(o,m)}async function D(a={},b={}){var c;let{space_id:d,session:e,visibility:g="org"}=a;if(!d)throw Error("publishDashboardSpace: space_id is required");let h=a.org_id||e?.org_id;if(!h)throw Error("publishDashboardSpace: org_id (or session.org_id) is required");w(g,"publishDashboardSpace");let i=(0,f.getDb)().prepare("SELECT * FROM dashboard_spaces WHERE id = ?").get(String(d));if(!i)throw Error(`publishDashboardSpace: dashboard space ${d} not found locally`);let j=function(a,b={}){if(!a||!a.id)throw Error("mapDashboardSpaceToSharedSpaceMetadata: space with id is required");if(!b.org_id)throw Error("mapDashboardSpaceToSharedSpaceMetadata: org_id is required");let c=b.visibility||"org";w(c,"mapDashboardSpaceToSharedSpaceMetadata");let d=a.slug||String(a.id);return{org_id:b.org_id,space_type:"dashboard_space",local_space_id:String(a.id),local_project_id:null,slug:d,name:a.name||d,description:a.description??null,visibility:c,created_by:b.created_by??null}}(i,{org_id:h,visibility:g,created_by:a.published_by??null}),k=(c=String(d),(0,f.getDb)().prepare("SELECT id, title, kind FROM artifacts WHERE space_id = ? ORDER BY created_at DESC").all(String(c)).map(a=>({local_resource_id:a.id,resource_type:"artifact",name:a.title||a.id,kind:a.kind??null})));return C(j,{session:e,options:b,resources:k,include_resource_metadata:!0,target_type:"dashboard_space",target_id:String(d)})}async function E(a={},b={}){let{session:c,visibility:d="org",includeResourceMetadata:e=!0}=a,g=a.project_id||a.slug;if(!g)throw Error("publishProjectFolder: project_id or slug is required");let h=a.org_id||c?.org_id;if(!h)throw Error("publishProjectFolder: org_id (or session.org_id) is required");w(d,"publishProjectFolder");let i=(0,j.U1)(g);if(!i)throw Error(`publishProjectFolder: project ${g} not found locally`);let k=function(a,b={}){if(!a||!a.id)throw Error("mapProjectToSharedSpaceMetadata: project with id is required");if(!b.org_id)throw Error("mapProjectToSharedSpaceMetadata: org_id is required");let c=b.visibility||"org";return w(c,"mapProjectToSharedSpaceMetadata"),{org_id:b.org_id,space_type:"project",local_space_id:String(a.id),local_project_id:String(a.id),slug:a.slug||String(a.id),name:a.name||a.slug||String(a.id),description:a.description??null,visibility:c,created_by:b.created_by??null}}(i,{org_id:h,visibility:d,created_by:a.published_by??null}),l=null,m=0;if(e){let b=function(a,{includeLocalOnly:b=!1,allowLocalOnlyOverride:c=!1}={}){if(b&&!c)throw Error("publishProjectFolder: refusing to share local_only resources. local_only is a hard content boundary; pass allowLocalOnlyOverride:true to force metadata-only sharing of local_only files (bodies are never uploaded).");let d=(0,f.getDb)(),e=[];for(let b of d.prepare("SELECT * FROM disk_folders WHERE project_id = ? ORDER BY path ASC").all(a))e.push({local_resource_id:b.id,resource_type:"folder",name:b.name,path:b.path});let g=0;for(let c of d.prepare("SELECT * FROM disk_files WHERE project_id = ? ORDER BY updated_at DESC").all(a)){let a=1===c.local_only;if(a&&!b){g+=1;continue}e.push({local_resource_id:c.id,resource_type:"file",name:c.name,path:c.path??null,mime_type:c.mime_type??null,kind:c.kind??null,size_bytes:"number"==typeof c.size_bytes?c.size_bytes:null,sha256:c.sha256??null,local_only:a})}for(let b of d.prepare("SELECT id, title, kind FROM artifacts WHERE project_id = ? ORDER BY created_at DESC").all(a))e.push({local_resource_id:b.id,resource_type:"artifact",name:b.title||b.id,kind:b.kind??null});return{resources:e,excludedLocalOnly:g}}(i.id,{includeLocalOnly:!0===a.includeLocalOnly,allowLocalOnlyOverride:!0===a.allowLocalOnlyOverride});l=b.resources,m=b.excludedLocalOnly}return C(k,{session:c,options:b,resources:l,include_resource_metadata:e,excludedLocalOnly:m,target_type:"project",target_id:i.id})}async function F(a={},b={}){let{local_space_id:c,session:d,space_type:e="dashboard_space"}=a;if(!c)throw Error("unpublishSpace: local_space_id is required");let g=a.org_id||d?.org_id;if(!g)throw Error("unpublishSpace: org_id (or session.org_id) is required");if(x(e,"unpublishSpace"),!n(b))throw Error("unpublishSpace: shared cloud is not configured.");let h=r(b),j=y(c,e);return j?.cloud_space_id&&await h.delete("shared_space_resources",{filters:{org_id:g,shared_space_id:j.cloud_space_id}}),await h.delete("shared_spaces",{filters:{org_id:g,space_type:e,local_space_id:c}}),z({local_space_id:c,space_type:e,org_id:g,visibility:j?.visibility||"private",status:"unpublished",resource_count:0,published_by:d?.user_id,unpublished_at:(0,f.nowIso)(),last_synced_at:(0,f.nowIso)()}),(0,i.appendComplianceAudit)({user_id:d?.user_id,org_id:g,action:`${e}.shared.unpublished`,action_target_id:c,action_target_type:e,status:"success",summary:`Unshared ${e} ${c} from shared cloud`}),A(c,e)}function G(a){return(0,f.getDb)().prepare("SELECT * FROM brand_publications WHERE org_id = ?").get(a)||null}function H(a){let b=(0,f.getDb)(),c=G(a.org_id),d=c?.id||(0,f.newId)("bpub");return b.prepare(`INSERT INTO brand_publications
       (id, org_id, source, content_hash, status, last_error,
        published_by, published_at, adopted_at, last_synced_at, unpublished_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
     ON CONFLICT(org_id) DO UPDATE SET
       source         = excluded.source,
       content_hash   = excluded.content_hash,
       status         = excluded.status,
       last_error     = excluded.last_error,
       published_by   = excluded.published_by,
       published_at   = COALESCE(excluded.published_at, brand_publications.published_at),
       adopted_at     = COALESCE(excluded.adopted_at, brand_publications.adopted_at),
       last_synced_at = excluded.last_synced_at,
       unpublished_at = excluded.unpublished_at`).run(d,a.org_id,a.source||"local",a.content_hash??null,a.status,a.last_error??null,a.published_by??null,a.published_at??null,a.adopted_at??null,a.last_synced_at??null,a.unpublished_at??null),d}function I(a){let b=G(a);return b?{published:"published"===b.status,status:b.status,source:b.source||"local",content_hash:b.content_hash||null,published_by:b.published_by||null,published_at:b.published_at||null,adopted_at:b.adopted_at||null,last_synced_at:b.last_synced_at||null,last_error:b.last_error||null}:{published:!1,status:"local",source:"local",content_hash:null,last_synced_at:null}}async function J(a={},b={}){let{session:c,profile:d}=a,g=a.org_id||c?.org_id;if(!g)throw Error("publishBrandProfile: org_id (or session.org_id) is required");if(!d||"object"!=typeof d)throw Error("publishBrandProfile: a profile is required");let{client:h}=u(a,b);if(!h)throw Error("publishBrandProfile: shared cloud is not configured. Owner instances need SUPABASE_URL + SUPABASE_SERVICE_ROLE_KEY; member instances need SUPABASE_URL + SUPABASE_ANON_KEY and a signed-in session.");let j=function(a,b={}){var c;if(!a||"object"!=typeof a)throw Error("mapBrandToCloud: a profile object is required");if(!b.org_id)throw Error("mapBrandToCloud: org_id is required");return{org_id:b.org_id,company_name:String(a.company_name||"Brand").slice(0,200),profile_json:a,logo_data_url:a.logo_data_url??null,content_hash:(c=JSON.stringify(a),(0,e.createHash)("sha256").update(String(c??""),"utf8").digest("hex")),published_by:b.published_by??null,updated_at:(0,f.nowIso)()}}(d,{org_id:g,published_by:a.published_by});var k=j;if(!k||"object"!=typeof k)throw Error("shared brand metadata must be an object");for(let a of["org_id","company_name","profile_json","content_hash"])if(null==k[a]||""===k[a])throw Error(`shared brand metadata missing required field: ${a}`);if("object"!=typeof k.profile_json)throw Error("shared brand metadata profile_json must be an object");if(!/^[0-9a-f]{64}$/.test(k.content_hash))throw Error("shared brand metadata content_hash must be a sha256 hex digest");try{await h.upsert("shared_brand_profiles",j,{onConflict:"org_id"})}catch(a){throw H({org_id:g,source:"local",content_hash:j.content_hash,status:"error",last_error:a.message,published_by:c?.user_id}),(0,i.appendComplianceAudit)({user_id:c?.user_id,org_id:g,action:"brand.shared.publish.error",action_target_id:g,action_target_type:"brand",status:"error",summary:"Failed to publish org brand to shared cloud",meta:{error:a.message}}),a}return H({org_id:g,source:"local",content_hash:j.content_hash,status:"published",published_by:c?.user_id,published_at:(0,f.nowIso)(),last_synced_at:(0,f.nowIso)()}),(0,i.appendComplianceAudit)({user_id:c?.user_id,org_id:g,action:"brand.shared.published",action_target_id:g,action_target_type:"brand",status:"success",summary:`Published org brand "${j.company_name}" to shared cloud`}),I(g)}async function K(a={},b={}){let{session:c}=a,d=a.org_id||c?.org_id;if(!d)throw Error("fetchOrgBrandProfile: org_id (or session.org_id) is required");let{client:e}=u(a,b);if(!e)throw Error("fetchOrgBrandProfile: shared cloud is not configured.");let f=await e.select("shared_brand_profiles",{filters:{org_id:d},limit:1}),g=Array.isArray(f)?f[0]:f;return g?{org_id:d,company_name:g.company_name||"Brand",profile:g.profile_json||null,logo_data_url:g.logo_data_url||null,content_hash:g.content_hash||null,updated_at:g.updated_at||null,published_by:g.published_by||null}:null}function L(a,{content_hash:b,user_id:c}={}){if(!a)throw Error("markBrandAdopted: orgId is required");return H({org_id:a,source:"org",content_hash:b??null,status:"adopted",published_by:c??null,adopted_at:(0,f.nowIso)(),last_synced_at:(0,f.nowIso)()}),(0,i.appendComplianceAudit)({user_id:c,org_id:a,action:"brand.shared.adopted",action_target_id:a,action_target_type:"brand",status:"success",summary:"Adopted org brand from shared cloud"}),I(a)}async function M(a={},b={}){let{session:c}=a,d=a.org_id||c?.org_id;if(!d)throw Error("unpublishBrandProfile: org_id (or session.org_id) is required");let{client:e}=u(a,b);if(!e)throw Error("unpublishBrandProfile: shared cloud is not configured.");return await e.delete("shared_brand_profiles",{filters:{org_id:d}}),H({org_id:d,source:"local",status:"unpublished",published_by:c?.user_id,unpublished_at:(0,f.nowIso)(),last_synced_at:(0,f.nowIso)()}),(0,i.appendComplianceAudit)({user_id:c?.user_id,org_id:d,action:"brand.shared.unpublished",action_target_id:d,action_target_type:"brand",status:"success",summary:"Stopped sharing org brand from shared cloud"}),I(d)}function N(a,b,c,d){let e=(0,f.getDb)();if(!e.prepare("SELECT id FROM organizations WHERE id = ?").get(a)){let b=(0,f.nowIso)();e.prepare(`INSERT INTO organizations (id, slug, name, plan, created_at, updated_at)
       VALUES (?, ?, ?, 'free', ?, ?) ON CONFLICT(id) DO NOTHING`).run(a,`org-${String(a).slice(-8)}`,d||String(a),b,b)}e.prepare("SELECT id FROM org_memberships WHERE org_id = ? AND user_id = ?").get(a,b)||e.prepare("INSERT INTO org_memberships (id, org_id, user_id, role, accepted_at) VALUES (?, ?, ?, ?, ?)").run((0,f.newId)("mem"),a,b,c,(0,f.nowIso)())}async function O(a,b={}){let c,d=a?.supabase_access_token;if(!d||!q(b))return[];try{c=await s(d,b).rpc("claim_email_invites")}catch{return[]}let e=Array.isArray(c)?c:[],f=[];for(let b of e){let c=b.granted_role||b.role;b.org_id&&(N(b.org_id,a.user_id,c),f.push({org_id:b.org_id,role:c}))}return f}async function P(a,b,c={}){let d=b?.supabase_access_token;if(!d)throw Error("redeemInviteViaCloud: no session access token");if(!q(c))throw Error("redeemInviteViaCloud: shared cloud (user) not configured");let e=await s(d,c).rpc("redeem_invite_token",{p_token:a}),f=Array.isArray(e)?e[0]:e;if(!f||!f.org_id)throw Object.assign(Error("invite is no longer valid (expired, revoked, or fully used)"),{code:"invite_invalid"});let g=f.granted_role||f.role;return N(f.org_id,b.user_id,g),{org_id:f.org_id,role:g}}async function Q(a,b={}){let c,d,e=a?.user_id;if(!e)return[];let f=a?.supabase_access_token||null,g=t({serviceReady:n(b),userReady:q(b),accessToken:f});if(!g)return[];try{c="admin"===g?r(b):s(f,b)}catch{return[]}try{d=await c.select("org_memberships",{filters:{user_id:e},select:"org_id,role",limit:100})}catch{return[]}if(!Array.isArray(d)||0===d.length)return[];let h=[...new Set(d.map(a=>a.org_id).filter(Boolean))],i=new Map;try{if(h.length){let a=await c.select("organizations",{filters:{id:`in.(${h.join(",")})`},select:"id,name",limit:1e3});for(let b of Array.isArray(a)?a:[])b.id&&i.set(b.id,b.name)}}catch{}let j=[];for(let a of d)a.org_id&&(N(a.org_id,e,a.role,i.get(a.org_id)),j.push({org_id:a.org_id,role:a.role}));return j}let _=Object.freeze(["user","team","org"]),aa=Object.freeze(["user","org"]),ab=Object.freeze(["read","write","admin"]),ac=Object.freeze({read:1,write:2,admin:3});function R(a,b,{writableOnly:c=!1}={}){let d=c?aa:_;if(!d.includes(a))throw Error(`${b}: invalid principal_type "${a}" (expected one of ${d.join("|")})`)}function S(a,b,c,d){if("org"===a)return b||c;if(!b)throw Error(`${d}: principal_id is required for principal_type "${a}"`);return b}function T(a,b,c){let d=y(a,b);if(!d||"published"!==d.status||!d.cloud_space_id)throw Error(`${c}: ${b} ${a} is not published to the shared cloud`);return d.cloud_space_id}async function U(a={},b={}){let c,{local_space_id:d,session:e,principal_type:g,permission:h="read",space_type:j="project"}=a;if(!d)throw Error("grantSpaceAccess: local_space_id is required");let k=a.org_id||e?.org_id;if(!k)throw Error("grantSpaceAccess: org_id (or session.org_id) is required");x(j,"grantSpaceAccess"),R(g,"grantSpaceAccess",{writableOnly:!0});if(!ab.includes(h))throw Error(`grantSpaceAccess: invalid permission "${h}" (expected one of ${ab.join("|")})`);let l=S(g,a.principal_id,k,"grantSpaceAccess");if(!n(b))throw Error("grantSpaceAccess: shared cloud is not configured.");let m=T(d,j,"grantSpaceAccess"),o=r(b);try{let a=await o.upsert("shared_space_acl",{shared_space_id:m,org_id:k,principal_type:g,principal_id:l,permission:h,created_by:e?.user_id??null,updated_at:(0,f.nowIso)()},{onConflict:"shared_space_id,principal_type,principal_id"});c=Array.isArray(a)?a[0]:a}catch(a){throw(0,i.appendComplianceAudit)({user_id:e?.user_id,org_id:k,action:`${j}.shared.acl.grant.error`,action_target_id:d,action_target_type:j,status:"error",summary:`Failed to grant ${h} on ${j} ${d} to ${g}:${l}`,meta:{principal_type:g,principal_id:l,permission:h,error:a.message}}),a}return(0,i.appendComplianceAudit)({user_id:e?.user_id,org_id:k,action:`${j}.shared.acl.granted`,action_target_id:d,action_target_type:j,status:"success",summary:`Granted ${h} on ${j} ${d} to ${g}:${l}`,meta:{principal_type:g,principal_id:l,permission:h,cloud_space_id:m}}),c}async function V(a={},b={}){let{local_space_id:c,session:d,principal_type:e,space_type:f="project"}=a;if(!c)throw Error("revokeSpaceAccess: local_space_id is required");let g=a.org_id||d?.org_id;if(!g)throw Error("revokeSpaceAccess: org_id (or session.org_id) is required");x(f,"revokeSpaceAccess"),R(e,"revokeSpaceAccess",{writableOnly:!0});let h=S(e,a.principal_id,g,"revokeSpaceAccess");if(!n(b))throw Error("revokeSpaceAccess: shared cloud is not configured.");let j=T(c,f,"revokeSpaceAccess"),k=r(b),l=await k.delete("shared_space_acl",{filters:{shared_space_id:j,principal_type:e,principal_id:h}});return(0,i.appendComplianceAudit)({user_id:d?.user_id,org_id:g,action:`${f}.shared.acl.revoked`,action_target_id:c,action_target_type:f,status:"success",summary:`Revoked ${f} ${c} grant from ${e}:${h}`,meta:{principal_type:e,principal_id:h,cloud_space_id:j}}),{revoked:Array.isArray(l)?l.length:0,principal_type:e,principal_id:h}}async function W(a={},b={}){let{local_space_id:c,session:d,space_type:e="project"}=a;if(!c)throw Error("listSpaceAccess: local_space_id is required");if(!(a.org_id||d?.org_id))throw Error("listSpaceAccess: org_id (or session.org_id) is required");x(e,"listSpaceAccess");let f=y(c,e);if(!f||"published"!==f.status||!f.cloud_space_id)return[];if(!n(b))throw Error("listSpaceAccess: shared cloud is not configured.");return r(b).select("shared_space_acl",{filters:{shared_space_id:f.cloud_space_id},select:"*",limit:1e3})}async function X(a={},b={}){let{local_space_id:c,user_id:d,space_type:e="project",session:f}=a;if(!c)throw Error("resolveSpacePermission: local_space_id is required");x(e,"resolveSpacePermission");let g=a.org_id||f?.org_id,h=y(c,e);if(!h||"published"!==h.status)return null;let i=await W({local_space_id:c,space_type:e,org_id:g},b);return function({visibility:a,grants:b=[],userId:c,orgId:d}={}){let e=null,f=a=>{a&&ac[a]&&(!e||ac[a]>ac[e])&&(e=a)};for(let e of("org"===a&&f("read"),b))e&&("user"===e.principal_type&&c&&e.principal_id===c?f(e.permission):"org"===e.principal_type&&(null==e.principal_id||e.principal_id===d)&&f(e.permission));return e}({visibility:h.visibility,grants:i,userId:d,orgId:g})}d()}catch(a){d(a)}})}};