@safetech/inheriti-client-sdk 1.17.22 → 1.17.24

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 Bi}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as Vt,useEffect as Qe,createContext as $t,useMemo as Bt}from"react";import{CoreProvider as Ht,HttpClientFactory as Wt,AuthModule as jt,AuthStateProvider as Yt,AuthSessionRestorer as Xt,useClient as Qt}from"@safetech/inheriti-core-sdk";function K(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 J}from"sonner";var Xe={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{J.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{J.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{J.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{J.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{J.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as en,jsx as Y}from"react/jsx-runtime";var Zt="inheriti_client_merging_process",Te=$t(null);function Ze({children:r,clientId:e,options:t}){let n=t?.env??"development",i={key:e??"",options:{env:n}},s=Vt(Wt.create({apiUrl:K("",n),errorHandlingStrategy:Xe}));Qe(()=>{s.current?.setApiUrl(K("",n))},[n]);let o=Bt(()=>({core:{httpClient:s.current},"protection-plan":{authTokens:{mergingProcessKey:Zt}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return Y(Te.Provider,{value:s.current,children:Y(Yt,{children:Y(Ht,{modules:{auth:jt},moduleConfigs:o,children:Y(Xt,{children:Y(Jt,{client:i,children:r})})})})})}function Jt({children:r,client:e}){let{connect:t,isConnected:n}=Qt();return Qe(()=>{!e?.key||n||t(e)},[e.key]),Y(en,{children:r})}import{useContext as tn,useCallback as nn}from"react";import{useClient as rn}from"@safetech/inheriti-core-sdk";function Je(){let{connect:r,...e}=rn(),t=tn(Te),n=nn(async i=>(i?.options?.env&&t?.setApiUrl(K("",i.options.env)),r(i)),[r,t]);return{...e,connect:n}}function sn(){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=K("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:i}}import{decryptRSAOAEP as on,generateRSAOAEPKeyPair as an}from"@safetech/inheriti-core-sdk/crypto";var le=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ce=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ue=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},F=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 an();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(P=>setTimeout(P,S))),c=!0,g=!1,I,b=()=>I??=(async()=>{let S=new AbortController,P,zt=new Promise((Xn,Ft)=>{P=setTimeout(()=>{S.abort(),Ft(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),zt])}finally{clearTimeout(P)}})(),T,z=new Promise((S,P)=>{T=()=>{c&&b().catch(()=>{}),P(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",T,{once:!0})});z.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),g=!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),z]);if(S.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(S.status==="DELIVERED"&&S.sealedMasterKey){let P=(await on(S.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(P))throw new Error("invalid_master_key_material");return P}if(S.status==="EXPIRED")throw new ce(s.sessionId);await dn(d,o,e)}throw new le(s.sessionId)}catch(S){if(c&&(!g||e?.aborted))try{await b()}catch(P){if(e?.aborted)throw new ue(P)}throw S}finally{T&&e?.removeEventListener("abort",T)}}};async function dn(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 pe(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||Oe(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(ln(e,r.applicationId)){let i=await r.source?.resolve();return i||Oe(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Oe(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function ln(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Oe(r,e,t,n,i){if((await e()).relayAvailable)return new F({...r.relay,api:cn(r.api,t)}).resolve(n,i)}function cn(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 U(r){return`${r.system}:${r.contextId}`}function ee(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var k=class extends Error{constructor(t){super(`master_key_required:${U(t)}`);this.ref=t;this.name="MasterKeyRequired"}},De=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(U(e),t),this}async resolve(e){return this.sources.get(U(e))?.resolve()}};var te=class{keys=new Map;async store(e,t){let n=U(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(U(e))?.slice()}async remove(e){let t=U(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ne=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 re=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},u=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var ie=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var me=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],ke={"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"]},tt=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],y=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},E=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function X(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new E("plan_material_field_unknown");if(Me(r.dataShards,"data_shards_invalid"),Me(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Me(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new E("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new E("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new E("material_operation_invalid")}function Me(r,e){if(!Array.isArray(r))throw new E(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new E(e);if(t.data!==void 0&&typeof t.data!="string")throw new E(e)}}function $(r){if(V(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!mn(r.idempotencyKey))throw new y("idempotency_key_invalid");if(!r.name?.trim())throw new y("plan_name_required");if(!r.assets.length)throw new y("assets_required");let e=new Set;for(let t of r.assets){if(V(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 y("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!me.includes(t.type))throw new y("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new y("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 y("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new y("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new y("asset_field_names_invalid");if(un(t.matchOrigins),!t.isBinary){let s=ke[t.type];if(!s||i.some(o=>!s.includes(o)))throw new y("asset_field_name_not_canonical")}}if(!r.participants.length)throw new y("participants_required");for(let t of r.participants){if(V(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!nt(t.routingEmail))throw new y("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new y("participant_relationships_invalid")}pn(r)}function un(r){if(r===void 0)return;if(!r.length)throw new y("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new y("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new y("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof y?n:new y("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new y("asset_match_origins_duplicated")}function pn(r){let e=r.policy;if(e&&V(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new y("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){V(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new y("authentication_mode_invalid")}if(e.moderation){V(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new y("moderation_requires_moderators");let o=e.moderation.minimumApprovals;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>s.length))throw new y("minimum_approvals_invalid");let a=e.moderation.approvalMode;if(a!==void 0&&a!=="THRESHOLD"&&a!=="UNANIMOUS")throw new y("approval_mode_invalid")}let t=e.dms;if(!t)return;V(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!nt(t.subjectEmail))throw new y("dms_subject_invalid");if(!r.participants.some(s=>et(s.routingEmail)===et(t.subjectEmail)))throw new y("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 y("dms_countdown_invalid")}function mn(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 nt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function et(r){return r.normalize("NFC").trim().toLowerCase()}function V(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new y(t)}var he=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)}},fe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),$(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={}){$(t);let o=await this.checkpoints.load(e);if(!o)throw new ye("creation_checkpoint_missing");if(o.idempotencyKey!==t.idempotencyKey||o.declarationHash!==await rt(t))throw new ye("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),X(c);let g=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(g.stage),g.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,g),g}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 rt(e),serverStage:t.stage})}},ye=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function rt(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 it(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new re(n.stage);return r.authorizeRevealAction(e,t)}function gn(r){let e=r?.status;return e===400||e===401||e===403}async function st(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!gn(s))throw s}return r.releaseRevealMaterial(e,t)}function lt(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"?fn(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":hn.has(r.stage)?"ENDED":"CONTINUING"}var hn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function fn(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"}},R=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function ct(r,e,t={}){if(t.signal?.aborted)throw v();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):ot(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw v();let s=t.idempotencyKey??crypto.randomUUID(),o;try{o=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:s})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?d:ot(c.id)}let a;try{if(t.signal?.aborted)throw v();let d=await vn(r,o,t);if(t.signal?.aborted||(L(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw v();let c=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id),t.signal?.aborted))throw v();let g;try{g=await Rn(r,d,wn(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(L(t,"RECONSTRUCTING",d),t.signal?.aborted))throw v();try{a=await r.reconstructPlanMaterial(g)}catch(b){throw t.signal?.aborted?v():(await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Pn(b)}),b)}if(t.signal?.aborted)throw v();let I=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(L(t,"OPEN",I),t.signal?.aborted))throw v();return new Ke(r,I,n,a,t.signal)}catch(d){throw a?.fill(0),await pt(r,o.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function ot(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var yn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function vn(r,e,t){let n=await N(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw v();if(t.onSession?.(n),t.onProgress?.({phase:lt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(yn.has(n.stage))throw new Ne(n.stage);await Le(t.pollIntervalMs??1500,t.signal),n=await N(()=>r.getReveal(e.id,t.signal),t.signal)}}var Ne=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function L(r,e,t){r.onProgress?.({phase:e,session:t})}function Le(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 Ke=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 R("asset_selector_invalid");if(!this.client.assetDecoder)throw new R("asset_decoder_required");let n=e.map(({selector:s,options:o={}})=>{let a=ut(s),d=this.plan.assets.find(c=>(c.code??c.id)===a.asset);if(!d)throw new R("asset_not_found");if(d.isBinary)throw new R("action_not_allowed");if(!d.fieldNames.includes(a.field))throw new R("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 R("asset_value_invalid");return{selector:o.selector,value:In(a.data,o.field,o.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(o=>this.reportAction(o.id,"FAILED",at(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new R("asset_selector_invalid");if(!this.client.assetDecoder)throw new R("asset_decoder_required");let n=this.plan.assets.find(o=>o.code===e||o.id===e);if(!n)throw new R("asset_not_found");if(!n.isBinary)throw new R("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 R("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",at(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=pt(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 ut(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new R("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new R("asset_selector_invalid");return{asset:r.asset,field:r.field}}function In(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new R("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new R("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?ke[t]:void 0)?.includes(e))return"";throw new R("asset_value_invalid")}return n[e]}function at(r){if(r instanceof R)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 Pn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Rn(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await N(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Ie;let c=await N(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(dt(c,i.id,e.planId),!c.shares.includes(i.data))throw new O;L(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:g}=await N(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw v();if(!g?.trim())throw new O;if(await r.claimRevealCustodianShare(e.id,c.id,g),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw v();return{...t,shares:t.shares.filter(I=>I!==i).concat(c.shares.map((I,b)=>({id:`${c.id}:${b}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:I})))}}if(d!=="SK_MOBILE")throw new O;if(n.signal?.aborted)throw v();return await r.distributeRevealCustodianShare(e.id),L(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await N(()=>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),L(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Le(n.pollIntervalMs??1500,n.signal),s=await N(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Ie;if(!s.shareId||!s.deviceId)throw new O;L(n,"CONNECTING_SAFEKEY_PRO",e);let d=await N(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw v();if(dt(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new O;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw v();return{...t,shares:t.shares.concat(d.shares.map((c,g)=>({id:`${d.id}:${g}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new O;let o={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(o),L(n,"WAITING_FOR_CUSTODIAN",o),n.signal?.aborted)throw v();await r.requestRevealCustodianRelease(e.id);let a=await bn(r,e.id,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 dt(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 O}async function N(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 bn(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await N(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new O}if(Date.now()>=n)throw new Ue;await Le(t.pollIntervalMs??1500,t.signal)}}var O=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Ie=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ue=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function wn(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function pt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(o){if(!Sn(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 Sn(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 B=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 te,this.state=t.state??new ne,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??_n(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 u;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new u;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new u;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return $(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new u;return X(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new he){if(this.requireApplication(),!this.api)throw new u;return new fe(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 k({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 xn(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new k(e);return await this.keyVault.store(e,An(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new u;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 u;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new ie;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 k({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=ee(e);if(!i)throw new k({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new u;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new u;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new u;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new u;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new u;return this.api.getReveal(e,t)}openReveal(e,t){return ct(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 u;return st(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new u;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new u;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new u;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new u;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new u;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new u;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new u;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new u;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new u;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new u;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new u;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new u;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new u;return it(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new u;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new u;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new u;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new u;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new u;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new u;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 u;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 k({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 En(r){return new B(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 An(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 xn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function _n(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 pe({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return pe({...e,organizationId:r.organizationId})}var Cn=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Tn=["DIRECT","GOVERNED"],gt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],On=["ACTIVE","REVOKED"],Dn=["SK_MOBILE"],Mn=["ACTIVE","INACTIVE"],kn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function ht(r){let e=w(r);return{items:_(e.items).map(yt),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function ft(r){let e=w(r);return{total:D(e.total,"total"),items:_(e.items).map(t=>{let n=w(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:_(n.details).map(i=>{let s=w(i);return{label:p(s.label,"log.detail.label"),value:p(s.value,"log.detail.value")}})}})}}function Pe(r){let e=w(r),t=yt(e),n=w(e.source),i=p(n.kind,"source.kind");return{...t,assets:_(e.assets).map(s=>{let o=w(s);return{id:p(o.id,"asset.id"),code:q(o.code),type:x(p(o.type,"asset.type"),me),name:p(o.name,"asset.name"),isBinary:Kn(o.isBinary,"asset.isBinary"),fieldNames:_(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:D(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:_(o.matchOrigins).map(a=>p(a,"asset.matchOrigins"))}}),participants:_(e.participants).map(s=>{let o=w(s);return{id:p(o.id,"participant.id"),displayName:p(o.displayName,"participant.displayName"),relationships:_(o.relationships).map(a=>x(p(a,"relationship"),gt)),lifecycle:x(p(o.lifecycle,"participant.lifecycle"),On)}}),revealPolicy:(()=>{let s=w(e.revealPolicy);return{masterKeyRelease:x(p(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:x(p(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=w(e.dms);return{subjectEmail:p(s.subjectEmail,"dms.subjectEmail"),countdownDays:D(s.countdownDays,"dms.countdownDays"),countdownHours:D(s.countdownHours,"dms.countdownHours"),countdownMinutes:D(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:x(p(n.system,"source.system"),["INHERITI_BUSINESS"]),status:x(p(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function se(r){let e=w(r);return{operationId:p(e.operationId,"operationId"),stage:x(p(e.stage,"stage"),tt),outcome:x(p(e.outcome,"outcome"),kn),planId:q(e.planId),lastErrorCode:q(e.lastErrorCode),participants:e.participants===void 0?void 0:_(e.participants).map(t=>{let n=w(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:_(n.relationships).map(i=>Nn(p(i,"relationship"),gt))}})}}function yt(r){let e=w(r),t=w(e.assetSummary),n=w(e.governance),i=w(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:q(e.description),status:x(p(e.status,"status"),Cn),createdAt:p(e.createdAt,"createdAt"),configuredAt:q(e.configuredAt),assetSummary:{count:D(t.count,"assetSummary.count"),types:_(t.types).map(s=>x(p(s,"assetType"),me)),names:mt(t.names).map(s=>p(s,"assetSummary.names"))},governance:{mode:x(p(n.mode,"governance.mode"),Tn),minimumApprovals:D(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:D(i.owners,"owners"),mergers:D(i.mergers,"mergers"),moderators:D(i.moderators,"moderators")},authentication:mt(e.authentication).map(s=>{let o=w(s);return{id:x(p(o.id,"authentication.id"),Dn),status:x(p(o.status,"authentication.status"),Mn)}})}}function x(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Nn(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function w(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function mt(r){return r==null?[]:_(r)}function _(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 D(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Kn(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var Q=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function vt(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 Un(r,e){if(!e){if(r.length===0)throw new Q("organization_required");if(r.length>1)throw new Q("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new Q("organization_access_denied");return e}function Ln(r){let e=h(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:m(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:m(e.participantRevision,1),createdAt:A(e.createdAt),...It(e)}}function It(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=h(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:A(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=h(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:m(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:A(i.revealedAt)}:{}}})}:{}}})}}function Pt(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Ln),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0),unreadCount:m(e.unreadCount,0),readThroughSequence:m(e.readThroughSequence,0)}}function Rt(r){let e=h(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:m(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:m(e.participantRevision,1),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:m(e.senderDeviceVersion,1),canonicalManifest:l(e.canonicalManifest),signature:l(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=h(t);return{unitId:l(n.unitId),position:m(n.position,0),commitment:l(n.commitment),status:l(n.status)}})}}function Ge(r){let e=h(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:l(e.parentId),sequence:m(e.sequence,1),status:e.status}}function bt(r){let e=h(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:m(e.participantRevision,1),recipients:e.recipients.map(ze)}}function wt(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(t);return{parentId:l(n.parentId),sequence:m(n.sequence,1),senderMemberId:l(n.senderMemberId),senderDeviceId:l(n.senderDeviceId),participantRevision:m(n.participantRevision,1),createdAt:A(n.createdAt),...It(n)}}),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0),unreadCount:m(e.unreadCount,0),readThroughSequence:m(e.readThroughSequence,0)}}function St(r){return{readThroughSequence:m(h(r).readThroughSequence,0)}}function Et(r){return{clearedThroughSequence:m(h(r).clearedThroughSequence,0)}}function At(r){let e=h(r);return{parentId:l(e.parentId),sequence:m(e.sequence,1),senderMemberId:l(e.senderMemberId),senderDeviceId:l(e.senderDeviceId),participantRevision:m(e.participantRevision,1),canonicalManifest:l(e.canonicalManifest),frame:l(e.frame),signature:l(e.signature),wrappedContentKey:l(e.wrappedContentKey),senderSigningPublicKey:l(e.senderSigningPublicKey)}}function h(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 A(r){let e=l(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function m(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function ze(r){let e=h(r);return{memberId:l(e.memberId),deviceId:l(e.deviceId),deviceVersion:m(e.deviceVersion,1),encryptionPublicKey:l(e.encryptionPublicKey),encryptionKeyFingerprint:l(e.encryptionKeyFingerprint),signingPublicKey:l(e.signingPublicKey),signingKeyFingerprint:l(e.signingKeyFingerprint)}}function Z(r){let e=h(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:A(e.createdAt),updatedAt:A(e.updatedAt)}}function Re(r){let e=h(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:A(e.createdAt),updatedAt:A(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=h(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:A(n.createdAt)}}return t}function xt(r){let e=h(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(Re),total:e.total,limit:e.limit,offset:e.offset}}function _t(r){let e=h(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=ze(t);return{memberId:n.memberId,name:l(h(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:m(e.limit,1),offset:m(e.offset,0),nextOffset:e.nextOffset===null?null:m(e.nextOffset,0)}}function Ct(r){let e=h(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=h(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(h(n.profilePicture).url)}}}}),limit:m(e.limit,1),offset:m(e.offset,0),nextOffset:e.nextOffset===null?null:m(e.nextOffset,0)}}function Tt(r){let e=h(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:m(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(ze),shareLayers:e.shareLayers.map(t=>{let n=h(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 be(r){let e=h(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 Ot(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(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:A(n.createdAt),updatedAt:A(n.updatedAt),expiresAt:A(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=h(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:A(o.consumedAt)}:{}}})),i}),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0)}}function Dt(r){let e=h(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:l(e.leaseId),leaseExpiresAt:A(e.leaseExpiresAt),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:m(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=h(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:m(n.index,0),shareId:l(n.shareId),layerId:l(n.layerId),ciphertext:l(n.ciphertext)}})}}function Mt(r){let e=h(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:l(e.leaseId),leaseExpiresAt:A(e.leaseExpiresAt),senderSigningPublicKey:l(e.senderSigningPublicKey),senderSigningKeyFingerprint:l(e.senderSigningKeyFingerprint),senderDeviceVersion:m(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=h(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:m(n.index,0),shareId:l(n.shareId),layerId:l(n.layerId)}})}}function H(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 W(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var C=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}},Se=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;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:Z(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:Z(n)}async registerInboxDevice(e){return Z(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return Z(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return Z(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Re(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Re(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 xt(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 _t(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 Ct(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Tt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return bt(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 be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return Ge(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return Ge(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 Pt(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 Rt(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 Et(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 wt(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 At(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 St(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return be(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 we(a,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new C(a.status,H(d),W(d),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return be(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 Mt(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 g=Number(c.headers.get("content-length"));if(Number.isFinite(g)&&g>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let I=c.body.getReader(),b=[],T=0;try{for(;;){o?.throwIfAborted();let P=await I.read();if(P.done)break;if(T+=P.value.length,T>14*1024*1024)throw new Error("invalid_inbox_share_size");b.push(P.value)}}catch(P){throw await I.cancel().catch(()=>{}),P}let z=new Uint8Array(T),S=0;for(let P of b)z.set(P,S),S+=P.length;return z}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 Ot(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return Dt(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(vt)}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 ht(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Pe(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 ft(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){$(e);let{idempotencyKey:t,...n}=e;return se(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return se(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return X(t),se(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return se(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[T,z]of Object.entries(s??{}))d.set(T,z);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,g={method:t,headers:d,body:n?JSON.stringify(n):void 0};o&&(g.signal=o);let I=await this.transport(new URL(e,c),g);o?.throwIfAborted();let b=await we(I,o);if(o?.throwIfAborted(),!I.ok)throw new C(I.status,H(b),W(b),I.headers.get("x-request-id")??void 0);if(!b.ok||b.result===void 0)throw new C(I.status,H(b),W(b),I.headers.get("x-request-id")??void 0);return b.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 we(d,i);throw new C(d.status,H(c),W(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});n&&i.set("authorization",`Bearer ${n}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let s=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,o=await this.transport(new URL(e,s),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),a=await we(o);if(!o.ok||!a.ok)throw new C(o.status,H(a),W(a),o.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 C(400,"organization_selection_required")}};async function we(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}var Fe=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 Pe(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 g;try{g=await c.json()}catch{o?.throwIfAborted()}if(!c.ok||g&&g.ok===!1||i&&g?.result===void 0)throw new C(c.status,g&&H(g),g&&W(g));return g?.result}};function qn(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=ee(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new F({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)}});return new B(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)}}}).openReveal(e,t)}}}async function kt(r,e){if(!e)throw new Error("master_key_required");let t=Gn(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=zn(r),s=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,o);return Fn(new Uint8Array(a))}function Gn(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 zn(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 Fn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Ve=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}};import{MergeProcessReconciliationLoop as Vn}from"@safetech/inheriti-core-sdk/shared-configuration";var $n=new Set(["COMPLETED","ABORTED","EXPIRED"]),$e=class{constructor(e,t=new Ee,n=new Ae,i=Math.random){this.api=e;this.loop=new Vn(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=Bn(a);n!==void 0&&c!==n&&await t.onProcessUpdated?.(),i!==void 0&&d!==i&&await t.onApprovalUpdated?.(),n=c,i=d;let g=$n.has(a.status);if(a.status==="EXPIRED"&&await t.onRevealWindowExpired?.(e),a.status==="ABORTED"&&await t.onForceAborted?.(e),g)return{transitionKey:c,shouldPoll:!1,terminal:!0};if(!s){let I=await this.api.getCustodianShare(e);"status"in I||(s=!0,await t.onCustodianShareReceived?.(e,I))}return{transitionKey:c,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,o)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function Bn(r){return`${r.status}:${r.approvalProcess?.status??""}`}var Ee=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)})}},Ae=class{join(e,t){let n=!0;return{isOwner:()=>n,requestReconciliation:()=>{n&&t.onReconciliationRequested()},publishReconciled:()=>{},leave:()=>{n=!1}}}};var Nt=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){oe(e.signal),Wn(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return oe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){oe(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(oe(e.signal),!i.custodianPair)throw new E("custodian_share_required");let s=Be(i.keyShards),o=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),a=await this.sealer.encryptShares(Be(i.dataShards),o.symmetricKeyBase64),d=await this.sealer.encryptShares(Be(i.backupShards),o.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,o.symmetricKeyBase64);return oe(e.signal),{protectionProtocol:i.protocol,validatorShares:He(o.encryptedShares),dataShards:He(a.encryptedShares),backupShards:He(d.encryptedShares),encryptedKey:o.encryptedKey,assetsMetadata:Hn(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:We(n.encryptedShares[0]),dataShard:We(n.encryptedShares[1])}}};function Be(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function He(r){return r.map(We)}function We(r){return{id:r.id,data:r.encryptedData}}function Hn(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new E("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 Wn(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new E("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new E("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new E("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 E("plan_secrets_declaration_mismatch")}}function oe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}function Kt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var xe=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Kt(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Kt(new Uint8Array(t))}},_e=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 ae=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},de=class extends ae{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},f=class extends ae{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function je(r){if(r instanceof ae)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Ut=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:G(n,"issuer"),authorizationEndpoint:G(n,"authorization_endpoint"),tokenEndpoint:G(n,"token_endpoint"),deviceAuthorizationEndpoint:M(n,"device_authorization_endpoint"),endSessionEndpoint:M(n,"end_session_endpoint"),revocationEndpoint:M(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:G(t,"device_code"),userCode:G(t,"user_code"),verificationUri:G(t,"verification_uri"),verificationUriComplete:M(t,"verification_uri_complete"),expiresInSeconds:Lt(t,"expires_in"),intervalSeconds:Ye(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 token(e,t){let n=await this.form(e,t);return{accessToken:G(n,"access_token"),refreshToken:M(n,"refresh_token"),idToken:M(n,"id_token"),tokenType:G(n,"token_type"),expiresInSeconds:Lt(n,"expires_in"),refreshExpiresInSeconds:Ye(n,"refresh_expires_in"),scope:M(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=M(i,"error")??`oauth_http_${n.status}`;throw new f(s,M(i,"error_description")??s)}return i}};function G(r,e){let t=M(r,e);if(!t)throw new f("invalid_oauth_response",`Missing ${e}`);return t}function M(r,e){return typeof r[e]=="string"?r[e]:void 0}function Lt(r,e){let t=Ye(r,e);if(t===void 0)throw new f("invalid_oauth_response",`Missing ${e}`);return t}function Ye(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var jn=600*1e3,Ce=5,Yn=5,qt=class{constructor(e){this.options=e;this.crypto=e.crypto??new xe,this.clock=e.clock??new _e}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),s=await this.crypto.sha256UrlSafe(i),o=this.clock.now()+jn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let a=new URL(e.authorizationEndpoint);return a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.options.configuration.clientId),a.searchParams.set("redirect_uri",this.options.configuration.redirectUri),a.searchParams.set("scope",this.options.configuration.scopes.join(" ")),a.searchParams.set("state",t),a.searchParams.set("nonce",n),a.searchParams.set("code_challenge",s),a.searchParams.set("code_challenge_method","S256"),{authorizationUrl:a.toString(),expiresAt:o}}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 f("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new f("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new f("redirect_uri_mismatch");let o=i.searchParams.get("error");if(o)throw new f(o,i.searchParams.get("error_description")??o);if(i.searchParams.get("state")!==n.state)throw new f("state_mismatch");let a=i.searchParams.get("code");if(!a)throw new f("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}),g=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(g),g}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new f("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(Ce,t.intervalSeconds??Ce),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 f("device_transaction_missing");let i=n,s=await this.getDiscovery(),o=Math.max(Ce,i.intervalSeconds??Ce),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 this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(d){let c=je(d);if(c==="authorization_pending"){a=this.clock.now()+o*1e3;continue}if(c==="slow_down"){o+=Yn,a=this.clock.now()+o*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new f("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new de;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=je(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new de):(this.isOfflineSession(e)||await this.options.sessions.clear(),n)}try{if(!t.refreshToken)throw new f("refresh_token_rotation_missing");let n=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(n),n}catch(n){throw await this.options.sessions.clear(),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(j(e.issuer)!==j(this.options.configuration.issuer))throw new f("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}|${j(t)}|${n}|${i}`}async acceptTokens(e,t,n){if(e.tokenType.toLowerCase()!=="bearer")throw new f("unsupported_token_type");let i=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(i,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new f("id_token_validation_required");let a=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(a,t),a.subject!==i.subject||a.sessionId!==i.sessionId)throw new f("token_subject_mismatch")}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"));return{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}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(j(e.issuer)!==j(i.issuer))throw new f("issuer_mismatch");if(!s.includes(i.audience))throw new f("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new f("client_mismatch");if(e.environment!==i.environment)throw new f("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new f("required_claim_missing");if(n&&e.nonce!==t)throw new f("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(j(e.issuer)!==j(n.issuer))throw new f("issuer_mismatch");if(!i.includes(n.clientId))throw new f("client_mismatch");if(e.authorizedParty!==n.clientId)throw new f("client_mismatch");if(!e.subject||!e.sessionId)throw new f("required_claim_missing");if(e.nonce!==t)throw new f("nonce_mismatch")}};function j(r){return r.replace(/\/+$/u,"")}var Gt=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{Q as BusinessOrganizationSelectionError,me as CANONICAL_PLAN_ASSET_TYPES,ke as CANONICAL_STRUCTURED_ASSET_FIELDS,Nt as CorePlanMaterialBuilder,u as ElementsApiPortRequired,C as ElementsApiRequestFailed,B as ElementsClient,ye as GuidedCreateRecoveryError,fe as GuidedPlanCreator,Ee as HostProcessRuntimeEnvironment,Fe as HttpAutomationRevealApiPort,Se as HttpElementsApiPort,Ut as HttpOperatorAuthTransport,Ze as InheritiClientProvider,y as InvalidPlanDeclaration,E as InvalidPlanMaterial,Ae as LocalProcessReconciliationOwnership,ue as MasterKeyRelayCancellationFailed,ce as MasterKeyRelayExpired,le as MasterKeyRelayTimedOut,k as MasterKeyRequired,he as MemoryGuidedCreateCheckpointStore,te as MemoryKeyVault,ne as MemoryStatePort,f as OAuthProtocolError,qt as OperatorAuthClient,ae as OperatorAuthError,de as OperatorReauthenticationRequired,Gt as OperatorSessionController,tt as PLAN_CREATION_SERVER_STAGES,Ve as PlanMaterialReconstructionFailed,ie as PlanMaterialReconstructorRequired,$e as PollingSharedPlanEventListener,F as RelayMasterKeySource,re as RevealActionsNotOpen,R as RevealFieldAccessError,ve as RevealHandleClosed,Bi as SDKContainer,De as StaticMasterKeyResolver,_e as SystemOAuthClock,xe as WebOAuthCrypto,qn as createAutomationRevealClient,En as createElementsClient,pe as createMasterKeyResolver,sn as getAvailableEnvs,ee as masterKeyRefFor,U as masterKeyRefKey,je as oauthErrorCode,ut as parseAssetFieldSelector,lt as revealPhaseOf,Un as selectBusinessOrganization,kt as unwrapDekWithMasterKey,Je as useClient,$ as validatePlanCreationInput,X as validatePlanCreationMaterial};
1
+ import{SDKContainer as ps}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as Yt,useEffect as rt,createContext as Xt,useMemo as Qt}from"react";import{CoreProvider as Zt,HttpClientFactory as Jt,AuthModule as en,AuthStateProvider as tn,AuthSessionRestorer as nn,useClient as rn}from"@safetech/inheriti-core-sdk";function L(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 J}from"sonner";var nt={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{J.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{J.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{J.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{J.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{J.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as an,jsx as Y}from"react/jsx-runtime";var sn="inheriti_client_merging_process",Me=Xt(null);function it({children:r,clientId:e,options:t}){let n=t?.env??"development",i={key:e??"",options:{env:n}},s=Yt(Jt.create({apiUrl:L("",n),errorHandlingStrategy:nt}));rt(()=>{s.current?.setApiUrl(L("",n))},[n]);let o=Qt(()=>({core:{httpClient:s.current},"protection-plan":{authTokens:{mergingProcessKey:sn}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return Y(Me.Provider,{value:s.current,children:Y(tn,{children:Y(Zt,{modules:{auth:en},moduleConfigs:o,children:Y(nn,{children:Y(on,{client:i,children:r})})})})})}function on({children:r,client:e}){let{connect:t,isConnected:n}=rn();return rt(()=>{!e?.key||n||t(e)},[e.key]),Y(an,{children:r})}import{useContext as ln,useCallback as dn}from"react";import{useClient as cn}from"@safetech/inheriti-core-sdk";function st(){let{connect:r,...e}=cn(),t=ln(Me),n=dn(async i=>(i?.options?.env&&t?.setApiUrl(L("",i.options.env)),r(i)),[r,t]);return{...e,connect:n}}function pn(){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=L("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:i}}import{decryptRSAOAEP as un,generateRSAOAEPKeyPair as mn}from"@safetech/inheriti-core-sdk/crypto";var de=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ce=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"}},z=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 mn();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),l=this.options.sleep??(A=>new Promise(R=>setTimeout(R,A))),c=!0,u=!1,v,P=()=>v??=(async()=>{let A=new AbortController,R,Te=new Promise((Oe,De)=>{R=setTimeout(()=>{A.abort(),De(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),Te])}finally{clearTimeout(R)}})(),x,b=new Promise((A,R)=>{x=()=>{c&&P().catch(()=>{}),R(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",x,{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 R=(await un(A.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(R))throw new Error("invalid_master_key_material");return R}if(A.status==="EXPIRED")throw new ce(s.sessionId);await gn(l,o,e)}throw new de(s.sessionId)}catch(A){if(c&&(!u||e?.aborted))try{await P()}catch(R){if(e?.aborted)throw new pe(R)}throw A}finally{x&&e?.removeEventListener("abort",x)}}};async function gn(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 ue(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||Ne(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(hn(e,r.applicationId)){let i=await r.source?.resolve();return i||Ne(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Ne(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function hn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Ne(r,e,t,n,i){if((await e()).relayAvailable)return new z({...r.relay,api:fn(r.api,t)}).resolve(n,i)}function fn(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 F(r){return`${r.system}:${r.contextId}`}function ee(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var k=class extends Error{constructor(t){super(`master_key_required:${F(t)}`);this.ref=t;this.name="MasterKeyRequired"}},ke=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(F(e),t),this}async resolve(e){return this.sources.get(F(e))?.resolve()}};var te=class{keys=new Map;async store(e,t){let n=F(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(F(e))?.slice()}async remove(e){let t=F(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ne=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 re=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 ie=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var me=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Ue={"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"]},at=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],y=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},S=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function X(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new S("plan_material_field_unknown");if(Ke(r.dataShards,"data_shards_invalid"),Ke(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Ke(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new S("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new S("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new S("material_operation_invalid")}function Ke(r,e){if(!Array.isArray(r))throw new S(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new S(e);if(t.data!==void 0&&typeof t.data!="string")throw new S(e)}}function $(r){if(V(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!vn(r.idempotencyKey))throw new y("idempotency_key_invalid");if(!r.name?.trim())throw new y("plan_name_required");if(!r.assets.length)throw new y("assets_required");let e=new Set;for(let t of r.assets){if(V(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 y("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!me.includes(t.type))throw new y("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new y("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 y("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new y("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new y("asset_field_names_invalid");if(yn(t.matchOrigins),!t.isBinary){let s=Ue[t.type];if(!s||i.some(o=>!s.includes(o)))throw new y("asset_field_name_not_canonical")}}if(!r.participants.length)throw new y("participants_required");for(let t of r.participants){if(V(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!lt(t.routingEmail))throw new y("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new y("participant_relationships_invalid")}In(r)}function yn(r){if(r===void 0)return;if(!r.length)throw new y("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new y("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new y("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof y?n:new y("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new y("asset_match_origins_duplicated")}function In(r){let e=r.policy;if(e&&V(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new y("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){V(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new y("authentication_mode_invalid")}if(e.moderation){V(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(l=>l.relationships.includes("MODERATOR"));if(s.length===0)throw new y("moderation_requires_moderators");let o=e.moderation.minimumApprovals;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>s.length))throw new y("minimum_approvals_invalid");let a=e.moderation.approvalMode;if(a!==void 0&&a!=="THRESHOLD"&&a!=="UNANIMOUS")throw new y("approval_mode_invalid")}let t=e.dms;if(!t)return;V(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!lt(t.subjectEmail))throw new y("dms_subject_invalid");if(!r.participants.some(s=>ot(s.routingEmail)===ot(t.subjectEmail)))throw new y("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 y("dms_countdown_invalid")}function vn(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 lt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function ot(r){return r.normalize("NFC").trim().toLowerCase()}function V(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new y(t)}var he=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)}},fe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),$(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={}){$(t);let o=await this.checkpoints.load(e);if(!o)throw new ye("creation_checkpoint_missing");if(o.idempotencyKey!==t.idempotencyKey||o.declarationHash!==await dt(t))throw new ye("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 l=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:l,signal:s.signal});ge(s.signal),X(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 dt(e),serverStage:t.stage})}},ye=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function dt(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 ct(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new re(n.stage);return r.authorizeRevealAction(e,t)}function Pn(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(!Pn(s))throw s}return r.releaseRevealMaterial(e,t)}function ht(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"?bn(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":Rn.has(r.stage)?"ENDED":"CONTINUING"}var Rn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function bn(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 Ie=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 ft(r,e,t={}){if(t.signal?.aborted)throw I();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")||i.protectedCopy!==void 0&&i.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):ut(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)}),t.signal?.aborted))throw I();let s=t.idempotencyKey??crypto.randomUUID(),o;try{o=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:s,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")||c.protectedCopy!==void 0&&c.protectedCopy!==(t.protectedCopy??!1)?l:ut(c.id)}if(o.protectedCopy!==void 0&&o.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(o.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let a;try{if(t.signal?.aborted)throw I();let l=await An(r,o,t);if(t.signal?.aborted||(q(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw I();let c=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id),t.signal?.aborted))throw I();let u;try{u=await xn(r,l,Cn(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(q(t,"RECONSTRUCTING",l),t.signal?.aborted))throw I();try{a=await r.reconstructPlanMaterial(u)}catch(P){throw t.signal?.aborted?I():(await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:Sn(P)}),P)}if(t.signal?.aborted)throw I();let v=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(q(t,"OPEN",v),t.signal?.aborted))throw I();return new Fe(r,v,n,a,t.signal)}catch(l){throw a?.fill(0),await It(r,o.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function ut(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var wn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function An(r,e,t){let n=await K(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw I();if(t.onSession?.(n),t.onProgress?.({phase:ht(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(wn.has(n.stage))throw new Le(n.stage);await Ge(t.pollIntervalMs??1500,t.signal),n=await K(()=>r.getReveal(e.id,t.signal),t.signal)}}var Le=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function q(r,e,t){r.onProgress?.({phase:e,session:t})}function Ge(r,e){return e?.aborted?Promise.reject(I()):new Promise((t,n)=>{let i=setTimeout(o,Math.max(0,r)),s=()=>{clearTimeout(i),n(I())};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Fe=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 Ie;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=yt(s),l=this.plan.assets.find(c=>(c.code??c.id)===a.asset);if(!l)throw new w("asset_not_found");if(l.isBinary)throw new w("action_not_allowed");if(!l.fieldNames.includes(a.field))throw new w("asset_field_not_found");return{selector:`${a.asset}.${a.field}`,assetCode:a.asset,asset:l,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(l=>l.id===o.asset.id||l.id===o.assetCode);if(!a)throw new w("asset_value_invalid");return{selector:o.selector,value:En(a.data,o.field,o.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(o=>this.reportAction(o.id,"FAILED",mt(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",mt(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=It(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 yt(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 En(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"?Ue[t]:void 0)?.includes(e))return"";throw new w("asset_value_invalid")}return n[e]}function mt(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 Sn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function xn(r,e,t,n){let i=t.shares.find(l=>l.shareType==="CUSTODIAN_KEY_SHARD");if(i){let l=await K(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(l==="SK_PRO"){if(!n.proDevice)throw new ve;let c=await K(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(gt(c,i.id,e.planId),!c.shares.includes(i.data))throw new M;q(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:u}=await K(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw I();if(!u?.trim())throw new M;if(await r.claimRevealCustodianShare(e.id,c.id,u),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw I();return{...t,shares:t.shares.filter(v=>v!==i).concat(c.shares.map((v,P)=>({id:`${c.id}:${P}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:v})))}}if(l!=="SK_MOBILE")throw new M;if(n.signal?.aborted)throw I();return await r.distributeRevealCustodianShare(e.id),q(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await K(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(l),q(n,"WAITING_FOR_CUSTODIAN_CLAIM",l),await Ge(n.pollIntervalMs??1500,n.signal),s=await K(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new ve;if(!s.shareId||!s.deviceId)throw new M;q(n,"CONNECTING_SAFEKEY_PRO",e);let l=await K(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw I();if(gt(l,s.shareId,e.planId),l.deviceId!==s.deviceId)throw new M;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw I();return{...t,shares:t.shares.concat(l.shares.map((c,u)=>({id:`${l.id}:${u}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new M;let o={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(o),q(n,"WAITING_FOR_CUSTODIAN",o),n.signal?.aborted)throw I();await r.requestRevealCustodianRelease(e.id);let a=await _n(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(a.shares.map((l,c)=>({id:`${a.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}function gt(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 M}async function K(r,e){if(e?.aborted)throw I();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(I()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw I();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function _n(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await K(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new M}if(Date.now()>=n)throw new qe;await Ge(t.pollIntervalMs??1500,t.signal)}}var M=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},ve=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},qe=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Cn(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function It(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(o){if(!Tn(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 Tn(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function I(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var B=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 te,this.state=t.state??new ne,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Nn(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 $(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 X(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new m;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new he){if(this.requireApplication(),!this.api)throw new m;return new fe(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 k({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 Mn(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new k(e);return await this.keyVault.store(e,Dn(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 ie;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 k({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=ee(e);if(!i)throw new k({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 ft(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 pt(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 ct(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"})),l=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,l),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 ze;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new k({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},ze=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function On(r){return new B(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 Dn(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 Mn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Nn(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 ue({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ue({...e,organizationId:r.organizationId})}import{generateInheritiFileKey as Ve,sealInheritiFile as $e,readInheritiFileHeader as kn,openInheritiFile as Kn,InheritiFileInvalid as Un,MAX_INHERITI_FILE_BYTES as Be}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as vt,openInheritiFileKey as ti}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Ln(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>Be-1024*1024)throw new Error("unsupported_protected_asset");let l=Ve(),c,u=!1,v=!1;try{n?.throwIfAborted();let P=await vt(l,i.publicKey);u=!0;let x=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:a.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:P,openLimit:o},n);if(x.copyId!==r.copyId||x.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((R,Te)=>{let Oe=()=>{clearTimeout(De),Te(n?.reason)},De=setTimeout(()=>{n?.removeEventListener("abort",Oe),R()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",Oe,{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 $e({plaintext:a.bytes,fileKey:l,mimeType:a.mimeType,binding:b});A.fileKey.fill(0),c=A.fileBytes,n?.throwIfAborted(),await r.save({fileName:a.fileName,fileBytes:c}),v=!0}catch(P){if(u&&!v)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(x){throw new AggregateError([P,x],"protected_asset_export_and_cleanup_failed",{cause:P})}throw P}finally{l.fill(0),c?.fill(0)}})}var Fn=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],qn=["DIRECT","GOVERNED"],Rt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Gn=["ACTIVE","REVOKED"],zn=["SK_MOBILE"],Vn=["ACTIVE","INACTIVE"],$n=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function bt(r){let e=E(r);return{items:T(e.items).map(Et),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function wt(r){let e=E(r);return{total:O(e.total,"total"),items:T(e.items).map(t=>{let n=E(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:U(n.status),title:p(n.title,"log.title"),details:T(n.details).map(i=>{let s=E(i);return{label:p(s.label,"log.detail.label"),value:p(s.value,"log.detail.value")}})}})}}function At(r){let e=E(r);return{total:O(e.total,"total"),items:T(e.items).map(t=>{let n=E(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:U(n.status)}})}}function Pe(r){let e=E(r),t=Et(e),n=E(e.source),i=p(n.kind,"source.kind");return{...t,assets:T(e.assets).map(s=>{let o=E(s);return{id:p(o.id,"asset.id"),code:U(o.code),type:C(p(o.type,"asset.type"),me),name:p(o.name,"asset.name"),isBinary:Hn(o.isBinary,"asset.isBinary"),fieldNames:T(o.fieldNames).map(a=>p(a,"asset.fieldNames")),fileName:U(o.fileName),mimeType:U(o.mimeType),size:o.size===void 0||o.size===null?void 0:O(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:T(o.matchOrigins).map(a=>p(a,"asset.matchOrigins"))}}),participants:T(e.participants).map(s=>{let o=E(s);return{id:p(o.id,"participant.id"),displayName:p(o.displayName,"participant.displayName"),relationships:T(o.relationships).map(a=>C(p(a,"relationship"),Rt)),lifecycle:C(p(o.lifecycle,"participant.lifecycle"),Gn)}}),revealPolicy:(()=>{let s=E(e.revealPolicy);return{masterKeyRelease:C(p(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:C(p(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=E(e.dms);return{subjectEmail:p(s.subjectEmail,"dms.subjectEmail"),countdownDays:O(s.countdownDays,"dms.countdownDays"),countdownHours:O(s.countdownHours,"dms.countdownHours"),countdownMinutes:O(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:C(p(n.system,"source.system"),["INHERITI_BUSINESS"]),status:C(p(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function se(r){let e=E(r);return{operationId:p(e.operationId,"operationId"),stage:C(p(e.stage,"stage"),at),outcome:C(p(e.outcome,"outcome"),$n),planId:U(e.planId),lastErrorCode:U(e.lastErrorCode),participants:e.participants===void 0?void 0:T(e.participants).map(t=>{let n=E(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:T(n.relationships).map(i=>Bn(p(i,"relationship"),Rt))}})}}function Et(r){let e=E(r),t=E(e.assetSummary),n=E(e.governance),i=E(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:U(e.description),status:C(p(e.status,"status"),Fn),createdAt:p(e.createdAt,"createdAt"),configuredAt:U(e.configuredAt),assetSummary:{count:O(t.count,"assetSummary.count"),types:T(t.types).map(s=>C(p(s,"assetType"),me)),names:Pt(t.names).map(s=>p(s,"assetSummary.names"))},governance:{mode:C(p(n.mode,"governance.mode"),qn),minimumApprovals:O(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:O(i.owners,"owners"),mergers:O(i.mergers,"mergers"),moderators:O(i.moderators,"moderators")},authentication:Pt(e.authentication).map(s=>{let o=E(s);return{id:C(p(o.id,"authentication.id"),zn),status:C(p(o.status,"authentication.status"),Vn)}})}}function C(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Bn(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 Pt(r){return r==null?[]:T(r)}function T(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 U(r){return r==null?void 0:p(r,"optional")}function O(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Hn(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var Q=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function St(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 Wn(r,e){if(!e){if(r.length===0)throw new Q("organization_required");if(r.length>1)throw new Q("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new Q("organization_access_denied");return e}function jn(r){let e=h(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:g(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:g(e.participantRevision,1),createdAt:_(e.createdAt),...xt(e)}}function xt(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=h(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:d(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:_(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=h(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:_(i.revealedAt)}:{}}})}:{}}})}}function _t(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(jn),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 Ct(r){let e=h(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:d(e.parentId),sequence:g(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:g(e.participantRevision,1),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:g(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=h(t);return{unitId:d(n.unitId),position:g(n.position,0),commitment:d(n.commitment),status:d(n.status)}})}}function He(r){let e=h(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:g(e.sequence,1),status:e.status}}function Tt(r){let e=h(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),parentId:d(e.parentId),participantRevision:g(e.participantRevision,1),recipients:e.recipients.map(We)}}function Ot(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(t);return{parentId:d(n.parentId),sequence:g(n.sequence,1),senderMemberId:d(n.senderMemberId),senderDeviceId:d(n.senderDeviceId),participantRevision:g(n.participantRevision,1),createdAt:_(n.createdAt),...xt(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 Dt(r){return{readThroughSequence:g(h(r).readThroughSequence,0)}}function Mt(r){return{clearedThroughSequence:g(h(r).clearedThroughSequence,0)}}function Nt(r){let e=h(r);return{parentId:d(e.parentId),sequence:g(e.sequence,1),senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:g(e.participantRevision,1),canonicalManifest:d(e.canonicalManifest),frame:d(e.frame),signature:d(e.signature),wrappedContentKey:d(e.wrappedContentKey),senderSigningPublicKey:d(e.senderSigningPublicKey)}}function h(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function d(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function _(r){let e=d(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 We(r){let e=h(r);return{memberId:d(e.memberId),deviceId:d(e.deviceId),deviceVersion:g(e.deviceVersion,1),encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint)}}function Z(r){let e=h(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:d(e.id),tenantId:d(e.tenantId),memberId:d(e.memberId),version:e.version,encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint),status:e.status,createdAt:_(e.createdAt),updatedAt:_(e.updatedAt)}}function Re(r){let e=h(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:d(e.id),tenantId:d(e.tenantId),creatorMemberId:d(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(d),participantRevision:e.participantRevision,status:e.status,createdAt:_(e.createdAt),updatedAt:_(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=h(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:d(n.senderMemberId),createdAt:_(n.createdAt)}}return t}function kt(r){let e=h(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(Re),total:e.total,limit:e.limit,offset:e.offset}}function Kt(r){let e=h(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=We(t);return{memberId:n.memberId,name:d(h(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 Ut(r){let e=h(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=h(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:d(n.memberId),name:d(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:d(h(n.profilePicture).url)}}}}),limit:g(e.limit,1),offset:g(e.offset,0),nextOffset:e.nextOffset===null?null:g(e.nextOffset,0)}}function Lt(r){let e=h(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:d(e.conversationId),messageId:d(e.messageId),participantRevision:g(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(We),shareLayers:e.shareLayers.map(t=>{let n=h(t),i=d(n.id),s=d(n.dataShareId),o=d(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:d(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 be(r){let e=h(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:d(e.messageId),status:e.status}}function Ft(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(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:d(n.id),status:n.status,senderMemberId:d(n.senderMemberId),senderDeviceId:d(n.senderDeviceId),createdAt:_(n.createdAt),updatedAt:_(n.updatedAt),expiresAt:_(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=h(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:d(o.memberId),status:o.status,...o.consumedAt!==void 0?{consumedAt:o.consumedAt===null?null:_(o.consumedAt)}:{}}})),i}),total:g(e.total,0),limit:g(e.limit,1),offset:g(e.offset,0)}}function qt(r){let e=h(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:_(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:g(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(t=>{let n=h(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:g(n.index,0),shareId:d(n.shareId),layerId:d(n.layerId),ciphertext:d(n.ciphertext)}})}}function Gt(r){let e=h(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:_(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:g(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(t=>{let n=h(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:g(n.index,0),shareId:d(n.shareId),layerId:d(n.layerId)}})}}function H(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 W(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var D=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}},Ae=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:Z(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:Z(n)}async registerInboxDevice(e){return Z(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return Z(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return Z(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Re(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Re(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 kt(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 Ut(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Lt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Tt(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 be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return He(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return He(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 _t(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 Ct(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 Mt(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 Ot(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 Dt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return be(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),l=await we(a,s);if(!l.ok||l.result?.shareId!==n||l.result.status!=="STORED")throw new D(a.status,H(l),W(l),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return be(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 Gt(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}),l=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${a}`,c=await this.requestBinary(l,"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 v=c.body.getReader(),P=[],x=0;try{for(;;){o?.throwIfAborted();let R=await v.read();if(R.done)break;if(x+=R.value.length,x>14*1024*1024)throw new Error("invalid_inbox_share_size");P.push(R.value)}}catch(R){throw await v.cancel().catch(()=>{}),R}let b=new Uint8Array(x),A=0;for(let R of P)b.set(R,A),A+=R.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 Ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return qt(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(St)}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 bt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Pe(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 wt(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){$(e);let{idempotencyKey:t,...n}=e;return se(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return se(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return X(t),se(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return se(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 l=new Headers({"x-elements-environment":this.environment});a&&l.set("authorization",`Bearer ${a}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&l.set("x-organization-id",this.business.organizationId),i?.requestId&&l.set("x-elements-step-up-request",i.requestId);for(let[x,b]of Object.entries(s??{}))l.set(x,b);n&&l.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,u={method:t,headers:l,body:n?JSON.stringify(n):void 0};o&&(u.signal=o);let v=await this.transport(new URL(e,c),u);o?.throwIfAborted();let P=await we(v,o);if(o?.throwIfAborted(),!v.ok)throw new D(v.status,H(P),W(P),v.headers.get("x-request-id")??void 0);if(!P.ok||P.result===void 0)throw new D(v.status,H(P),W(P),v.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}/`,l=await this.transport(new URL(e,a),{method:t,headers:o,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!l.ok){let c=await we(l,i);throw new D(l.status,H(c),W(c),l.headers.get("x-request-id")??void 0)}return l}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[v,P]of Object.entries(n??{}))a.set(v,P);t&&a.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,l),{method:i,headers:a,body:t?JSON.stringify(t):void 0,signal:s}),u=await we(c,s);if(s?.throwIfAborted(),!c.ok||!u.ok)throw new D(c.status,H(u),W(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 D(400,"organization_selection_required")}};async function we(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}var je=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 Pe(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 l=new Headers({authorization:`Bearer ${a}`,...s});n!==void 0&&l.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:l,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 D(c.status,u&&H(u),u&&W(u));return u?.result}};function Yn(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=ee(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new z({api:{startRelaySession:a=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,a),readRelaySession:(a,l)=>r.api.readMasterKeyRelaySession(a,l),cancelRelaySession:(a,l)=>r.api.cancelMasterKeyRelaySession(a,l)}});return new B(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(a,l,c)=>{if(a.system!==i.system||a.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(l,c)}}}).openReveal(e,t)}}}async function zt(r,e){if(!e)throw new Error("master_key_required");let t=Xn(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Qn(r),s=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,o);return Zn(new Uint8Array(a))}function Xn(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 Qn(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 Zn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Ye=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}};import{MergeProcessReconciliationLoop as Jn}from"@safetech/inheriti-core-sdk/shared-configuration";var er=new Set(["COMPLETED","ABORTED","EXPIRED"]),Xe=class{constructor(e,t=new Ee,n=new Se,i=Math.random){this.api=e;this.loop=new Jn(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),l=a.approvalProcess?.status??"",c=tr(a);n!==void 0&&c!==n&&await t.onProcessUpdated?.(),i!==void 0&&l!==i&&await t.onApprovalUpdated?.(),n=c,i=l;let u=er.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 v=await this.api.getCustodianShare(e);"status"in v||(s=!0,await t.onCustodianShareReceived?.(e,v))}return{transitionKey:c,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,o)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function tr(r){return`${r.status}:${r.approvalProcess?.status??""}`}var Ee=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)})}},Se=class{join(e,t){let n=!0;return{isOwner:()=>n,requestReconciliation:()=>{n&&t.onReconciliationRequested()},publishReconciled:()=>{},leave:()=>{n=!1}}}};var Vt=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){oe(e.signal),rr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return oe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){oe(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(oe(e.signal),!i.custodianPair)throw new S("custodian_share_required");let s=Qe(i.keyShards),o=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),a=await this.sealer.encryptShares(Qe(i.dataShards),o.symmetricKeyBase64),l=await this.sealer.encryptShares(Qe(i.backupShards),o.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,o.symmetricKeyBase64);return oe(e.signal),{protectionProtocol:i.protocol,validatorShares:Ze(o.encryptedShares),dataShards:Ze(a.encryptedShares),backupShards:Ze(l.encryptedShares),encryptedKey:o.encryptedKey,assetsMetadata:nr(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:Je(n.encryptedShares[0]),dataShard:Je(n.encryptedShares[1])}}};function Qe(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Ze(r){return r.map(Je)}function Je(r){return{id:r.id,data:r.encryptedData}}function nr(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new S("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 rr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new S("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new S("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new S("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 S("plan_secrets_declaration_mismatch")}}function oe(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 xe=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))}},_e=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 ae=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},le=class extends ae{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},f=class extends ae{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function et(r){if(r instanceof ae)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Bt=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:G(n,"issuer"),authorizationEndpoint:G(n,"authorization_endpoint"),tokenEndpoint:G(n,"token_endpoint"),deviceAuthorizationEndpoint:N(n,"device_authorization_endpoint"),endSessionEndpoint:N(n,"end_session_endpoint"),revocationEndpoint:N(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:G(t,"device_code"),userCode:G(t,"user_code"),verificationUri:G(t,"verification_uri"),verificationUriComplete:N(t,"verification_uri_complete"),expiresInSeconds:Ht(t,"expires_in"),intervalSeconds:tt(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 token(e,t){let n=await this.form(e,t);return{accessToken:G(n,"access_token"),refreshToken:N(n,"refresh_token"),idToken:N(n,"id_token"),tokenType:G(n,"token_type"),expiresInSeconds:Ht(n,"expires_in"),refreshExpiresInSeconds:tt(n,"refresh_expires_in"),scope:N(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=N(i,"error")??`oauth_http_${n.status}`;throw new f(s,N(i,"error_description")??s)}return i}};function G(r,e){let t=N(r,e);if(!t)throw new f("invalid_oauth_response",`Missing ${e}`);return t}function N(r,e){return typeof r[e]=="string"?r[e]:void 0}function Ht(r,e){let t=tt(r,e);if(t===void 0)throw new f("invalid_oauth_response",`Missing ${e}`);return t}function tt(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var ir=600*1e3,Ce=5,sr=5,Wt=class{constructor(e){this.options=e;this.crypto=e.crypto??new xe,this.clock=e.clock??new _e}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()+ir;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 l=new URL(t.authorizationEndpoint);return l.searchParams.set("response_type","code"),l.searchParams.set("client_id",this.options.configuration.clientId),l.searchParams.set("redirect_uri",this.options.configuration.redirectUri),l.searchParams.set("scope",this.options.configuration.scopes.join(" ")),l.searchParams.set("state",n),l.searchParams.set("nonce",i),l.searchParams.set("code_challenge",o),l.searchParams.set("code_challenge_method","S256"),e?.prompt&&l.searchParams.set("prompt",e.prompt),{authorizationUrl:l.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 f("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new f("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new f("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new f("state_mismatch");let o=i.searchParams.get("error");if(o)throw new f(o,i.searchParams.get("error_description")??o);let a=i.searchParams.get("code");if(!a)throw new f("authorization_code_missing");let l=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:l.tokenEndpoint,clientId:this.options.configuration.clientId,code:a,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),u=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(u),u}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new f("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(Ce,t.intervalSeconds??Ce),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 f("device_transaction_missing");let i=n,s=await this.getDiscovery(),o=Math.max(Ce,i.intervalSeconds??Ce),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 l=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(l);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(l){let c=et(l);if(c==="authorization_pending"){a=this.clock.now()+o*1e3;continue}if(c==="slow_down"){o+=sr,a=this.clock.now()+o*1e3;continue}throw await this.options.transactions.remove(t),l}}throw await this.options.transactions.remove(t),new f("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new le;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=et(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new le):(this.isOfflineSession(e)||await this.options.sessions.clear(),n)}try{if(!t.refreshToken)throw new f("refresh_token_rotation_missing");let n=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(n),n}catch(n){throw await this.options.sessions.clear(),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(j(e.issuer)!==j(this.options.configuration.issuer))throw new f("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}|${j(t)}|${n}|${i}`}async acceptTokens(e,t,n){if(e.tokenType.toLowerCase()!=="bearer")throw new f("unsupported_token_type");let i=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(i,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new f("id_token_validation_required");let a=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(a,t),a.subject!==i.subject||a.sessionId!==i.sessionId)throw new f("token_subject_mismatch")}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"));return{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}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(j(e.issuer)!==j(i.issuer))throw new f("issuer_mismatch");if(!s.includes(i.audience))throw new f("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new f("client_mismatch");if(e.environment!==i.environment)throw new f("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new f("required_claim_missing");if(n&&e.nonce!==t)throw new f("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(j(e.issuer)!==j(n.issuer))throw new f("issuer_mismatch");if(!i.includes(n.clientId))throw new f("client_mismatch");if(e.authorizedParty!==n.clientId)throw new f("client_mismatch");if(!e.subject||!e.sessionId)throw new f("required_claim_missing");if(e.nonce!==t)throw new f("nonce_mismatch")}};function j(r){return r.replace(/\/+$/u,"")}var jt=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{Q as BusinessOrganizationSelectionError,me as CANONICAL_PLAN_ASSET_TYPES,Ue as CANONICAL_STRUCTURED_ASSET_FIELDS,Vt as CorePlanMaterialBuilder,m as ElementsApiPortRequired,D as ElementsApiRequestFailed,B as ElementsClient,ye as GuidedCreateRecoveryError,fe as GuidedPlanCreator,Ee as HostProcessRuntimeEnvironment,je as HttpAutomationRevealApiPort,Ae as HttpElementsApiPort,Bt as HttpOperatorAuthTransport,it as InheritiClientProvider,Un as InheritiFileInvalid,y as InvalidPlanDeclaration,S as InvalidPlanMaterial,Se as LocalProcessReconciliationOwnership,Be as MAX_INHERITI_FILE_BYTES,pe as MasterKeyRelayCancellationFailed,ce as MasterKeyRelayExpired,de as MasterKeyRelayTimedOut,k as MasterKeyRequired,he as MemoryGuidedCreateCheckpointStore,te as MemoryKeyVault,ne as MemoryStatePort,f as OAuthProtocolError,Wt as OperatorAuthClient,ae as OperatorAuthError,le as OperatorReauthenticationRequired,jt as OperatorSessionController,at as PLAN_CREATION_SERVER_STAGES,Ye as PlanMaterialReconstructionFailed,ie as PlanMaterialReconstructorRequired,Xe as PollingSharedPlanEventListener,z as RelayMasterKeySource,re as RevealActionsNotOpen,w as RevealFieldAccessError,Ie as RevealHandleClosed,ps as SDKContainer,ke as StaticMasterKeyResolver,_e as SystemOAuthClock,xe as WebOAuthCrypto,Yn as createAutomationRevealClient,On as createElementsClient,ue as createMasterKeyResolver,Ln as exportProtectedRevealAsset,Ve as generateInheritiFileKey,pn as getAvailableEnvs,ee as masterKeyRefFor,F as masterKeyRefKey,et as oauthErrorCode,Kn as openInheritiFile,ti as openInheritiFileKey,yt as parseAssetFieldSelector,kn as readInheritiFileHeader,ht as revealPhaseOf,$e as sealInheritiFile,vt as sealInheritiFileKey,Wn as selectBusinessOrganization,zt as unwrapDekWithMasterKey,st as useClient,$ as validatePlanCreationInput,X as validatePlanCreationMaterial};