@safetech/inheriti-client-sdk 1.17.25 → 1.17.26

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/node.js CHANGED
@@ -1 +1 @@
1
- import{createNodeSharedConfigurationSdk as Kt,decodeAssetContainer as Fr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as qn,generateRSAOAEPKeyPair as Gn}from"@safetech/inheriti-core-sdk/crypto";var Oe=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ke=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},Ne=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},z=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await Gn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(g=>new Promise(f=>setTimeout(f,g))),c=!0,l=!1,p,m=()=>p??=(async()=>{let g=new AbortController,f,T=new Promise((x,k)=>{f=setTimeout(()=>{g.abort(),k(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,g.signal),T])}finally{clearTimeout(f)}})(),y,b=new Promise((g,f)=>{y=()=>{c&&m().catch(()=>{}),f(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",y,{once:!0})});b.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let g=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),b]);if(g.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(g.status==="DELIVERED"&&g.sealedMasterKey){let f=(await qn(g.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(f))throw new Error("invalid_master_key_material");return f}if(g.status==="EXPIRED")throw new ke(s.sessionId);await Vn(d,a,e)}throw new Oe(s.sessionId)}catch(g){if(c&&(!l||e?.aborted))try{await m()}catch(f){if(e?.aborted)throw new Ne(f)}throw g}finally{y&&e?.removeEventListener("abort",y)}}};async function Vn(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function Ke(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||pt(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(zn(e,r.applicationId)){let i=await r.source?.resolve();return i||pt(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return pt(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function zn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function pt(r,e,t,n,i){if((await e()).relayAvailable)return new z({...r.relay,api:Bn(r.api,t)}).resolve(n,i)}function Bn(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function J(r){return`${r.system}:${r.contextId}`}function Ie(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var j=class extends Error{constructor(t){super(`master_key_required:${J(t)}`);this.ref=t;this.name="MasterKeyRequired"}},ut=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(J(e),t),this}async resolve(e){return this.sources.get(J(e))?.resolve()}};var he=class{keys=new Map;async store(e,t){let n=J(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(J(e))?.slice()}async remove(e){let t=J(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ye=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 Ue=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},P=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Le=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var Fe=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],gt={"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"]},It=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],w=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},N=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function se(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new N("plan_material_field_unknown");if(mt(r.dataShards,"data_shards_invalid"),mt(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&mt(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new N("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new N("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new N("material_operation_invalid")}function mt(r,e){if(!Array.isArray(r))throw new N(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new N(e);if(t.data!==void 0&&typeof t.data!="string")throw new N(e)}}function Z(r){if(ie(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Wn(r.idempotencyKey))throw new w("idempotency_key_invalid");if(!r.name?.trim())throw new w("plan_name_required");if(!r.assets.length)throw new w("assets_required");let e=new Set;for(let t of r.assets){if(ie(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 w("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!Fe.includes(t.type))throw new w("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new w("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 w("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new w("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new w("asset_field_names_invalid");if($n(t.matchOrigins),!t.isBinary){let s=gt[t.type];if(!s||i.some(a=>!s.includes(a)))throw new w("asset_field_name_not_canonical")}}if(!r.participants.length)throw new w("participants_required");for(let t of r.participants){if(ie(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Ft(t.routingEmail))throw new w("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new w("participant_relationships_invalid")}Hn(r)}function $n(r){if(r===void 0)return;if(!r.length)throw new w("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new w("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new w("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof w?n:new w("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new w("asset_match_origins_duplicated")}function Hn(r){let e=r.policy;if(e&&ie(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new w("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){ie(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new w("authentication_mode_invalid")}if(e.moderation){ie(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new w("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new w("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new w("approval_mode_invalid")}let t=e.dms;if(!t)return;ie(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Ft(t.subjectEmail))throw new w("dms_subject_invalid");if(!r.participants.some(s=>Lt(s.routingEmail)===Lt(t.subjectEmail)))throw new w("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new w("dms_countdown_invalid")}function Wn(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Ft(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Lt(r){return r.normalize("NFC").trim().toLowerCase()}function ie(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new w(t)}var fe=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},Pe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),Z(e),qe(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,s={}){Z(t);let a=await this.checkpoints.load(e);if(!a)throw new ve("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await qt(t))throw new ve("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.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;qe(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});qe(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});qe(s.signal),se(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(l.stage),l.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,l),l}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 qt(e),serverStage:t.stage})}},ve=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function qt(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function qe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Gt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Ue(n.stage);return r.authorizeRevealAction(e,t)}function Qn(r){let e=r?.status;return e===400||e===401||e===403}async function Vt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Qn(s))throw s}return r.releaseRevealMaterial(e,t)}function jn(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?Xn(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Yn.has(r.stage)?"ENDED":"CONTINUING"}var Yn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Xn(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var ht=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ve(r,e,t={},n=!1){if(t.signal?.aborted)throw R();let i=await r.getPlan(e),s=await r.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):zt(s.id);if(t.signal?.aborted)throw R();let a=()=>r.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)});if(n||await a(),t.signal?.aborted)throw R();let o=t.idempotencyKey??crypto.randomUUID(),d;try{d=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:o,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let p=await r.getActivePlanReveal(e);throw!p||p.planId!==e||p.mode!==(t.mode??"DIRECT")||p.protectedCopy!==void 0&&p.protectedCopy!==(t.protectedCopy??!1)?l:zt(p.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let c;try{if(t.signal?.aborted)throw R();let l=await Zn(r,d,t);if(t.signal?.aborted||(n&&await a(),t.signal?.aborted)||(ee(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw R();let p=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id),t.signal?.aborted))throw R();let m;try{m=await rr(r,l,sr(p),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(ee(t,"RECONSTRUCTING",l),t.signal?.aborted))throw R();try{c=await r.reconstructPlanMaterial(m)}catch(b){throw t.signal?.aborted?R():(await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:nr(b)}),b)}if(t.signal?.aborted)throw R();let y=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(ee(t,"OPEN",y),t.signal?.aborted))throw R();return new ft(r,y,i,c,t.signal)}catch(l){throw c?.fill(0),await Ht(r,d.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function zt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Jn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Zn(r,e,t){let n=await Y(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw R();if(t.onSession?.(n),t.onProgress?.({phase:jn(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Jn.has(n.stage))throw new yt(n.stage);await vt(t.pollIntervalMs??1500,t.signal),n=await Y(()=>r.getReveal(e.id,t.signal),t.signal)}}var yt=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function ee(r,e,t){r.onProgress?.({phase:e,session:t})}function vt(r,e){return e?.aborted?Promise.reject(R()):new Promise((t,n)=>{let i=setTimeout(a,Math.max(0,r)),s=()=>{clearTimeout(i),n(R())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var ft=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new ht;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=e.map(({selector:s,options:a={}})=>{let o=er(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new M("asset_not_found");if(d.isBinary)throw new M("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new M("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),i=[];try{for(let a of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:a.options.idempotencyKey??crypto.randomUUID(),assetId:a.asset.id,fieldName:a.field,action:a.options.action??"VIEW_FIELD",...a.options.destination===void 0?{}:{destination:a.options.destination},...a.options.origin===void 0?{}:{origin:a.options.origin}}));let s=n.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new M("asset_value_invalid");return{selector:a.selector,value:tr(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",Bt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=this.plan.assets.find(a=>a.code===e||a.id===e);if(!n)throw new M("asset_not_found");if(!n.isBinary)throw new M("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!a||!(a.data instanceof Uint8Array))throw new M("asset_value_invalid");s=a.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",Bt(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Ht(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 er(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new M("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new M("asset_selector_invalid");return{asset:r.asset,field:r.field}}function tr(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new M("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new M("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?gt[t]:void 0)?.includes(e))return"";throw new M("asset_value_invalid")}return n[e]}function Bt(r){if(r instanceof M)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function nr(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function rr(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await Y(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Ge;let c=await Y(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if($t(c,i.id,e.planId),!c.shares.includes(i.data))throw new W;ee(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await Y(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw R();if(!l?.trim())throw new W;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw R();return{...t,shares:t.shares.filter(p=>p!==i).concat(c.shares.map((p,m)=>({id:`${c.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:p})))}}if(d!=="SK_MOBILE")throw new W;if(n.signal?.aborted)throw R();return await r.distributeRevealCustodianShare(e.id),ee(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),ee(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await vt(n.pollIntervalMs??1500,n.signal),s=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Ge;if(!s.shareId||!s.deviceId)throw new W;ee(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Y(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw R();if($t(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new W;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw R();return{...t,shares:t.shares.concat(d.shares.map((c,l)=>({id:`${d.id}:${l}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new W;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(a),ee(n,"WAITING_FOR_CUSTODIAN",a),n.signal?.aborted)throw R();await r.requestRevealCustodianRelease(e.id);let o=await ir(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function $t(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new W}async function Y(r,e){if(e?.aborted)throw R();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(R()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw R();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function ir(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await Y(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new W}if(Date.now()>=n)throw new Pt;await vt(t.pollIntervalMs??1500,t.signal)}}var W=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Ge=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Pt=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function sr(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function Ht(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(a){if(!ar(a))throw a}return}let n=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(a.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(a){if(a?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:a}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function ar(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function R(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var ae=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 he,this.state=t.state??new ye,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??cr(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new P;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new P;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new P;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new P;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return Z(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new P;return se(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new P;return new Pe(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new j({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return dr(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new j(e);return await this.keyVault.store(e,or(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new P;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new P;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Le;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new j({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=Ie(e);if(!i)throw new j({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new P;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new P;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new P;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new P;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new P;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new P;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new P;return this.api.getReveal(e,t)}openReveal(e,t){return Ve(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new P;return Vt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new P;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new P;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new P;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new P;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new P;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new P;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new P;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new P;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new P;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new P;return Gt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new P;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new P;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new P;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new P;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new P;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new P;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new P;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new bt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new j({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},bt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function or(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function dr(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function cr(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return Ke({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Ke({...e,organizationId:r.organizationId})}var lr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],pr=["DIRECT","GOVERNED"],Qt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],ur=["ACTIVE","REVOKED"],mr=["SK_MOBILE"],gr=["ACTIVE","INACTIVE"],Ir=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function jt(r){let e=O(r);return{items:F(e.items).map(Jt),nextCursor:e.nextCursor===null?null:h(e.nextCursor,"nextCursor")}}function Yt(r){let e=O(r);return{total:B(e.total,"total"),items:F(e.items).map(t=>{let n=O(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:h(n.id,"log.id"),planId:h(n.planId,"log.planId"),tenantId:h(n.tenantId,"log.tenantId"),event:h(n.event,"log.event"),occurredOn:h(n.occurredOn,"log.occurredOn"),status:X(n.status),title:h(n.title,"log.title"),details:F(n.details).map(i=>{let s=O(i);return{label:h(s.label,"log.detail.label"),value:h(s.value,"log.detail.value")}})}})}}function Xt(r){let e=O(r);return{total:B(e.total,"total"),items:F(e.items).map(t=>{let n=O(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=h(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:h(n.id,"log.id"),memberId:h(n.memberId,"log.memberId"),source:i,event:h(n.event,"log.event"),occurredOn:h(n.occurredOn,"log.occurredOn"),status:X(n.status)}})}}function ze(r){let e=O(r),t=Jt(e),n=O(e.source),i=h(n.kind,"source.kind");return{...t,assets:F(e.assets).map(s=>{let a=O(s);return{id:h(a.id,"asset.id"),code:X(a.code),type:L(h(a.type,"asset.type"),Fe),name:h(a.name,"asset.name"),isBinary:yr(a.isBinary,"asset.isBinary"),fieldNames:F(a.fieldNames).map(o=>h(o,"asset.fieldNames")),fileName:X(a.fileName),mimeType:X(a.mimeType),size:a.size===void 0||a.size===null?void 0:B(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:F(a.matchOrigins).map(o=>h(o,"asset.matchOrigins"))}}),participants:F(e.participants).map(s=>{let a=O(s);return{id:h(a.id,"participant.id"),displayName:h(a.displayName,"participant.displayName"),relationships:F(a.relationships).map(o=>L(h(o,"relationship"),Qt)),lifecycle:L(h(a.lifecycle,"participant.lifecycle"),ur)}}),revealPolicy:(()=>{let s=O(e.revealPolicy);return{masterKeyRelease:L(h(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:L(h(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=O(e.dms);return{subjectEmail:h(s.subjectEmail,"dms.subjectEmail"),countdownDays:B(s.countdownDays,"dms.countdownDays"),countdownHours:B(s.countdownHours,"dms.countdownHours"),countdownMinutes:B(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:L(h(n.system,"source.system"),["INHERITI_BUSINESS"]),status:L(h(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function be(r){let e=O(r);return{operationId:h(e.operationId,"operationId"),stage:L(h(e.stage,"stage"),It),outcome:L(h(e.outcome,"outcome"),Ir),planId:X(e.planId),lastErrorCode:X(e.lastErrorCode),participants:e.participants===void 0?void 0:F(e.participants).map(t=>{let n=O(t);return{clientParticipantRef:h(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:h(n.planParticipantId,"planParticipantId"),relationships:F(n.relationships).map(i=>hr(h(i,"relationship"),Qt))}})}}function Jt(r){let e=O(r),t=O(e.assetSummary),n=O(e.governance),i=O(e.participantSummary);return{id:h(e.id,"id"),name:h(e.name,"name"),description:X(e.description),status:L(h(e.status,"status"),lr),createdAt:h(e.createdAt,"createdAt"),configuredAt:X(e.configuredAt),assetSummary:{count:B(t.count,"assetSummary.count"),types:F(t.types).map(s=>L(h(s,"assetType"),Fe)),names:Wt(t.names).map(s=>h(s,"assetSummary.names"))},governance:{mode:L(h(n.mode,"governance.mode"),pr),minimumApprovals:B(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:B(i.owners,"owners"),mergers:B(i.mergers,"mergers"),moderators:B(i.moderators,"moderators")},authentication:Wt(e.authentication).map(s=>{let a=O(s);return{id:L(h(a.id,"authentication.id"),mr),status:L(h(a.status,"authentication.status"),gr)}})}}function L(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function hr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function O(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Wt(r){return r==null?[]:F(r)}function F(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function h(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function X(r){return r==null?void 0:h(r,"optional")}function B(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function yr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var ue=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Zt(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function fr(r,e){if(!e){if(r.length===0)throw new ue("organization_required");if(r.length>1)throw new ue("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new ue("organization_access_denied");return e}function Pr(r){let e=E(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),createdAt:U(e.createdAt),...en(e)}}function en(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=E(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:u(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:U(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=E(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:v(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:U(i.revealedAt)}:{}}})}:{}}})}}function tn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Pr),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0),unreadCount:v(e.unreadCount,0),readThroughSequence:v(e.readThroughSequence,0)}}function nn(r){let e=E(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=E(t);return{unitId:u(n.unitId),position:v(n.position,0),commitment:u(n.commitment),status:u(n.status)}})}}function wt(r){let e=E(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),status:e.status}}function rn(r){let e=E(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),parentId:u(e.parentId),participantRevision:v(e.participantRevision,1),recipients:e.recipients.map(Et)}}function sn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);return{parentId:u(n.parentId),sequence:v(n.sequence,1),senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),participantRevision:v(n.participantRevision,1),createdAt:U(n.createdAt),...en(n)}}),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0),unreadCount:v(e.unreadCount,0),readThroughSequence:v(e.readThroughSequence,0)}}function an(r){return{readThroughSequence:v(E(r).readThroughSequence,0)}}function on(r){return{clearedThroughSequence:v(E(r).clearedThroughSequence,0)}}function dn(r){let e=E(r);return{parentId:u(e.parentId),sequence:v(e.sequence,1),senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),canonicalManifest:u(e.canonicalManifest),frame:u(e.frame),signature:u(e.signature),wrappedContentKey:u(e.wrappedContentKey),senderSigningPublicKey:u(e.senderSigningPublicKey)}}function E(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function u(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function U(r){let e=u(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function v(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Et(r){let e=E(r);return{memberId:u(e.memberId),deviceId:u(e.deviceId),deviceVersion:v(e.deviceVersion,1),encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint)}}function me(r){let e=E(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:u(e.id),tenantId:u(e.tenantId),memberId:u(e.memberId),version:e.version,encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint),status:e.status,createdAt:U(e.createdAt),updatedAt:U(e.updatedAt)}}function Be(r){let e=E(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:u(e.id),tenantId:u(e.tenantId),creatorMemberId:u(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(u),participantRevision:e.participantRevision,status:e.status,createdAt:U(e.createdAt),updatedAt:U(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=E(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:u(n.senderMemberId),createdAt:U(n.createdAt)}}return t}function cn(r){let e=E(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(Be),total:e.total,limit:e.limit,offset:e.offset}}function ln(r){let e=E(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Et(t);return{memberId:n.memberId,name:u(E(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:v(e.limit,1),offset:v(e.offset,0),nextOffset:e.nextOffset===null?null:v(e.nextOffset,0)}}function pn(r){let e=E(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:u(n.memberId),name:u(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:u(E(n.profilePicture).url)}}}}),limit:v(e.limit,1),offset:v(e.offset,0),nextOffset:e.nextOffset===null?null:v(e.nextOffset,0)}}function un(r){let e=E(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),messageId:u(e.messageId),participantRevision:v(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Et),shareLayers:e.shareLayers.map(t=>{let n=E(t),i=u(n.id),s=u(n.dataShareId),a=u(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:u(n.contractAddress),dataShareId:s,keyShareId:a};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function $e(r){let e=E(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:u(e.messageId),status:e.status}}function mn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:u(n.id),status:n.status,senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),createdAt:U(n.createdAt),updatedAt:U(n.updatedAt),expiresAt:U(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let a=E(s);if(a.status!=="UNREAD"&&a.status!=="LEASED"&&a.status!=="CONSUMED"&&a.status!=="EXPIRED"&&a.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:u(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:U(a.consumedAt)}:{}}})),i}),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0)}}function gn(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:U(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:v(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId),ciphertext:u(n.ciphertext)}})}}function In(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:U(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:v(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId)}})}}function oe(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function de(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var q=class extends Error{constructor(t,n,i,s){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ce=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,n,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":n},i)}confirmFileAccessDelivery(e,t,n){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":n})}createInboxFileAccess(e,t,n,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",n,void 0,void 0,i)}createRevealFileAccess(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,n)}cancelRevealFileAccess(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",n)}cancelInboxFileAccess(e,t,n,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let n=t;if(typeof n.publicKey!="string"||!n.publicKey||typeof n.fingerprint!="string"||!n.fingerprint||n.status!=="ACTIVE"&&n.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:n.publicKey,fingerprint:n.fingerprint,status:n.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:me(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:me(n)}async registerInboxDevice(e){return me(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return me(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return me(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Be(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return cn(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return ln(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return pn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return un(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return $e(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return tn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return nn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return on(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return sn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return dn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return an(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return $e(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let a=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(a,"PUT",i,s),d=await He(o,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new q(o.status,oe(d),de(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return $e(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return In(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,c=await this.requestBinary(d,"GET",void 0,a);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let l=Number(c.headers.get("content-length"));if(Number.isFinite(l)&&l>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let p=c.body.getReader(),m=[],y=0;try{for(;;){a?.throwIfAborted();let f=await p.read();if(f.done)break;if(y+=f.value.length,y>14*1024*1024)throw new Error("invalid_inbox_share_size");m.push(f.value)}}catch(f){throw await p.cancel().catch(()=>{}),f}let b=new Uint8Array(y),g=0;for(let f of m)b.set(f,g),g+=f.length;return b}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return mn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return gn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Zt)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return jt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return ze(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Yt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let n=new URLSearchParams;t.source&&n.set("source",t.source),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Xt(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){Z(e);let{idempotencyKey:t,...n}=e;return be(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return se(t),be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,s,a){this.requireBusinessSelection(e),a?.throwIfAborted();let o=await this.getBearerToken();a?.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[y,b]of Object.entries(s??{}))d.set(y,b);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:n?JSON.stringify(n):void 0};a&&(l.signal=a);let p=await this.transport(new URL(e,c),l);a?.throwIfAborted();let m=await He(p,a);if(a?.throwIfAborted(),!p.ok)throw new q(p.status,oe(m),de(m),p.headers.get("x-request-id")??void 0);if(!m.ok||m.result===void 0)throw new q(p.status,oe(m),de(m),p.headers.get("x-request-id")??void 0);return m.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let a=new Headers({"x-elements-environment":this.environment});s&&a.set("authorization",`Bearer ${s}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),n&&a.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:a,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await He(d,i);throw new q(d.status,oe(c),de(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let a=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});a&&o.set("authorization",`Bearer ${a}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId);for(let[p,m]of Object.entries(n??{}))o.set(p,m);t&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:o,body:t?JSON.stringify(t):void 0,signal:s}),l=await He(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new q(c.status,oe(l),de(l),c.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new q(400,"organization_selection_required")}};async function He(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Ar}from"@safetech/inheriti-core-sdk/node";async function St(r,e){if(!e)throw new Error("master_key_required");let t=vr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=br(r),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,a);return wr(new Uint8Array(o))}function vr(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function br(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function wr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var we=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await hn("plan_key_unwrap_failed",()=>St(e.planKey,t)),i=await crypto.subtle.importKey("raw",Rt(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await hn("plan_share_decryption_failed",()=>xr(o.data,i));Rr(o.shareType)?a.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new We("plan_share_reconstruction_failed",Sr(o))}}},We=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},Er=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 Sr(r){let e=r instanceof Error?r.message:void 0;if(e)return Er.has(e)?e:void 0}async function hn(r,e){try{return await e()}catch{throw new We(r)}}function Rr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function xr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Rt(r.slice(0,t)),i=Rt(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function Rt(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var le=class extends we{constructor(e){super(()=>Ar(e))}};var Ee=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return ze(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,s,a){a?.throwIfAborted();let o=await this.getAutomationBearerToken();if(a?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...s});n!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:a});a?.throwIfAborted();let l;try{l=await c.json()}catch{a?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new q(c.status,l&&oe(l),l&&de(l));return l?.result}};var _={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 te=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},Se=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;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,n,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:n.validatorShares,encryptedKey:n.encryptedKey})}preflight(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",yn(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",yn(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(_.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(_.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(_.relayFailed);return n}async request(e,t,n,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(_.reauthenticationRequired);s.set("authorization",`Bearer ${a}`),i!==void 0&&s.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,c=await this.transport(new URL(d,o),{method:n,headers:s,body:i===void 0?void 0:JSON.stringify(i)}),l={};try{l=await c.json()}catch{}if(!c.ok||l.ok!==!0)throw new te(c.status,l.error);return l.result}};function yn(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var xe=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){Re(e.signal),Cr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return Re(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){Re(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(Re(e.signal),!i.custodianPair)throw new N("custodian_share_required");let s=xt(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(xt(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(xt(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return Re(e.signal),{protectionProtocol:i.protocol,validatorShares:At(a.encryptedShares),dataShards:At(o.encryptedShares),backupShards:At(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:_r(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:_t(n.encryptedShares[0]),dataShard:_t(n.encryptedShares[1])}}};function xt(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function At(r){return r.map(_t)}function _t(r){return{id:r.id,data:r.encryptedData}}function _r(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new N("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function Cr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new N("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new N("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new N("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new N("plan_secrets_declaration_mismatch")}}function Re(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function fn(r,e,t,n,i,s,a){let o=n.mergeThreshold-(n.withCustodian?1:0);if(typeof n.withCustodian!="boolean"||!Number.isInteger(n.mergeThreshold)||o<1||o>r.totalShares)throw new Error(_.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new z({api:{startRelaySession:y=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,y),readRelaySession:y=>i.readRelaySession(r.organizationId,y)}}),p=new xe(s,l);a?.("encrypting");let m=await p.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return a?.("generating_shares"),p.generateShares({planId:r.planId,declaration:c,encrypted:m})}import{PlanAssetDeclaration as Tr}from"@safetech/inheriti-core-sdk/node";function Pn(r){let e=Ct({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function Ct(r){if(!r.assets.length)throw new w("assets_required");let e=r.assets.map(s=>{if(s.meta.isMedia!==!0)return;let a="data"in s.secret?s.secret.data:void 0,o;if(a instanceof Blob&&(o=a.size),typeof a=="string")try{o=atob(a).length}catch{throw new w("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new w("binary_asset_metadata_invalid");return o}),t=Tr.create(r.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),n=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,r.assets[a].secret]))),i={idempotencyKey:r.planId,name:r.title,assets:n.map((s,a)=>{let o=s.meta.isMedia===!0;return{clientAssetRef:s.id,type:s.type,name:s.meta.name,fieldNames:o?[]:Object.keys(s.secret),isBinary:o,fileName:s.meta.fileName,mimeType:s.meta.mimeType,size:e[a]}}),participants:[]};return{assets:n,plan:i}}async function bn(r){let e=await Promise.all(r.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([n],[i])=>n.localeCompare(i)).map(async([n,i])=>[n,i instanceof Blob?await vn(new Uint8Array(await i.arrayBuffer())):i]))})));return vn(new TextEncoder().encode(JSON.stringify({organizationId:r.organizationId,planId:r.planId,title:r.title,description:r.description??null,audience:r.audience??null,totalShares:r.totalShares,assets:e})))}async function vn(r){let e=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ae=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(a=>!a?.meta?.name?.trim()))throw new Error(_.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(_.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(_.invalidShares);let n=await bn(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(_.reconciliationRequired);return i.promise}let s=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let i=Ct({planId:e.planId,title:e.title,assets:e.assets}),s=this.material.get(e.planId);if(s&&(s.fingerprint!==t||s.masterKeySource!==e.masterKeySource))throw new Error(_.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(Qe(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(_.reconciliationRequired);if(!a&&s)throw new Error(_.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(_.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(_.invalidMasterKeyContext);if(!a){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(a=await this.statusOrMissing(e.organizationId,e.planId),!a)throw l}}a??=await this.port.status(e.organizationId,e.planId);let d=s?.encrypted??await fn(e,i,o,a,this.port,this.coreSdk,n);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),n?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),n?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),n?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!Qe(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return Qe(c)&&this.material.delete(e.planId),{planId:e.planId,status:Qe(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(_.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof te&&n.status===404)return;throw n}}};function Qe(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var je=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}start(e,t,n,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:n},i)}async listEligibleCandidates(e,t,n){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),n&&i.set("namePrefix",n);let s=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(s))throw new Error("invalid_plan_edit_candidates");return s}async context(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(n))throw new Error("invalid_plan_edit_context");return n}async moderatorNames(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!n||typeof n!="object")throw new Error("invalid_plan_edit_participants");let i=n;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let s=new Map;for(let a of i.participants){if(!a||typeof a.id!="string"||!a.id||typeof a.displayName!="string"||!Array.isArray(a.relationships)||!a.relationships.every(o=>typeof o=="string")||typeof a.lifecycle!="string")throw new Error("invalid_plan_edit_participants");a.lifecycle==="ACTIVE"&&a.relationships.includes("MODERATOR")&&s.set(a.id,a.displayName)}return s}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(_.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(_.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(_.relayFailed);return n}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(n))}commit(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(n))}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,n,i,s){let a=await this.getBearerToken();if(!a)throw new Error(_.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${a}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),s&&o.set("idempotency-key",s);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),c=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,l=await this.transport(new URL(c,d),{method:n,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),p={};try{p=await l.json()}catch{}if(!l.ok||p.ok!==!0){let m=Array.isArray(p.validationErrors)?p.validationErrors.join("; "):void 0;throw new te(l.status,m||p.error)}return p.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(n=>!!n&&typeof n.id=="string"&&!!n.id&&typeof n.name=="string"&&n.status==="PROTECTED"&&typeof n.createdAt=="string"&&!!n.assetSummary&&Number.isSafeInteger(n.assetSummary.count)&&n.assetSummary.count>=0&&Array.isArray(n.assetSummary.types)&&n.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(n.assetSummary.names)&&n.assetSummary.names.every(i=>typeof i=="string")&&!!n.governance&&["DIRECT","GOVERNED"].includes(n.governance.mode)&&Number.isSafeInteger(n.governance.minimumApprovals)&&n.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 Ye=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.recoveryStore=n}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 n=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),s=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!s)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let a=this.revealedAssets,o=a?.organizationId===e.organizationId&&a.planId===e.planId&&a.editId===e.editId&&a.expiresAt>Date.now();a&&!o&&(this.revealedAssets=void 0);let d=s.masterKeyEncrypted?e.masterKey??(o?a.masterKey:void 0):void 0;s.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?a.assets:await this.revealAssets(e,d,s.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(l.map(p=>p.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&n===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:s,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),n=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"||!(n>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return n}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new z({api:{startRelaySession:n=>this.port.startRelaySession(e.organizationId,t,n),readRelaySession:n=>this.port.readRelaySession(e.organizationId,n)}}).resolve()}async revealAssets(e,t,n,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=g=>{g!==o&&(o=g,i?.(g))},c=g=>{if(g.processId!==e.editId||g.planId&&g.planId!==e.planId)return;switch(g.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 f=this.approvalError(g);if(f?.startsWith("edit_authentication_")&&d("pending_auth"),f?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!g.moderatorParticipants||g.requiredModeratorApprovals===void 0||!g.approvalProcess)return;let T=g.moderatorParticipants.map(x=>x.memberId??x.userId);T.some(x=>typeof x!="string"||!x)||new Set(T).size!==T.length||i?.(o,{requiredApprovals:g.requiredModeratorApprovals,approvedModerators:g.approvalProcess.approvedModerators,moderators:g.moderatorParticipants.map((x,k)=>{let A=T[k],H=x.flows.filter(ge=>ge.status==="PENDING"&&ge.expiresAt&&Number.isFinite(ge.expiresAt.getTime())).map(ge=>ge.expiresAt.getTime());return{id:A,displayName:a.get(A)||"Moderator",status:x.status,expiresAt:H.length?new Date(Math.min(...H)).toISOString():void 0}})})},l=await s.resume(e.planId,{onViewUpdate:c});if(l?.processId!==e.editId||l.planId&&l.planId!==e.planId)throw new Error("edit_merge_not_ready");c(l),this.assertApprovalOutcome(e.planId,l),l.status!=="READY_TO_REVEAL"&&l.status!=="REVEALED"&&await s.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let p=await s.getView(e.editId);if(p?.processId!==e.editId||p.planId&&p.planId!==e.planId)throw new Error("edit_merge_not_ready");c(p),this.assertApprovalOutcome(e.planId,p);let m=p?.status;if(m!=="READY_TO_REVEAL"&&m!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let y=null,b={onRevealed:g=>{y=g},onViewUpdate:c,onRevealStepUpdate:(g,f)=>{if(f==="IN_PROCESS")switch(g){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(n&&(b.onCustodianShareRequired=async(g,f)=>{switch(f.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 s.distributeCustodianShareViaMobile(f.planId);if(T!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let x=e.proDevice;try{this.assertNotAborted(e.signal);let k=await s.getCustodianShareData(g);this.assertShare(k,f.planId),d("connecting_safekey_pro");let{deviceId:A}=await x.write(k,e.signal);if(this.assertNotAborted(e.signal),!A?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(f.planId,k.id,A,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(g,k.id);return}finally{x.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),!f.shareId||!f.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let x=await T.read({shareId:f.shareId,planId:f.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(x,f.planId,f.shareId),x.deviceId!==f.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:x.shares}}finally{T.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),m==="REVEALED"?await s.resumeReveal(e.editId,b,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},b,t),this.assertNotAborted(e.signal),!y)throw new Error("edit_assets_unavailable");return y}assertApprovalOutcome(e,t){let n=this.approvalError(t);if(n)throw this.clearRevealedAssets(e),new Error(n)}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,n){if(!e||!e.id||e.id!==(n??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 Dr=r=>JSON.stringify(r??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([n],[i])=>n<i?-1:n>i?1:0))),Xe=class{constructor(e,t,n,i){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=i}async saveAssets(e,t,n,i,s,a){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,i);a?.("preparing");let c=await o.prepare(d);this.assertNotAborted(e.signal);let l={mergeProcessId:e.editId,protectionProtocol:c.protectionProtocol,validatorShares:this.transportShares(c.validatorShares),dataShards:this.transportShares(c.dataShards),backupShards:this.transportShares(c.backupShards),encryptedKey:c.encryptedKey,assetsMetadata:c.assetsMetadata,custodianPair:c.custodianPair};if(a?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,l),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:s,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,s,l,o,d,a)}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 n=await this.configurationRepository().findByPlanId(e.planId),i=n?.editDistribution??n?.preparedDistribution;if(!t&&(!i||n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let s=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),dataShards:i.dataShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),backupShards:i.backupShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,s))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let a=await this.port.status(e.organizationId,e.editId);return a.id!==e.editId||a.planId!==e.planId||a.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,s),await this.port.commit(e.organizationId,e.planId,s),await this.isCommitted(e,s)?(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 n=await this.configurationRepository().findByPlanId(e.planId);if(n?.editDistribution&&n.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 n=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await n.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await n.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,n,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:s,configuration:a}}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,n,i,s,a){let o,d=c=>{let l;switch(c.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":l="distributing_validators";break;case"SHARES_DISTRIBUTION":l="distributing_data";break;case"FINALIZE":l="finalizing";break;default:return}l!==o&&(o=l,a?.(l))};try{await i.execute(s,{onLocalProcessUpdated:d})}catch(c){try{if(a?.("verifying"),await this.isCommitted(e,n))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&a?.(o),c}try{if(a?.("verifying"),!await this.isCommitted(e,n))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 n=await this.port.commitStatus(e.organizationId,e.editId);if(n.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(n.status)||n.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(Dr(t.assetsMetadata)),s=await globalThis.crypto.subtle.digest("SHA-256",i),a=Array.from(new Uint8Array(s),c=>c.toString(16).padStart(2,"0")).join("");if(n.assetsMetadataHash!==a)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(c=>c.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(n.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var Je=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new Ye(e,t,n),this.reconfiguration=new Xe(e,t,n,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,n,i){return this.port.start(e,t,n,i)}async listAssets(e,t){let{assets:n}=await this.assetAccess.loadAssets(e,t);return n.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,n){let{assets:i}=await this.assetAccess.loadAssets(e,n),s=i.find(a=>a.id===t);if(!s)throw new Error("edit_asset_not_found");return structuredClone(s)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=s.findIndex(l=>l.id===e.assetId);if(a<0)throw new Error("edit_asset_not_found");let o=s[a];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},c=s.map((l,p)=>p===a?d:l);return this.reconfiguration.saveAssets(e,c,n.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=Pn({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(s.map(d=>d.id)).has(a.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,s.concat(a),n.withCustodian,i,a.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 wn({apiUrl:r,organizationId:e,planId:t,editId:n,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),c=new URL(r.endsWith("/")?r:`${r}/`);if(d.origin!==c.origin||!d.pathname.startsWith(c.pathname))throw new Error("unsupported_core_edit_route");let l=d.pathname.slice(c.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(l===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return s(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let p=Mr(l,d.searchParams,t,n),m=new Headers(o?.headers);m.set("x-organization-id",e),m.set("x-elements-environment",i);let y=c.pathname.endsWith("/integrations/")?`v1/${p}`:`integrations/v1/${p}`;return s(new URL(y,c),Object.assign({},o,{headers:m}))}}function Mr(r,e,t,n){if(r==="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 s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){let o=s[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(s[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(n)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as Or}from"@safetech/inheriti-core-sdk/node";function En(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=Ie(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new z({api:{startRelaySession:o=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>r.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>r.api.cancelMasterKeyRelaySession(o,d)}}),a=new ae(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(o,d,c)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,c)}}});return Ve(a,e,t,!0)}}}function kr(r){let e=new Ee(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{...En({api:e,reconstructor:new le(r.workerUrl),assetDecoder:Or}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as Ze,sealInheritiFile as et,readInheritiFileHeader as Tt,openInheritiFile as Dt,InheritiFileInvalid as Nr,MAX_INHERITI_FILE_BYTES as Mt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as tt,openInheritiFileKey as Ot}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Kr(r){let{reveal:e,api:t,signal:n}=r;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(n);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let a=r.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(r.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>Mt-1024*1024)throw new Error("unsupported_protected_asset");let d=Ze(),c,l=!1,p=!1;try{n?.throwIfAborted();let m=await tt(d,i.publicKey);l=!0;let y=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:m,openLimit:a},n);if(y.copyId!==r.copyId||y.status!=="PENDING")throw new Error("file_access_create_invalid");let b=await t.getFileAccess(r.copyId,n);for(;b.status==="PENDING";){if(n?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((f,T)=>{let x=()=>{clearTimeout(k),T(n?.reason)},k=setTimeout(()=>{n?.removeEventListener("abort",x),f()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",x,{once:!0})}),b=await t.getFileAccess(r.copyId,n)}if(b.status!=="READY"||b.origin!=="REVEAL"||b.copyId!==r.copyId||b.allowedUses!==a||!b.recipient||!b.deployment||b.expiresAt!==null&&(!Number.isFinite(Date.parse(b.expiresAt))||Date.parse(b.expiresAt)>s||Date.parse(b.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let g=await et({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:b});g.fileKey.fill(0),c=g.fileBytes,n?.throwIfAborted(),await r.save({fileName:o.fileName,fileBytes:c}),p=!0}catch(m){if(l&&!p)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(y){throw new AggregateError([m,y],"protected_asset_export_and_cleanup_failed",{cause:m})}throw m}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as Io}from"@safetech/inheriti-core-sdk/node";function Sn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var nt=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Sn(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Sn(new Uint8Array(t))}},rt=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var _e=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},Ce=class extends _e{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},S=class extends _e{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function kt(r){if(r instanceof _e)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Rn=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:ne(n,"issuer"),authorizationEndpoint:ne(n,"authorization_endpoint"),tokenEndpoint:ne(n,"token_endpoint"),deviceAuthorizationEndpoint:Q(n,"device_authorization_endpoint"),endSessionEndpoint:Q(n,"end_session_endpoint"),revocationEndpoint:Q(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:ne(t,"device_code"),userCode:ne(t,"user_code"),verificationUri:ne(t,"verification_uri"),verificationUriComplete:Q(t,"verification_uri_complete"),expiresInSeconds:xn(t,"expires_in"),intervalSeconds:Nt(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:ne(n,"access_token"),refreshToken:Q(n,"refresh_token"),idToken:Q(n,"id_token"),tokenType:ne(n,"token_type"),expiresInSeconds:xn(n,"expires_in"),refreshExpiresInSeconds:Nt(n,"refresh_expires_in"),scope:Q(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let s=Q(i,"error")??`oauth_http_${n.status}`;throw new S(s,Q(i,"error_description")??s)}return i}};function ne(r,e){let t=Q(r,e);if(!t)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function Q(r,e){return typeof r[e]=="string"?r[e]:void 0}function xn(r,e){let t=Nt(r,e);if(t===void 0)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function Nt(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Ur=600*1e3,it=5,Lr=5,An=class{constructor(e){this.options=e;this.crypto=e.crypto??new nt,this.clock=e.clock??new rt}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+Ur;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",a),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:o}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new S("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new S("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new S("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new S("state_mismatch");let a=i.searchParams.get("error");if(a)throw new S(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new S("authorization_code_missing");let d=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),l=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(l),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new S("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(it,t.intervalSeconds??it),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new S("device_transaction_missing");let i=n,s=await this.getDiscovery(),a=Math.max(it,i.intervalSeconds??it),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:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(d){let c=kt(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=Lr,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new S("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 Ce;let t;try{let n=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:n.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(n){let i=kt(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Ce):(this.isOfflineSession(e)||await this.options.sessions.clear(),n)}try{if(!t.refreshToken)throw new S("refresh_token_rotation_missing");let n=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(n),n}catch(n){throw await this.options.sessions.clear(),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(pe(e.issuer)!==pe(this.options.configuration.issuer))throw new S("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${pe(t)}|${n}|${i}`}async acceptTokens(e,t,n){if(e.tokenType.toLowerCase()!=="bearer")throw new S("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 S("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 S("token_subject_mismatch")}let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access"));return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&a?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:a,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(i.issuer))throw new S("issuer_mismatch");if(!s.includes(i.audience))throw new S("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new S("client_mismatch");if(e.environment!==i.environment)throw new S("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new S("required_claim_missing");if(n&&e.nonce!==t)throw new S("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(n.issuer))throw new S("issuer_mismatch");if(!i.includes(n.clientId))throw new S("client_mismatch");if(e.authorizedParty!==n.clientId)throw new S("client_mismatch");if(!e.subject||!e.sessionId)throw new S("required_claim_missing");if(e.nonce!==t)throw new S("nonce_mismatch")}};function pe(r){return r.replace(/\/+$/u,"")}var _n=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 bo,RawMasterKeySource as wo,deriveMasterKey as Eo,generateHexSeed as So,computePassphraseVerifier as Ro}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as Ao}from"@safetech/inheriti-core-sdk/node";function Xa(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",r.environment),e(s,Object.assign({},a,{headers:o}))},n=r.business?void 0:Kt({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),i=new ce(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new ae(n,{keyVault:r.keyVault,state:r.state,api:i,reconstructor:new le(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:Fr})}function Ja(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=Kt({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ae(new Se(r.apiUrl,r.environment,r.getBearerToken,e),t)}function Za(r){if(!r.payloadStorage||!r.secureSessionStorage||!r.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=r.transport??globalThis.fetch.bind(globalThis),t=new URL(r.apiUrl).origin,n=Kt({apiUrl:t,getBearerToken:r.getBearerToken,transport:wn({apiUrl:t,organizationId:r.organizationId,planId:r.planId,editId:r.editId,environment:r.environment,transport:e}),secureSessionStorage:r.secureSessionStorage,payloadStorage:r.payloadStorage,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Je(new je(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as qr}from"node:crypto";import{generateRSAOAEPKeyPair as Gr}from"@safetech/inheriti-core-sdk/crypto";async function Cn(r){let e=Tt(r.fileBytes);if(!/^[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(e.copyId))throw new Error("invalid_startup_file");if(r.signal?.aborted)throw new Error("opening_cancelled");let t=await r.api.getFileAccess(e.copyId,r.signal);if(e.deployment!==t.deployment||e.origin!==t.origin||e.copyId!==t.copyId||e.recipient!==t.recipient||e.expiresAt!==t.expiresAt||e.allowedUses!==t.allowedUses)throw new Error("file_binding_mismatch");return{header:e,access:t}}async function Vr(r){let{api:e,sessionId:t,signal:n}=r;if(!/^[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(t))throw new Error("invalid_opening_session");let i=Uint8Array.from(r.fileBytes),s,a,o=()=>{if(n?.aborted)throw new Error("opening_cancelled")};try{let{access:d}=await Cn({fileBytes:i,api:e,signal:n});if(d.status!=="READY"||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())throw new Error("file_access_unavailable");if(r.delivery==="REVEAL"&&d.origin!=="REVEAL")throw new Error("file_access_unavailable");o();let{publicKeyBase64:c,privateKey:l}=await Gr(),p=qr("sha256").update(c).digest("hex");o();let m=await e.requestFileAccessOpening(d.copyId,{sessionId:t,clientPublicKey:c,...r.delivery==="REVEAL"?{delivery:"REVEAL"}:{}});r.delivery==="REVEAL"&&r.onPairingCode?.(p.slice(0,12));let y=Math.min(Date.parse(m.expiresAt),Date.now()+3e5);if(!Number.isFinite(y))throw new Error("file_opening_expired");let b;for(;!n?.aborted&&Date.now()<y;){let T=await e.readFileAccessOpening(d.copyId,t,p,n);if(T.status==="READY"&&T.encryptedFileKey){b=T.encryptedFileKey;break}if(T.status==="EXPIRED"||T.status==="DELIVERY_CONFIRMED")throw new Error("file_opening_expired");o(),await new Promise(x=>{let k=()=>{clearTimeout(A),n?.removeEventListener("abort",k),x()},A=setTimeout(k,1e3);n?.addEventListener("abort",k,{once:!0})})}if(o(),!b)throw new Error("file_opening_expired");s=await Ot(b,l),o(),await e.confirmFileAccessDelivery(d.copyId,t,p);let g=await Dt(i,s,d);a=g.plaintext,o();let f={plaintext:a,header:g.header};return a=void 0,f}finally{i.fill(0),s?.fill(0),a?.fill(0)}}import{createHash as zr,webcrypto as Br}from"node:crypto";import{canonicalInboxManifest as $r,decodeInboxManifest as Hr,decodeInboxContentFrame as Wr,decodeInboxText as Qr,decryptInboxShare as jr,encodeInboxContentFrame as Ut,encodeInboxText as Yr,encryptInboxShare as Tn,inboxProtectedUnitCommitment as Xr,inboxTextMetadataDigest as Dn,openInboxContent as Jr,sealInboxContent as Zr,signInboxFrame as ei,unwrapInboxContentKey as ti,unwrapInboxShareKey as ni,verifyInboxFrame as Mn,wrapInboxContentKey as ri,wrapInboxShareKey as ii}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as si}from"@safetech/inheriti-core-sdk/workers/inbox.node";var $=Br,D=$,C=r=>{if(!/^[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid_inbox_key");return Buffer.from(r,"hex")},I=r=>{let e=Buffer.from(r,"base64");if(!r||e.toString("base64")!==r)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},G=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),st=async r=>new Uint8Array(await D.subtle.digest("SHA-256",Uint8Array.from(r))),Te=r=>zr("sha256").update(r).digest("hex"),re=class{constructor(e,t=new si){this.api=e;this.worker=t}async send(e){let t=await this.prepare(e);return this.api.publishInboxMessage(e.conversationId,t.submission)}async prepare(e){let{preparation:t,sender:n}=await this.prepareSender(e),i=await this.textManifest(e,t,n),s=$r(i),a=await st(s),{contentKey:o,frame:d}=await Zr(Yr(e.text),a,D),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:p}=await this.protectShares(t,d,a),m=await this.wrapRecipientKeys(t,o,a),y=await ii(l,C(e.tenantKeyHex),a,i.tenantId,i.messageId,D);return{frame:Buffer.from(Ut(d)).toString("base64"),submission:{messageId:t.messageId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,expiresAt:e.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(c).toString("base64"),tenantWrappedShareKey:Buffer.from(y).toString("base64"),recipients:m,shares:p}}}async open(e){return this.openWithCommitment(e)}openCommitted(e,t){return this.openWithCommitment(e,t)}async openWithCommitment(e,t){let n=await this.api.openInboxMessage(e.conversationId,e.messageId,e.identity.deviceId),i;try{e.signal?.throwIfAborted();let{manifest:a,manifestDigest:o,senderPublicDer:d}=await this.verifyOpening(e,n),c=await this.recoverFrame(n,a,o,e.tenantKeyHex);if(t&&!G(t,await Xr(a,Ut(c),I(n.signature),D)))throw new Error("inbox_parent_unit_mismatch");i=await this.decryptText(n,c,a,o,d,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(a){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId)}catch{}throw a}let s=await this.ack(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId,e.signal);return e.signal?.throwIfAborted(),{text:i,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:s}}async ack(e,t,n,i,s){for(let a=0;a<2;a++){s?.throwIfAborted();try{return await this.api.ackInboxMessage(e,t,n,i,s),s?.throwIfAborted(),"ACKNOWLEDGED"}catch(o){if(s?.throwIfAborted(),o instanceof q&&o.status>=400&&o.status<500)throw o}}return"PENDING"}async prepareSender(e){let t=await this.api.getInboxSendPreparation(e.conversationId);if(t.conversationId!==e.conversationId||t.threshold!==t.total||t.total!==t.shareLayers.length||t.total<2)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId);if(!n||n.deviceId!==e.identity.deviceId||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Te(I(n.signingPublicKey))!==n.signingKeyFingerprint||Te(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return{preparation:t,sender:n}}async textManifest(e,t,n){let i=Date.parse(e.expiresAt);if(!Number.isSafeInteger(i)||i<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:e.identity.tenantId,conversationId:e.conversationId,messageId:t.messageId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:C(s.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await Dn(D)}}async signFrame(e,t,n,i){let s=await D.subtle.importKey("pkcs8",I(n),"Ed25519",!1,["sign"]),a=await ei(e,t,s,D),o=await D.subtle.importKey("spki",I(i),"Ed25519",!1,["verify"]);if(!await Mn(e,t,a,o,D))throw new Error("inbox_identity_mismatch");return a}async protectShares(e,t,n){let i=await this.worker.split(Ut(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),s=D.getRandomValues(new Uint8Array(32)),a=[];for(let o=0;o<e.total;o++){let d=e.shareLayers[o];a.push({kind:"DATA",index:o,shareId:d.dataShareId,layerId:d.id,ciphertext:Buffer.from(await Tn(i.dataShares[o],s,n,e.messageId,D)).toString("base64")}),a.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await Tn(i.keyShares[o],s,n,e.messageId,D)).toString("base64")})}return{shareKey:s,shares:a}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=I(i.encryptionPublicKey);if(Te(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await D.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:Buffer.from(await ri(t,a,n,D)).toString("base64")}}))}async verifyOpening(e,t,n){let i=I(t.canonicalManifest),s=Hr(i);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!G(s.metadataDigest,n??await Dn(D)))throw new Error("inbox_manifest_mismatch");let a=s.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!a||!G(a.encryptionKeyFingerprint,C(Te(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=I(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Te(o)||!G(s.senderSigningKeyFingerprint,C(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await st(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let s=await ni(I(e.tenantWrappedShareKey),C(i),n,t.tenantId,t.messageId,D),a=[],o=[],d=new Set;for(let l of e.shares){let p=`${l.kind}:${l.index}`;if(d.has(p))throw new Error("duplicate_inbox_share");d.add(p);let m=await jr(I(l.ciphertext),s,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,D);(l.kind==="DATA"?a:o).push(m)}if(a.length!==o.length||a.length<2)throw new Error("incomplete_inbox_shares");let c=await this.worker.reconstruct(a,o,{threshold:a.length,total:a.length,messageId:t.messageId,manifestDigest:n});return Wr(c)}async decryptText(e,t,n,i,s,a){return Qr(await this.decryptContent(e,t,n,i,s,a))}async decryptContent(e,t,n,i,s,a){let o=await D.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Mn(n,t,I(e.signature),o,D))throw new Error("inbox_signature_invalid");let d=await D.subtle.importKey("pkcs8",I(a),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await ti(I(e.wrappedContentKey),d,i,D);return Jr(t,c,i,D)}};import{canonicalInboxManifest as ai,decodeInboxContentFrame as oi,decodeInboxFile as di,decryptInboxShare as ci,encodeInboxContentFrame as li,encodeInboxFile as pi,encryptInboxShare as On,inboxFileMetadataDigest as kn,sealInboxContent as ui,unwrapInboxShareKey as mi,wrapInboxShareKey as gi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var at=class extends re{constructor(t){super(t);this.fileApi=t}async sendFile(t){t.signal?.throwIfAborted();let{preparation:n,sender:i}=await this.prepareSender(t),s=await this.fileManifest(t,n,i),a=ai(s),o=await st(a),d=pi(t.file),c;try{c=await ui(d,o,$)}finally{d.fill(0)}let{contentKey:l,frame:p}=c,m=await this.signFrame(s,p,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let y=await this.worker.split(li(p),{threshold:n.threshold,total:n.total,messageId:n.messageId,manifestDigest:o},t.signal,A=>t.onProgress?.(0,n.total*2,A.stage));t.signal?.throwIfAborted();let b=$.getRandomValues(new Uint8Array(32)),g=[];for(let A=0;A<n.total;A++){let H=n.shareLayers[A];g.push({reference:{kind:"DATA",index:A,shareId:H.dataShareId,layerId:H.id},bytes:await On(y.dataShares[A],b,o,n.messageId,$)}),g.push({reference:{kind:"KEY",index:A,shareId:H.keyShareId,layerId:H.id},bytes:await On(y.keyShares[A],b,o,n.messageId,$)})}let f=await this.wrapRecipientKeys(n,l,o),T=await gi(b,C(t.tenantKeyHex),o,s.tenantId,s.messageId,$);t.signal?.throwIfAborted();let x=await this.fileApi.stageInboxFile(t.conversationId,{messageId:n.messageId,senderDeviceId:i.deviceId,participantRevision:n.participantRevision,expiresAt:t.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(a).toString("base64"),signature:Buffer.from(m).toString("base64"),tenantWrappedShareKey:Buffer.from(T).toString("base64"),recipients:f,shares:g.map(A=>A.reference)},t.signal);if(x.messageId!==n.messageId||x.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let A=0;A<g.length;A++){t.signal?.throwIfAborted();let H=g[A];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,H.reference.shareId,H.bytes,t.signal),t.onProgress?.(A+1,g.length,"UPLOADING")}t.signal?.throwIfAborted();let k=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(k.messageId!==n.messageId||k.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return k}async openFile(t){t.signal?.throwIfAborted();let n=await this.fileApi.openInboxFile(t.conversationId,t.messageId,t.identity.deviceId,t.signal),i,s;try{let{manifest:o,manifestDigest:d,senderPublicDer:c}=await this.verifyOpening(t,n,await kn($)),l=await this.recoverFileFrame(t,n,o,d);s=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=di(s),t.signal?.throwIfAborted(),await t.save(i,{leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt}),t.signal?.throwIfAborted()}catch(o){try{await this.fileApi.releaseInboxMessage(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId)}catch{}throw o}finally{s?.fill(0)}let a=await this.ack(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId,t.signal);return t.signal?.throwIfAborted(),{name:i.name,mimeType:i.mimeType,size:i.bytes.length,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:a}}async fileManifest(t,n,i){let s=Date.parse(t.expiresAt);if(!Number.isSafeInteger(s)||s<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:t.identity.tenantId,conversationId:t.conversationId,messageId:n.messageId,senderId:t.identity.memberId,senderDeviceId:i.deviceId,senderSigningKeyFingerprint:C(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:C(a.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await kn($)}}async recoverFileFrame(t,n,i,s){let a=await mi(I(n.tenantWrappedShareKey),C(t.tenantKeyHex),s,i.tenantId,i.messageId,$),o=[],d=[],c=new Set;for(let p=0;p<n.shares.length;p++){t.signal?.throwIfAborted();let m=n.shares[p],y=`${m.kind}:${m.index}`;if(c.has(y))throw new Error("duplicate_inbox_share");c.add(y);let b=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,m.shareId,t.identity.deviceId,n.leaseId,t.signal),g=await ci(b,a,s,i.messageId,m.kind==="DATA"?"data":"key",m.index,$);(m.kind==="DATA"?o:d).push(g),t.onProgress?.(p+1,n.shares.length,"DOWNLOADING")}if(o.length!==d.length||o.length<2)throw new Error("incomplete_inbox_shares");t.signal?.throwIfAborted();let l=await this.worker.reconstruct(o,d,{threshold:o.length,total:o.length,messageId:i.messageId,manifestDigest:s},t.signal,p=>t.onProgress?.(n.shares.length,n.shares.length,p.stage));return t.signal?.throwIfAborted(),oi(l)}};import{createHash as Kn,webcrypto as Ii}from"node:crypto";import{canonicalInboxParentManifest as hi,decodeInboxParentManifest as yi,encodeInboxParentNormalFrame as fi,decodeInboxParentNormalFrame as Pi,sealInboxParentNormalBody as vi,openInboxParentNormalBody as bi,wrapInboxParentNormalKey as wi,unwrapInboxParentNormalKey as Ei,signInboxParentNormalFrame as Si,verifyInboxParentNormalFrame as Nn,encodeInboxText as Ri,decodeInboxText as xi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var V=Ii,De=r=>Kn("sha256").update(r).digest("hex"),ot=r=>Buffer.from(r).toString("base64"),dt=class{constructor(e){this.api=e}pending=new Map;async send(e){let t=this.digestInput(e),n=e.parentId?this.pending.get(e.parentId):void 0;if(n){if(n.inputDigest!==t)throw new Error("inbox_idempotency_conflict");let c=await this.api.publishNormalInboxMessage(e.conversationId,n.submission);return this.pending.delete(e.parentId),c}let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validatePreparation(e,i),a=this.createManifest(e,i,s),o=await this.createSubmission(e,i,s,a);this.rememberSubmission(a.parentId,t,o);let d=await this.api.publishNormalInboxMessage(e.conversationId,o);return this.pending.delete(a.parentId),d}digestInput(e){return Kn("sha256").update(JSON.stringify([e.conversationId,e.parentId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.text])).digest("hex")}validatePreparation(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||De(I(n.signingPublicKey))!==n.signingKeyFingerprint||De(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}createManifest(e,t,n){return{mode:"NORMAL",tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:e.parentId??t.parentId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:C(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let s=hi(i),{contentKey:a,frame:o}=await vi(Ri(e.text),i,V),d=await V.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await Si(i,o,d,V),l=await V.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Nn(i,o,c,l,V))throw new Error("inbox_identity_mismatch");let p=await Promise.all(t.recipients.map(m=>this.wrapRecipientKey(m,a,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:ot(s),frame:ot(fi(o)),signature:ot(c),recipients:p}}async wrapRecipientKey(e,t,n){let i=I(e.encryptionPublicKey);if(De(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await V.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:e.memberId,deviceId:e.deviceId,deviceVersion:e.deviceVersion,keyFingerprint:e.encryptionKeyFingerprint,wrappedContentKey:ot(await wi(t,s,n,V))}}rememberSubmission(e,t,n){if(this.pending.size>=32){let i=this.pending.keys().next().value;i&&this.pending.delete(i)}this.pending.set(e,{inputDigest:t,submission:n})}list(e,t,n){return this.api.listNormalInboxMessages(e,t,n)}async open(e){e.signal?.throwIfAborted();let t=await this.api.openNormalInboxMessage(e.conversationId,e.parentId,e.identity.deviceId,e.signal),n=yi(I(t.canonicalManifest));if(n.mode!=="NORMAL"||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch");let i=n.recipients.find(p=>p.memberId===e.identity.memberId&&p.deviceId===e.identity.deviceId);if(!i||!G(i.encryptionKeyFingerprint,C(De(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=I(t.senderSigningPublicKey);if(!G(n.senderSigningKeyFingerprint,C(De(s))))throw new Error("inbox_sender_key_mismatch");let a=Pi(I(t.frame)),o=await V.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Nn(n,a,I(t.signature),o,V))throw new Error("inbox_signature_invalid");let d=await V.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Ei(I(t.wrappedContentKey),d,n,V),l=xi(await bi(a,c,n,V));return e.signal?.throwIfAborted(),{text:l,parentId:t.parentId,sequence:t.sequence}}markRead(e){return this.api.markNormalInboxMessageRead(e.conversationId,e.parentId,e.identity.deviceId)}};import{createHash as Fn,webcrypto as Ai}from"node:crypto";import{canonicalInboxParentManifest as _i,decodeInboxParentManifest as Ci,decodeInboxManifest as Ti,encodeInboxParentNormalFrame as Di,decodeInboxParentNormalFrame as Mi,sealInboxParentNormalBody as Oi,openInboxParentNormalBody as ki,wrapInboxParentNormalKey as Ni,unwrapInboxParentNormalKey as Ki,signInboxParentNormalFrame as Ui,verifyInboxParentNormalFrame as Un,signInboxProtectedParent as Li,verifyInboxProtectedParent as Ln,inboxProtectedUnitCommitment as Fi,encodeInboxText as qi,decodeInboxText as Gi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var K=Ai,ct=r=>Buffer.from(r).toString("base64"),Me=r=>Fn("sha256").update(r).digest("hex"),lt=class{constructor(e,t){this.api=e;this.child=t??new re(e)}pending=new Map;child;async send(e){let t=Fn("sha256").update(JSON.stringify([e.conversationId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.segments])).digest("hex"),n=e.parentId?[e.parentId,this.pending.get(e.parentId)]:[...this.pending.entries()].find(([,o])=>o.digest===t),i=n?.[1];if(i){if(i.digest!==t)throw new Error("inbox_idempotency_conflict");try{e.onProgress?.(i.submission.protectedUnits.length,i.submission.protectedUnits.length)}catch{}let o=await this.api.publishInboxParent(e.conversationId,i.submission);return this.pending.delete(n[0]),o}let s=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(s.parentId,{digest:t,submission:s});let a=await this.api.publishInboxParent(e.conversationId,s);return this.pending.delete(s.parentId),a}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let t=e.segments.filter(y=>"protectedText"in y).length;if(t<1||t>4)throw new Error("invalid_inbox_parent_segments");let n=e.segments.length===1&&t===1?"PROTECTED":"MIXED";if(n==="MIXED"&&!e.segments.some(y=>"text"in y))throw new Error("invalid_inbox_parent_segments");let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validateSender(e,i),a=e.parentId??i.parentId,{protectedUnits:o,manifestUnits:d}=await this.prepareChildren(e,i,s),c=this.parentManifest(e,i,s,a,n,d),{frame:l,signature:p,recipients:m}=await this.signAndWrap(e,i,s,c);return{parentId:a,idempotencyKey:a,senderDeviceId:s.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:ct(_i(c)),signature:ct(p),frame:l,recipients:m,protectedUnits:o}}async prepareChildren(e,t,n){let i=[],s=[],a=e.segments.filter(o=>"protectedText"in o).length;for(let o=0;o<e.segments.length;o++){let d=e.segments[o];if(!("protectedText"in d))continue;let c=await this.child.prepare({conversationId:e.conversationId,text:d.protectedText,expiresAt:d.expiresAt,identity:e.identity,tenantKeyHex:e.tenantKeyHex}),l=Ti(I(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let p=await Fi(l,I(c.frame),I(c.submission.signature),K);i.push({position:o,frame:c.frame,child:c.submission}),s.push({unitId:c.submission.messageId,position:o,commitment:p});try{e.onProgress?.(i.length,a)}catch{}}return{protectedUnits:i,manifestUnits:s}}validateChildSnapshot(e,t,n,i){if(e.tenantId!==t.identity.tenantId||e.conversationId!==t.conversationId||e.senderId!==t.identity.memberId||e.senderDeviceId!==i.deviceId||e.participantRevision!==n.participantRevision||e.recipients.length!==n.recipients.length||e.recipients.some(s=>!n.recipients.some(a=>a.memberId===s.memberId&&a.deviceId===s.deviceId&&G(s.encryptionKeyFingerprint,C(a.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,t,n,i,s,a){return{mode:s,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:i,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:C(o.encryptionKeyFingerprint)})),protectedUnits:a}}async signAndWrap(e,t,n,i){let s=await K.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),a=await K.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(i.mode==="PROTECTED")return{signature:await this.signProtectedParent(i,s,a),recipients:this.recipientReferences(t)};let{frame:o,signature:d,contentKey:c}=await this.sealMixedParent(e,i,s,a);return{frame:o,signature:d,recipients:await this.wrapRecipients(t,c,i)}}async signProtectedParent(e,t,n){let i=await Li(e,t,K);if(!await Ln(e,i,n,K))throw new Error("inbox_identity_mismatch");return i}async sealMixedParent(e,t,n,i){let s=e.segments.map((d,c)=>"text"in d?{text:d.text}:{unitId:t.protectedUnits.find(l=>l.position===c).unitId}),a=await Oi(qi(JSON.stringify(s)),t,K),o=await Ui(t,a.frame,n,K);if(!await Un(t,a.frame,o,i,K))throw new Error("inbox_identity_mismatch");return{frame:ct(Di(a.frame)),signature:o,contentKey:a.contentKey}}recipientReferences(e){return e.recipients.map(t=>({memberId:t.memberId,deviceId:t.deviceId,deviceVersion:t.deviceVersion,keyFingerprint:t.encryptionKeyFingerprint}))}async wrapRecipients(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=I(i.encryptionPublicKey);if(Me(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await K.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:ct(await Ni(t,a,n,K))}}))}validateSender(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Me(I(n.signingPublicKey))!==n.signingKeyFingerprint||Me(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}list(e,t,n){return this.api.listInboxParents(e,t,n)}clearHistory(e,t){return this.api.clearInboxHistory(e,t)}async open(e){let{opened:t,manifest:n,segments:i}=await this.openAndVerify(e);return{parentId:t.parentId,sequence:t.sequence,mode:n.mode,segments:i}}async openAndVerify(e){e.signal?.throwIfAborted();let t=await this.api.openInboxParent(e.conversationId,e.parentId,e.identity.deviceId,e.signal),{manifest:n,senderKey:i}=await this.verifyOpening(e,t),s=n.mode==="PROTECTED"?await this.openProtectedParent(t,n,i):await this.openMixedParent(e,t,n,i);return e.signal?.throwIfAborted(),{opened:t,manifest:n,segments:s}}async verifyOpening(e,t){let n=Ci(I(t.canonicalManifest));return this.verifyManifestContext(e,t,n),this.verifyManifestUnits(t,n),this.verifyRecipient(e,n),{manifest:n,senderKey:await this.senderKey(t,n)}}verifyManifestContext(e,t,n){if(n.mode!==t.mode||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch")}verifyManifestUnits(e,t){if(t.protectedUnits.length!==e.protectedUnits.length||t.protectedUnits.some((n,i)=>n.unitId!==e.protectedUnits[i].unitId||n.position!==e.protectedUnits[i].position||!G(n.commitment,C(e.protectedUnits[i].commitment))))throw new Error("inbox_manifest_mismatch")}verifyRecipient(e,t){let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||!G(n.encryptionKeyFingerprint,C(Me(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,t){let n=I(e.senderSigningPublicKey);if(Me(n)!==e.senderSigningKeyFingerprint||!G(t.senderSigningKeyFingerprint,C(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return K.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await Ln(t,I(e.signature),n,K))throw new Error("inbox_signature_invalid");return[{unitId:t.protectedUnits[0].unitId,position:0,status:e.protectedUnits[0].status}]}async openMixedParent(e,t,n,i){if(!t.frame||!t.wrappedContentKey)throw new Error("inbox_missing_normal_body");let s=Mi(I(t.frame));if(!await Un(n,s,I(t.signature),i,K))throw new Error("inbox_signature_invalid");let a=await K.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await Ki(I(t.wrappedContentKey),a,n,K),d=JSON.parse(Gi(await ki(s,o,n,K)));return this.decodeSegments(d,t,n)}decodeSegments(e,t,n){if(!Array.isArray(e))throw new Error("invalid_inbox_parent_body");let i=e.map((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error("invalid_inbox_parent_body");let o=s;if(typeof o.text=="string"&&Object.keys(o).length===1)return{text:o.text};let d=n.protectedUnits.find(c=>c.position===a);if(!d||o.unitId!==d.unitId||Object.keys(o).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:d.unitId,position:a,status:t.protectedUnits.find(c=>c.unitId===d.unitId).status}});if(n.protectedUnits.some(s=>!i[s.position]||!("unitId"in i[s.position])))throw new Error("invalid_inbox_parent_body");return i}async revealUnit(e){let{manifest:t,segments:n}=await this.openAndVerify(e);if(!n.some(s=>"unitId"in s&&s.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let i=t.protectedUnits.find(s=>s.unitId===e.unitId);return this.child.openCommitted({conversationId:e.conversationId,messageId:e.unitId,identity:e.identity,tenantKeyHex:e.tenantKeyHex,signal:e.signal},i.commitment)}};export{ue as BusinessOrganizationSelectionError,xe as CorePlanMaterialBuilder,Io as DataAssetDefinitionService,q as ElementsApiRequestFailed,ae as ElementsClient,ve as GuidedCreateRecoveryError,Pe as GuidedPlanCreator,Ee as HttpAutomationRevealApiPort,ce as HttpElementsApiPort,Rn as HttpOperatorAuthTransport,je as HttpPlanEditPort,Se as HttpQuickPlanPort,Nr as InheritiFileInvalid,w as InvalidPlanDeclaration,N as InvalidPlanMaterial,Mt as MAX_INHERITI_FILE_BYTES,Ne as MasterKeyRelayCancellationFailed,ke as MasterKeyRelayExpired,Oe as MasterKeyRelayTimedOut,j as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,he as MemoryKeyVault,ye as MemoryStatePort,at as NodeInboxFile,dt as NodeInboxNormal,lt as NodeInboxParent,re as NodeInboxText,S as OAuthProtocolError,An as OperatorAuthClient,_e as OperatorAuthError,Ce as OperatorReauthenticationRequired,_n as OperatorSessionController,It as PLAN_CREATION_SERVER_STAGES,bo as PassphraseMasterKeySource,Ao as PlanAssetDeclaration,te as PlanRequestFailed,Ae as QuickPlanCreator,Je as QuickPlanEditor,wo as RawMasterKeySource,z as RelayMasterKeySource,ut as StaticMasterKeyResolver,rt as SystemOAuthClock,nt as WebOAuthCrypto,Ro as computePassphraseVerifier,Ke as createMasterKeyResolver,kr as createNodeAutomationRevealClient,Xa as createNodeElementsClient,Ja as createNodeQuickPlanCreator,Za as createNodeQuickPlanEditor,Fr as decodeAssetContainer,Eo as deriveMasterKey,Kr as exportProtectedRevealAsset,So as generateHexSeed,Ze as generateInheritiFileKey,Cn as inspectInheritiFileAccess,Ie as masterKeyRefFor,J as masterKeyRefKey,kt as oauthErrorCode,Dt as openInheritiFile,Vr as openInheritiFileAccess,Ot as openInheritiFileKey,Tt as readInheritiFileHeader,et as sealInheritiFile,tt as sealInheritiFileKey,fr as selectBusinessOrganization,St as unwrapDekWithMasterKey,Z as validatePlanCreationInput,se as validatePlanCreationMaterial};
1
+ import{createNodeSharedConfigurationSdk as Kt,decodeAssetContainer as Fr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as qn,generateRSAOAEPKeyPair as Gn}from"@safetech/inheriti-core-sdk/crypto";var Oe=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ke=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},Ne=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},z=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await Gn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(g=>new Promise(f=>setTimeout(f,g))),c=!0,l=!1,p,m=()=>p??=(async()=>{let g=new AbortController,f,T=new Promise((x,k)=>{f=setTimeout(()=>{g.abort(),k(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,g.signal),T])}finally{clearTimeout(f)}})(),y,b=new Promise((g,f)=>{y=()=>{c&&m().catch(()=>{}),f(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",y,{once:!0})});b.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let g=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),b]);if(g.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(g.status==="DELIVERED"&&g.sealedMasterKey){let f=(await qn(g.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(f))throw new Error("invalid_master_key_material");return f}if(g.status==="EXPIRED")throw new ke(s.sessionId);await Vn(d,a,e)}throw new Oe(s.sessionId)}catch(g){if(c&&(!l||e?.aborted))try{await m()}catch(f){if(e?.aborted)throw new Ne(f)}throw g}finally{y&&e?.removeEventListener("abort",y)}}};async function Vn(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function Ke(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||ut(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(zn(e,r.applicationId)){let i=await r.source?.resolve();return i||ut(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return ut(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function zn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ut(r,e,t,n,i){if((await e()).relayAvailable)return new z({...r.relay,api:Bn(r.api,t)}).resolve(n,i)}function Bn(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function J(r){return`${r.system}:${r.contextId}`}function Ie(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var j=class extends Error{constructor(t){super(`master_key_required:${J(t)}`);this.ref=t;this.name="MasterKeyRequired"}},mt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(J(e),t),this}async resolve(e){return this.sources.get(J(e))?.resolve()}};var he=class{keys=new Map;async store(e,t){let n=J(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(J(e))?.slice()}async remove(e){let t=J(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ye=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 Ue=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},P=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Le=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var Fe=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],It={"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"]},ht=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],w=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},N=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function se(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new N("plan_material_field_unknown");if(gt(r.dataShards,"data_shards_invalid"),gt(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&gt(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new N("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new N("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new N("material_operation_invalid")}function gt(r,e){if(!Array.isArray(r))throw new N(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new N(e);if(t.data!==void 0&&typeof t.data!="string")throw new N(e)}}function Z(r){if(ie(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Wn(r.idempotencyKey))throw new w("idempotency_key_invalid");if(!r.name?.trim())throw new w("plan_name_required");if(!r.assets.length)throw new w("assets_required");let e=new Set;for(let t of r.assets){if(ie(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 w("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!Fe.includes(t.type))throw new w("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new w("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 w("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new w("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new w("asset_field_names_invalid");if($n(t.matchOrigins),!t.isBinary){let s=It[t.type];if(!s||i.some(a=>!s.includes(a)))throw new w("asset_field_name_not_canonical")}}if(!r.participants.length)throw new w("participants_required");for(let t of r.participants){if(ie(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Ft(t.routingEmail))throw new w("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new w("participant_relationships_invalid")}Hn(r)}function $n(r){if(r===void 0)return;if(!r.length)throw new w("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new w("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new w("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof w?n:new w("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new w("asset_match_origins_duplicated")}function Hn(r){let e=r.policy;if(e&&ie(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new w("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){ie(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new w("authentication_mode_invalid")}if(e.moderation){ie(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new w("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new w("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new w("approval_mode_invalid")}let t=e.dms;if(!t)return;ie(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Ft(t.subjectEmail))throw new w("dms_subject_invalid");if(!r.participants.some(s=>Lt(s.routingEmail)===Lt(t.subjectEmail)))throw new w("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new w("dms_countdown_invalid")}function Wn(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Ft(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Lt(r){return r.normalize("NFC").trim().toLowerCase()}function ie(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new w(t)}var fe=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},Pe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),Z(e),qe(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,s={}){Z(t);let a=await this.checkpoints.load(e);if(!a)throw new ve("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await qt(t))throw new ve("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.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;qe(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});qe(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});qe(s.signal),se(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(l.stage),l.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,l),l}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 qt(e),serverStage:t.stage})}},ve=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function qt(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function qe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Gt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Ue(n.stage);return r.authorizeRevealAction(e,t)}function Qn(r){let e=r?.status;return e===400||e===401||e===403}async function Vt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Qn(s))throw s}return r.releaseRevealMaterial(e,t)}function jn(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?Xn(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Yn.has(r.stage)?"ENDED":"CONTINUING"}var Yn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Xn(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var yt=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function ze(r,e,t={},n=!1){if(t.signal?.aborted)throw R();let i=await r.getPlan(e),s=await r.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):zt(s.id);if(t.signal?.aborted)throw R();let a=()=>r.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)});if(n||await a(),t.signal?.aborted)throw R();let o=t.idempotencyKey??crypto.randomUUID(),d;try{d=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:o,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let p=await r.getActivePlanReveal(e);throw!p||p.planId!==e||p.mode!==(t.mode??"DIRECT")||p.protectedCopy!==void 0&&p.protectedCopy!==(t.protectedCopy??!1)?l:zt(p.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let c;try{if(t.signal?.aborted)throw R();let l=await Zn(r,d,t);if(t.signal?.aborted||(n&&await a(),t.signal?.aborted)||(ee(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw R();let p=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id),t.signal?.aborted))throw R();let m;try{m=await rr(r,l,sr(p),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(ee(t,"RECONSTRUCTING",l),t.signal?.aborted))throw R();try{c=await r.reconstructPlanMaterial(m)}catch(b){throw t.signal?.aborted?R():(await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:nr(b)}),b)}if(t.signal?.aborted)throw R();let y=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(ee(t,"OPEN",y),t.signal?.aborted))throw R();return new Pt(r,y,i,c,t.signal)}catch(l){throw c?.fill(0),await Ht(r,d.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function zt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Jn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Zn(r,e,t){let n=await Y(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw R();if(t.onSession?.(n),t.onProgress?.({phase:jn(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Jn.has(n.stage))throw new ft(n.stage);await vt(t.pollIntervalMs??1500,t.signal),n=await Y(()=>r.getReveal(e.id,t.signal),t.signal)}}var ft=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function ee(r,e,t){r.onProgress?.({phase:e,session:t})}function vt(r,e){return e?.aborted?Promise.reject(R()):new Promise((t,n)=>{let i=setTimeout(a,Math.max(0,r)),s=()=>{clearTimeout(i),n(R())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Pt=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new yt;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=e.map(({selector:s,options:a={}})=>{let o=er(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new M("asset_not_found");if(d.isBinary)throw new M("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new M("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),i=[];try{for(let a of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:a.options.idempotencyKey??crypto.randomUUID(),assetId:a.asset.id,fieldName:a.field,action:a.options.action??"VIEW_FIELD",...a.options.destination===void 0?{}:{destination:a.options.destination},...a.options.origin===void 0?{}:{origin:a.options.origin}}));let s=n.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new M("asset_value_invalid");return{selector:a.selector,value:tr(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",Bt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=this.plan.assets.find(a=>a.code===e||a.id===e);if(!n)throw new M("asset_not_found");if(!n.isBinary)throw new M("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!a||!(a.data instanceof Uint8Array))throw new M("asset_value_invalid");s=a.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",Bt(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Ht(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 er(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new M("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new M("asset_selector_invalid");return{asset:r.asset,field:r.field}}function tr(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new M("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new M("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?It[t]:void 0)?.includes(e))return"";throw new M("asset_value_invalid")}return n[e]}function Bt(r){if(r instanceof M)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function nr(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function rr(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await Y(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Ge;let c=await Y(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if($t(c,i.id,e.planId),!c.shares.includes(i.data))throw new W;ee(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await Y(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw R();if(!l?.trim())throw new W;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw R();return{...t,shares:t.shares.filter(p=>p!==i).concat(c.shares.map((p,m)=>({id:`${c.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:p})))}}if(d!=="SK_MOBILE")throw new W;if(n.signal?.aborted)throw R();return await r.distributeRevealCustodianShare(e.id),ee(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),ee(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await vt(n.pollIntervalMs??1500,n.signal),s=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Ge;if(!s.shareId||!s.deviceId)throw new W;ee(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Y(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw R();if($t(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new W;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw R();return{...t,shares:t.shares.concat(d.shares.map((c,l)=>({id:`${d.id}:${l}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new W;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(a),ee(n,"WAITING_FOR_CUSTODIAN",a),n.signal?.aborted)throw R();await r.requestRevealCustodianRelease(e.id);let o=await ir(r,e,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function $t(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new W}async function Y(r,e){if(e?.aborted)throw R();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(R()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw R();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function ir(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Ve;let s=await Y(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Ve;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new W}await vt(t.pollIntervalMs??1500,t.signal)}}var W=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Ge=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ve=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function sr(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function Ht(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(a){if(!ar(a))throw a}return}let n=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(a.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(a){if(a?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:a}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function ar(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function R(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var ae=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 he,this.state=t.state??new ye,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??cr(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new P;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new P;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new P;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new P;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return Z(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new P;return se(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new P;return new Pe(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new j({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return dr(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new j(e);return await this.keyVault.store(e,or(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new P;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new P;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Le;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new j({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=Ie(e);if(!i)throw new j({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new P;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new P;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new P;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new P;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new P;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new P;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new P;return this.api.getReveal(e,t)}openReveal(e,t){return ze(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new P;return Vt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new P;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new P;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new P;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new P;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new P;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new P;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new P;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new P;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new P;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new P;return Gt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new P;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new P;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new P;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new P;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new P;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new P;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new P;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new bt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new j({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},bt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function or(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function dr(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function cr(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return Ke({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Ke({...e,organizationId:r.organizationId})}var lr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],pr=["DIRECT","GOVERNED"],Qt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],ur=["ACTIVE","REVOKED"],mr=["SK_MOBILE"],gr=["ACTIVE","INACTIVE"],Ir=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function jt(r){let e=O(r);return{items:F(e.items).map(Jt),nextCursor:e.nextCursor===null?null:h(e.nextCursor,"nextCursor")}}function Yt(r){let e=O(r);return{total:B(e.total,"total"),items:F(e.items).map(t=>{let n=O(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:h(n.id,"log.id"),planId:h(n.planId,"log.planId"),tenantId:h(n.tenantId,"log.tenantId"),event:h(n.event,"log.event"),occurredOn:h(n.occurredOn,"log.occurredOn"),status:X(n.status),title:h(n.title,"log.title"),details:F(n.details).map(i=>{let s=O(i);return{label:h(s.label,"log.detail.label"),value:h(s.value,"log.detail.value")}})}})}}function Xt(r){let e=O(r);return{total:B(e.total,"total"),items:F(e.items).map(t=>{let n=O(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=h(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:h(n.id,"log.id"),memberId:h(n.memberId,"log.memberId"),source:i,event:h(n.event,"log.event"),occurredOn:h(n.occurredOn,"log.occurredOn"),status:X(n.status)}})}}function Be(r){let e=O(r),t=Jt(e),n=O(e.source),i=h(n.kind,"source.kind");return{...t,assets:F(e.assets).map(s=>{let a=O(s);return{id:h(a.id,"asset.id"),code:X(a.code),type:L(h(a.type,"asset.type"),Fe),name:h(a.name,"asset.name"),isBinary:yr(a.isBinary,"asset.isBinary"),fieldNames:F(a.fieldNames).map(o=>h(o,"asset.fieldNames")),fileName:X(a.fileName),mimeType:X(a.mimeType),size:a.size===void 0||a.size===null?void 0:B(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:F(a.matchOrigins).map(o=>h(o,"asset.matchOrigins"))}}),participants:F(e.participants).map(s=>{let a=O(s);return{id:h(a.id,"participant.id"),displayName:h(a.displayName,"participant.displayName"),relationships:F(a.relationships).map(o=>L(h(o,"relationship"),Qt)),lifecycle:L(h(a.lifecycle,"participant.lifecycle"),ur)}}),revealPolicy:(()=>{let s=O(e.revealPolicy);return{masterKeyRelease:L(h(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:L(h(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=O(e.dms);return{subjectEmail:h(s.subjectEmail,"dms.subjectEmail"),countdownDays:B(s.countdownDays,"dms.countdownDays"),countdownHours:B(s.countdownHours,"dms.countdownHours"),countdownMinutes:B(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:L(h(n.system,"source.system"),["INHERITI_BUSINESS"]),status:L(h(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function be(r){let e=O(r);return{operationId:h(e.operationId,"operationId"),stage:L(h(e.stage,"stage"),ht),outcome:L(h(e.outcome,"outcome"),Ir),planId:X(e.planId),lastErrorCode:X(e.lastErrorCode),participants:e.participants===void 0?void 0:F(e.participants).map(t=>{let n=O(t);return{clientParticipantRef:h(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:h(n.planParticipantId,"planParticipantId"),relationships:F(n.relationships).map(i=>hr(h(i,"relationship"),Qt))}})}}function Jt(r){let e=O(r),t=O(e.assetSummary),n=O(e.governance),i=O(e.participantSummary);return{id:h(e.id,"id"),name:h(e.name,"name"),description:X(e.description),status:L(h(e.status,"status"),lr),createdAt:h(e.createdAt,"createdAt"),configuredAt:X(e.configuredAt),assetSummary:{count:B(t.count,"assetSummary.count"),types:F(t.types).map(s=>L(h(s,"assetType"),Fe)),names:Wt(t.names).map(s=>h(s,"assetSummary.names"))},governance:{mode:L(h(n.mode,"governance.mode"),pr),minimumApprovals:B(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:B(i.owners,"owners"),mergers:B(i.mergers,"mergers"),moderators:B(i.moderators,"moderators")},authentication:Wt(e.authentication).map(s=>{let a=O(s);return{id:L(h(a.id,"authentication.id"),mr),status:L(h(a.status,"authentication.status"),gr)}})}}function L(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function hr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function O(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Wt(r){return r==null?[]:F(r)}function F(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function h(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function X(r){return r==null?void 0:h(r,"optional")}function B(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function yr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var ue=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Zt(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function fr(r,e){if(!e){if(r.length===0)throw new ue("organization_required");if(r.length>1)throw new ue("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new ue("organization_access_denied");return e}function Pr(r){let e=E(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),createdAt:U(e.createdAt),...en(e)}}function en(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=E(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:u(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:U(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=E(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:v(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:U(i.revealedAt)}:{}}})}:{}}})}}function tn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Pr),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0),unreadCount:v(e.unreadCount,0),readThroughSequence:v(e.readThroughSequence,0)}}function nn(r){let e=E(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=E(t);return{unitId:u(n.unitId),position:v(n.position,0),commitment:u(n.commitment),status:u(n.status)}})}}function wt(r){let e=E(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),status:e.status}}function rn(r){let e=E(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),parentId:u(e.parentId),participantRevision:v(e.participantRevision,1),recipients:e.recipients.map(Et)}}function sn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);return{parentId:u(n.parentId),sequence:v(n.sequence,1),senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),participantRevision:v(n.participantRevision,1),createdAt:U(n.createdAt),...en(n)}}),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0),unreadCount:v(e.unreadCount,0),readThroughSequence:v(e.readThroughSequence,0)}}function an(r){return{readThroughSequence:v(E(r).readThroughSequence,0)}}function on(r){return{clearedThroughSequence:v(E(r).clearedThroughSequence,0)}}function dn(r){let e=E(r);return{parentId:u(e.parentId),sequence:v(e.sequence,1),senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),canonicalManifest:u(e.canonicalManifest),frame:u(e.frame),signature:u(e.signature),wrappedContentKey:u(e.wrappedContentKey),senderSigningPublicKey:u(e.senderSigningPublicKey)}}function E(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function u(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function U(r){let e=u(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function v(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Et(r){let e=E(r);return{memberId:u(e.memberId),deviceId:u(e.deviceId),deviceVersion:v(e.deviceVersion,1),encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint)}}function me(r){let e=E(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:u(e.id),tenantId:u(e.tenantId),memberId:u(e.memberId),version:e.version,encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint),status:e.status,createdAt:U(e.createdAt),updatedAt:U(e.updatedAt)}}function $e(r){let e=E(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:u(e.id),tenantId:u(e.tenantId),creatorMemberId:u(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(u),participantRevision:e.participantRevision,status:e.status,createdAt:U(e.createdAt),updatedAt:U(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=E(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:u(n.senderMemberId),createdAt:U(n.createdAt)}}return t}function cn(r){let e=E(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map($e),total:e.total,limit:e.limit,offset:e.offset}}function ln(r){let e=E(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Et(t);return{memberId:n.memberId,name:u(E(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:v(e.limit,1),offset:v(e.offset,0),nextOffset:e.nextOffset===null?null:v(e.nextOffset,0)}}function pn(r){let e=E(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:u(n.memberId),name:u(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:u(E(n.profilePicture).url)}}}}),limit:v(e.limit,1),offset:v(e.offset,0),nextOffset:e.nextOffset===null?null:v(e.nextOffset,0)}}function un(r){let e=E(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),messageId:u(e.messageId),participantRevision:v(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Et),shareLayers:e.shareLayers.map(t=>{let n=E(t),i=u(n.id),s=u(n.dataShareId),a=u(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:u(n.contractAddress),dataShareId:s,keyShareId:a};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function He(r){let e=E(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:u(e.messageId),status:e.status}}function mn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:u(n.id),status:n.status,senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),createdAt:U(n.createdAt),updatedAt:U(n.updatedAt),expiresAt:U(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let a=E(s);if(a.status!=="UNREAD"&&a.status!=="LEASED"&&a.status!=="CONSUMED"&&a.status!=="EXPIRED"&&a.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:u(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:U(a.consumedAt)}:{}}})),i}),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0)}}function gn(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:U(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:v(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId),ciphertext:u(n.ciphertext)}})}}function In(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:U(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:v(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId)}})}}function oe(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function de(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var q=class extends Error{constructor(t,n,i,s){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ce=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,n,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":n},i)}confirmFileAccessDelivery(e,t,n){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":n})}createInboxFileAccess(e,t,n,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",n,void 0,void 0,i)}createRevealFileAccess(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,n)}cancelRevealFileAccess(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",n)}cancelInboxFileAccess(e,t,n,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let n=t;if(typeof n.publicKey!="string"||!n.publicKey||typeof n.fingerprint!="string"||!n.fingerprint||n.status!=="ACTIVE"&&n.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:n.publicKey,fingerprint:n.fingerprint,status:n.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:me(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:me(n)}async registerInboxDevice(e){return me(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return me(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return me(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return $e(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return $e(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return cn(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return ln(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return pn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return un(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return He(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return tn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return nn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return on(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return sn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return dn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return an(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return He(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let a=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(a,"PUT",i,s),d=await We(o,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new q(o.status,oe(d),de(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return He(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return In(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,c=await this.requestBinary(d,"GET",void 0,a);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let l=Number(c.headers.get("content-length"));if(Number.isFinite(l)&&l>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let p=c.body.getReader(),m=[],y=0;try{for(;;){a?.throwIfAborted();let f=await p.read();if(f.done)break;if(y+=f.value.length,y>14*1024*1024)throw new Error("invalid_inbox_share_size");m.push(f.value)}}catch(f){throw await p.cancel().catch(()=>{}),f}let b=new Uint8Array(y),g=0;for(let f of m)b.set(f,g),g+=f.length;return b}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return mn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return gn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Zt)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return jt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Be(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Yt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let n=new URLSearchParams;t.source&&n.set("source",t.source),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Xt(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){Z(e);let{idempotencyKey:t,...n}=e;return be(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return se(t),be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,s,a){this.requireBusinessSelection(e),a?.throwIfAborted();let o=await this.getBearerToken();a?.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[y,b]of Object.entries(s??{}))d.set(y,b);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:n?JSON.stringify(n):void 0};a&&(l.signal=a);let p=await this.transport(new URL(e,c),l);a?.throwIfAborted();let m=await We(p,a);if(a?.throwIfAborted(),!p.ok)throw new q(p.status,oe(m),de(m),p.headers.get("x-request-id")??void 0);if(!m.ok||m.result===void 0)throw new q(p.status,oe(m),de(m),p.headers.get("x-request-id")??void 0);return m.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let a=new Headers({"x-elements-environment":this.environment});s&&a.set("authorization",`Bearer ${s}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),n&&a.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:a,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await We(d,i);throw new q(d.status,oe(c),de(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let a=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});a&&o.set("authorization",`Bearer ${a}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId);for(let[p,m]of Object.entries(n??{}))o.set(p,m);t&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:o,body:t?JSON.stringify(t):void 0,signal:s}),l=await We(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new q(c.status,oe(l),de(l),c.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new q(400,"organization_selection_required")}};async function We(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Ar}from"@safetech/inheriti-core-sdk/node";async function St(r,e){if(!e)throw new Error("master_key_required");let t=vr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=br(r),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,a);return wr(new Uint8Array(o))}function vr(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function br(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function wr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var we=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await hn("plan_key_unwrap_failed",()=>St(e.planKey,t)),i=await crypto.subtle.importKey("raw",Rt(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await hn("plan_share_decryption_failed",()=>xr(o.data,i));Rr(o.shareType)?a.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new Qe("plan_share_reconstruction_failed",Sr(o))}}},Qe=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},Er=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 Sr(r){let e=r instanceof Error?r.message:void 0;if(e)return Er.has(e)?e:void 0}async function hn(r,e){try{return await e()}catch{throw new Qe(r)}}function Rr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function xr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Rt(r.slice(0,t)),i=Rt(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function Rt(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var le=class extends we{constructor(e){super(()=>Ar(e))}};var Ee=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Be(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,s,a){a?.throwIfAborted();let o=await this.getAutomationBearerToken();if(a?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...s});n!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:a});a?.throwIfAborted();let l;try{l=await c.json()}catch{a?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new q(c.status,l&&oe(l),l&&de(l));return l?.result}};var _={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 te=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},Se=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;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,n,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:n.validatorShares,encryptedKey:n.encryptedKey})}preflight(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",yn(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",yn(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(_.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(_.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(_.relayFailed);return n}async request(e,t,n,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(_.reauthenticationRequired);s.set("authorization",`Bearer ${a}`),i!==void 0&&s.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,c=await this.transport(new URL(d,o),{method:n,headers:s,body:i===void 0?void 0:JSON.stringify(i)}),l={};try{l=await c.json()}catch{}if(!c.ok||l.ok!==!0)throw new te(c.status,l.error);return l.result}};function yn(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var xe=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){Re(e.signal),Cr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return Re(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){Re(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(Re(e.signal),!i.custodianPair)throw new N("custodian_share_required");let s=xt(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(xt(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(xt(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return Re(e.signal),{protectionProtocol:i.protocol,validatorShares:At(a.encryptedShares),dataShards:At(o.encryptedShares),backupShards:At(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:_r(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:_t(n.encryptedShares[0]),dataShard:_t(n.encryptedShares[1])}}};function xt(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function At(r){return r.map(_t)}function _t(r){return{id:r.id,data:r.encryptedData}}function _r(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new N("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function Cr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new N("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new N("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new N("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new N("plan_secrets_declaration_mismatch")}}function Re(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function fn(r,e,t,n,i,s,a){let o=n.mergeThreshold-(n.withCustodian?1:0);if(typeof n.withCustodian!="boolean"||!Number.isInteger(n.mergeThreshold)||o<1||o>r.totalShares)throw new Error(_.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new z({api:{startRelaySession:y=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,y),readRelaySession:y=>i.readRelaySession(r.organizationId,y)}}),p=new xe(s,l);a?.("encrypting");let m=await p.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return a?.("generating_shares"),p.generateShares({planId:r.planId,declaration:c,encrypted:m})}import{PlanAssetDeclaration as Tr}from"@safetech/inheriti-core-sdk/node";function Pn(r){let e=Ct({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function Ct(r){if(!r.assets.length)throw new w("assets_required");let e=r.assets.map(s=>{if(s.meta.isMedia!==!0)return;let a="data"in s.secret?s.secret.data:void 0,o;if(a instanceof Blob&&(o=a.size),typeof a=="string")try{o=atob(a).length}catch{throw new w("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new w("binary_asset_metadata_invalid");return o}),t=Tr.create(r.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),n=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,r.assets[a].secret]))),i={idempotencyKey:r.planId,name:r.title,assets:n.map((s,a)=>{let o=s.meta.isMedia===!0;return{clientAssetRef:s.id,type:s.type,name:s.meta.name,fieldNames:o?[]:Object.keys(s.secret),isBinary:o,fileName:s.meta.fileName,mimeType:s.meta.mimeType,size:e[a]}}),participants:[]};return{assets:n,plan:i}}async function bn(r){let e=await Promise.all(r.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([n],[i])=>n.localeCompare(i)).map(async([n,i])=>[n,i instanceof Blob?await vn(new Uint8Array(await i.arrayBuffer())):i]))})));return vn(new TextEncoder().encode(JSON.stringify({organizationId:r.organizationId,planId:r.planId,title:r.title,description:r.description??null,audience:r.audience??null,totalShares:r.totalShares,assets:e})))}async function vn(r){let e=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ae=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(a=>!a?.meta?.name?.trim()))throw new Error(_.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(_.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(_.invalidShares);let n=await bn(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(_.reconciliationRequired);return i.promise}let s=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let i=Ct({planId:e.planId,title:e.title,assets:e.assets}),s=this.material.get(e.planId);if(s&&(s.fingerprint!==t||s.masterKeySource!==e.masterKeySource))throw new Error(_.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(je(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(_.reconciliationRequired);if(!a&&s)throw new Error(_.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(_.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(_.invalidMasterKeyContext);if(!a){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(a=await this.statusOrMissing(e.organizationId,e.planId),!a)throw l}}a??=await this.port.status(e.organizationId,e.planId);let d=s?.encrypted??await fn(e,i,o,a,this.port,this.coreSdk,n);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),n?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),n?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),n?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!je(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return je(c)&&this.material.delete(e.planId),{planId:e.planId,status:je(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(_.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof te&&n.status===404)return;throw n}}};function je(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var Ye=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}start(e,t,n,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:n},i)}async listEligibleCandidates(e,t,n){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),n&&i.set("namePrefix",n);let s=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(s))throw new Error("invalid_plan_edit_candidates");return s}async context(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(n))throw new Error("invalid_plan_edit_context");return n}async moderatorNames(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!n||typeof n!="object")throw new Error("invalid_plan_edit_participants");let i=n;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let s=new Map;for(let a of i.participants){if(!a||typeof a.id!="string"||!a.id||typeof a.displayName!="string"||!Array.isArray(a.relationships)||!a.relationships.every(o=>typeof o=="string")||typeof a.lifecycle!="string")throw new Error("invalid_plan_edit_participants");a.lifecycle==="ACTIVE"&&a.relationships.includes("MODERATOR")&&s.set(a.id,a.displayName)}return s}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(_.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(_.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(_.relayFailed);return n}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(n))}commit(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(n))}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,n,i,s){let a=await this.getBearerToken();if(!a)throw new Error(_.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${a}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),s&&o.set("idempotency-key",s);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),c=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,l=await this.transport(new URL(c,d),{method:n,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),p={};try{p=await l.json()}catch{}if(!l.ok||p.ok!==!0){let m=Array.isArray(p.validationErrors)?p.validationErrors.join("; "):void 0;throw new te(l.status,m||p.error)}return p.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(n=>!!n&&typeof n.id=="string"&&!!n.id&&typeof n.name=="string"&&n.status==="PROTECTED"&&typeof n.createdAt=="string"&&!!n.assetSummary&&Number.isSafeInteger(n.assetSummary.count)&&n.assetSummary.count>=0&&Array.isArray(n.assetSummary.types)&&n.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(n.assetSummary.names)&&n.assetSummary.names.every(i=>typeof i=="string")&&!!n.governance&&["DIRECT","GOVERNED"].includes(n.governance.mode)&&Number.isSafeInteger(n.governance.minimumApprovals)&&n.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 Xe=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.recoveryStore=n}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 n=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),s=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!s)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let a=this.revealedAssets,o=a?.organizationId===e.organizationId&&a.planId===e.planId&&a.editId===e.editId&&a.expiresAt>Date.now();a&&!o&&(this.revealedAssets=void 0);let d=s.masterKeyEncrypted?e.masterKey??(o?a.masterKey:void 0):void 0;s.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?a.assets:await this.revealAssets(e,d,s.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(l.map(p=>p.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&n===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:s,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),n=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"||!(n>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return n}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new z({api:{startRelaySession:n=>this.port.startRelaySession(e.organizationId,t,n),readRelaySession:n=>this.port.readRelaySession(e.organizationId,n)}}).resolve()}async revealAssets(e,t,n,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=g=>{g!==o&&(o=g,i?.(g))},c=g=>{if(g.processId!==e.editId||g.planId&&g.planId!==e.planId)return;switch(g.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 f=this.approvalError(g);if(f?.startsWith("edit_authentication_")&&d("pending_auth"),f?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!g.moderatorParticipants||g.requiredModeratorApprovals===void 0||!g.approvalProcess)return;let T=g.moderatorParticipants.map(x=>x.memberId??x.userId);T.some(x=>typeof x!="string"||!x)||new Set(T).size!==T.length||i?.(o,{requiredApprovals:g.requiredModeratorApprovals,approvedModerators:g.approvalProcess.approvedModerators,moderators:g.moderatorParticipants.map((x,k)=>{let A=T[k],H=x.flows.filter(ge=>ge.status==="PENDING"&&ge.expiresAt&&Number.isFinite(ge.expiresAt.getTime())).map(ge=>ge.expiresAt.getTime());return{id:A,displayName:a.get(A)||"Moderator",status:x.status,expiresAt:H.length?new Date(Math.min(...H)).toISOString():void 0}})})},l=await s.resume(e.planId,{onViewUpdate:c});if(l?.processId!==e.editId||l.planId&&l.planId!==e.planId)throw new Error("edit_merge_not_ready");c(l),this.assertApprovalOutcome(e.planId,l),l.status!=="READY_TO_REVEAL"&&l.status!=="REVEALED"&&await s.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let p=await s.getView(e.editId);if(p?.processId!==e.editId||p.planId&&p.planId!==e.planId)throw new Error("edit_merge_not_ready");c(p),this.assertApprovalOutcome(e.planId,p);let m=p?.status;if(m!=="READY_TO_REVEAL"&&m!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let y=null,b={onRevealed:g=>{y=g},onViewUpdate:c,onRevealStepUpdate:(g,f)=>{if(f==="IN_PROCESS")switch(g){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(n&&(b.onCustodianShareRequired=async(g,f)=>{switch(f.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 s.distributeCustodianShareViaMobile(f.planId);if(T!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let x=e.proDevice;try{this.assertNotAborted(e.signal);let k=await s.getCustodianShareData(g);this.assertShare(k,f.planId),d("connecting_safekey_pro");let{deviceId:A}=await x.write(k,e.signal);if(this.assertNotAborted(e.signal),!A?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(f.planId,k.id,A,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(g,k.id);return}finally{x.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),!f.shareId||!f.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let x=await T.read({shareId:f.shareId,planId:f.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(x,f.planId,f.shareId),x.deviceId!==f.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:x.shares}}finally{T.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),m==="REVEALED"?await s.resumeReveal(e.editId,b,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},b,t),this.assertNotAborted(e.signal),!y)throw new Error("edit_assets_unavailable");return y}assertApprovalOutcome(e,t){let n=this.approvalError(t);if(n)throw this.clearRevealedAssets(e),new Error(n)}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,n){if(!e||!e.id||e.id!==(n??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 Dr=r=>JSON.stringify(r??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([n],[i])=>n<i?-1:n>i?1:0))),Je=class{constructor(e,t,n,i){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=i}async saveAssets(e,t,n,i,s,a){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,i);a?.("preparing");let c=await o.prepare(d);this.assertNotAborted(e.signal);let l={mergeProcessId:e.editId,protectionProtocol:c.protectionProtocol,validatorShares:this.transportShares(c.validatorShares),dataShards:this.transportShares(c.dataShards),backupShards:this.transportShares(c.backupShards),encryptedKey:c.encryptedKey,assetsMetadata:c.assetsMetadata,custodianPair:c.custodianPair};if(a?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,l),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:s,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,s,l,o,d,a)}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 n=await this.configurationRepository().findByPlanId(e.planId),i=n?.editDistribution??n?.preparedDistribution;if(!t&&(!i||n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let s=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),dataShards:i.dataShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),backupShards:i.backupShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,s))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let a=await this.port.status(e.organizationId,e.editId);return a.id!==e.editId||a.planId!==e.planId||a.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,s),await this.port.commit(e.organizationId,e.planId,s),await this.isCommitted(e,s)?(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 n=await this.configurationRepository().findByPlanId(e.planId);if(n?.editDistribution&&n.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 n=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await n.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await n.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,n,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:s,configuration:a}}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,n,i,s,a){let o,d=c=>{let l;switch(c.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":l="distributing_validators";break;case"SHARES_DISTRIBUTION":l="distributing_data";break;case"FINALIZE":l="finalizing";break;default:return}l!==o&&(o=l,a?.(l))};try{await i.execute(s,{onLocalProcessUpdated:d})}catch(c){try{if(a?.("verifying"),await this.isCommitted(e,n))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&a?.(o),c}try{if(a?.("verifying"),!await this.isCommitted(e,n))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 n=await this.port.commitStatus(e.organizationId,e.editId);if(n.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(n.status)||n.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(Dr(t.assetsMetadata)),s=await globalThis.crypto.subtle.digest("SHA-256",i),a=Array.from(new Uint8Array(s),c=>c.toString(16).padStart(2,"0")).join("");if(n.assetsMetadataHash!==a)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(c=>c.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(n.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var Ze=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new Xe(e,t,n),this.reconfiguration=new Je(e,t,n,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,n,i){return this.port.start(e,t,n,i)}async listAssets(e,t){let{assets:n}=await this.assetAccess.loadAssets(e,t);return n.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,n){let{assets:i}=await this.assetAccess.loadAssets(e,n),s=i.find(a=>a.id===t);if(!s)throw new Error("edit_asset_not_found");return structuredClone(s)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=s.findIndex(l=>l.id===e.assetId);if(a<0)throw new Error("edit_asset_not_found");let o=s[a];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},c=s.map((l,p)=>p===a?d:l);return this.reconfiguration.saveAssets(e,c,n.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=Pn({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(s.map(d=>d.id)).has(a.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,s.concat(a),n.withCustodian,i,a.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 wn({apiUrl:r,organizationId:e,planId:t,editId:n,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),c=new URL(r.endsWith("/")?r:`${r}/`);if(d.origin!==c.origin||!d.pathname.startsWith(c.pathname))throw new Error("unsupported_core_edit_route");let l=d.pathname.slice(c.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(l===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return s(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let p=Mr(l,d.searchParams,t,n),m=new Headers(o?.headers);m.set("x-organization-id",e),m.set("x-elements-environment",i);let y=c.pathname.endsWith("/integrations/")?`v1/${p}`:`integrations/v1/${p}`;return s(new URL(y,c),Object.assign({},o,{headers:m}))}}function Mr(r,e,t,n){if(r==="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 s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){let o=s[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(s[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(n)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as Or}from"@safetech/inheriti-core-sdk/node";function En(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=Ie(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new z({api:{startRelaySession:o=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>r.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>r.api.cancelMasterKeyRelaySession(o,d)}}),a=new ae(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(o,d,c)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,c)}}});return ze(a,e,t,!0)}}}function kr(r){let e=new Ee(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{...En({api:e,reconstructor:new le(r.workerUrl),assetDecoder:Or}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as et,sealInheritiFile as tt,readInheritiFileHeader as Tt,openInheritiFile as Dt,InheritiFileInvalid as Nr,MAX_INHERITI_FILE_BYTES as Mt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as nt,openInheritiFileKey as Ot}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Kr(r){let{reveal:e,api:t,signal:n}=r;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(n);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let a=r.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(r.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>Mt-1024*1024)throw new Error("unsupported_protected_asset");let d=et(),c,l=!1,p=!1;try{n?.throwIfAborted();let m=await nt(d,i.publicKey);l=!0;let y=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:m,openLimit:a},n);if(y.copyId!==r.copyId||y.status!=="PENDING")throw new Error("file_access_create_invalid");let b=await t.getFileAccess(r.copyId,n);for(;b.status==="PENDING";){if(n?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((f,T)=>{let x=()=>{clearTimeout(k),T(n?.reason)},k=setTimeout(()=>{n?.removeEventListener("abort",x),f()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",x,{once:!0})}),b=await t.getFileAccess(r.copyId,n)}if(b.status!=="READY"||b.origin!=="REVEAL"||b.copyId!==r.copyId||b.allowedUses!==a||!b.recipient||!b.deployment||b.expiresAt!==null&&(!Number.isFinite(Date.parse(b.expiresAt))||Date.parse(b.expiresAt)>s||Date.parse(b.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let g=await tt({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:b});g.fileKey.fill(0),c=g.fileBytes,n?.throwIfAborted(),await r.save({fileName:o.fileName,fileBytes:c}),p=!0}catch(m){if(l&&!p)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(y){throw new AggregateError([m,y],"protected_asset_export_and_cleanup_failed",{cause:m})}throw m}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as Io}from"@safetech/inheriti-core-sdk/node";function Sn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var rt=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Sn(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Sn(new Uint8Array(t))}},it=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var _e=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},Ce=class extends _e{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},S=class extends _e{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function kt(r){if(r instanceof _e)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Rn=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:ne(n,"issuer"),authorizationEndpoint:ne(n,"authorization_endpoint"),tokenEndpoint:ne(n,"token_endpoint"),deviceAuthorizationEndpoint:Q(n,"device_authorization_endpoint"),endSessionEndpoint:Q(n,"end_session_endpoint"),revocationEndpoint:Q(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:ne(t,"device_code"),userCode:ne(t,"user_code"),verificationUri:ne(t,"verification_uri"),verificationUriComplete:Q(t,"verification_uri_complete"),expiresInSeconds:xn(t,"expires_in"),intervalSeconds:Nt(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:ne(n,"access_token"),refreshToken:Q(n,"refresh_token"),idToken:Q(n,"id_token"),tokenType:ne(n,"token_type"),expiresInSeconds:xn(n,"expires_in"),refreshExpiresInSeconds:Nt(n,"refresh_expires_in"),scope:Q(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let s=Q(i,"error")??`oauth_http_${n.status}`;throw new S(s,Q(i,"error_description")??s)}return i}};function ne(r,e){let t=Q(r,e);if(!t)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function Q(r,e){return typeof r[e]=="string"?r[e]:void 0}function xn(r,e){let t=Nt(r,e);if(t===void 0)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function Nt(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Ur=600*1e3,st=5,Lr=5,An=class{constructor(e){this.options=e;this.crypto=e.crypto??new rt,this.clock=e.clock??new it}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+Ur;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",a),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:o}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new S("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new S("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new S("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new S("state_mismatch");let a=i.searchParams.get("error");if(a)throw new S(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new S("authorization_code_missing");let d=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),l=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(l),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new S("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(st,t.intervalSeconds??st),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new S("device_transaction_missing");let i=n,s=await this.getDiscovery(),a=Math.max(st,i.intervalSeconds??st),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:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(d){let c=kt(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=Lr,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new S("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 Ce;let t;try{let n=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:n.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(n){let i=kt(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Ce):(this.isOfflineSession(e)||await this.options.sessions.clear(),n)}try{if(!t.refreshToken)throw new S("refresh_token_rotation_missing");let n=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(n),n}catch(n){throw await this.options.sessions.clear(),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(pe(e.issuer)!==pe(this.options.configuration.issuer))throw new S("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${pe(t)}|${n}|${i}`}async acceptTokens(e,t,n){if(e.tokenType.toLowerCase()!=="bearer")throw new S("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 S("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 S("token_subject_mismatch")}let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access"));return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&a?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:a,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(i.issuer))throw new S("issuer_mismatch");if(!s.includes(i.audience))throw new S("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new S("client_mismatch");if(e.environment!==i.environment)throw new S("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new S("required_claim_missing");if(n&&e.nonce!==t)throw new S("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(n.issuer))throw new S("issuer_mismatch");if(!i.includes(n.clientId))throw new S("client_mismatch");if(e.authorizedParty!==n.clientId)throw new S("client_mismatch");if(!e.subject||!e.sessionId)throw new S("required_claim_missing");if(e.nonce!==t)throw new S("nonce_mismatch")}};function pe(r){return r.replace(/\/+$/u,"")}var _n=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 bo,RawMasterKeySource as wo,deriveMasterKey as Eo,generateHexSeed as So,computePassphraseVerifier as Ro}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as Ao}from"@safetech/inheriti-core-sdk/node";function Xa(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",r.environment),e(s,Object.assign({},a,{headers:o}))},n=r.business?void 0:Kt({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),i=new ce(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new ae(n,{keyVault:r.keyVault,state:r.state,api:i,reconstructor:new le(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:Fr})}function Ja(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=Kt({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ae(new Se(r.apiUrl,r.environment,r.getBearerToken,e),t)}function Za(r){if(!r.payloadStorage||!r.secureSessionStorage||!r.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=r.transport??globalThis.fetch.bind(globalThis),t=new URL(r.apiUrl).origin,n=Kt({apiUrl:t,getBearerToken:r.getBearerToken,transport:wn({apiUrl:t,organizationId:r.organizationId,planId:r.planId,editId:r.editId,environment:r.environment,transport:e}),secureSessionStorage:r.secureSessionStorage,payloadStorage:r.payloadStorage,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ze(new Ye(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as qr}from"node:crypto";import{generateRSAOAEPKeyPair as Gr}from"@safetech/inheriti-core-sdk/crypto";async function Cn(r){let e=Tt(r.fileBytes);if(!/^[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(e.copyId))throw new Error("invalid_startup_file");if(r.signal?.aborted)throw new Error("opening_cancelled");let t=await r.api.getFileAccess(e.copyId,r.signal);if(e.deployment!==t.deployment||e.origin!==t.origin||e.copyId!==t.copyId||e.recipient!==t.recipient||e.expiresAt!==t.expiresAt||e.allowedUses!==t.allowedUses)throw new Error("file_binding_mismatch");return{header:e,access:t}}async function Vr(r){let{api:e,sessionId:t,signal:n}=r;if(!/^[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(t))throw new Error("invalid_opening_session");let i=Uint8Array.from(r.fileBytes),s,a,o=()=>{if(n?.aborted)throw new Error("opening_cancelled")};try{let{access:d}=await Cn({fileBytes:i,api:e,signal:n});if(d.status!=="READY"||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())throw new Error("file_access_unavailable");if(r.delivery==="REVEAL"&&d.origin!=="REVEAL")throw new Error("file_access_unavailable");o();let{publicKeyBase64:c,privateKey:l}=await Gr(),p=qr("sha256").update(c).digest("hex");o();let m=await e.requestFileAccessOpening(d.copyId,{sessionId:t,clientPublicKey:c,...r.delivery==="REVEAL"?{delivery:"REVEAL"}:{}});r.delivery==="REVEAL"&&r.onPairingCode?.(p.slice(0,12));let y=Math.min(Date.parse(m.expiresAt),Date.now()+3e5);if(!Number.isFinite(y))throw new Error("file_opening_expired");let b;for(;!n?.aborted&&Date.now()<y;){let T=await e.readFileAccessOpening(d.copyId,t,p,n);if(T.status==="READY"&&T.encryptedFileKey){b=T.encryptedFileKey;break}if(T.status==="EXPIRED"||T.status==="DELIVERY_CONFIRMED")throw new Error("file_opening_expired");o(),await new Promise(x=>{let k=()=>{clearTimeout(A),n?.removeEventListener("abort",k),x()},A=setTimeout(k,1e3);n?.addEventListener("abort",k,{once:!0})})}if(o(),!b)throw new Error("file_opening_expired");s=await Ot(b,l),o(),await e.confirmFileAccessDelivery(d.copyId,t,p);let g=await Dt(i,s,d);a=g.plaintext,o();let f={plaintext:a,header:g.header};return a=void 0,f}finally{i.fill(0),s?.fill(0),a?.fill(0)}}import{createHash as zr,webcrypto as Br}from"node:crypto";import{canonicalInboxManifest as $r,decodeInboxManifest as Hr,decodeInboxContentFrame as Wr,decodeInboxText as Qr,decryptInboxShare as jr,encodeInboxContentFrame as Ut,encodeInboxText as Yr,encryptInboxShare as Tn,inboxProtectedUnitCommitment as Xr,inboxTextMetadataDigest as Dn,openInboxContent as Jr,sealInboxContent as Zr,signInboxFrame as ei,unwrapInboxContentKey as ti,unwrapInboxShareKey as ni,verifyInboxFrame as Mn,wrapInboxContentKey as ri,wrapInboxShareKey as ii}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as si}from"@safetech/inheriti-core-sdk/workers/inbox.node";var $=Br,D=$,C=r=>{if(!/^[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid_inbox_key");return Buffer.from(r,"hex")},I=r=>{let e=Buffer.from(r,"base64");if(!r||e.toString("base64")!==r)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},G=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),at=async r=>new Uint8Array(await D.subtle.digest("SHA-256",Uint8Array.from(r))),Te=r=>zr("sha256").update(r).digest("hex"),re=class{constructor(e,t=new si){this.api=e;this.worker=t}async send(e){let t=await this.prepare(e);return this.api.publishInboxMessage(e.conversationId,t.submission)}async prepare(e){let{preparation:t,sender:n}=await this.prepareSender(e),i=await this.textManifest(e,t,n),s=$r(i),a=await at(s),{contentKey:o,frame:d}=await Zr(Yr(e.text),a,D),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:p}=await this.protectShares(t,d,a),m=await this.wrapRecipientKeys(t,o,a),y=await ii(l,C(e.tenantKeyHex),a,i.tenantId,i.messageId,D);return{frame:Buffer.from(Ut(d)).toString("base64"),submission:{messageId:t.messageId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,expiresAt:e.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(c).toString("base64"),tenantWrappedShareKey:Buffer.from(y).toString("base64"),recipients:m,shares:p}}}async open(e){return this.openWithCommitment(e)}openCommitted(e,t){return this.openWithCommitment(e,t)}async openWithCommitment(e,t){let n=await this.api.openInboxMessage(e.conversationId,e.messageId,e.identity.deviceId),i;try{e.signal?.throwIfAborted();let{manifest:a,manifestDigest:o,senderPublicDer:d}=await this.verifyOpening(e,n),c=await this.recoverFrame(n,a,o,e.tenantKeyHex);if(t&&!G(t,await Xr(a,Ut(c),I(n.signature),D)))throw new Error("inbox_parent_unit_mismatch");i=await this.decryptText(n,c,a,o,d,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(a){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId)}catch{}throw a}let s=await this.ack(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId,e.signal);return e.signal?.throwIfAborted(),{text:i,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:s}}async ack(e,t,n,i,s){for(let a=0;a<2;a++){s?.throwIfAborted();try{return await this.api.ackInboxMessage(e,t,n,i,s),s?.throwIfAborted(),"ACKNOWLEDGED"}catch(o){if(s?.throwIfAborted(),o instanceof q&&o.status>=400&&o.status<500)throw o}}return"PENDING"}async prepareSender(e){let t=await this.api.getInboxSendPreparation(e.conversationId);if(t.conversationId!==e.conversationId||t.threshold!==t.total||t.total!==t.shareLayers.length||t.total<2)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId);if(!n||n.deviceId!==e.identity.deviceId||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Te(I(n.signingPublicKey))!==n.signingKeyFingerprint||Te(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return{preparation:t,sender:n}}async textManifest(e,t,n){let i=Date.parse(e.expiresAt);if(!Number.isSafeInteger(i)||i<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:e.identity.tenantId,conversationId:e.conversationId,messageId:t.messageId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:C(s.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await Dn(D)}}async signFrame(e,t,n,i){let s=await D.subtle.importKey("pkcs8",I(n),"Ed25519",!1,["sign"]),a=await ei(e,t,s,D),o=await D.subtle.importKey("spki",I(i),"Ed25519",!1,["verify"]);if(!await Mn(e,t,a,o,D))throw new Error("inbox_identity_mismatch");return a}async protectShares(e,t,n){let i=await this.worker.split(Ut(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),s=D.getRandomValues(new Uint8Array(32)),a=[];for(let o=0;o<e.total;o++){let d=e.shareLayers[o];a.push({kind:"DATA",index:o,shareId:d.dataShareId,layerId:d.id,ciphertext:Buffer.from(await Tn(i.dataShares[o],s,n,e.messageId,D)).toString("base64")}),a.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await Tn(i.keyShares[o],s,n,e.messageId,D)).toString("base64")})}return{shareKey:s,shares:a}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=I(i.encryptionPublicKey);if(Te(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await D.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:Buffer.from(await ri(t,a,n,D)).toString("base64")}}))}async verifyOpening(e,t,n){let i=I(t.canonicalManifest),s=Hr(i);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!G(s.metadataDigest,n??await Dn(D)))throw new Error("inbox_manifest_mismatch");let a=s.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!a||!G(a.encryptionKeyFingerprint,C(Te(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=I(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Te(o)||!G(s.senderSigningKeyFingerprint,C(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await at(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let s=await ni(I(e.tenantWrappedShareKey),C(i),n,t.tenantId,t.messageId,D),a=[],o=[],d=new Set;for(let l of e.shares){let p=`${l.kind}:${l.index}`;if(d.has(p))throw new Error("duplicate_inbox_share");d.add(p);let m=await jr(I(l.ciphertext),s,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,D);(l.kind==="DATA"?a:o).push(m)}if(a.length!==o.length||a.length<2)throw new Error("incomplete_inbox_shares");let c=await this.worker.reconstruct(a,o,{threshold:a.length,total:a.length,messageId:t.messageId,manifestDigest:n});return Wr(c)}async decryptText(e,t,n,i,s,a){return Qr(await this.decryptContent(e,t,n,i,s,a))}async decryptContent(e,t,n,i,s,a){let o=await D.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Mn(n,t,I(e.signature),o,D))throw new Error("inbox_signature_invalid");let d=await D.subtle.importKey("pkcs8",I(a),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await ti(I(e.wrappedContentKey),d,i,D);return Jr(t,c,i,D)}};import{canonicalInboxManifest as ai,decodeInboxContentFrame as oi,decodeInboxFile as di,decryptInboxShare as ci,encodeInboxContentFrame as li,encodeInboxFile as pi,encryptInboxShare as On,inboxFileMetadataDigest as kn,sealInboxContent as ui,unwrapInboxShareKey as mi,wrapInboxShareKey as gi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var ot=class extends re{constructor(t){super(t);this.fileApi=t}async sendFile(t){t.signal?.throwIfAborted();let{preparation:n,sender:i}=await this.prepareSender(t),s=await this.fileManifest(t,n,i),a=ai(s),o=await at(a),d=pi(t.file),c;try{c=await ui(d,o,$)}finally{d.fill(0)}let{contentKey:l,frame:p}=c,m=await this.signFrame(s,p,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let y=await this.worker.split(li(p),{threshold:n.threshold,total:n.total,messageId:n.messageId,manifestDigest:o},t.signal,A=>t.onProgress?.(0,n.total*2,A.stage));t.signal?.throwIfAborted();let b=$.getRandomValues(new Uint8Array(32)),g=[];for(let A=0;A<n.total;A++){let H=n.shareLayers[A];g.push({reference:{kind:"DATA",index:A,shareId:H.dataShareId,layerId:H.id},bytes:await On(y.dataShares[A],b,o,n.messageId,$)}),g.push({reference:{kind:"KEY",index:A,shareId:H.keyShareId,layerId:H.id},bytes:await On(y.keyShares[A],b,o,n.messageId,$)})}let f=await this.wrapRecipientKeys(n,l,o),T=await gi(b,C(t.tenantKeyHex),o,s.tenantId,s.messageId,$);t.signal?.throwIfAborted();let x=await this.fileApi.stageInboxFile(t.conversationId,{messageId:n.messageId,senderDeviceId:i.deviceId,participantRevision:n.participantRevision,expiresAt:t.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(a).toString("base64"),signature:Buffer.from(m).toString("base64"),tenantWrappedShareKey:Buffer.from(T).toString("base64"),recipients:f,shares:g.map(A=>A.reference)},t.signal);if(x.messageId!==n.messageId||x.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let A=0;A<g.length;A++){t.signal?.throwIfAborted();let H=g[A];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,H.reference.shareId,H.bytes,t.signal),t.onProgress?.(A+1,g.length,"UPLOADING")}t.signal?.throwIfAborted();let k=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(k.messageId!==n.messageId||k.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return k}async openFile(t){t.signal?.throwIfAborted();let n=await this.fileApi.openInboxFile(t.conversationId,t.messageId,t.identity.deviceId,t.signal),i,s;try{let{manifest:o,manifestDigest:d,senderPublicDer:c}=await this.verifyOpening(t,n,await kn($)),l=await this.recoverFileFrame(t,n,o,d);s=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=di(s),t.signal?.throwIfAborted(),await t.save(i,{leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt}),t.signal?.throwIfAborted()}catch(o){try{await this.fileApi.releaseInboxMessage(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId)}catch{}throw o}finally{s?.fill(0)}let a=await this.ack(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId,t.signal);return t.signal?.throwIfAborted(),{name:i.name,mimeType:i.mimeType,size:i.bytes.length,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:a}}async fileManifest(t,n,i){let s=Date.parse(t.expiresAt);if(!Number.isSafeInteger(s)||s<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:t.identity.tenantId,conversationId:t.conversationId,messageId:n.messageId,senderId:t.identity.memberId,senderDeviceId:i.deviceId,senderSigningKeyFingerprint:C(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:C(a.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await kn($)}}async recoverFileFrame(t,n,i,s){let a=await mi(I(n.tenantWrappedShareKey),C(t.tenantKeyHex),s,i.tenantId,i.messageId,$),o=[],d=[],c=new Set;for(let p=0;p<n.shares.length;p++){t.signal?.throwIfAborted();let m=n.shares[p],y=`${m.kind}:${m.index}`;if(c.has(y))throw new Error("duplicate_inbox_share");c.add(y);let b=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,m.shareId,t.identity.deviceId,n.leaseId,t.signal),g=await ci(b,a,s,i.messageId,m.kind==="DATA"?"data":"key",m.index,$);(m.kind==="DATA"?o:d).push(g),t.onProgress?.(p+1,n.shares.length,"DOWNLOADING")}if(o.length!==d.length||o.length<2)throw new Error("incomplete_inbox_shares");t.signal?.throwIfAborted();let l=await this.worker.reconstruct(o,d,{threshold:o.length,total:o.length,messageId:i.messageId,manifestDigest:s},t.signal,p=>t.onProgress?.(n.shares.length,n.shares.length,p.stage));return t.signal?.throwIfAborted(),oi(l)}};import{createHash as Kn,webcrypto as Ii}from"node:crypto";import{canonicalInboxParentManifest as hi,decodeInboxParentManifest as yi,encodeInboxParentNormalFrame as fi,decodeInboxParentNormalFrame as Pi,sealInboxParentNormalBody as vi,openInboxParentNormalBody as bi,wrapInboxParentNormalKey as wi,unwrapInboxParentNormalKey as Ei,signInboxParentNormalFrame as Si,verifyInboxParentNormalFrame as Nn,encodeInboxText as Ri,decodeInboxText as xi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var V=Ii,De=r=>Kn("sha256").update(r).digest("hex"),dt=r=>Buffer.from(r).toString("base64"),ct=class{constructor(e){this.api=e}pending=new Map;async send(e){let t=this.digestInput(e),n=e.parentId?this.pending.get(e.parentId):void 0;if(n){if(n.inputDigest!==t)throw new Error("inbox_idempotency_conflict");let c=await this.api.publishNormalInboxMessage(e.conversationId,n.submission);return this.pending.delete(e.parentId),c}let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validatePreparation(e,i),a=this.createManifest(e,i,s),o=await this.createSubmission(e,i,s,a);this.rememberSubmission(a.parentId,t,o);let d=await this.api.publishNormalInboxMessage(e.conversationId,o);return this.pending.delete(a.parentId),d}digestInput(e){return Kn("sha256").update(JSON.stringify([e.conversationId,e.parentId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.text])).digest("hex")}validatePreparation(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||De(I(n.signingPublicKey))!==n.signingKeyFingerprint||De(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}createManifest(e,t,n){return{mode:"NORMAL",tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:e.parentId??t.parentId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:C(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let s=hi(i),{contentKey:a,frame:o}=await vi(Ri(e.text),i,V),d=await V.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await Si(i,o,d,V),l=await V.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Nn(i,o,c,l,V))throw new Error("inbox_identity_mismatch");let p=await Promise.all(t.recipients.map(m=>this.wrapRecipientKey(m,a,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:dt(s),frame:dt(fi(o)),signature:dt(c),recipients:p}}async wrapRecipientKey(e,t,n){let i=I(e.encryptionPublicKey);if(De(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await V.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:e.memberId,deviceId:e.deviceId,deviceVersion:e.deviceVersion,keyFingerprint:e.encryptionKeyFingerprint,wrappedContentKey:dt(await wi(t,s,n,V))}}rememberSubmission(e,t,n){if(this.pending.size>=32){let i=this.pending.keys().next().value;i&&this.pending.delete(i)}this.pending.set(e,{inputDigest:t,submission:n})}list(e,t,n){return this.api.listNormalInboxMessages(e,t,n)}async open(e){e.signal?.throwIfAborted();let t=await this.api.openNormalInboxMessage(e.conversationId,e.parentId,e.identity.deviceId,e.signal),n=yi(I(t.canonicalManifest));if(n.mode!=="NORMAL"||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch");let i=n.recipients.find(p=>p.memberId===e.identity.memberId&&p.deviceId===e.identity.deviceId);if(!i||!G(i.encryptionKeyFingerprint,C(De(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=I(t.senderSigningPublicKey);if(!G(n.senderSigningKeyFingerprint,C(De(s))))throw new Error("inbox_sender_key_mismatch");let a=Pi(I(t.frame)),o=await V.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Nn(n,a,I(t.signature),o,V))throw new Error("inbox_signature_invalid");let d=await V.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Ei(I(t.wrappedContentKey),d,n,V),l=xi(await bi(a,c,n,V));return e.signal?.throwIfAborted(),{text:l,parentId:t.parentId,sequence:t.sequence}}markRead(e){return this.api.markNormalInboxMessageRead(e.conversationId,e.parentId,e.identity.deviceId)}};import{createHash as Fn,webcrypto as Ai}from"node:crypto";import{canonicalInboxParentManifest as _i,decodeInboxParentManifest as Ci,decodeInboxManifest as Ti,encodeInboxParentNormalFrame as Di,decodeInboxParentNormalFrame as Mi,sealInboxParentNormalBody as Oi,openInboxParentNormalBody as ki,wrapInboxParentNormalKey as Ni,unwrapInboxParentNormalKey as Ki,signInboxParentNormalFrame as Ui,verifyInboxParentNormalFrame as Un,signInboxProtectedParent as Li,verifyInboxProtectedParent as Ln,inboxProtectedUnitCommitment as Fi,encodeInboxText as qi,decodeInboxText as Gi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var K=Ai,lt=r=>Buffer.from(r).toString("base64"),Me=r=>Fn("sha256").update(r).digest("hex"),pt=class{constructor(e,t){this.api=e;this.child=t??new re(e)}pending=new Map;child;async send(e){let t=Fn("sha256").update(JSON.stringify([e.conversationId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.segments])).digest("hex"),n=e.parentId?[e.parentId,this.pending.get(e.parentId)]:[...this.pending.entries()].find(([,o])=>o.digest===t),i=n?.[1];if(i){if(i.digest!==t)throw new Error("inbox_idempotency_conflict");try{e.onProgress?.(i.submission.protectedUnits.length,i.submission.protectedUnits.length)}catch{}let o=await this.api.publishInboxParent(e.conversationId,i.submission);return this.pending.delete(n[0]),o}let s=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(s.parentId,{digest:t,submission:s});let a=await this.api.publishInboxParent(e.conversationId,s);return this.pending.delete(s.parentId),a}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let t=e.segments.filter(y=>"protectedText"in y).length;if(t<1||t>4)throw new Error("invalid_inbox_parent_segments");let n=e.segments.length===1&&t===1?"PROTECTED":"MIXED";if(n==="MIXED"&&!e.segments.some(y=>"text"in y))throw new Error("invalid_inbox_parent_segments");let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validateSender(e,i),a=e.parentId??i.parentId,{protectedUnits:o,manifestUnits:d}=await this.prepareChildren(e,i,s),c=this.parentManifest(e,i,s,a,n,d),{frame:l,signature:p,recipients:m}=await this.signAndWrap(e,i,s,c);return{parentId:a,idempotencyKey:a,senderDeviceId:s.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:lt(_i(c)),signature:lt(p),frame:l,recipients:m,protectedUnits:o}}async prepareChildren(e,t,n){let i=[],s=[],a=e.segments.filter(o=>"protectedText"in o).length;for(let o=0;o<e.segments.length;o++){let d=e.segments[o];if(!("protectedText"in d))continue;let c=await this.child.prepare({conversationId:e.conversationId,text:d.protectedText,expiresAt:d.expiresAt,identity:e.identity,tenantKeyHex:e.tenantKeyHex}),l=Ti(I(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let p=await Fi(l,I(c.frame),I(c.submission.signature),K);i.push({position:o,frame:c.frame,child:c.submission}),s.push({unitId:c.submission.messageId,position:o,commitment:p});try{e.onProgress?.(i.length,a)}catch{}}return{protectedUnits:i,manifestUnits:s}}validateChildSnapshot(e,t,n,i){if(e.tenantId!==t.identity.tenantId||e.conversationId!==t.conversationId||e.senderId!==t.identity.memberId||e.senderDeviceId!==i.deviceId||e.participantRevision!==n.participantRevision||e.recipients.length!==n.recipients.length||e.recipients.some(s=>!n.recipients.some(a=>a.memberId===s.memberId&&a.deviceId===s.deviceId&&G(s.encryptionKeyFingerprint,C(a.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,t,n,i,s,a){return{mode:s,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:i,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:C(o.encryptionKeyFingerprint)})),protectedUnits:a}}async signAndWrap(e,t,n,i){let s=await K.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),a=await K.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(i.mode==="PROTECTED")return{signature:await this.signProtectedParent(i,s,a),recipients:this.recipientReferences(t)};let{frame:o,signature:d,contentKey:c}=await this.sealMixedParent(e,i,s,a);return{frame:o,signature:d,recipients:await this.wrapRecipients(t,c,i)}}async signProtectedParent(e,t,n){let i=await Li(e,t,K);if(!await Ln(e,i,n,K))throw new Error("inbox_identity_mismatch");return i}async sealMixedParent(e,t,n,i){let s=e.segments.map((d,c)=>"text"in d?{text:d.text}:{unitId:t.protectedUnits.find(l=>l.position===c).unitId}),a=await Oi(qi(JSON.stringify(s)),t,K),o=await Ui(t,a.frame,n,K);if(!await Un(t,a.frame,o,i,K))throw new Error("inbox_identity_mismatch");return{frame:lt(Di(a.frame)),signature:o,contentKey:a.contentKey}}recipientReferences(e){return e.recipients.map(t=>({memberId:t.memberId,deviceId:t.deviceId,deviceVersion:t.deviceVersion,keyFingerprint:t.encryptionKeyFingerprint}))}async wrapRecipients(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=I(i.encryptionPublicKey);if(Me(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await K.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:lt(await Ni(t,a,n,K))}}))}validateSender(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Me(I(n.signingPublicKey))!==n.signingKeyFingerprint||Me(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}list(e,t,n){return this.api.listInboxParents(e,t,n)}clearHistory(e,t){return this.api.clearInboxHistory(e,t)}async open(e){let{opened:t,manifest:n,segments:i}=await this.openAndVerify(e);return{parentId:t.parentId,sequence:t.sequence,mode:n.mode,segments:i}}async openAndVerify(e){e.signal?.throwIfAborted();let t=await this.api.openInboxParent(e.conversationId,e.parentId,e.identity.deviceId,e.signal),{manifest:n,senderKey:i}=await this.verifyOpening(e,t),s=n.mode==="PROTECTED"?await this.openProtectedParent(t,n,i):await this.openMixedParent(e,t,n,i);return e.signal?.throwIfAborted(),{opened:t,manifest:n,segments:s}}async verifyOpening(e,t){let n=Ci(I(t.canonicalManifest));return this.verifyManifestContext(e,t,n),this.verifyManifestUnits(t,n),this.verifyRecipient(e,n),{manifest:n,senderKey:await this.senderKey(t,n)}}verifyManifestContext(e,t,n){if(n.mode!==t.mode||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch")}verifyManifestUnits(e,t){if(t.protectedUnits.length!==e.protectedUnits.length||t.protectedUnits.some((n,i)=>n.unitId!==e.protectedUnits[i].unitId||n.position!==e.protectedUnits[i].position||!G(n.commitment,C(e.protectedUnits[i].commitment))))throw new Error("inbox_manifest_mismatch")}verifyRecipient(e,t){let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||!G(n.encryptionKeyFingerprint,C(Me(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,t){let n=I(e.senderSigningPublicKey);if(Me(n)!==e.senderSigningKeyFingerprint||!G(t.senderSigningKeyFingerprint,C(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return K.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await Ln(t,I(e.signature),n,K))throw new Error("inbox_signature_invalid");return[{unitId:t.protectedUnits[0].unitId,position:0,status:e.protectedUnits[0].status}]}async openMixedParent(e,t,n,i){if(!t.frame||!t.wrappedContentKey)throw new Error("inbox_missing_normal_body");let s=Mi(I(t.frame));if(!await Un(n,s,I(t.signature),i,K))throw new Error("inbox_signature_invalid");let a=await K.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await Ki(I(t.wrappedContentKey),a,n,K),d=JSON.parse(Gi(await ki(s,o,n,K)));return this.decodeSegments(d,t,n)}decodeSegments(e,t,n){if(!Array.isArray(e))throw new Error("invalid_inbox_parent_body");let i=e.map((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error("invalid_inbox_parent_body");let o=s;if(typeof o.text=="string"&&Object.keys(o).length===1)return{text:o.text};let d=n.protectedUnits.find(c=>c.position===a);if(!d||o.unitId!==d.unitId||Object.keys(o).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:d.unitId,position:a,status:t.protectedUnits.find(c=>c.unitId===d.unitId).status}});if(n.protectedUnits.some(s=>!i[s.position]||!("unitId"in i[s.position])))throw new Error("invalid_inbox_parent_body");return i}async revealUnit(e){let{manifest:t,segments:n}=await this.openAndVerify(e);if(!n.some(s=>"unitId"in s&&s.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let i=t.protectedUnits.find(s=>s.unitId===e.unitId);return this.child.openCommitted({conversationId:e.conversationId,messageId:e.unitId,identity:e.identity,tenantKeyHex:e.tenantKeyHex,signal:e.signal},i.commitment)}};export{ue as BusinessOrganizationSelectionError,xe as CorePlanMaterialBuilder,Io as DataAssetDefinitionService,q as ElementsApiRequestFailed,ae as ElementsClient,ve as GuidedCreateRecoveryError,Pe as GuidedPlanCreator,Ee as HttpAutomationRevealApiPort,ce as HttpElementsApiPort,Rn as HttpOperatorAuthTransport,Ye as HttpPlanEditPort,Se as HttpQuickPlanPort,Nr as InheritiFileInvalid,w as InvalidPlanDeclaration,N as InvalidPlanMaterial,Mt as MAX_INHERITI_FILE_BYTES,Ne as MasterKeyRelayCancellationFailed,ke as MasterKeyRelayExpired,Oe as MasterKeyRelayTimedOut,j as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,he as MemoryKeyVault,ye as MemoryStatePort,ot as NodeInboxFile,ct as NodeInboxNormal,pt as NodeInboxParent,re as NodeInboxText,S as OAuthProtocolError,An as OperatorAuthClient,_e as OperatorAuthError,Ce as OperatorReauthenticationRequired,_n as OperatorSessionController,ht as PLAN_CREATION_SERVER_STAGES,bo as PassphraseMasterKeySource,Ao as PlanAssetDeclaration,te as PlanRequestFailed,Ae as QuickPlanCreator,Ze as QuickPlanEditor,wo as RawMasterKeySource,z as RelayMasterKeySource,mt as StaticMasterKeyResolver,it as SystemOAuthClock,rt as WebOAuthCrypto,Ro as computePassphraseVerifier,Ke as createMasterKeyResolver,kr as createNodeAutomationRevealClient,Xa as createNodeElementsClient,Ja as createNodeQuickPlanCreator,Za as createNodeQuickPlanEditor,Fr as decodeAssetContainer,Eo as deriveMasterKey,Kr as exportProtectedRevealAsset,So as generateHexSeed,et as generateInheritiFileKey,Cn as inspectInheritiFileAccess,Ie as masterKeyRefFor,J as masterKeyRefKey,kt as oauthErrorCode,Dt as openInheritiFile,Vr as openInheritiFileAccess,Ot as openInheritiFileKey,Tt as readInheritiFileHeader,tt as sealInheritiFile,nt as sealInheritiFileKey,fr as selectBusinessOrganization,St as unwrapDekWithMasterKey,Z as validatePlanCreationInput,se as validatePlanCreationMaterial};