@safetech/inheriti-client-sdk 1.17.28 → 1.17.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/automation.js +1 -1
- package/dist/browser.js +1 -1
- package/dist/inbox.js +1 -1
- package/dist/index.js +1 -1
- package/dist/inheriti-client-sdk.umd.js +41 -41
- package/dist/node-base.js +1 -1
- package/dist/node.js +1 -1
- package/dist/sdk-types.d.ts +103 -1
- package/dist/src/elements/elements-api-port.d.ts +4 -0
- package/dist/src/elements/elements-client.d.ts +5 -0
- package/dist/src/elements/http-elements-api-port.d.ts +6 -0
- package/dist/src/elements/index.d.ts +1 -0
- package/dist/src/elements/organization-queries.d.ts +92 -0
- package/dist/src/elements/plan-operations.d.ts +1 -0
- package/package.json +1 -1
package/dist/browser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeAssetContainer as Un}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as Dt,generateRSAOAEPKeyPair as Nt}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"}},ue=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},pe=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},Q=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 Nt();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),o=this.options.pollIntervalMs??2e3,a=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(A=>new Promise(b=>setTimeout(b,A))),l=!0,p=!1,v,P=()=>v??=(async()=>{let A=new AbortController,b,kt=new Promise((Kn,Mt)=>{b=setTimeout(()=>{A.abort(),Mt(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),kt])}finally{clearTimeout(b)}})(),T,M=new Promise((A,b)=>{T=()=>{l&&P().catch(()=>{}),b(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",T,{once:!0})});M.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),p=!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),M]);if(A.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(A.status==="DELIVERED"&&A.sealedMasterKey){let b=(await Dt(A.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(b))throw new Error("invalid_master_key_material");return b}if(A.status==="EXPIRED")throw new ue(s.sessionId);await Ut(d,o,e)}throw new le(s.sessionId)}catch(A){if(l&&(!p||e?.aborted))try{await P()}catch(b){if(e?.aborted)throw new pe(b)}throw A}finally{T&&e?.removeEventListener("abort",T)}}};async function Ut(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function me(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||Te(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(Kt(e,r.applicationId)){let i=await r.source?.resolve();return i||Te(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Te(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function Kt(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Te(r,e,t,n,i){if((await e()).relayAvailable)return new Q({...r.relay,api:Lt(r.api,t)}).resolve(n,i)}function Lt(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 G(r){return`${r.system}:${r.contextId}`}function ke(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var U=class extends Error{constructor(t){super(`master_key_required:${G(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Oe=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(G(e),t),this}async resolve(e){return this.sources.get(G(e))?.resolve()}};var Z=class{keys=new Map;async store(e,t){let n=G(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(G(e))?.slice()}async remove(e){let t=G(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var J=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 ge=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},g=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var ee=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var he=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],De={"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"]},We=["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"}},K=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function H(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new K("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 K("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new K("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new K("material_operation_invalid")}function Me(r,e){if(!Array.isArray(r))throw new K(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new K(e);if(t.data!==void 0&&typeof t.data!="string")throw new K(e)}}function $(r){if(z(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Gt(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(z(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),!he.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(Ft(t.matchOrigins),!t.isBinary){let s=De[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(z(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!je(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")}qt(r)}function Ft(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 qt(r){let e=r.policy;if(e&&z(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"){z(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){z(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;z(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!je(t.subjectEmail))throw new y("dms_subject_invalid");if(!r.participants.some(s=>He(s.routingEmail)===He(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 Gt(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 je(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function He(r){return r.normalize("NFC").trim().toLowerCase()}function z(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new y(t)}var ye=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)}},Ie=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),$(e),fe(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 ve("creation_checkpoint_missing");if(o.idempotencyKey!==t.idempotencyKey||o.declarationHash!==await Ye(t))throw new ve("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;fe(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:a.planId,declaration:t,secrets:n,signal:s.signal});fe(s.signal),s.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:a.planId,declaration:t,encrypted:d,signal:s.signal});fe(s.signal),H(l);let p=await this.api.supplyPlanCreationMaterial(e,l);return s.onProgress?.(p.stage),p.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,p),p}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 Ye(e),serverStage:t.stage})}},ve=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Ye(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 fe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Xe(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new ge(n.stage);return r.authorizeRevealAction(e,t)}function Bt(r){let e=r?.status;return e===400||e===401||e===403}async function Qe(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Bt(s))throw s}return r.releaseRevealMaterial(e,t)}function tt(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"?zt(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":Vt.has(r.stage)?"ENDED":"CONTINUING"}var Vt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function zt(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 Pe=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 Ue(r,e,t={},n=!1){if(t.signal?.aborted)throw I();let i=await r.getPlan(e),s=await r.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Ze(s.id);if(t.signal?.aborted)throw I();let o=()=>r.prepareReveal(e,t.signal,async p=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(p)});if(n||await o(),t.signal?.aborted)throw I();let a=t.idempotencyKey??crypto.randomUUID(),d;try{d=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(p){if(p?.code!=="merge_process_already_active")throw p;let v=await r.getActivePlanReveal(e);throw!v||v.planId!==e||v.mode!==(t.mode??"DIRECT")||v.protectedCopy!==void 0&&v.protectedCopy!==(t.protectedCopy??!1)?p:Ze(v.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let l;try{if(t.signal?.aborted)throw I();let p=await Ht(r,d,t);if(t.signal?.aborted||(n&&await o(),t.signal?.aborted)||(B(t,"RELEASING_MATERIAL",p),t.signal?.aborted))throw I();let v=await r.releaseRevealMaterial(p.id,p.materialVersion??"1");if(t.signal?.aborted||(p.mode==="GOVERNED"&&await r.markRevealSharesCollected(p.id),t.signal?.aborted))throw I();let P;try{P=await Yt(r,p,Qt(v),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(B(t,"RECONSTRUCTING",p),t.signal?.aborted))throw I();try{l=await r.reconstructPlanMaterial(P)}catch(M){throw t.signal?.aborted?I():(await r.reportRevealReconstruction(p.id,{status:"FAILED",errorCode:jt(M)}),M)}if(t.signal?.aborted)throw I();let T=await r.reportRevealReconstruction(p.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(B(t,"OPEN",T),t.signal?.aborted))throw I();return new Ne(r,T,i,l,t.signal)}catch(p){throw l?.fill(0),await rt(r,d.id,t.signal?.aborted?"CANCELED":"ERROR"),p}}function Ze(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var $t=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Ht(r,e,t){let n=await L(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw I();if(t.onSession?.(n),t.onProgress?.({phase:tt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if($t.has(n.stage))throw new be(n.stage);await Ke(t.pollIntervalMs??1500,t.signal),n=await L(()=>r.getReveal(e.id,t.signal),t.signal)}}var be=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function B(r,e,t){r.onProgress?.({phase:e,session:t})}function Ke(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 Ne=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 Pe;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=nt(s),d=this.plan.assets.find(l=>(l.code??l.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:Wt(a.data,o.field,o.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(o=>this.reportAction(o.id,"FAILED",Je(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",Je(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=rt(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 nt(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 Wt(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"?De[t]:void 0)?.includes(e))return"";throw new R("asset_value_invalid")}return n[e]}function Je(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 jt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Yt(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await L(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Re;let l=await L(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(et(l,i.id,e.planId),!l.shares.includes(i.data))throw new D;B(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:p}=await L(()=>n.proDevice.write(l,n.signal),n.signal);if(n.signal?.aborted)throw I();if(!p?.trim())throw new D;if(await r.claimRevealCustodianShare(e.id,l.id,p),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,l.id),n.signal?.aborted))throw I();return{...t,shares:t.shares.filter(v=>v!==i).concat(l.shares.map((v,P)=>({id:`${l.id}:${P}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:v})))}}if(d!=="SK_MOBILE")throw new D;if(n.signal?.aborted)throw I();return await r.distributeRevealCustodianShare(e.id),B(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await L(()=>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),B(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Ke(n.pollIntervalMs??1500,n.signal),s=await L(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Re;if(!s.shareId||!s.deviceId)throw new D;B(n,"CONNECTING_SAFEKEY_PRO",e);let d=await L(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw I();if(et(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new D;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw I();return{...t,shares:t.shares.concat(d.shares.map((l,p)=>({id:`${d.id}:${p}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new D;let o={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(o),B(n,"WAITING_FOR_CUSTODIAN",o),n.signal?.aborted)throw I();await r.requestRevealCustodianRelease(e.id);let a=await Xt(r,e,n);return Object.assign({},t,{shares:t.shares.concat(a.shares.map((d,l)=>({id:`${a.id}:${l}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function et(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 D}async function L(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 Xt(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new we;let s=await L(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new we;if(s&&s.status!=="PENDING"){let o=s;if(o.shares?.length)return o;throw new D}await Ke(t.pollIntervalMs??1500,t.signal)}}var D=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Re=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},we=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Qt(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function rt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(o){if(!Zt(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 Zt(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 te=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 Z,this.state=t.state??new J,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??tn(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 g;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new g;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new g;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new g;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return $(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new g;return H(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new ye){if(this.requireApplication(),!this.api)throw new g;return new Ie(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 U({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 en(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new U(e);return await this.keyVault.store(e,Jt(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new g;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 g;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new ee;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 U({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=ke(e);if(!i)throw new U({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new g;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new g;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new g;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new g;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new g;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new g;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new g;return this.api.getReveal(e,t)}openReveal(e,t){return Ue(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 g;return Qe(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new g;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new g;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new g;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new g;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new g;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new g;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new g;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new g;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new g;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new g;return Xe(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new g;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new g;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new g;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new g;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new g;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new g;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(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),o=i.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),a=i.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(l=>Object.assign({},l,{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 g;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 Se;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new U({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Se=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Jt(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 en(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function tn(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return me({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return me({...e,organizationId:r.organizationId})}import{createBrowserSsdpV2WorkerFactory as ln,createSsdpV2Processor as un}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function Le(r,e){if(!e)throw new Error("master_key_required");let t=nn(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=rn(r),s=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,o);return sn(new Uint8Array(a))}function nn(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function rn(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 sn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var ne=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await it("plan_key_unwrap_failed",()=>Le(e.planKey,t)),i=await crypto.subtle.importKey("raw",Fe(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],o=[];for(let a of e.shares){let d=await it("plan_share_decryption_failed",()=>cn(a.data,i));dn(a.shareType)?o.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:o}).result}catch(a){throw new Ae("plan_share_reconstruction_failed",an(a))}}},Ae=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},on=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function an(r){let e=r instanceof Error?r.message:void 0;if(e)return on.has(e)?e:void 0}async function it(r,e){try{return await e()}catch{throw new Ae(r)}}function dn(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function cn(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Fe(r.slice(0,t)),i=Fe(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function Fe(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var re=class extends ne{constructor(e={}){let t=e.processor??un(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:ln(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var pn=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],mn=["DIRECT","GOVERNED"],ot=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],gn=["ACTIVE","REVOKED"],hn=["SK_MOBILE"],fn=["ACTIVE","INACTIVE"],yn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function at(r){let e=w(r);return{items:O(e.items).map(ut),nextCursor:e.nextCursor===null?null:u(e.nextCursor,"nextCursor")}}function dt(r){let e=w(r);return{total:k(e.total,"total"),items:O(e.items).map(t=>{let n=w(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:u(n.id,"log.id"),planId:u(n.planId,"log.planId"),tenantId:u(n.tenantId,"log.tenantId"),event:u(n.event,"log.event"),occurredOn:u(n.occurredOn,"log.occurredOn"),status:F(n.status),title:u(n.title,"log.title"),details:O(n.details).map(i=>{let s=w(i);return{label:u(s.label,"log.detail.label"),value:u(s.value,"log.detail.value")}})}})}}function ct(r){let e=w(r);return{total:k(e.total,"total"),items:O(e.items).map(t=>{let n=w(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=u(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:u(n.id,"log.id"),memberId:u(n.memberId,"log.memberId"),source:i,event:u(n.event,"log.event"),occurredOn:u(n.occurredOn,"log.occurredOn"),status:F(n.status)}})}}function lt(r){let e=w(r),t=ut(e),n=w(e.source),i=u(n.kind,"source.kind");return{...t,assets:O(e.assets).map(s=>{let o=w(s);return{id:u(o.id,"asset.id"),code:F(o.code),type:C(u(o.type,"asset.type"),he),name:u(o.name,"asset.name"),isBinary:vn(o.isBinary,"asset.isBinary"),fieldNames:O(o.fieldNames).map(a=>u(a,"asset.fieldNames")),fileName:F(o.fileName),mimeType:F(o.mimeType),size:o.size===void 0||o.size===null?void 0:k(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:O(o.matchOrigins).map(a=>u(a,"asset.matchOrigins"))}}),participants:O(e.participants).map(s=>{let o=w(s);return{id:u(o.id,"participant.id"),displayName:u(o.displayName,"participant.displayName"),relationships:O(o.relationships).map(a=>C(u(a,"relationship"),ot)),lifecycle:C(u(o.lifecycle,"participant.lifecycle"),gn)}}),revealPolicy:(()=>{let s=w(e.revealPolicy);return{masterKeyRelease:C(u(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:C(u(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=w(e.dms);return{subjectEmail:u(s.subjectEmail,"dms.subjectEmail"),countdownDays:k(s.countdownDays,"dms.countdownDays"),countdownHours:k(s.countdownHours,"dms.countdownHours"),countdownMinutes:k(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:C(u(n.system,"source.system"),["INHERITI_BUSINESS"]),status:C(u(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ie(r){let e=w(r);return{operationId:u(e.operationId,"operationId"),stage:C(u(e.stage,"stage"),We),outcome:C(u(e.outcome,"outcome"),yn),planId:F(e.planId),lastErrorCode:F(e.lastErrorCode),participants:e.participants===void 0?void 0:O(e.participants).map(t=>{let n=w(t);return{clientParticipantRef:u(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:u(n.planParticipantId,"planParticipantId"),relationships:O(n.relationships).map(i=>In(u(i,"relationship"),ot))}})}}function ut(r){let e=w(r),t=w(e.assetSummary),n=w(e.governance),i=w(e.participantSummary);return{id:u(e.id,"id"),name:u(e.name,"name"),description:F(e.description),status:C(u(e.status,"status"),pn),createdAt:u(e.createdAt,"createdAt"),configuredAt:F(e.configuredAt),assetSummary:{count:k(t.count,"assetSummary.count"),types:O(t.types).map(s=>C(u(s,"assetType"),he)),names:st(t.names).map(s=>u(s,"assetSummary.names"))},governance:{mode:C(u(n.mode,"governance.mode"),mn),minimumApprovals:k(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:k(i.owners,"owners"),mergers:k(i.mergers,"mergers"),moderators:k(i.moderators,"moderators")},authentication:st(e.authentication).map(s=>{let o=w(s);return{id:C(u(o.id,"authentication.id"),hn),status:C(u(o.status,"authentication.status"),fn)}})}}function C(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function In(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 st(r){return r==null?[]:O(r)}function O(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function u(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function F(r){return r==null?void 0:u(r,"optional")}function k(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function vn(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var W=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function pt(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 Pn(r,e){if(!e){if(r.length===0)throw new W("organization_required");if(r.length>1)throw new W("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new W("organization_access_denied");return e}function bn(r){let e=f(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),createdAt:x(e.createdAt),...mt(e)}}function mt(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=f(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:c(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:x(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=f(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:h(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:x(i.revealedAt)}:{}}})}:{}}})}}function gt(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(bn),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0),unreadCount:h(e.unreadCount,0),readThroughSequence:h(e.readThroughSequence,0)}}function ht(r){let e=f(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=f(t);return{unitId:c(n.unitId),position:h(n.position,0),commitment:c(n.commitment),status:c(n.status)}})}}function qe(r){let e=f(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),status:e.status}}function ft(r){let e=f(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:c(e.conversationId),parentId:c(e.parentId),participantRevision:h(e.participantRevision,1),recipients:e.recipients.map(Ge)}}function yt(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);return{parentId:c(n.parentId),sequence:h(n.sequence,1),senderMemberId:c(n.senderMemberId),senderDeviceId:c(n.senderDeviceId),participantRevision:h(n.participantRevision,1),createdAt:x(n.createdAt),...mt(n)}}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0),unreadCount:h(e.unreadCount,0),readThroughSequence:h(e.readThroughSequence,0)}}function It(r){return{readThroughSequence:h(f(r).readThroughSequence,0)}}function vt(r){return{clearedThroughSequence:h(f(r).clearedThroughSequence,0)}}function Pt(r){let e=f(r);return{parentId:c(e.parentId),sequence:h(e.sequence,1),senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),canonicalManifest:c(e.canonicalManifest),frame:c(e.frame),signature:c(e.signature),wrappedContentKey:c(e.wrappedContentKey),senderSigningPublicKey:c(e.senderSigningPublicKey)}}function f(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function c(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function x(r){let e=c(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function h(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Ge(r){let e=f(r);return{memberId:c(e.memberId),deviceId:c(e.deviceId),deviceVersion:h(e.deviceVersion,1),encryptionPublicKey:c(e.encryptionPublicKey),encryptionKeyFingerprint:c(e.encryptionKeyFingerprint),signingPublicKey:c(e.signingPublicKey),signingKeyFingerprint:c(e.signingKeyFingerprint)}}function j(r){let e=f(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:c(e.id),tenantId:c(e.tenantId),memberId:c(e.memberId),version:e.version,encryptionPublicKey:c(e.encryptionPublicKey),encryptionKeyFingerprint:c(e.encryptionKeyFingerprint),signingPublicKey:c(e.signingPublicKey),signingKeyFingerprint:c(e.signingKeyFingerprint),status:e.status,createdAt:x(e.createdAt),updatedAt:x(e.updatedAt)}}function Ee(r){let e=f(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:c(e.id),tenantId:c(e.tenantId),creatorMemberId:c(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(c),participantRevision:e.participantRevision,status:e.status,createdAt:x(e.createdAt),updatedAt:x(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=f(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:c(n.senderMemberId),createdAt:x(n.createdAt)}}return t}function bt(r){let e=f(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(Ee),total:e.total,limit:e.limit,offset:e.offset}}function Rt(r){let e=f(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Ge(t);return{memberId:n.memberId,name:c(f(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function wt(r){let e=f(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:c(n.memberId),name:c(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:c(f(n.profilePicture).url)}}}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function St(r){let e=f(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:c(e.conversationId),messageId:c(e.messageId),participantRevision:h(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Ge),shareLayers:e.shareLayers.map(t=>{let n=f(t),i=c(n.id),s=c(n.dataShareId),o=c(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:c(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 _e(r){let e=f(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:c(e.messageId),status:e.status}}function At(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:c(n.id),status:n.status,senderMemberId:c(n.senderMemberId),senderDeviceId:c(n.senderDeviceId),createdAt:x(n.createdAt),updatedAt:x(n.updatedAt),expiresAt:x(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let o=f(s);if(o.status!=="UNREAD"&&o.status!=="LEASED"&&o.status!=="CONSUMED"&&o.status!=="EXPIRED"&&o.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:c(o.memberId),status:o.status,...o.consumedAt!==void 0?{consumedAt:o.consumedAt===null?null:x(o.consumedAt)}:{}}})),i}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0)}}function Et(r){let e=f(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:c(e.leaseId),leaseExpiresAt:x(e.leaseExpiresAt),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),tenantWrappedShareKey:c(e.tenantWrappedShareKey),wrappedContentKey:c(e.wrappedContentKey),shares:e.shares.map(t=>{let n=f(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:h(n.index,0),shareId:c(n.shareId),layerId:c(n.layerId),ciphertext:c(n.ciphertext)}})}}function _t(r){let e=f(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:c(e.leaseId),leaseExpiresAt:x(e.leaseExpiresAt),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),tenantWrappedShareKey:c(e.tenantWrappedShareKey),wrappedContentKey:c(e.wrappedContentKey),shares:e.shares.map(t=>{let n=f(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:h(n.index,0),shareId:c(n.shareId),layerId:c(n.layerId)}})}}function se(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 oe(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var q=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}},Y=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:j(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:j(n)}async registerInboxDevice(e){return j(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return j(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return j(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Ee(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Ee(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 bt(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 Rt(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 wt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return St(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return ft(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 _e(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return qe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return qe(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 gt(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 ht(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 vt(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 yt(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 Pt(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 It(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return _e(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 xe(a,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new q(a.status,se(d),oe(d),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return _e(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 _t(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}`,l=await this.requestBinary(d,"GET",void 0,o);if(!l.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let p=Number(l.headers.get("content-length"));if(Number.isFinite(p)&&p>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!l.body)throw new Error("invalid_inbox_share_response");let v=l.body.getReader(),P=[],T=0;try{for(;;){o?.throwIfAborted();let b=await v.read();if(b.done)break;if(T+=b.value.length,T>14*1024*1024)throw new Error("invalid_inbox_share_size");P.push(b.value)}}catch(b){throw await v.cancel().catch(()=>{}),b}let M=new Uint8Array(T),A=0;for(let b of P)M.set(b,A),A+=b.length;return M}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 At(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return Et(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(pt)}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 at(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return lt(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 dt(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 ct(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){$(e);let{idempotencyKey:t,...n}=e;return ie(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ie(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return H(t),ie(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ie(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,M]of Object.entries(s??{}))d.set(T,M);n&&d.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,p={method:t,headers:d,body:n?JSON.stringify(n):void 0};o&&(p.signal=o);let v=await this.transport(new URL(e,l),p);o?.throwIfAborted();let P=await xe(v,o);if(o?.throwIfAborted(),!v.ok)throw new q(v.status,se(P),oe(P),v.headers.get("x-request-id")??void 0);if(!P.ok||P.result===void 0)throw new q(v.status,se(P),oe(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}/`,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 l=await xe(d,i);throw new q(d.status,se(l),oe(l),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});o&&a.set("authorization",`Bearer ${o}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId);for(let[v,P]of Object.entries(n??{}))a.set(v,P);t&&a.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,d),{method:i,headers:a,body:t?JSON.stringify(t):void 0,signal:s}),p=await xe(l,s);if(s?.throwIfAborted(),!l.ok||!p.ok)throw new q(l.status,se(p),oe(p),l.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 q(400,"organization_selection_required")}};async function xe(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{PassphraseMasterKeySource as Zr,RawMasterKeySource as Jr,computePassphraseVerifier as ei,deriveMasterKey as ti,generateHexSeed as ni}from"@safetech/inheriti-core-sdk/crypto";import{generateInheritiFileKey as Rn,sealInheritiFile as wn,readInheritiFileHeader as Sn,openInheritiFile as An,InheritiFileInvalid as En,MAX_INHERITI_FILE_BYTES as _n}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as xn,openInheritiFileKey as Cn}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";function xt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var ae=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),xt(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return xt(new Uint8Array(t))}},de=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 X=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},E=class extends X{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},m=class extends X{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function ce(r){if(r instanceof X)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Be=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:S(n,"issuer"),authorizationEndpoint:S(n,"authorization_endpoint"),tokenEndpoint:S(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:S(t,"device_code"),userCode:S(t,"user_code"),verificationUri:S(t,"verification_uri"),verificationUriComplete:N(t,"verification_uri_complete"),expiresInSeconds:Ct(t,"expires_in"),intervalSeconds:Ve(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async revoke(e){let t=await this.http(new URL(e.endpoint),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,token:e.refreshToken,token_type_hint:"refresh_token"}),signal:e.signal});if(!t.ok)throw new m(`oauth_http_${t.status}`)}async exchangeBusinessSession(e){return this.businessSession(e.apiUrl,"exchange",{providerAccessToken:e.providerAccessToken})}async refreshBusinessSession(e){return this.businessSession(e.apiUrl,"refresh",{refreshToken:e.refreshToken})}async revokeBusinessSession(e){await this.businessRequest(e.apiUrl,"revoke",{refreshToken:e.refreshToken},e.signal)}async businessSession(e,t,n){let i=await this.businessRequest(e,t,n);return{accessToken:S(i,"accessToken"),refreshToken:S(i,"refreshToken"),accessExpiresAt:S(i,"accessExpiresAt"),sessionExpiresAt:S(i,"sessionExpiresAt"),familyId:S(i,"familyId"),environment:On(i,"environment"),clientId:S(i,"clientId"),providerIssuer:S(i,"providerIssuer"),providerSubject:S(i,"providerSubject")}}async businessRequest(e,t,n,i){let s=e.endsWith("/")?e:`${e}/`,o=new URL(`operator-sessions/${t}`,s),a=await this.http(o,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"omit",signal:i,body:JSON.stringify(n)}),d={};try{d=await a.json()}catch{}if(!a.ok)throw new m(`business_http_${a.status}`);if(d.ok!==!0||!Tn(d.result))throw new m("invalid_business_response");return d.result}async token(e,t){let n=await this.form(e,t);return{accessToken:S(n,"access_token"),refreshToken:N(n,"refresh_token"),idToken:N(n,"id_token"),tokenType:S(n,"token_type"),expiresInSeconds:Ct(n,"expires_in"),refreshExpiresInSeconds:Ve(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 m(s,N(i,"error_description")??s)}return i}};function Tn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function On(r,e){let t=S(r,e);if(t!=="TEST"&&t!=="LIVE")throw new m("invalid_business_response");return t}function S(r,e){let t=N(r,e);if(!t)throw new m("invalid_oauth_response",`Missing ${e}`);return t}function N(r,e){return typeof r[e]=="string"?r[e]:void 0}function Ct(r,e){let t=Ve(r,e);if(t===void 0)throw new m("invalid_oauth_response",`Missing ${e}`);return t}function Ve(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var kn=600*1e3,Ce=5,Mn=5,Tt=5e3,Dn=new WeakMap,Nn=new WeakMap;async function Ot(r,e,t){let n=r.get(e),i,s=new Promise(o=>{i=o});r.set(e,s),n&&await n;try{return await t()}finally{r.get(e)===s&&r.delete(e),i()}}function V(r,e){return Ot(Dn,r,e)}var ze=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new m("business_api_url_required");this.crypto=e.crypto??new ae,this.clock=e.clock??new de}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()+kn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:a});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",o),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:a}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new m("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new m("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new m("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new m("state_mismatch");let o=i.searchParams.get("error");if(o)throw new m(o,i.searchParams.get("error_description")??o);let a=i.searchParams.get("code");if(!a)throw new m("authorization_code_missing");let d=await this.getDiscovery(),l=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:a,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),p=await this.acceptTokens(l,n.nonce);return await V(this.options.sessions,()=>this.options.sessions.save(p)),p}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new m("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 m("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 l=await this.acceptTokens(d);return await V(this.options.sessions,()=>this.options.sessions.save(l)),await this.options.transactions.remove(t),l}catch(d){let l=ce(d);if(l==="authorization_pending"){a=this.clock.now()+o*1e3;continue}if(l==="slow_down"){o+=Mn,a=this.clock.now()+o*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new m("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e){if(this.isSafeIdBusinessMode()&&!this.isValidSafeIdBusinessSession(e))throw await this.clearIfUnchanged(e),new E;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new E;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new E;return e.expiresAt>this.clock.now()?e.accessToken:(await this.refreshExpired(e)).accessToken}}refresh(){return this.refreshExpired()}refreshExpired(e){if(this.refreshFlight)return this.refreshFlight;let t=this.performRefresh(e).finally(()=>{this.refreshFlight===t&&(this.refreshFlight=void 0)});return this.refreshFlight=t,t}async clear(){let e;if(await V(this.options.sessions,async()=>{try{e=await this.options.sessions.load()}finally{await this.options.sessions.clear()}}),this.isSafeIdBusinessMode()&&e&&this.isValidSafeIdBusinessSession(e)&&e.refreshToken){let i=new AbortController,s;try{await Promise.race([(async()=>{let o=await this.getDiscovery();o.revocationEndpoint&&this.options.transport.revoke&&await this.options.transport.revoke({endpoint:o.revocationEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken,signal:i.signal})})(),new Promise((o,a)=>{s=setTimeout(()=>{i.abort(),this.discovery=void 0,a(new m("provider_revoke_timeout"))},Tt)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,n;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{n=setTimeout(()=>{t.abort(),s(new m("business_revoke_timeout"))},Tt)})])}finally{n&&clearTimeout(n)}}async performRefresh(e){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.performProviderRefresh(e);let t=await this.options.sessions.load();if(!t||!this.isValidBusinessSession(t))throw t&&await this.clearIfUnchanged(t),new E;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new E;let n;try{n=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=ce(i);if(s==="business_http_409"){let o=await V(this.options.sessions,async()=>{let a=await this.options.sessions.load();if(a&&this.isValidBusinessSession(a)&&a.refreshToken!==t.refreshToken&&a.familyId===t.familyId&&a.principal.subject===t.principal.subject)return a;a&&this.sameCredential(a,t)&&await this.options.sessions.clear()});if(o)return o;throw new E}throw s==="business_http_401"?(await this.clearIfCurrent(t),new E):i}try{let i=this.businessSession(n,t.principal,t);if(i.refreshToken===t.refreshToken)throw new m("refresh_token_rotation_missing");return await V(this.options.sessions,async()=>{let s=await this.options.sessions.load();if(s&&this.isValidBusinessSession(s)&&s.familyId===t.familyId&&s.principal.subject===t.principal.subject&&s.refreshToken!==t.refreshToken)return s;if(!s||!this.sameCredential(s,t))throw new E;return await this.options.sessions.save(i),i})}catch(i){throw await this.clearIfCurrent(t),i}}sameCredential(e,t){return this.isValidBusinessSession(e)&&e.familyId===t.familyId&&e.refreshToken===t.refreshToken&&e.principal.subject===t.principal.subject}async clearIfUnchanged(e){await V(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&t.kind===e.kind&&t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.principal?.subject===e.principal?.subject&&await this.options.sessions.clear()})}async clearIfCurrent(e){await V(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&this.sameCredential(t,e)&&await this.options.sessions.clear()})}async performProviderRefresh(e){return e??=await this.options.sessions.load(),Ot(Nn,this.options.sessions,async()=>{let t=await this.options.sessions.load();if(e&&t&&t.kind===e.kind&&t.refreshToken!==e.refreshToken&&t.expiresAt>this.clock.now()&&t.principal?.subject===e.principal?.subject&&t.principal?.sessionId===e.principal?.sessionId){if(this.isSafeIdBusinessMode()){if(this.isValidSafeIdBusinessSession(t))return t}else if(t.kind!=="business"&&t.kind!=="safeid-oidc-business")return t}return this.refreshProviderUnderLock()})}async refreshProviderUnderLock(){let e=await this.options.sessions.load();if(!e||(this.isSafeIdBusinessMode()?!this.isValidSafeIdBusinessSession(e):e.kind==="business"||e.kind==="safeid-oidc-business")||!e.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw e&&await this.clearIfUnchanged(e),new E;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=ce(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new E):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),n)}try{if(!t.refreshToken)throw new m("refresh_token_rotation_missing");let n=await this.acceptProviderTokens(t,void 0,e);return await V(this.options.sessions,async()=>{let i=await this.options.sessions.load();if(!i||i.kind!==e.kind||i.refreshToken!==e.refreshToken||i.accessToken!==e.accessToken)throw new E;return await this.options.sessions.save(n),n})}catch(n){throw await this.clearIfUnchanged(e),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(_(e.issuer)!==_(this.options.configuration.issuer))throw new m("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}|${_(t)}|${n}|${i}|${this.options.businessApiUrl?this.isSafeIdBusinessMode()?"safeid-oidc":"business":"provider"}|${this.options.configuration.audience}`}async acceptTokens(e,t){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.acceptProviderTokens(e,t);let n=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,n)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new m("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new m("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new m("token_subject_mismatch")}return n}async acceptProviderTokens(e,t,n){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new E;let s=this.clock.now(),o=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access")),a={accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&o?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:o,principal:i};return this.isSafeIdBusinessMode()?{kind:"safeid-oidc-business",accessToken:a.accessToken,refreshToken:a.refreshToken,idToken:a.idToken,tokenType:a.tokenType,expiresAt:a.expiresAt,refreshExpiresAt:a.refreshExpiresAt,offlineAccessGranted:a.offlineAccessGranted,principal:a.principal,businessApiUrl:this.options.businessApiUrl,audience:this.options.configuration.audience,clientId:this.options.configuration.clientId,issuer:_(this.options.configuration.issuer),environment:this.options.configuration.environment}:a}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}isSafeIdBusinessMode(){return this.options.businessAuthority==="safeid-oidc"}isValidSafeIdBusinessSession(e){let t=e,n=t.principal;return t.kind==="safeid-oidc-business"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&(t.refreshExpiresAt===void 0||Number.isFinite(t.refreshExpiresAt))&&typeof t.issuer=="string"&&typeof t.businessApiUrl=="string"&&typeof t.audience=="string"&&typeof t.clientId=="string"&&(t.environment==="TEST"||t.environment==="LIVE")&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&typeof n.authorizedParty=="string"&&(n.environment==="TEST"||n.environment==="LIVE")&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&_(t.issuer)===_(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment&&_(n.issuer)===_(this.options.configuration.issuer)&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)}businessSession(e,t,n){if(_(e.providerIssuer)!==_(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||n&&e.familyId!==n.familyId)throw new m("business_identity_mismatch");let i=Date.parse(e.accessExpiresAt),s=Date.parse(e.sessionExpiresAt);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=this.clock.now()||s<=this.clock.now()||i>s)throw new m("invalid_business_expiry");return{kind:"business",familyId:e.familyId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenType:"Bearer",expiresAt:i,sessionExpiresAt:s,principal:{issuer:t.issuer,audience:t.audience,authorizedParty:t.authorizedParty,environment:t.environment,subject:t.subject,sessionId:t.sessionId,tokenId:t.tokenId,scopes:t.scopes,nonce:t.nonce}}}isValidBusinessSession(e){let t=e,n=t.principal;return t.kind==="business"&&typeof t.familyId=="string"&&t.familyId.length>0&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&Number.isFinite(t.sessionExpiresAt)&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&_(n.issuer)===_(this.options.configuration.issuer)&&typeof n.subject=="string"&&n.subject.length>0&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(_(e.issuer)!==_(i.issuer))throw new m("issuer_mismatch");if(!s.includes(i.audience))throw new m("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new m("client_mismatch");if(e.environment!==i.environment)throw new m("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new m("required_claim_missing");if(n&&e.nonce!==t)throw new m("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(_(e.issuer)!==_(n.issuer))throw new m("issuer_mismatch");if(!i.includes(n.clientId))throw new m("client_mismatch");if(e.authorizedParty!==n.clientId)throw new m("client_mismatch");if(!e.subject||!e.sessionId)throw new m("required_claim_missing");if(e.nonce!==t)throw new m("nonce_mismatch")}};function _(r){return r.replace(/\/+$/u,"")}var $e=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()}}};function Vr(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=new Y(r.apiUrl,r.environment,r.getBearerToken,e,r.business?{organizationId:r.organizationId}:void 0);return new te(void 0,{api:t,applicationId:r.applicationId,organizationId:r.organizationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:Un,reconstructor:r.reconstructor??new re(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{re as BrowserPlanMaterialReconstructor,W as BusinessOrganizationSelectionError,Se as CoreSdkContainerRequired,q as ElementsApiRequestFailed,te as ElementsClient,Y as HttpElementsApiPort,Be as HttpOperatorAuthTransport,En as InheritiFileInvalid,_n as MAX_INHERITI_FILE_BYTES,pe as MasterKeyRelayCancellationFailed,ue as MasterKeyRelayExpired,le as MasterKeyRelayTimedOut,U as MasterKeyRequired,Z as MemoryKeyVault,J as MemoryStatePort,m as OAuthProtocolError,ze as OperatorAuthClient,X as OperatorAuthError,E as OperatorReauthenticationRequired,$e as OperatorSessionController,Zr as PassphraseMasterKeySource,ee as PlanMaterialReconstructorRequired,Jr as RawMasterKeySource,Q as RelayMasterKeySource,be as RevealAuthorizationEnded,R as RevealFieldAccessError,Pe as RevealHandleClosed,Oe as StaticMasterKeyResolver,de as SystemOAuthClock,ae as WebOAuthCrypto,ei as computePassphraseVerifier,Vr as createBrowserElementsClient,me as createMasterKeyResolver,Un as decodeAssetContainer,ti as deriveMasterKey,ni as generateHexSeed,Rn as generateInheritiFileKey,ke as masterKeyRefFor,G as masterKeyRefKey,ce as oauthErrorCode,An as openInheritiFile,Cn as openInheritiFileKey,Ue as openScopedReveal,nt as parseAssetFieldSelector,Sn as readInheritiFileHeader,tt as revealPhaseOf,wn as sealInheritiFile,xn as sealInheritiFileKey,Pn as selectBusinessOrganization,Le as unwrapDekWithMasterKey};
|
|
1
|
+
import{decodeAssetContainer as jn}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as $t,generateRSAOAEPKeyPair as Ht}from"@safetech/inheriti-core-sdk/crypto";var ge=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},he=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},fe=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},te=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 Ht();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??(_=>new Promise(w=>setTimeout(w,_))),l=!0,m=!1,v,b=()=>v??=(async()=>{let _=new AbortController,w,Bt=new Promise((Yn,Vt)=>{w=setTimeout(()=>{_.abort(),Vt(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,_.signal),Bt])}finally{clearTimeout(w)}})(),k,U=new Promise((_,w)=>{k=()=>{l&&b().catch(()=>{}),w(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",k,{once:!0})});U.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),m=!0;Date.now()<a;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let _=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),U]);if(_.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(_.status==="DELIVERED"&&_.sealedMasterKey){let w=(await $t(_.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(w))throw new Error("invalid_master_key_material");return w}if(_.status==="EXPIRED")throw new he(s.sessionId);await Wt(d,o,e)}throw new ge(s.sessionId)}catch(_){if(l&&(!m||e?.aborted))try{await b()}catch(w){if(e?.aborted)throw new fe(w)}throw _}finally{k&&e?.removeEventListener("abort",k)}}};async function Wt(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function ye(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||Ue(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(jt(e,r.applicationId)){let i=await r.source?.resolve();return i||Ue(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Ue(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function jt(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Ue(r,e,t,n,i){if((await e()).relayAvailable)return new te({...r.relay,api:Yt(r.api,t)}).resolve(n,i)}function Yt(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 V(r){return`${r.system}:${r.contextId}`}function Le(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var z=class extends Error{constructor(t){super(`master_key_required:${V(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(V(e),t),this}async resolve(e){return this.sources.get(V(e))?.resolve()}};var ne=class{keys=new Map;async store(e,t){let n=V(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(V(e))?.slice()}async remove(e){let t=V(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var re=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 Ie=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 ve=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],ze={"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"]},et=["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"}},F=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 F("plan_material_field_unknown");if(qe(r.dataShards,"data_shards_invalid"),qe(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&qe(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new F("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new F("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new F("material_operation_invalid")}function qe(r,e){if(!Array.isArray(r))throw new F(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new F(e);if(t.data!==void 0&&typeof t.data!="string")throw new F(e)}}function j(r){if(W(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Zt(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(W(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),!ve.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(Xt(t.matchOrigins),!t.isBinary){let s=ze[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(W(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!tt(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")}Qt(r)}function Xt(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 Qt(r){let e=r.policy;if(e&&W(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"){W(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){W(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;W(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!tt(t.subjectEmail))throw new y("dms_subject_invalid");if(!r.participants.some(s=>Je(s.routingEmail)===Je(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 Zt(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 tt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Je(r){return r.normalize("NFC").trim().toLowerCase()}function W(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new y(t)}var be=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)}},we=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),j(e),Pe(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={}){j(t);let o=await this.checkpoints.load(e);if(!o)throw new Re("creation_checkpoint_missing");if(o.idempotencyKey!==t.idempotencyKey||o.declarationHash!==await nt(t))throw new Re("creation_declaration_mismatch");let a=await this.api.getPlanCreation(e);if(s.onProgress?.(a.stage),a.outcome==="COMPLETED"||a.outcome==="CANCELED")return await this.checkpoints.remove(e),a;if(a.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!a.planId)return a;Pe(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:a.planId,declaration:t,secrets:n,signal:s.signal});Pe(s.signal),s.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:a.planId,declaration:t,encrypted:d,signal:s.signal});Pe(s.signal),X(l);let m=await this.api.supplyPlanCreationMaterial(e,l);return s.onProgress?.(m.stage),m.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,m),m}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 nt(e),serverStage:t.stage})}},Re=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function nt(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 Pe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function rt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Ie(n.stage);return r.authorizeRevealAction(e,t)}function Jt(r){let e=r?.status;return e===400||e===401||e===403}async function it(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Jt(s))throw s}return r.releaseRevealMaterial(e,t)}function dt(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"?tn(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":en.has(r.stage)?"ENDED":"CONTINUING"}var en=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function tn(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 Ae=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 Ge(r,e,t={},n=!1){if(t.signal?.aborted)throw I();let i=await r.getPlan(e),s=await r.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):st(s.id);if(t.signal?.aborted)throw I();let o=()=>r.prepareReveal(e,t.signal,async m=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(m)});if(n||await o(),t.signal?.aborted)throw I();let a=t.idempotencyKey??crypto.randomUUID(),d;try{d=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(m){if(m?.code!=="merge_process_already_active")throw m;let v=await r.getActivePlanReveal(e);throw!v||v.planId!==e||v.mode!==(t.mode??"DIRECT")||v.protectedCopy!==void 0&&v.protectedCopy!==(t.protectedCopy??!1)?m:st(v.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let l;try{if(t.signal?.aborted)throw I();let m=await rn(r,d,t);if(t.signal?.aborted||(n&&await o(),t.signal?.aborted)||($(t,"RELEASING_MATERIAL",m),t.signal?.aborted))throw I();let v=await r.releaseRevealMaterial(m.id,m.materialVersion??"1");if(t.signal?.aborted||(m.mode==="GOVERNED"&&await r.markRevealSharesCollected(m.id),t.signal?.aborted))throw I();let b;try{b=await an(r,m,cn(v),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||($(t,"RECONSTRUCTING",m),t.signal?.aborted))throw I();try{l=await r.reconstructPlanMaterial(b)}catch(U){throw t.signal?.aborted?I():(await r.reportRevealReconstruction(m.id,{status:"FAILED",errorCode:on(U)}),U)}if(t.signal?.aborted)throw I();let k=await r.reportRevealReconstruction(m.id,{status:"SUCCEEDED"});if(t.signal?.aborted||($(t,"OPEN",k),t.signal?.aborted))throw I();return new Fe(r,k,i,l,t.signal)}catch(m){throw l?.fill(0),await lt(r,d.id,t.signal?.aborted?"CANCELED":"ERROR"),m}}function st(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var nn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function rn(r,e,t){let n=await G(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw I();if(t.onSession?.(n),t.onProgress?.({phase:dt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(nn.has(n.stage))throw new Se(n.stage);await Be(t.pollIntervalMs??1500,t.signal),n=await G(()=>r.getReveal(e.id,t.signal),t.signal)}}var Se=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function $(r,e,t){r.onProgress?.({phase:e,session:t})}function Be(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 Ae;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=ct(s),d=this.plan.assets.find(l=>(l.code??l.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:sn(a.data,o.field,o.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(o=>this.reportAction(o.id,"FAILED",ot(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",ot(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=lt(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 ct(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 sn(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"?ze[t]:void 0)?.includes(e))return"";throw new R("asset_value_invalid")}return n[e]}function ot(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 on(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function an(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await G(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Ee;let l=await G(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(at(l,i.id,e.planId),!l.shares.includes(i.data))throw new K;$(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:m}=await G(()=>n.proDevice.write(l,n.signal),n.signal);if(n.signal?.aborted)throw I();if(!m?.trim())throw new K;if(await r.claimRevealCustodianShare(e.id,l.id,m),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,l.id),n.signal?.aborted))throw I();return{...t,shares:t.shares.filter(v=>v!==i).concat(l.shares.map((v,b)=>({id:`${l.id}:${b}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:v})))}}if(d!=="SK_MOBILE")throw new K;if(n.signal?.aborted)throw I();return await r.distributeRevealCustodianShare(e.id),$(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await G(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),$(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Be(n.pollIntervalMs??1500,n.signal),s=await G(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Ee;if(!s.shareId||!s.deviceId)throw new K;$(n,"CONNECTING_SAFEKEY_PRO",e);let d=await G(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw I();if(at(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new K;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw I();return{...t,shares:t.shares.concat(d.shares.map((l,m)=>({id:`${d.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new K;let o={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(o),$(n,"WAITING_FOR_CUSTODIAN",o),n.signal?.aborted)throw I();await r.requestRevealCustodianRelease(e.id);let a=await dn(r,e,n);return Object.assign({},t,{shares:t.shares.concat(a.shares.map((d,l)=>({id:`${a.id}:${l}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function at(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 K}async function G(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 dn(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new _e;let s=await G(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new _e;if(s&&s.status!=="PENDING"){let o=s;if(o.shares?.length)return o;throw new K}await Be(t.pollIntervalMs??1500,t.signal)}}var K=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Ee=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},_e=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 lt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(o){if(!ln(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 ln(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 se=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 ne,this.state=t.state??new re,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??mn(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)}listMemberLogs(e,t){if(!this.api)throw new u;return this.api.listMemberLogs(e,t)}listOrganizationMembers(e){if(!this.api)throw new u;return this.api.listOrganizationMembers(e)}listOrganizationAuditTrail(e){if(!this.api)throw new u;return this.api.listOrganizationAuditTrail(e)}getOrganizationInsights(e){if(!this.api)throw new u;return this.api.getOrganizationInsights(e)}getPlanResponsibilities(e){if(!this.api)throw new u;return this.api.getPlanResponsibilities(e)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return j(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 be){if(this.requireApplication(),!this.api)throw new u;return new we(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 z({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 pn(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new z(e);return await this.keyVault.store(e,un(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 z({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=Le(e);if(!i)throw new z({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)}createRevealFileAccess(e,t,n){if(!this.api)throw new u;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new u;return this.api.cancelRevealFileAccess(e,t,n)}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 Ge(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 it(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 rt(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(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),o=i.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),a=i.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(l=>Object.assign({},l,{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 xe;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new z({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},xe=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function un(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 pn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function mn(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return ye({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ye({...e,organizationId:r.organizationId})}import{createBrowserSsdpV2WorkerFactory as bn,createSsdpV2Processor as wn}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function Ve(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=hn(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 hn(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 oe=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await ut("plan_key_unwrap_failed",()=>Ve(e.planKey,t)),i=await crypto.subtle.importKey("raw",$e(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],o=[];for(let a of e.shares){let d=await ut("plan_share_decryption_failed",()=>Pn(a.data,i));vn(a.shareType)?o.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:o}).result}catch(a){throw new Te("plan_share_reconstruction_failed",In(a))}}},Te=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},yn=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function In(r){let e=r instanceof Error?r.message:void 0;if(e)return yn.has(e)?e:void 0}async function ut(r,e){try{return await e()}catch{throw new Te(r)}}function vn(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function Pn(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=$e(r.slice(0,t)),i=$e(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function $e(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var ae=class extends oe{constructor(e={}){let t=e.processor??wn(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:bn(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var Rn=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],An=["DIRECT","GOVERNED"],mt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Sn=["ACTIVE","REVOKED"],En=["SK_MOBILE"],_n=["ACTIVE","INACTIVE"],xn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function gt(r){let e=A(r);return{items:M(e.items).map(It),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function ht(r){let e=A(r);return{total:N(e.total,"total"),items:M(e.items).map(t=>{let n=A(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:p(n.id,"log.id"),planId:p(n.planId,"log.planId"),tenantId:p(n.tenantId,"log.tenantId"),event:p(n.event,"log.event"),occurredOn:p(n.occurredOn,"log.occurredOn"),status:B(n.status),title:p(n.title,"log.title"),details:M(n.details).map(i=>{let s=A(i);return{label:p(s.label,"log.detail.label"),value:p(s.value,"log.detail.value")}})}})}}function ft(r){let e=A(r);return{total:N(e.total,"total"),items:M(e.items).map(t=>{let n=A(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=p(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:p(n.id,"log.id"),memberId:p(n.memberId,"log.memberId"),source:i,event:p(n.event,"log.event"),occurredOn:p(n.occurredOn,"log.occurredOn"),status:B(n.status)}})}}function yt(r){let e=A(r),t=It(e),n=A(e.source),i=p(n.kind,"source.kind");return{...t,assets:M(e.assets).map(s=>{let o=A(s);return{id:p(o.id,"asset.id"),code:B(o.code),type:O(p(o.type,"asset.type"),ve),name:p(o.name,"asset.name"),isBinary:Cn(o.isBinary,"asset.isBinary"),fieldNames:M(o.fieldNames).map(a=>p(a,"asset.fieldNames")),fileName:B(o.fileName),mimeType:B(o.mimeType),size:o.size===void 0||o.size===null?void 0:N(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:M(o.matchOrigins).map(a=>p(a,"asset.matchOrigins"))}}),participants:M(e.participants).map(s=>{let o=A(s);return{id:p(o.id,"participant.id"),displayName:p(o.displayName,"participant.displayName"),relationships:M(o.relationships).map(a=>O(p(a,"relationship"),mt)),lifecycle:O(p(o.lifecycle,"participant.lifecycle"),Sn)}}),revealPolicy:(()=>{let s=A(e.revealPolicy);return{masterKeyRelease:O(p(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:O(p(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=A(e.dms);return{subjectEmail:p(s.subjectEmail,"dms.subjectEmail"),countdownDays:N(s.countdownDays,"dms.countdownDays"),countdownHours:N(s.countdownHours,"dms.countdownHours"),countdownMinutes:N(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:O(p(n.system,"source.system"),["INHERITI_BUSINESS"]),status:O(p(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function de(r){let e=A(r);return{operationId:p(e.operationId,"operationId"),stage:O(p(e.stage,"stage"),et),outcome:O(p(e.outcome,"outcome"),xn),planId:B(e.planId),lastErrorCode:B(e.lastErrorCode),participants:e.participants===void 0?void 0:M(e.participants).map(t=>{let n=A(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:M(n.relationships).map(i=>Tn(p(i,"relationship"),mt))}})}}function It(r){let e=A(r),t=A(e.assetSummary),n=A(e.governance),i=A(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:B(e.description),status:O(p(e.status,"status"),Rn),createdAt:p(e.createdAt,"createdAt"),configuredAt:B(e.configuredAt),assetSummary:{count:N(t.count,"assetSummary.count"),types:M(t.types).map(s=>O(p(s,"assetType"),ve)),names:pt(t.names).map(s=>p(s,"assetSummary.names"))},governance:{mode:O(p(n.mode,"governance.mode"),An),minimumApprovals:N(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:N(i.owners,"owners"),mergers:N(i.mergers,"mergers"),moderators:N(i.moderators,"moderators")},authentication:pt(e.authentication).map(s=>{let o=A(s);return{id:O(p(o.id,"authentication.id"),En),status:O(p(o.status,"authentication.status"),_n)}})}}function O(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Tn(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function A(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function pt(r){return r==null?[]:M(r)}function M(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function p(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function B(r){return r==null?void 0:p(r,"optional")}function N(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Cn(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function D(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Y(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function P(r){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function He(r){return r==null?void 0:P(r)}function S(r){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function On(r){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function vt(r){let e=D(r);return{total:S(e.total),items:Y(e.items).map(t=>{let n=D(t);return{id:P(n.id),displayName:P(n.displayName),role:P(n.role),status:P(n.status)}})}}function Pt(r){let e=D(r);return{total:S(e.total),shownCount:S(e.shownCount),totalCount:S(e.totalCount),nextCursor:e.nextCursor==null?null:P(e.nextCursor),hasMore:On(e.hasMore),items:Y(e.items).map(t=>{let n=D(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:P(n.id),occurredOn:P(n.occurredOn),actorName:P(n.actorName),actorRole:P(n.actorRole),category:P(n.category),action:P(n.action),subject:P(n.subject),status:P(n.status),sourceEvent:P(n.sourceEvent),planId:He(n.planId),planName:He(n.planName),responsibleMemberName:He(n.responsibleMemberName)}})}}function bt(r){let e=D(r),t=D(e.stats),n=D(e.planAccessResults);return{stats:{totalPlans:S(t.totalPlans),plansCreatedThisMonth:S(t.plansCreatedThisMonth),activeMembers:S(t.activeMembers),totalSeats:t.totalSeats==null?null:S(t.totalSeats),accessRequests30d:S(t.accessRequests30d),accessRequestsPrevious30d:S(t.accessRequestsPrevious30d),pendingApprovals:S(t.pendingApprovals)},plansOverTime:Y(e.plansOverTime).map(i=>{let s=D(i);return{month:P(s.month),count:S(s.count)}}),planTypes:Y(e.planTypes).map(i=>{let s=D(i);return{type:P(s.type),count:S(s.count)}}),accessModerationActivity:Y(e.accessModerationActivity).map(i=>{let s=D(i);return{week:P(s.week),requests:S(s.requests),approvals:S(s.approvals)}}),planAccessResults:{success:S(n.success),aborted:S(n.aborted),expired:S(n.expired)}}}function wt(r){let e=D(r);return{planId:P(e.planId),participants:Y(e.participants).map(t=>{let n=D(t);return{id:P(n.id),displayName:P(n.displayName),relationships:Y(n.relationships).map(i=>P(i)),lifecycle:P(n.lifecycle)}})}}function Ce(r,e){if(Object.keys(r).some(t=>!e.includes(t)))throw new Error("organization_query_field_unknown")}var Q=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Rt(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 kn(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 Mn(r){let e=f(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),createdAt:C(e.createdAt),...At(e)}}function At(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=f(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:c(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:C(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=f(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:h(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:C(i.revealedAt)}:{}}})}:{}}})}}function St(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Mn),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0),unreadCount:h(e.unreadCount,0),readThroughSequence:h(e.readThroughSequence,0)}}function Et(r){let e=f(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=f(t);return{unitId:c(n.unitId),position:h(n.position,0),commitment:c(n.commitment),status:c(n.status)}})}}function We(r){let e=f(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),status:e.status}}function _t(r){let e=f(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:c(e.conversationId),parentId:c(e.parentId),participantRevision:h(e.participantRevision,1),recipients:e.recipients.map(je)}}function xt(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);return{parentId:c(n.parentId),sequence:h(n.sequence,1),senderMemberId:c(n.senderMemberId),senderDeviceId:c(n.senderDeviceId),participantRevision:h(n.participantRevision,1),createdAt:C(n.createdAt),...At(n)}}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0),unreadCount:h(e.unreadCount,0),readThroughSequence:h(e.readThroughSequence,0)}}function Tt(r){return{readThroughSequence:h(f(r).readThroughSequence,0)}}function Ct(r){return{clearedThroughSequence:h(f(r).clearedThroughSequence,0)}}function Ot(r){let e=f(r);return{parentId:c(e.parentId),sequence:h(e.sequence,1),senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),canonicalManifest:c(e.canonicalManifest),frame:c(e.frame),signature:c(e.signature),wrappedContentKey:c(e.wrappedContentKey),senderSigningPublicKey:c(e.senderSigningPublicKey)}}function f(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function c(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function C(r){let e=c(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function h(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function je(r){let e=f(r);return{memberId:c(e.memberId),deviceId:c(e.deviceId),deviceVersion:h(e.deviceVersion,1),encryptionPublicKey:c(e.encryptionPublicKey),encryptionKeyFingerprint:c(e.encryptionKeyFingerprint),signingPublicKey:c(e.signingPublicKey),signingKeyFingerprint:c(e.signingKeyFingerprint)}}function Z(r){let e=f(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:c(e.id),tenantId:c(e.tenantId),memberId:c(e.memberId),version:e.version,encryptionPublicKey:c(e.encryptionPublicKey),encryptionKeyFingerprint:c(e.encryptionKeyFingerprint),signingPublicKey:c(e.signingPublicKey),signingKeyFingerprint:c(e.signingKeyFingerprint),status:e.status,createdAt:C(e.createdAt),updatedAt:C(e.updatedAt)}}function Oe(r){let e=f(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:c(e.id),tenantId:c(e.tenantId),creatorMemberId:c(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(c),participantRevision:e.participantRevision,status:e.status,createdAt:C(e.createdAt),updatedAt:C(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=f(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:c(n.senderMemberId),createdAt:C(n.createdAt)}}return t}function kt(r){let e=f(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(Oe),total:e.total,limit:e.limit,offset:e.offset}}function Mt(r){let e=f(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=je(t);return{memberId:n.memberId,name:c(f(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function Dt(r){let e=f(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:c(n.memberId),name:c(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:c(f(n.profilePicture).url)}}}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function Nt(r){let e=f(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:c(e.conversationId),messageId:c(e.messageId),participantRevision:h(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(je),shareLayers:e.shareLayers.map(t=>{let n=f(t),i=c(n.id),s=c(n.dataShareId),o=c(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:c(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 ke(r){let e=f(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:c(e.messageId),status:e.status}}function Ut(r){let e=f(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=f(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:c(n.id),status:n.status,senderMemberId:c(n.senderMemberId),senderDeviceId:c(n.senderDeviceId),createdAt:C(n.createdAt),updatedAt:C(n.updatedAt),expiresAt:C(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let o=f(s);if(o.status!=="UNREAD"&&o.status!=="LEASED"&&o.status!=="CONSUMED"&&o.status!=="EXPIRED"&&o.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:c(o.memberId),status:o.status,...o.consumedAt!==void 0?{consumedAt:o.consumedAt===null?null:C(o.consumedAt)}:{}}})),i}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0)}}function Kt(r){let e=f(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:c(e.leaseId),leaseExpiresAt:C(e.leaseExpiresAt),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),tenantWrappedShareKey:c(e.tenantWrappedShareKey),wrappedContentKey:c(e.wrappedContentKey),shares:e.shares.map(t=>{let n=f(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:h(n.index,0),shareId:c(n.shareId),layerId:c(n.layerId),ciphertext:c(n.ciphertext)}})}}function Lt(r){let e=f(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:c(e.leaseId),leaseExpiresAt:C(e.leaseExpiresAt),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),tenantWrappedShareKey:c(e.tenantWrappedShareKey),wrappedContentKey:c(e.wrappedContentKey),shares:e.shares.map(t=>{let n=f(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:h(n.index,0),shareId:c(n.shareId),layerId:c(n.layerId)}})}}function Me(r){return typeof r=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(r)&&Number.isFinite(Date.parse(r))}function ce(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 le(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var L=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}},J=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 Oe(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Oe(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 Mt(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 Dt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return _t(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 ke(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return We(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return We(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 St(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 Et(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 Ct(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 xt(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 Ot(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 Tt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return ke(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 De(a,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new L(a.status,ce(d),le(d),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return ke(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 Lt(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}`,l=await this.requestBinary(d,"GET",void 0,o);if(!l.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let m=Number(l.headers.get("content-length"));if(Number.isFinite(m)&&m>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!l.body)throw new Error("invalid_inbox_share_response");let v=l.body.getReader(),b=[],k=0;try{for(;;){o?.throwIfAborted();let w=await v.read();if(w.done)break;if(k+=w.value.length,k>14*1024*1024)throw new Error("invalid_inbox_share_size");b.push(w.value)}}catch(w){throw await v.cancel().catch(()=>{}),w}let U=new Uint8Array(k),_=0;for(let w of b)U.set(w,_),_+=w.length;return U}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 Ut(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return Kt(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(Rt)}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 gt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return yt(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 ht(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let n=new URLSearchParams;t.source&&n.set("source",t.source),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return ft(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listOrganizationMembers(e={}){if(this.requireOrganizationSelection(),Ce(e,["limit","offset"]),e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>100))throw new Error("organization_query_limit_invalid");if(e.offset!==void 0&&(!Number.isSafeInteger(e.offset)||e.offset<0))throw new Error("organization_query_offset_invalid");let t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),vt(await this.request(`v1/organization/members${t.size?`?${t}`:""}`,"GET"))}async listOrganizationAuditTrail(e){if(this.requireOrganizationSelection(),Ce(e,["from","to","limit","cursor","category","memberId","responsibleMemberId"]),!Me(e.from)||!Me(e.to)||Date.parse(e.from)>Date.parse(e.to))throw new Error("organization_query_date_invalid");if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>500))throw new Error("organization_query_limit_invalid");if(e.cursor!==void 0&&!/^[1-9]\d*$/.test(e.cursor))throw new Error("organization_query_cursor_invalid");let t=new URLSearchParams({from:e.from,to:e.to});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor!==void 0&&t.set("cursor",e.cursor),e.category!==void 0&&t.set("category",e.category),e.memberId!==void 0&&t.set("memberId",e.memberId),e.responsibleMemberId!==void 0&&t.set("responsibleMemberId",e.responsibleMemberId),Pt(await this.request(`v1/organization/audit-trail?${t}`,"GET"))}async getOrganizationInsights(e={}){if(this.requireOrganizationSelection(),Ce(e,["from","to"]),e.from===void 0!=(e.to===void 0)||e.from!==void 0&&(!Me(e.from)||!Me(e.to)||Date.parse(e.from)>Date.parse(e.to)))throw new Error("organization_query_date_invalid");let t=new URLSearchParams;return e.from!==void 0&&e.to!==void 0&&(t.set("from",e.from),t.set("to",e.to)),bt(await this.request(`v1/organization/insights${t.size?`?${t}`:""}`,"GET"))}async getPlanResponsibilities(e){if(this.requireOrganizationSelection(),!e)throw new Error("plan_id_required");return wt(await this.request(`v1/plans/${encodeURIComponent(e)}/responsibilities`,"GET"))}async startPlanCreation(e){j(e);let{idempotencyKey:t,...n}=e;return de(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return de(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return X(t),de(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return de(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[k,U]of Object.entries(s??{}))d.set(k,U);n&&d.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,m={method:t,headers:d,body:n?JSON.stringify(n):void 0};o&&(m.signal=o);let v=await this.transport(new URL(e,l),m);o?.throwIfAborted();let b=await De(v,o);if(o?.throwIfAborted(),!v.ok)throw new L(v.status,ce(b),le(b),v.headers.get("x-request-id")??void 0);if(!b.ok||b.result===void 0)throw new L(v.status,ce(b),le(b),v.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 l=await De(d,i);throw new L(d.status,ce(l),le(l),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});o&&a.set("authorization",`Bearer ${o}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId);for(let[v,b]of Object.entries(n??{}))a.set(v,b);t&&a.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,d),{method:i,headers:a,body:t?JSON.stringify(t):void 0,signal:s}),m=await De(l,s);if(s?.throwIfAborted(),!l.ok||!m.ok)throw new L(l.status,ce(m),le(m),l.headers.get("x-request-id")??void 0)}requireOrganizationSelection(){if(!this.business?.organizationId)throw new L(400,"organization_selection_required")}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new L(400,"organization_selection_required")}};async function De(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{PassphraseMasterKeySource as pi,RawMasterKeySource as mi,computePassphraseVerifier as gi,deriveMasterKey as hi,generateHexSeed as fi}from"@safetech/inheriti-core-sdk/crypto";import{generateInheritiFileKey as Dn,sealInheritiFile as Nn,readInheritiFileHeader as Un,openInheritiFile as Kn,InheritiFileInvalid as Ln,MAX_INHERITI_FILE_BYTES as qn}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as zn,openInheritiFileKey as Fn}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";function qt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var ue=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),qt(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return qt(new Uint8Array(t))}},pe=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 ee=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},x=class extends ee{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},g=class extends ee{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function me(r){if(r instanceof ee)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Ye=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:E(n,"issuer"),authorizationEndpoint:E(n,"authorization_endpoint"),tokenEndpoint:E(n,"token_endpoint"),deviceAuthorizationEndpoint:q(n,"device_authorization_endpoint"),endSessionEndpoint:q(n,"end_session_endpoint"),revocationEndpoint:q(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:E(t,"device_code"),userCode:E(t,"user_code"),verificationUri:E(t,"verification_uri"),verificationUriComplete:q(t,"verification_uri_complete"),expiresInSeconds:zt(t,"expires_in"),intervalSeconds:Xe(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async revoke(e){let t=await this.http(new URL(e.endpoint),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,token:e.refreshToken,token_type_hint:"refresh_token"}),signal:e.signal});if(!t.ok)throw new g(`oauth_http_${t.status}`)}async exchangeBusinessSession(e){return this.businessSession(e.apiUrl,"exchange",{providerAccessToken:e.providerAccessToken})}async refreshBusinessSession(e){return this.businessSession(e.apiUrl,"refresh",{refreshToken:e.refreshToken})}async revokeBusinessSession(e){await this.businessRequest(e.apiUrl,"revoke",{refreshToken:e.refreshToken},e.signal)}async businessSession(e,t,n){let i=await this.businessRequest(e,t,n);return{accessToken:E(i,"accessToken"),refreshToken:E(i,"refreshToken"),accessExpiresAt:E(i,"accessExpiresAt"),sessionExpiresAt:E(i,"sessionExpiresAt"),familyId:E(i,"familyId"),environment:Bn(i,"environment"),clientId:E(i,"clientId"),providerIssuer:E(i,"providerIssuer"),providerSubject:E(i,"providerSubject")}}async businessRequest(e,t,n,i){let s=e.endsWith("/")?e:`${e}/`,o=new URL(`operator-sessions/${t}`,s),a=await this.http(o,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"omit",signal:i,body:JSON.stringify(n)}),d={};try{d=await a.json()}catch{}if(!a.ok)throw new g(`business_http_${a.status}`);if(d.ok!==!0||!Gn(d.result))throw new g("invalid_business_response");return d.result}async token(e,t){let n=await this.form(e,t);return{accessToken:E(n,"access_token"),refreshToken:q(n,"refresh_token"),idToken:q(n,"id_token"),tokenType:E(n,"token_type"),expiresInSeconds:zt(n,"expires_in"),refreshExpiresInSeconds:Xe(n,"refresh_expires_in"),scope:q(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=q(i,"error")??`oauth_http_${n.status}`;throw new g(s,q(i,"error_description")??s)}return i}};function Gn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Bn(r,e){let t=E(r,e);if(t!=="TEST"&&t!=="LIVE")throw new g("invalid_business_response");return t}function E(r,e){let t=q(r,e);if(!t)throw new g("invalid_oauth_response",`Missing ${e}`);return t}function q(r,e){return typeof r[e]=="string"?r[e]:void 0}function zt(r,e){let t=Xe(r,e);if(t===void 0)throw new g("invalid_oauth_response",`Missing ${e}`);return t}function Xe(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Vn=600*1e3,Ne=5,$n=5,Ft=5e3,Hn=new WeakMap,Wn=new WeakMap;async function Gt(r,e,t){let n=r.get(e),i,s=new Promise(o=>{i=o});r.set(e,s),n&&await n;try{return await t()}finally{r.get(e)===s&&r.delete(e),i()}}function H(r,e){return Gt(Hn,r,e)}var Qe=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new g("business_api_url_required");this.crypto=e.crypto??new ue,this.clock=e.clock??new pe}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()+Vn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:a});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",o),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:a}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new g("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new g("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new g("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new g("state_mismatch");let o=i.searchParams.get("error");if(o)throw new g(o,i.searchParams.get("error_description")??o);let a=i.searchParams.get("code");if(!a)throw new g("authorization_code_missing");let d=await this.getDiscovery(),l=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:a,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),m=await this.acceptTokens(l,n.nonce);return await H(this.options.sessions,()=>this.options.sessions.save(m)),m}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new g("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(Ne,t.intervalSeconds??Ne),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new g("device_transaction_missing");let i=n,s=await this.getDiscovery(),o=Math.max(Ne,i.intervalSeconds??Ne),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 l=await this.acceptTokens(d);return await H(this.options.sessions,()=>this.options.sessions.save(l)),await this.options.transactions.remove(t),l}catch(d){let l=me(d);if(l==="authorization_pending"){a=this.clock.now()+o*1e3;continue}if(l==="slow_down"){o+=$n,a=this.clock.now()+o*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new g("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e){if(this.isSafeIdBusinessMode()&&!this.isValidSafeIdBusinessSession(e))throw await this.clearIfUnchanged(e),new x;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new x;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new x;return e.expiresAt>this.clock.now()?e.accessToken:(await this.refreshExpired(e)).accessToken}}refresh(){return this.refreshExpired()}refreshExpired(e){if(this.refreshFlight)return this.refreshFlight;let t=this.performRefresh(e).finally(()=>{this.refreshFlight===t&&(this.refreshFlight=void 0)});return this.refreshFlight=t,t}async clear(){let e;if(await H(this.options.sessions,async()=>{try{e=await this.options.sessions.load()}finally{await this.options.sessions.clear()}}),this.isSafeIdBusinessMode()&&e&&this.isValidSafeIdBusinessSession(e)&&e.refreshToken){let i=new AbortController,s;try{await Promise.race([(async()=>{let o=await this.getDiscovery();o.revocationEndpoint&&this.options.transport.revoke&&await this.options.transport.revoke({endpoint:o.revocationEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken,signal:i.signal})})(),new Promise((o,a)=>{s=setTimeout(()=>{i.abort(),this.discovery=void 0,a(new g("provider_revoke_timeout"))},Ft)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,n;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{n=setTimeout(()=>{t.abort(),s(new g("business_revoke_timeout"))},Ft)})])}finally{n&&clearTimeout(n)}}async performRefresh(e){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.performProviderRefresh(e);let t=await this.options.sessions.load();if(!t||!this.isValidBusinessSession(t))throw t&&await this.clearIfUnchanged(t),new x;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new x;let n;try{n=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=me(i);if(s==="business_http_409"){let o=await H(this.options.sessions,async()=>{let a=await this.options.sessions.load();if(a&&this.isValidBusinessSession(a)&&a.refreshToken!==t.refreshToken&&a.familyId===t.familyId&&a.principal.subject===t.principal.subject)return a;a&&this.sameCredential(a,t)&&await this.options.sessions.clear()});if(o)return o;throw new x}throw s==="business_http_401"?(await this.clearIfCurrent(t),new x):i}try{let i=this.businessSession(n,t.principal,t);if(i.refreshToken===t.refreshToken)throw new g("refresh_token_rotation_missing");return await H(this.options.sessions,async()=>{let s=await this.options.sessions.load();if(s&&this.isValidBusinessSession(s)&&s.familyId===t.familyId&&s.principal.subject===t.principal.subject&&s.refreshToken!==t.refreshToken)return s;if(!s||!this.sameCredential(s,t))throw new x;return await this.options.sessions.save(i),i})}catch(i){throw await this.clearIfCurrent(t),i}}sameCredential(e,t){return this.isValidBusinessSession(e)&&e.familyId===t.familyId&&e.refreshToken===t.refreshToken&&e.principal.subject===t.principal.subject}async clearIfUnchanged(e){await H(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&t.kind===e.kind&&t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.principal?.subject===e.principal?.subject&&await this.options.sessions.clear()})}async clearIfCurrent(e){await H(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&this.sameCredential(t,e)&&await this.options.sessions.clear()})}async performProviderRefresh(e){return e??=await this.options.sessions.load(),Gt(Wn,this.options.sessions,async()=>{let t=await this.options.sessions.load();if(e&&t&&t.kind===e.kind&&t.refreshToken!==e.refreshToken&&t.expiresAt>this.clock.now()&&t.principal?.subject===e.principal?.subject&&t.principal?.sessionId===e.principal?.sessionId){if(this.isSafeIdBusinessMode()){if(this.isValidSafeIdBusinessSession(t))return t}else if(t.kind!=="business"&&t.kind!=="safeid-oidc-business")return t}return this.refreshProviderUnderLock()})}async refreshProviderUnderLock(){let e=await this.options.sessions.load();if(!e||(this.isSafeIdBusinessMode()?!this.isValidSafeIdBusinessSession(e):e.kind==="business"||e.kind==="safeid-oidc-business")||!e.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw e&&await this.clearIfUnchanged(e),new x;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=me(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new x):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),n)}try{if(!t.refreshToken)throw new g("refresh_token_rotation_missing");let n=await this.acceptProviderTokens(t,void 0,e);return await H(this.options.sessions,async()=>{let i=await this.options.sessions.load();if(!i||i.kind!==e.kind||i.refreshToken!==e.refreshToken||i.accessToken!==e.accessToken)throw new x;return await this.options.sessions.save(n),n})}catch(n){throw await this.clearIfUnchanged(e),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(T(e.issuer)!==T(this.options.configuration.issuer))throw new g("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${T(t)}|${n}|${i}|${this.options.businessApiUrl?this.isSafeIdBusinessMode()?"safeid-oidc":"business":"provider"}|${this.options.configuration.audience}`}async acceptTokens(e,t){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.acceptProviderTokens(e,t);let n=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,n)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new g("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new g("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new g("token_subject_mismatch")}return n}async acceptProviderTokens(e,t,n){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new x;let s=this.clock.now(),o=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access")),a={accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&o?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:o,principal:i};return this.isSafeIdBusinessMode()?{kind:"safeid-oidc-business",accessToken:a.accessToken,refreshToken:a.refreshToken,idToken:a.idToken,tokenType:a.tokenType,expiresAt:a.expiresAt,refreshExpiresAt:a.refreshExpiresAt,offlineAccessGranted:a.offlineAccessGranted,principal:a.principal,businessApiUrl:this.options.businessApiUrl,audience:this.options.configuration.audience,clientId:this.options.configuration.clientId,issuer:T(this.options.configuration.issuer),environment:this.options.configuration.environment}:a}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}isSafeIdBusinessMode(){return this.options.businessAuthority==="safeid-oidc"}isValidSafeIdBusinessSession(e){let t=e,n=t.principal;return t.kind==="safeid-oidc-business"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&(t.refreshExpiresAt===void 0||Number.isFinite(t.refreshExpiresAt))&&typeof t.issuer=="string"&&typeof t.businessApiUrl=="string"&&typeof t.audience=="string"&&typeof t.clientId=="string"&&(t.environment==="TEST"||t.environment==="LIVE")&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&typeof n.authorizedParty=="string"&&(n.environment==="TEST"||n.environment==="LIVE")&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&T(t.issuer)===T(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment&&T(n.issuer)===T(this.options.configuration.issuer)&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)}businessSession(e,t,n){if(T(e.providerIssuer)!==T(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||n&&e.familyId!==n.familyId)throw new g("business_identity_mismatch");let i=Date.parse(e.accessExpiresAt),s=Date.parse(e.sessionExpiresAt);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=this.clock.now()||s<=this.clock.now()||i>s)throw new g("invalid_business_expiry");return{kind:"business",familyId:e.familyId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenType:"Bearer",expiresAt:i,sessionExpiresAt:s,principal:{issuer:t.issuer,audience:t.audience,authorizedParty:t.authorizedParty,environment:t.environment,subject:t.subject,sessionId:t.sessionId,tokenId:t.tokenId,scopes:t.scopes,nonce:t.nonce}}}isValidBusinessSession(e){let t=e,n=t.principal;return t.kind==="business"&&typeof t.familyId=="string"&&t.familyId.length>0&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&Number.isFinite(t.sessionExpiresAt)&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&T(n.issuer)===T(this.options.configuration.issuer)&&typeof n.subject=="string"&&n.subject.length>0&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(T(e.issuer)!==T(i.issuer))throw new g("issuer_mismatch");if(!s.includes(i.audience))throw new g("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new g("client_mismatch");if(e.environment!==i.environment)throw new g("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new g("required_claim_missing");if(n&&e.nonce!==t)throw new g("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(T(e.issuer)!==T(n.issuer))throw new g("issuer_mismatch");if(!i.includes(n.clientId))throw new g("client_mismatch");if(e.authorizedParty!==n.clientId)throw new g("client_mismatch");if(!e.subject||!e.sessionId)throw new g("required_claim_missing");if(e.nonce!==t)throw new g("nonce_mismatch")}};function T(r){return r.replace(/\/+$/u,"")}var Ze=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()}}};function ri(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=new J(r.apiUrl,r.environment,r.getBearerToken,e,r.business?{organizationId:r.organizationId}:void 0);return new se(void 0,{api:t,applicationId:r.applicationId,organizationId:r.organizationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:jn,reconstructor:r.reconstructor??new ae(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{ae as BrowserPlanMaterialReconstructor,Q as BusinessOrganizationSelectionError,xe as CoreSdkContainerRequired,L as ElementsApiRequestFailed,se as ElementsClient,J as HttpElementsApiPort,Ye as HttpOperatorAuthTransport,Ln as InheritiFileInvalid,qn as MAX_INHERITI_FILE_BYTES,fe as MasterKeyRelayCancellationFailed,he as MasterKeyRelayExpired,ge as MasterKeyRelayTimedOut,z as MasterKeyRequired,ne as MemoryKeyVault,re as MemoryStatePort,g as OAuthProtocolError,Qe as OperatorAuthClient,ee as OperatorAuthError,x as OperatorReauthenticationRequired,Ze as OperatorSessionController,pi as PassphraseMasterKeySource,ie as PlanMaterialReconstructorRequired,mi as RawMasterKeySource,te as RelayMasterKeySource,Se as RevealAuthorizationEnded,R as RevealFieldAccessError,Ae as RevealHandleClosed,Ke as StaticMasterKeyResolver,pe as SystemOAuthClock,ue as WebOAuthCrypto,gi as computePassphraseVerifier,ri as createBrowserElementsClient,ye as createMasterKeyResolver,jn as decodeAssetContainer,hi as deriveMasterKey,fi as generateHexSeed,Dn as generateInheritiFileKey,Le as masterKeyRefFor,V as masterKeyRefKey,me as oauthErrorCode,Kn as openInheritiFile,Fn as openInheritiFileKey,Ge as openScopedReveal,ct as parseAssetFieldSelector,Un as readInheritiFileHeader,dt as revealPhaseOf,Nn as sealInheritiFile,zn as sealInheritiFileKey,kn as selectBusinessOrganization,Ve as unwrapDekWithMasterKey};
|