@safetech/inheriti-client-sdk 1.17.19 → 1.17.21

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 _t,decodeAssetContainer as xr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Tn,generateRSAOAEPKeyPair as Dn}from"@safetech/inheriti-core-sdk/crypto";var ke=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Oe=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 Dn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let a=await this.options.api.startRelaySession(n),s=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(m=>new Promise(y=>setTimeout(y,m))),c=!0,l=!1,u,g=()=>u??=(async()=>{let m=new AbortController,y,N=new Promise((C,L)=>{y=setTimeout(()=>{m.abort(),L(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(a.sessionId,m.signal),N])}finally{clearTimeout(y)}})(),b,D=new Promise((m,y)=>{b=()=>{c&&g().catch(()=>{}),y(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",b,{once:!0})});D.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(a),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let m=await Promise.race([this.options.api.readRelaySession(a.sessionId,e),D]);if(m.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(m.status==="DELIVERED"&&m.sealedMasterKey){let y=(await Tn(m.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(y))throw new Error("invalid_master_key_material");return y}if(m.status==="EXPIRED")throw new Oe(a.sessionId);await Mn(d,s,e)}throw new ke(a.sessionId)}catch(m){if(c&&(!l||e?.aborted))try{await g()}catch(y){if(e?.aborted)throw new Ne(y)}throw m}finally{b&&e?.removeEventListener("abort",b)}}};async function Mn(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 a=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",a,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",a))})}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||ot(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(kn(e,r.applicationId)){let i=await r.source?.resolve();return i||ot(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return ot(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function kn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ot(r,e,t,n,i){if((await e()).relayAvailable)return new z({...r.relay,api:On(r.api,t)}).resolve(n,i)}function On(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 X(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:${X(t)}`);this.ref=t;this.name="MasterKeyRequired"}},dt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(X(e),t),this}async resolve(e){return this.sources.get(X(e))?.resolve()}};var he=class{keys=new Map;async store(e,t){let n=X(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(X(e))?.slice()}async remove(e){let t=X(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"},f=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 qe=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],lt={"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"]},pt=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],v=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function ae(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new M("plan_material_field_unknown");if(ct(r.dataShards,"data_shards_invalid"),ct(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ct(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new M("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new M("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new M("material_operation_invalid")}function ct(r,e){if(!Array.isArray(r))throw new M(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new M(e);if(t.data!==void 0&&typeof t.data!="string")throw new M(e)}}function J(r){if(ie(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Un(r.idempotencyKey))throw new v("idempotency_key_invalid");if(!r.name?.trim())throw new v("plan_name_required");if(!r.assets.length)throw new v("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 v("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!qe.includes(t.type))throw new v("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new v("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 v("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new v("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(a=>!a.trim()))throw new v("asset_field_names_invalid");if(Nn(t.matchOrigins),!t.isBinary){let a=lt[t.type];if(!a||i.some(s=>!a.includes(s)))throw new v("asset_field_name_not_canonical")}}if(!r.participants.length)throw new v("participants_required");for(let t of r.participants){if(ie(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Dt(t.routingEmail))throw new v("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new v("participant_relationships_invalid")}Kn(r)}function Nn(r){if(r===void 0)return;if(!r.length)throw new v("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new v("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new v("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof v?n:new v("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new v("asset_match_origins_duplicated")}function Kn(r){let e=r.policy;if(e&&ie(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new v("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){ie(e.authentication,["mode"],"plan_authentication_field_unknown");let a=e.authentication.mode;if(a!==void 0&&a!=="EXCLUSIVE"&&a!=="ALL_REQUIRED")throw new v("authentication_mode_invalid")}if(e.moderation){ie(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let a=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(a.length===0)throw new v("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>a.length))throw new v("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new v("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(!Dt(t.subjectEmail))throw new v("dms_subject_invalid");if(!r.participants.some(a=>Tt(a.routingEmail)===Tt(t.subjectEmail)))throw new v("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 v("dms_countdown_invalid")}function Un(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 Dt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Tt(r){return r.normalize("NFC").trim().toLowerCase()}function ie(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new v(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"),J(e),Ge(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,a={}){J(t);let s=await this.checkpoints.load(e);if(!s)throw new ve("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Mt(t))throw new ve("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(a.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Ge(a.signal),a.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:a.signal});Ge(a.signal),a.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:a.signal});Ge(a.signal),ae(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return a.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 Mt(e),serverStage:t.stage})}},ve=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Mt(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Ge(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function kt(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 Ln(r){let e=r?.status;return e===400||e===401||e===403}async function Ot(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(a){if(!Ln(a))throw a}return r.releaseRevealMaterial(e,t)}function qn(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?Fn(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Gn.has(r.stage)?"ENDED":"CONTINUING"}var Gn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Fn(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var ut=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},T=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Lt(r,e,t={}){if(t.signal?.aborted)throw E();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Nt(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw E();let a=t.idempotencyKey??crypto.randomUUID(),s;try{s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?d:Nt(c.id)}let o;try{if(t.signal?.aborted)throw E();let d=await zn(r,s,t);if(t.signal?.aborted||(Z(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw E();let c=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id),t.signal?.aborted))throw E();let l;try{l=await Wn(r,d,jn(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(Z(t,"RECONSTRUCTING",d),t.signal?.aborted))throw E();try{o=await r.reconstructPlanMaterial(l)}catch(g){throw t.signal?.aborted?E():(await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Hn(g)}),g)}if(t.signal?.aborted)throw E();let u=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(Z(t,"OPEN",u),t.signal?.aborted))throw E();return new gt(r,u,n,o,t.signal)}catch(d){throw o?.fill(0),await qt(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function Nt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Vn=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 E();if(t.onSession?.(n),t.onProgress?.({phase:qn(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Vn.has(n.stage))throw new mt(n.stage);await ht(t.pollIntervalMs??1500,t.signal),n=await Y(()=>r.getReveal(e.id,t.signal),t.signal)}}var mt=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function Z(r,e,t){r.onProgress?.({phase:e,session:t})}function ht(r,e){return e?.aborted?Promise.reject(E()):new Promise((t,n)=>{let i=setTimeout(s,Math.max(0,r)),a=()=>{clearTimeout(i),n(E())};function s(){e?.removeEventListener("abort",a),t()}e?.addEventListener("abort",a,{once:!0})})}var gt=class{constructor(e,t,n,i,a){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=a?()=>{this.close("CANCELED").catch(()=>{})}:void 0,a&&this.abortListener&&a.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new ut;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 T("asset_selector_invalid");if(!this.client.assetDecoder)throw new T("asset_decoder_required");let n=e.map(({selector:a,options:s={}})=>{let o=Bn(a),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new T("asset_not_found");if(d.isBinary)throw new T("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new T("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:s}}),i=[];try{for(let s of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let a=n.map(s=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===s.asset.id||d.id===s.assetCode);if(!o)throw new T("asset_value_invalid");return{selector:s.selector,value:$n(o.data,s.field,s.asset.type)}});await t(a)}catch(a){throw await Promise.all(i.map(s=>this.reportAction(s.id,"FAILED",Kt(a)))),a}await Promise.all(i.map(a=>this.reportAction(a.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new T("asset_selector_invalid");if(!this.client.assetDecoder)throw new T("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new T("asset_not_found");if(!n.isBinary)throw new T("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),a;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new T("asset_value_invalid");a=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:a})}catch(s){throw await this.reportAction(i.id,"FAILED",Kt(s)),s}finally{a?.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=qt(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 Bn(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new T("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new T("asset_selector_invalid");return{asset:r.asset,field:r.field}}function $n(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new T("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new T("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?lt[t]:void 0)?.includes(e))return"";throw new T("asset_value_invalid")}return n[e]}function Kt(r){if(r instanceof T)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 Hn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Wn(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 Fe;let c=await Y(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(Ut(c,i.id,e.planId),!c.shares.includes(i.data))throw new H;Z(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await Y(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw E();if(!l?.trim())throw new H;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw E();return{...t,shares:t.shares.filter(u=>u!==i).concat(c.shares.map((u,g)=>({id:`${c.id}:${g}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new H;if(n.signal?.aborted)throw E();return await r.distributeRevealCustodianShare(e.id),Z(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let a=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;a.status==="PENDING"||a.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),Z(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ht(n.pollIntervalMs??1500,n.signal),a=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(a.status==="CLAIMED"&&a.deviceType==="SK_PRO"){if(!n.proDevice)throw new Fe;if(!a.shareId||!a.deviceId)throw new H;Z(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Y(()=>n.proDevice.read({shareId:a.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw E();if(Ut(d,a.shareId,e.planId),d.deviceId!==a.deviceId)throw new H;if(await r.collectRevealCustodianShare(e.id,a.shareId),n.signal?.aborted)throw E();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(a.status!=="CLAIMED"||a.deviceType!=="SK_MOBILE")throw new H;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(s),Z(n,"WAITING_FOR_CUSTODIAN",s),n.signal?.aborted)throw E();await r.requestRevealCustodianRelease(e.id);let o=await Qn(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 Ut(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 H}async function Y(r,e){if(e?.aborted)throw E();if(!e)return r();let t,n=new Promise((i,a)=>{t=()=>a(E()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw E();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function Qn(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 a=i;if(a.shares?.length)return a;throw new H}if(Date.now()>=n)throw new It;await ht(t.pollIntervalMs??1500,t.signal)}}var H=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Fe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},It=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function jn(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function qt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(s){if(!Yn(s))throw s}return}let n=new AbortController,i,a=new Promise((s,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let s=await Promise.race([r.closeReveal(e,t,n.signal),a]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(s.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(s){if(s?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:s}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Yn(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function E(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var se=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new he,this.state=t.state??new ye,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Zn(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new f;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new f;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new f;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return J(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new f;return ae(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new f;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 Jn(i);let a=await this.masterKeys?.resolve(e,t,n);if(!a)throw new j(e);return await this.keyVault.store(e,Xn(a)),a}async prepareReveal(e,t,n){if(!this.api)throw new f;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,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 f;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 f;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new f;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new f;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new f;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new f;return this.api.getReveal(e,t)}openReveal(e,t){return Lt(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let a=await n(i);return await i.close("COMPLETED"),a}catch(a){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),a}}async releaseRevealMaterial(e,t){if(!this.api)throw new f;return Ot(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new f;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new f;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new f;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new f;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new f;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new f;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new f;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new f;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new f;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new f;return kt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new f;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new f;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new f;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new f;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new f;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new f;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let 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 a=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),s=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:a.concat(s,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 f;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 yt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new j({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},yt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Xn(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Jn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Zn(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 er=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],tr=["DIRECT","GOVERNED"],Ft=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],nr=["ACTIVE","REVOKED"],rr=["SK_MOBILE"],ir=["ACTIVE","INACTIVE"],ar=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Vt(r){let e=k(r);return{items:q(e.items).map(Bt),nextCursor:e.nextCursor===null?null:h(e.nextCursor,"nextCursor")}}function zt(r){let e=k(r);return{total:W(e.total,"total"),items:q(e.items).map(t=>{let n=k(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:ee(n.status),title:h(n.title,"log.title"),details:q(n.details).map(i=>{let a=k(i);return{label:h(a.label,"log.detail.label"),value:h(a.value,"log.detail.value")}})}})}}function Ve(r){let e=k(r),t=Bt(e),n=k(e.source),i=h(n.kind,"source.kind");return{...t,assets:q(e.assets).map(a=>{let s=k(a);return{id:h(s.id,"asset.id"),code:ee(s.code),type:K(h(s.type,"asset.type"),qe),name:h(s.name,"asset.name"),isBinary:or(s.isBinary,"asset.isBinary"),fieldNames:q(s.fieldNames).map(o=>h(o,"asset.fieldNames")),fileName:ee(s.fileName),mimeType:ee(s.mimeType),size:s.size===void 0||s.size===null?void 0:W(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:q(s.matchOrigins).map(o=>h(o,"asset.matchOrigins"))}}),participants:q(e.participants).map(a=>{let s=k(a);return{id:h(s.id,"participant.id"),displayName:h(s.displayName,"participant.displayName"),relationships:q(s.relationships).map(o=>K(h(o,"relationship"),Ft)),lifecycle:K(h(s.lifecycle,"participant.lifecycle"),nr)}}),revealPolicy:(()=>{let a=k(e.revealPolicy);return{masterKeyRelease:K(h(a.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:K(h(a.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let a=k(e.dms);return{subjectEmail:h(a.subjectEmail,"dms.subjectEmail"),countdownDays:W(a.countdownDays,"dms.countdownDays"),countdownHours:W(a.countdownHours,"dms.countdownHours"),countdownMinutes:W(a.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:K(h(n.system,"source.system"),["INHERITI_BUSINESS"]),status:K(h(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function be(r){let e=k(r);return{operationId:h(e.operationId,"operationId"),stage:K(h(e.stage,"stage"),pt),outcome:K(h(e.outcome,"outcome"),ar),planId:ee(e.planId),lastErrorCode:ee(e.lastErrorCode),participants:e.participants===void 0?void 0:q(e.participants).map(t=>{let n=k(t);return{clientParticipantRef:h(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:h(n.planParticipantId,"planParticipantId"),relationships:q(n.relationships).map(i=>sr(h(i,"relationship"),Ft))}})}}function Bt(r){let e=k(r),t=k(e.assetSummary),n=k(e.governance),i=k(e.participantSummary);return{id:h(e.id,"id"),name:h(e.name,"name"),description:ee(e.description),status:K(h(e.status,"status"),er),createdAt:h(e.createdAt,"createdAt"),configuredAt:ee(e.configuredAt),assetSummary:{count:W(t.count,"assetSummary.count"),types:q(t.types).map(a=>K(h(a,"assetType"),qe)),names:Gt(t.names).map(a=>h(a,"assetSummary.names"))},governance:{mode:K(h(n.mode,"governance.mode"),tr),minimumApprovals:W(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:W(i.owners,"owners"),mergers:W(i.mergers,"mergers"),moderators:W(i.moderators,"moderators")},authentication:Gt(e.authentication).map(a=>{let s=k(a);return{id:K(h(s.id,"authentication.id"),rr),status:K(h(s.status,"authentication.status"),ir)}})}}function K(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function sr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function k(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Gt(r){return r==null?[]:q(r)}function q(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 ee(r){return r==null?void 0:h(r,"optional")}function W(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function or(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var ue=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function $t(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function dr(r,e){if(!e){if(r.length===0)throw new 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 cr(r){let e=S(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:P(e.participantRevision,1),createdAt:G(e.createdAt)}}function Ht(r){let e=S(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(cr),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0),unreadCount:P(e.unreadCount,0),readThroughSequence:P(e.readThroughSequence,0)}}function Wt(r){let e=S(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:p(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:P(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=S(t);return{unitId:p(n.unitId),position:P(n.position,0),commitment:p(n.commitment),status:p(n.status)}})}}function ft(r){let e=S(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:P(e.sequence,1),status:e.status}}function Qt(r){let e=S(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:P(e.participantRevision,1),recipients:e.recipients.map(Pt)}}function jt(r){let e=S(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=S(t);return{parentId:p(n.parentId),sequence:P(n.sequence,1),senderMemberId:p(n.senderMemberId),senderDeviceId:p(n.senderDeviceId),participantRevision:P(n.participantRevision,1),createdAt:G(n.createdAt)}}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0),unreadCount:P(e.unreadCount,0),readThroughSequence:P(e.readThroughSequence,0)}}function Yt(r){return{readThroughSequence:P(S(r).readThroughSequence,0)}}function Xt(r){return{clearedThroughSequence:P(S(r).clearedThroughSequence,0)}}function Jt(r){let e=S(r);return{parentId:p(e.parentId),sequence:P(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:P(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function S(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function p(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function G(r){let e=p(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function P(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Pt(r){let e=S(r);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:P(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function me(r){let e=S(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:G(e.createdAt),updatedAt:G(e.updatedAt)}}function ze(r){let e=S(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:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:G(e.createdAt),updatedAt:G(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=S(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:p(n.senderMemberId),createdAt:G(n.createdAt)}}return t}function Zt(r){let e=S(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(ze),total:e.total,limit:e.limit,offset:e.offset}}function en(r){let e=S(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=Pt(t);return{memberId:n.memberId,name:p(S(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function tn(r){let e=S(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=S(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(n.memberId),name:p(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:p(S(n.profilePicture).url)}}}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function nn(r){let e=S(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:p(e.conversationId),messageId:p(e.messageId),participantRevision:P(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Pt),shareLayers:e.shareLayers.map(t=>{let n=S(t),i=p(n.id),a=p(n.dataShareId),s=p(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:p(n.contractAddress),dataShareId:a,keyShareId:s};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:a,keyShareId:s};throw new Error("invalid_inbox_response")})}}function Be(r){let e=S(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:p(e.messageId),status:e.status}}function rn(r){let e=S(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=S(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:p(n.id),status:n.status,senderMemberId:p(n.senderMemberId),senderDeviceId:p(n.senderDeviceId),createdAt:G(n.createdAt),updatedAt:G(n.updatedAt),expiresAt:G(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(a=>{let s=S(a);if(s.status!=="UNREAD"&&s.status!=="LEASED"&&s.status!=="CONSUMED"&&s.status!=="EXPIRED"&&s.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:p(s.memberId),status:s.status}})),i}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0)}}function an(r){let e=S(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:G(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let n=S(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:p(n.shareId),layerId:p(n.layerId),ciphertext:p(n.ciphertext)}})}}function sn(r){let e=S(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:G(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let n=S(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:p(n.shareId),layerId:p(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 U=class extends Error{constructor(t,n,i){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ce=class{constructor(e,t,n,i,a){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=a?Object.freeze({...a}):void 0}business;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null: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 ze(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return ze(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 Zt(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 en(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 tn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return nn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return ft(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 a=i.size?`?${i}`:"";return Ht(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${a}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let a=new URLSearchParams({deviceId:n});return Wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return Xt(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 a=i.size?`?${i}`:"";return jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${a}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let a=new URLSearchParams({deviceId:n});return Jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return Yt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,a){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let s=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(s,"PUT",i,a),d=await $e(o,a);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new U(o.status,oe(d),de(d))}async publishInboxFile(e,t,n){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return sn(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,a,s){let o=new URLSearchParams({deviceId:i,leaseId:a}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,c=await this.requestBinary(d,"GET",void 0,s);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 u=c.body.getReader(),g=[],b=0;try{for(;;){s?.throwIfAborted();let y=await u.read();if(y.done)break;if(b+=y.value.length,b>14*1024*1024)throw new Error("invalid_inbox_share_size");g.push(y.value)}}catch(y){throw await u.cancel().catch(()=>{}),y}let D=new Uint8Array(b),m=0;for(let y of g)D.set(y,m),m+=y.length;return D}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 a=i.size?`?${i}`:"";return rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${a}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return an(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,a){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,a)}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($t)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return Vt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ve(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 zt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){J(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 ae(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,...a}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,a,s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken();s?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[b,D]of Object.entries(a??{}))d.set(b,D);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};s&&(l.signal=s);let u=await this.transport(new URL(e,c),l);s?.throwIfAborted();let g=await $e(u,s);if(s?.throwIfAborted(),!u.ok)throw new U(u.status,oe(g),de(g));if(!g.ok||g.result===void 0)throw new U(u.status,oe(g),de(g));return g.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let a=await this.getBearerToken();i?.throwIfAborted();let s=new Headers({"x-elements-environment":this.environment});a&&s.set("authorization",`Bearer ${a}`),this.business?.organizationId&&s.set("x-organization-id",this.business.organizationId),n&&s.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:s,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await $e(d,i);throw new U(d.status,oe(c),de(c))}return d}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});n&&i.set("authorization",`Bearer ${n}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,a),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),o=await $e(s);if(!s.ok||!o.ok)throw new U(s.status,oe(o),de(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new U(400,"organization_selection_required")}};async function $e(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 yr}from"@safetech/inheriti-core-sdk/node";async function vt(r,e){if(!e)throw new Error("master_key_required");let t=lr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=pr(r),a=i.slice(0,12),s=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},n,s);return ur(new Uint8Array(o))}function lr(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function pr(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function ur(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 on("plan_key_unwrap_failed",()=>vt(e.planKey,t)),i=await crypto.subtle.importKey("raw",bt(n),{name:"AES-GCM"},!1,["decrypt"]),a=[],s=[];for(let o of e.shares){let d=await on("plan_share_decryption_failed",()=>hr(o.data,i));Ir(o.shareType)?s.push(d):a.push(d)}try{return await this.processor().reconstruct(a,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new He("plan_share_reconstruction_failed",gr(o))}}},He=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},mr=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function gr(r){let e=r instanceof Error?r.message:void 0;if(e)return mr.has(e)?e:void 0}async function on(r,e){try{return await e()}catch{throw new He(r)}}function Ir(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function hr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=bt(r.slice(0,t)),i=bt(r.slice(t+1)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(a)}function bt(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(()=>yr(e))}};var Se=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 Ve(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,...a}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,!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,a,s){s?.throwIfAborted();let o=await this.getAutomationBearerToken();if(s?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...a});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:s});s?.throwIfAborted();let l;try{l=await c.json()}catch{s?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new U(c.status,l&&oe(l),l&&de(l));return l?.result}};var R={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}},Ee=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,a){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n,...a?{description:a}:{}},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",dn(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",dn(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(R.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(R.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(R.relayFailed);return n}async request(e,t,n,i){let a=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),s=await this.getBearerToken();if(!s)throw new Error(R.reauthenticationRequired);a.set("authorization",`Bearer ${s}`),i!==void 0&&a.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,c=await this.transport(new URL(d,o),{method:n,headers:a,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 dn(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),Pr(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 M("custodian_share_required");let a=wt(i.keyShards),s=await this.sealer.encryptShares(a,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(wt(i.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares(wt(i.backupShards),s.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,s.symmetricKeyBase64);return Re(e.signal),{protectionProtocol:i.protocol,validatorShares:St(s.encryptedShares),dataShards:St(o.encryptedShares),backupShards:St(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:fr(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:Et(n.encryptedShares[0]),dataShard:Et(n.encryptedShares[1])}}};function wt(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function St(r){return r.map(Et)}function Et(r){return{id:r.id,data:r.encryptedData}}function fr(r,e){let t={};for(let n of r){let i=e.assets.find(a=>a.clientAssetRef===n.id);if(!i)throw new M("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 Pr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new M("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new M("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new M("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 M("plan_secrets_declaration_mismatch")}}function Re(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function cn(r,e,t,n,i,a,s){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(R.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new z({api:{startRelaySession:b=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,b),readRelaySession:b=>i.readRelaySession(r.organizationId,b)}}),u=new xe(a,l);s?.("encrypting");let g=await u.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return s?.("generating_shares"),u.generateShares({planId:r.planId,declaration:c,encrypted:g})}import{PlanAssetDeclaration as vr}from"@safetech/inheriti-core-sdk/node";function ln(r){let e=Rt({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function Rt(r){if(!r.assets.length)throw new v("assets_required");let e=r.assets.map(a=>{if(a.meta.isMedia!==!0)return;let s="data"in a.secret?a.secret.data:void 0,o;if(s instanceof Blob&&(o=s.size),typeof s=="string")try{o=atob(s).length}catch{throw new v("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new v("binary_asset_metadata_invalid");return o}),t=vr.create(r.assets.map(({type:a,meta:s})=>({type:a,meta:s}))),n=t.complete(Object.fromEntries(t.entries.map((a,s)=>[a.id,r.assets[s].secret]))),i={idempotencyKey:r.planId,name:r.title,assets:n.map((a,s)=>{let o=a.meta.isMedia===!0;return{clientAssetRef:a.id,type:a.type,name:a.meta.name,fieldNames:o?[]:Object.keys(a.secret),isBinary:o,fileName:a.meta.fileName,mimeType:a.meta.mimeType,size:e[s]}}),participants:[]};return{assets:n,plan:i}}async function un(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 pn(new Uint8Array(await i.arrayBuffer())):i]))})));return pn(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 pn(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(s=>!s?.meta?.name?.trim()))throw new Error(R.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(R.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(R.invalidShares);let n=await un(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(R.reconciliationRequired);return i.promise}let a=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:a});try{return await a}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let i=Rt({planId:e.planId,title:e.title,assets:e.assets}),a=this.material.get(e.planId);if(a&&(a.fingerprint!==t||a.masterKeySource!==e.masterKeySource))throw new Error(R.reconciliationRequired);let s=await this.statusOrMissing(e.organizationId,e.planId);if(We(s))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(s&&!a)throw new Error(R.reconciliationRequired);if(!s&&a)throw new Error(R.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(R.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(R.invalidMasterKeyContext);if(!s){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(s=await this.statusOrMissing(e.organizationId,e.planId),!s)throw l}}s??=await this.port.status(e.organizationId,e.planId);let d=a?.encrypted??await cn(e,i,o,s,this.port,this.coreSdk,n);a||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(!We(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return We(c)&&this.material.delete(e.planId),{planId:e.planId,status:We(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(R.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 We(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var Qe=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 a=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(a))throw new Error("invalid_plan_edit_candidates");return a}async context(e,t){let 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 a=new Map;for(let s of i.participants){if(!s||typeof s.id!="string"||!s.id||typeof s.displayName!="string"||!Array.isArray(s.relationships)||!s.relationships.every(o=>typeof o=="string")||typeof s.lifecycle!="string")throw new Error("invalid_plan_edit_participants");s.lifecycle==="ACTIVE"&&s.relationships.includes("MODERATOR")&&a.set(s.id,s.displayName)}return a}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(R.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(R.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(R.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,a){let s=await this.getBearerToken();if(!s)throw new Error(R.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${s}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),a&&o.set("idempotency-key",a);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),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)}),u={};try{u=await l.json()}catch{}if(!l.ok||u.ok!==!0){let g=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new te(l.status,g||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(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 je=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){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),a=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!a)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let s=this.revealedAssets,o=s?.organizationId===e.organizationId&&s.planId===e.planId&&s.editId===e.editId&&s.expiresAt>Date.now();s&&!o&&(this.revealedAssets=void 0);let d=a.masterKeyEncrypted?e.masterKey??(o?s.masterKey:void 0):void 0;a.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?s.assets:await this.revealAssets(e,d,a.withCustodian,t);if(new Set(l.map(u=>u.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:a,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 a=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),s=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=m=>{m!==o&&(o=m,i?.(m))},c=m=>{if(m.processId!==e.editId||m.planId&&m.planId!==e.planId)return;switch(m.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let y=this.approvalError(m);if(y?.startsWith("edit_authentication_")&&d("pending_auth"),y?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!m.moderatorParticipants||m.requiredModeratorApprovals===void 0||!m.approvalProcess)return;let N=m.moderatorParticipants.map(C=>C.memberId??C.userId);N.some(C=>typeof C!="string"||!C)||new Set(N).size!==N.length||i?.(o,{requiredApprovals:m.requiredModeratorApprovals,approvedModerators:m.approvalProcess.approvedModerators,moderators:m.moderatorParticipants.map((C,L)=>{let A=N[L],$=C.flows.filter(ge=>ge.status==="PENDING"&&ge.expiresAt&&Number.isFinite(ge.expiresAt.getTime())).map(ge=>ge.expiresAt.getTime());return{id:A,displayName:s.get(A)||"Moderator",status:C.status,expiresAt:$.length?new Date(Math.min(...$)).toISOString():void 0}})})},l=await a.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 a.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let u=await a.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");c(u),this.assertApprovalOutcome(e.planId,u);let g=u?.status;if(g!=="READY_TO_REVEAL"&&g!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let b=null,D={onRevealed:m=>{b=m},onViewUpdate:c,onRevealStepUpdate:(m,y)=>{if(y==="IN_PROCESS")switch(m){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(n&&(D.onCustodianShareRequired=async(m,y)=>{switch(y.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let N=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),N==="SK_MOBILE")return a.distributeCustodianShareViaMobile(y.planId);if(N!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let C=e.proDevice;try{this.assertNotAborted(e.signal);let L=await a.getCustodianShareData(m);this.assertShare(L,y.planId),d("connecting_safekey_pro");let{deviceId:A}=await C.write(L,e.signal);if(this.assertNotAborted(e.signal),!A?.trim())throw new Error("custodian_share_unavailable");await a.recordCustodianShareClaim(y.planId,L.id,A,"SK_PRO"),this.assertNotAborted(e.signal),await a.markCustodianShareAsCollected(m,L.id);return}finally{C.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let N=e.proDevice;try{if(this.assertNotAborted(e.signal),!y.shareId||!y.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let C=await N.read({shareId:y.shareId,planId:y.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(C,y.planId,y.shareId),C.deviceId!==y.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:C.shares}}finally{N.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),g==="REVEALED"?await a.resumeReveal(e.editId,D,t):await a.openRevealWindow(e.editId,{timeoutMinutes:10},D,t),!b)throw new Error("edit_assets_unavailable");return b}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 Ye=class{constructor(e,t,n,i){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=i}async saveAssets(e,t,n,i,a,s){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,i);s?.("preparing");let c=await o.prepare(d),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(s?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,l),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:a,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,a,l,o,d,s)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let 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 a=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),dataShards:i.dataShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),backupShards:i.backupShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,a))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let s=await this.port.status(e.organizationId,e.editId);return s.id!==e.editId||s.planId!==e.planId||s.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,a),await this.port.commit(e.organizationId,e.planId,a),await this.isCommitted(e,a)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let 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 a=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),s={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:a,configuration:s}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}async commit(e,t,n,i,a,s){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,s?.(l))};try{await i.execute(a,{onLocalProcessUpdated:d})}catch(c){try{if(s?.("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&&s?.(o),c}try{if(s?.("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=[t.validatorShares,t.dataShards,t.backupShards].flat().map(s=>s.id);t.custodianPair&&i.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let a=n.shares.map(s=>s.id).sort();return i.sort(),!(i.length!==a.length||i.some((s,o)=>s!==a[o]))}};var Xe=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new je(e,t,n),this.reconfiguration=new Ye(e,t,n,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;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),a=i.find(s=>s.id===t);if(!a)throw new Error("edit_asset_not_found");return a}async replaceAsset(e,t){if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=a.findIndex(l=>l.id===e.assetId);if(s<0)throw new Error("edit_asset_not_found");let o=a[s];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},c=a.map((l,u)=>u===s?d:l);return this.reconfiguration.saveAssets(e,c,n.withCustodian,i,o.id,t)}async addAsset(e,t){let{plan:n,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=ln({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(a.map(d=>d.id)).has(s.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,a.concat(s),n.withCustodian,i,s.id,t)}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.reconfiguration.recover(e)}discard(e){return this.reconfiguration.discard(e)}discardLocal(e){return this.reconfiguration.discardLocal(e)}};function mn({apiUrl:r,organizationId:e,planId:t,editId:n,environment:i,transport:a}){return(s,o)=>{let d=new URL(s instanceof Request?s.url:s.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 a(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let u=br(l,d.searchParams,t,n),g=new Headers(o?.headers);g.set("x-organization-id",e),g.set("x-elements-environment",i);let b=c.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return a(new URL(b,c),Object.assign({},o,{headers:g}))}}function br(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 a=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(a){let o=a[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(a[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(a[1])}/${d[o]}`}let s=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){if(s[1]!==t)throw new Error("edit_plan_id_mismatch");let o=s[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(s[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 wr}from"@safetech/inheriti-core-sdk/node";function gn(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 a=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)}});return new se(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 a.resolve(d,c)}}}).openReveal(e,t)}}}function Sr(r){let e=new Se(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{...gn({api:e,reconstructor:new le(r.workerUrl),assetDecoder:wr}),getPlan:t=>e.getPlan(t)}}import{DataAssetDefinitionService as zs}from"@safetech/inheriti-core-sdk/node";function In(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Je=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),In(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return In(new Uint8Array(t))}},Ze=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 a=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(a),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"}},w=class extends _e{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function xt(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 hn=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:yn(t,"expires_in"),intervalSeconds:At(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:yn(n,"expires_in"),refreshExpiresInSeconds:At(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 a=Q(i,"error")??`oauth_http_${n.status}`;throw new w(a,Q(i,"error_description")??a)}return i}};function ne(r,e){let t=Q(r,e);if(!t)throw new w("invalid_oauth_response",`Missing ${e}`);return t}function Q(r,e){return typeof r[e]=="string"?r[e]:void 0}function yn(r,e){let t=At(r,e);if(t===void 0)throw new w("invalid_oauth_response",`Missing ${e}`);return t}function At(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Er=600*1e3,et=5,Rr=5,fn=class{constructor(e){this.options=e;this.crypto=e.crypto??new Je,this.clock=e.clock??new Ze}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(i),s=this.clock.now()+Er;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",a),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new w("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new w("authorization_transaction_expired");let i=new URL(e),a=new URL(n.redirectUri);if(i.origin!==a.origin||i.pathname!==a.pathname)throw new w("redirect_uri_mismatch");let s=i.searchParams.get("error");if(s)throw new w(s,i.searchParams.get("error_description")??s);if(i.searchParams.get("state")!==n.state)throw new w("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new w("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 w("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(et,t.intervalSeconds??et),i=this.clock.now(),a={...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"),a),a}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 w("device_transaction_missing");let i=n,a=await this.getDiscovery(),s=Math.max(et,i.intervalSeconds??et),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:a.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(d){let c=xt(d);if(c==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(c==="slow_down"){s+=Rr,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new w("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;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new w("refresh_token_rotation_missing");let i=await this.acceptTokens(n);return await this.options.sessions.save(i),i}catch(t){await this.options.sessions.clear();let n=xt(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new Ce:t}}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 w("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){if(e.tokenType.toLowerCase()!=="bearer")throw new w("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new w("id_token_validation_required");let a=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(a,t),a.subject!==n.subject||a.sessionId!==n.sessionId)throw new w("token_subject_mismatch")}let i=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:i+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:i+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let i=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(i.issuer))throw new w("issuer_mismatch");if(!a.includes(i.audience))throw new w("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new w("client_mismatch");if(e.environment!==i.environment)throw new w("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new w("required_claim_missing");if(n&&e.nonce!==t)throw new w("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 w("issuer_mismatch");if(!i.includes(n.clientId))throw new w("client_mismatch");if(e.authorizedParty!==n.clientId)throw new w("client_mismatch");if(!e.subject||!e.sessionId)throw new w("required_claim_missing");if(e.nonce!==t)throw new w("nonce_mismatch")}};function pe(r){return r.replace(/\/+$/u,"")}var Pn=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 js,RawMasterKeySource as Ys,deriveMasterKey as Xs,generateHexSeed as Js,computePassphraseVerifier as Zs}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as to}from"@safetech/inheriti-core-sdk/node";function As(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(a,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",r.environment),e(a,Object.assign({},s,{headers:o}))},n=r.business?void 0:_t({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 se(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:xr})}function _s(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=_t({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ae(new Ee(r.apiUrl,r.environment,r.getBearerToken,e),t)}function Cs(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=_t({apiUrl:t,getBearerToken:r.getBearerToken,transport:mn({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 Xe(new Qe(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as Ar,webcrypto as _r}from"node:crypto";import{canonicalInboxManifest as Cr,decodeInboxManifest as Tr,decodeInboxContentFrame as Dr,decodeInboxText as Mr,decryptInboxShare as kr,encodeInboxContentFrame as Ct,encodeInboxText as Or,encryptInboxShare as vn,inboxProtectedUnitCommitment as Nr,inboxTextMetadataDigest as bn,openInboxContent as Kr,sealInboxContent as Ur,signInboxFrame as Lr,unwrapInboxContentKey as qr,unwrapInboxShareKey as Gr,verifyInboxFrame as wn,wrapInboxContentKey as Fr,wrapInboxShareKey as Vr}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as zr}from"@safetech/inheriti-core-sdk/workers/inbox.node";var B=_r,_=B,x=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)},F=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),tt=async r=>new Uint8Array(await _.subtle.digest("SHA-256",Uint8Array.from(r))),Te=r=>Ar("sha256").update(r).digest("hex"),re=class{constructor(e,t=new zr){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),a=Cr(i),s=await tt(a),{contentKey:o,frame:d}=await Ur(Or(e.text),s,_),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:u}=await this.protectShares(t,d,s),g=await this.wrapRecipientKeys(t,o,s),b=await Vr(l,x(e.tenantKeyHex),s,i.tenantId,i.messageId,_);return{frame:Buffer.from(Ct(d)).toString("base64"),submission:{messageId:t.messageId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,expiresAt:e.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(a).toString("base64"),signature:Buffer.from(c).toString("base64"),tenantWrappedShareKey:Buffer.from(b).toString("base64"),recipients:g,shares:u}}}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:s,manifestDigest:o,senderPublicDer:d}=await this.verifyOpening(e,n),c=await this.recoverFrame(n,s,o,e.tenantKeyHex);if(t&&!F(t,await Nr(s,Ct(c),I(n.signature),_)))throw new Error("inbox_parent_unit_mismatch");i=await this.decryptText(n,c,s,o,d,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(s){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId)}catch{}throw s}let a=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:a}}async ack(e,t,n,i,a){for(let s=0;s<2;s++){a?.throwIfAborted();try{return await this.api.ackInboxMessage(e,t,n,i,a),a?.throwIfAborted(),"ACKNOWLEDGED"}catch(o){if(a?.throwIfAborted(),o instanceof U&&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:x(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:x(a.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await bn(_)}}async signFrame(e,t,n,i){let a=await _.subtle.importKey("pkcs8",I(n),"Ed25519",!1,["sign"]),s=await Lr(e,t,a,_),o=await _.subtle.importKey("spki",I(i),"Ed25519",!1,["verify"]);if(!await wn(e,t,s,o,_))throw new Error("inbox_identity_mismatch");return s}async protectShares(e,t,n){let i=await this.worker.split(Ct(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),a=_.getRandomValues(new Uint8Array(32)),s=[];for(let o=0;o<e.total;o++){let d=e.shareLayers[o];s.push({kind:"DATA",index:o,shareId:d.dataShareId,layerId:d.id,ciphertext:Buffer.from(await vn(i.dataShares[o],a,n,e.messageId,_)).toString("base64")}),s.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await vn(i.keyShares[o],a,n,e.messageId,_)).toString("base64")})}return{shareKey:a,shares:s}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let a=I(i.encryptionPublicKey);if(Te(a)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await _.subtle.importKey("spki",a,{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 Fr(t,s,n,_)).toString("base64")}}))}async verifyOpening(e,t,n){let i=I(t.canonicalManifest),a=Tr(i);if(a.tenantId!==e.identity.tenantId||a.conversationId!==e.conversationId||a.messageId!==e.messageId||a.expiresAtEpochMs<=Date.now()||!F(a.metadataDigest,n??await bn(_)))throw new Error("inbox_manifest_mismatch");let s=a.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!s||!F(s.encryptionKeyFingerprint,x(Te(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=I(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Te(o)||!F(a.senderSigningKeyFingerprint,x(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:a,manifestDigest:await tt(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let a=await Gr(I(e.tenantWrappedShareKey),x(i),n,t.tenantId,t.messageId,_),s=[],o=[],d=new Set;for(let l of e.shares){let u=`${l.kind}:${l.index}`;if(d.has(u))throw new Error("duplicate_inbox_share");d.add(u);let g=await kr(I(l.ciphertext),a,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,_);(l.kind==="DATA"?s:o).push(g)}if(s.length!==o.length||s.length<2)throw new Error("incomplete_inbox_shares");let c=await this.worker.reconstruct(s,o,{threshold:s.length,total:s.length,messageId:t.messageId,manifestDigest:n});return Dr(c)}async decryptText(e,t,n,i,a,s){return Mr(await this.decryptContent(e,t,n,i,a,s))}async decryptContent(e,t,n,i,a,s){let o=await _.subtle.importKey("spki",a,"Ed25519",!1,["verify"]);if(!await wn(n,t,I(e.signature),o,_))throw new Error("inbox_signature_invalid");let d=await _.subtle.importKey("pkcs8",I(s),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await qr(I(e.wrappedContentKey),d,i,_);return Kr(t,c,i,_)}};import{canonicalInboxManifest as Br,decodeInboxContentFrame as $r,decodeInboxFile as Hr,decryptInboxShare as Wr,encodeInboxContentFrame as Qr,encodeInboxFile as jr,encryptInboxShare as Sn,inboxFileMetadataDigest as En,sealInboxContent as Yr,unwrapInboxShareKey as Xr,wrapInboxShareKey as Jr}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var nt=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),a=await this.fileManifest(t,n,i),s=Br(a),o=await tt(s),d=jr(t.file),c;try{c=await Yr(d,o,B)}finally{d.fill(0)}let{contentKey:l,frame:u}=c,g=await this.signFrame(a,u,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let b=await this.worker.split(Qr(u),{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 D=B.getRandomValues(new Uint8Array(32)),m=[];for(let A=0;A<n.total;A++){let $=n.shareLayers[A];m.push({reference:{kind:"DATA",index:A,shareId:$.dataShareId,layerId:$.id},bytes:await Sn(b.dataShares[A],D,o,n.messageId,B)}),m.push({reference:{kind:"KEY",index:A,shareId:$.keyShareId,layerId:$.id},bytes:await Sn(b.keyShares[A],D,o,n.messageId,B)})}let y=await this.wrapRecipientKeys(n,l,o),N=await Jr(D,x(t.tenantKeyHex),o,a.tenantId,a.messageId,B);t.signal?.throwIfAborted();let C=await this.fileApi.stageInboxFile(t.conversationId,{messageId:n.messageId,senderDeviceId:i.deviceId,participantRevision:n.participantRevision,expiresAt:t.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(g).toString("base64"),tenantWrappedShareKey:Buffer.from(N).toString("base64"),recipients:y,shares:m.map(A=>A.reference)},t.signal);if(C.messageId!==n.messageId||C.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let A=0;A<m.length;A++){t.signal?.throwIfAborted();let $=m[A];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,$.reference.shareId,$.bytes,t.signal),t.onProgress?.(A+1,m.length,"UPLOADING")}t.signal?.throwIfAborted();let L=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(L.messageId!==n.messageId||L.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return L}async openFile(t){t.signal?.throwIfAborted();let n=await this.fileApi.openInboxFile(t.conversationId,t.messageId,t.identity.deviceId,t.signal),i,a;try{let{manifest:o,manifestDigest:d,senderPublicDer:c}=await this.verifyOpening(t,n,await En(B)),l=await this.recoverFileFrame(t,n,o,d);a=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=Hr(a),t.signal?.throwIfAborted(),await t.save(i),t.signal?.throwIfAborted()}catch(o){try{await this.fileApi.releaseInboxMessage(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId)}catch{}throw o}finally{a?.fill(0)}let s=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:s}}async fileManifest(t,n,i){let a=Date.parse(t.expiresAt);if(!Number.isSafeInteger(a)||a<=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:x(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:x(s.encryptionKeyFingerprint)})),expiresAtEpochMs:a,metadataDigest:await En(B)}}async recoverFileFrame(t,n,i,a){let s=await Xr(I(n.tenantWrappedShareKey),x(t.tenantKeyHex),a,i.tenantId,i.messageId,B),o=[],d=[],c=new Set;for(let u=0;u<n.shares.length;u++){t.signal?.throwIfAborted();let g=n.shares[u],b=`${g.kind}:${g.index}`;if(c.has(b))throw new Error("duplicate_inbox_share");c.add(b);let D=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,g.shareId,t.identity.deviceId,n.leaseId,t.signal),m=await Wr(D,s,a,i.messageId,g.kind==="DATA"?"data":"key",g.index,B);(g.kind==="DATA"?o:d).push(m),t.onProgress?.(u+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:a},t.signal,u=>t.onProgress?.(n.shares.length,n.shares.length,u.stage));return t.signal?.throwIfAborted(),$r(l)}};import{createHash as xn,webcrypto as Zr}from"node:crypto";import{canonicalInboxParentManifest as ei,decodeInboxParentManifest as ti,encodeInboxParentNormalFrame as ni,decodeInboxParentNormalFrame as ri,sealInboxParentNormalBody as ii,openInboxParentNormalBody as ai,wrapInboxParentNormalKey as si,unwrapInboxParentNormalKey as oi,signInboxParentNormalFrame as di,verifyInboxParentNormalFrame as Rn,encodeInboxText as ci,decodeInboxText as li}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var V=Zr,De=r=>xn("sha256").update(r).digest("hex"),rt=r=>Buffer.from(r).toString("base64"),it=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),a=this.validatePreparation(e,i),s=this.createManifest(e,i,a),o=await this.createSubmission(e,i,a,s);this.rememberSubmission(s.parentId,t,o);let d=await this.api.publishNormalInboxMessage(e.conversationId,o);return this.pending.delete(s.parentId),d}digestInput(e){return xn("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:x(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:x(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let a=ei(i),{contentKey:s,frame:o}=await ii(ci(e.text),i,V),d=await V.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await di(i,o,d,V),l=await V.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Rn(i,o,c,l,V))throw new Error("inbox_identity_mismatch");let u=await Promise.all(t.recipients.map(g=>this.wrapRecipientKey(g,s,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:rt(a),frame:rt(ni(o)),signature:rt(c),recipients:u}}async wrapRecipientKey(e,t,n){let i=I(e.encryptionPublicKey);if(De(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=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:rt(await si(t,a,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=ti(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(u=>u.memberId===e.identity.memberId&&u.deviceId===e.identity.deviceId);if(!i||!F(i.encryptionKeyFingerprint,x(De(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let a=I(t.senderSigningPublicKey);if(!F(n.senderSigningKeyFingerprint,x(De(a))))throw new Error("inbox_sender_key_mismatch");let s=ri(I(t.frame)),o=await V.subtle.importKey("spki",a,"Ed25519",!1,["verify"]);if(!await Rn(n,s,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 oi(I(t.wrappedContentKey),d,n,V),l=li(await ai(s,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 Cn,webcrypto as pi}from"node:crypto";import{canonicalInboxParentManifest as ui,decodeInboxParentManifest as mi,decodeInboxManifest as gi,encodeInboxParentNormalFrame as Ii,decodeInboxParentNormalFrame as hi,sealInboxParentNormalBody as yi,openInboxParentNormalBody as fi,wrapInboxParentNormalKey as Pi,unwrapInboxParentNormalKey as vi,signInboxParentNormalFrame as bi,verifyInboxParentNormalFrame as An,signInboxProtectedParent as wi,verifyInboxProtectedParent as _n,inboxProtectedUnitCommitment as Si,encodeInboxText as Ei,decodeInboxText as Ri}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var O=pi,at=r=>Buffer.from(r).toString("base64"),Me=r=>Cn("sha256").update(r).digest("hex"),st=class{constructor(e,t){this.api=e;this.child=t??new re(e)}pending=new Map;child;async send(e){let t=Cn("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 a=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(a.parentId,{digest:t,submission:a});let s=await this.api.publishInboxParent(e.conversationId,a);return this.pending.delete(a.parentId),s}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let t=e.segments.filter(b=>"protectedText"in b).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(b=>"text"in b))throw new Error("invalid_inbox_parent_segments");let i=await this.api.getNormalInboxSendPreparation(e.conversationId),a=this.validateSender(e,i),s=e.parentId??i.parentId,{protectedUnits:o,manifestUnits:d}=await this.prepareChildren(e,i,a),c=this.parentManifest(e,i,a,s,n,d),{frame:l,signature:u,recipients:g}=await this.signAndWrap(e,i,a,c);return{parentId:s,idempotencyKey:s,senderDeviceId:a.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:at(ui(c)),signature:at(u),frame:l,recipients:g,protectedUnits:o}}async prepareChildren(e,t,n){let i=[],a=[],s=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=gi(I(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let u=await Si(l,I(c.frame),I(c.submission.signature),O);i.push({position:o,frame:c.frame,child:c.submission}),a.push({unitId:c.submission.messageId,position:o,commitment:u});try{e.onProgress?.(i.length,s)}catch{}}return{protectedUnits:i,manifestUnits:a}}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(a=>!n.recipients.some(s=>s.memberId===a.memberId&&s.deviceId===a.deviceId&&F(a.encryptionKeyFingerprint,x(s.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,t,n,i,a,s){return{mode:a,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:i,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:x(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:x(o.encryptionKeyFingerprint)})),protectedUnits:s}}async signAndWrap(e,t,n,i){let a=await O.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),s=await O.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(i.mode==="PROTECTED")return{signature:await this.signProtectedParent(i,a,s),recipients:this.recipientReferences(t)};let{frame:o,signature:d,contentKey:c}=await this.sealMixedParent(e,i,a,s);return{frame:o,signature:d,recipients:await this.wrapRecipients(t,c,i)}}async signProtectedParent(e,t,n){let i=await wi(e,t,O);if(!await _n(e,i,n,O))throw new Error("inbox_identity_mismatch");return i}async sealMixedParent(e,t,n,i){let a=e.segments.map((d,c)=>"text"in d?{text:d.text}:{unitId:t.protectedUnits.find(l=>l.position===c).unitId}),s=await yi(Ei(JSON.stringify(a)),t,O),o=await bi(t,s.frame,n,O);if(!await An(t,s.frame,o,i,O))throw new Error("inbox_identity_mismatch");return{frame:at(Ii(s.frame)),signature:o,contentKey:s.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 a=I(i.encryptionPublicKey);if(Me(a)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await O.subtle.importKey("spki",a,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:at(await Pi(t,s,n,O))}}))}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),a=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:a}}async verifyOpening(e,t){let n=mi(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||!F(n.commitment,x(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||!F(n.encryptionKeyFingerprint,x(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||!F(t.senderSigningKeyFingerprint,x(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return O.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await _n(t,I(e.signature),n,O))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 a=hi(I(t.frame));if(!await An(n,a,I(t.signature),i,O))throw new Error("inbox_signature_invalid");let s=await O.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await vi(I(t.wrappedContentKey),s,n,O),d=JSON.parse(Ri(await fi(a,o,n,O)));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((a,s)=>{if(!a||typeof a!="object"||Array.isArray(a))throw new Error("invalid_inbox_parent_body");let o=a;if(typeof o.text=="string"&&Object.keys(o).length===1)return{text:o.text};let d=n.protectedUnits.find(c=>c.position===s);if(!d||o.unitId!==d.unitId||Object.keys(o).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:d.unitId,position:s,status:t.protectedUnits.find(c=>c.unitId===d.unitId).status}});if(n.protectedUnits.some(a=>!i[a.position]||!("unitId"in i[a.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(a=>"unitId"in a&&a.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let i=t.protectedUnits.find(a=>a.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,zs as DataAssetDefinitionService,U as ElementsApiRequestFailed,se as ElementsClient,ve as GuidedCreateRecoveryError,Pe as GuidedPlanCreator,Se as HttpAutomationRevealApiPort,ce as HttpElementsApiPort,hn as HttpOperatorAuthTransport,Qe as HttpPlanEditPort,Ee as HttpQuickPlanPort,v as InvalidPlanDeclaration,M as InvalidPlanMaterial,Ne as MasterKeyRelayCancellationFailed,Oe as MasterKeyRelayExpired,ke as MasterKeyRelayTimedOut,j as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,he as MemoryKeyVault,ye as MemoryStatePort,nt as NodeInboxFile,it as NodeInboxNormal,st as NodeInboxParent,re as NodeInboxText,w as OAuthProtocolError,fn as OperatorAuthClient,_e as OperatorAuthError,Ce as OperatorReauthenticationRequired,Pn as OperatorSessionController,pt as PLAN_CREATION_SERVER_STAGES,js as PassphraseMasterKeySource,to as PlanAssetDeclaration,te as PlanRequestFailed,Ae as QuickPlanCreator,Xe as QuickPlanEditor,Ys as RawMasterKeySource,z as RelayMasterKeySource,dt as StaticMasterKeyResolver,Ze as SystemOAuthClock,Je as WebOAuthCrypto,Zs as computePassphraseVerifier,Ke as createMasterKeyResolver,Sr as createNodeAutomationRevealClient,As as createNodeElementsClient,_s as createNodeQuickPlanCreator,Cs as createNodeQuickPlanEditor,xr as decodeAssetContainer,Xs as deriveMasterKey,Js as generateHexSeed,Ie as masterKeyRefFor,X as masterKeyRefKey,xt as oauthErrorCode,dr as selectBusinessOrganization,vt as unwrapDekWithMasterKey,J as validatePlanCreationInput,ae as validatePlanCreationMaterial};
1
+ import{createNodeSharedConfigurationSdk as _t,decodeAssetContainer as Ar}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Tn,generateRSAOAEPKeyPair as Dn}from"@safetech/inheriti-core-sdk/crypto";var ke=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Oe=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 Dn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let a=await this.options.api.startRelaySession(n),s=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(m=>new Promise(y=>setTimeout(y,m))),c=!0,l=!1,u,g=()=>u??=(async()=>{let m=new AbortController,y,N=new Promise((C,L)=>{y=setTimeout(()=>{m.abort(),L(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(a.sessionId,m.signal),N])}finally{clearTimeout(y)}})(),b,D=new Promise((m,y)=>{b=()=>{c&&g().catch(()=>{}),y(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",b,{once:!0})});D.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(a),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let m=await Promise.race([this.options.api.readRelaySession(a.sessionId,e),D]);if(m.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(m.status==="DELIVERED"&&m.sealedMasterKey){let y=(await Tn(m.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(y))throw new Error("invalid_master_key_material");return y}if(m.status==="EXPIRED")throw new Oe(a.sessionId);await Mn(d,s,e)}throw new ke(a.sessionId)}catch(m){if(c&&(!l||e?.aborted))try{await g()}catch(y){if(e?.aborted)throw new Ne(y)}throw m}finally{b&&e?.removeEventListener("abort",b)}}};async function Mn(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 a=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",a,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",a))})}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||ot(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(kn(e,r.applicationId)){let i=await r.source?.resolve();return i||ot(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return ot(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function kn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ot(r,e,t,n,i){if((await e()).relayAvailable)return new z({...r.relay,api:On(r.api,t)}).resolve(n,i)}function On(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 X(r){return`${r.system}:${r.contextId}`}function he(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:${X(t)}`);this.ref=t;this.name="MasterKeyRequired"}},dt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(X(e),t),this}async resolve(e){return this.sources.get(X(e))?.resolve()}};var Ie=class{keys=new Map;async store(e,t){let n=X(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(X(e))?.slice()}async remove(e){let t=X(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"},f=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 qe=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],lt={"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"]},pt=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],v=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function ae(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new M("plan_material_field_unknown");if(ct(r.dataShards,"data_shards_invalid"),ct(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ct(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new M("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new M("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new M("material_operation_invalid")}function ct(r,e){if(!Array.isArray(r))throw new M(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new M(e);if(t.data!==void 0&&typeof t.data!="string")throw new M(e)}}function J(r){if(ie(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Un(r.idempotencyKey))throw new v("idempotency_key_invalid");if(!r.name?.trim())throw new v("plan_name_required");if(!r.assets.length)throw new v("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 v("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!qe.includes(t.type))throw new v("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new v("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 v("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new v("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(a=>!a.trim()))throw new v("asset_field_names_invalid");if(Nn(t.matchOrigins),!t.isBinary){let a=lt[t.type];if(!a||i.some(s=>!a.includes(s)))throw new v("asset_field_name_not_canonical")}}if(!r.participants.length)throw new v("participants_required");for(let t of r.participants){if(ie(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Dt(t.routingEmail))throw new v("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new v("participant_relationships_invalid")}Kn(r)}function Nn(r){if(r===void 0)return;if(!r.length)throw new v("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new v("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new v("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof v?n:new v("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new v("asset_match_origins_duplicated")}function Kn(r){let e=r.policy;if(e&&ie(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new v("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){ie(e.authentication,["mode"],"plan_authentication_field_unknown");let a=e.authentication.mode;if(a!==void 0&&a!=="EXCLUSIVE"&&a!=="ALL_REQUIRED")throw new v("authentication_mode_invalid")}if(e.moderation){ie(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let a=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(a.length===0)throw new v("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>a.length))throw new v("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new v("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(!Dt(t.subjectEmail))throw new v("dms_subject_invalid");if(!r.participants.some(a=>Tt(a.routingEmail)===Tt(t.subjectEmail)))throw new v("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 v("dms_countdown_invalid")}function Un(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 Dt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Tt(r){return r.normalize("NFC").trim().toLowerCase()}function ie(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new v(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"),J(e),Ge(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,a={}){J(t);let s=await this.checkpoints.load(e);if(!s)throw new ve("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Mt(t))throw new ve("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(a.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Ge(a.signal),a.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:a.signal});Ge(a.signal),a.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:a.signal});Ge(a.signal),ae(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return a.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 Mt(e),serverStage:t.stage})}},ve=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Mt(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Ge(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function kt(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 Ln(r){let e=r?.status;return e===400||e===401||e===403}async function Ot(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(a){if(!Ln(a))throw a}return r.releaseRevealMaterial(e,t)}function qn(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?Fn(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Gn.has(r.stage)?"ENDED":"CONTINUING"}var Gn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Fn(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var ut=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},T=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Lt(r,e,t={}){if(t.signal?.aborted)throw E();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Nt(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw E();let a=t.idempotencyKey??crypto.randomUUID(),s;try{s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?d:Nt(c.id)}let o;try{if(t.signal?.aborted)throw E();let d=await zn(r,s,t);if(t.signal?.aborted||(Z(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw E();let c=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id),t.signal?.aborted))throw E();let l;try{l=await Wn(r,d,jn(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(Z(t,"RECONSTRUCTING",d),t.signal?.aborted))throw E();try{o=await r.reconstructPlanMaterial(l)}catch(g){throw t.signal?.aborted?E():(await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Hn(g)}),g)}if(t.signal?.aborted)throw E();let u=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(Z(t,"OPEN",u),t.signal?.aborted))throw E();return new gt(r,u,n,o,t.signal)}catch(d){throw o?.fill(0),await qt(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function Nt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Vn=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 E();if(t.onSession?.(n),t.onProgress?.({phase:qn(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Vn.has(n.stage))throw new mt(n.stage);await It(t.pollIntervalMs??1500,t.signal),n=await Y(()=>r.getReveal(e.id,t.signal),t.signal)}}var mt=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function Z(r,e,t){r.onProgress?.({phase:e,session:t})}function It(r,e){return e?.aborted?Promise.reject(E()):new Promise((t,n)=>{let i=setTimeout(s,Math.max(0,r)),a=()=>{clearTimeout(i),n(E())};function s(){e?.removeEventListener("abort",a),t()}e?.addEventListener("abort",a,{once:!0})})}var gt=class{constructor(e,t,n,i,a){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=a?()=>{this.close("CANCELED").catch(()=>{})}:void 0,a&&this.abortListener&&a.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new ut;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 T("asset_selector_invalid");if(!this.client.assetDecoder)throw new T("asset_decoder_required");let n=e.map(({selector:a,options:s={}})=>{let o=Bn(a),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new T("asset_not_found");if(d.isBinary)throw new T("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new T("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:s}}),i=[];try{for(let s of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let a=n.map(s=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===s.asset.id||d.id===s.assetCode);if(!o)throw new T("asset_value_invalid");return{selector:s.selector,value:$n(o.data,s.field,s.asset.type)}});await t(a)}catch(a){throw await Promise.all(i.map(s=>this.reportAction(s.id,"FAILED",Kt(a)))),a}await Promise.all(i.map(a=>this.reportAction(a.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new T("asset_selector_invalid");if(!this.client.assetDecoder)throw new T("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new T("asset_not_found");if(!n.isBinary)throw new T("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),a;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new T("asset_value_invalid");a=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:a})}catch(s){throw await this.reportAction(i.id,"FAILED",Kt(s)),s}finally{a?.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=qt(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 Bn(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new T("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new T("asset_selector_invalid");return{asset:r.asset,field:r.field}}function $n(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new T("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new T("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?lt[t]:void 0)?.includes(e))return"";throw new T("asset_value_invalid")}return n[e]}function Kt(r){if(r instanceof T)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 Hn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Wn(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 Fe;let c=await Y(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(Ut(c,i.id,e.planId),!c.shares.includes(i.data))throw new H;Z(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await Y(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw E();if(!l?.trim())throw new H;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw E();return{...t,shares:t.shares.filter(u=>u!==i).concat(c.shares.map((u,g)=>({id:`${c.id}:${g}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new H;if(n.signal?.aborted)throw E();return await r.distributeRevealCustodianShare(e.id),Z(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let a=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;a.status==="PENDING"||a.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),Z(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await It(n.pollIntervalMs??1500,n.signal),a=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(a.status==="CLAIMED"&&a.deviceType==="SK_PRO"){if(!n.proDevice)throw new Fe;if(!a.shareId||!a.deviceId)throw new H;Z(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Y(()=>n.proDevice.read({shareId:a.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw E();if(Ut(d,a.shareId,e.planId),d.deviceId!==a.deviceId)throw new H;if(await r.collectRevealCustodianShare(e.id,a.shareId),n.signal?.aborted)throw E();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(a.status!=="CLAIMED"||a.deviceType!=="SK_MOBILE")throw new H;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(s),Z(n,"WAITING_FOR_CUSTODIAN",s),n.signal?.aborted)throw E();await r.requestRevealCustodianRelease(e.id);let o=await Qn(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 Ut(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 H}async function Y(r,e){if(e?.aborted)throw E();if(!e)return r();let t,n=new Promise((i,a)=>{t=()=>a(E()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw E();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function Qn(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 a=i;if(a.shares?.length)return a;throw new H}if(Date.now()>=n)throw new ht;await It(t.pollIntervalMs??1500,t.signal)}}var H=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Fe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},ht=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function jn(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function qt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(s){if(!Yn(s))throw s}return}let n=new AbortController,i,a=new Promise((s,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let s=await Promise.race([r.closeReveal(e,t,n.signal),a]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(s.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(s){if(s?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:s}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Yn(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function E(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var se=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new Ie,this.state=t.state??new ye,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Zn(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new f;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new f;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new f;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return J(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new f;return ae(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new f;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new f;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 Jn(i);let a=await this.masterKeys?.resolve(e,t,n);if(!a)throw new j(e);return await this.keyVault.store(e,Xn(a)),a}async prepareReveal(e,t,n){if(!this.api)throw new f;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,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 f;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=he(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 f;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new f;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new f;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new f;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new f;return this.api.getReveal(e,t)}openReveal(e,t){return Lt(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let a=await n(i);return await i.close("COMPLETED"),a}catch(a){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),a}}async releaseRevealMaterial(e,t){if(!this.api)throw new f;return Ot(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new f;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new f;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new f;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new f;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new f;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new f;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new f;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new f;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new f;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new f;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new f;return kt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new f;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new f;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new f;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new f;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new f;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new f;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let 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 a=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),s=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:a.concat(s,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 f;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 yt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new j({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},yt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Xn(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Jn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Zn(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 er=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],tr=["DIRECT","GOVERNED"],Ft=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],nr=["ACTIVE","REVOKED"],rr=["SK_MOBILE"],ir=["ACTIVE","INACTIVE"],ar=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Vt(r){let e=k(r);return{items:q(e.items).map(Bt),nextCursor:e.nextCursor===null?null:I(e.nextCursor,"nextCursor")}}function zt(r){let e=k(r);return{total:W(e.total,"total"),items:q(e.items).map(t=>{let n=k(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:I(n.id,"log.id"),planId:I(n.planId,"log.planId"),tenantId:I(n.tenantId,"log.tenantId"),event:I(n.event,"log.event"),occurredOn:I(n.occurredOn,"log.occurredOn"),status:ee(n.status),title:I(n.title,"log.title"),details:q(n.details).map(i=>{let a=k(i);return{label:I(a.label,"log.detail.label"),value:I(a.value,"log.detail.value")}})}})}}function Ve(r){let e=k(r),t=Bt(e),n=k(e.source),i=I(n.kind,"source.kind");return{...t,assets:q(e.assets).map(a=>{let s=k(a);return{id:I(s.id,"asset.id"),code:ee(s.code),type:K(I(s.type,"asset.type"),qe),name:I(s.name,"asset.name"),isBinary:or(s.isBinary,"asset.isBinary"),fieldNames:q(s.fieldNames).map(o=>I(o,"asset.fieldNames")),fileName:ee(s.fileName),mimeType:ee(s.mimeType),size:s.size===void 0||s.size===null?void 0:W(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:q(s.matchOrigins).map(o=>I(o,"asset.matchOrigins"))}}),participants:q(e.participants).map(a=>{let s=k(a);return{id:I(s.id,"participant.id"),displayName:I(s.displayName,"participant.displayName"),relationships:q(s.relationships).map(o=>K(I(o,"relationship"),Ft)),lifecycle:K(I(s.lifecycle,"participant.lifecycle"),nr)}}),revealPolicy:(()=>{let a=k(e.revealPolicy);return{masterKeyRelease:K(I(a.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:K(I(a.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let a=k(e.dms);return{subjectEmail:I(a.subjectEmail,"dms.subjectEmail"),countdownDays:W(a.countdownDays,"dms.countdownDays"),countdownHours:W(a.countdownHours,"dms.countdownHours"),countdownMinutes:W(a.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:K(I(n.system,"source.system"),["INHERITI_BUSINESS"]),status:K(I(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function be(r){let e=k(r);return{operationId:I(e.operationId,"operationId"),stage:K(I(e.stage,"stage"),pt),outcome:K(I(e.outcome,"outcome"),ar),planId:ee(e.planId),lastErrorCode:ee(e.lastErrorCode),participants:e.participants===void 0?void 0:q(e.participants).map(t=>{let n=k(t);return{clientParticipantRef:I(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:I(n.planParticipantId,"planParticipantId"),relationships:q(n.relationships).map(i=>sr(I(i,"relationship"),Ft))}})}}function Bt(r){let e=k(r),t=k(e.assetSummary),n=k(e.governance),i=k(e.participantSummary);return{id:I(e.id,"id"),name:I(e.name,"name"),description:ee(e.description),status:K(I(e.status,"status"),er),createdAt:I(e.createdAt,"createdAt"),configuredAt:ee(e.configuredAt),assetSummary:{count:W(t.count,"assetSummary.count"),types:q(t.types).map(a=>K(I(a,"assetType"),qe)),names:Gt(t.names).map(a=>I(a,"assetSummary.names"))},governance:{mode:K(I(n.mode,"governance.mode"),tr),minimumApprovals:W(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:W(i.owners,"owners"),mergers:W(i.mergers,"mergers"),moderators:W(i.moderators,"moderators")},authentication:Gt(e.authentication).map(a=>{let s=k(a);return{id:K(I(s.id,"authentication.id"),rr),status:K(I(s.status,"authentication.status"),ir)}})}}function K(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function sr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function k(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Gt(r){return r==null?[]:q(r)}function q(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function I(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function ee(r){return r==null?void 0:I(r,"optional")}function W(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function or(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var ue=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function $t(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function dr(r,e){if(!e){if(r.length===0)throw new 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 cr(r){let e=S(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:P(e.participantRevision,1),createdAt:G(e.createdAt)}}function Ht(r){let e=S(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(cr),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0),unreadCount:P(e.unreadCount,0),readThroughSequence:P(e.readThroughSequence,0)}}function Wt(r){let e=S(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:p(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:P(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=S(t);return{unitId:p(n.unitId),position:P(n.position,0),commitment:p(n.commitment),status:p(n.status)}})}}function ft(r){let e=S(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:P(e.sequence,1),status:e.status}}function Qt(r){let e=S(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:P(e.participantRevision,1),recipients:e.recipients.map(Pt)}}function jt(r){let e=S(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=S(t);return{parentId:p(n.parentId),sequence:P(n.sequence,1),senderMemberId:p(n.senderMemberId),senderDeviceId:p(n.senderDeviceId),participantRevision:P(n.participantRevision,1),createdAt:G(n.createdAt)}}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0),unreadCount:P(e.unreadCount,0),readThroughSequence:P(e.readThroughSequence,0)}}function Yt(r){return{readThroughSequence:P(S(r).readThroughSequence,0)}}function Xt(r){return{clearedThroughSequence:P(S(r).clearedThroughSequence,0)}}function Jt(r){let e=S(r);return{parentId:p(e.parentId),sequence:P(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:P(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function S(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function p(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function G(r){let e=p(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function P(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Pt(r){let e=S(r);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:P(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function me(r){let e=S(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:G(e.createdAt),updatedAt:G(e.updatedAt)}}function ze(r){let e=S(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:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:G(e.createdAt),updatedAt:G(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=S(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:p(n.senderMemberId),createdAt:G(n.createdAt)}}return t}function Zt(r){let e=S(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(ze),total:e.total,limit:e.limit,offset:e.offset}}function en(r){let e=S(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=Pt(t);return{memberId:n.memberId,name:p(S(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function tn(r){let e=S(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=S(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(n.memberId),name:p(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:p(S(n.profilePicture).url)}}}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function nn(r){let e=S(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:p(e.conversationId),messageId:p(e.messageId),participantRevision:P(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Pt),shareLayers:e.shareLayers.map(t=>{let n=S(t),i=p(n.id),a=p(n.dataShareId),s=p(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:p(n.contractAddress),dataShareId:a,keyShareId:s};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:a,keyShareId:s};throw new Error("invalid_inbox_response")})}}function Be(r){let e=S(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:p(e.messageId),status:e.status}}function rn(r){let e=S(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=S(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:p(n.id),status:n.status,senderMemberId:p(n.senderMemberId),senderDeviceId:p(n.senderDeviceId),createdAt:G(n.createdAt),updatedAt:G(n.updatedAt),expiresAt:G(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(a=>{let s=S(a);if(s.status!=="UNREAD"&&s.status!=="LEASED"&&s.status!=="CONSUMED"&&s.status!=="EXPIRED"&&s.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:p(s.memberId),status:s.status}})),i}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0)}}function an(r){let e=S(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:G(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let n=S(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:p(n.shareId),layerId:p(n.layerId),ciphertext:p(n.ciphertext)}})}}function sn(r){let e=S(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:G(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let n=S(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:p(n.shareId),layerId:p(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 U=class extends Error{constructor(t,n,i,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ce=class{constructor(e,t,n,i,a){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=a?Object.freeze({...a}):void 0}business;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null: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 ze(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return ze(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 Zt(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 en(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 tn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return nn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return ft(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 a=i.size?`?${i}`:"";return Ht(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${a}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let a=new URLSearchParams({deviceId:n});return Wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return Xt(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 a=i.size?`?${i}`:"";return jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${a}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let a=new URLSearchParams({deviceId:n});return Jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return Yt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,a){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let s=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(s,"PUT",i,a),d=await $e(o,a);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new U(o.status,oe(d),de(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return sn(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,a,s){let o=new URLSearchParams({deviceId:i,leaseId:a}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,c=await this.requestBinary(d,"GET",void 0,s);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 u=c.body.getReader(),g=[],b=0;try{for(;;){s?.throwIfAborted();let y=await u.read();if(y.done)break;if(b+=y.value.length,b>14*1024*1024)throw new Error("invalid_inbox_share_size");g.push(y.value)}}catch(y){throw await u.cancel().catch(()=>{}),y}let D=new Uint8Array(b),m=0;for(let y of g)D.set(y,m),m+=y.length;return D}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 a=i.size?`?${i}`:"";return rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${a}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return an(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,a){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,a)}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($t)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return Vt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ve(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 zt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){J(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 ae(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,...a}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,a,s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken();s?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[b,D]of Object.entries(a??{}))d.set(b,D);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};s&&(l.signal=s);let u=await this.transport(new URL(e,c),l);s?.throwIfAborted();let g=await $e(u,s);if(s?.throwIfAborted(),!u.ok)throw new U(u.status,oe(g),de(g),u.headers.get("x-request-id")??void 0);if(!g.ok||g.result===void 0)throw new U(u.status,oe(g),de(g),u.headers.get("x-request-id")??void 0);return g.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let a=await this.getBearerToken();i?.throwIfAborted();let s=new Headers({"x-elements-environment":this.environment});a&&s.set("authorization",`Bearer ${a}`),this.business?.organizationId&&s.set("x-organization-id",this.business.organizationId),n&&s.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:s,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await $e(d,i);throw new U(d.status,oe(c),de(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});n&&i.set("authorization",`Bearer ${n}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,a),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),o=await $e(s);if(!s.ok||!o.ok)throw new U(s.status,oe(o),de(o),s.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new U(400,"organization_selection_required")}};async function $e(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 yr}from"@safetech/inheriti-core-sdk/node";async function vt(r,e){if(!e)throw new Error("master_key_required");let t=lr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=pr(r),a=i.slice(0,12),s=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},n,s);return ur(new Uint8Array(o))}function lr(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function pr(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function ur(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 on("plan_key_unwrap_failed",()=>vt(e.planKey,t)),i=await crypto.subtle.importKey("raw",bt(n),{name:"AES-GCM"},!1,["decrypt"]),a=[],s=[];for(let o of e.shares){let d=await on("plan_share_decryption_failed",()=>Ir(o.data,i));hr(o.shareType)?s.push(d):a.push(d)}try{return await this.processor().reconstruct(a,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new He("plan_share_reconstruction_failed",gr(o))}}},He=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},mr=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function gr(r){let e=r instanceof Error?r.message:void 0;if(e)return mr.has(e)?e:void 0}async function on(r,e){try{return await e()}catch{throw new He(r)}}function hr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function Ir(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=bt(r.slice(0,t)),i=bt(r.slice(t+1)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(a)}function bt(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(()=>yr(e))}};var Se=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 Ve(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,...a}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,!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,a,s){s?.throwIfAborted();let o=await this.getAutomationBearerToken();if(s?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...a});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:s});s?.throwIfAborted();let l;try{l=await c.json()}catch{s?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new U(c.status,l&&oe(l),l&&de(l));return l?.result}};var x={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}},Ee=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,a){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n,...a?{description:a}:{}},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",dn(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",dn(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(x.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(x.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(x.relayFailed);return n}async request(e,t,n,i){let a=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),s=await this.getBearerToken();if(!s)throw new Error(x.reauthenticationRequired);a.set("authorization",`Bearer ${s}`),i!==void 0&&a.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,c=await this.transport(new URL(d,o),{method:n,headers:a,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 dn(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var Re=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){xe(e.signal),Pr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return xe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){xe(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(xe(e.signal),!i.custodianPair)throw new M("custodian_share_required");let a=wt(i.keyShards),s=await this.sealer.encryptShares(a,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(wt(i.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares(wt(i.backupShards),s.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,s.symmetricKeyBase64);return xe(e.signal),{protectionProtocol:i.protocol,validatorShares:St(s.encryptedShares),dataShards:St(o.encryptedShares),backupShards:St(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:fr(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:Et(n.encryptedShares[0]),dataShard:Et(n.encryptedShares[1])}}};function wt(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function St(r){return r.map(Et)}function Et(r){return{id:r.id,data:r.encryptedData}}function fr(r,e){let t={};for(let n of r){let i=e.assets.find(a=>a.clientAssetRef===n.id);if(!i)throw new M("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 Pr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new M("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new M("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new M("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 M("plan_secrets_declaration_mismatch")}}function xe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function cn(r,e,t,n,i,a,s){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(x.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new z({api:{startRelaySession:b=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,b),readRelaySession:b=>i.readRelaySession(r.organizationId,b)}}),u=new Re(a,l);s?.("encrypting");let g=await u.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return s?.("generating_shares"),u.generateShares({planId:r.planId,declaration:c,encrypted:g})}import{PlanAssetDeclaration as vr}from"@safetech/inheriti-core-sdk/node";function ln(r){let e=xt({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function xt(r){if(!r.assets.length)throw new v("assets_required");let e=r.assets.map(a=>{if(a.meta.isMedia!==!0)return;let s="data"in a.secret?a.secret.data:void 0,o;if(s instanceof Blob&&(o=s.size),typeof s=="string")try{o=atob(s).length}catch{throw new v("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new v("binary_asset_metadata_invalid");return o}),t=vr.create(r.assets.map(({type:a,meta:s})=>({type:a,meta:s}))),n=t.complete(Object.fromEntries(t.entries.map((a,s)=>[a.id,r.assets[s].secret]))),i={idempotencyKey:r.planId,name:r.title,assets:n.map((a,s)=>{let o=a.meta.isMedia===!0;return{clientAssetRef:a.id,type:a.type,name:a.meta.name,fieldNames:o?[]:Object.keys(a.secret),isBinary:o,fileName:a.meta.fileName,mimeType:a.meta.mimeType,size:e[s]}}),participants:[]};return{assets:n,plan:i}}async function un(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 pn(new Uint8Array(await i.arrayBuffer())):i]))})));return pn(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 pn(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(s=>!s?.meta?.name?.trim()))throw new Error(x.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(x.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(x.invalidShares);let n=await un(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(x.reconciliationRequired);return i.promise}let a=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:a});try{return await a}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let i=xt({planId:e.planId,title:e.title,assets:e.assets}),a=this.material.get(e.planId);if(a&&(a.fingerprint!==t||a.masterKeySource!==e.masterKeySource))throw new Error(x.reconciliationRequired);let s=await this.statusOrMissing(e.organizationId,e.planId);if(We(s))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(s&&!a)throw new Error(x.reconciliationRequired);if(!s&&a)throw new Error(x.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(x.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(x.invalidMasterKeyContext);if(!s){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(s=await this.statusOrMissing(e.organizationId,e.planId),!s)throw l}}s??=await this.port.status(e.organizationId,e.planId);let d=a?.encrypted??await cn(e,i,o,s,this.port,this.coreSdk,n);a||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(!We(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return We(c)&&this.material.delete(e.planId),{planId:e.planId,status:We(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(x.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 We(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var Qe=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 a=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(a))throw new Error("invalid_plan_edit_candidates");return a}async context(e,t){let 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 a=new Map;for(let s of i.participants){if(!s||typeof s.id!="string"||!s.id||typeof s.displayName!="string"||!Array.isArray(s.relationships)||!s.relationships.every(o=>typeof o=="string")||typeof s.lifecycle!="string")throw new Error("invalid_plan_edit_participants");s.lifecycle==="ACTIVE"&&s.relationships.includes("MODERATOR")&&a.set(s.id,s.displayName)}return a}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(x.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(x.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(x.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,a){let s=await this.getBearerToken();if(!s)throw new Error(x.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${s}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),a&&o.set("idempotency-key",a);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),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)}),u={};try{u=await l.json()}catch{}if(!l.ok||u.ok!==!0){let g=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new te(l.status,g||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(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 je=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),a=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!a)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let s=this.revealedAssets,o=s?.organizationId===e.organizationId&&s.planId===e.planId&&s.editId===e.editId&&s.expiresAt>Date.now();s&&!o&&(this.revealedAssets=void 0);let d=a.masterKeyEncrypted?e.masterKey??(o?s.masterKey:void 0):void 0;a.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?s.assets:await this.revealAssets(e,d,a.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(l.map(u=>u.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:a,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 a=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),s=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=m=>{m!==o&&(o=m,i?.(m))},c=m=>{if(m.processId!==e.editId||m.planId&&m.planId!==e.planId)return;switch(m.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let y=this.approvalError(m);if(y?.startsWith("edit_authentication_")&&d("pending_auth"),y?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!m.moderatorParticipants||m.requiredModeratorApprovals===void 0||!m.approvalProcess)return;let N=m.moderatorParticipants.map(C=>C.memberId??C.userId);N.some(C=>typeof C!="string"||!C)||new Set(N).size!==N.length||i?.(o,{requiredApprovals:m.requiredModeratorApprovals,approvedModerators:m.approvalProcess.approvedModerators,moderators:m.moderatorParticipants.map((C,L)=>{let A=N[L],$=C.flows.filter(ge=>ge.status==="PENDING"&&ge.expiresAt&&Number.isFinite(ge.expiresAt.getTime())).map(ge=>ge.expiresAt.getTime());return{id:A,displayName:s.get(A)||"Moderator",status:C.status,expiresAt:$.length?new Date(Math.min(...$)).toISOString():void 0}})})},l=await a.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 a.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let u=await a.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");c(u),this.assertApprovalOutcome(e.planId,u);let g=u?.status;if(g!=="READY_TO_REVEAL"&&g!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let b=null,D={onRevealed:m=>{b=m},onViewUpdate:c,onRevealStepUpdate:(m,y)=>{if(y==="IN_PROCESS")switch(m){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(n&&(D.onCustodianShareRequired=async(m,y)=>{switch(y.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let N=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),N==="SK_MOBILE")return a.distributeCustodianShareViaMobile(y.planId);if(N!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let C=e.proDevice;try{this.assertNotAborted(e.signal);let L=await a.getCustodianShareData(m);this.assertShare(L,y.planId),d("connecting_safekey_pro");let{deviceId:A}=await C.write(L,e.signal);if(this.assertNotAborted(e.signal),!A?.trim())throw new Error("custodian_share_unavailable");await a.recordCustodianShareClaim(y.planId,L.id,A,"SK_PRO"),this.assertNotAborted(e.signal),await a.markCustodianShareAsCollected(m,L.id);return}finally{C.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let N=e.proDevice;try{if(this.assertNotAborted(e.signal),!y.shareId||!y.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let C=await N.read({shareId:y.shareId,planId:y.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(C,y.planId,y.shareId),C.deviceId!==y.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:C.shares}}finally{N.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),g==="REVEALED"?await a.resumeReveal(e.editId,D,t):await a.openRevealWindow(e.editId,{timeoutMinutes:10},D,t),this.assertNotAborted(e.signal),!b)throw new Error("edit_assets_unavailable");return b}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 br=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))),Ye=class{constructor(e,t,n,i){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=i}async saveAssets(e,t,n,i,a,s){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,i);s?.("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(s?.("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:a,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,a,l,o,d,s)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let 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 a=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),dataShards:i.dataShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),backupShards:i.backupShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,a))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let s=await this.port.status(e.organizationId,e.editId);return s.id!==e.editId||s.planId!==e.planId||s.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,a),await this.port.commit(e.organizationId,e.planId,a),await this.isCommitted(e,a)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let 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 a=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),s={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:a,configuration:s}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,n,i,a,s){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,s?.(l))};try{await i.execute(a,{onLocalProcessUpdated:d})}catch(c){try{if(s?.("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&&s?.(o),c}try{if(s?.("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(br(t.assetsMetadata)),a=await globalThis.crypto.subtle.digest("SHA-256",i),s=Array.from(new Uint8Array(a),c=>c.toString(16).padStart(2,"0")).join("");if(n.assetsMetadataHash!==s)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 Xe=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new je(e,t,n),this.reconfiguration=new Ye(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),a=i.find(s=>s.id===t);if(!a)throw new Error("edit_asset_not_found");return structuredClone(a)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=a.findIndex(l=>l.id===e.assetId);if(s<0)throw new Error("edit_asset_not_found");let o=a[s];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},c=a.map((l,u)=>u===s?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:a}=await this.assetAccess.loadAssets(e,t),s=ln({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(a.map(d=>d.id)).has(s.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,a.concat(s),n.withCustodian,i,s.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function mn({apiUrl:r,organizationId:e,planId:t,editId:n,environment:i,transport:a}){return(s,o)=>{let d=new URL(s instanceof Request?s.url:s.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 a(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let u=wr(l,d.searchParams,t,n),g=new Headers(o?.headers);g.set("x-organization-id",e),g.set("x-elements-environment",i);let b=c.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return a(new URL(b,c),Object.assign({},o,{headers:g}))}}function wr(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 a=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(a){let o=a[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(a[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(a[1])}/${d[o]}`}let s=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){if(s[1]!==t)throw new Error("edit_plan_id_mismatch");let o=s[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(s[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 Sr}from"@safetech/inheriti-core-sdk/node";function gn(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=he(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=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)}});return new se(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 a.resolve(d,c)}}}).openReveal(e,t)}}}function Er(r){let e=new Se(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{...gn({api:e,reconstructor:new le(r.workerUrl),assetDecoder:Sr}),getPlan:t=>e.getPlan(t)}}import{DataAssetDefinitionService as Bs}from"@safetech/inheriti-core-sdk/node";function hn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Je=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),hn(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return hn(new Uint8Array(t))}},Ze=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 a=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(a),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"}},w=class extends _e{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Rt(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 In=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:yn(t,"expires_in"),intervalSeconds:At(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:yn(n,"expires_in"),refreshExpiresInSeconds:At(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 a=Q(i,"error")??`oauth_http_${n.status}`;throw new w(a,Q(i,"error_description")??a)}return i}};function ne(r,e){let t=Q(r,e);if(!t)throw new w("invalid_oauth_response",`Missing ${e}`);return t}function Q(r,e){return typeof r[e]=="string"?r[e]:void 0}function yn(r,e){let t=At(r,e);if(t===void 0)throw new w("invalid_oauth_response",`Missing ${e}`);return t}function At(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var xr=600*1e3,et=5,Rr=5,fn=class{constructor(e){this.options=e;this.crypto=e.crypto??new Je,this.clock=e.clock??new Ze}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(i),s=this.clock.now()+xr;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",a),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new w("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new w("authorization_transaction_expired");let i=new URL(e),a=new URL(n.redirectUri);if(i.origin!==a.origin||i.pathname!==a.pathname)throw new w("redirect_uri_mismatch");let s=i.searchParams.get("error");if(s)throw new w(s,i.searchParams.get("error_description")??s);if(i.searchParams.get("state")!==n.state)throw new w("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new w("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 w("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(et,t.intervalSeconds??et),i=this.clock.now(),a={...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"),a),a}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 w("device_transaction_missing");let i=n,a=await this.getDiscovery(),s=Math.max(et,i.intervalSeconds??et),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:a.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(d){let c=Rt(d);if(c==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(c==="slow_down"){s+=Rr,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new w("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=Rt(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 w("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 w("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 w("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 w("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 w("token_subject_mismatch")}let a=this.clock.now(),s=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:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&s?void 0:a+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:s,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(i.issuer))throw new w("issuer_mismatch");if(!a.includes(i.audience))throw new w("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new w("client_mismatch");if(e.environment!==i.environment)throw new w("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new w("required_claim_missing");if(n&&e.nonce!==t)throw new w("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 w("issuer_mismatch");if(!i.includes(n.clientId))throw new w("client_mismatch");if(e.authorizedParty!==n.clientId)throw new w("client_mismatch");if(!e.subject||!e.sessionId)throw new w("required_claim_missing");if(e.nonce!==t)throw new w("nonce_mismatch")}};function pe(r){return r.replace(/\/+$/u,"")}var Pn=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 Ys,RawMasterKeySource as Xs,deriveMasterKey as Js,generateHexSeed as Zs,computePassphraseVerifier as eo}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as no}from"@safetech/inheriti-core-sdk/node";function _s(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(a,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",r.environment),e(a,Object.assign({},s,{headers:o}))},n=r.business?void 0:_t({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 se(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:Ar})}function Cs(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=_t({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ae(new Ee(r.apiUrl,r.environment,r.getBearerToken,e),t)}function Ts(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=_t({apiUrl:t,getBearerToken:r.getBearerToken,transport:mn({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 Xe(new Qe(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as _r,webcrypto as Cr}from"node:crypto";import{canonicalInboxManifest as Tr,decodeInboxManifest as Dr,decodeInboxContentFrame as Mr,decodeInboxText as kr,decryptInboxShare as Or,encodeInboxContentFrame as Ct,encodeInboxText as Nr,encryptInboxShare as vn,inboxProtectedUnitCommitment as Kr,inboxTextMetadataDigest as bn,openInboxContent as Ur,sealInboxContent as Lr,signInboxFrame as qr,unwrapInboxContentKey as Gr,unwrapInboxShareKey as Fr,verifyInboxFrame as wn,wrapInboxContentKey as Vr,wrapInboxShareKey as zr}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as Br}from"@safetech/inheriti-core-sdk/workers/inbox.node";var B=Cr,_=B,R=r=>{if(!/^[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid_inbox_key");return Buffer.from(r,"hex")},h=r=>{let e=Buffer.from(r,"base64");if(!r||e.toString("base64")!==r)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},F=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),tt=async r=>new Uint8Array(await _.subtle.digest("SHA-256",Uint8Array.from(r))),Te=r=>_r("sha256").update(r).digest("hex"),re=class{constructor(e,t=new Br){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),a=Tr(i),s=await tt(a),{contentKey:o,frame:d}=await Lr(Nr(e.text),s,_),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:u}=await this.protectShares(t,d,s),g=await this.wrapRecipientKeys(t,o,s),b=await zr(l,R(e.tenantKeyHex),s,i.tenantId,i.messageId,_);return{frame:Buffer.from(Ct(d)).toString("base64"),submission:{messageId:t.messageId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,expiresAt:e.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(a).toString("base64"),signature:Buffer.from(c).toString("base64"),tenantWrappedShareKey:Buffer.from(b).toString("base64"),recipients:g,shares:u}}}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:s,manifestDigest:o,senderPublicDer:d}=await this.verifyOpening(e,n),c=await this.recoverFrame(n,s,o,e.tenantKeyHex);if(t&&!F(t,await Kr(s,Ct(c),h(n.signature),_)))throw new Error("inbox_parent_unit_mismatch");i=await this.decryptText(n,c,s,o,d,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(s){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId)}catch{}throw s}let a=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:a}}async ack(e,t,n,i,a){for(let s=0;s<2;s++){a?.throwIfAborted();try{return await this.api.ackInboxMessage(e,t,n,i,a),a?.throwIfAborted(),"ACKNOWLEDGED"}catch(o){if(a?.throwIfAborted(),o instanceof U&&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(h(n.signingPublicKey))!==n.signingKeyFingerprint||Te(h(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:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:R(a.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await bn(_)}}async signFrame(e,t,n,i){let a=await _.subtle.importKey("pkcs8",h(n),"Ed25519",!1,["sign"]),s=await qr(e,t,a,_),o=await _.subtle.importKey("spki",h(i),"Ed25519",!1,["verify"]);if(!await wn(e,t,s,o,_))throw new Error("inbox_identity_mismatch");return s}async protectShares(e,t,n){let i=await this.worker.split(Ct(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),a=_.getRandomValues(new Uint8Array(32)),s=[];for(let o=0;o<e.total;o++){let d=e.shareLayers[o];s.push({kind:"DATA",index:o,shareId:d.dataShareId,layerId:d.id,ciphertext:Buffer.from(await vn(i.dataShares[o],a,n,e.messageId,_)).toString("base64")}),s.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await vn(i.keyShares[o],a,n,e.messageId,_)).toString("base64")})}return{shareKey:a,shares:s}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let a=h(i.encryptionPublicKey);if(Te(a)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await _.subtle.importKey("spki",a,{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 Vr(t,s,n,_)).toString("base64")}}))}async verifyOpening(e,t,n){let i=h(t.canonicalManifest),a=Dr(i);if(a.tenantId!==e.identity.tenantId||a.conversationId!==e.conversationId||a.messageId!==e.messageId||a.expiresAtEpochMs<=Date.now()||!F(a.metadataDigest,n??await bn(_)))throw new Error("inbox_manifest_mismatch");let s=a.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!s||!F(s.encryptionKeyFingerprint,R(Te(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=h(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Te(o)||!F(a.senderSigningKeyFingerprint,R(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:a,manifestDigest:await tt(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let a=await Fr(h(e.tenantWrappedShareKey),R(i),n,t.tenantId,t.messageId,_),s=[],o=[],d=new Set;for(let l of e.shares){let u=`${l.kind}:${l.index}`;if(d.has(u))throw new Error("duplicate_inbox_share");d.add(u);let g=await Or(h(l.ciphertext),a,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,_);(l.kind==="DATA"?s:o).push(g)}if(s.length!==o.length||s.length<2)throw new Error("incomplete_inbox_shares");let c=await this.worker.reconstruct(s,o,{threshold:s.length,total:s.length,messageId:t.messageId,manifestDigest:n});return Mr(c)}async decryptText(e,t,n,i,a,s){return kr(await this.decryptContent(e,t,n,i,a,s))}async decryptContent(e,t,n,i,a,s){let o=await _.subtle.importKey("spki",a,"Ed25519",!1,["verify"]);if(!await wn(n,t,h(e.signature),o,_))throw new Error("inbox_signature_invalid");let d=await _.subtle.importKey("pkcs8",h(s),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Gr(h(e.wrappedContentKey),d,i,_);return Ur(t,c,i,_)}};import{canonicalInboxManifest as $r,decodeInboxContentFrame as Hr,decodeInboxFile as Wr,decryptInboxShare as Qr,encodeInboxContentFrame as jr,encodeInboxFile as Yr,encryptInboxShare as Sn,inboxFileMetadataDigest as En,sealInboxContent as Xr,unwrapInboxShareKey as Jr,wrapInboxShareKey as Zr}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var nt=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),a=await this.fileManifest(t,n,i),s=$r(a),o=await tt(s),d=Yr(t.file),c;try{c=await Xr(d,o,B)}finally{d.fill(0)}let{contentKey:l,frame:u}=c,g=await this.signFrame(a,u,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let b=await this.worker.split(jr(u),{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 D=B.getRandomValues(new Uint8Array(32)),m=[];for(let A=0;A<n.total;A++){let $=n.shareLayers[A];m.push({reference:{kind:"DATA",index:A,shareId:$.dataShareId,layerId:$.id},bytes:await Sn(b.dataShares[A],D,o,n.messageId,B)}),m.push({reference:{kind:"KEY",index:A,shareId:$.keyShareId,layerId:$.id},bytes:await Sn(b.keyShares[A],D,o,n.messageId,B)})}let y=await this.wrapRecipientKeys(n,l,o),N=await Zr(D,R(t.tenantKeyHex),o,a.tenantId,a.messageId,B);t.signal?.throwIfAborted();let C=await this.fileApi.stageInboxFile(t.conversationId,{messageId:n.messageId,senderDeviceId:i.deviceId,participantRevision:n.participantRevision,expiresAt:t.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(g).toString("base64"),tenantWrappedShareKey:Buffer.from(N).toString("base64"),recipients:y,shares:m.map(A=>A.reference)},t.signal);if(C.messageId!==n.messageId||C.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let A=0;A<m.length;A++){t.signal?.throwIfAborted();let $=m[A];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,$.reference.shareId,$.bytes,t.signal),t.onProgress?.(A+1,m.length,"UPLOADING")}t.signal?.throwIfAborted();let L=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(L.messageId!==n.messageId||L.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return L}async openFile(t){t.signal?.throwIfAborted();let n=await this.fileApi.openInboxFile(t.conversationId,t.messageId,t.identity.deviceId,t.signal),i,a;try{let{manifest:o,manifestDigest:d,senderPublicDer:c}=await this.verifyOpening(t,n,await En(B)),l=await this.recoverFileFrame(t,n,o,d);a=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=Wr(a),t.signal?.throwIfAborted(),await t.save(i),t.signal?.throwIfAborted()}catch(o){try{await this.fileApi.releaseInboxMessage(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId)}catch{}throw o}finally{a?.fill(0)}let s=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:s}}async fileManifest(t,n,i){let a=Date.parse(t.expiresAt);if(!Number.isSafeInteger(a)||a<=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:R(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:R(s.encryptionKeyFingerprint)})),expiresAtEpochMs:a,metadataDigest:await En(B)}}async recoverFileFrame(t,n,i,a){let s=await Jr(h(n.tenantWrappedShareKey),R(t.tenantKeyHex),a,i.tenantId,i.messageId,B),o=[],d=[],c=new Set;for(let u=0;u<n.shares.length;u++){t.signal?.throwIfAborted();let g=n.shares[u],b=`${g.kind}:${g.index}`;if(c.has(b))throw new Error("duplicate_inbox_share");c.add(b);let D=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,g.shareId,t.identity.deviceId,n.leaseId,t.signal),m=await Qr(D,s,a,i.messageId,g.kind==="DATA"?"data":"key",g.index,B);(g.kind==="DATA"?o:d).push(m),t.onProgress?.(u+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:a},t.signal,u=>t.onProgress?.(n.shares.length,n.shares.length,u.stage));return t.signal?.throwIfAborted(),Hr(l)}};import{createHash as Rn,webcrypto as ei}from"node:crypto";import{canonicalInboxParentManifest as ti,decodeInboxParentManifest as ni,encodeInboxParentNormalFrame as ri,decodeInboxParentNormalFrame as ii,sealInboxParentNormalBody as ai,openInboxParentNormalBody as si,wrapInboxParentNormalKey as oi,unwrapInboxParentNormalKey as di,signInboxParentNormalFrame as ci,verifyInboxParentNormalFrame as xn,encodeInboxText as li,decodeInboxText as pi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var V=ei,De=r=>Rn("sha256").update(r).digest("hex"),rt=r=>Buffer.from(r).toString("base64"),it=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),a=this.validatePreparation(e,i),s=this.createManifest(e,i,a),o=await this.createSubmission(e,i,a,s);this.rememberSubmission(s.parentId,t,o);let d=await this.api.publishNormalInboxMessage(e.conversationId,o);return this.pending.delete(s.parentId),d}digestInput(e){return Rn("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(h(n.signingPublicKey))!==n.signingKeyFingerprint||De(h(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:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:R(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let a=ti(i),{contentKey:s,frame:o}=await ai(li(e.text),i,V),d=await V.subtle.importKey("pkcs8",h(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await ci(i,o,d,V),l=await V.subtle.importKey("spki",h(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await xn(i,o,c,l,V))throw new Error("inbox_identity_mismatch");let u=await Promise.all(t.recipients.map(g=>this.wrapRecipientKey(g,s,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:rt(a),frame:rt(ri(o)),signature:rt(c),recipients:u}}async wrapRecipientKey(e,t,n){let i=h(e.encryptionPublicKey);if(De(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=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:rt(await oi(t,a,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=ni(h(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(u=>u.memberId===e.identity.memberId&&u.deviceId===e.identity.deviceId);if(!i||!F(i.encryptionKeyFingerprint,R(De(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let a=h(t.senderSigningPublicKey);if(!F(n.senderSigningKeyFingerprint,R(De(a))))throw new Error("inbox_sender_key_mismatch");let s=ii(h(t.frame)),o=await V.subtle.importKey("spki",a,"Ed25519",!1,["verify"]);if(!await xn(n,s,h(t.signature),o,V))throw new Error("inbox_signature_invalid");let d=await V.subtle.importKey("pkcs8",h(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await di(h(t.wrappedContentKey),d,n,V),l=pi(await si(s,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 Cn,webcrypto as ui}from"node:crypto";import{canonicalInboxParentManifest as mi,decodeInboxParentManifest as gi,decodeInboxManifest as hi,encodeInboxParentNormalFrame as Ii,decodeInboxParentNormalFrame as yi,sealInboxParentNormalBody as fi,openInboxParentNormalBody as Pi,wrapInboxParentNormalKey as vi,unwrapInboxParentNormalKey as bi,signInboxParentNormalFrame as wi,verifyInboxParentNormalFrame as An,signInboxProtectedParent as Si,verifyInboxProtectedParent as _n,inboxProtectedUnitCommitment as Ei,encodeInboxText as xi,decodeInboxText as Ri}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var O=ui,at=r=>Buffer.from(r).toString("base64"),Me=r=>Cn("sha256").update(r).digest("hex"),st=class{constructor(e,t){this.api=e;this.child=t??new re(e)}pending=new Map;child;async send(e){let t=Cn("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 a=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(a.parentId,{digest:t,submission:a});let s=await this.api.publishInboxParent(e.conversationId,a);return this.pending.delete(a.parentId),s}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let t=e.segments.filter(b=>"protectedText"in b).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(b=>"text"in b))throw new Error("invalid_inbox_parent_segments");let i=await this.api.getNormalInboxSendPreparation(e.conversationId),a=this.validateSender(e,i),s=e.parentId??i.parentId,{protectedUnits:o,manifestUnits:d}=await this.prepareChildren(e,i,a),c=this.parentManifest(e,i,a,s,n,d),{frame:l,signature:u,recipients:g}=await this.signAndWrap(e,i,a,c);return{parentId:s,idempotencyKey:s,senderDeviceId:a.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:at(mi(c)),signature:at(u),frame:l,recipients:g,protectedUnits:o}}async prepareChildren(e,t,n){let i=[],a=[],s=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=hi(h(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let u=await Ei(l,h(c.frame),h(c.submission.signature),O);i.push({position:o,frame:c.frame,child:c.submission}),a.push({unitId:c.submission.messageId,position:o,commitment:u});try{e.onProgress?.(i.length,s)}catch{}}return{protectedUnits:i,manifestUnits:a}}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(a=>!n.recipients.some(s=>s.memberId===a.memberId&&s.deviceId===a.deviceId&&F(a.encryptionKeyFingerprint,R(s.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,t,n,i,a,s){return{mode:a,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:i,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:R(o.encryptionKeyFingerprint)})),protectedUnits:s}}async signAndWrap(e,t,n,i){let a=await O.subtle.importKey("pkcs8",h(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),s=await O.subtle.importKey("spki",h(n.signingPublicKey),"Ed25519",!1,["verify"]);if(i.mode==="PROTECTED")return{signature:await this.signProtectedParent(i,a,s),recipients:this.recipientReferences(t)};let{frame:o,signature:d,contentKey:c}=await this.sealMixedParent(e,i,a,s);return{frame:o,signature:d,recipients:await this.wrapRecipients(t,c,i)}}async signProtectedParent(e,t,n){let i=await Si(e,t,O);if(!await _n(e,i,n,O))throw new Error("inbox_identity_mismatch");return i}async sealMixedParent(e,t,n,i){let a=e.segments.map((d,c)=>"text"in d?{text:d.text}:{unitId:t.protectedUnits.find(l=>l.position===c).unitId}),s=await fi(xi(JSON.stringify(a)),t,O),o=await wi(t,s.frame,n,O);if(!await An(t,s.frame,o,i,O))throw new Error("inbox_identity_mismatch");return{frame:at(Ii(s.frame)),signature:o,contentKey:s.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 a=h(i.encryptionPublicKey);if(Me(a)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await O.subtle.importKey("spki",a,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:at(await vi(t,s,n,O))}}))}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(h(n.signingPublicKey))!==n.signingKeyFingerprint||Me(h(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),a=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:a}}async verifyOpening(e,t){let n=gi(h(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||!F(n.commitment,R(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||!F(n.encryptionKeyFingerprint,R(Me(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,t){let n=h(e.senderSigningPublicKey);if(Me(n)!==e.senderSigningKeyFingerprint||!F(t.senderSigningKeyFingerprint,R(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return O.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await _n(t,h(e.signature),n,O))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 a=yi(h(t.frame));if(!await An(n,a,h(t.signature),i,O))throw new Error("inbox_signature_invalid");let s=await O.subtle.importKey("pkcs8",h(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await bi(h(t.wrappedContentKey),s,n,O),d=JSON.parse(Ri(await Pi(a,o,n,O)));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((a,s)=>{if(!a||typeof a!="object"||Array.isArray(a))throw new Error("invalid_inbox_parent_body");let o=a;if(typeof o.text=="string"&&Object.keys(o).length===1)return{text:o.text};let d=n.protectedUnits.find(c=>c.position===s);if(!d||o.unitId!==d.unitId||Object.keys(o).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:d.unitId,position:s,status:t.protectedUnits.find(c=>c.unitId===d.unitId).status}});if(n.protectedUnits.some(a=>!i[a.position]||!("unitId"in i[a.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(a=>"unitId"in a&&a.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let i=t.protectedUnits.find(a=>a.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,Re as CorePlanMaterialBuilder,Bs as DataAssetDefinitionService,U as ElementsApiRequestFailed,se as ElementsClient,ve as GuidedCreateRecoveryError,Pe as GuidedPlanCreator,Se as HttpAutomationRevealApiPort,ce as HttpElementsApiPort,In as HttpOperatorAuthTransport,Qe as HttpPlanEditPort,Ee as HttpQuickPlanPort,v as InvalidPlanDeclaration,M as InvalidPlanMaterial,Ne as MasterKeyRelayCancellationFailed,Oe as MasterKeyRelayExpired,ke as MasterKeyRelayTimedOut,j as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,Ie as MemoryKeyVault,ye as MemoryStatePort,nt as NodeInboxFile,it as NodeInboxNormal,st as NodeInboxParent,re as NodeInboxText,w as OAuthProtocolError,fn as OperatorAuthClient,_e as OperatorAuthError,Ce as OperatorReauthenticationRequired,Pn as OperatorSessionController,pt as PLAN_CREATION_SERVER_STAGES,Ys as PassphraseMasterKeySource,no as PlanAssetDeclaration,te as PlanRequestFailed,Ae as QuickPlanCreator,Xe as QuickPlanEditor,Xs as RawMasterKeySource,z as RelayMasterKeySource,dt as StaticMasterKeyResolver,Ze as SystemOAuthClock,Je as WebOAuthCrypto,eo as computePassphraseVerifier,Ke as createMasterKeyResolver,Er as createNodeAutomationRevealClient,_s as createNodeElementsClient,Cs as createNodeQuickPlanCreator,Ts as createNodeQuickPlanEditor,Ar as decodeAssetContainer,Js as deriveMasterKey,Zs as generateHexSeed,he as masterKeyRefFor,X as masterKeyRefKey,Rt as oauthErrorCode,dr as selectBusinessOrganization,vt as unwrapDekWithMasterKey,J as validatePlanCreationInput,ae as validatePlanCreationMaterial};