@safetech/inheriti-client-sdk 1.17.21 → 1.17.22
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 +22 -22
- package/dist/node-base.js +1 -1
- package/dist/node.js +1 -1
- package/dist/sdk-types.d.ts +11 -0
- package/dist/src/business/inbox/types.d.ts +11 -0
- package/package.json +2 -2
package/dist/node-base.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createNodeSharedConfigurationSdk as ct,decodeAssetContainer as Zr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as tr,generateRSAOAEPKeyPair as rr}from"@safetech/inheriti-core-sdk/crypto";var Re=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Ee=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},we=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},M=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:r,privateKey:i}=await rr();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let a=await this.options.api.startRelaySession(r),s=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(m=>new Promise(y=>setTimeout(y,m))),l=!0,c=!1,u,R=()=>u??=(async()=>{let m=new AbortController,y,T=new Promise((C,z)=>{y=setTimeout(()=>{m.abort(),z(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(a.sessionId,m.signal),T])}finally{clearTimeout(y)}})(),S,O=new Promise((m,y)=>{S=()=>{l&&R().catch(()=>{}),y(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",S,{once:!0})});O.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(a),c=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let m=await Promise.race([this.options.api.readRelaySession(a.sessionId,e),O]);if(m.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(m.status==="DELIVERED"&&m.sealedMasterKey){let y=(await tr(m.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(y))throw new Error("invalid_master_key_material");return y}if(m.status==="EXPIRED")throw new Ee(a.sessionId);await nr(d,s,e)}throw new Re(a.sessionId)}catch(m){if(l&&(!c||e?.aborted))try{await R()}catch(y){if(e?.aborted)throw new we(y)}throw m}finally{S&&e?.removeEventListener("abort",S)}}};async function nr(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,i)=>{let a=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",a,{once:!0}),n(e).then(r,i).finally(()=>t.removeEventListener("abort",a))})}function Se(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let i=await n.source?.resolve();return i||Be(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(ir(e,n.applicationId)){let i=await n.source?.resolve();return i||Be(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return Be(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function ir(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function Be(n,e,t,r,i){if((await e()).relayAvailable)return new M({...n.relay,api:ar(n.api,t)}).resolve(r,i)}function ar(n,e){return{startRelaySession:t=>e?n.startMasterKeyRelaySession(t,e):n.startMasterKeyRelaySession(t),readRelaySession:(t,r)=>n.readMasterKeyRelaySession(t,r),cancelRelaySession:(t,r)=>n.cancelMasterKeyRelaySession(t,r)}}function V(n){return`${n.system}:${n.contextId}`}function se(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var q=class extends Error{constructor(t){super(`master_key_required:${V(t)}`);this.ref=t;this.name="MasterKeyRequired"}},$e=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(V(e),t),this}async resolve(e){return this.sources.get(V(e))?.resolve()}};var oe=class{keys=new Map;async store(e,t){let r=V(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,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 de=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var Ae=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},h=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var be=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var _e=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],He={"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"],I=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},b=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function j(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new b("plan_material_field_unknown");if(Fe(n.dataShards,"data_shards_invalid"),Fe(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&Fe(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new b("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new b("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new b("material_operation_invalid")}function Fe(n,e){if(!Array.isArray(n))throw new b(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new b(e);if(t.data!==void 0&&typeof t.data!="string")throw new b(e)}}function B(n){if(Q(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!dr(n.idempotencyKey))throw new I("idempotency_key_invalid");if(!n.name?.trim())throw new I("plan_name_required");if(!n.assets.length)throw new I("assets_required");let e=new Set;for(let t of n.assets){if(Q(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new I("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!_e.includes(t.type))throw new I("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new I("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new I("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new I("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(a=>!a.trim()))throw new I("asset_field_names_invalid");if(sr(t.matchOrigins),!t.isBinary){let a=He[t.type];if(!a||i.some(s=>!a.includes(s)))throw new I("asset_field_name_not_canonical")}}if(!n.participants.length)throw new I("participants_required");for(let t of n.participants){if(Q(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!mt(t.routingEmail))throw new I("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new I("participant_relationships_invalid")}or(n)}function sr(n){if(n===void 0)return;if(!n.length)throw new I("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new I("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new I("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof I?r:new I("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new I("asset_match_origins_duplicated")}function or(n){let e=n.policy;if(e&&Q(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new I("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){Q(e.authentication,["mode"],"plan_authentication_field_unknown");let a=e.authentication.mode;if(a!==void 0&&a!=="EXCLUSIVE"&&a!=="ALL_REQUIRED")throw new I("authentication_mode_invalid")}if(e.moderation){Q(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let a=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(a.length===0)throw new I("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>a.length))throw new I("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new I("approval_mode_invalid")}let t=e.dms;if(!t)return;Q(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!mt(t.subjectEmail))throw new I("dms_subject_invalid");if(!n.participants.some(a=>ut(a.routingEmail)===ut(t.subjectEmail)))throw new I("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(i)||t.countdownDays<0||r<0||r>23||i<0||i>59||t.countdownDays+r+i===0)throw new I("dms_countdown_invalid")}function dr(n){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(n)}function mt(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function ut(n){return n.normalize("NFC").trim().toLowerCase()}function Q(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new I(t)}var le=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)}},ce=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),B(e),Ce(t.signal);let r=await this.api.startPlanCreation(e);return r.outcome==="COMPLETED"||r.outcome==="CANCELED"?await this.checkpoints.remove(r.operationId):await this.saveCheckpoint(e,r),t.onProgress?.(r.stage),r}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,r,i,a={}){B(t);let s=await this.checkpoints.load(e);if(!s)throw new pe("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await gt(t))throw new pe("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(a.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Ce(a.signal),a.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:a.signal});Ce(a.signal),a.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:a.signal});Ce(a.signal),j(l);let c=await this.api.supplyPlanCreationMaterial(e,l);return a.onProgress?.(c.stage),c.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,c),c}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 gt(e),serverStage:t.stage})}},pe=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function gt(n){let e=JSON.stringify({name:n.name.normalize("NFC").trim(),description:n.description?.normalize("NFC").trim()??null,assets:n.assets.map(r=>({...r,fieldNames:[...r.fieldNames??[]]})).sort((r,i)=>r.clientAssetRef.localeCompare(i.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,i)=>r.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:n.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function Ce(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function ht(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new Ae(r.stage);return n.authorizeRevealAction(e,t)}function lr(n){let e=n?.status;return e===400||e===401||e===403}async function ft(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(a){if(!lr(a))throw a}return n.releaseRevealMaterial(e,t)}function cr(n){return n.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":n.stage==="STARTING"?"STARTING":n.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":n.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":n.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":n.stage==="WAITING_FOR_PARTICIPANTS"?ur(n):n.stage==="DENIED"?"DENIED":n.stage==="EXPIRED"?"EXPIRED":n.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":n.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":n.stage==="MATERIAL_RELEASED"||n.stage==="RECONSTRUCTED"?"RECONSTRUCTING":n.stage==="ACTIONS_OPEN"?"OPEN":pr.has(n.stage)?"ENDED":"CONTINUING"}var pr=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function ur(n){return n.governanceGate==="DMS"?"WAITING_FOR_DMS":n.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":n.governanceGate==="AUTHENTICATION"||n.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var Qe=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},A=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Pt(n,e,t={}){if(t.signal?.aborted)throw E();let r=await n.getPlan(e),i=await n.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):yt(i.id);if(t.signal?.aborted||(await n.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw E();let a=t.idempotencyKey??crypto.randomUUID(),s;try{s=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let l=await n.getActivePlanReveal(e);throw!l||l.planId!==e||l.mode!==(t.mode??"DIRECT")?d:yt(l.id)}let o;try{if(t.signal?.aborted)throw E();let d=await gr(n,s,t);if(t.signal?.aborted||($(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw E();let l=await n.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await n.markRevealSharesCollected(d.id),t.signal?.aborted))throw E();let c;try{c=await Ir(n,d,Pr(l),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||($(t,"RECONSTRUCTING",d),t.signal?.aborted))throw E();try{o=await n.reconstructPlanMaterial(c)}catch(R){throw t.signal?.aborted?E():(await n.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:yr(R)}),R)}if(t.signal?.aborted)throw E();let u=await n.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||($(t,"OPEN",u),t.signal?.aborted))throw E();return new Ye(n,u,r,o,t.signal)}catch(d){throw o?.fill(0),await Rt(n,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function yt(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var mr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function gr(n,e,t){let r=await G(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw E();if(t.onSession?.(r),t.onProgress?.({phase:cr(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(mr.has(r.stage))throw new je(r.stage);await Ze(t.pollIntervalMs??1500,t.signal),r=await G(()=>n.getReveal(e.id,t.signal),t.signal)}}var je=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function $(n,e,t){n.onProgress?.({phase:e,session:t})}function Ze(n,e){return e?.aborted?Promise.reject(E()):new Promise((t,r)=>{let i=setTimeout(s,Math.max(0,n)),a=()=>{clearTimeout(i),r(E())};function s(){e?.removeEventListener("abort",a),t()}e?.addEventListener("abort",a,{once:!0})})}var Ye=class{constructor(e,t,r,i,a){this.client=e;this.session=t;this.plan=r;this.plaintext=i;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=a?()=>{this.close("CANCELED").catch(()=>{})}:void 0,a&&this.abortListener&&a.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new Qe;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([i])=>{r=i?.value}),r}async consumeFields(e,t){if(e.length===0)throw new A("asset_selector_invalid");if(!this.client.assetDecoder)throw new A("asset_decoder_required");let r=e.map(({selector:a,options:s={}})=>{let o=hr(a),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new A("asset_not_found");if(d.isBinary)throw new A("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new A("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:s}}),i=[];try{for(let s of r)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let a=r.map(s=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===s.asset.id||d.id===s.assetCode);if(!o)throw new A("asset_value_invalid");return{selector:s.selector,value:fr(o.data,s.field,s.asset.type)}});await t(a)}catch(a){throw await Promise.all(i.map(s=>this.reportAction(s.id,"FAILED",It(a)))),a}await Promise.all(i.map(a=>this.reportAction(a.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new A("asset_selector_invalid");if(!this.client.assetDecoder)throw new A("asset_decoder_required");let r=this.plan.assets.find(s=>s.code===e||s.id===e);if(!r)throw new A("asset_not_found");if(!r.isBinary)throw new A("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),a;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===r.id||o.id===r.code);if(!s||!(s.data instanceof Uint8Array))throw new A("asset_value_invalid");a=s.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:a})}catch(s){throw await this.reportAction(i.id,"FAILED",It(s)),s}finally{a?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,r){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...r===void 0?{}:{errorCode:r}})}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 hr(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new A("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new A("asset_selector_invalid");return{asset:n.asset,field:n.field}}function fr(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new A("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new A("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?He[t]:void 0)?.includes(e))return"";throw new A("asset_value_invalid")}return r[e]}function It(n){if(n instanceof A)return n.code;let e=n?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function yr(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Ir(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await G(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new xe;let l=await G(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(vt(l,i.id,e.planId),!l.shares.includes(i.data))throw new K;$(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:c}=await G(()=>r.proDevice.write(l,r.signal),r.signal);if(r.signal?.aborted)throw E();if(!c?.trim())throw new K;if(await n.claimRevealCustodianShare(e.id,l.id,c),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,l.id),r.signal?.aborted))throw E();return{...t,shares:t.shares.filter(u=>u!==i).concat(l.shares.map((u,R)=>({id:`${l.id}:${R}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new K;if(r.signal?.aborted)throw E();return await n.distributeRevealCustodianShare(e.id),$(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let a=await G(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;a.status==="PENDING"||a.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),$(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Ze(r.pollIntervalMs??1500,r.signal),a=await G(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(a.status==="CLAIMED"&&a.deviceType==="SK_PRO"){if(!r.proDevice)throw new xe;if(!a.shareId||!a.deviceId)throw new K;$(r,"CONNECTING_SAFEKEY_PRO",e);let d=await G(()=>r.proDevice.read({shareId:a.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw E();if(vt(d,a.shareId,e.planId),d.deviceId!==a.deviceId)throw new K;if(await n.collectRevealCustodianShare(e.id,a.shareId),r.signal?.aborted)throw E();return{...t,shares:t.shares.concat(d.shares.map((l,c)=>({id:`${d.id}:${c}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(a.status!=="CLAIMED"||a.deviceType!=="SK_MOBILE")throw new K;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(s),$(r,"WAITING_FOR_CUSTODIAN",s),r.signal?.aborted)throw E();await n.requestRevealCustodianRelease(e.id);let o=await vr(n,e.id,r);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,l)=>({id:`${o.id}:${l}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function vt(n,e,t){if(n?.id!==e||n.planId!==t||!Array.isArray(n.shares)||n.shares.length===0||n.shares.some(r=>typeof r!="string"||!r))throw new K}async function G(n,e){if(e?.aborted)throw E();if(!e)return n();let t,r=new Promise((i,a)=>{t=()=>a(E()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw E();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function vr(n,e,t){let r=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await G(()=>n.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let a=i;if(a.shares?.length)return a;throw new K}if(Date.now()>=r)throw new Xe;await Ze(t.pollIntervalMs??1500,t.signal)}}var K=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},xe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Xe=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Pr(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Rt(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(s){if(!Rr(s))throw s}return}let r=new AbortController,i,a=new Promise((s,o)=>{i=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let s=await Promise.race([n.closeReveal(e,t,r.signal),a]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(s.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(s){if(s?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:s}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Rr(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function E(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var Y=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 oe,this.state=t.state??new de,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Sr(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 h;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new h;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new h;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return B(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new h;return j(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new le){if(this.requireApplication(),!this.api)throw new h;return new ce(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),r=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",r)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new q({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let i=await this.keyVault.load(e);if(i)return wr(i);let a=await this.masterKeys?.resolve(e,t,r);if(!a)throw new q(e);return await this.keyVault.store(e,Er(a)),a}async prepareReveal(e,t,r){if(!this.api)throw new h;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,r)}}async revealPlan(e,t){await this.prepareReveal(e);let r=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(r)}collectPlanMaterial(e,t){if(!this.api)throw new h;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new be;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,r){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 q({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=se(e);if(!i)throw new q({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new h;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new h;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new h;return this.api.getReveal(e,t)}openReveal(e,t){return Pt(this,e,t)}async withReveal(e,t,r){let i=await this.openReveal(e,t);try{let a=await r(i);return await i.close("COMPLETED"),a}catch(a){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),a}}async releaseRevealMaterial(e,t){if(!this.api)throw new h;return ft(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new h;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new h;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new h;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new h;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new h;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new h;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new h;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new h;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new h;return ht(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new h;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new h;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new h;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new h;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new h;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new h;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let r=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 a=r.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),s=i.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),o=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||r.dek,shares:a.concat(s,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let r=await this.reconstructPlanMaterial(t);if(!this.api)throw new h;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),r}useCase(e,t){if(!this.coreSdk)throw new Je;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new q({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Je=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Er(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function wr(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Sr(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return Se({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return Se({...e,organizationId:n.organizationId})}var Ar=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],br=["DIRECT","GOVERNED"],wt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],_r=["ACTIVE","REVOKED"],Cr=["SK_MOBILE"],xr=["ACTIVE","INACTIVE"],Tr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function St(n){let e=_(n);return{items:D(e.items).map(bt),nextCursor:e.nextCursor===null?null:g(e.nextCursor,"nextCursor")}}function At(n){let e=_(n);return{total:U(e.total,"total"),items:D(e.items).map(t=>{let r=_(t);if("eventData"in r)throw new Error("invalid_elements_response");return{id:g(r.id,"log.id"),planId:g(r.planId,"log.planId"),tenantId:g(r.tenantId,"log.tenantId"),event:g(r.event,"log.event"),occurredOn:g(r.occurredOn,"log.occurredOn"),status:F(r.status),title:g(r.title,"log.title"),details:D(r.details).map(i=>{let a=_(i);return{label:g(a.label,"log.detail.label"),value:g(a.value,"log.detail.value")}})}})}}function Te(n){let e=_(n),t=bt(e),r=_(e.source),i=g(r.kind,"source.kind");return{...t,assets:D(e.assets).map(a=>{let s=_(a);return{id:g(s.id,"asset.id"),code:F(s.code),type:x(g(s.type,"asset.type"),_e),name:g(s.name,"asset.name"),isBinary:kr(s.isBinary,"asset.isBinary"),fieldNames:D(s.fieldNames).map(o=>g(o,"asset.fieldNames")),fileName:F(s.fileName),mimeType:F(s.mimeType),size:s.size===void 0||s.size===null?void 0:U(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:D(s.matchOrigins).map(o=>g(o,"asset.matchOrigins"))}}),participants:D(e.participants).map(a=>{let s=_(a);return{id:g(s.id,"participant.id"),displayName:g(s.displayName,"participant.displayName"),relationships:D(s.relationships).map(o=>x(g(o,"relationship"),wt)),lifecycle:x(g(s.lifecycle,"participant.lifecycle"),_r)}}),revealPolicy:(()=>{let a=_(e.revealPolicy);return{masterKeyRelease:x(g(a.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:x(g(a.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let a=_(e.dms);return{subjectEmail:g(a.subjectEmail,"dms.subjectEmail"),countdownDays:U(a.countdownDays,"dms.countdownDays"),countdownHours:U(a.countdownHours,"dms.countdownHours"),countdownMinutes:U(a.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:x(g(r.system,"source.system"),["INHERITI_BUSINESS"]),status:x(g(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ue(n){let e=_(n);return{operationId:g(e.operationId,"operationId"),stage:x(g(e.stage,"stage"),We),outcome:x(g(e.outcome,"outcome"),Tr),planId:F(e.planId),lastErrorCode:F(e.lastErrorCode),participants:e.participants===void 0?void 0:D(e.participants).map(t=>{let r=_(t);return{clientParticipantRef:g(r.clientParticipantRef,"clientParticipantRef"),planParticipantId:g(r.planParticipantId,"planParticipantId"),relationships:D(r.relationships).map(i=>Dr(g(i,"relationship"),wt))}})}}function bt(n){let e=_(n),t=_(e.assetSummary),r=_(e.governance),i=_(e.participantSummary);return{id:g(e.id,"id"),name:g(e.name,"name"),description:F(e.description),status:x(g(e.status,"status"),Ar),createdAt:g(e.createdAt,"createdAt"),configuredAt:F(e.configuredAt),assetSummary:{count:U(t.count,"assetSummary.count"),types:D(t.types).map(a=>x(g(a,"assetType"),_e)),names:Et(t.names).map(a=>g(a,"assetSummary.names"))},governance:{mode:x(g(r.mode,"governance.mode"),br),minimumApprovals:U(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:U(i.owners,"owners"),mergers:U(i.mergers,"mergers"),moderators:U(i.moderators,"moderators")},authentication:Et(e.authentication).map(a=>{let s=_(a);return{id:x(g(s.id,"authentication.id"),Cr),status:x(g(s.status,"authentication.status"),xr)}})}}function x(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function Dr(n,e){if(!e.includes(n))throw new Error("invalid_elements_response");return n}function _(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function Et(n){return n==null?[]:D(n)}function D(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function g(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function F(n){return n==null?void 0:g(n,"optional")}function U(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function kr(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}var te=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function _t(n){if(!n||typeof n!="object"||!("items"in n)||!Array.isArray(n.items)||!n.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 n.items.map(({id:e,name:t})=>({id:e,name:t}))}function Or(n,e){if(!e){if(n.length===0)throw new te("organization_required");if(n.length>1)throw new te("organization_selection_required");return n[0].id}if(!n.some(({id:t})=>t===e))throw new te("organization_access_denied");return e}function Mr(n){let e=P(n);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:f(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),createdAt:k(e.createdAt)}}function Ct(n){let e=P(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Mr),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0),unreadCount:f(e.unreadCount,0),readThroughSequence:f(e.readThroughSequence,0)}}function xt(n){let e=P(n);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:p(e.parentId),sequence:f(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let r=P(t);return{unitId:p(r.unitId),position:f(r.position,0),commitment:p(r.commitment),status:p(r.status)}})}}function et(n){let e=P(n);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:f(e.sequence,1),status:e.status}}function Tt(n){let e=P(n);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:f(e.participantRevision,1),recipients:e.recipients.map(tt)}}function Dt(n){let e=P(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=P(t);return{parentId:p(r.parentId),sequence:f(r.sequence,1),senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),participantRevision:f(r.participantRevision,1),createdAt:k(r.createdAt)}}),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0),unreadCount:f(e.unreadCount,0),readThroughSequence:f(e.readThroughSequence,0)}}function kt(n){return{readThroughSequence:f(P(n).readThroughSequence,0)}}function Ot(n){return{clearedThroughSequence:f(P(n).clearedThroughSequence,0)}}function Mt(n){let e=P(n);return{parentId:p(e.parentId),sequence:f(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function P(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_inbox_response");return n}function p(n){if(typeof n!="string"||!n)throw new Error("invalid_inbox_response");return n}function k(n){let e=p(n);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function f(n,e){if(!Number.isSafeInteger(n)||n<e)throw new Error("invalid_inbox_response");return n}function tt(n){let e=P(n);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:f(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function re(n){let e=P(n);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:k(e.createdAt),updatedAt:k(e.updatedAt)}}function De(n){let e=P(n);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:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:k(e.createdAt),updatedAt:k(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 r=P(e.latestMessage);if(r.contentKind!=="TEXT"&&r.contentKind!=="FILE"&&r.contentKind!=="NORMAL"&&r.contentKind!=="MIXED"&&r.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:r.contentKind,senderMemberId:p(r.senderMemberId),createdAt:k(r.createdAt)}}return t}function Nt(n){let e=P(n);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(De),total:e.total,limit:e.limit,offset:e.offset}}function Kt(n){let e=P(n);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 r=tt(t);return{memberId:r.memberId,name:p(P(t).name),deviceId:r.deviceId,deviceVersion:r.deviceVersion,encryptionPublicKey:r.encryptionPublicKey,encryptionKeyFingerprint:r.encryptionKeyFingerprint,signingPublicKey:r.signingPublicKey,signingKeyFingerprint:r.signingKeyFingerprint}}),limit:f(e.limit,1),offset:f(e.offset,0),nextOffset:e.nextOffset===null?null:f(e.nextOffset,0)}}function Ut(n){let e=P(n);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 r=P(t);if(typeof r.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(r.memberId),name:p(r.name),ready:r.ready,...r.profilePicture===void 0?{}:{profilePicture:{url:p(P(r.profilePicture).url)}}}}),limit:f(e.limit,1),offset:f(e.offset,0),nextOffset:e.nextOffset===null?null:f(e.nextOffset,0)}}function Lt(n){let e=P(n);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:p(e.conversationId),messageId:p(e.messageId),participantRevision:f(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(tt),shareLayers:e.shareLayers.map(t=>{let r=P(t),i=p(r.id),a=p(r.dataShareId),s=p(r.keyShareId);if(r.type==="INHERITI_CHAIN")return{id:i,type:r.type,contractAddress:p(r.contractAddress),dataShareId:a,keyShareId:s};if(r.type==="INHERITI_VAULT"||r.type==="GOOGLE_DRIVE"||r.type==="DROPBOX"||r.type==="ONEDRIVE")return{id:i,type:r.type,dataShareId:a,keyShareId:s};throw new Error("invalid_inbox_response")})}}function ke(n){let e=P(n);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:p(e.messageId),status:e.status}}function qt(n){let e=P(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=P(t);if(r.status!=="PREPARING"&&r.status!=="AVAILABLE"&&r.status!=="FAILED"&&r.status!=="DELETING")throw new Error("invalid_inbox_response");if(r.contentKind!==void 0&&r.contentKind!=="TEXT"&&r.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(r.recipientStatus!==void 0&&r.recipientStatus!=="UNREAD"&&r.recipientStatus!=="LEASED"&&r.recipientStatus!=="CONSUMED"&&r.recipientStatus!=="EXPIRED"&&r.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(r.recipientStatuses!==void 0&&!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:p(r.id),status:r.status,senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),createdAt:k(r.createdAt),updatedAt:k(r.updatedAt),expiresAt:k(r.expiresAt)};return r.contentKind&&(i.contentKind=r.contentKind),r.recipientStatus&&(i.recipientStatus=r.recipientStatus),Array.isArray(r.recipientStatuses)&&(i.recipientStatuses=r.recipientStatuses.map(a=>{let s=P(a);if(s.status!=="UNREAD"&&s.status!=="LEASED"&&s.status!=="CONSUMED"&&s.status!=="EXPIRED"&&s.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:p(s.memberId),status:s.status}})),i}),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0)}}function Gt(n){let e=P(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:k(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=P(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:f(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId),ciphertext:p(r.ciphertext)}})}}function zt(n){let e=P(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:k(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=P(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:f(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId)}})}}function X(n){return typeof n.error=="string"?/^[a-z][a-z0-9_]*$/.test(n.error)?n.error:typeof n.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(n.validationErrors)?n.validationErrors:n.error||void 0:n.error?.code??n.name??n.message}function Z(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var N=class extends Error{constructor(t,r,i,a){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.requestId=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ne=class{constructor(e,t,r,i,a){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i;this.business=a?Object.freeze({...a}):void 0}business;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:re(t)}async getMemberInboxDevice(e,t){let r=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return r===null?null:re(r)}async registerInboxDevice(e){return re(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return re(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return re(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return De(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return De(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Nt(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Kt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Ut(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Lt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Tt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let r={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",r))}async publishNormalInboxMessage(e,t){return et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},r){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 a=i.size?`?${i}`:"";return Ct(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${a}`,"GET",void 0,void 0,void 0,r))}async openInboxParent(e,t,r,i){let a=new URLSearchParams({deviceId:r});return xt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return Ot(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},r){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 a=i.size?`?${i}`:"";return Dt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${a}`,"GET",void 0,void 0,void 0,r))}async openNormalInboxMessage(e,t,r,i){let a=new URLSearchParams({deviceId:r});return Mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,r){return kt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:r}))}async stageInboxFile(e,t,r){return ke(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,r))}async uploadInboxFileShare(e,t,r,i,a){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let s=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}`,o=await this.requestBinary(s,"PUT",i,a),d=await Oe(o,a);if(!d.ok||d.result?.shareId!==r||d.result.status!=="STORED")throw new N(o.status,X(d),Z(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,r){return ke(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,r))}async openInboxFile(e,t,r,i){return zt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:r},void 0,void 0,i))}async downloadInboxFileShare(e,t,r,i,a,s){let o=new URLSearchParams({deviceId:i,leaseId:a}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}?${o}`,l=await this.requestBinary(d,"GET",void 0,s);if(!l.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let c=Number(l.headers.get("content-length"));if(Number.isFinite(c)&&c>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!l.body)throw new Error("invalid_inbox_share_response");let u=l.body.getReader(),R=[],S=0;try{for(;;){s?.throwIfAborted();let y=await u.read();if(y.done)break;if(S+=y.value.length,S>14*1024*1024)throw new Error("invalid_inbox_share_size");R.push(y.value)}}catch(y){throw await u.cancel().catch(()=>{}),y}let O=new Uint8Array(S),m=0;for(let y of R)O.set(y,m),m+=y.length;return O}async listInboxMessages(e,t={},r){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 a=i.size?`?${i}`:"";return qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${a}`,"GET",void 0,void 0,void 0,r))}async openInboxMessage(e,t,r){return Gt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:r}))}async ackInboxMessage(e,t,r,i,a){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:r,leaseId:i},void 0,void 0,a)}async releaseInboxMessage(e,t,r,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:r,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(_t)}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 r=t.size?`?${t}`:"";return St(await this.request(`v1/plans${r}`,"GET"))}async getPlan(e){return Te(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let r=new URLSearchParams;t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return At(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){B(e);let{idempotencyKey:t,...r}=e;return ue(await this.request("v1/plan-creations","POST",r,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return j(t),ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:r,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":r})}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,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:r})}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,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,r)}abortPlanAccess(e,t){let r=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${r}?revealId=${encodeURIComponent(t)}`:r,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...a}=r;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,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,r,i,a,s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken();s?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),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[S,O]of Object.entries(a??{}))d.set(S,O);r&&d.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c={method:t,headers:d,body:r?JSON.stringify(r):void 0};s&&(c.signal=s);let u=await this.transport(new URL(e,l),c);s?.throwIfAborted();let R=await Oe(u,s);if(s?.throwIfAborted(),!u.ok)throw new N(u.status,X(R),Z(R),u.headers.get("x-request-id")??void 0);if(!R.ok||R.result===void 0)throw new N(u.status,X(R),Z(R),u.headers.get("x-request-id")??void 0);return R.result}async requestBinary(e,t,r,i){this.requireBusinessSelection(e),i?.throwIfAborted();let a=await this.getBearerToken();i?.throwIfAborted();let s=new Headers({"x-elements-environment":this.environment});a&&s.set("authorization",`Bearer ${a}`),this.business?.organizationId&&s.set("x-organization-id",this.business.organizationId),r&&s.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:s,body:r?Buffer.from(r):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let l=await Oe(d,i);throw new N(d.status,X(l),Z(l),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let r=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});r&&i.set("authorization",`Bearer ${r}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,a),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),o=await Oe(s);if(!s.ok||!o.ok)throw new N(s.status,X(o),Z(o),s.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new N(400,"organization_selection_required")}};async function Oe(n,e){try{return await n.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Vr}from"@safetech/inheriti-core-sdk/node";async function rt(n,e){if(!e)throw new Error("master_key_required");let t=Nr(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Kr(n),a=i.slice(0,12),s=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},r,s);return Ur(new Uint8Array(o))}function Nr(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Kr(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Ur(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var me=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await Vt("plan_key_unwrap_failed",()=>rt(e.planKey,t)),i=await crypto.subtle.importKey("raw",nt(r),{name:"AES-GCM"},!1,["decrypt"]),a=[],s=[];for(let o of e.shares){let d=await Vt("plan_share_decryption_failed",()=>zr(o.data,i));Gr(o.shareType)?s.push(d):a.push(d)}try{return await this.processor().reconstruct(a,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new Me("plan_share_reconstruction_failed",qr(o))}}},Me=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},Lr=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 qr(n){let e=n instanceof Error?n.message:void 0;if(e)return Lr.has(e)?e:void 0}async function Vt(n,e){try{return await e()}catch{throw new Me(n)}}function Gr(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function zr(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=nt(n.slice(0,t)),i=nt(n.slice(t+1)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(a)}function nt(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i+=1)r[i]=e.charCodeAt(i);return t}var J=class extends me{constructor(e){super(()=>Vr(e))}};var ge=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Te(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,r){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,r)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...a}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let r=this.firstRelayStates.get(e);return r?(this.firstRelayStates.delete(e),Promise.resolve(r)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,r,i=!0,a,s){s?.throwIfAborted();let o=await this.getAutomationBearerToken();if(s?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...a});r!==void 0&&d.set("content-type","application/json");let l=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:r===void 0?void 0:JSON.stringify(r),signal:s});s?.throwIfAborted();let c;try{c=await l.json()}catch{s?.throwIfAborted()}if(!l.ok||c&&c.ok===!1||i&&c?.result===void 0)throw new N(l.status,c&&X(c),c&&Z(c));return c?.result}};var w={invalidDeclaration:"plan_declaration_invalid",invalidShares:"plan_share_count_invalid",storageChanged:"plan_storage_context_changed",invalidMasterKeyContext:"invalid_master_key_context",reauthenticationRequired:"operator_reauthentication_required",relayFailed:"master_key_relay_failed",reconciliationRequired:"reconciliation_required"};var H=class extends Error{constructor(t,r){super(r??`plan_request_failed_${t}`);this.status=t;this.code=r}},he=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,r,i,a){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:r,...a?{description:a}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:r.validatorShares,encryptedKey:r.encryptedKey})}preflight(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",Bt(r))}configure(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",Bt(r))}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(w.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(w.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(w.relayFailed);return r}async request(e,t,r,i){let a=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),s=await this.getBearerToken();if(!s)throw new Error(w.reauthenticationRequired);a.set("authorization",`Bearer ${s}`),i!==void 0&&a.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,l=await this.transport(new URL(d,o),{method:r,headers:a,body:i===void 0?void 0:JSON.stringify(i)}),c={};try{c=await l.json()}catch{}if(!l.ok||c.ok!==!0)throw new H(l.status,c.error);return c.result}};function Bt(n){return{protectionProtocol:n.protectionProtocol,operation:"FINALIZE",dataShards:n.dataShards,backupShards:n.backupShards,encryptedKey:n.encryptedKey,assetsMetadata:n.assetsMetadata,custodianPair:n.custodianShard}}var ye=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){fe(e.signal),$r(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return fe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){fe(e.signal);let t=e.encrypted.totalShares+1,r=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:r,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(fe(e.signal),!i.custodianPair)throw new b("custodian_share_required");let a=it(i.keyShards),s=await this.sealer.encryptShares(a,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(it(i.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares(it(i.backupShards),s.symmetricKeyBase64),l=await this.sealCustodianPair(i.custodianPair,s.symmetricKeyBase64);return fe(e.signal),{protectionProtocol:i.protocol,validatorShares:at(s.encryptedShares),dataShards:at(o.encryptedShares),backupShards:at(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:Br(e.encrypted.assets,e.declaration),custodianShard:l,operation:"FINALIZE"}}async sealCustodianPair(e,t){let r=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:st(r.encryptedShares[0]),dataShard:st(r.encryptedShares[1])}}};function it(n){return n.map(e=>({id:crypto.randomUUID(),data:e}))}function at(n){return n.map(st)}function st(n){return{id:n.id,data:n.encryptedData}}function Br(n,e){let t={};for(let r of n){let i=e.assets.find(a=>a.clientAssetRef===r.id);if(!i)throw new b("plan_secrets_declaration_mismatch");t[r.id]={type:r.type,meta:{name:r.meta.name,notes:r.meta.notes,...r.meta.isMedia===void 0?{}:{isMedia:r.meta.isMedia},...r.meta.mimeType===void 0?{}:{mimeType:r.meta.mimeType},...r.meta.fileName===void 0?{}:{fileName:r.meta.fileName},...r.meta.code===void 0?{}:{code:r.meta.code},...r.meta.matchOrigins===void 0?{}:{matchOrigins:[...r.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function $r(n,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new b("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new b("share_threshold_invalid");if(e.assets.length!==n.assets.length)throw new b("plan_secrets_declaration_mismatch");let t=new Map(n.assets.map(r=>[r.clientAssetRef,r]));for(let r of e.assets){let i=t.get(r.id);if(!i||i.type!==r.type)throw new b("plan_secrets_declaration_mismatch")}}function fe(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function $t(n,e,t,r,i,a,s){let o=r.mergeThreshold-(r.withCustodian?1:0);if(typeof r.withCustodian!="boolean"||!Number.isInteger(r.mergeThreshold)||o<1||o>n.totalShares)throw new Error(w.invalidShares);let{assets:d,plan:l}=e;l.policy={custodian:r.withCustodian?"FORCE":"BYPASS"};let c=n.masterKeySource??new M({api:{startRelaySession:S=>i.startRelaySession(n.organizationId,t.masterKeyAcquisition,S),readRelaySession:S=>i.readRelaySession(n.organizationId,S)}}),u=new ye(a,c);s?.("encrypting");let R=await u.encrypt({planId:n.planId,declaration:l,secrets:{assets:d,totalShares:n.totalShares,threshold:o}});return s?.("generating_shares"),u.generateShares({planId:n.planId,declaration:l,encrypted:R})}import{PlanAssetDeclaration as Fr}from"@safetech/inheriti-core-sdk/node";function Ft(n){let e=ot({planId:n.planId,title:n.title,assets:[n.asset]});return{asset:e.assets[0],plan:e.plan}}function ot(n){if(!n.assets.length)throw new I("assets_required");let e=n.assets.map(a=>{if(a.meta.isMedia!==!0)return;let s="data"in a.secret?a.secret.data:void 0,o;if(s instanceof Blob&&(o=s.size),typeof s=="string")try{o=atob(s).length}catch{throw new I("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new I("binary_asset_metadata_invalid");return o}),t=Fr.create(n.assets.map(({type:a,meta:s})=>({type:a,meta:s}))),r=t.complete(Object.fromEntries(t.entries.map((a,s)=>[a.id,n.assets[s].secret]))),i={idempotencyKey:n.planId,name:n.title,assets:r.map((a,s)=>{let o=a.meta.isMedia===!0;return{clientAssetRef:a.id,type:a.type,name:a.meta.name,fieldNames:o?[]:Object.keys(a.secret),isBinary:o,fileName:a.meta.fileName,mimeType:a.meta.mimeType,size:e[s]}}),participants:[]};return{assets:r,plan:i}}async function Wt(n){let e=await Promise.all(n.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([r],[i])=>r.localeCompare(i)).map(async([r,i])=>[r,i instanceof Blob?await Ht(new Uint8Array(await i.arrayBuffer())):i]))})));return Ht(new TextEncoder().encode(JSON.stringify({organizationId:n.organizationId,planId:n.planId,title:n.title,description:n.description??null,audience:n.audience??null,totalShares:n.totalShares,assets:e})))}async function Ht(n){let e=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ie=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){return this.createPlan({...e,assets:[e.asset]},t)}async createPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!Array.isArray(e.assets)||!e.assets.length||e.assets.some(s=>!s?.meta?.name?.trim()))throw new Error(w.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(w.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(w.invalidShares);let r=await Wt(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==r)throw new Error(w.reconciliationRequired);return i.promise}let a=this.performCreate(e,r,t);this.flights.set(e.planId,{fingerprint:r,promise:a});try{return await a}finally{this.flights.delete(e.planId)}}async performCreate(e,t,r){let i=ot({planId:e.planId,title:e.title,assets:e.assets}),a=this.material.get(e.planId);if(a&&(a.fingerprint!==t||a.masterKeySource!==e.masterKeySource))throw new Error(w.reconciliationRequired);let s=await this.statusOrMissing(e.organizationId,e.planId);if(Ne(s))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(s&&!a)throw new Error(w.reconciliationRequired);if(!s&&a)throw new Error(w.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(w.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(w.invalidMasterKeyContext);if(!s){r?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(c){if(s=await this.statusOrMissing(e.organizationId,e.planId),!s)throw c}}s??=await this.port.status(e.organizationId,e.planId);let d=a?.encrypted??await $t(e,i,o,s,this.port,this.coreSdk,r);a||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),r?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),r?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),r?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(c){if(!Ne(await this.statusOrMissing(e.organizationId,e.planId)))throw c}r?.("verifying");let l=await this.port.status(e.organizationId,e.planId);return Ne(l)&&this.material.delete(e.planId),{planId:e.planId,status:Ne(l)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(w.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(r){if(r instanceof H&&r.status===404)return;throw r}}};function Ne(n){return n?.status==="PROTECTED"||n?.status==="CONFIGURED"}var Ke=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}start(e,t,r,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:r},i)}async listEligibleCandidates(e,t,r){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),r&&i.set("namePrefix",r);let a=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(a))throw new Error("invalid_plan_edit_candidates");return a}async context(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(r))throw new Error("invalid_plan_edit_context");return r}async moderatorNames(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!r||typeof r!="object")throw new Error("invalid_plan_edit_participants");let i=r;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let a=new Map;for(let s of i.participants){if(!s||typeof s.id!="string"||!s.id||typeof s.displayName!="string"||!Array.isArray(s.relationships)||!s.relationships.every(o=>typeof o=="string")||typeof s.lifecycle!="string")throw new Error("invalid_plan_edit_participants");s.lifecycle==="ACTIVE"&&s.relationships.includes("MODERATOR")&&a.set(s.id,s.displayName)}return a}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(w.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(w.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(w.relayFailed);return r}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(r))}commit(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(r))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,r,i,a){let s=await this.getBearerToken();if(!s)throw new Error(w.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${s}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),a&&o.set("idempotency-key",a);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),l=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,c=await this.transport(new URL(l,d),{method:r,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),u={};try{u=await c.json()}catch{}if(!c.ok||u.ok!==!0){let R=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new H(c.status,R||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(r=>!!r&&typeof r.id=="string"&&!!r.id&&typeof r.name=="string"&&r.status==="PROTECTED"&&typeof r.createdAt=="string"&&!!r.assetSummary&&Number.isSafeInteger(r.assetSummary.count)&&r.assetSummary.count>=0&&Array.isArray(r.assetSummary.types)&&r.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(r.assetSummary.names)&&r.assetSummary.names.every(i=>typeof i=="string")&&!!r.governance&&["DIRECT","GOVERNED"].includes(r.governance.mode)&&Number.isSafeInteger(r.governance.minimumApprovals)&&r.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var Ue=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.recoveryStore=r}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let r=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),a=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!a)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let s=this.revealedAssets,o=s?.organizationId===e.organizationId&&s.planId===e.planId&&s.editId===e.editId&&s.expiresAt>Date.now();s&&!o&&(this.revealedAssets=void 0);let d=a.masterKeyEncrypted?e.masterKey??(o?s.masterKey:void 0):void 0;a.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let l=Date.now()+10*6e4;o||t?.("opening_plan");let c=o?s.assets:await this.revealAssets(e,d,a.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(c.map(u=>u.id)).size!==c.length)throw new Error("duplicate_existing_asset_id");return!o&&r===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,l),assets:c,masterKey:d}),{plan:a,masterKey:d,assets:c}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),r=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(r>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return r}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new M({api:{startRelaySession:r=>this.port.startRelaySession(e.organizationId,t,r),readRelaySession:r=>this.port.readRelaySession(e.organizationId,r)}}).resolve()}async revealAssets(e,t,r,i){let a=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),s=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=m=>{m!==o&&(o=m,i?.(m))},l=m=>{if(m.processId!==e.editId||m.planId&&m.planId!==e.planId)return;switch(m.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let y=this.approvalError(m);if(y?.startsWith("edit_authentication_")&&d("pending_auth"),y?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!m.moderatorParticipants||m.requiredModeratorApprovals===void 0||!m.approvalProcess)return;let T=m.moderatorParticipants.map(C=>C.memberId??C.userId);T.some(C=>typeof C!="string"||!C)||new Set(T).size!==T.length||i?.(o,{requiredApprovals:m.requiredModeratorApprovals,approvedModerators:m.approvalProcess.approvedModerators,moderators:m.moderatorParticipants.map((C,z)=>{let ie=T[z],pt=C.flows.filter(ae=>ae.status==="PENDING"&&ae.expiresAt&&Number.isFinite(ae.expiresAt.getTime())).map(ae=>ae.expiresAt.getTime());return{id:ie,displayName:s.get(ie)||"Moderator",status:C.status,expiresAt:pt.length?new Date(Math.min(...pt)).toISOString():void 0}})})},c=await a.resume(e.planId,{onViewUpdate:l});if(c?.processId!==e.editId||c.planId&&c.planId!==e.planId)throw new Error("edit_merge_not_ready");l(c),this.assertApprovalOutcome(e.planId,c),c.status!=="READY_TO_REVEAL"&&c.status!=="REVEALED"&&await a.run(e.editId,{onViewUpdate:l,onApprovalsRequested:()=>d("pending_approvals")});let u=await a.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");l(u),this.assertApprovalOutcome(e.planId,u);let R=u?.status;if(R!=="READY_TO_REVEAL"&&R!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let S=null,O={onRevealed:m=>{S=m},onViewUpdate:l,onRevealStepUpdate:(m,y)=>{if(y==="IN_PROCESS")switch(m){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(r&&(O.onCustodianShareRequired=async(m,y)=>{switch(y.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let T=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),T==="SK_MOBILE")return a.distributeCustodianShareViaMobile(y.planId);if(T!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let C=e.proDevice;try{this.assertNotAborted(e.signal);let z=await a.getCustodianShareData(m);this.assertShare(z,y.planId),d("connecting_safekey_pro");let{deviceId:ie}=await C.write(z,e.signal);if(this.assertNotAborted(e.signal),!ie?.trim())throw new Error("custodian_share_unavailable");await a.recordCustodianShareClaim(y.planId,z.id,ie,"SK_PRO"),this.assertNotAborted(e.signal),await a.markCustodianShareAsCollected(m,z.id);return}finally{C.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let T=e.proDevice;try{if(this.assertNotAborted(e.signal),!y.shareId||!y.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let C=await T.read({shareId:y.shareId,planId:y.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(C,y.planId,y.shareId),C.deviceId!==y.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:C.shares}}finally{T.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),R==="REVEALED"?await a.resumeReveal(e.editId,O,t):await a.openRevealWindow(e.editId,{timeoutMinutes:10},O,t),this.assertNotAborted(e.signal),!S)throw new Error("edit_assets_unavailable");return S}assertApprovalOutcome(e,t){let r=this.approvalError(t);if(r)throw this.clearRevealedAssets(e),new Error(r)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,r){if(!e||!e.id||e.id!==(r??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var Hr=n=>JSON.stringify(n??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([r],[i])=>r<i?-1:r>i?1:0))),Le=class{constructor(e,t,r,i){this.port=e;this.coreSdk=t;this.recoveryStore=r;this.clearRevealedAssets=i}async saveAssets(e,t,r,i,a,s){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,r,i);s?.("preparing");let l=await o.prepare(d);this.assertNotAborted(e.signal);let c={mergeProcessId:e.editId,protectionProtocol:l.protectionProtocol,validatorShares:this.transportShares(l.validatorShares),dataShards:this.transportShares(l.dataShards),backupShards:this.transportShares(l.backupShards),encryptedKey:l.encryptedKey,assetsMetadata:l.assetsMetadata,custodianPair:l.custodianPair};if(s?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,c),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:a,material:c}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,a,c,o,d,s)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let r=await this.configurationRepository().findByPlanId(e.planId),i=r?.editDistribution??r?.preparedDistribution;if(!t&&(!i||r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let a=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),dataShards:i.dataShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),backupShards:i.backupShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,a))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!r?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let s=await this.port.status(e.organizationId,e.editId);return s.id!==e.editId||s.planId!==e.planId||s.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,a),await this.port.commit(e.organizationId,e.planId,a),await this.isCommitted(e,a)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let r=await this.configurationRepository().findByPlanId(e.planId);if(r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let r=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await r.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await r.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,r,i){let a=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),s={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:r,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:a,configuration:s}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,r,i,a,s){let o,d=l=>{let c;switch(l.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":c="distributing_validators";break;case"SHARES_DISTRIBUTION":c="distributing_data";break;case"FINALIZE":c="finalizing";break;default:return}c!==o&&(o=c,s?.(c))};try{await i.execute(a,{onLocalProcessUpdated:d})}catch(l){try{if(s?.("verifying"),await this.isCommitted(e,r))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&s?.(o),l}try{if(s?.("verifying"),!await this.isCommitted(e,r))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let r=await this.port.commitStatus(e.organizationId,e.editId);if(r.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(r.status)||r.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(Hr(t.assetsMetadata)),a=await globalThis.crypto.subtle.digest("SHA-256",i),s=Array.from(new Uint8Array(a),l=>l.toString(16).padStart(2,"0")).join("");if(r.assetsMetadataHash!==s)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(l=>l.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(r.shares.map(l=>l.id));return!o.some(l=>!d.has(l))}};var qe=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.assetAccess=new Ue(e,t,r),this.reconfiguration=new Le(e,t,r,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,r,i){return this.port.start(e,t,r,i)}async listAssets(e,t){let{assets:r}=await this.assetAccess.loadAssets(e,t);return r.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,r){let{assets:i}=await this.assetAccess.loadAssets(e,r),a=i.find(s=>s.id===t);if(!a)throw new Error("edit_asset_not_found");return structuredClone(a)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:r,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=a.findIndex(c=>c.id===e.assetId);if(s<0)throw new Error("edit_asset_not_found");let o=a[s];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},l=a.map((c,u)=>u===s?d:c);return this.reconfiguration.saveAssets(e,l,r.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:r,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=Ft({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(a.map(d=>d.id)).has(s.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,a.concat(s),r.withCustodian,i,s.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function Qt({apiUrl:n,organizationId:e,planId:t,editId:r,environment:i,transport:a}){return(s,o)=>{let d=new URL(s instanceof Request?s.url:s.toString()),l=new URL(n.endsWith("/")?n:`${n}/`);if(d.origin!==l.origin||!d.pathname.startsWith(l.pathname))throw new Error("unsupported_core_edit_route");let c=d.pathname.slice(l.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(c===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return a(d,o)}if(c==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let u=Wr(c,d.searchParams,t,r),R=new Headers(o?.headers);R.set("x-organization-id",e),R.set("x-elements-environment",i);let S=l.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return a(new URL(S,l),Object.assign({},o,{headers:R}))}}function Wr(n,e,t,r){if(n==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let a=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(n);if(a){let o=a[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(a[1]!==r||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(a[1])}/${d[o]}`}let s=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(n);if(s){if(s[1]!==t)throw new Error("edit_plan_id_mismatch");let o=s[2]??"";if(o==="")return`edits/${encodeURIComponent(r)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(s[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(r)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as Qr}from"@safetech/inheriti-core-sdk/node";function jt(n){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let r=await n.api.planKeyReference(e),i=se(r);if(!r.masterKeyWrapped||!i||r.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new M({api:{startRelaySession:o=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>n.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>n.api.cancelMasterKeyRelaySession(o,d)}});return new Y(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(o,d,l)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(d,l)}}}).openReveal(e,t)}}}function jr(n){let e=new ge(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{...jt({api:e,reconstructor:new J(n.workerUrl),assetDecoder:Qr}),getPlan:t=>e.getPlan(t)}}import{DataAssetDefinitionService as ya}from"@safetech/inheriti-core-sdk/node";function Yt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Ge=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Yt(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Yt(new Uint8Array(t))}},ze=class{now(){return Date.now()}sleep(e,t){return new Promise((r,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let a=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(a),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var ve=class extends Error{constructor(t,r=t){super(r);this.code=t;this.name="OperatorAuthError"}},Pe=class extends ve{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},v=class extends ve{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function dt(n){if(n instanceof ve)return n.code;if(typeof n!="object"||n===null)return;let e=n.code??n.error;return typeof e=="string"?e:void 0}var Xt=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,r=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:W(r,"issuer"),authorizationEndpoint:W(r,"authorization_endpoint"),tokenEndpoint:W(r,"token_endpoint"),deviceAuthorizationEndpoint:L(r,"device_authorization_endpoint"),endSessionEndpoint:L(r,"end_session_endpoint"),revocationEndpoint:L(r,"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:W(t,"device_code"),userCode:W(t,"user_code"),verificationUri:W(t,"verification_uri"),verificationUriComplete:L(t,"verification_uri_complete"),expiresInSeconds:Zt(t,"expires_in"),intervalSeconds:lt(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let r=await this.form(e,t);return{accessToken:W(r,"access_token"),refreshToken:L(r,"refresh_token"),idToken:L(r,"id_token"),tokenType:W(r,"token_type"),expiresInSeconds:Zt(r,"expires_in"),refreshExpiresInSeconds:lt(r,"refresh_expires_in"),scope:L(r,"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 r=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await r.json()}catch{}if(!r.ok){let a=L(i,"error")??`oauth_http_${r.status}`;throw new v(a,L(i,"error_description")??a)}return i}};function W(n,e){let t=L(n,e);if(!t)throw new v("invalid_oauth_response",`Missing ${e}`);return t}function L(n,e){return typeof n[e]=="string"?n[e]:void 0}function Zt(n,e){let t=lt(n,e);if(t===void 0)throw new v("invalid_oauth_response",`Missing ${e}`);return t}function lt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Yr=600*1e3,Ve=5,Xr=5,Jt=class{constructor(e){this.options=e;this.crypto=e.crypto??new Ge,this.clock=e.clock??new ze}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),r=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(i),s=this.clock.now()+Yr;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:r,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",r),o.searchParams.set("code_challenge",a),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),r=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!r||r.kind!=="authorization-code")throw new v("authorization_transaction_missing");if(r.expiresAt<=this.clock.now())throw new v("authorization_transaction_expired");let i=new URL(e),a=new URL(r.redirectUri);if(i.origin!==a.origin||i.pathname!==a.pathname)throw new v("redirect_uri_mismatch");let s=i.searchParams.get("error");if(s)throw new v(s,i.searchParams.get("error_description")??s);if(i.searchParams.get("state")!==r.state)throw new v("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new v("authorization_code_missing");let d=await this.getDiscovery(),l=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:r.codeVerifier,redirectUri:r.redirectUri}),c=await this.acceptTokens(l,r.nonce);return await this.options.sessions.save(c),c}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new v("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),r=Math.max(Ve,t.intervalSeconds??Ve),i=this.clock.now(),a={...t,kind:"device-code",intervalSeconds:r,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+r*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),a),a}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),r=await this.options.transactions.load(t);if(!r||r.kind!=="device-code"||r.consumed)throw new v("device_transaction_missing");let i=r,a=await this.getDiscovery(),s=Math.max(Ve,i.intervalSeconds??Ve),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:a.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 this.options.sessions.save(l),await this.options.transactions.remove(t),l}catch(d){let l=dt(d);if(l==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(l==="slow_down"){s+=Xr,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new v("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new Pe;let t;try{let r=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:r.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(r){let i=dt(r);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Pe):(this.isOfflineSession(e)||await this.options.sessions.clear(),r)}try{if(!t.refreshToken)throw new v("refresh_token_rotation_missing");let r=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(r),r}catch(r){throw await this.options.sessions.clear(),r}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(ee(e.issuer)!==ee(this.options.configuration.issuer))throw new v("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:r,redirectUri:i}=this.options.configuration;return`${e}|${ee(t)}|${r}|${i}`}async acceptTokens(e,t,r){if(e.tokenType.toLowerCase()!=="bearer")throw new v("unsupported_token_type");let i=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(i,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new v("id_token_validation_required");let o=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(o,t),o.subject!==i.subject||o.sessionId!==i.sessionId)throw new v("token_subject_mismatch")}let a=this.clock.now(),s=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?r?this.isOfflineSession(r):!0:e.scope.split(/\s+/u).includes("offline_access"));return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&s?void 0:a+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:s,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,r){let i=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(ee(e.issuer)!==ee(i.issuer))throw new v("issuer_mismatch");if(!a.includes(i.audience))throw new v("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new v("client_mismatch");if(e.environment!==i.environment)throw new v("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new v("required_claim_missing");if(r&&e.nonce!==t)throw new v("nonce_mismatch")}assertIdentity(e,t){let r=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(ee(e.issuer)!==ee(r.issuer))throw new v("issuer_mismatch");if(!i.includes(r.clientId))throw new v("client_mismatch");if(e.authorizedParty!==r.clientId)throw new v("client_mismatch");if(!e.subject||!e.sessionId)throw new v("required_claim_missing");if(e.nonce!==t)throw new v("nonce_mismatch")}};function ee(n){return n.replace(/\/+$/u,"")}var er=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()}}};import{PassphraseMasterKeySource as wa,RawMasterKeySource as Sa,deriveMasterKey as Aa,generateHexSeed as ba,computePassphraseVerifier as _a}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as xa}from"@safetech/inheriti-core-sdk/node";function ta(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=(a,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",n.environment),e(a,Object.assign({},s,{headers:o}))},r=n.business?void 0:ct({apiUrl:n.apiUrl,getBearerToken:n.getBearerToken,transport:t,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners}),i=new ne(n.apiUrl,n.environment,n.getBearerToken,t,n.business?{organizationId:n.organizationId}:void 0);return new Y(r,{keyVault:n.keyVault,state:n.state,api:i,reconstructor:new J(n.workerUrl),masterKeys:n.masterKeys,masterKey:n.masterKey,applicationId:n.applicationId,organizationId:n.organizationId,assetDecoder:Zr})}function ra(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=ct({apiUrl:new URL(n.apiUrl).origin,getBearerToken:n.getBearerToken,transport:e,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new Ie(new he(n.apiUrl,n.environment,n.getBearerToken,e),t)}function na(n){if(!n.payloadStorage||!n.secureSessionStorage||!n.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=n.transport??globalThis.fetch.bind(globalThis),t=new URL(n.apiUrl).origin,r=ct({apiUrl:t,getBearerToken:n.getBearerToken,transport:Qt({apiUrl:t,organizationId:n.organizationId,planId:n.planId,editId:n.editId,environment:n.environment,transport:e}),secureSessionStorage:n.secureSessionStorage,payloadStorage:n.payloadStorage,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new qe(new Ke(n.apiUrl,n.environment,n.getBearerToken,e),r,n.editRecoveryStore)}export{te as BusinessOrganizationSelectionError,ye as CorePlanMaterialBuilder,ya as DataAssetDefinitionService,N as ElementsApiRequestFailed,Y as ElementsClient,pe as GuidedCreateRecoveryError,ce as GuidedPlanCreator,ge as HttpAutomationRevealApiPort,ne as HttpElementsApiPort,Xt as HttpOperatorAuthTransport,Ke as HttpPlanEditPort,he as HttpQuickPlanPort,I as InvalidPlanDeclaration,b as InvalidPlanMaterial,we as MasterKeyRelayCancellationFailed,Ee as MasterKeyRelayExpired,Re as MasterKeyRelayTimedOut,q as MasterKeyRequired,le as MemoryGuidedCreateCheckpointStore,oe as MemoryKeyVault,de as MemoryStatePort,v as OAuthProtocolError,Jt as OperatorAuthClient,ve as OperatorAuthError,Pe as OperatorReauthenticationRequired,er as OperatorSessionController,We as PLAN_CREATION_SERVER_STAGES,wa as PassphraseMasterKeySource,xa as PlanAssetDeclaration,H as PlanRequestFailed,Ie as QuickPlanCreator,qe as QuickPlanEditor,Sa as RawMasterKeySource,M as RelayMasterKeySource,$e as StaticMasterKeyResolver,ze as SystemOAuthClock,Ge as WebOAuthCrypto,_a as computePassphraseVerifier,Se as createMasterKeyResolver,jr as createNodeAutomationRevealClient,ta as createNodeElementsClient,ra as createNodeQuickPlanCreator,na as createNodeQuickPlanEditor,Zr as decodeAssetContainer,Aa as deriveMasterKey,ba as generateHexSeed,se as masterKeyRefFor,V as masterKeyRefKey,dt as oauthErrorCode,Or as selectBusinessOrganization,rt as unwrapDekWithMasterKey,B as validatePlanCreationInput,j as validatePlanCreationMaterial};
|
|
1
|
+
import{createNodeSharedConfigurationSdk as ct,decodeAssetContainer as Jr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as rr,generateRSAOAEPKeyPair as nr}from"@safetech/inheriti-core-sdk/crypto";var Re=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Ee=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},we=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},M=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:r,privateKey:i}=await nr();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let a=await this.options.api.startRelaySession(r),s=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(m=>new Promise(y=>setTimeout(y,m))),l=!0,c=!1,u,R=()=>u??=(async()=>{let m=new AbortController,y,D=new Promise((C,z)=>{y=setTimeout(()=>{m.abort(),z(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(a.sessionId,m.signal),D])}finally{clearTimeout(y)}})(),S,O=new Promise((m,y)=>{S=()=>{l&&R().catch(()=>{}),y(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",S,{once:!0})});O.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(a),c=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let m=await Promise.race([this.options.api.readRelaySession(a.sessionId,e),O]);if(m.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(m.status==="DELIVERED"&&m.sealedMasterKey){let y=(await rr(m.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(y))throw new Error("invalid_master_key_material");return y}if(m.status==="EXPIRED")throw new Ee(a.sessionId);await ir(d,s,e)}throw new Re(a.sessionId)}catch(m){if(l&&(!c||e?.aborted))try{await R()}catch(y){if(e?.aborted)throw new we(y)}throw m}finally{S&&e?.removeEventListener("abort",S)}}};async function ir(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,i)=>{let a=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",a,{once:!0}),n(e).then(r,i).finally(()=>t.removeEventListener("abort",a))})}function Se(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let i=await n.source?.resolve();return i||Be(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(ar(e,n.applicationId)){let i=await n.source?.resolve();return i||Be(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return Be(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function ar(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function Be(n,e,t,r,i){if((await e()).relayAvailable)return new M({...n.relay,api:sr(n.api,t)}).resolve(r,i)}function sr(n,e){return{startRelaySession:t=>e?n.startMasterKeyRelaySession(t,e):n.startMasterKeyRelaySession(t),readRelaySession:(t,r)=>n.readMasterKeyRelaySession(t,r),cancelRelaySession:(t,r)=>n.cancelMasterKeyRelaySession(t,r)}}function V(n){return`${n.system}:${n.contextId}`}function se(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var q=class extends Error{constructor(t){super(`master_key_required:${V(t)}`);this.ref=t;this.name="MasterKeyRequired"}},$e=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(V(e),t),this}async resolve(e){return this.sources.get(V(e))?.resolve()}};var oe=class{keys=new Map;async store(e,t){let r=V(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,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 de=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var Ae=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},f=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var be=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var _e=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],He={"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"],I=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},b=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function j(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new b("plan_material_field_unknown");if(Fe(n.dataShards,"data_shards_invalid"),Fe(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&Fe(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new b("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new b("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new b("material_operation_invalid")}function Fe(n,e){if(!Array.isArray(n))throw new b(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new b(e);if(t.data!==void 0&&typeof t.data!="string")throw new b(e)}}function B(n){if(Q(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!lr(n.idempotencyKey))throw new I("idempotency_key_invalid");if(!n.name?.trim())throw new I("plan_name_required");if(!n.assets.length)throw new I("assets_required");let e=new Set;for(let t of n.assets){if(Q(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new I("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!_e.includes(t.type))throw new I("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new I("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new I("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new I("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(a=>!a.trim()))throw new I("asset_field_names_invalid");if(or(t.matchOrigins),!t.isBinary){let a=He[t.type];if(!a||i.some(s=>!a.includes(s)))throw new I("asset_field_name_not_canonical")}}if(!n.participants.length)throw new I("participants_required");for(let t of n.participants){if(Q(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!mt(t.routingEmail))throw new I("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new I("participant_relationships_invalid")}dr(n)}function or(n){if(n===void 0)return;if(!n.length)throw new I("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new I("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new I("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof I?r:new I("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new I("asset_match_origins_duplicated")}function dr(n){let e=n.policy;if(e&&Q(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new I("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){Q(e.authentication,["mode"],"plan_authentication_field_unknown");let a=e.authentication.mode;if(a!==void 0&&a!=="EXCLUSIVE"&&a!=="ALL_REQUIRED")throw new I("authentication_mode_invalid")}if(e.moderation){Q(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let a=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(a.length===0)throw new I("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>a.length))throw new I("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new I("approval_mode_invalid")}let t=e.dms;if(!t)return;Q(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!mt(t.subjectEmail))throw new I("dms_subject_invalid");if(!n.participants.some(a=>ut(a.routingEmail)===ut(t.subjectEmail)))throw new I("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(i)||t.countdownDays<0||r<0||r>23||i<0||i>59||t.countdownDays+r+i===0)throw new I("dms_countdown_invalid")}function lr(n){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(n)}function mt(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function ut(n){return n.normalize("NFC").trim().toLowerCase()}function Q(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new I(t)}var le=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)}},ce=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),B(e),Ce(t.signal);let r=await this.api.startPlanCreation(e);return r.outcome==="COMPLETED"||r.outcome==="CANCELED"?await this.checkpoints.remove(r.operationId):await this.saveCheckpoint(e,r),t.onProgress?.(r.stage),r}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,r,i,a={}){B(t);let s=await this.checkpoints.load(e);if(!s)throw new pe("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await gt(t))throw new pe("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(a.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Ce(a.signal),a.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:a.signal});Ce(a.signal),a.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:a.signal});Ce(a.signal),j(l);let c=await this.api.supplyPlanCreationMaterial(e,l);return a.onProgress?.(c.stage),c.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,c),c}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 gt(e),serverStage:t.stage})}},pe=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function gt(n){let e=JSON.stringify({name:n.name.normalize("NFC").trim(),description:n.description?.normalize("NFC").trim()??null,assets:n.assets.map(r=>({...r,fieldNames:[...r.fieldNames??[]]})).sort((r,i)=>r.clientAssetRef.localeCompare(i.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,i)=>r.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:n.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function Ce(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function ht(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new Ae(r.stage);return n.authorizeRevealAction(e,t)}function cr(n){let e=n?.status;return e===400||e===401||e===403}async function ft(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(a){if(!cr(a))throw a}return n.releaseRevealMaterial(e,t)}function pr(n){return n.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":n.stage==="STARTING"?"STARTING":n.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":n.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":n.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":n.stage==="WAITING_FOR_PARTICIPANTS"?mr(n):n.stage==="DENIED"?"DENIED":n.stage==="EXPIRED"?"EXPIRED":n.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":n.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":n.stage==="MATERIAL_RELEASED"||n.stage==="RECONSTRUCTED"?"RECONSTRUCTING":n.stage==="ACTIONS_OPEN"?"OPEN":ur.has(n.stage)?"ENDED":"CONTINUING"}var ur=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function mr(n){return n.governanceGate==="DMS"?"WAITING_FOR_DMS":n.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":n.governanceGate==="AUTHENTICATION"||n.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var Qe=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},A=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Pt(n,e,t={}){if(t.signal?.aborted)throw E();let r=await n.getPlan(e),i=await n.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):yt(i.id);if(t.signal?.aborted||(await n.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw E();let a=t.idempotencyKey??crypto.randomUUID(),s;try{s=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let l=await n.getActivePlanReveal(e);throw!l||l.planId!==e||l.mode!==(t.mode??"DIRECT")?d:yt(l.id)}let o;try{if(t.signal?.aborted)throw E();let d=await hr(n,s,t);if(t.signal?.aborted||($(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw E();let l=await n.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await n.markRevealSharesCollected(d.id),t.signal?.aborted))throw E();let c;try{c=await vr(n,d,Rr(l),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||($(t,"RECONSTRUCTING",d),t.signal?.aborted))throw E();try{o=await n.reconstructPlanMaterial(c)}catch(R){throw t.signal?.aborted?E():(await n.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Ir(R)}),R)}if(t.signal?.aborted)throw E();let u=await n.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||($(t,"OPEN",u),t.signal?.aborted))throw E();return new Ye(n,u,r,o,t.signal)}catch(d){throw o?.fill(0),await Rt(n,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function yt(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var gr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function hr(n,e,t){let r=await G(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw E();if(t.onSession?.(r),t.onProgress?.({phase:pr(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(gr.has(r.stage))throw new je(r.stage);await Ze(t.pollIntervalMs??1500,t.signal),r=await G(()=>n.getReveal(e.id,t.signal),t.signal)}}var je=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function $(n,e,t){n.onProgress?.({phase:e,session:t})}function Ze(n,e){return e?.aborted?Promise.reject(E()):new Promise((t,r)=>{let i=setTimeout(s,Math.max(0,n)),a=()=>{clearTimeout(i),r(E())};function s(){e?.removeEventListener("abort",a),t()}e?.addEventListener("abort",a,{once:!0})})}var Ye=class{constructor(e,t,r,i,a){this.client=e;this.session=t;this.plan=r;this.plaintext=i;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=a?()=>{this.close("CANCELED").catch(()=>{})}:void 0,a&&this.abortListener&&a.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new Qe;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([i])=>{r=i?.value}),r}async consumeFields(e,t){if(e.length===0)throw new A("asset_selector_invalid");if(!this.client.assetDecoder)throw new A("asset_decoder_required");let r=e.map(({selector:a,options:s={}})=>{let o=fr(a),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new A("asset_not_found");if(d.isBinary)throw new A("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new A("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:s}}),i=[];try{for(let s of r)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let a=r.map(s=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===s.asset.id||d.id===s.assetCode);if(!o)throw new A("asset_value_invalid");return{selector:s.selector,value:yr(o.data,s.field,s.asset.type)}});await t(a)}catch(a){throw await Promise.all(i.map(s=>this.reportAction(s.id,"FAILED",It(a)))),a}await Promise.all(i.map(a=>this.reportAction(a.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new A("asset_selector_invalid");if(!this.client.assetDecoder)throw new A("asset_decoder_required");let r=this.plan.assets.find(s=>s.code===e||s.id===e);if(!r)throw new A("asset_not_found");if(!r.isBinary)throw new A("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),a;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===r.id||o.id===r.code);if(!s||!(s.data instanceof Uint8Array))throw new A("asset_value_invalid");a=s.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:a})}catch(s){throw await this.reportAction(i.id,"FAILED",It(s)),s}finally{a?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,r){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...r===void 0?{}:{errorCode:r}})}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 fr(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new A("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new A("asset_selector_invalid");return{asset:n.asset,field:n.field}}function yr(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new A("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new A("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?He[t]:void 0)?.includes(e))return"";throw new A("asset_value_invalid")}return r[e]}function It(n){if(n instanceof A)return n.code;let e=n?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function Ir(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function vr(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await G(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new xe;let l=await G(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(vt(l,i.id,e.planId),!l.shares.includes(i.data))throw new K;$(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:c}=await G(()=>r.proDevice.write(l,r.signal),r.signal);if(r.signal?.aborted)throw E();if(!c?.trim())throw new K;if(await n.claimRevealCustodianShare(e.id,l.id,c),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,l.id),r.signal?.aborted))throw E();return{...t,shares:t.shares.filter(u=>u!==i).concat(l.shares.map((u,R)=>({id:`${l.id}:${R}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new K;if(r.signal?.aborted)throw E();return await n.distributeRevealCustodianShare(e.id),$(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let a=await G(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;a.status==="PENDING"||a.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),$(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Ze(r.pollIntervalMs??1500,r.signal),a=await G(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(a.status==="CLAIMED"&&a.deviceType==="SK_PRO"){if(!r.proDevice)throw new xe;if(!a.shareId||!a.deviceId)throw new K;$(r,"CONNECTING_SAFEKEY_PRO",e);let d=await G(()=>r.proDevice.read({shareId:a.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw E();if(vt(d,a.shareId,e.planId),d.deviceId!==a.deviceId)throw new K;if(await n.collectRevealCustodianShare(e.id,a.shareId),r.signal?.aborted)throw E();return{...t,shares:t.shares.concat(d.shares.map((l,c)=>({id:`${d.id}:${c}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(a.status!=="CLAIMED"||a.deviceType!=="SK_MOBILE")throw new K;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(s),$(r,"WAITING_FOR_CUSTODIAN",s),r.signal?.aborted)throw E();await n.requestRevealCustodianRelease(e.id);let o=await Pr(n,e.id,r);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,l)=>({id:`${o.id}:${l}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function vt(n,e,t){if(n?.id!==e||n.planId!==t||!Array.isArray(n.shares)||n.shares.length===0||n.shares.some(r=>typeof r!="string"||!r))throw new K}async function G(n,e){if(e?.aborted)throw E();if(!e)return n();let t,r=new Promise((i,a)=>{t=()=>a(E()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw E();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Pr(n,e,t){let r=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await G(()=>n.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let a=i;if(a.shares?.length)return a;throw new K}if(Date.now()>=r)throw new Xe;await Ze(t.pollIntervalMs??1500,t.signal)}}var K=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},xe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Xe=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Rr(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Rt(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(s){if(!Er(s))throw s}return}let r=new AbortController,i,a=new Promise((s,o)=>{i=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let s=await Promise.race([n.closeReveal(e,t,r.signal),a]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(s.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(s){if(s?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:s}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Er(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function E(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var Y=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 oe,this.state=t.state??new de,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Ar(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 f;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new f;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new f;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return B(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new f;return j(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new le){if(this.requireApplication(),!this.api)throw new f;return new ce(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),r=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",r)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new q({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let i=await this.keyVault.load(e);if(i)return Sr(i);let a=await this.masterKeys?.resolve(e,t,r);if(!a)throw new q(e);return await this.keyVault.store(e,wr(a)),a}async prepareReveal(e,t,r){if(!this.api)throw new f;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,r)}}async revealPlan(e,t){await this.prepareReveal(e);let r=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(r)}collectPlanMaterial(e,t){if(!this.api)throw new f;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new be;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,r){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 q({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=se(e);if(!i)throw new q({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new f;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new f;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new f;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new f;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new f;return this.api.getReveal(e,t)}openReveal(e,t){return Pt(this,e,t)}async withReveal(e,t,r){let i=await this.openReveal(e,t);try{let a=await r(i);return await i.close("COMPLETED"),a}catch(a){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),a}}async releaseRevealMaterial(e,t){if(!this.api)throw new f;return ft(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new f;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new f;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new f;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new f;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new f;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new f;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new f;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new f;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new f;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new f;return ht(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new f;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new f;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new f;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new f;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new f;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new f;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let r=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 a=r.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),s=i.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),o=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||r.dek,shares:a.concat(s,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let r=await this.reconstructPlanMaterial(t);if(!this.api)throw new f;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),r}useCase(e,t){if(!this.coreSdk)throw new Je;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new q({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Je=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function wr(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Sr(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Ar(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return Se({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return Se({...e,organizationId:n.organizationId})}var br=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],_r=["DIRECT","GOVERNED"],wt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Cr=["ACTIVE","REVOKED"],xr=["SK_MOBILE"],Tr=["ACTIVE","INACTIVE"],Dr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function St(n){let e=_(n);return{items:k(e.items).map(bt),nextCursor:e.nextCursor===null?null:g(e.nextCursor,"nextCursor")}}function At(n){let e=_(n);return{total:U(e.total,"total"),items:k(e.items).map(t=>{let r=_(t);if("eventData"in r)throw new Error("invalid_elements_response");return{id:g(r.id,"log.id"),planId:g(r.planId,"log.planId"),tenantId:g(r.tenantId,"log.tenantId"),event:g(r.event,"log.event"),occurredOn:g(r.occurredOn,"log.occurredOn"),status:F(r.status),title:g(r.title,"log.title"),details:k(r.details).map(i=>{let a=_(i);return{label:g(a.label,"log.detail.label"),value:g(a.value,"log.detail.value")}})}})}}function Te(n){let e=_(n),t=bt(e),r=_(e.source),i=g(r.kind,"source.kind");return{...t,assets:k(e.assets).map(a=>{let s=_(a);return{id:g(s.id,"asset.id"),code:F(s.code),type:T(g(s.type,"asset.type"),_e),name:g(s.name,"asset.name"),isBinary:Or(s.isBinary,"asset.isBinary"),fieldNames:k(s.fieldNames).map(o=>g(o,"asset.fieldNames")),fileName:F(s.fileName),mimeType:F(s.mimeType),size:s.size===void 0||s.size===null?void 0:U(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:k(s.matchOrigins).map(o=>g(o,"asset.matchOrigins"))}}),participants:k(e.participants).map(a=>{let s=_(a);return{id:g(s.id,"participant.id"),displayName:g(s.displayName,"participant.displayName"),relationships:k(s.relationships).map(o=>T(g(o,"relationship"),wt)),lifecycle:T(g(s.lifecycle,"participant.lifecycle"),Cr)}}),revealPolicy:(()=>{let a=_(e.revealPolicy);return{masterKeyRelease:T(g(a.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:T(g(a.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let a=_(e.dms);return{subjectEmail:g(a.subjectEmail,"dms.subjectEmail"),countdownDays:U(a.countdownDays,"dms.countdownDays"),countdownHours:U(a.countdownHours,"dms.countdownHours"),countdownMinutes:U(a.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:T(g(r.system,"source.system"),["INHERITI_BUSINESS"]),status:T(g(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ue(n){let e=_(n);return{operationId:g(e.operationId,"operationId"),stage:T(g(e.stage,"stage"),We),outcome:T(g(e.outcome,"outcome"),Dr),planId:F(e.planId),lastErrorCode:F(e.lastErrorCode),participants:e.participants===void 0?void 0:k(e.participants).map(t=>{let r=_(t);return{clientParticipantRef:g(r.clientParticipantRef,"clientParticipantRef"),planParticipantId:g(r.planParticipantId,"planParticipantId"),relationships:k(r.relationships).map(i=>kr(g(i,"relationship"),wt))}})}}function bt(n){let e=_(n),t=_(e.assetSummary),r=_(e.governance),i=_(e.participantSummary);return{id:g(e.id,"id"),name:g(e.name,"name"),description:F(e.description),status:T(g(e.status,"status"),br),createdAt:g(e.createdAt,"createdAt"),configuredAt:F(e.configuredAt),assetSummary:{count:U(t.count,"assetSummary.count"),types:k(t.types).map(a=>T(g(a,"assetType"),_e)),names:Et(t.names).map(a=>g(a,"assetSummary.names"))},governance:{mode:T(g(r.mode,"governance.mode"),_r),minimumApprovals:U(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:U(i.owners,"owners"),mergers:U(i.mergers,"mergers"),moderators:U(i.moderators,"moderators")},authentication:Et(e.authentication).map(a=>{let s=_(a);return{id:T(g(s.id,"authentication.id"),xr),status:T(g(s.status,"authentication.status"),Tr)}})}}function T(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function kr(n,e){if(!e.includes(n))throw new Error("invalid_elements_response");return n}function _(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function Et(n){return n==null?[]:k(n)}function k(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function g(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function F(n){return n==null?void 0:g(n,"optional")}function U(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function Or(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}var te=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function _t(n){if(!n||typeof n!="object"||!("items"in n)||!Array.isArray(n.items)||!n.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 n.items.map(({id:e,name:t})=>({id:e,name:t}))}function Mr(n,e){if(!e){if(n.length===0)throw new te("organization_required");if(n.length>1)throw new te("organization_selection_required");return n[0].id}if(!n.some(({id:t})=>t===e))throw new te("organization_access_denied");return e}function Nr(n){let e=v(n);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:h(e.participantRevision,1),createdAt:x(e.createdAt),...Ct(e)}}function Ct(n){if(n.recipientStatuses===void 0)return{};if(!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:n.recipientStatuses.map(e=>{let t=v(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:p(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(r=>{let i=v(r);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 xt(n){let e=v(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Nr),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(n){let e=v(n);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:p(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:h(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let r=v(t);return{unitId:p(r.unitId),position:h(r.position,0),commitment:p(r.commitment),status:p(r.status)}})}}function et(n){let e=v(n);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:h(e.sequence,1),status:e.status}}function Dt(n){let e=v(n);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:h(e.participantRevision,1),recipients:e.recipients.map(tt)}}function kt(n){let e=v(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=v(t);return{parentId:p(r.parentId),sequence:h(r.sequence,1),senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),participantRevision:h(r.participantRevision,1),createdAt:x(r.createdAt),...Ct(r)}}),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 Ot(n){return{readThroughSequence:h(v(n).readThroughSequence,0)}}function Mt(n){return{clearedThroughSequence:h(v(n).clearedThroughSequence,0)}}function Nt(n){let e=v(n);return{parentId:p(e.parentId),sequence:h(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:h(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function v(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_inbox_response");return n}function p(n){if(typeof n!="string"||!n)throw new Error("invalid_inbox_response");return n}function x(n){let e=p(n);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function h(n,e){if(!Number.isSafeInteger(n)||n<e)throw new Error("invalid_inbox_response");return n}function tt(n){let e=v(n);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:h(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function re(n){let e=v(n);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:x(e.createdAt),updatedAt:x(e.updatedAt)}}function De(n){let e=v(n);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:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),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 r=v(e.latestMessage);if(r.contentKind!=="TEXT"&&r.contentKind!=="FILE"&&r.contentKind!=="NORMAL"&&r.contentKind!=="MIXED"&&r.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:r.contentKind,senderMemberId:p(r.senderMemberId),createdAt:x(r.createdAt)}}return t}function Kt(n){let e=v(n);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(De),total:e.total,limit:e.limit,offset:e.offset}}function Ut(n){let e=v(n);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 r=tt(t);return{memberId:r.memberId,name:p(v(t).name),deviceId:r.deviceId,deviceVersion:r.deviceVersion,encryptionPublicKey:r.encryptionPublicKey,encryptionKeyFingerprint:r.encryptionKeyFingerprint,signingPublicKey:r.signingPublicKey,signingKeyFingerprint:r.signingKeyFingerprint}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function Lt(n){let e=v(n);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 r=v(t);if(typeof r.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(r.memberId),name:p(r.name),ready:r.ready,...r.profilePicture===void 0?{}:{profilePicture:{url:p(v(r.profilePicture).url)}}}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function qt(n){let e=v(n);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:p(e.conversationId),messageId:p(e.messageId),participantRevision:h(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(tt),shareLayers:e.shareLayers.map(t=>{let r=v(t),i=p(r.id),a=p(r.dataShareId),s=p(r.keyShareId);if(r.type==="INHERITI_CHAIN")return{id:i,type:r.type,contractAddress:p(r.contractAddress),dataShareId:a,keyShareId:s};if(r.type==="INHERITI_VAULT"||r.type==="GOOGLE_DRIVE"||r.type==="DROPBOX"||r.type==="ONEDRIVE")return{id:i,type:r.type,dataShareId:a,keyShareId:s};throw new Error("invalid_inbox_response")})}}function ke(n){let e=v(n);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:p(e.messageId),status:e.status}}function Gt(n){let e=v(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=v(t);if(r.status!=="PREPARING"&&r.status!=="AVAILABLE"&&r.status!=="FAILED"&&r.status!=="DELETING")throw new Error("invalid_inbox_response");if(r.contentKind!==void 0&&r.contentKind!=="TEXT"&&r.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(r.recipientStatus!==void 0&&r.recipientStatus!=="UNREAD"&&r.recipientStatus!=="LEASED"&&r.recipientStatus!=="CONSUMED"&&r.recipientStatus!=="EXPIRED"&&r.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(r.recipientStatuses!==void 0&&!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:p(r.id),status:r.status,senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),createdAt:x(r.createdAt),updatedAt:x(r.updatedAt),expiresAt:x(r.expiresAt)};return r.contentKind&&(i.contentKind=r.contentKind),r.recipientStatus&&(i.recipientStatus=r.recipientStatus),Array.isArray(r.recipientStatuses)&&(i.recipientStatuses=r.recipientStatuses.map(a=>{let s=v(a);if(s.status!=="UNREAD"&&s.status!=="LEASED"&&s.status!=="CONSUMED"&&s.status!=="EXPIRED"&&s.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:p(s.memberId),status:s.status,...s.consumedAt!==void 0?{consumedAt:s.consumedAt===null?null:x(s.consumedAt)}:{}}})),i}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0)}}function zt(n){let e=v(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:x(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=v(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:h(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId),ciphertext:p(r.ciphertext)}})}}function Vt(n){let e=v(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:x(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=v(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:h(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId)}})}}function X(n){return typeof n.error=="string"?/^[a-z][a-z0-9_]*$/.test(n.error)?n.error:typeof n.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(n.validationErrors)?n.validationErrors:n.error||void 0:n.error?.code??n.name??n.message}function Z(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var N=class extends Error{constructor(t,r,i,a){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.requestId=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ne=class{constructor(e,t,r,i,a){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i;this.business=a?Object.freeze({...a}):void 0}business;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:re(t)}async getMemberInboxDevice(e,t){let r=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return r===null?null:re(r)}async registerInboxDevice(e){return re(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return re(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return re(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return De(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return De(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Kt(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Ut(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Lt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Dt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let r={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",r))}async publishNormalInboxMessage(e,t){return et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},r){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 a=i.size?`?${i}`:"";return xt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${a}`,"GET",void 0,void 0,void 0,r))}async openInboxParent(e,t,r,i){let a=new URLSearchParams({deviceId:r});return Tt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return Mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},r){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 a=i.size?`?${i}`:"";return kt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${a}`,"GET",void 0,void 0,void 0,r))}async openNormalInboxMessage(e,t,r,i){let a=new URLSearchParams({deviceId:r});return Nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,r){return Ot(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:r}))}async stageInboxFile(e,t,r){return ke(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,r))}async uploadInboxFileShare(e,t,r,i,a){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let s=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}`,o=await this.requestBinary(s,"PUT",i,a),d=await Oe(o,a);if(!d.ok||d.result?.shareId!==r||d.result.status!=="STORED")throw new N(o.status,X(d),Z(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,r){return ke(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,r))}async openInboxFile(e,t,r,i){return Vt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:r},void 0,void 0,i))}async downloadInboxFileShare(e,t,r,i,a,s){let o=new URLSearchParams({deviceId:i,leaseId:a}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}?${o}`,l=await this.requestBinary(d,"GET",void 0,s);if(!l.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let c=Number(l.headers.get("content-length"));if(Number.isFinite(c)&&c>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!l.body)throw new Error("invalid_inbox_share_response");let u=l.body.getReader(),R=[],S=0;try{for(;;){s?.throwIfAborted();let y=await u.read();if(y.done)break;if(S+=y.value.length,S>14*1024*1024)throw new Error("invalid_inbox_share_size");R.push(y.value)}}catch(y){throw await u.cancel().catch(()=>{}),y}let O=new Uint8Array(S),m=0;for(let y of R)O.set(y,m),m+=y.length;return O}async listInboxMessages(e,t={},r){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 a=i.size?`?${i}`:"";return Gt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${a}`,"GET",void 0,void 0,void 0,r))}async openInboxMessage(e,t,r){return zt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:r}))}async ackInboxMessage(e,t,r,i,a){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:r,leaseId:i},void 0,void 0,a)}async releaseInboxMessage(e,t,r,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:r,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(_t)}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 r=t.size?`?${t}`:"";return St(await this.request(`v1/plans${r}`,"GET"))}async getPlan(e){return Te(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let r=new URLSearchParams;t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return At(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){B(e);let{idempotencyKey:t,...r}=e;return ue(await this.request("v1/plan-creations","POST",r,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return j(t),ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:r,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":r})}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,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:r})}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,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,r)}abortPlanAccess(e,t){let r=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${r}?revealId=${encodeURIComponent(t)}`:r,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...a}=r;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,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,r,i,a,s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken();s?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),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[S,O]of Object.entries(a??{}))d.set(S,O);r&&d.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c={method:t,headers:d,body:r?JSON.stringify(r):void 0};s&&(c.signal=s);let u=await this.transport(new URL(e,l),c);s?.throwIfAborted();let R=await Oe(u,s);if(s?.throwIfAborted(),!u.ok)throw new N(u.status,X(R),Z(R),u.headers.get("x-request-id")??void 0);if(!R.ok||R.result===void 0)throw new N(u.status,X(R),Z(R),u.headers.get("x-request-id")??void 0);return R.result}async requestBinary(e,t,r,i){this.requireBusinessSelection(e),i?.throwIfAborted();let a=await this.getBearerToken();i?.throwIfAborted();let s=new Headers({"x-elements-environment":this.environment});a&&s.set("authorization",`Bearer ${a}`),this.business?.organizationId&&s.set("x-organization-id",this.business.organizationId),r&&s.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:s,body:r?Buffer.from(r):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let l=await Oe(d,i);throw new N(d.status,X(l),Z(l),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let r=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});r&&i.set("authorization",`Bearer ${r}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,a),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),o=await Oe(s);if(!s.ok||!o.ok)throw new N(s.status,X(o),Z(o),s.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new N(400,"organization_selection_required")}};async function Oe(n,e){try{return await n.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Br}from"@safetech/inheriti-core-sdk/node";async function rt(n,e){if(!e)throw new Error("master_key_required");let t=Kr(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Ur(n),a=i.slice(0,12),s=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},r,s);return Lr(new Uint8Array(o))}function Kr(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Ur(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Lr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var me=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await Bt("plan_key_unwrap_failed",()=>rt(e.planKey,t)),i=await crypto.subtle.importKey("raw",nt(r),{name:"AES-GCM"},!1,["decrypt"]),a=[],s=[];for(let o of e.shares){let d=await Bt("plan_share_decryption_failed",()=>Vr(o.data,i));zr(o.shareType)?s.push(d):a.push(d)}try{return await this.processor().reconstruct(a,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new Me("plan_share_reconstruction_failed",Gr(o))}}},Me=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},qr=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 Gr(n){let e=n instanceof Error?n.message:void 0;if(e)return qr.has(e)?e:void 0}async function Bt(n,e){try{return await e()}catch{throw new Me(n)}}function zr(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function Vr(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=nt(n.slice(0,t)),i=nt(n.slice(t+1)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(a)}function nt(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i+=1)r[i]=e.charCodeAt(i);return t}var J=class extends me{constructor(e){super(()=>Br(e))}};var ge=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Te(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,r){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,r)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...a}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let r=this.firstRelayStates.get(e);return r?(this.firstRelayStates.delete(e),Promise.resolve(r)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,r,i=!0,a,s){s?.throwIfAborted();let o=await this.getAutomationBearerToken();if(s?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...a});r!==void 0&&d.set("content-type","application/json");let l=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:r===void 0?void 0:JSON.stringify(r),signal:s});s?.throwIfAborted();let c;try{c=await l.json()}catch{s?.throwIfAborted()}if(!l.ok||c&&c.ok===!1||i&&c?.result===void 0)throw new N(l.status,c&&X(c),c&&Z(c));return c?.result}};var w={invalidDeclaration:"plan_declaration_invalid",invalidShares:"plan_share_count_invalid",storageChanged:"plan_storage_context_changed",invalidMasterKeyContext:"invalid_master_key_context",reauthenticationRequired:"operator_reauthentication_required",relayFailed:"master_key_relay_failed",reconciliationRequired:"reconciliation_required"};var H=class extends Error{constructor(t,r){super(r??`plan_request_failed_${t}`);this.status=t;this.code=r}},he=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,r,i,a){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:r,...a?{description:a}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:r.validatorShares,encryptedKey:r.encryptedKey})}preflight(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",$t(r))}configure(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",$t(r))}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(w.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(w.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(w.relayFailed);return r}async request(e,t,r,i){let a=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),s=await this.getBearerToken();if(!s)throw new Error(w.reauthenticationRequired);a.set("authorization",`Bearer ${s}`),i!==void 0&&a.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,l=await this.transport(new URL(d,o),{method:r,headers:a,body:i===void 0?void 0:JSON.stringify(i)}),c={};try{c=await l.json()}catch{}if(!l.ok||c.ok!==!0)throw new H(l.status,c.error);return c.result}};function $t(n){return{protectionProtocol:n.protectionProtocol,operation:"FINALIZE",dataShards:n.dataShards,backupShards:n.backupShards,encryptedKey:n.encryptedKey,assetsMetadata:n.assetsMetadata,custodianPair:n.custodianShard}}var ye=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){fe(e.signal),Fr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return fe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){fe(e.signal);let t=e.encrypted.totalShares+1,r=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:r,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(fe(e.signal),!i.custodianPair)throw new b("custodian_share_required");let a=it(i.keyShards),s=await this.sealer.encryptShares(a,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(it(i.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares(it(i.backupShards),s.symmetricKeyBase64),l=await this.sealCustodianPair(i.custodianPair,s.symmetricKeyBase64);return fe(e.signal),{protectionProtocol:i.protocol,validatorShares:at(s.encryptedShares),dataShards:at(o.encryptedShares),backupShards:at(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:$r(e.encrypted.assets,e.declaration),custodianShard:l,operation:"FINALIZE"}}async sealCustodianPair(e,t){let r=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:st(r.encryptedShares[0]),dataShard:st(r.encryptedShares[1])}}};function it(n){return n.map(e=>({id:crypto.randomUUID(),data:e}))}function at(n){return n.map(st)}function st(n){return{id:n.id,data:n.encryptedData}}function $r(n,e){let t={};for(let r of n){let i=e.assets.find(a=>a.clientAssetRef===r.id);if(!i)throw new b("plan_secrets_declaration_mismatch");t[r.id]={type:r.type,meta:{name:r.meta.name,notes:r.meta.notes,...r.meta.isMedia===void 0?{}:{isMedia:r.meta.isMedia},...r.meta.mimeType===void 0?{}:{mimeType:r.meta.mimeType},...r.meta.fileName===void 0?{}:{fileName:r.meta.fileName},...r.meta.code===void 0?{}:{code:r.meta.code},...r.meta.matchOrigins===void 0?{}:{matchOrigins:[...r.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function Fr(n,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new b("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new b("share_threshold_invalid");if(e.assets.length!==n.assets.length)throw new b("plan_secrets_declaration_mismatch");let t=new Map(n.assets.map(r=>[r.clientAssetRef,r]));for(let r of e.assets){let i=t.get(r.id);if(!i||i.type!==r.type)throw new b("plan_secrets_declaration_mismatch")}}function fe(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function Ft(n,e,t,r,i,a,s){let o=r.mergeThreshold-(r.withCustodian?1:0);if(typeof r.withCustodian!="boolean"||!Number.isInteger(r.mergeThreshold)||o<1||o>n.totalShares)throw new Error(w.invalidShares);let{assets:d,plan:l}=e;l.policy={custodian:r.withCustodian?"FORCE":"BYPASS"};let c=n.masterKeySource??new M({api:{startRelaySession:S=>i.startRelaySession(n.organizationId,t.masterKeyAcquisition,S),readRelaySession:S=>i.readRelaySession(n.organizationId,S)}}),u=new ye(a,c);s?.("encrypting");let R=await u.encrypt({planId:n.planId,declaration:l,secrets:{assets:d,totalShares:n.totalShares,threshold:o}});return s?.("generating_shares"),u.generateShares({planId:n.planId,declaration:l,encrypted:R})}import{PlanAssetDeclaration as Hr}from"@safetech/inheriti-core-sdk/node";function Ht(n){let e=ot({planId:n.planId,title:n.title,assets:[n.asset]});return{asset:e.assets[0],plan:e.plan}}function ot(n){if(!n.assets.length)throw new I("assets_required");let e=n.assets.map(a=>{if(a.meta.isMedia!==!0)return;let s="data"in a.secret?a.secret.data:void 0,o;if(s instanceof Blob&&(o=s.size),typeof s=="string")try{o=atob(s).length}catch{throw new I("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new I("binary_asset_metadata_invalid");return o}),t=Hr.create(n.assets.map(({type:a,meta:s})=>({type:a,meta:s}))),r=t.complete(Object.fromEntries(t.entries.map((a,s)=>[a.id,n.assets[s].secret]))),i={idempotencyKey:n.planId,name:n.title,assets:r.map((a,s)=>{let o=a.meta.isMedia===!0;return{clientAssetRef:a.id,type:a.type,name:a.meta.name,fieldNames:o?[]:Object.keys(a.secret),isBinary:o,fileName:a.meta.fileName,mimeType:a.meta.mimeType,size:e[s]}}),participants:[]};return{assets:r,plan:i}}async function Qt(n){let e=await Promise.all(n.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([r],[i])=>r.localeCompare(i)).map(async([r,i])=>[r,i instanceof Blob?await Wt(new Uint8Array(await i.arrayBuffer())):i]))})));return Wt(new TextEncoder().encode(JSON.stringify({organizationId:n.organizationId,planId:n.planId,title:n.title,description:n.description??null,audience:n.audience??null,totalShares:n.totalShares,assets:e})))}async function Wt(n){let e=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ie=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){return this.createPlan({...e,assets:[e.asset]},t)}async createPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!Array.isArray(e.assets)||!e.assets.length||e.assets.some(s=>!s?.meta?.name?.trim()))throw new Error(w.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(w.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(w.invalidShares);let r=await Qt(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==r)throw new Error(w.reconciliationRequired);return i.promise}let a=this.performCreate(e,r,t);this.flights.set(e.planId,{fingerprint:r,promise:a});try{return await a}finally{this.flights.delete(e.planId)}}async performCreate(e,t,r){let i=ot({planId:e.planId,title:e.title,assets:e.assets}),a=this.material.get(e.planId);if(a&&(a.fingerprint!==t||a.masterKeySource!==e.masterKeySource))throw new Error(w.reconciliationRequired);let s=await this.statusOrMissing(e.organizationId,e.planId);if(Ne(s))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(s&&!a)throw new Error(w.reconciliationRequired);if(!s&&a)throw new Error(w.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(w.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(w.invalidMasterKeyContext);if(!s){r?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(c){if(s=await this.statusOrMissing(e.organizationId,e.planId),!s)throw c}}s??=await this.port.status(e.organizationId,e.planId);let d=a?.encrypted??await Ft(e,i,o,s,this.port,this.coreSdk,r);a||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),r?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),r?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),r?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(c){if(!Ne(await this.statusOrMissing(e.organizationId,e.planId)))throw c}r?.("verifying");let l=await this.port.status(e.organizationId,e.planId);return Ne(l)&&this.material.delete(e.planId),{planId:e.planId,status:Ne(l)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(w.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(r){if(r instanceof H&&r.status===404)return;throw r}}};function Ne(n){return n?.status==="PROTECTED"||n?.status==="CONFIGURED"}var Ke=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}start(e,t,r,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:r},i)}async listEligibleCandidates(e,t,r){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),r&&i.set("namePrefix",r);let a=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(a))throw new Error("invalid_plan_edit_candidates");return a}async context(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(r))throw new Error("invalid_plan_edit_context");return r}async moderatorNames(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!r||typeof r!="object")throw new Error("invalid_plan_edit_participants");let i=r;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let a=new Map;for(let s of i.participants){if(!s||typeof s.id!="string"||!s.id||typeof s.displayName!="string"||!Array.isArray(s.relationships)||!s.relationships.every(o=>typeof o=="string")||typeof s.lifecycle!="string")throw new Error("invalid_plan_edit_participants");s.lifecycle==="ACTIVE"&&s.relationships.includes("MODERATOR")&&a.set(s.id,s.displayName)}return a}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(w.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(w.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(w.relayFailed);return r}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(r))}commit(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(r))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,r,i,a){let s=await this.getBearerToken();if(!s)throw new Error(w.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${s}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),a&&o.set("idempotency-key",a);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),l=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,c=await this.transport(new URL(l,d),{method:r,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),u={};try{u=await c.json()}catch{}if(!c.ok||u.ok!==!0){let R=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new H(c.status,R||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(r=>!!r&&typeof r.id=="string"&&!!r.id&&typeof r.name=="string"&&r.status==="PROTECTED"&&typeof r.createdAt=="string"&&!!r.assetSummary&&Number.isSafeInteger(r.assetSummary.count)&&r.assetSummary.count>=0&&Array.isArray(r.assetSummary.types)&&r.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(r.assetSummary.names)&&r.assetSummary.names.every(i=>typeof i=="string")&&!!r.governance&&["DIRECT","GOVERNED"].includes(r.governance.mode)&&Number.isSafeInteger(r.governance.minimumApprovals)&&r.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var Ue=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.recoveryStore=r}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let r=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),a=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!a)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let s=this.revealedAssets,o=s?.organizationId===e.organizationId&&s.planId===e.planId&&s.editId===e.editId&&s.expiresAt>Date.now();s&&!o&&(this.revealedAssets=void 0);let d=a.masterKeyEncrypted?e.masterKey??(o?s.masterKey:void 0):void 0;a.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let l=Date.now()+10*6e4;o||t?.("opening_plan");let c=o?s.assets:await this.revealAssets(e,d,a.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(c.map(u=>u.id)).size!==c.length)throw new Error("duplicate_existing_asset_id");return!o&&r===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,l),assets:c,masterKey:d}),{plan:a,masterKey:d,assets:c}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),r=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(r>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return r}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new M({api:{startRelaySession:r=>this.port.startRelaySession(e.organizationId,t,r),readRelaySession:r=>this.port.readRelaySession(e.organizationId,r)}}).resolve()}async revealAssets(e,t,r,i){let a=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),s=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=m=>{m!==o&&(o=m,i?.(m))},l=m=>{if(m.processId!==e.editId||m.planId&&m.planId!==e.planId)return;switch(m.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let y=this.approvalError(m);if(y?.startsWith("edit_authentication_")&&d("pending_auth"),y?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!m.moderatorParticipants||m.requiredModeratorApprovals===void 0||!m.approvalProcess)return;let D=m.moderatorParticipants.map(C=>C.memberId??C.userId);D.some(C=>typeof C!="string"||!C)||new Set(D).size!==D.length||i?.(o,{requiredApprovals:m.requiredModeratorApprovals,approvedModerators:m.approvalProcess.approvedModerators,moderators:m.moderatorParticipants.map((C,z)=>{let ie=D[z],pt=C.flows.filter(ae=>ae.status==="PENDING"&&ae.expiresAt&&Number.isFinite(ae.expiresAt.getTime())).map(ae=>ae.expiresAt.getTime());return{id:ie,displayName:s.get(ie)||"Moderator",status:C.status,expiresAt:pt.length?new Date(Math.min(...pt)).toISOString():void 0}})})},c=await a.resume(e.planId,{onViewUpdate:l});if(c?.processId!==e.editId||c.planId&&c.planId!==e.planId)throw new Error("edit_merge_not_ready");l(c),this.assertApprovalOutcome(e.planId,c),c.status!=="READY_TO_REVEAL"&&c.status!=="REVEALED"&&await a.run(e.editId,{onViewUpdate:l,onApprovalsRequested:()=>d("pending_approvals")});let u=await a.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");l(u),this.assertApprovalOutcome(e.planId,u);let R=u?.status;if(R!=="READY_TO_REVEAL"&&R!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let S=null,O={onRevealed:m=>{S=m},onViewUpdate:l,onRevealStepUpdate:(m,y)=>{if(y==="IN_PROCESS")switch(m){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(r&&(O.onCustodianShareRequired=async(m,y)=>{switch(y.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let D=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),D==="SK_MOBILE")return a.distributeCustodianShareViaMobile(y.planId);if(D!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let C=e.proDevice;try{this.assertNotAborted(e.signal);let z=await a.getCustodianShareData(m);this.assertShare(z,y.planId),d("connecting_safekey_pro");let{deviceId:ie}=await C.write(z,e.signal);if(this.assertNotAborted(e.signal),!ie?.trim())throw new Error("custodian_share_unavailable");await a.recordCustodianShareClaim(y.planId,z.id,ie,"SK_PRO"),this.assertNotAborted(e.signal),await a.markCustodianShareAsCollected(m,z.id);return}finally{C.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let D=e.proDevice;try{if(this.assertNotAborted(e.signal),!y.shareId||!y.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let C=await D.read({shareId:y.shareId,planId:y.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(C,y.planId,y.shareId),C.deviceId!==y.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:C.shares}}finally{D.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),R==="REVEALED"?await a.resumeReveal(e.editId,O,t):await a.openRevealWindow(e.editId,{timeoutMinutes:10},O,t),this.assertNotAborted(e.signal),!S)throw new Error("edit_assets_unavailable");return S}assertApprovalOutcome(e,t){let r=this.approvalError(t);if(r)throw this.clearRevealedAssets(e),new Error(r)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,r){if(!e||!e.id||e.id!==(r??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var Wr=n=>JSON.stringify(n??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([r],[i])=>r<i?-1:r>i?1:0))),Le=class{constructor(e,t,r,i){this.port=e;this.coreSdk=t;this.recoveryStore=r;this.clearRevealedAssets=i}async saveAssets(e,t,r,i,a,s){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,r,i);s?.("preparing");let l=await o.prepare(d);this.assertNotAborted(e.signal);let c={mergeProcessId:e.editId,protectionProtocol:l.protectionProtocol,validatorShares:this.transportShares(l.validatorShares),dataShards:this.transportShares(l.dataShards),backupShards:this.transportShares(l.backupShards),encryptedKey:l.encryptedKey,assetsMetadata:l.assetsMetadata,custodianPair:l.custodianPair};if(s?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,c),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:a,material:c}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,a,c,o,d,s)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let r=await this.configurationRepository().findByPlanId(e.planId),i=r?.editDistribution??r?.preparedDistribution;if(!t&&(!i||r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let a=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),dataShards:i.dataShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),backupShards:i.backupShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,a))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!r?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let s=await this.port.status(e.organizationId,e.editId);return s.id!==e.editId||s.planId!==e.planId||s.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,a),await this.port.commit(e.organizationId,e.planId,a),await this.isCommitted(e,a)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let r=await this.configurationRepository().findByPlanId(e.planId);if(r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let r=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await r.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await r.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,r,i){let a=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),s={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:r,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:a,configuration:s}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,r,i,a,s){let o,d=l=>{let c;switch(l.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":c="distributing_validators";break;case"SHARES_DISTRIBUTION":c="distributing_data";break;case"FINALIZE":c="finalizing";break;default:return}c!==o&&(o=c,s?.(c))};try{await i.execute(a,{onLocalProcessUpdated:d})}catch(l){try{if(s?.("verifying"),await this.isCommitted(e,r))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&s?.(o),l}try{if(s?.("verifying"),!await this.isCommitted(e,r))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let r=await this.port.commitStatus(e.organizationId,e.editId);if(r.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(r.status)||r.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(Wr(t.assetsMetadata)),a=await globalThis.crypto.subtle.digest("SHA-256",i),s=Array.from(new Uint8Array(a),l=>l.toString(16).padStart(2,"0")).join("");if(r.assetsMetadataHash!==s)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(l=>l.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(r.shares.map(l=>l.id));return!o.some(l=>!d.has(l))}};var qe=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.assetAccess=new Ue(e,t,r),this.reconfiguration=new Le(e,t,r,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,r,i){return this.port.start(e,t,r,i)}async listAssets(e,t){let{assets:r}=await this.assetAccess.loadAssets(e,t);return r.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,r){let{assets:i}=await this.assetAccess.loadAssets(e,r),a=i.find(s=>s.id===t);if(!a)throw new Error("edit_asset_not_found");return structuredClone(a)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:r,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=a.findIndex(c=>c.id===e.assetId);if(s<0)throw new Error("edit_asset_not_found");let o=a[s];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},l=a.map((c,u)=>u===s?d:c);return this.reconfiguration.saveAssets(e,l,r.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:r,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=Ht({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(a.map(d=>d.id)).has(s.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,a.concat(s),r.withCustodian,i,s.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function jt({apiUrl:n,organizationId:e,planId:t,editId:r,environment:i,transport:a}){return(s,o)=>{let d=new URL(s instanceof Request?s.url:s.toString()),l=new URL(n.endsWith("/")?n:`${n}/`);if(d.origin!==l.origin||!d.pathname.startsWith(l.pathname))throw new Error("unsupported_core_edit_route");let c=d.pathname.slice(l.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(c===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return a(d,o)}if(c==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let u=Qr(c,d.searchParams,t,r),R=new Headers(o?.headers);R.set("x-organization-id",e),R.set("x-elements-environment",i);let S=l.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return a(new URL(S,l),Object.assign({},o,{headers:R}))}}function Qr(n,e,t,r){if(n==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let a=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(n);if(a){let o=a[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(a[1]!==r||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(a[1])}/${d[o]}`}let s=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(n);if(s){if(s[1]!==t)throw new Error("edit_plan_id_mismatch");let o=s[2]??"";if(o==="")return`edits/${encodeURIComponent(r)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(s[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(r)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as jr}from"@safetech/inheriti-core-sdk/node";function Yt(n){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let r=await n.api.planKeyReference(e),i=se(r);if(!r.masterKeyWrapped||!i||r.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new M({api:{startRelaySession:o=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>n.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>n.api.cancelMasterKeyRelaySession(o,d)}});return new Y(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(o,d,l)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(d,l)}}}).openReveal(e,t)}}}function Yr(n){let e=new ge(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{...Yt({api:e,reconstructor:new J(n.workerUrl),assetDecoder:jr}),getPlan:t=>e.getPlan(t)}}import{DataAssetDefinitionService as Ia}from"@safetech/inheriti-core-sdk/node";function Xt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Ge=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))}},ze=class{now(){return Date.now()}sleep(e,t){return new Promise((r,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let a=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(a),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var ve=class extends Error{constructor(t,r=t){super(r);this.code=t;this.name="OperatorAuthError"}},Pe=class extends ve{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},P=class extends ve{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function dt(n){if(n instanceof ve)return n.code;if(typeof n!="object"||n===null)return;let e=n.code??n.error;return typeof e=="string"?e:void 0}var Zt=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,r=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:W(r,"issuer"),authorizationEndpoint:W(r,"authorization_endpoint"),tokenEndpoint:W(r,"token_endpoint"),deviceAuthorizationEndpoint:L(r,"device_authorization_endpoint"),endSessionEndpoint:L(r,"end_session_endpoint"),revocationEndpoint:L(r,"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:W(t,"device_code"),userCode:W(t,"user_code"),verificationUri:W(t,"verification_uri"),verificationUriComplete:L(t,"verification_uri_complete"),expiresInSeconds:Jt(t,"expires_in"),intervalSeconds:lt(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let r=await this.form(e,t);return{accessToken:W(r,"access_token"),refreshToken:L(r,"refresh_token"),idToken:L(r,"id_token"),tokenType:W(r,"token_type"),expiresInSeconds:Jt(r,"expires_in"),refreshExpiresInSeconds:lt(r,"refresh_expires_in"),scope:L(r,"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 r=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await r.json()}catch{}if(!r.ok){let a=L(i,"error")??`oauth_http_${r.status}`;throw new P(a,L(i,"error_description")??a)}return i}};function W(n,e){let t=L(n,e);if(!t)throw new P("invalid_oauth_response",`Missing ${e}`);return t}function L(n,e){return typeof n[e]=="string"?n[e]:void 0}function Jt(n,e){let t=lt(n,e);if(t===void 0)throw new P("invalid_oauth_response",`Missing ${e}`);return t}function lt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Xr=600*1e3,Ve=5,Zr=5,er=class{constructor(e){this.options=e;this.crypto=e.crypto??new Ge,this.clock=e.clock??new ze}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),r=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(i),s=this.clock.now()+Xr;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:r,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",r),o.searchParams.set("code_challenge",a),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),r=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!r||r.kind!=="authorization-code")throw new P("authorization_transaction_missing");if(r.expiresAt<=this.clock.now())throw new P("authorization_transaction_expired");let i=new URL(e),a=new URL(r.redirectUri);if(i.origin!==a.origin||i.pathname!==a.pathname)throw new P("redirect_uri_mismatch");let s=i.searchParams.get("error");if(s)throw new P(s,i.searchParams.get("error_description")??s);if(i.searchParams.get("state")!==r.state)throw new P("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new P("authorization_code_missing");let d=await this.getDiscovery(),l=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:r.codeVerifier,redirectUri:r.redirectUri}),c=await this.acceptTokens(l,r.nonce);return await this.options.sessions.save(c),c}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new P("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),r=Math.max(Ve,t.intervalSeconds??Ve),i=this.clock.now(),a={...t,kind:"device-code",intervalSeconds:r,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+r*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),a),a}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),r=await this.options.transactions.load(t);if(!r||r.kind!=="device-code"||r.consumed)throw new P("device_transaction_missing");let i=r,a=await this.getDiscovery(),s=Math.max(Ve,i.intervalSeconds??Ve),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:a.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 this.options.sessions.save(l),await this.options.transactions.remove(t),l}catch(d){let l=dt(d);if(l==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(l==="slow_down"){s+=Zr,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new P("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new Pe;let t;try{let r=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:r.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(r){let i=dt(r);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Pe):(this.isOfflineSession(e)||await this.options.sessions.clear(),r)}try{if(!t.refreshToken)throw new P("refresh_token_rotation_missing");let r=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(r),r}catch(r){throw await this.options.sessions.clear(),r}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(ee(e.issuer)!==ee(this.options.configuration.issuer))throw new P("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:r,redirectUri:i}=this.options.configuration;return`${e}|${ee(t)}|${r}|${i}`}async acceptTokens(e,t,r){if(e.tokenType.toLowerCase()!=="bearer")throw new P("unsupported_token_type");let i=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(i,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new P("id_token_validation_required");let o=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(o,t),o.subject!==i.subject||o.sessionId!==i.sessionId)throw new P("token_subject_mismatch")}let a=this.clock.now(),s=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?r?this.isOfflineSession(r):!0:e.scope.split(/\s+/u).includes("offline_access"));return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&s?void 0:a+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:s,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,r){let i=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(ee(e.issuer)!==ee(i.issuer))throw new P("issuer_mismatch");if(!a.includes(i.audience))throw new P("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new P("client_mismatch");if(e.environment!==i.environment)throw new P("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new P("required_claim_missing");if(r&&e.nonce!==t)throw new P("nonce_mismatch")}assertIdentity(e,t){let r=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(ee(e.issuer)!==ee(r.issuer))throw new P("issuer_mismatch");if(!i.includes(r.clientId))throw new P("client_mismatch");if(e.authorizedParty!==r.clientId)throw new P("client_mismatch");if(!e.subject||!e.sessionId)throw new P("required_claim_missing");if(e.nonce!==t)throw new P("nonce_mismatch")}};function ee(n){return n.replace(/\/+$/u,"")}var tr=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()}}};import{PassphraseMasterKeySource as Sa,RawMasterKeySource as Aa,deriveMasterKey as ba,generateHexSeed as _a,computePassphraseVerifier as Ca}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as Ta}from"@safetech/inheriti-core-sdk/node";function ra(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=(a,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",n.environment),e(a,Object.assign({},s,{headers:o}))},r=n.business?void 0:ct({apiUrl:n.apiUrl,getBearerToken:n.getBearerToken,transport:t,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners}),i=new ne(n.apiUrl,n.environment,n.getBearerToken,t,n.business?{organizationId:n.organizationId}:void 0);return new Y(r,{keyVault:n.keyVault,state:n.state,api:i,reconstructor:new J(n.workerUrl),masterKeys:n.masterKeys,masterKey:n.masterKey,applicationId:n.applicationId,organizationId:n.organizationId,assetDecoder:Jr})}function na(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=ct({apiUrl:new URL(n.apiUrl).origin,getBearerToken:n.getBearerToken,transport:e,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new Ie(new he(n.apiUrl,n.environment,n.getBearerToken,e),t)}function ia(n){if(!n.payloadStorage||!n.secureSessionStorage||!n.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=n.transport??globalThis.fetch.bind(globalThis),t=new URL(n.apiUrl).origin,r=ct({apiUrl:t,getBearerToken:n.getBearerToken,transport:jt({apiUrl:t,organizationId:n.organizationId,planId:n.planId,editId:n.editId,environment:n.environment,transport:e}),secureSessionStorage:n.secureSessionStorage,payloadStorage:n.payloadStorage,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new qe(new Ke(n.apiUrl,n.environment,n.getBearerToken,e),r,n.editRecoveryStore)}export{te as BusinessOrganizationSelectionError,ye as CorePlanMaterialBuilder,Ia as DataAssetDefinitionService,N as ElementsApiRequestFailed,Y as ElementsClient,pe as GuidedCreateRecoveryError,ce as GuidedPlanCreator,ge as HttpAutomationRevealApiPort,ne as HttpElementsApiPort,Zt as HttpOperatorAuthTransport,Ke as HttpPlanEditPort,he as HttpQuickPlanPort,I as InvalidPlanDeclaration,b as InvalidPlanMaterial,we as MasterKeyRelayCancellationFailed,Ee as MasterKeyRelayExpired,Re as MasterKeyRelayTimedOut,q as MasterKeyRequired,le as MemoryGuidedCreateCheckpointStore,oe as MemoryKeyVault,de as MemoryStatePort,P as OAuthProtocolError,er as OperatorAuthClient,ve as OperatorAuthError,Pe as OperatorReauthenticationRequired,tr as OperatorSessionController,We as PLAN_CREATION_SERVER_STAGES,Sa as PassphraseMasterKeySource,Ta as PlanAssetDeclaration,H as PlanRequestFailed,Ie as QuickPlanCreator,qe as QuickPlanEditor,Aa as RawMasterKeySource,M as RelayMasterKeySource,$e as StaticMasterKeyResolver,ze as SystemOAuthClock,Ge as WebOAuthCrypto,Ca as computePassphraseVerifier,Se as createMasterKeyResolver,Yr as createNodeAutomationRevealClient,ra as createNodeElementsClient,na as createNodeQuickPlanCreator,ia as createNodeQuickPlanEditor,Jr as decodeAssetContainer,ba as deriveMasterKey,_a as generateHexSeed,se as masterKeyRefFor,V as masterKeyRefKey,dt as oauthErrorCode,Mr as selectBusinessOrganization,rt as unwrapDekWithMasterKey,B as validatePlanCreationInput,j as validatePlanCreationMaterial};
|