@safetech/inheriti-client-sdk 1.17.28 → 1.17.29

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 +1 @@
1
- import{SDKContainer as vs}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as Zt,useEffect as st,createContext as Jt,useMemo as en}from"react";import{CoreProvider as tn,HttpClientFactory as nn,AuthModule as rn,AuthStateProvider as sn,AuthSessionRestorer as on,useClient as an}from"@safetech/inheriti-core-sdk";function G(r,e="local"){let t={local:"http://localhost:3000",development:"https://api-dev.inheriti.com",staging:"https://api-stg.inheriti.com",production:"https://api.inheriti.com"},n=t[e]??t.development;return r==""?n:`${n}/${r}`}import{toast as te}from"sonner";var it={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{te.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{te.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{te.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{te.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{te.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as cn,jsx as Q}from"react/jsx-runtime";var dn="inheriti_client_merging_process",Ke=Jt(null);function ot({children:r,clientId:e,options:t}){let n=t?.env??"development",i={key:e??"",options:{env:n}},s=Zt(nn.create({apiUrl:G("",n),errorHandlingStrategy:it}));st(()=>{s.current?.setApiUrl(G("",n))},[n]);let o=en(()=>({core:{httpClient:s.current},"protection-plan":{authTokens:{mergingProcessKey:dn}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return Q(Ke.Provider,{value:s.current,children:Q(sn,{children:Q(tn,{modules:{auth:rn},moduleConfigs:o,children:Q(on,{children:Q(ln,{client:i,children:r})})})})})}function ln({children:r,client:e}){let{connect:t,isConnected:n}=an();return st(()=>{!e?.key||n||t(e)},[e.key]),Q(cn,{children:r})}import{useContext as un,useCallback as pn}from"react";import{useClient as mn}from"@safetech/inheriti-core-sdk";function at(){let{connect:r,...e}=mn(),t=un(Ke),n=pn(async i=>(i?.options?.env&&t?.setApiUrl(G("",i.options.env)),r(i)),[r,t]);return{...e,connect:n}}function hn(){let r=typeof window<"u"?window.location.hostname:"",e=r.includes("localhost")?["local","development","staging","production"]:r.includes("elements-dev.inheriti.com")?["development","staging","production"]:["staging","production"],t=r.includes("localhost")?"local":r.includes("elements-dev.inheriti.com")?"development":"staging",n=r.includes("localhost")?"http://localhost:8081":r.includes("elements-dev.inheriti.com")?"https://app-dev.inheriti.com/":"https://app-stg.inheriti.com/",i=G("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:i}}import{decryptRSAOAEP as gn,generateRSAOAEPKeyPair as fn}from"@safetech/inheriti-core-sdk/crypto";var ce=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ue=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},pe=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},$=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await fn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),o=this.options.pollIntervalMs??2e3,a=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(S=>new Promise(b=>setTimeout(b,S))),c=!0,u=!1,y,P=()=>y??=(async()=>{let S=new AbortController,b,ke=new Promise((Ne,Ue)=>{b=setTimeout(()=>{S.abort(),Ue(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,S.signal),ke])}finally{clearTimeout(b)}})(),E,R=new Promise((S,b)=>{E=()=>{c&&P().catch(()=>{}),b(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",E,{once:!0})});R.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),u=!0;Date.now()<a;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let S=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),R]);if(S.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(S.status==="DELIVERED"&&S.sealedMasterKey){let b=(await gn(S.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(b))throw new Error("invalid_master_key_material");return b}if(S.status==="EXPIRED")throw new ue(s.sessionId);await yn(d,o,e)}throw new ce(s.sessionId)}catch(S){if(c&&(!u||e?.aborted))try{await P()}catch(b){if(e?.aborted)throw new pe(b)}throw S}finally{E&&e?.removeEventListener("abort",E)}}};async function yn(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function me(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||Le(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(In(e,r.applicationId)){let i=await r.source?.resolve();return i||Le(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Le(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function In(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Le(r,e,t,n,i){if((await e()).relayAvailable)return new $({...r.relay,api:vn(r.api,t)}).resolve(n,i)}function vn(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function B(r){return`${r.system}:${r.contextId}`}function ne(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var L=class extends Error{constructor(t){super(`master_key_required:${B(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Fe=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(B(e),t),this}async resolve(e){return this.sources.get(B(e))?.resolve()}};var re=class{keys=new Map;async store(e,t){let n=B(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(B(e))?.slice()}async remove(e){let t=B(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ie=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var se=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},m=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var oe=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var he=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Ge={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},lt=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],I=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},_=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function Z(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new _("plan_material_field_unknown");if(qe(r.dataShards,"data_shards_invalid"),qe(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&qe(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new _("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new _("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new _("material_operation_invalid")}function qe(r,e){if(!Array.isArray(r))throw new _(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new _(e);if(t.data!==void 0&&typeof t.data!="string")throw new _(e)}}function W(r){if(H(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!bn(r.idempotencyKey))throw new I("idempotency_key_invalid");if(!r.name?.trim())throw new I("plan_name_required");if(!r.assets.length)throw new I("assets_required");let e=new Set;for(let t of r.assets){if(H(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new I("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!he.includes(t.type))throw new I("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new I("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new I("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new I("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new I("asset_field_names_invalid");if(Pn(t.matchOrigins),!t.isBinary){let s=Ge[t.type];if(!s||i.some(o=>!s.includes(o)))throw new I("asset_field_name_not_canonical")}}if(!r.participants.length)throw new I("participants_required");for(let t of r.participants){if(H(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!ct(t.routingEmail))throw new I("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new I("participant_relationships_invalid")}Rn(r)}function Pn(r){if(r===void 0)return;if(!r.length)throw new I("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new I("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new I("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof I?n:new I("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new I("asset_match_origins_duplicated")}function Rn(r){let e=r.policy;if(e&&H(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new I("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){H(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new I("authentication_mode_invalid")}if(e.moderation){H(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new I("moderation_requires_moderators");let o=e.moderation.minimumApprovals;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>s.length))throw new I("minimum_approvals_invalid");let a=e.moderation.approvalMode;if(a!==void 0&&a!=="THRESHOLD"&&a!=="UNANIMOUS")throw new I("approval_mode_invalid")}let t=e.dms;if(!t)return;H(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!ct(t.subjectEmail))throw new I("dms_subject_invalid");if(!r.participants.some(s=>dt(s.routingEmail)===dt(t.subjectEmail)))throw new I("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new I("dms_countdown_invalid")}function bn(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function ct(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function dt(r){return r.normalize("NFC").trim().toLowerCase()}function H(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new I(t)}var fe=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},ye=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),W(e),ge(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,s={}){W(t);let o=await this.checkpoints.load(e);if(!o)throw new Ie("creation_checkpoint_missing");if(o.idempotencyKey!==t.idempotencyKey||o.declarationHash!==await ut(t))throw new Ie("creation_declaration_mismatch");let a=await this.api.getPlanCreation(e);if(s.onProgress?.(a.stage),a.outcome==="COMPLETED"||a.outcome==="CANCELED")return await this.checkpoints.remove(e),a;if(a.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!a.planId)return a;ge(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:a.planId,declaration:t,secrets:n,signal:s.signal});ge(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:a.planId,declaration:t,encrypted:d,signal:s.signal});ge(s.signal),Z(c);let u=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(u.stage),u.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,u),u}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await ut(e),serverStage:t.stage})}},Ie=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function ut(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ge(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function pt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new se(n.stage);return r.authorizeRevealAction(e,t)}function wn(r){let e=r?.status;return e===400||e===401||e===403}async function mt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!wn(s))throw s}return r.releaseRevealMaterial(e,t)}function yt(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?An(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Sn.has(r.stage)?"ENDED":"CONTINUING"}var Sn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function An(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var ve=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},w=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function be(r,e,t={},n=!1){if(t.signal?.aborted)throw v();let i=await r.getPlan(e),s=await r.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):ht(s.id);if(t.signal?.aborted)throw v();let o=()=>r.prepareReveal(e,t.signal,async u=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(u)});if(n||await o(),t.signal?.aborted)throw v();let a=t.idempotencyKey??crypto.randomUUID(),d;try{d=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(u){if(u?.code!=="merge_process_already_active")throw u;let y=await r.getActivePlanReveal(e);throw!y||y.planId!==e||y.mode!==(t.mode??"DIRECT")||y.protectedCopy!==void 0&&y.protectedCopy!==(t.protectedCopy??!1)?u:ht(y.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let c;try{if(t.signal?.aborted)throw v();let u=await xn(r,d,t);if(t.signal?.aborted||(n&&await o(),t.signal?.aborted)||(V(t,"RELEASING_MATERIAL",u),t.signal?.aborted))throw v();let y=await r.releaseRevealMaterial(u.id,u.materialVersion??"1");if(t.signal?.aborted||(u.mode==="GOVERNED"&&await r.markRevealSharesCollected(u.id),t.signal?.aborted))throw v();let P;try{P=await Tn(r,u,Dn(y),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(V(t,"RECONSTRUCTING",u),t.signal?.aborted))throw v();try{c=await r.reconstructPlanMaterial(P)}catch(R){throw t.signal?.aborted?v():(await r.reportRevealReconstruction(u.id,{status:"FAILED",errorCode:Cn(R)}),R)}if(t.signal?.aborted)throw v();let E=await r.reportRevealReconstruction(u.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(V(t,"OPEN",E),t.signal?.aborted))throw v();return new Ve(r,E,i,c,t.signal)}catch(u){throw c?.fill(0),await vt(r,d.id,t.signal?.aborted?"CANCELED":"ERROR"),u}}function ht(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var En=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function xn(r,e,t){let n=await F(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw v();if(t.onSession?.(n),t.onProgress?.({phase:yt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(En.has(n.stage))throw new Be(n.stage);await ze(t.pollIntervalMs??1500,t.signal),n=await F(()=>r.getReveal(e.id,t.signal),t.signal)}}var Be=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function V(r,e,t){r.onProgress?.({phase:e,session:t})}function ze(r,e){return e?.aborted?Promise.reject(v()):new Promise((t,n)=>{let i=setTimeout(o,Math.max(0,r)),s=()=>{clearTimeout(i),n(v())};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Ve=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let o=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(o,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new ve;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new w("asset_selector_invalid");if(!this.client.assetDecoder)throw new w("asset_decoder_required");let n=e.map(({selector:s,options:o={}})=>{let a=It(s),d=this.plan.assets.find(c=>(c.code??c.id)===a.asset);if(!d)throw new w("asset_not_found");if(d.isBinary)throw new w("action_not_allowed");if(!d.fieldNames.includes(a.field))throw new w("asset_field_not_found");return{selector:`${a.asset}.${a.field}`,assetCode:a.asset,asset:d,field:a.field,options:o}}),i=[];try{for(let o of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:o.options.idempotencyKey??crypto.randomUUID(),assetId:o.asset.id,fieldName:o.field,action:o.options.action??"VIEW_FIELD",...o.options.destination===void 0?{}:{destination:o.options.destination},...o.options.origin===void 0?{}:{origin:o.options.origin}}));let s=n.map(o=>{let a=this.client.assetDecoder(this.material).find(d=>d.id===o.asset.id||d.id===o.assetCode);if(!a)throw new w("asset_value_invalid");return{selector:o.selector,value:_n(a.data,o.field,o.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(o=>this.reportAction(o.id,"FAILED",gt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new w("asset_selector_invalid");if(!this.client.assetDecoder)throw new w("asset_decoder_required");let n=this.plan.assets.find(o=>o.code===e||o.id===e);if(!n)throw new w("asset_not_found");if(!n.isBinary)throw new w("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let o=this.client.assetDecoder(this.material).find(a=>a.id===n.id||a.id===n.code);if(!o||!(o.data instanceof Uint8Array))throw new w("asset_value_invalid");s=o.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(o){throw await this.reportAction(i.id,"FAILED",gt(o)),o}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=vt(this.client,this.session.id,e),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function It(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new w("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new w("asset_selector_invalid");return{asset:r.asset,field:r.field}}function _n(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new w("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new w("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?Ge[t]:void 0)?.includes(e))return"";throw new w("asset_value_invalid")}return n[e]}function gt(r){if(r instanceof w)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function Cn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Tn(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await F(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Pe;let c=await F(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(ft(c,i.id,e.planId),!c.shares.includes(i.data))throw new U;V(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:u}=await F(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw v();if(!u?.trim())throw new U;if(await r.claimRevealCustodianShare(e.id,c.id,u),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw v();return{...t,shares:t.shares.filter(y=>y!==i).concat(c.shares.map((y,P)=>({id:`${c.id}:${P}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:y})))}}if(d!=="SK_MOBILE")throw new U;if(n.signal?.aborted)throw v();return await r.distributeRevealCustodianShare(e.id),V(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await F(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),V(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ze(n.pollIntervalMs??1500,n.signal),s=await F(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Pe;if(!s.shareId||!s.deviceId)throw new U;V(n,"CONNECTING_SAFEKEY_PRO",e);let d=await F(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw v();if(ft(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new U;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw v();return{...t,shares:t.shares.concat(d.shares.map((c,u)=>({id:`${d.id}:${u}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new U;let o={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(o),V(n,"WAITING_FOR_CUSTODIAN",o),n.signal?.aborted)throw v();await r.requestRevealCustodianRelease(e.id);let a=await On(r,e,n);return Object.assign({},t,{shares:t.shares.concat(a.shares.map((d,c)=>({id:`${a.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function ft(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new U}async function F(r,e){if(e?.aborted)throw v();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(v()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw v();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function On(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Re;let s=await F(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Re;if(s&&s.status!=="PENDING"){let o=s;if(o.shares?.length)return o;throw new U}await ze(t.pollIntervalMs??1500,t.signal)}}var U=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Pe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Re=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Dn(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function vt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(o){if(!Mn(o))throw o}return}let n=new AbortController,i,s=new Promise((o,a)=>{i=setTimeout(()=>{n.abort(),a(new Error("reveal_cancellation_timed_out"))},5e3)});try{let o=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(o.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(o){if(o?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:o}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Mn(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function v(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var j=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new re,this.state=t.state??new ie,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Kn(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new m;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new m;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new m;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new m;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new m;return W(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new m;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new m;return Z(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new m;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new m;return new ye(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new L({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return Un(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new L(e);return await this.keyVault.store(e,Nn(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new m;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new m;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new oe;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new L({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=ne(e);if(!i)throw new L({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new m;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new m;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new m;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new m;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new m;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new m;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new m;return this.api.getReveal(e,t)}openReveal(e,t){return be(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new m;return mt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new m;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new m;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new m;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new m;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new m;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new m;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new m;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new m;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new m;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new m;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new m;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new m;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new m;return pt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new m;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new m;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new m;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new m;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new m;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new m;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),o=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),a=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(o,a,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new m;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new $e;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new L({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},$e=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function kn(r){return new j(r.coreSdk,{keyVault:r.keyVault,state:r.state,api:r.api,reconstructor:r.reconstructor,masterKeys:r.masterKeys,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:r.assetDecoder})}function Nn(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Un(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Kn(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return me({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return me({...e,organizationId:r.organizationId})}import{generateInheritiFileKey as He,sealInheritiFile as We,readInheritiFileHeader as Ln,openInheritiFile as Fn,InheritiFileInvalid as qn,MAX_INHERITI_FILE_BYTES as je}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as Pt,openInheritiFileKey as di}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Gn(r){let{reveal:e,api:t,signal:n}=r;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(n);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let o=r.openLimit??1;if(!Number.isSafeInteger(o)||o<1||o>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(r.selector,async a=>{if(!(a.bytes instanceof Uint8Array)||a.bytes.length<1||a.bytes.length>je-1024*1024)throw new Error("unsupported_protected_asset");let d=He(),c,u=!1,y=!1;try{n?.throwIfAborted();let P=await Pt(d,i.publicKey);u=!0;let E=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:a.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:P,openLimit:o},n);if(E.copyId!==r.copyId||E.status!=="PENDING")throw new Error("file_access_create_invalid");let R=await t.getFileAccess(r.copyId,n);for(;R.status==="PENDING";){if(n?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((b,ke)=>{let Ne=()=>{clearTimeout(Ue),ke(n?.reason)},Ue=setTimeout(()=>{n?.removeEventListener("abort",Ne),b()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",Ne,{once:!0})}),R=await t.getFileAccess(r.copyId,n)}if(R.status!=="READY"||R.origin!=="REVEAL"||R.copyId!==r.copyId||R.allowedUses!==o||!R.recipient||!R.deployment||R.expiresAt!==null&&(!Number.isFinite(Date.parse(R.expiresAt))||Date.parse(R.expiresAt)>s||Date.parse(R.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let S=await We({plaintext:a.bytes,fileKey:d,mimeType:a.mimeType,binding:R});S.fileKey.fill(0),c=S.fileBytes,n?.throwIfAborted(),await r.save({fileName:a.fileName,fileBytes:c}),y=!0}catch(P){if(u&&!y)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(E){throw new AggregateError([P,E],"protected_asset_export_and_cleanup_failed",{cause:P})}throw P}finally{d.fill(0),c?.fill(0)}})}var Bn=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Vn=["DIRECT","GOVERNED"],bt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],zn=["ACTIVE","REVOKED"],$n=["SK_MOBILE"],Hn=["ACTIVE","INACTIVE"],Wn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function wt(r){let e=A(r);return{items:M(e.items).map(Et),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function St(r){let e=A(r);return{total:k(e.total,"total"),items:M(e.items).map(t=>{let n=A(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:p(n.id,"log.id"),planId:p(n.planId,"log.planId"),tenantId:p(n.tenantId,"log.tenantId"),event:p(n.event,"log.event"),occurredOn:p(n.occurredOn,"log.occurredOn"),status:q(n.status),title:p(n.title,"log.title"),details:M(n.details).map(i=>{let s=A(i);return{label:p(s.label,"log.detail.label"),value:p(s.value,"log.detail.value")}})}})}}function At(r){let e=A(r);return{total:k(e.total,"total"),items:M(e.items).map(t=>{let n=A(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=p(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:p(n.id,"log.id"),memberId:p(n.memberId,"log.memberId"),source:i,event:p(n.event,"log.event"),occurredOn:p(n.occurredOn,"log.occurredOn"),status:q(n.status)}})}}function we(r){let e=A(r),t=Et(e),n=A(e.source),i=p(n.kind,"source.kind");return{...t,assets:M(e.assets).map(s=>{let o=A(s);return{id:p(o.id,"asset.id"),code:q(o.code),type:D(p(o.type,"asset.type"),he),name:p(o.name,"asset.name"),isBinary:Yn(o.isBinary,"asset.isBinary"),fieldNames:M(o.fieldNames).map(a=>p(a,"asset.fieldNames")),fileName:q(o.fileName),mimeType:q(o.mimeType),size:o.size===void 0||o.size===null?void 0:k(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:M(o.matchOrigins).map(a=>p(a,"asset.matchOrigins"))}}),participants:M(e.participants).map(s=>{let o=A(s);return{id:p(o.id,"participant.id"),displayName:p(o.displayName,"participant.displayName"),relationships:M(o.relationships).map(a=>D(p(a,"relationship"),bt)),lifecycle:D(p(o.lifecycle,"participant.lifecycle"),zn)}}),revealPolicy:(()=>{let s=A(e.revealPolicy);return{masterKeyRelease:D(p(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:D(p(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=A(e.dms);return{subjectEmail:p(s.subjectEmail,"dms.subjectEmail"),countdownDays:k(s.countdownDays,"dms.countdownDays"),countdownHours:k(s.countdownHours,"dms.countdownHours"),countdownMinutes:k(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:D(p(n.system,"source.system"),["INHERITI_BUSINESS"]),status:D(p(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ae(r){let e=A(r);return{operationId:p(e.operationId,"operationId"),stage:D(p(e.stage,"stage"),lt),outcome:D(p(e.outcome,"outcome"),Wn),planId:q(e.planId),lastErrorCode:q(e.lastErrorCode),participants:e.participants===void 0?void 0:M(e.participants).map(t=>{let n=A(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:M(n.relationships).map(i=>jn(p(i,"relationship"),bt))}})}}function Et(r){let e=A(r),t=A(e.assetSummary),n=A(e.governance),i=A(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:q(e.description),status:D(p(e.status,"status"),Bn),createdAt:p(e.createdAt,"createdAt"),configuredAt:q(e.configuredAt),assetSummary:{count:k(t.count,"assetSummary.count"),types:M(t.types).map(s=>D(p(s,"assetType"),he)),names:Rt(t.names).map(s=>p(s,"assetSummary.names"))},governance:{mode:D(p(n.mode,"governance.mode"),Vn),minimumApprovals:k(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:k(i.owners,"owners"),mergers:k(i.mergers,"mergers"),moderators:k(i.moderators,"moderators")},authentication:Rt(e.authentication).map(s=>{let o=A(s);return{id:D(p(o.id,"authentication.id"),$n),status:D(p(o.status,"authentication.status"),Hn)}})}}function D(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function jn(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function A(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Rt(r){return r==null?[]:M(r)}function M(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function p(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function q(r){return r==null?void 0:p(r,"optional")}function k(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Yn(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var J=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function xt(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function Xn(r,e){if(!e){if(r.length===0)throw new J("organization_required");if(r.length>1)throw new J("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new J("organization_access_denied");return e}function Qn(r){let e=f(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:l(e.parentId),sequence:g(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:g(e.participantRevision,1),createdAt:T(e.createdAt),..._t(e)}}function _t(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=f(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:l(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:T(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=f(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:g(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:T(i.revealedAt)}:{}}})}:{}}})}}function Ct(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Qn),total:g(e.total,0),limit:g(e.limit,1),offset:g(e.offset,0),unreadCount:g(e.unreadCount,0),readThroughSequence:g(e.readThroughSequence,0)}}function Tt(r){let e=f(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:l(e.parentId),sequence:g(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:g(e.participantRevision,1),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:g(e.senderDeviceVersion,1),canonicalManifest:l(e.canonicalManifest),signature:l(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=f(t);return{unitId:l(n.unitId),position:g(n.position,0),commitment:l(n.commitment),status:l(n.status)}})}}function Ye(r){let e=f(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:l(e.parentId),sequence:g(e.sequence,1),status:e.status}}function Ot(r){let e=f(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:l(e.conversationId),parentId:l(e.parentId),participantRevision:g(e.participantRevision,1),recipients:e.recipients.map(Xe)}}function Dt(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);return{parentId:l(n.parentId),sequence:g(n.sequence,1),senderMemberId:l(n.senderMemberId),senderDeviceId:l(n.senderDeviceId),participantRevision:g(n.participantRevision,1),createdAt:T(n.createdAt),..._t(n)}}),total:g(e.total,0),limit:g(e.limit,1),offset:g(e.offset,0),unreadCount:g(e.unreadCount,0),readThroughSequence:g(e.readThroughSequence,0)}}function Mt(r){return{readThroughSequence:g(f(r).readThroughSequence,0)}}function kt(r){return{clearedThroughSequence:g(f(r).clearedThroughSequence,0)}}function Nt(r){let e=f(r);return{parentId:l(e.parentId),sequence:g(e.sequence,1),senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:g(e.participantRevision,1),canonicalManifest:l(e.canonicalManifest),frame:l(e.frame),signature:l(e.signature),wrappedContentKey:l(e.wrappedContentKey),senderSigningPublicKey:l(e.senderSigningPublicKey)}}function f(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function l(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function T(r){let e=l(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function g(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Xe(r){let e=f(r);return{memberId:l(e.memberId),deviceId:l(e.deviceId),deviceVersion:g(e.deviceVersion,1),encryptionPublicKey:l(e.encryptionPublicKey),encryptionKeyFingerprint:l(e.encryptionKeyFingerprint),signingPublicKey:l(e.signingPublicKey),signingKeyFingerprint:l(e.signingKeyFingerprint)}}function ee(r){let e=f(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:l(e.id),tenantId:l(e.tenantId),memberId:l(e.memberId),version:e.version,encryptionPublicKey:l(e.encryptionPublicKey),encryptionKeyFingerprint:l(e.encryptionKeyFingerprint),signingPublicKey:l(e.signingPublicKey),signingKeyFingerprint:l(e.signingKeyFingerprint),status:e.status,createdAt:T(e.createdAt),updatedAt:T(e.updatedAt)}}function Se(r){let e=f(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:l(e.id),tenantId:l(e.tenantId),creatorMemberId:l(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(l),participantRevision:e.participantRevision,status:e.status,createdAt:T(e.createdAt),updatedAt:T(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=f(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:l(n.senderMemberId),createdAt:T(n.createdAt)}}return t}function Ut(r){let e=f(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(Se),total:e.total,limit:e.limit,offset:e.offset}}function Kt(r){let e=f(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Xe(t);return{memberId:n.memberId,name:l(f(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:g(e.limit,1),offset:g(e.offset,0),nextOffset:e.nextOffset===null?null:g(e.nextOffset,0)}}function Lt(r){let e=f(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:l(n.memberId),name:l(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:l(f(n.profilePicture).url)}}}}),limit:g(e.limit,1),offset:g(e.offset,0),nextOffset:e.nextOffset===null?null:g(e.nextOffset,0)}}function Ft(r){let e=f(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:l(e.conversationId),messageId:l(e.messageId),participantRevision:g(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Xe),shareLayers:e.shareLayers.map(t=>{let n=f(t),i=l(n.id),s=l(n.dataShareId),o=l(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:l(n.contractAddress),dataShareId:s,keyShareId:o};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:o};throw new Error("invalid_inbox_response")})}}function Ae(r){let e=f(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:l(e.messageId),status:e.status}}function qt(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:l(n.id),status:n.status,senderMemberId:l(n.senderMemberId),senderDeviceId:l(n.senderDeviceId),createdAt:T(n.createdAt),updatedAt:T(n.updatedAt),expiresAt:T(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let o=f(s);if(o.status!=="UNREAD"&&o.status!=="LEASED"&&o.status!=="CONSUMED"&&o.status!=="EXPIRED"&&o.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:l(o.memberId),status:o.status,...o.consumedAt!==void 0?{consumedAt:o.consumedAt===null?null:T(o.consumedAt)}:{}}})),i}),total:g(e.total,0),limit:g(e.limit,1),offset:g(e.offset,0)}}function Gt(r){let e=f(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:l(e.leaseId),leaseExpiresAt:T(e.leaseExpiresAt),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:g(e.senderDeviceVersion,1),canonicalManifest:l(e.canonicalManifest),signature:l(e.signature),tenantWrappedShareKey:l(e.tenantWrappedShareKey),wrappedContentKey:l(e.wrappedContentKey),shares:e.shares.map(t=>{let n=f(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:g(n.index,0),shareId:l(n.shareId),layerId:l(n.layerId),ciphertext:l(n.ciphertext)}})}}function Bt(r){let e=f(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:l(e.leaseId),leaseExpiresAt:T(e.leaseExpiresAt),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:g(e.senderDeviceVersion,1),canonicalManifest:l(e.canonicalManifest),signature:l(e.signature),tenantWrappedShareKey:l(e.tenantWrappedShareKey),wrappedContentKey:l(e.wrappedContentKey),shares:e.shares.map(t=>{let n=f(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:g(n.index,0),shareId:l(n.shareId),layerId:l(n.layerId)}})}}function Y(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function X(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var N=class extends Error{constructor(t,n,i,s){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},xe=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,n,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":n},i)}confirmFileAccessDelivery(e,t,n){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":n})}createInboxFileAccess(e,t,n,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",n,void 0,void 0,i)}createRevealFileAccess(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,n)}cancelRevealFileAccess(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",n)}cancelInboxFileAccess(e,t,n,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let n=t;if(typeof n.publicKey!="string"||!n.publicKey||typeof n.fingerprint!="string"||!n.fingerprint||n.status!=="ACTIVE"&&n.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:n.publicKey,fingerprint:n.fingerprint,status:n.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:ee(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:ee(n)}async registerInboxDevice(e){return ee(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return ee(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return ee(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Se(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Se(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Ut(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Kt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Lt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Ot(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Ae(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return Ye(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return Ye(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return Ct(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return Tt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return kt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return Dt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return Nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return Mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Ae(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let o=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,a=await this.requestBinary(o,"PUT",i,s),d=await Ee(a,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new N(a.status,Y(d),X(d),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return Ae(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return Bt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,o){let a=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${a}`,c=await this.requestBinary(d,"GET",void 0,o);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let u=Number(c.headers.get("content-length"));if(Number.isFinite(u)&&u>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let y=c.body.getReader(),P=[],E=0;try{for(;;){o?.throwIfAborted();let b=await y.read();if(b.done)break;if(E+=b.value.length,E>14*1024*1024)throw new Error("invalid_inbox_share_size");P.push(b.value)}}catch(b){throw await y.cancel().catch(()=>{}),b}let R=new Uint8Array(E),S=0;for(let b of P)R.set(b,S),S+=b.length;return R}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return Gt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(xt)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return wt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return we(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return St(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let n=new URLSearchParams;t.source&&n.set("source",t.source),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return At(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){W(e);let{idempotencyKey:t,...n}=e;return ae(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ae(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return Z(t),ae(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ae(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,s,o){this.requireBusinessSelection(e),o?.throwIfAborted();let a=await this.getBearerToken();o?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});a&&d.set("authorization",`Bearer ${a}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[E,R]of Object.entries(s??{}))d.set(E,R);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,u={method:t,headers:d,body:n?JSON.stringify(n):void 0};o&&(u.signal=o);let y=await this.transport(new URL(e,c),u);o?.throwIfAborted();let P=await Ee(y,o);if(o?.throwIfAborted(),!y.ok)throw new N(y.status,Y(P),X(P),y.headers.get("x-request-id")??void 0);if(!P.ok||P.result===void 0)throw new N(y.status,Y(P),X(P),y.headers.get("x-request-id")??void 0);return P.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId),n&&o.set("content-type","application/octet-stream");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,a),{method:t,headers:o,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await Ee(d,i);throw new N(d.status,Y(c),X(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});o&&a.set("authorization",`Bearer ${o}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId);for(let[y,P]of Object.entries(n??{}))a.set(y,P);t&&a.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:a,body:t?JSON.stringify(t):void 0,signal:s}),u=await Ee(c,s);if(s?.throwIfAborted(),!c.ok||!u.ok)throw new N(c.status,Y(u),X(u),c.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new N(400,"organization_selection_required")}};async function Ee(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}var Qe=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return we(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,s,o){o?.throwIfAborted();let a=await this.getAutomationBearerToken();if(o?.throwIfAborted(),!a)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${a}`,...s});n!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:o});o?.throwIfAborted();let u;try{u=await c.json()}catch{o?.throwIfAborted()}if(!c.ok||u&&u.ok===!1||i&&u?.result===void 0)throw new N(c.status,u&&Y(u),u&&X(u));return u?.result}};function Zn(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=ne(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new $({api:{startRelaySession:a=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,a),readRelaySession:(a,d)=>r.api.readMasterKeyRelaySession(a,d),cancelRelaySession:(a,d)=>r.api.cancelMasterKeyRelaySession(a,d)}}),o=new j(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(a,d,c)=>{if(a.system!==i.system||a.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,c)}}});return be(o,e,t,!0)}}}async function Vt(r,e){if(!e)throw new Error("master_key_required");let t=Jn(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=er(r),s=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,o);return tr(new Uint8Array(a))}function Jn(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function er(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function tr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Ze=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}};import{MergeProcessReconciliationLoop as nr}from"@safetech/inheriti-core-sdk/shared-configuration";var rr=new Set(["COMPLETED","ABORTED","EXPIRED"]),Je=class{constructor(e,t=new _e,n=new Ce,i=Math.random){this.api=e;this.loop=new nr(t,n,i)}subscriptions=new Map;loop;refreshConnection(){for(let e of this.subscriptions.values())e.wake()}subscribe(e,t){this.unsubscribe(e);let n,i,s=!1,o=this.loop.start(e,async()=>{let a=await this.api.getGovernedReveal(e),d=a.approvalProcess?.status??"",c=ir(a);n!==void 0&&c!==n&&await t.onProcessUpdated?.(),i!==void 0&&d!==i&&await t.onApprovalUpdated?.(),n=c,i=d;let u=rr.has(a.status);if(a.status==="EXPIRED"&&await t.onRevealWindowExpired?.(e),a.status==="ABORTED"&&await t.onForceAborted?.(e),u)return{transitionKey:c,shouldPoll:!1,terminal:!0};if(!s){let y=await this.api.getCustodianShare(e);"status"in y||(s=!0,await t.onCustodianShareReceived?.(e,y))}return{transitionKey:c,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,o)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function ir(r){return`${r.status}:${r.approvalProcess?.status??""}`}var _e=class{visibility(){return typeof document<"u"&&document.visibilityState==="hidden"?"hidden":"visible"}isOnline(){return typeof navigator>"u"||navigator.onLine!==!1}now(){return Date.now()}schedule(e,t){let n=setTimeout(e,t);return()=>clearTimeout(n)}onRecovery(e){return typeof globalThis.addEventListener!="function"?()=>{}:(globalThis.addEventListener("online",e),globalThis.addEventListener("visibilitychange",e),()=>{globalThis.removeEventListener("online",e),globalThis.removeEventListener("visibilitychange",e)})}},Ce=class{join(e,t){let n=!0;return{isOwner:()=>n,requestReconciliation:()=>{n&&t.onReconciliationRequested()},publishReconciled:()=>{},leave:()=>{n=!1}}}};var zt=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){de(e.signal),or(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return de(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){de(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(de(e.signal),!i.custodianPair)throw new _("custodian_share_required");let s=et(i.keyShards),o=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),a=await this.sealer.encryptShares(et(i.dataShards),o.symmetricKeyBase64),d=await this.sealer.encryptShares(et(i.backupShards),o.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,o.symmetricKeyBase64);return de(e.signal),{protectionProtocol:i.protocol,validatorShares:tt(o.encryptedShares),dataShards:tt(a.encryptedShares),backupShards:tt(d.encryptedShares),encryptedKey:o.encryptedKey,assetsMetadata:sr(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:nt(n.encryptedShares[0]),dataShard:nt(n.encryptedShares[1])}}};function et(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function tt(r){return r.map(nt)}function nt(r){return{id:r.id,data:r.encryptedData}}function sr(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new _("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function or(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new _("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new _("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new _("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new _("plan_secrets_declaration_mismatch")}}function de(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}function $t(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Te=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),$t(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return $t(new Uint8Array(t))}},Oe=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var le=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},O=class extends le{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},h=class extends le{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function De(r){if(r instanceof le)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Ht=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:x(n,"issuer"),authorizationEndpoint:x(n,"authorization_endpoint"),tokenEndpoint:x(n,"token_endpoint"),deviceAuthorizationEndpoint:K(n,"device_authorization_endpoint"),endSessionEndpoint:K(n,"end_session_endpoint"),revocationEndpoint:K(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:x(t,"device_code"),userCode:x(t,"user_code"),verificationUri:x(t,"verification_uri"),verificationUriComplete:K(t,"verification_uri_complete"),expiresInSeconds:Wt(t,"expires_in"),intervalSeconds:rt(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async revoke(e){let t=await this.http(new URL(e.endpoint),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,token:e.refreshToken,token_type_hint:"refresh_token"}),signal:e.signal});if(!t.ok)throw new h(`oauth_http_${t.status}`)}async exchangeBusinessSession(e){return this.businessSession(e.apiUrl,"exchange",{providerAccessToken:e.providerAccessToken})}async refreshBusinessSession(e){return this.businessSession(e.apiUrl,"refresh",{refreshToken:e.refreshToken})}async revokeBusinessSession(e){await this.businessRequest(e.apiUrl,"revoke",{refreshToken:e.refreshToken},e.signal)}async businessSession(e,t,n){let i=await this.businessRequest(e,t,n);return{accessToken:x(i,"accessToken"),refreshToken:x(i,"refreshToken"),accessExpiresAt:x(i,"accessExpiresAt"),sessionExpiresAt:x(i,"sessionExpiresAt"),familyId:x(i,"familyId"),environment:dr(i,"environment"),clientId:x(i,"clientId"),providerIssuer:x(i,"providerIssuer"),providerSubject:x(i,"providerSubject")}}async businessRequest(e,t,n,i){let s=e.endsWith("/")?e:`${e}/`,o=new URL(`operator-sessions/${t}`,s),a=await this.http(o,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"omit",signal:i,body:JSON.stringify(n)}),d={};try{d=await a.json()}catch{}if(!a.ok)throw new h(`business_http_${a.status}`);if(d.ok!==!0||!ar(d.result))throw new h("invalid_business_response");return d.result}async token(e,t){let n=await this.form(e,t);return{accessToken:x(n,"access_token"),refreshToken:K(n,"refresh_token"),idToken:K(n,"id_token"),tokenType:x(n,"token_type"),expiresInSeconds:Wt(n,"expires_in"),refreshExpiresInSeconds:rt(n,"refresh_expires_in"),scope:K(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let s=K(i,"error")??`oauth_http_${n.status}`;throw new h(s,K(i,"error_description")??s)}return i}};function ar(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function dr(r,e){let t=x(r,e);if(t!=="TEST"&&t!=="LIVE")throw new h("invalid_business_response");return t}function x(r,e){let t=K(r,e);if(!t)throw new h("invalid_oauth_response",`Missing ${e}`);return t}function K(r,e){return typeof r[e]=="string"?r[e]:void 0}function Wt(r,e){let t=rt(r,e);if(t===void 0)throw new h("invalid_oauth_response",`Missing ${e}`);return t}function rt(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var lr=600*1e3,Me=5,cr=5,jt=5e3,ur=new WeakMap,pr=new WeakMap;async function Xt(r,e,t){let n=r.get(e),i,s=new Promise(o=>{i=o});r.set(e,s),n&&await n;try{return await t()}finally{r.get(e)===s&&r.delete(e),i()}}function z(r,e){return Xt(ur,r,e)}var Yt=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new h("business_api_url_required");this.crypto=e.crypto??new Te,this.clock=e.clock??new Oe}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),o=await this.crypto.sha256UrlSafe(s),a=this.clock.now()+lr;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:a});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",o),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:a}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new h("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new h("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new h("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new h("state_mismatch");let o=i.searchParams.get("error");if(o)throw new h(o,i.searchParams.get("error_description")??o);let a=i.searchParams.get("code");if(!a)throw new h("authorization_code_missing");let d=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:a,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),u=await this.acceptTokens(c,n.nonce);return await z(this.options.sessions,()=>this.options.sessions.save(u)),u}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new h("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(Me,t.intervalSeconds??Me),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new h("device_transaction_missing");let i=n,s=await this.getDiscovery(),o=Math.max(Me,i.intervalSeconds??Me),a=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(a>=i.expiresAt);){await this.clock.sleep(Math.max(0,a-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await z(this.options.sessions,()=>this.options.sessions.save(c)),await this.options.transactions.remove(t),c}catch(d){let c=De(d);if(c==="authorization_pending"){a=this.clock.now()+o*1e3;continue}if(c==="slow_down"){o+=cr,a=this.clock.now()+o*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new h("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e){if(this.isSafeIdBusinessMode()&&!this.isValidSafeIdBusinessSession(e))throw await this.clearIfUnchanged(e),new O;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new O;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new O;return e.expiresAt>this.clock.now()?e.accessToken:(await this.refreshExpired(e)).accessToken}}refresh(){return this.refreshExpired()}refreshExpired(e){if(this.refreshFlight)return this.refreshFlight;let t=this.performRefresh(e).finally(()=>{this.refreshFlight===t&&(this.refreshFlight=void 0)});return this.refreshFlight=t,t}async clear(){let e;if(await z(this.options.sessions,async()=>{try{e=await this.options.sessions.load()}finally{await this.options.sessions.clear()}}),this.isSafeIdBusinessMode()&&e&&this.isValidSafeIdBusinessSession(e)&&e.refreshToken){let i=new AbortController,s;try{await Promise.race([(async()=>{let o=await this.getDiscovery();o.revocationEndpoint&&this.options.transport.revoke&&await this.options.transport.revoke({endpoint:o.revocationEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken,signal:i.signal})})(),new Promise((o,a)=>{s=setTimeout(()=>{i.abort(),this.discovery=void 0,a(new h("provider_revoke_timeout"))},jt)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,n;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{n=setTimeout(()=>{t.abort(),s(new h("business_revoke_timeout"))},jt)})])}finally{n&&clearTimeout(n)}}async performRefresh(e){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.performProviderRefresh(e);let t=await this.options.sessions.load();if(!t||!this.isValidBusinessSession(t))throw t&&await this.clearIfUnchanged(t),new O;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new O;let n;try{n=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=De(i);if(s==="business_http_409"){let o=await z(this.options.sessions,async()=>{let a=await this.options.sessions.load();if(a&&this.isValidBusinessSession(a)&&a.refreshToken!==t.refreshToken&&a.familyId===t.familyId&&a.principal.subject===t.principal.subject)return a;a&&this.sameCredential(a,t)&&await this.options.sessions.clear()});if(o)return o;throw new O}throw s==="business_http_401"?(await this.clearIfCurrent(t),new O):i}try{let i=this.businessSession(n,t.principal,t);if(i.refreshToken===t.refreshToken)throw new h("refresh_token_rotation_missing");return await z(this.options.sessions,async()=>{let s=await this.options.sessions.load();if(s&&this.isValidBusinessSession(s)&&s.familyId===t.familyId&&s.principal.subject===t.principal.subject&&s.refreshToken!==t.refreshToken)return s;if(!s||!this.sameCredential(s,t))throw new O;return await this.options.sessions.save(i),i})}catch(i){throw await this.clearIfCurrent(t),i}}sameCredential(e,t){return this.isValidBusinessSession(e)&&e.familyId===t.familyId&&e.refreshToken===t.refreshToken&&e.principal.subject===t.principal.subject}async clearIfUnchanged(e){await z(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&t.kind===e.kind&&t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.principal?.subject===e.principal?.subject&&await this.options.sessions.clear()})}async clearIfCurrent(e){await z(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&this.sameCredential(t,e)&&await this.options.sessions.clear()})}async performProviderRefresh(e){return e??=await this.options.sessions.load(),Xt(pr,this.options.sessions,async()=>{let t=await this.options.sessions.load();if(e&&t&&t.kind===e.kind&&t.refreshToken!==e.refreshToken&&t.expiresAt>this.clock.now()&&t.principal?.subject===e.principal?.subject&&t.principal?.sessionId===e.principal?.sessionId){if(this.isSafeIdBusinessMode()){if(this.isValidSafeIdBusinessSession(t))return t}else if(t.kind!=="business"&&t.kind!=="safeid-oidc-business")return t}return this.refreshProviderUnderLock()})}async refreshProviderUnderLock(){let e=await this.options.sessions.load();if(!e||(this.isSafeIdBusinessMode()?!this.isValidSafeIdBusinessSession(e):e.kind==="business"||e.kind==="safeid-oidc-business")||!e.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw e&&await this.clearIfUnchanged(e),new O;let t;try{let n=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:n.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(n){let i=De(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new O):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),n)}try{if(!t.refreshToken)throw new h("refresh_token_rotation_missing");let n=await this.acceptProviderTokens(t,void 0,e);return await z(this.options.sessions,async()=>{let i=await this.options.sessions.load();if(!i||i.kind!==e.kind||i.refreshToken!==e.refreshToken||i.accessToken!==e.accessToken)throw new O;return await this.options.sessions.save(n),n})}catch(n){throw await this.clearIfUnchanged(e),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(C(e.issuer)!==C(this.options.configuration.issuer))throw new h("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${C(t)}|${n}|${i}|${this.options.businessApiUrl?this.isSafeIdBusinessMode()?"safeid-oidc":"business":"provider"}|${this.options.configuration.audience}`}async acceptTokens(e,t){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.acceptProviderTokens(e,t);let n=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,n)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new h("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new h("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new h("token_subject_mismatch")}return n}async acceptProviderTokens(e,t,n){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new O;let s=this.clock.now(),o=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access")),a={accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&o?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:o,principal:i};return this.isSafeIdBusinessMode()?{kind:"safeid-oidc-business",accessToken:a.accessToken,refreshToken:a.refreshToken,idToken:a.idToken,tokenType:a.tokenType,expiresAt:a.expiresAt,refreshExpiresAt:a.refreshExpiresAt,offlineAccessGranted:a.offlineAccessGranted,principal:a.principal,businessApiUrl:this.options.businessApiUrl,audience:this.options.configuration.audience,clientId:this.options.configuration.clientId,issuer:C(this.options.configuration.issuer),environment:this.options.configuration.environment}:a}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}isSafeIdBusinessMode(){return this.options.businessAuthority==="safeid-oidc"}isValidSafeIdBusinessSession(e){let t=e,n=t.principal;return t.kind==="safeid-oidc-business"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&(t.refreshExpiresAt===void 0||Number.isFinite(t.refreshExpiresAt))&&typeof t.issuer=="string"&&typeof t.businessApiUrl=="string"&&typeof t.audience=="string"&&typeof t.clientId=="string"&&(t.environment==="TEST"||t.environment==="LIVE")&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&typeof n.authorizedParty=="string"&&(n.environment==="TEST"||n.environment==="LIVE")&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&C(t.issuer)===C(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment&&C(n.issuer)===C(this.options.configuration.issuer)&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)}businessSession(e,t,n){if(C(e.providerIssuer)!==C(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||n&&e.familyId!==n.familyId)throw new h("business_identity_mismatch");let i=Date.parse(e.accessExpiresAt),s=Date.parse(e.sessionExpiresAt);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=this.clock.now()||s<=this.clock.now()||i>s)throw new h("invalid_business_expiry");return{kind:"business",familyId:e.familyId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenType:"Bearer",expiresAt:i,sessionExpiresAt:s,principal:{issuer:t.issuer,audience:t.audience,authorizedParty:t.authorizedParty,environment:t.environment,subject:t.subject,sessionId:t.sessionId,tokenId:t.tokenId,scopes:t.scopes,nonce:t.nonce}}}isValidBusinessSession(e){let t=e,n=t.principal;return t.kind==="business"&&typeof t.familyId=="string"&&t.familyId.length>0&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&Number.isFinite(t.sessionExpiresAt)&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&C(n.issuer)===C(this.options.configuration.issuer)&&typeof n.subject=="string"&&n.subject.length>0&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(C(e.issuer)!==C(i.issuer))throw new h("issuer_mismatch");if(!s.includes(i.audience))throw new h("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new h("client_mismatch");if(e.environment!==i.environment)throw new h("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new h("required_claim_missing");if(n&&e.nonce!==t)throw new h("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(C(e.issuer)!==C(n.issuer))throw new h("issuer_mismatch");if(!i.includes(n.clientId))throw new h("client_mismatch");if(e.authorizedParty!==n.clientId)throw new h("client_mismatch");if(!e.subject||!e.sessionId)throw new h("required_claim_missing");if(e.nonce!==t)throw new h("nonce_mismatch")}};function C(r){return r.replace(/\/+$/u,"")}var Qt=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};export{J as BusinessOrganizationSelectionError,he as CANONICAL_PLAN_ASSET_TYPES,Ge as CANONICAL_STRUCTURED_ASSET_FIELDS,zt as CorePlanMaterialBuilder,m as ElementsApiPortRequired,N as ElementsApiRequestFailed,j as ElementsClient,Ie as GuidedCreateRecoveryError,ye as GuidedPlanCreator,_e as HostProcessRuntimeEnvironment,Qe as HttpAutomationRevealApiPort,xe as HttpElementsApiPort,Ht as HttpOperatorAuthTransport,ot as InheritiClientProvider,qn as InheritiFileInvalid,I as InvalidPlanDeclaration,_ as InvalidPlanMaterial,Ce as LocalProcessReconciliationOwnership,je as MAX_INHERITI_FILE_BYTES,pe as MasterKeyRelayCancellationFailed,ue as MasterKeyRelayExpired,ce as MasterKeyRelayTimedOut,L as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,re as MemoryKeyVault,ie as MemoryStatePort,h as OAuthProtocolError,Yt as OperatorAuthClient,le as OperatorAuthError,O as OperatorReauthenticationRequired,Qt as OperatorSessionController,lt as PLAN_CREATION_SERVER_STAGES,Ze as PlanMaterialReconstructionFailed,oe as PlanMaterialReconstructorRequired,Je as PollingSharedPlanEventListener,$ as RelayMasterKeySource,se as RevealActionsNotOpen,w as RevealFieldAccessError,ve as RevealHandleClosed,vs as SDKContainer,Fe as StaticMasterKeyResolver,Oe as SystemOAuthClock,Te as WebOAuthCrypto,Zn as createAutomationRevealClient,kn as createElementsClient,me as createMasterKeyResolver,Gn as exportProtectedRevealAsset,He as generateInheritiFileKey,hn as getAvailableEnvs,ne as masterKeyRefFor,B as masterKeyRefKey,De as oauthErrorCode,Fn as openInheritiFile,di as openInheritiFileKey,It as parseAssetFieldSelector,Ln as readInheritiFileHeader,yt as revealPhaseOf,We as sealInheritiFile,Pt as sealInheritiFileKey,Xn as selectBusinessOrganization,Vt as unwrapDekWithMasterKey,at as useClient,W as validatePlanCreationInput,Z as validatePlanCreationMaterial};
1
+ import{SDKContainer as ks}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as cn,useEffect as pt,createContext as un,useMemo as pn}from"react";import{CoreProvider as mn,HttpClientFactory as gn,AuthModule as hn,AuthStateProvider as fn,AuthSessionRestorer as yn,useClient as In}from"@safetech/inheriti-core-sdk";function V(r,e="local"){let t={local:"http://localhost:3000",development:"https://api-dev.inheriti.com",staging:"https://api-stg.inheriti.com",production:"https://api.inheriti.com"},n=t[e]??t.development;return r==""?n:`${n}/${r}`}import{toast as se}from"sonner";var ut={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{se.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{se.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{se.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{se.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{se.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as bn,jsx as te}from"react/jsx-runtime";var vn="inheriti_client_merging_process",Be=un(null);function mt({children:r,clientId:e,options:t}){let n=t?.env??"development",i={key:e??"",options:{env:n}},s=cn(gn.create({apiUrl:V("",n),errorHandlingStrategy:ut}));pt(()=>{s.current?.setApiUrl(V("",n))},[n]);let o=pn(()=>({core:{httpClient:s.current},"protection-plan":{authTokens:{mergingProcessKey:vn}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return te(Be.Provider,{value:s.current,children:te(fn,{children:te(mn,{modules:{auth:hn},moduleConfigs:o,children:te(yn,{children:te(Pn,{client:i,children:r})})})})})}function Pn({children:r,client:e}){let{connect:t,isConnected:n}=In();return pt(()=>{!e?.key||n||t(e)},[e.key]),te(bn,{children:r})}import{useContext as Rn,useCallback as wn}from"react";import{useClient as Sn}from"@safetech/inheriti-core-sdk";function gt(){let{connect:r,...e}=Sn(),t=Rn(Be),n=wn(async i=>(i?.options?.env&&t?.setApiUrl(V("",i.options.env)),r(i)),[r,t]);return{...e,connect:n}}function An(){let r=typeof window<"u"?window.location.hostname:"",e=r.includes("localhost")?["local","development","staging","production"]:r.includes("elements-dev.inheriti.com")?["development","staging","production"]:["staging","production"],t=r.includes("localhost")?"local":r.includes("elements-dev.inheriti.com")?"development":"staging",n=r.includes("localhost")?"http://localhost:8081":r.includes("elements-dev.inheriti.com")?"https://app-dev.inheriti.com/":"https://app-stg.inheriti.com/",i=V("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:i}}import{decryptRSAOAEP as En,generateRSAOAEPKeyPair as _n}from"@safetech/inheriti-core-sdk/crypto";var ge=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},he=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},fe=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},j=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await _n();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),o=this.options.pollIntervalMs??2e3,a=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(A=>new Promise(w=>setTimeout(w,A))),c=!0,u=!1,y,P=()=>y??=(async()=>{let A=new AbortController,w,ze=new Promise((Fe,Ge)=>{w=setTimeout(()=>{A.abort(),Ge(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,A.signal),ze])}finally{clearTimeout(w)}})(),_,b=new Promise((A,w)=>{_=()=>{c&&P().catch(()=>{}),w(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",_,{once:!0})});b.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),u=!0;Date.now()<a;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let A=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),b]);if(A.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(A.status==="DELIVERED"&&A.sealedMasterKey){let w=(await En(A.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(w))throw new Error("invalid_master_key_material");return w}if(A.status==="EXPIRED")throw new he(s.sessionId);await xn(d,o,e)}throw new ge(s.sessionId)}catch(A){if(c&&(!u||e?.aborted))try{await P()}catch(w){if(e?.aborted)throw new fe(w)}throw A}finally{_&&e?.removeEventListener("abort",_)}}};async function xn(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function ye(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||Ve(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(Cn(e,r.applicationId)){let i=await r.source?.resolve();return i||Ve(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Ve(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function Cn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Ve(r,e,t,n,i){if((await e()).relayAvailable)return new j({...r.relay,api:Tn(r.api,t)}).resolve(n,i)}function Tn(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function $(r){return`${r.system}:${r.contextId}`}function oe(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var F=class extends Error{constructor(t){super(`master_key_required:${$(t)}`);this.ref=t;this.name="MasterKeyRequired"}},$e=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set($(e),t),this}async resolve(e){return this.sources.get($(e))?.resolve()}};var ae=class{keys=new Map;async store(e,t){let n=$(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get($(e))?.slice()}async remove(e){let t=$(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var de=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var le=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},p=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var ce=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var Ie=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],We={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},ft=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],I=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},T=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function ne(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new T("plan_material_field_unknown");if(He(r.dataShards,"data_shards_invalid"),He(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&He(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new T("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new T("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new T("material_operation_invalid")}function He(r,e){if(!Array.isArray(r))throw new T(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new T(e);if(t.data!==void 0&&typeof t.data!="string")throw new T(e)}}function X(r){if(Y(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!kn(r.idempotencyKey))throw new I("idempotency_key_invalid");if(!r.name?.trim())throw new I("plan_name_required");if(!r.assets.length)throw new I("assets_required");let e=new Set;for(let t of r.assets){if(Y(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new I("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!Ie.includes(t.type))throw new I("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new I("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new I("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new I("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new I("asset_field_names_invalid");if(On(t.matchOrigins),!t.isBinary){let s=We[t.type];if(!s||i.some(o=>!s.includes(o)))throw new I("asset_field_name_not_canonical")}}if(!r.participants.length)throw new I("participants_required");for(let t of r.participants){if(Y(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!yt(t.routingEmail))throw new I("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new I("participant_relationships_invalid")}Mn(r)}function On(r){if(r===void 0)return;if(!r.length)throw new I("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new I("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new I("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof I?n:new I("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new I("asset_match_origins_duplicated")}function Mn(r){let e=r.policy;if(e&&Y(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new I("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){Y(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new I("authentication_mode_invalid")}if(e.moderation){Y(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new I("moderation_requires_moderators");let o=e.moderation.minimumApprovals;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>s.length))throw new I("minimum_approvals_invalid");let a=e.moderation.approvalMode;if(a!==void 0&&a!=="THRESHOLD"&&a!=="UNANIMOUS")throw new I("approval_mode_invalid")}let t=e.dms;if(!t)return;Y(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!yt(t.subjectEmail))throw new I("dms_subject_invalid");if(!r.participants.some(s=>ht(s.routingEmail)===ht(t.subjectEmail)))throw new I("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new I("dms_countdown_invalid")}function kn(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function yt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function ht(r){return r.normalize("NFC").trim().toLowerCase()}function Y(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new I(t)}var Pe=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},be=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),X(e),ve(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,s={}){X(t);let o=await this.checkpoints.load(e);if(!o)throw new Re("creation_checkpoint_missing");if(o.idempotencyKey!==t.idempotencyKey||o.declarationHash!==await It(t))throw new Re("creation_declaration_mismatch");let a=await this.api.getPlanCreation(e);if(s.onProgress?.(a.stage),a.outcome==="COMPLETED"||a.outcome==="CANCELED")return await this.checkpoints.remove(e),a;if(a.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!a.planId)return a;ve(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:a.planId,declaration:t,secrets:n,signal:s.signal});ve(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:a.planId,declaration:t,encrypted:d,signal:s.signal});ve(s.signal),ne(c);let u=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(u.stage),u.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,u),u}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await It(e),serverStage:t.stage})}},Re=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function It(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ve(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function vt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new le(n.stage);return r.authorizeRevealAction(e,t)}function Dn(r){let e=r?.status;return e===400||e===401||e===403}async function Pt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Dn(s))throw s}return r.releaseRevealMaterial(e,t)}function St(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?Un(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Nn.has(r.stage)?"ENDED":"CONTINUING"}var Nn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Un(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var we=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},S=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ee(r,e,t={},n=!1){if(t.signal?.aborted)throw v();let i=await r.getPlan(e),s=await r.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):bt(s.id);if(t.signal?.aborted)throw v();let o=()=>r.prepareReveal(e,t.signal,async u=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(u)});if(n||await o(),t.signal?.aborted)throw v();let a=t.idempotencyKey??crypto.randomUUID(),d;try{d=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(u){if(u?.code!=="merge_process_already_active")throw u;let y=await r.getActivePlanReveal(e);throw!y||y.planId!==e||y.mode!==(t.mode??"DIRECT")||y.protectedCopy!==void 0&&y.protectedCopy!==(t.protectedCopy??!1)?u:bt(y.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let c;try{if(t.signal?.aborted)throw v();let u=await Ln(r,d,t);if(t.signal?.aborted||(n&&await o(),t.signal?.aborted)||(H(t,"RELEASING_MATERIAL",u),t.signal?.aborted))throw v();let y=await r.releaseRevealMaterial(u.id,u.materialVersion??"1");if(t.signal?.aborted||(u.mode==="GOVERNED"&&await r.markRevealSharesCollected(u.id),t.signal?.aborted))throw v();let P;try{P=await Fn(r,u,Bn(y),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(H(t,"RECONSTRUCTING",u),t.signal?.aborted))throw v();try{c=await r.reconstructPlanMaterial(P)}catch(b){throw t.signal?.aborted?v():(await r.reportRevealReconstruction(u.id,{status:"FAILED",errorCode:zn(b)}),b)}if(t.signal?.aborted)throw v();let _=await r.reportRevealReconstruction(u.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(H(t,"OPEN",_),t.signal?.aborted))throw v();return new Ye(r,_,i,c,t.signal)}catch(u){throw c?.fill(0),await Et(r,d.id,t.signal?.aborted?"CANCELED":"ERROR"),u}}function bt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Kn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Ln(r,e,t){let n=await G(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw v();if(t.onSession?.(n),t.onProgress?.({phase:St(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Kn.has(n.stage))throw new je(n.stage);await Xe(t.pollIntervalMs??1500,t.signal),n=await G(()=>r.getReveal(e.id,t.signal),t.signal)}}var je=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function H(r,e,t){r.onProgress?.({phase:e,session:t})}function Xe(r,e){return e?.aborted?Promise.reject(v()):new Promise((t,n)=>{let i=setTimeout(o,Math.max(0,r)),s=()=>{clearTimeout(i),n(v())};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Ye=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let o=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(o,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new we;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new S("asset_selector_invalid");if(!this.client.assetDecoder)throw new S("asset_decoder_required");let n=e.map(({selector:s,options:o={}})=>{let a=At(s),d=this.plan.assets.find(c=>(c.code??c.id)===a.asset);if(!d)throw new S("asset_not_found");if(d.isBinary)throw new S("action_not_allowed");if(!d.fieldNames.includes(a.field))throw new S("asset_field_not_found");return{selector:`${a.asset}.${a.field}`,assetCode:a.asset,asset:d,field:a.field,options:o}}),i=[];try{for(let o of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:o.options.idempotencyKey??crypto.randomUUID(),assetId:o.asset.id,fieldName:o.field,action:o.options.action??"VIEW_FIELD",...o.options.destination===void 0?{}:{destination:o.options.destination},...o.options.origin===void 0?{}:{origin:o.options.origin}}));let s=n.map(o=>{let a=this.client.assetDecoder(this.material).find(d=>d.id===o.asset.id||d.id===o.assetCode);if(!a)throw new S("asset_value_invalid");return{selector:o.selector,value:qn(a.data,o.field,o.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(o=>this.reportAction(o.id,"FAILED",Rt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new S("asset_selector_invalid");if(!this.client.assetDecoder)throw new S("asset_decoder_required");let n=this.plan.assets.find(o=>o.code===e||o.id===e);if(!n)throw new S("asset_not_found");if(!n.isBinary)throw new S("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let o=this.client.assetDecoder(this.material).find(a=>a.id===n.id||a.id===n.code);if(!o||!(o.data instanceof Uint8Array))throw new S("asset_value_invalid");s=o.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(o){throw await this.reportAction(i.id,"FAILED",Rt(o)),o}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Et(this.client,this.session.id,e),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function At(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new S("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new S("asset_selector_invalid");return{asset:r.asset,field:r.field}}function qn(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new S("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new S("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?We[t]:void 0)?.includes(e))return"";throw new S("asset_value_invalid")}return n[e]}function Rt(r){if(r instanceof S)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function zn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Fn(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await G(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Se;let c=await G(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(wt(c,i.id,e.planId),!c.shares.includes(i.data))throw new q;H(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:u}=await G(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw v();if(!u?.trim())throw new q;if(await r.claimRevealCustodianShare(e.id,c.id,u),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw v();return{...t,shares:t.shares.filter(y=>y!==i).concat(c.shares.map((y,P)=>({id:`${c.id}:${P}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:y})))}}if(d!=="SK_MOBILE")throw new q;if(n.signal?.aborted)throw v();return await r.distributeRevealCustodianShare(e.id),H(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await G(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),H(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Xe(n.pollIntervalMs??1500,n.signal),s=await G(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Se;if(!s.shareId||!s.deviceId)throw new q;H(n,"CONNECTING_SAFEKEY_PRO",e);let d=await G(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw v();if(wt(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new q;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw v();return{...t,shares:t.shares.concat(d.shares.map((c,u)=>({id:`${d.id}:${u}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new q;let o={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(o),H(n,"WAITING_FOR_CUSTODIAN",o),n.signal?.aborted)throw v();await r.requestRevealCustodianRelease(e.id);let a=await Gn(r,e,n);return Object.assign({},t,{shares:t.shares.concat(a.shares.map((d,c)=>({id:`${a.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function wt(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new q}async function G(r,e){if(e?.aborted)throw v();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(v()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw v();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function Gn(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Ae;let s=await G(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Ae;if(s&&s.status!=="PENDING"){let o=s;if(o.shares?.length)return o;throw new q}await Xe(t.pollIntervalMs??1500,t.signal)}}var q=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Se=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ae=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Bn(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function Et(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(o){if(!Vn(o))throw o}return}let n=new AbortController,i,s=new Promise((o,a)=>{i=setTimeout(()=>{n.abort(),a(new Error("reveal_cancellation_timed_out"))},5e3)});try{let o=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(o.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(o){if(o?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:o}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Vn(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function v(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var Q=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new ae,this.state=t.state??new de,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??jn(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new p;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new p;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new p;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new p;return this.api.listMemberLogs(e,t)}listOrganizationMembers(e){if(!this.api)throw new p;return this.api.listOrganizationMembers(e)}listOrganizationAuditTrail(e){if(!this.api)throw new p;return this.api.listOrganizationAuditTrail(e)}getOrganizationInsights(e){if(!this.api)throw new p;return this.api.getOrganizationInsights(e)}getPlanResponsibilities(e){if(!this.api)throw new p;return this.api.getPlanResponsibilities(e)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return X(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new p;return ne(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new Pe){if(this.requireApplication(),!this.api)throw new p;return new be(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new F({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return Wn(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new F(e);return await this.keyVault.store(e,Hn(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new p;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new p;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new ce;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new F({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=oe(e);if(!i)throw new F({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new p;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new p;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new p;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new p;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new p;return this.api.getReveal(e,t)}openReveal(e,t){return Ee(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new p;return Pt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new p;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new p;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new p;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new p;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new p;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new p;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new p;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new p;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new p;return vt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new p;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new p;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new p;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new p;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new p;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new p;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),o=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),a=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(o,a,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new p;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new Qe;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new F({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Qe=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function $n(r){return new Q(r.coreSdk,{keyVault:r.keyVault,state:r.state,api:r.api,reconstructor:r.reconstructor,masterKeys:r.masterKeys,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:r.assetDecoder})}function Hn(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Wn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function jn(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return ye({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ye({...e,organizationId:r.organizationId})}import{generateInheritiFileKey as Ze,sealInheritiFile as Je,readInheritiFileHeader as Yn,openInheritiFile as Xn,InheritiFileInvalid as Qn,MAX_INHERITI_FILE_BYTES as et}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as _t,openInheritiFileKey as Pi}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Zn(r){let{reveal:e,api:t,signal:n}=r;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(n);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let o=r.openLimit??1;if(!Number.isSafeInteger(o)||o<1||o>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(r.selector,async a=>{if(!(a.bytes instanceof Uint8Array)||a.bytes.length<1||a.bytes.length>et-1024*1024)throw new Error("unsupported_protected_asset");let d=Ze(),c,u=!1,y=!1;try{n?.throwIfAborted();let P=await _t(d,i.publicKey);u=!0;let _=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:a.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:P,openLimit:o},n);if(_.copyId!==r.copyId||_.status!=="PENDING")throw new Error("file_access_create_invalid");let b=await t.getFileAccess(r.copyId,n);for(;b.status==="PENDING";){if(n?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((w,ze)=>{let Fe=()=>{clearTimeout(Ge),ze(n?.reason)},Ge=setTimeout(()=>{n?.removeEventListener("abort",Fe),w()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",Fe,{once:!0})}),b=await t.getFileAccess(r.copyId,n)}if(b.status!=="READY"||b.origin!=="REVEAL"||b.copyId!==r.copyId||b.allowedUses!==o||!b.recipient||!b.deployment||b.expiresAt!==null&&(!Number.isFinite(Date.parse(b.expiresAt))||Date.parse(b.expiresAt)>s||Date.parse(b.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let A=await Je({plaintext:a.bytes,fileKey:d,mimeType:a.mimeType,binding:b});A.fileKey.fill(0),c=A.fileBytes,n?.throwIfAborted(),await r.save({fileName:a.fileName,fileBytes:c}),y=!0}catch(P){if(u&&!y)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(_){throw new AggregateError([P,_],"protected_asset_export_and_cleanup_failed",{cause:P})}throw P}finally{d.fill(0),c?.fill(0)}})}var Jn=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],er=["DIRECT","GOVERNED"],Ct=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],tr=["ACTIVE","REVOKED"],nr=["SK_MOBILE"],rr=["ACTIVE","INACTIVE"],ir=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Tt(r){let e=E(r);return{items:N(e.items).map(kt),nextCursor:e.nextCursor===null?null:m(e.nextCursor,"nextCursor")}}function Ot(r){let e=E(r);return{total:L(e.total,"total"),items:N(e.items).map(t=>{let n=E(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:m(n.id,"log.id"),planId:m(n.planId,"log.planId"),tenantId:m(n.tenantId,"log.tenantId"),event:m(n.event,"log.event"),occurredOn:m(n.occurredOn,"log.occurredOn"),status:B(n.status),title:m(n.title,"log.title"),details:N(n.details).map(i=>{let s=E(i);return{label:m(s.label,"log.detail.label"),value:m(s.value,"log.detail.value")}})}})}}function Mt(r){let e=E(r);return{total:L(e.total,"total"),items:N(e.items).map(t=>{let n=E(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=m(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:m(n.id,"log.id"),memberId:m(n.memberId,"log.memberId"),source:i,event:m(n.event,"log.event"),occurredOn:m(n.occurredOn,"log.occurredOn"),status:B(n.status)}})}}function _e(r){let e=E(r),t=kt(e),n=E(e.source),i=m(n.kind,"source.kind");return{...t,assets:N(e.assets).map(s=>{let o=E(s);return{id:m(o.id,"asset.id"),code:B(o.code),type:D(m(o.type,"asset.type"),Ie),name:m(o.name,"asset.name"),isBinary:or(o.isBinary,"asset.isBinary"),fieldNames:N(o.fieldNames).map(a=>m(a,"asset.fieldNames")),fileName:B(o.fileName),mimeType:B(o.mimeType),size:o.size===void 0||o.size===null?void 0:L(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:N(o.matchOrigins).map(a=>m(a,"asset.matchOrigins"))}}),participants:N(e.participants).map(s=>{let o=E(s);return{id:m(o.id,"participant.id"),displayName:m(o.displayName,"participant.displayName"),relationships:N(o.relationships).map(a=>D(m(a,"relationship"),Ct)),lifecycle:D(m(o.lifecycle,"participant.lifecycle"),tr)}}),revealPolicy:(()=>{let s=E(e.revealPolicy);return{masterKeyRelease:D(m(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:D(m(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=E(e.dms);return{subjectEmail:m(s.subjectEmail,"dms.subjectEmail"),countdownDays:L(s.countdownDays,"dms.countdownDays"),countdownHours:L(s.countdownHours,"dms.countdownHours"),countdownMinutes:L(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:D(m(n.system,"source.system"),["INHERITI_BUSINESS"]),status:D(m(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ue(r){let e=E(r);return{operationId:m(e.operationId,"operationId"),stage:D(m(e.stage,"stage"),ft),outcome:D(m(e.outcome,"outcome"),ir),planId:B(e.planId),lastErrorCode:B(e.lastErrorCode),participants:e.participants===void 0?void 0:N(e.participants).map(t=>{let n=E(t);return{clientParticipantRef:m(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:m(n.planParticipantId,"planParticipantId"),relationships:N(n.relationships).map(i=>sr(m(i,"relationship"),Ct))}})}}function kt(r){let e=E(r),t=E(e.assetSummary),n=E(e.governance),i=E(e.participantSummary);return{id:m(e.id,"id"),name:m(e.name,"name"),description:B(e.description),status:D(m(e.status,"status"),Jn),createdAt:m(e.createdAt,"createdAt"),configuredAt:B(e.configuredAt),assetSummary:{count:L(t.count,"assetSummary.count"),types:N(t.types).map(s=>D(m(s,"assetType"),Ie)),names:xt(t.names).map(s=>m(s,"assetSummary.names"))},governance:{mode:D(m(n.mode,"governance.mode"),er),minimumApprovals:L(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:L(i.owners,"owners"),mergers:L(i.mergers,"mergers"),moderators:L(i.moderators,"moderators")},authentication:xt(e.authentication).map(s=>{let o=E(s);return{id:D(m(o.id,"authentication.id"),nr),status:D(m(o.status,"authentication.status"),rr)}})}}function D(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function sr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function E(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function xt(r){return r==null?[]:N(r)}function N(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function m(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function B(r){return r==null?void 0:m(r,"optional")}function L(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function or(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function U(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Z(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function R(r){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function tt(r){return r==null?void 0:R(r)}function x(r){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function ar(r){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function Dt(r){let e=U(r);return{total:x(e.total),items:Z(e.items).map(t=>{let n=U(t);return{id:R(n.id),displayName:R(n.displayName),role:R(n.role),status:R(n.status)}})}}function Nt(r){let e=U(r);return{total:x(e.total),shownCount:x(e.shownCount),totalCount:x(e.totalCount),nextCursor:e.nextCursor==null?null:R(e.nextCursor),hasMore:ar(e.hasMore),items:Z(e.items).map(t=>{let n=U(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:R(n.id),occurredOn:R(n.occurredOn),actorName:R(n.actorName),actorRole:R(n.actorRole),category:R(n.category),action:R(n.action),subject:R(n.subject),status:R(n.status),sourceEvent:R(n.sourceEvent),planId:tt(n.planId),planName:tt(n.planName),responsibleMemberName:tt(n.responsibleMemberName)}})}}function Ut(r){let e=U(r),t=U(e.stats),n=U(e.planAccessResults);return{stats:{totalPlans:x(t.totalPlans),plansCreatedThisMonth:x(t.plansCreatedThisMonth),activeMembers:x(t.activeMembers),totalSeats:t.totalSeats==null?null:x(t.totalSeats),accessRequests30d:x(t.accessRequests30d),accessRequestsPrevious30d:x(t.accessRequestsPrevious30d),pendingApprovals:x(t.pendingApprovals)},plansOverTime:Z(e.plansOverTime).map(i=>{let s=U(i);return{month:R(s.month),count:x(s.count)}}),planTypes:Z(e.planTypes).map(i=>{let s=U(i);return{type:R(s.type),count:x(s.count)}}),accessModerationActivity:Z(e.accessModerationActivity).map(i=>{let s=U(i);return{week:R(s.week),requests:x(s.requests),approvals:x(s.approvals)}}),planAccessResults:{success:x(n.success),aborted:x(n.aborted),expired:x(n.expired)}}}function Kt(r){let e=U(r);return{planId:R(e.planId),participants:Z(e.participants).map(t=>{let n=U(t);return{id:R(n.id),displayName:R(n.displayName),relationships:Z(n.relationships).map(i=>R(i)),lifecycle:R(n.lifecycle)}})}}function xe(r,e){if(Object.keys(r).some(t=>!e.includes(t)))throw new Error("organization_query_field_unknown")}var re=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Lt(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function dr(r,e){if(!e){if(r.length===0)throw new re("organization_required");if(r.length>1)throw new re("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new re("organization_access_denied");return e}function lr(r){let e=f(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:l(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:h(e.participantRevision,1),createdAt:M(e.createdAt),...qt(e)}}function qt(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=f(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:l(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:M(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=f(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:h(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:M(i.revealedAt)}:{}}})}:{}}})}}function zt(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(lr),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0),unreadCount:h(e.unreadCount,0),readThroughSequence:h(e.readThroughSequence,0)}}function Ft(r){let e=f(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:l(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:h(e.participantRevision,1),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:l(e.canonicalManifest),signature:l(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=f(t);return{unitId:l(n.unitId),position:h(n.position,0),commitment:l(n.commitment),status:l(n.status)}})}}function nt(r){let e=f(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:l(e.parentId),sequence:h(e.sequence,1),status:e.status}}function Gt(r){let e=f(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:l(e.conversationId),parentId:l(e.parentId),participantRevision:h(e.participantRevision,1),recipients:e.recipients.map(rt)}}function Bt(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);return{parentId:l(n.parentId),sequence:h(n.sequence,1),senderMemberId:l(n.senderMemberId),senderDeviceId:l(n.senderDeviceId),participantRevision:h(n.participantRevision,1),createdAt:M(n.createdAt),...qt(n)}}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0),unreadCount:h(e.unreadCount,0),readThroughSequence:h(e.readThroughSequence,0)}}function Vt(r){return{readThroughSequence:h(f(r).readThroughSequence,0)}}function $t(r){return{clearedThroughSequence:h(f(r).clearedThroughSequence,0)}}function Ht(r){let e=f(r);return{parentId:l(e.parentId),sequence:h(e.sequence,1),senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:h(e.participantRevision,1),canonicalManifest:l(e.canonicalManifest),frame:l(e.frame),signature:l(e.signature),wrappedContentKey:l(e.wrappedContentKey),senderSigningPublicKey:l(e.senderSigningPublicKey)}}function f(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function l(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function M(r){let e=l(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function h(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function rt(r){let e=f(r);return{memberId:l(e.memberId),deviceId:l(e.deviceId),deviceVersion:h(e.deviceVersion,1),encryptionPublicKey:l(e.encryptionPublicKey),encryptionKeyFingerprint:l(e.encryptionKeyFingerprint),signingPublicKey:l(e.signingPublicKey),signingKeyFingerprint:l(e.signingKeyFingerprint)}}function ie(r){let e=f(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:l(e.id),tenantId:l(e.tenantId),memberId:l(e.memberId),version:e.version,encryptionPublicKey:l(e.encryptionPublicKey),encryptionKeyFingerprint:l(e.encryptionKeyFingerprint),signingPublicKey:l(e.signingPublicKey),signingKeyFingerprint:l(e.signingKeyFingerprint),status:e.status,createdAt:M(e.createdAt),updatedAt:M(e.updatedAt)}}function Ce(r){let e=f(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:l(e.id),tenantId:l(e.tenantId),creatorMemberId:l(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(l),participantRevision:e.participantRevision,status:e.status,createdAt:M(e.createdAt),updatedAt:M(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=f(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:l(n.senderMemberId),createdAt:M(n.createdAt)}}return t}function Wt(r){let e=f(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(Ce),total:e.total,limit:e.limit,offset:e.offset}}function jt(r){let e=f(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=rt(t);return{memberId:n.memberId,name:l(f(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function Yt(r){let e=f(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:l(n.memberId),name:l(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:l(f(n.profilePicture).url)}}}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function Xt(r){let e=f(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:l(e.conversationId),messageId:l(e.messageId),participantRevision:h(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(rt),shareLayers:e.shareLayers.map(t=>{let n=f(t),i=l(n.id),s=l(n.dataShareId),o=l(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:l(n.contractAddress),dataShareId:s,keyShareId:o};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:o};throw new Error("invalid_inbox_response")})}}function Te(r){let e=f(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:l(e.messageId),status:e.status}}function Qt(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:l(n.id),status:n.status,senderMemberId:l(n.senderMemberId),senderDeviceId:l(n.senderDeviceId),createdAt:M(n.createdAt),updatedAt:M(n.updatedAt),expiresAt:M(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let o=f(s);if(o.status!=="UNREAD"&&o.status!=="LEASED"&&o.status!=="CONSUMED"&&o.status!=="EXPIRED"&&o.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:l(o.memberId),status:o.status,...o.consumedAt!==void 0?{consumedAt:o.consumedAt===null?null:M(o.consumedAt)}:{}}})),i}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0)}}function Zt(r){let e=f(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:l(e.leaseId),leaseExpiresAt:M(e.leaseExpiresAt),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:l(e.canonicalManifest),signature:l(e.signature),tenantWrappedShareKey:l(e.tenantWrappedShareKey),wrappedContentKey:l(e.wrappedContentKey),shares:e.shares.map(t=>{let n=f(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:h(n.index,0),shareId:l(n.shareId),layerId:l(n.layerId),ciphertext:l(n.ciphertext)}})}}function Jt(r){let e=f(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:l(e.leaseId),leaseExpiresAt:M(e.leaseExpiresAt),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:l(e.canonicalManifest),signature:l(e.signature),tenantWrappedShareKey:l(e.tenantWrappedShareKey),wrappedContentKey:l(e.wrappedContentKey),shares:e.shares.map(t=>{let n=f(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:h(n.index,0),shareId:l(n.shareId),layerId:l(n.layerId)}})}}function Oe(r){return typeof r=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(r)&&Number.isFinite(Date.parse(r))}function J(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function ee(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var K=class extends Error{constructor(t,n,i,s){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ke=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,n,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":n},i)}confirmFileAccessDelivery(e,t,n){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":n})}createInboxFileAccess(e,t,n,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",n,void 0,void 0,i)}createRevealFileAccess(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,n)}cancelRevealFileAccess(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",n)}cancelInboxFileAccess(e,t,n,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let n=t;if(typeof n.publicKey!="string"||!n.publicKey||typeof n.fingerprint!="string"||!n.fingerprint||n.status!=="ACTIVE"&&n.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:n.publicKey,fingerprint:n.fingerprint,status:n.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:ie(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:ie(n)}async registerInboxDevice(e){return ie(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return ie(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return ie(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Ce(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Ce(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Wt(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return jt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Yt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Xt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Gt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Te(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return zt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return Ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return $t(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return Bt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return Ht(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return Vt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Te(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let o=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,a=await this.requestBinary(o,"PUT",i,s),d=await Me(a,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new K(a.status,J(d),ee(d),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return Te(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return Jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,o){let a=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${a}`,c=await this.requestBinary(d,"GET",void 0,o);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let u=Number(c.headers.get("content-length"));if(Number.isFinite(u)&&u>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let y=c.body.getReader(),P=[],_=0;try{for(;;){o?.throwIfAborted();let w=await y.read();if(w.done)break;if(_+=w.value.length,_>14*1024*1024)throw new Error("invalid_inbox_share_size");P.push(w.value)}}catch(w){throw await y.cancel().catch(()=>{}),w}let b=new Uint8Array(_),A=0;for(let w of P)b.set(w,A),A+=w.length;return b}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return Qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return Zt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Lt)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return Tt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return _e(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Ot(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let n=new URLSearchParams;t.source&&n.set("source",t.source),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Mt(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listOrganizationMembers(e={}){if(this.requireOrganizationSelection(),xe(e,["limit","offset"]),e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>100))throw new Error("organization_query_limit_invalid");if(e.offset!==void 0&&(!Number.isSafeInteger(e.offset)||e.offset<0))throw new Error("organization_query_offset_invalid");let t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),Dt(await this.request(`v1/organization/members${t.size?`?${t}`:""}`,"GET"))}async listOrganizationAuditTrail(e){if(this.requireOrganizationSelection(),xe(e,["from","to","limit","cursor","category","memberId","responsibleMemberId"]),!Oe(e.from)||!Oe(e.to)||Date.parse(e.from)>Date.parse(e.to))throw new Error("organization_query_date_invalid");if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>500))throw new Error("organization_query_limit_invalid");if(e.cursor!==void 0&&!/^[1-9]\d*$/.test(e.cursor))throw new Error("organization_query_cursor_invalid");let t=new URLSearchParams({from:e.from,to:e.to});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor!==void 0&&t.set("cursor",e.cursor),e.category!==void 0&&t.set("category",e.category),e.memberId!==void 0&&t.set("memberId",e.memberId),e.responsibleMemberId!==void 0&&t.set("responsibleMemberId",e.responsibleMemberId),Nt(await this.request(`v1/organization/audit-trail?${t}`,"GET"))}async getOrganizationInsights(e={}){if(this.requireOrganizationSelection(),xe(e,["from","to"]),e.from===void 0!=(e.to===void 0)||e.from!==void 0&&(!Oe(e.from)||!Oe(e.to)||Date.parse(e.from)>Date.parse(e.to)))throw new Error("organization_query_date_invalid");let t=new URLSearchParams;return e.from!==void 0&&e.to!==void 0&&(t.set("from",e.from),t.set("to",e.to)),Ut(await this.request(`v1/organization/insights${t.size?`?${t}`:""}`,"GET"))}async getPlanResponsibilities(e){if(this.requireOrganizationSelection(),!e)throw new Error("plan_id_required");return Kt(await this.request(`v1/plans/${encodeURIComponent(e)}/responsibilities`,"GET"))}async startPlanCreation(e){X(e);let{idempotencyKey:t,...n}=e;return ue(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return ne(t),ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,s,o){this.requireBusinessSelection(e),o?.throwIfAborted();let a=await this.getBearerToken();o?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});a&&d.set("authorization",`Bearer ${a}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[_,b]of Object.entries(s??{}))d.set(_,b);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,u={method:t,headers:d,body:n?JSON.stringify(n):void 0};o&&(u.signal=o);let y=await this.transport(new URL(e,c),u);o?.throwIfAborted();let P=await Me(y,o);if(o?.throwIfAborted(),!y.ok)throw new K(y.status,J(P),ee(P),y.headers.get("x-request-id")??void 0);if(!P.ok||P.result===void 0)throw new K(y.status,J(P),ee(P),y.headers.get("x-request-id")??void 0);return P.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId),n&&o.set("content-type","application/octet-stream");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,a),{method:t,headers:o,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await Me(d,i);throw new K(d.status,J(c),ee(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});o&&a.set("authorization",`Bearer ${o}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId);for(let[y,P]of Object.entries(n??{}))a.set(y,P);t&&a.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:a,body:t?JSON.stringify(t):void 0,signal:s}),u=await Me(c,s);if(s?.throwIfAborted(),!c.ok||!u.ok)throw new K(c.status,J(u),ee(u),c.headers.get("x-request-id")??void 0)}requireOrganizationSelection(){if(!this.business?.organizationId)throw new K(400,"organization_selection_required")}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new K(400,"organization_selection_required")}};async function Me(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}var it=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return _e(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,s,o){o?.throwIfAborted();let a=await this.getAutomationBearerToken();if(o?.throwIfAborted(),!a)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${a}`,...s});n!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:o});o?.throwIfAborted();let u;try{u=await c.json()}catch{o?.throwIfAborted()}if(!c.ok||u&&u.ok===!1||i&&u?.result===void 0)throw new K(c.status,u&&J(u),u&&ee(u));return u?.result}};function cr(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=oe(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new j({api:{startRelaySession:a=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,a),readRelaySession:(a,d)=>r.api.readMasterKeyRelaySession(a,d),cancelRelaySession:(a,d)=>r.api.cancelMasterKeyRelaySession(a,d)}}),o=new Q(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(a,d,c)=>{if(a.system!==i.system||a.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,c)}}});return Ee(o,e,t,!0)}}}async function en(r,e){if(!e)throw new Error("master_key_required");let t=ur(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=pr(r),s=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,o);return mr(new Uint8Array(a))}function ur(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function pr(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function mr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var st=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}};import{MergeProcessReconciliationLoop as gr}from"@safetech/inheriti-core-sdk/shared-configuration";var hr=new Set(["COMPLETED","ABORTED","EXPIRED"]),ot=class{constructor(e,t=new De,n=new Ne,i=Math.random){this.api=e;this.loop=new gr(t,n,i)}subscriptions=new Map;loop;refreshConnection(){for(let e of this.subscriptions.values())e.wake()}subscribe(e,t){this.unsubscribe(e);let n,i,s=!1,o=this.loop.start(e,async()=>{let a=await this.api.getGovernedReveal(e),d=a.approvalProcess?.status??"",c=fr(a);n!==void 0&&c!==n&&await t.onProcessUpdated?.(),i!==void 0&&d!==i&&await t.onApprovalUpdated?.(),n=c,i=d;let u=hr.has(a.status);if(a.status==="EXPIRED"&&await t.onRevealWindowExpired?.(e),a.status==="ABORTED"&&await t.onForceAborted?.(e),u)return{transitionKey:c,shouldPoll:!1,terminal:!0};if(!s){let y=await this.api.getCustodianShare(e);"status"in y||(s=!0,await t.onCustodianShareReceived?.(e,y))}return{transitionKey:c,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,o)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function fr(r){return`${r.status}:${r.approvalProcess?.status??""}`}var De=class{visibility(){return typeof document<"u"&&document.visibilityState==="hidden"?"hidden":"visible"}isOnline(){return typeof navigator>"u"||navigator.onLine!==!1}now(){return Date.now()}schedule(e,t){let n=setTimeout(e,t);return()=>clearTimeout(n)}onRecovery(e){return typeof globalThis.addEventListener!="function"?()=>{}:(globalThis.addEventListener("online",e),globalThis.addEventListener("visibilitychange",e),()=>{globalThis.removeEventListener("online",e),globalThis.removeEventListener("visibilitychange",e)})}},Ne=class{join(e,t){let n=!0;return{isOwner:()=>n,requestReconciliation:()=>{n&&t.onReconciliationRequested()},publishReconciled:()=>{},leave:()=>{n=!1}}}};var tn=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){pe(e.signal),Ir(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return pe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){pe(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(pe(e.signal),!i.custodianPair)throw new T("custodian_share_required");let s=at(i.keyShards),o=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),a=await this.sealer.encryptShares(at(i.dataShards),o.symmetricKeyBase64),d=await this.sealer.encryptShares(at(i.backupShards),o.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,o.symmetricKeyBase64);return pe(e.signal),{protectionProtocol:i.protocol,validatorShares:dt(o.encryptedShares),dataShards:dt(a.encryptedShares),backupShards:dt(d.encryptedShares),encryptedKey:o.encryptedKey,assetsMetadata:yr(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:lt(n.encryptedShares[0]),dataShard:lt(n.encryptedShares[1])}}};function at(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function dt(r){return r.map(lt)}function lt(r){return{id:r.id,data:r.encryptedData}}function yr(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new T("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function Ir(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new T("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new T("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new T("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new T("plan_secrets_declaration_mismatch")}}function pe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}function nn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Ue=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),nn(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return nn(new Uint8Array(t))}},Ke=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var me=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},k=class extends me{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},g=class extends me{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Le(r){if(r instanceof me)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var rn=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:C(n,"issuer"),authorizationEndpoint:C(n,"authorization_endpoint"),tokenEndpoint:C(n,"token_endpoint"),deviceAuthorizationEndpoint:z(n,"device_authorization_endpoint"),endSessionEndpoint:z(n,"end_session_endpoint"),revocationEndpoint:z(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:C(t,"device_code"),userCode:C(t,"user_code"),verificationUri:C(t,"verification_uri"),verificationUriComplete:z(t,"verification_uri_complete"),expiresInSeconds:sn(t,"expires_in"),intervalSeconds:ct(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async revoke(e){let t=await this.http(new URL(e.endpoint),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,token:e.refreshToken,token_type_hint:"refresh_token"}),signal:e.signal});if(!t.ok)throw new g(`oauth_http_${t.status}`)}async exchangeBusinessSession(e){return this.businessSession(e.apiUrl,"exchange",{providerAccessToken:e.providerAccessToken})}async refreshBusinessSession(e){return this.businessSession(e.apiUrl,"refresh",{refreshToken:e.refreshToken})}async revokeBusinessSession(e){await this.businessRequest(e.apiUrl,"revoke",{refreshToken:e.refreshToken},e.signal)}async businessSession(e,t,n){let i=await this.businessRequest(e,t,n);return{accessToken:C(i,"accessToken"),refreshToken:C(i,"refreshToken"),accessExpiresAt:C(i,"accessExpiresAt"),sessionExpiresAt:C(i,"sessionExpiresAt"),familyId:C(i,"familyId"),environment:Pr(i,"environment"),clientId:C(i,"clientId"),providerIssuer:C(i,"providerIssuer"),providerSubject:C(i,"providerSubject")}}async businessRequest(e,t,n,i){let s=e.endsWith("/")?e:`${e}/`,o=new URL(`operator-sessions/${t}`,s),a=await this.http(o,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"omit",signal:i,body:JSON.stringify(n)}),d={};try{d=await a.json()}catch{}if(!a.ok)throw new g(`business_http_${a.status}`);if(d.ok!==!0||!vr(d.result))throw new g("invalid_business_response");return d.result}async token(e,t){let n=await this.form(e,t);return{accessToken:C(n,"access_token"),refreshToken:z(n,"refresh_token"),idToken:z(n,"id_token"),tokenType:C(n,"token_type"),expiresInSeconds:sn(n,"expires_in"),refreshExpiresInSeconds:ct(n,"refresh_expires_in"),scope:z(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let s=z(i,"error")??`oauth_http_${n.status}`;throw new g(s,z(i,"error_description")??s)}return i}};function vr(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Pr(r,e){let t=C(r,e);if(t!=="TEST"&&t!=="LIVE")throw new g("invalid_business_response");return t}function C(r,e){let t=z(r,e);if(!t)throw new g("invalid_oauth_response",`Missing ${e}`);return t}function z(r,e){return typeof r[e]=="string"?r[e]:void 0}function sn(r,e){let t=ct(r,e);if(t===void 0)throw new g("invalid_oauth_response",`Missing ${e}`);return t}function ct(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var br=600*1e3,qe=5,Rr=5,on=5e3,wr=new WeakMap,Sr=new WeakMap;async function dn(r,e,t){let n=r.get(e),i,s=new Promise(o=>{i=o});r.set(e,s),n&&await n;try{return await t()}finally{r.get(e)===s&&r.delete(e),i()}}function W(r,e){return dn(wr,r,e)}var an=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new g("business_api_url_required");this.crypto=e.crypto??new Ue,this.clock=e.clock??new Ke}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),o=await this.crypto.sha256UrlSafe(s),a=this.clock.now()+br;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:a});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",o),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:a}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new g("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new g("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new g("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new g("state_mismatch");let o=i.searchParams.get("error");if(o)throw new g(o,i.searchParams.get("error_description")??o);let a=i.searchParams.get("code");if(!a)throw new g("authorization_code_missing");let d=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:a,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),u=await this.acceptTokens(c,n.nonce);return await W(this.options.sessions,()=>this.options.sessions.save(u)),u}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new g("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(qe,t.intervalSeconds??qe),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new g("device_transaction_missing");let i=n,s=await this.getDiscovery(),o=Math.max(qe,i.intervalSeconds??qe),a=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(a>=i.expiresAt);){await this.clock.sleep(Math.max(0,a-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await W(this.options.sessions,()=>this.options.sessions.save(c)),await this.options.transactions.remove(t),c}catch(d){let c=Le(d);if(c==="authorization_pending"){a=this.clock.now()+o*1e3;continue}if(c==="slow_down"){o+=Rr,a=this.clock.now()+o*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new g("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e){if(this.isSafeIdBusinessMode()&&!this.isValidSafeIdBusinessSession(e))throw await this.clearIfUnchanged(e),new k;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new k;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new k;return e.expiresAt>this.clock.now()?e.accessToken:(await this.refreshExpired(e)).accessToken}}refresh(){return this.refreshExpired()}refreshExpired(e){if(this.refreshFlight)return this.refreshFlight;let t=this.performRefresh(e).finally(()=>{this.refreshFlight===t&&(this.refreshFlight=void 0)});return this.refreshFlight=t,t}async clear(){let e;if(await W(this.options.sessions,async()=>{try{e=await this.options.sessions.load()}finally{await this.options.sessions.clear()}}),this.isSafeIdBusinessMode()&&e&&this.isValidSafeIdBusinessSession(e)&&e.refreshToken){let i=new AbortController,s;try{await Promise.race([(async()=>{let o=await this.getDiscovery();o.revocationEndpoint&&this.options.transport.revoke&&await this.options.transport.revoke({endpoint:o.revocationEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken,signal:i.signal})})(),new Promise((o,a)=>{s=setTimeout(()=>{i.abort(),this.discovery=void 0,a(new g("provider_revoke_timeout"))},on)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,n;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{n=setTimeout(()=>{t.abort(),s(new g("business_revoke_timeout"))},on)})])}finally{n&&clearTimeout(n)}}async performRefresh(e){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.performProviderRefresh(e);let t=await this.options.sessions.load();if(!t||!this.isValidBusinessSession(t))throw t&&await this.clearIfUnchanged(t),new k;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new k;let n;try{n=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=Le(i);if(s==="business_http_409"){let o=await W(this.options.sessions,async()=>{let a=await this.options.sessions.load();if(a&&this.isValidBusinessSession(a)&&a.refreshToken!==t.refreshToken&&a.familyId===t.familyId&&a.principal.subject===t.principal.subject)return a;a&&this.sameCredential(a,t)&&await this.options.sessions.clear()});if(o)return o;throw new k}throw s==="business_http_401"?(await this.clearIfCurrent(t),new k):i}try{let i=this.businessSession(n,t.principal,t);if(i.refreshToken===t.refreshToken)throw new g("refresh_token_rotation_missing");return await W(this.options.sessions,async()=>{let s=await this.options.sessions.load();if(s&&this.isValidBusinessSession(s)&&s.familyId===t.familyId&&s.principal.subject===t.principal.subject&&s.refreshToken!==t.refreshToken)return s;if(!s||!this.sameCredential(s,t))throw new k;return await this.options.sessions.save(i),i})}catch(i){throw await this.clearIfCurrent(t),i}}sameCredential(e,t){return this.isValidBusinessSession(e)&&e.familyId===t.familyId&&e.refreshToken===t.refreshToken&&e.principal.subject===t.principal.subject}async clearIfUnchanged(e){await W(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&t.kind===e.kind&&t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.principal?.subject===e.principal?.subject&&await this.options.sessions.clear()})}async clearIfCurrent(e){await W(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&this.sameCredential(t,e)&&await this.options.sessions.clear()})}async performProviderRefresh(e){return e??=await this.options.sessions.load(),dn(Sr,this.options.sessions,async()=>{let t=await this.options.sessions.load();if(e&&t&&t.kind===e.kind&&t.refreshToken!==e.refreshToken&&t.expiresAt>this.clock.now()&&t.principal?.subject===e.principal?.subject&&t.principal?.sessionId===e.principal?.sessionId){if(this.isSafeIdBusinessMode()){if(this.isValidSafeIdBusinessSession(t))return t}else if(t.kind!=="business"&&t.kind!=="safeid-oidc-business")return t}return this.refreshProviderUnderLock()})}async refreshProviderUnderLock(){let e=await this.options.sessions.load();if(!e||(this.isSafeIdBusinessMode()?!this.isValidSafeIdBusinessSession(e):e.kind==="business"||e.kind==="safeid-oidc-business")||!e.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw e&&await this.clearIfUnchanged(e),new k;let t;try{let n=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:n.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(n){let i=Le(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new k):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),n)}try{if(!t.refreshToken)throw new g("refresh_token_rotation_missing");let n=await this.acceptProviderTokens(t,void 0,e);return await W(this.options.sessions,async()=>{let i=await this.options.sessions.load();if(!i||i.kind!==e.kind||i.refreshToken!==e.refreshToken||i.accessToken!==e.accessToken)throw new k;return await this.options.sessions.save(n),n})}catch(n){throw await this.clearIfUnchanged(e),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(O(e.issuer)!==O(this.options.configuration.issuer))throw new g("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${O(t)}|${n}|${i}|${this.options.businessApiUrl?this.isSafeIdBusinessMode()?"safeid-oidc":"business":"provider"}|${this.options.configuration.audience}`}async acceptTokens(e,t){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.acceptProviderTokens(e,t);let n=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,n)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new g("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new g("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new g("token_subject_mismatch")}return n}async acceptProviderTokens(e,t,n){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new k;let s=this.clock.now(),o=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access")),a={accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&o?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:o,principal:i};return this.isSafeIdBusinessMode()?{kind:"safeid-oidc-business",accessToken:a.accessToken,refreshToken:a.refreshToken,idToken:a.idToken,tokenType:a.tokenType,expiresAt:a.expiresAt,refreshExpiresAt:a.refreshExpiresAt,offlineAccessGranted:a.offlineAccessGranted,principal:a.principal,businessApiUrl:this.options.businessApiUrl,audience:this.options.configuration.audience,clientId:this.options.configuration.clientId,issuer:O(this.options.configuration.issuer),environment:this.options.configuration.environment}:a}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}isSafeIdBusinessMode(){return this.options.businessAuthority==="safeid-oidc"}isValidSafeIdBusinessSession(e){let t=e,n=t.principal;return t.kind==="safeid-oidc-business"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&(t.refreshExpiresAt===void 0||Number.isFinite(t.refreshExpiresAt))&&typeof t.issuer=="string"&&typeof t.businessApiUrl=="string"&&typeof t.audience=="string"&&typeof t.clientId=="string"&&(t.environment==="TEST"||t.environment==="LIVE")&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&typeof n.authorizedParty=="string"&&(n.environment==="TEST"||n.environment==="LIVE")&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&O(t.issuer)===O(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment&&O(n.issuer)===O(this.options.configuration.issuer)&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)}businessSession(e,t,n){if(O(e.providerIssuer)!==O(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||n&&e.familyId!==n.familyId)throw new g("business_identity_mismatch");let i=Date.parse(e.accessExpiresAt),s=Date.parse(e.sessionExpiresAt);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=this.clock.now()||s<=this.clock.now()||i>s)throw new g("invalid_business_expiry");return{kind:"business",familyId:e.familyId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenType:"Bearer",expiresAt:i,sessionExpiresAt:s,principal:{issuer:t.issuer,audience:t.audience,authorizedParty:t.authorizedParty,environment:t.environment,subject:t.subject,sessionId:t.sessionId,tokenId:t.tokenId,scopes:t.scopes,nonce:t.nonce}}}isValidBusinessSession(e){let t=e,n=t.principal;return t.kind==="business"&&typeof t.familyId=="string"&&t.familyId.length>0&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&Number.isFinite(t.sessionExpiresAt)&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&O(n.issuer)===O(this.options.configuration.issuer)&&typeof n.subject=="string"&&n.subject.length>0&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(O(e.issuer)!==O(i.issuer))throw new g("issuer_mismatch");if(!s.includes(i.audience))throw new g("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new g("client_mismatch");if(e.environment!==i.environment)throw new g("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new g("required_claim_missing");if(n&&e.nonce!==t)throw new g("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(O(e.issuer)!==O(n.issuer))throw new g("issuer_mismatch");if(!i.includes(n.clientId))throw new g("client_mismatch");if(e.authorizedParty!==n.clientId)throw new g("client_mismatch");if(!e.subject||!e.sessionId)throw new g("required_claim_missing");if(e.nonce!==t)throw new g("nonce_mismatch")}};function O(r){return r.replace(/\/+$/u,"")}var ln=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};export{re as BusinessOrganizationSelectionError,Ie as CANONICAL_PLAN_ASSET_TYPES,We as CANONICAL_STRUCTURED_ASSET_FIELDS,tn as CorePlanMaterialBuilder,p as ElementsApiPortRequired,K as ElementsApiRequestFailed,Q as ElementsClient,Re as GuidedCreateRecoveryError,be as GuidedPlanCreator,De as HostProcessRuntimeEnvironment,it as HttpAutomationRevealApiPort,ke as HttpElementsApiPort,rn as HttpOperatorAuthTransport,mt as InheritiClientProvider,Qn as InheritiFileInvalid,I as InvalidPlanDeclaration,T as InvalidPlanMaterial,Ne as LocalProcessReconciliationOwnership,et as MAX_INHERITI_FILE_BYTES,fe as MasterKeyRelayCancellationFailed,he as MasterKeyRelayExpired,ge as MasterKeyRelayTimedOut,F as MasterKeyRequired,Pe as MemoryGuidedCreateCheckpointStore,ae as MemoryKeyVault,de as MemoryStatePort,g as OAuthProtocolError,an as OperatorAuthClient,me as OperatorAuthError,k as OperatorReauthenticationRequired,ln as OperatorSessionController,ft as PLAN_CREATION_SERVER_STAGES,st as PlanMaterialReconstructionFailed,ce as PlanMaterialReconstructorRequired,ot as PollingSharedPlanEventListener,j as RelayMasterKeySource,le as RevealActionsNotOpen,S as RevealFieldAccessError,we as RevealHandleClosed,ks as SDKContainer,$e as StaticMasterKeyResolver,Ke as SystemOAuthClock,Ue as WebOAuthCrypto,cr as createAutomationRevealClient,$n as createElementsClient,ye as createMasterKeyResolver,Zn as exportProtectedRevealAsset,Ze as generateInheritiFileKey,An as getAvailableEnvs,oe as masterKeyRefFor,$ as masterKeyRefKey,Le as oauthErrorCode,Xn as openInheritiFile,Pi as openInheritiFileKey,At as parseAssetFieldSelector,Yn as readInheritiFileHeader,St as revealPhaseOf,Je as sealInheritiFile,_t as sealInheritiFileKey,dr as selectBusinessOrganization,en as unwrapDekWithMasterKey,gt as useClient,X as validatePlanCreationInput,ne as validatePlanCreationMaterial};