@safetech/inheriti-client-sdk 1.17.26 → 1.17.28
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/README.md +2 -1
- package/dist/browser.js +1 -1
- package/dist/index.js +1 -1
- package/dist/inheriti-client-sdk.umd.js +47 -47
- package/dist/node-base.js +1 -1
- package/dist/node.js +1 -1
- package/dist/sdk-types.d.ts +77 -2
- package/dist/src/operator-auth/http-operator-auth-transport.d.ts +12 -1
- package/dist/src/operator-auth/operator-auth-client.d.ts +14 -0
- package/dist/src/operator-auth/ports.d.ts +20 -1
- package/dist/src/operator-auth/types.d.ts +32 -1
- package/package.json +2 -2
package/dist/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createNodeSharedConfigurationSdk as Kt,decodeAssetContainer as Fr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as qn,generateRSAOAEPKeyPair as Gn}from"@safetech/inheriti-core-sdk/crypto";var Oe=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ke=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},Ne=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},z=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await Gn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(g=>new Promise(f=>setTimeout(f,g))),c=!0,l=!1,p,m=()=>p??=(async()=>{let g=new AbortController,f,T=new Promise((x,k)=>{f=setTimeout(()=>{g.abort(),k(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,g.signal),T])}finally{clearTimeout(f)}})(),y,b=new Promise((g,f)=>{y=()=>{c&&m().catch(()=>{}),f(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",y,{once:!0})});b.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let g=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),b]);if(g.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(g.status==="DELIVERED"&&g.sealedMasterKey){let f=(await qn(g.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(f))throw new Error("invalid_master_key_material");return f}if(g.status==="EXPIRED")throw new ke(s.sessionId);await Vn(d,a,e)}throw new Oe(s.sessionId)}catch(g){if(c&&(!l||e?.aborted))try{await m()}catch(f){if(e?.aborted)throw new Ne(f)}throw g}finally{y&&e?.removeEventListener("abort",y)}}};async function Vn(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function Ke(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||ut(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(zn(e,r.applicationId)){let i=await r.source?.resolve();return i||ut(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return ut(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function zn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ut(r,e,t,n,i){if((await e()).relayAvailable)return new z({...r.relay,api:Bn(r.api,t)}).resolve(n,i)}function Bn(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function J(r){return`${r.system}:${r.contextId}`}function Ie(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var j=class extends Error{constructor(t){super(`master_key_required:${J(t)}`);this.ref=t;this.name="MasterKeyRequired"}},mt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(J(e),t),this}async resolve(e){return this.sources.get(J(e))?.resolve()}};var he=class{keys=new Map;async store(e,t){let n=J(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(J(e))?.slice()}async remove(e){let t=J(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ye=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var Ue=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},P=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Le=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var Fe=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],It={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},ht=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],w=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},N=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function se(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new N("plan_material_field_unknown");if(gt(r.dataShards,"data_shards_invalid"),gt(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&>(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new N("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new N("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new N("material_operation_invalid")}function gt(r,e){if(!Array.isArray(r))throw new N(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new N(e);if(t.data!==void 0&&typeof t.data!="string")throw new N(e)}}function Z(r){if(ie(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Wn(r.idempotencyKey))throw new w("idempotency_key_invalid");if(!r.name?.trim())throw new w("plan_name_required");if(!r.assets.length)throw new w("assets_required");let e=new Set;for(let t of r.assets){if(ie(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new w("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!Fe.includes(t.type))throw new w("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new w("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new w("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new w("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new w("asset_field_names_invalid");if($n(t.matchOrigins),!t.isBinary){let s=It[t.type];if(!s||i.some(a=>!s.includes(a)))throw new w("asset_field_name_not_canonical")}}if(!r.participants.length)throw new w("participants_required");for(let t of r.participants){if(ie(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Ft(t.routingEmail))throw new w("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new w("participant_relationships_invalid")}Hn(r)}function $n(r){if(r===void 0)return;if(!r.length)throw new w("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new w("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new w("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof w?n:new w("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new w("asset_match_origins_duplicated")}function Hn(r){let e=r.policy;if(e&&ie(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new w("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){ie(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new w("authentication_mode_invalid")}if(e.moderation){ie(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new w("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new w("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new w("approval_mode_invalid")}let t=e.dms;if(!t)return;ie(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Ft(t.subjectEmail))throw new w("dms_subject_invalid");if(!r.participants.some(s=>Lt(s.routingEmail)===Lt(t.subjectEmail)))throw new w("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new w("dms_countdown_invalid")}function Wn(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Ft(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Lt(r){return r.normalize("NFC").trim().toLowerCase()}function ie(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new w(t)}var fe=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},Pe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),Z(e),qe(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,s={}){Z(t);let a=await this.checkpoints.load(e);if(!a)throw new ve("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await qt(t))throw new ve("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;qe(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});qe(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});qe(s.signal),se(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(l.stage),l.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,l),l}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await qt(e),serverStage:t.stage})}},ve=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function qt(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function qe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Gt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Ue(n.stage);return r.authorizeRevealAction(e,t)}function Qn(r){let e=r?.status;return e===400||e===401||e===403}async function Vt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Qn(s))throw s}return r.releaseRevealMaterial(e,t)}function jn(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?Xn(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Yn.has(r.stage)?"ENDED":"CONTINUING"}var Yn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Xn(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var yt=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function ze(r,e,t={},n=!1){if(t.signal?.aborted)throw R();let i=await r.getPlan(e),s=await r.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):zt(s.id);if(t.signal?.aborted)throw R();let a=()=>r.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)});if(n||await a(),t.signal?.aborted)throw R();let o=t.idempotencyKey??crypto.randomUUID(),d;try{d=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:o,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let p=await r.getActivePlanReveal(e);throw!p||p.planId!==e||p.mode!==(t.mode??"DIRECT")||p.protectedCopy!==void 0&&p.protectedCopy!==(t.protectedCopy??!1)?l:zt(p.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let c;try{if(t.signal?.aborted)throw R();let l=await Zn(r,d,t);if(t.signal?.aborted||(n&&await a(),t.signal?.aborted)||(ee(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw R();let p=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id),t.signal?.aborted))throw R();let m;try{m=await rr(r,l,sr(p),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(ee(t,"RECONSTRUCTING",l),t.signal?.aborted))throw R();try{c=await r.reconstructPlanMaterial(m)}catch(b){throw t.signal?.aborted?R():(await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:nr(b)}),b)}if(t.signal?.aborted)throw R();let y=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(ee(t,"OPEN",y),t.signal?.aborted))throw R();return new Pt(r,y,i,c,t.signal)}catch(l){throw c?.fill(0),await Ht(r,d.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function zt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Jn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Zn(r,e,t){let n=await Y(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw R();if(t.onSession?.(n),t.onProgress?.({phase:jn(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Jn.has(n.stage))throw new ft(n.stage);await vt(t.pollIntervalMs??1500,t.signal),n=await Y(()=>r.getReveal(e.id,t.signal),t.signal)}}var ft=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function ee(r,e,t){r.onProgress?.({phase:e,session:t})}function vt(r,e){return e?.aborted?Promise.reject(R()):new Promise((t,n)=>{let i=setTimeout(a,Math.max(0,r)),s=()=>{clearTimeout(i),n(R())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Pt=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new yt;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=e.map(({selector:s,options:a={}})=>{let o=er(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new M("asset_not_found");if(d.isBinary)throw new M("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new M("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),i=[];try{for(let a of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:a.options.idempotencyKey??crypto.randomUUID(),assetId:a.asset.id,fieldName:a.field,action:a.options.action??"VIEW_FIELD",...a.options.destination===void 0?{}:{destination:a.options.destination},...a.options.origin===void 0?{}:{origin:a.options.origin}}));let s=n.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new M("asset_value_invalid");return{selector:a.selector,value:tr(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",Bt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=this.plan.assets.find(a=>a.code===e||a.id===e);if(!n)throw new M("asset_not_found");if(!n.isBinary)throw new M("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!a||!(a.data instanceof Uint8Array))throw new M("asset_value_invalid");s=a.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",Bt(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Ht(this.client,this.session.id,e),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function er(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new M("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new M("asset_selector_invalid");return{asset:r.asset,field:r.field}}function tr(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new M("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new M("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?It[t]:void 0)?.includes(e))return"";throw new M("asset_value_invalid")}return n[e]}function Bt(r){if(r instanceof M)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function nr(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function rr(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await Y(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Ge;let c=await Y(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if($t(c,i.id,e.planId),!c.shares.includes(i.data))throw new W;ee(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await Y(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw R();if(!l?.trim())throw new W;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw R();return{...t,shares:t.shares.filter(p=>p!==i).concat(c.shares.map((p,m)=>({id:`${c.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:p})))}}if(d!=="SK_MOBILE")throw new W;if(n.signal?.aborted)throw R();return await r.distributeRevealCustodianShare(e.id),ee(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),ee(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await vt(n.pollIntervalMs??1500,n.signal),s=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Ge;if(!s.shareId||!s.deviceId)throw new W;ee(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Y(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw R();if($t(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new W;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw R();return{...t,shares:t.shares.concat(d.shares.map((c,l)=>({id:`${d.id}:${l}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new W;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(a),ee(n,"WAITING_FOR_CUSTODIAN",a),n.signal?.aborted)throw R();await r.requestRevealCustodianRelease(e.id);let o=await ir(r,e,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function $t(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new W}async function Y(r,e){if(e?.aborted)throw R();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(R()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw R();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function ir(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Ve;let s=await Y(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Ve;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new W}await vt(t.pollIntervalMs??1500,t.signal)}}var W=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Ge=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ve=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function sr(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function Ht(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(a){if(!ar(a))throw a}return}let n=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(a.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(a){if(a?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:a}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function ar(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function R(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var ae=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new he,this.state=t.state??new ye,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??cr(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new P;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new P;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new P;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new P;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return Z(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new P;return se(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new P;return new Pe(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new j({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return dr(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new j(e);return await this.keyVault.store(e,or(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new P;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new P;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Le;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new j({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=Ie(e);if(!i)throw new j({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new P;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new P;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new P;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new P;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new P;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new P;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new P;return this.api.getReveal(e,t)}openReveal(e,t){return ze(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new P;return Vt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new P;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new P;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new P;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new P;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new P;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new P;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new P;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new P;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new P;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new P;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new P;return Gt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new P;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new P;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new P;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new P;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new P;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new P;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new P;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new bt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new j({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},bt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function or(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function dr(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function cr(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return Ke({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Ke({...e,organizationId:r.organizationId})}var lr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],pr=["DIRECT","GOVERNED"],Qt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],ur=["ACTIVE","REVOKED"],mr=["SK_MOBILE"],gr=["ACTIVE","INACTIVE"],Ir=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function jt(r){let e=O(r);return{items:F(e.items).map(Jt),nextCursor:e.nextCursor===null?null:h(e.nextCursor,"nextCursor")}}function Yt(r){let e=O(r);return{total:B(e.total,"total"),items:F(e.items).map(t=>{let n=O(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:h(n.id,"log.id"),planId:h(n.planId,"log.planId"),tenantId:h(n.tenantId,"log.tenantId"),event:h(n.event,"log.event"),occurredOn:h(n.occurredOn,"log.occurredOn"),status:X(n.status),title:h(n.title,"log.title"),details:F(n.details).map(i=>{let s=O(i);return{label:h(s.label,"log.detail.label"),value:h(s.value,"log.detail.value")}})}})}}function Xt(r){let e=O(r);return{total:B(e.total,"total"),items:F(e.items).map(t=>{let n=O(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=h(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:h(n.id,"log.id"),memberId:h(n.memberId,"log.memberId"),source:i,event:h(n.event,"log.event"),occurredOn:h(n.occurredOn,"log.occurredOn"),status:X(n.status)}})}}function Be(r){let e=O(r),t=Jt(e),n=O(e.source),i=h(n.kind,"source.kind");return{...t,assets:F(e.assets).map(s=>{let a=O(s);return{id:h(a.id,"asset.id"),code:X(a.code),type:L(h(a.type,"asset.type"),Fe),name:h(a.name,"asset.name"),isBinary:yr(a.isBinary,"asset.isBinary"),fieldNames:F(a.fieldNames).map(o=>h(o,"asset.fieldNames")),fileName:X(a.fileName),mimeType:X(a.mimeType),size:a.size===void 0||a.size===null?void 0:B(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:F(a.matchOrigins).map(o=>h(o,"asset.matchOrigins"))}}),participants:F(e.participants).map(s=>{let a=O(s);return{id:h(a.id,"participant.id"),displayName:h(a.displayName,"participant.displayName"),relationships:F(a.relationships).map(o=>L(h(o,"relationship"),Qt)),lifecycle:L(h(a.lifecycle,"participant.lifecycle"),ur)}}),revealPolicy:(()=>{let s=O(e.revealPolicy);return{masterKeyRelease:L(h(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:L(h(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=O(e.dms);return{subjectEmail:h(s.subjectEmail,"dms.subjectEmail"),countdownDays:B(s.countdownDays,"dms.countdownDays"),countdownHours:B(s.countdownHours,"dms.countdownHours"),countdownMinutes:B(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:L(h(n.system,"source.system"),["INHERITI_BUSINESS"]),status:L(h(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function be(r){let e=O(r);return{operationId:h(e.operationId,"operationId"),stage:L(h(e.stage,"stage"),ht),outcome:L(h(e.outcome,"outcome"),Ir),planId:X(e.planId),lastErrorCode:X(e.lastErrorCode),participants:e.participants===void 0?void 0:F(e.participants).map(t=>{let n=O(t);return{clientParticipantRef:h(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:h(n.planParticipantId,"planParticipantId"),relationships:F(n.relationships).map(i=>hr(h(i,"relationship"),Qt))}})}}function Jt(r){let e=O(r),t=O(e.assetSummary),n=O(e.governance),i=O(e.participantSummary);return{id:h(e.id,"id"),name:h(e.name,"name"),description:X(e.description),status:L(h(e.status,"status"),lr),createdAt:h(e.createdAt,"createdAt"),configuredAt:X(e.configuredAt),assetSummary:{count:B(t.count,"assetSummary.count"),types:F(t.types).map(s=>L(h(s,"assetType"),Fe)),names:Wt(t.names).map(s=>h(s,"assetSummary.names"))},governance:{mode:L(h(n.mode,"governance.mode"),pr),minimumApprovals:B(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:B(i.owners,"owners"),mergers:B(i.mergers,"mergers"),moderators:B(i.moderators,"moderators")},authentication:Wt(e.authentication).map(s=>{let a=O(s);return{id:L(h(a.id,"authentication.id"),mr),status:L(h(a.status,"authentication.status"),gr)}})}}function L(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function hr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function O(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Wt(r){return r==null?[]:F(r)}function F(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function h(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function X(r){return r==null?void 0:h(r,"optional")}function B(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function yr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var ue=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Zt(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function fr(r,e){if(!e){if(r.length===0)throw new ue("organization_required");if(r.length>1)throw new ue("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new ue("organization_access_denied");return e}function Pr(r){let e=E(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),createdAt:U(e.createdAt),...en(e)}}function en(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=E(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:u(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:U(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=E(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:v(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:U(i.revealedAt)}:{}}})}:{}}})}}function tn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Pr),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0),unreadCount:v(e.unreadCount,0),readThroughSequence:v(e.readThroughSequence,0)}}function nn(r){let e=E(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=E(t);return{unitId:u(n.unitId),position:v(n.position,0),commitment:u(n.commitment),status:u(n.status)}})}}function wt(r){let e=E(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:v(e.sequence,1),status:e.status}}function rn(r){let e=E(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),parentId:u(e.parentId),participantRevision:v(e.participantRevision,1),recipients:e.recipients.map(Et)}}function sn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);return{parentId:u(n.parentId),sequence:v(n.sequence,1),senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),participantRevision:v(n.participantRevision,1),createdAt:U(n.createdAt),...en(n)}}),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0),unreadCount:v(e.unreadCount,0),readThroughSequence:v(e.readThroughSequence,0)}}function an(r){return{readThroughSequence:v(E(r).readThroughSequence,0)}}function on(r){return{clearedThroughSequence:v(E(r).clearedThroughSequence,0)}}function dn(r){let e=E(r);return{parentId:u(e.parentId),sequence:v(e.sequence,1),senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:v(e.participantRevision,1),canonicalManifest:u(e.canonicalManifest),frame:u(e.frame),signature:u(e.signature),wrappedContentKey:u(e.wrappedContentKey),senderSigningPublicKey:u(e.senderSigningPublicKey)}}function E(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function u(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function U(r){let e=u(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function v(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Et(r){let e=E(r);return{memberId:u(e.memberId),deviceId:u(e.deviceId),deviceVersion:v(e.deviceVersion,1),encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint)}}function me(r){let e=E(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:u(e.id),tenantId:u(e.tenantId),memberId:u(e.memberId),version:e.version,encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint),status:e.status,createdAt:U(e.createdAt),updatedAt:U(e.updatedAt)}}function $e(r){let e=E(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:u(e.id),tenantId:u(e.tenantId),creatorMemberId:u(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(u),participantRevision:e.participantRevision,status:e.status,createdAt:U(e.createdAt),updatedAt:U(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=E(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:u(n.senderMemberId),createdAt:U(n.createdAt)}}return t}function cn(r){let e=E(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map($e),total:e.total,limit:e.limit,offset:e.offset}}function ln(r){let e=E(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Et(t);return{memberId:n.memberId,name:u(E(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:v(e.limit,1),offset:v(e.offset,0),nextOffset:e.nextOffset===null?null:v(e.nextOffset,0)}}function pn(r){let e=E(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:u(n.memberId),name:u(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:u(E(n.profilePicture).url)}}}}),limit:v(e.limit,1),offset:v(e.offset,0),nextOffset:e.nextOffset===null?null:v(e.nextOffset,0)}}function un(r){let e=E(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),messageId:u(e.messageId),participantRevision:v(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Et),shareLayers:e.shareLayers.map(t=>{let n=E(t),i=u(n.id),s=u(n.dataShareId),a=u(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:u(n.contractAddress),dataShareId:s,keyShareId:a};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function He(r){let e=E(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:u(e.messageId),status:e.status}}function mn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:u(n.id),status:n.status,senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),createdAt:U(n.createdAt),updatedAt:U(n.updatedAt),expiresAt:U(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let a=E(s);if(a.status!=="UNREAD"&&a.status!=="LEASED"&&a.status!=="CONSUMED"&&a.status!=="EXPIRED"&&a.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:u(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:U(a.consumedAt)}:{}}})),i}),total:v(e.total,0),limit:v(e.limit,1),offset:v(e.offset,0)}}function gn(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:U(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:v(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId),ciphertext:u(n.ciphertext)}})}}function In(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:U(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:v(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:v(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId)}})}}function oe(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function de(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var q=class extends Error{constructor(t,n,i,s){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ce=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,n,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":n},i)}confirmFileAccessDelivery(e,t,n){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":n})}createInboxFileAccess(e,t,n,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",n,void 0,void 0,i)}createRevealFileAccess(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,n)}cancelRevealFileAccess(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",n)}cancelInboxFileAccess(e,t,n,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let n=t;if(typeof n.publicKey!="string"||!n.publicKey||typeof n.fingerprint!="string"||!n.fingerprint||n.status!=="ACTIVE"&&n.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:n.publicKey,fingerprint:n.fingerprint,status:n.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:me(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:me(n)}async registerInboxDevice(e){return me(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return me(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return me(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return $e(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return $e(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return cn(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return ln(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return pn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return un(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return He(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return tn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return nn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return on(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return sn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return dn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return an(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return He(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let a=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(a,"PUT",i,s),d=await We(o,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new q(o.status,oe(d),de(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return He(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return In(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,c=await this.requestBinary(d,"GET",void 0,a);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let l=Number(c.headers.get("content-length"));if(Number.isFinite(l)&&l>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let p=c.body.getReader(),m=[],y=0;try{for(;;){a?.throwIfAborted();let f=await p.read();if(f.done)break;if(y+=f.value.length,y>14*1024*1024)throw new Error("invalid_inbox_share_size");m.push(f.value)}}catch(f){throw await p.cancel().catch(()=>{}),f}let b=new Uint8Array(y),g=0;for(let f of m)b.set(f,g),g+=f.length;return b}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return mn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return gn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Zt)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return jt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Be(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Yt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let n=new URLSearchParams;t.source&&n.set("source",t.source),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Xt(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){Z(e);let{idempotencyKey:t,...n}=e;return be(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return se(t),be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,s,a){this.requireBusinessSelection(e),a?.throwIfAborted();let o=await this.getBearerToken();a?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[y,b]of Object.entries(s??{}))d.set(y,b);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:n?JSON.stringify(n):void 0};a&&(l.signal=a);let p=await this.transport(new URL(e,c),l);a?.throwIfAborted();let m=await We(p,a);if(a?.throwIfAborted(),!p.ok)throw new q(p.status,oe(m),de(m),p.headers.get("x-request-id")??void 0);if(!m.ok||m.result===void 0)throw new q(p.status,oe(m),de(m),p.headers.get("x-request-id")??void 0);return m.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let a=new Headers({"x-elements-environment":this.environment});s&&a.set("authorization",`Bearer ${s}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),n&&a.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:a,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await We(d,i);throw new q(d.status,oe(c),de(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let a=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});a&&o.set("authorization",`Bearer ${a}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId);for(let[p,m]of Object.entries(n??{}))o.set(p,m);t&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:o,body:t?JSON.stringify(t):void 0,signal:s}),l=await We(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new q(c.status,oe(l),de(l),c.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new q(400,"organization_selection_required")}};async function We(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Ar}from"@safetech/inheriti-core-sdk/node";async function St(r,e){if(!e)throw new Error("master_key_required");let t=vr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=br(r),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,a);return wr(new Uint8Array(o))}function vr(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function br(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function wr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var we=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await hn("plan_key_unwrap_failed",()=>St(e.planKey,t)),i=await crypto.subtle.importKey("raw",Rt(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await hn("plan_share_decryption_failed",()=>xr(o.data,i));Rr(o.shareType)?a.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new Qe("plan_share_reconstruction_failed",Sr(o))}}},Qe=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},Er=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function Sr(r){let e=r instanceof Error?r.message:void 0;if(e)return Er.has(e)?e:void 0}async function hn(r,e){try{return await e()}catch{throw new Qe(r)}}function Rr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function xr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Rt(r.slice(0,t)),i=Rt(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function Rt(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var le=class extends we{constructor(e){super(()=>Ar(e))}};var Ee=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Be(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,s,a){a?.throwIfAborted();let o=await this.getAutomationBearerToken();if(a?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...s});n!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:a});a?.throwIfAborted();let l;try{l=await c.json()}catch{a?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new q(c.status,l&&oe(l),l&&de(l));return l?.result}};var _={invalidDeclaration:"plan_declaration_invalid",invalidShares:"plan_share_count_invalid",storageChanged:"plan_storage_context_changed",invalidMasterKeyContext:"invalid_master_key_context",reauthenticationRequired:"operator_reauthentication_required",relayFailed:"master_key_relay_failed",reconciliationRequired:"reconciliation_required"};var te=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},Se=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,n,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:n.validatorShares,encryptedKey:n.encryptedKey})}preflight(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",yn(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",yn(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(_.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(_.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(_.relayFailed);return n}async request(e,t,n,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(_.reauthenticationRequired);s.set("authorization",`Bearer ${a}`),i!==void 0&&s.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,c=await this.transport(new URL(d,o),{method:n,headers:s,body:i===void 0?void 0:JSON.stringify(i)}),l={};try{l=await c.json()}catch{}if(!c.ok||l.ok!==!0)throw new te(c.status,l.error);return l.result}};function yn(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var xe=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){Re(e.signal),Cr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return Re(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){Re(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(Re(e.signal),!i.custodianPair)throw new N("custodian_share_required");let s=xt(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(xt(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(xt(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return Re(e.signal),{protectionProtocol:i.protocol,validatorShares:At(a.encryptedShares),dataShards:At(o.encryptedShares),backupShards:At(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:_r(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:_t(n.encryptedShares[0]),dataShard:_t(n.encryptedShares[1])}}};function xt(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function At(r){return r.map(_t)}function _t(r){return{id:r.id,data:r.encryptedData}}function _r(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new N("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function Cr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new N("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new N("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new N("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new N("plan_secrets_declaration_mismatch")}}function Re(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function fn(r,e,t,n,i,s,a){let o=n.mergeThreshold-(n.withCustodian?1:0);if(typeof n.withCustodian!="boolean"||!Number.isInteger(n.mergeThreshold)||o<1||o>r.totalShares)throw new Error(_.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new z({api:{startRelaySession:y=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,y),readRelaySession:y=>i.readRelaySession(r.organizationId,y)}}),p=new xe(s,l);a?.("encrypting");let m=await p.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return a?.("generating_shares"),p.generateShares({planId:r.planId,declaration:c,encrypted:m})}import{PlanAssetDeclaration as Tr}from"@safetech/inheriti-core-sdk/node";function Pn(r){let e=Ct({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function Ct(r){if(!r.assets.length)throw new w("assets_required");let e=r.assets.map(s=>{if(s.meta.isMedia!==!0)return;let a="data"in s.secret?s.secret.data:void 0,o;if(a instanceof Blob&&(o=a.size),typeof a=="string")try{o=atob(a).length}catch{throw new w("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new w("binary_asset_metadata_invalid");return o}),t=Tr.create(r.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),n=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,r.assets[a].secret]))),i={idempotencyKey:r.planId,name:r.title,assets:n.map((s,a)=>{let o=s.meta.isMedia===!0;return{clientAssetRef:s.id,type:s.type,name:s.meta.name,fieldNames:o?[]:Object.keys(s.secret),isBinary:o,fileName:s.meta.fileName,mimeType:s.meta.mimeType,size:e[a]}}),participants:[]};return{assets:n,plan:i}}async function bn(r){let e=await Promise.all(r.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([n],[i])=>n.localeCompare(i)).map(async([n,i])=>[n,i instanceof Blob?await vn(new Uint8Array(await i.arrayBuffer())):i]))})));return vn(new TextEncoder().encode(JSON.stringify({organizationId:r.organizationId,planId:r.planId,title:r.title,description:r.description??null,audience:r.audience??null,totalShares:r.totalShares,assets:e})))}async function vn(r){let e=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ae=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){return this.createPlan({...e,assets:[e.asset]},t)}async createPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!Array.isArray(e.assets)||!e.assets.length||e.assets.some(a=>!a?.meta?.name?.trim()))throw new Error(_.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(_.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(_.invalidShares);let n=await bn(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(_.reconciliationRequired);return i.promise}let s=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let i=Ct({planId:e.planId,title:e.title,assets:e.assets}),s=this.material.get(e.planId);if(s&&(s.fingerprint!==t||s.masterKeySource!==e.masterKeySource))throw new Error(_.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(je(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(_.reconciliationRequired);if(!a&&s)throw new Error(_.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(_.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(_.invalidMasterKeyContext);if(!a){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(a=await this.statusOrMissing(e.organizationId,e.planId),!a)throw l}}a??=await this.port.status(e.organizationId,e.planId);let d=s?.encrypted??await fn(e,i,o,a,this.port,this.coreSdk,n);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),n?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),n?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),n?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!je(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return je(c)&&this.material.delete(e.planId),{planId:e.planId,status:je(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(_.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof te&&n.status===404)return;throw n}}};function je(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var Ye=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}start(e,t,n,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:n},i)}async listEligibleCandidates(e,t,n){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),n&&i.set("namePrefix",n);let s=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(s))throw new Error("invalid_plan_edit_candidates");return s}async context(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(n))throw new Error("invalid_plan_edit_context");return n}async moderatorNames(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!n||typeof n!="object")throw new Error("invalid_plan_edit_participants");let i=n;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let s=new Map;for(let a of i.participants){if(!a||typeof a.id!="string"||!a.id||typeof a.displayName!="string"||!Array.isArray(a.relationships)||!a.relationships.every(o=>typeof o=="string")||typeof a.lifecycle!="string")throw new Error("invalid_plan_edit_participants");a.lifecycle==="ACTIVE"&&a.relationships.includes("MODERATOR")&&s.set(a.id,a.displayName)}return s}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(_.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(_.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(_.relayFailed);return n}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(n))}commit(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(n))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,n,i,s){let a=await this.getBearerToken();if(!a)throw new Error(_.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${a}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),s&&o.set("idempotency-key",s);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),c=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,l=await this.transport(new URL(c,d),{method:n,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),p={};try{p=await l.json()}catch{}if(!l.ok||p.ok!==!0){let m=Array.isArray(p.validationErrors)?p.validationErrors.join("; "):void 0;throw new te(l.status,m||p.error)}return p.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(n=>!!n&&typeof n.id=="string"&&!!n.id&&typeof n.name=="string"&&n.status==="PROTECTED"&&typeof n.createdAt=="string"&&!!n.assetSummary&&Number.isSafeInteger(n.assetSummary.count)&&n.assetSummary.count>=0&&Array.isArray(n.assetSummary.types)&&n.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(n.assetSummary.names)&&n.assetSummary.names.every(i=>typeof i=="string")&&!!n.governance&&["DIRECT","GOVERNED"].includes(n.governance.mode)&&Number.isSafeInteger(n.governance.minimumApprovals)&&n.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var Xe=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.recoveryStore=n}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let n=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),s=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!s)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let a=this.revealedAssets,o=a?.organizationId===e.organizationId&&a.planId===e.planId&&a.editId===e.editId&&a.expiresAt>Date.now();a&&!o&&(this.revealedAssets=void 0);let d=s.masterKeyEncrypted?e.masterKey??(o?a.masterKey:void 0):void 0;s.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?a.assets:await this.revealAssets(e,d,s.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(l.map(p=>p.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&n===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:s,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),n=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(n>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return n}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new z({api:{startRelaySession:n=>this.port.startRelaySession(e.organizationId,t,n),readRelaySession:n=>this.port.readRelaySession(e.organizationId,n)}}).resolve()}async revealAssets(e,t,n,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=g=>{g!==o&&(o=g,i?.(g))},c=g=>{if(g.processId!==e.editId||g.planId&&g.planId!==e.planId)return;switch(g.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let f=this.approvalError(g);if(f?.startsWith("edit_authentication_")&&d("pending_auth"),f?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!g.moderatorParticipants||g.requiredModeratorApprovals===void 0||!g.approvalProcess)return;let T=g.moderatorParticipants.map(x=>x.memberId??x.userId);T.some(x=>typeof x!="string"||!x)||new Set(T).size!==T.length||i?.(o,{requiredApprovals:g.requiredModeratorApprovals,approvedModerators:g.approvalProcess.approvedModerators,moderators:g.moderatorParticipants.map((x,k)=>{let A=T[k],H=x.flows.filter(ge=>ge.status==="PENDING"&&ge.expiresAt&&Number.isFinite(ge.expiresAt.getTime())).map(ge=>ge.expiresAt.getTime());return{id:A,displayName:a.get(A)||"Moderator",status:x.status,expiresAt:H.length?new Date(Math.min(...H)).toISOString():void 0}})})},l=await s.resume(e.planId,{onViewUpdate:c});if(l?.processId!==e.editId||l.planId&&l.planId!==e.planId)throw new Error("edit_merge_not_ready");c(l),this.assertApprovalOutcome(e.planId,l),l.status!=="READY_TO_REVEAL"&&l.status!=="REVEALED"&&await s.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let p=await s.getView(e.editId);if(p?.processId!==e.editId||p.planId&&p.planId!==e.planId)throw new Error("edit_merge_not_ready");c(p),this.assertApprovalOutcome(e.planId,p);let m=p?.status;if(m!=="READY_TO_REVEAL"&&m!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let y=null,b={onRevealed:g=>{y=g},onViewUpdate:c,onRevealStepUpdate:(g,f)=>{if(f==="IN_PROCESS")switch(g){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(n&&(b.onCustodianShareRequired=async(g,f)=>{switch(f.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let T=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),T==="SK_MOBILE")return s.distributeCustodianShareViaMobile(f.planId);if(T!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let x=e.proDevice;try{this.assertNotAborted(e.signal);let k=await s.getCustodianShareData(g);this.assertShare(k,f.planId),d("connecting_safekey_pro");let{deviceId:A}=await x.write(k,e.signal);if(this.assertNotAborted(e.signal),!A?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(f.planId,k.id,A,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(g,k.id);return}finally{x.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let T=e.proDevice;try{if(this.assertNotAborted(e.signal),!f.shareId||!f.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let x=await T.read({shareId:f.shareId,planId:f.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(x,f.planId,f.shareId),x.deviceId!==f.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:x.shares}}finally{T.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),m==="REVEALED"?await s.resumeReveal(e.editId,b,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},b,t),this.assertNotAborted(e.signal),!y)throw new Error("edit_assets_unavailable");return y}assertApprovalOutcome(e,t){let n=this.approvalError(t);if(n)throw this.clearRevealedAssets(e),new Error(n)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,n){if(!e||!e.id||e.id!==(n??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var Dr=r=>JSON.stringify(r??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([n],[i])=>n<i?-1:n>i?1:0))),Je=class{constructor(e,t,n,i){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=i}async saveAssets(e,t,n,i,s,a){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,i);a?.("preparing");let c=await o.prepare(d);this.assertNotAborted(e.signal);let l={mergeProcessId:e.editId,protectionProtocol:c.protectionProtocol,validatorShares:this.transportShares(c.validatorShares),dataShards:this.transportShares(c.dataShards),backupShards:this.transportShares(c.backupShards),encryptedKey:c.encryptedKey,assetsMetadata:c.assetsMetadata,custodianPair:c.custodianPair};if(a?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,l),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:s,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,s,l,o,d,a)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let n=await this.configurationRepository().findByPlanId(e.planId),i=n?.editDistribution??n?.preparedDistribution;if(!t&&(!i||n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let s=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),dataShards:i.dataShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),backupShards:i.backupShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,s))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let a=await this.port.status(e.organizationId,e.editId);return a.id!==e.editId||a.planId!==e.planId||a.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,s),await this.port.commit(e.organizationId,e.planId,s),await this.isCommitted(e,s)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let n=await this.configurationRepository().findByPlanId(e.planId);if(n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let n=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await n.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await n.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,n,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:s,configuration:a}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,n,i,s,a){let o,d=c=>{let l;switch(c.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":l="distributing_validators";break;case"SHARES_DISTRIBUTION":l="distributing_data";break;case"FINALIZE":l="finalizing";break;default:return}l!==o&&(o=l,a?.(l))};try{await i.execute(s,{onLocalProcessUpdated:d})}catch(c){try{if(a?.("verifying"),await this.isCommitted(e,n))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&a?.(o),c}try{if(a?.("verifying"),!await this.isCommitted(e,n))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let n=await this.port.commitStatus(e.organizationId,e.editId);if(n.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(n.status)||n.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(Dr(t.assetsMetadata)),s=await globalThis.crypto.subtle.digest("SHA-256",i),a=Array.from(new Uint8Array(s),c=>c.toString(16).padStart(2,"0")).join("");if(n.assetsMetadataHash!==a)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(c=>c.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(n.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var Ze=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new Xe(e,t,n),this.reconfiguration=new Je(e,t,n,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,n,i){return this.port.start(e,t,n,i)}async listAssets(e,t){let{assets:n}=await this.assetAccess.loadAssets(e,t);return n.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,n){let{assets:i}=await this.assetAccess.loadAssets(e,n),s=i.find(a=>a.id===t);if(!s)throw new Error("edit_asset_not_found");return structuredClone(s)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=s.findIndex(l=>l.id===e.assetId);if(a<0)throw new Error("edit_asset_not_found");let o=s[a];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},c=s.map((l,p)=>p===a?d:l);return this.reconfiguration.saveAssets(e,c,n.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=Pn({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(s.map(d=>d.id)).has(a.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,s.concat(a),n.withCustodian,i,a.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function wn({apiUrl:r,organizationId:e,planId:t,editId:n,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),c=new URL(r.endsWith("/")?r:`${r}/`);if(d.origin!==c.origin||!d.pathname.startsWith(c.pathname))throw new Error("unsupported_core_edit_route");let l=d.pathname.slice(c.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(l===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return s(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let p=Mr(l,d.searchParams,t,n),m=new Headers(o?.headers);m.set("x-organization-id",e),m.set("x-elements-environment",i);let y=c.pathname.endsWith("/integrations/")?`v1/${p}`:`integrations/v1/${p}`;return s(new URL(y,c),Object.assign({},o,{headers:m}))}}function Mr(r,e,t,n){if(r==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){let o=s[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(s[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(n)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as Or}from"@safetech/inheriti-core-sdk/node";function En(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=Ie(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new z({api:{startRelaySession:o=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>r.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>r.api.cancelMasterKeyRelaySession(o,d)}}),a=new ae(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(o,d,c)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,c)}}});return ze(a,e,t,!0)}}}function kr(r){let e=new Ee(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{...En({api:e,reconstructor:new le(r.workerUrl),assetDecoder:Or}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as et,sealInheritiFile as tt,readInheritiFileHeader as Tt,openInheritiFile as Dt,InheritiFileInvalid as Nr,MAX_INHERITI_FILE_BYTES as Mt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as nt,openInheritiFileKey as Ot}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Kr(r){let{reveal:e,api:t,signal:n}=r;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(n);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let a=r.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(r.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>Mt-1024*1024)throw new Error("unsupported_protected_asset");let d=et(),c,l=!1,p=!1;try{n?.throwIfAborted();let m=await nt(d,i.publicKey);l=!0;let y=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:m,openLimit:a},n);if(y.copyId!==r.copyId||y.status!=="PENDING")throw new Error("file_access_create_invalid");let b=await t.getFileAccess(r.copyId,n);for(;b.status==="PENDING";){if(n?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((f,T)=>{let x=()=>{clearTimeout(k),T(n?.reason)},k=setTimeout(()=>{n?.removeEventListener("abort",x),f()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",x,{once:!0})}),b=await t.getFileAccess(r.copyId,n)}if(b.status!=="READY"||b.origin!=="REVEAL"||b.copyId!==r.copyId||b.allowedUses!==a||!b.recipient||!b.deployment||b.expiresAt!==null&&(!Number.isFinite(Date.parse(b.expiresAt))||Date.parse(b.expiresAt)>s||Date.parse(b.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let g=await tt({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:b});g.fileKey.fill(0),c=g.fileBytes,n?.throwIfAborted(),await r.save({fileName:o.fileName,fileBytes:c}),p=!0}catch(m){if(l&&!p)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(y){throw new AggregateError([m,y],"protected_asset_export_and_cleanup_failed",{cause:m})}throw m}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as Io}from"@safetech/inheriti-core-sdk/node";function Sn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var rt=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Sn(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Sn(new Uint8Array(t))}},it=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var _e=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},Ce=class extends _e{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},S=class extends _e{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function kt(r){if(r instanceof _e)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Rn=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:ne(n,"issuer"),authorizationEndpoint:ne(n,"authorization_endpoint"),tokenEndpoint:ne(n,"token_endpoint"),deviceAuthorizationEndpoint:Q(n,"device_authorization_endpoint"),endSessionEndpoint:Q(n,"end_session_endpoint"),revocationEndpoint:Q(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:ne(t,"device_code"),userCode:ne(t,"user_code"),verificationUri:ne(t,"verification_uri"),verificationUriComplete:Q(t,"verification_uri_complete"),expiresInSeconds:xn(t,"expires_in"),intervalSeconds:Nt(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:ne(n,"access_token"),refreshToken:Q(n,"refresh_token"),idToken:Q(n,"id_token"),tokenType:ne(n,"token_type"),expiresInSeconds:xn(n,"expires_in"),refreshExpiresInSeconds:Nt(n,"refresh_expires_in"),scope:Q(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let s=Q(i,"error")??`oauth_http_${n.status}`;throw new S(s,Q(i,"error_description")??s)}return i}};function ne(r,e){let t=Q(r,e);if(!t)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function Q(r,e){return typeof r[e]=="string"?r[e]:void 0}function xn(r,e){let t=Nt(r,e);if(t===void 0)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function Nt(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Ur=600*1e3,st=5,Lr=5,An=class{constructor(e){this.options=e;this.crypto=e.crypto??new rt,this.clock=e.clock??new it}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+Ur;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",a),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:o}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new S("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new S("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new S("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new S("state_mismatch");let a=i.searchParams.get("error");if(a)throw new S(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new S("authorization_code_missing");let d=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),l=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(l),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new S("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(st,t.intervalSeconds??st),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new S("device_transaction_missing");let i=n,s=await this.getDiscovery(),a=Math.max(st,i.intervalSeconds??st),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(d){let c=kt(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=Lr,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new S("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new Ce;let t;try{let n=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:n.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(n){let i=kt(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Ce):(this.isOfflineSession(e)||await this.options.sessions.clear(),n)}try{if(!t.refreshToken)throw new S("refresh_token_rotation_missing");let n=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(n),n}catch(n){throw await this.options.sessions.clear(),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(pe(e.issuer)!==pe(this.options.configuration.issuer))throw new S("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${pe(t)}|${n}|${i}`}async acceptTokens(e,t,n){if(e.tokenType.toLowerCase()!=="bearer")throw new S("unsupported_token_type");let i=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(i,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new S("id_token_validation_required");let o=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(o,t),o.subject!==i.subject||o.sessionId!==i.sessionId)throw new S("token_subject_mismatch")}let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access"));return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&a?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:a,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(i.issuer))throw new S("issuer_mismatch");if(!s.includes(i.audience))throw new S("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new S("client_mismatch");if(e.environment!==i.environment)throw new S("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new S("required_claim_missing");if(n&&e.nonce!==t)throw new S("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(n.issuer))throw new S("issuer_mismatch");if(!i.includes(n.clientId))throw new S("client_mismatch");if(e.authorizedParty!==n.clientId)throw new S("client_mismatch");if(!e.subject||!e.sessionId)throw new S("required_claim_missing");if(e.nonce!==t)throw new S("nonce_mismatch")}};function pe(r){return r.replace(/\/+$/u,"")}var _n=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};import{PassphraseMasterKeySource as bo,RawMasterKeySource as wo,deriveMasterKey as Eo,generateHexSeed as So,computePassphraseVerifier as Ro}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as Ao}from"@safetech/inheriti-core-sdk/node";function Xa(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",r.environment),e(s,Object.assign({},a,{headers:o}))},n=r.business?void 0:Kt({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),i=new ce(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new ae(n,{keyVault:r.keyVault,state:r.state,api:i,reconstructor:new le(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:Fr})}function Ja(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=Kt({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ae(new Se(r.apiUrl,r.environment,r.getBearerToken,e),t)}function Za(r){if(!r.payloadStorage||!r.secureSessionStorage||!r.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=r.transport??globalThis.fetch.bind(globalThis),t=new URL(r.apiUrl).origin,n=Kt({apiUrl:t,getBearerToken:r.getBearerToken,transport:wn({apiUrl:t,organizationId:r.organizationId,planId:r.planId,editId:r.editId,environment:r.environment,transport:e}),secureSessionStorage:r.secureSessionStorage,payloadStorage:r.payloadStorage,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ze(new Ye(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as qr}from"node:crypto";import{generateRSAOAEPKeyPair as Gr}from"@safetech/inheriti-core-sdk/crypto";async function Cn(r){let e=Tt(r.fileBytes);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.copyId))throw new Error("invalid_startup_file");if(r.signal?.aborted)throw new Error("opening_cancelled");let t=await r.api.getFileAccess(e.copyId,r.signal);if(e.deployment!==t.deployment||e.origin!==t.origin||e.copyId!==t.copyId||e.recipient!==t.recipient||e.expiresAt!==t.expiresAt||e.allowedUses!==t.allowedUses)throw new Error("file_binding_mismatch");return{header:e,access:t}}async function Vr(r){let{api:e,sessionId:t,signal:n}=r;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t))throw new Error("invalid_opening_session");let i=Uint8Array.from(r.fileBytes),s,a,o=()=>{if(n?.aborted)throw new Error("opening_cancelled")};try{let{access:d}=await Cn({fileBytes:i,api:e,signal:n});if(d.status!=="READY"||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())throw new Error("file_access_unavailable");if(r.delivery==="REVEAL"&&d.origin!=="REVEAL")throw new Error("file_access_unavailable");o();let{publicKeyBase64:c,privateKey:l}=await Gr(),p=qr("sha256").update(c).digest("hex");o();let m=await e.requestFileAccessOpening(d.copyId,{sessionId:t,clientPublicKey:c,...r.delivery==="REVEAL"?{delivery:"REVEAL"}:{}});r.delivery==="REVEAL"&&r.onPairingCode?.(p.slice(0,12));let y=Math.min(Date.parse(m.expiresAt),Date.now()+3e5);if(!Number.isFinite(y))throw new Error("file_opening_expired");let b;for(;!n?.aborted&&Date.now()<y;){let T=await e.readFileAccessOpening(d.copyId,t,p,n);if(T.status==="READY"&&T.encryptedFileKey){b=T.encryptedFileKey;break}if(T.status==="EXPIRED"||T.status==="DELIVERY_CONFIRMED")throw new Error("file_opening_expired");o(),await new Promise(x=>{let k=()=>{clearTimeout(A),n?.removeEventListener("abort",k),x()},A=setTimeout(k,1e3);n?.addEventListener("abort",k,{once:!0})})}if(o(),!b)throw new Error("file_opening_expired");s=await Ot(b,l),o(),await e.confirmFileAccessDelivery(d.copyId,t,p);let g=await Dt(i,s,d);a=g.plaintext,o();let f={plaintext:a,header:g.header};return a=void 0,f}finally{i.fill(0),s?.fill(0),a?.fill(0)}}import{createHash as zr,webcrypto as Br}from"node:crypto";import{canonicalInboxManifest as $r,decodeInboxManifest as Hr,decodeInboxContentFrame as Wr,decodeInboxText as Qr,decryptInboxShare as jr,encodeInboxContentFrame as Ut,encodeInboxText as Yr,encryptInboxShare as Tn,inboxProtectedUnitCommitment as Xr,inboxTextMetadataDigest as Dn,openInboxContent as Jr,sealInboxContent as Zr,signInboxFrame as ei,unwrapInboxContentKey as ti,unwrapInboxShareKey as ni,verifyInboxFrame as Mn,wrapInboxContentKey as ri,wrapInboxShareKey as ii}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as si}from"@safetech/inheriti-core-sdk/workers/inbox.node";var $=Br,D=$,C=r=>{if(!/^[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid_inbox_key");return Buffer.from(r,"hex")},I=r=>{let e=Buffer.from(r,"base64");if(!r||e.toString("base64")!==r)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},G=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),at=async r=>new Uint8Array(await D.subtle.digest("SHA-256",Uint8Array.from(r))),Te=r=>zr("sha256").update(r).digest("hex"),re=class{constructor(e,t=new si){this.api=e;this.worker=t}async send(e){let t=await this.prepare(e);return this.api.publishInboxMessage(e.conversationId,t.submission)}async prepare(e){let{preparation:t,sender:n}=await this.prepareSender(e),i=await this.textManifest(e,t,n),s=$r(i),a=await at(s),{contentKey:o,frame:d}=await Zr(Yr(e.text),a,D),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:p}=await this.protectShares(t,d,a),m=await this.wrapRecipientKeys(t,o,a),y=await ii(l,C(e.tenantKeyHex),a,i.tenantId,i.messageId,D);return{frame:Buffer.from(Ut(d)).toString("base64"),submission:{messageId:t.messageId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,expiresAt:e.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(c).toString("base64"),tenantWrappedShareKey:Buffer.from(y).toString("base64"),recipients:m,shares:p}}}async open(e){return this.openWithCommitment(e)}openCommitted(e,t){return this.openWithCommitment(e,t)}async openWithCommitment(e,t){let n=await this.api.openInboxMessage(e.conversationId,e.messageId,e.identity.deviceId),i;try{e.signal?.throwIfAborted();let{manifest:a,manifestDigest:o,senderPublicDer:d}=await this.verifyOpening(e,n),c=await this.recoverFrame(n,a,o,e.tenantKeyHex);if(t&&!G(t,await Xr(a,Ut(c),I(n.signature),D)))throw new Error("inbox_parent_unit_mismatch");i=await this.decryptText(n,c,a,o,d,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(a){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId)}catch{}throw a}let s=await this.ack(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId,e.signal);return e.signal?.throwIfAborted(),{text:i,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:s}}async ack(e,t,n,i,s){for(let a=0;a<2;a++){s?.throwIfAborted();try{return await this.api.ackInboxMessage(e,t,n,i,s),s?.throwIfAborted(),"ACKNOWLEDGED"}catch(o){if(s?.throwIfAborted(),o instanceof q&&o.status>=400&&o.status<500)throw o}}return"PENDING"}async prepareSender(e){let t=await this.api.getInboxSendPreparation(e.conversationId);if(t.conversationId!==e.conversationId||t.threshold!==t.total||t.total!==t.shareLayers.length||t.total<2)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId);if(!n||n.deviceId!==e.identity.deviceId||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Te(I(n.signingPublicKey))!==n.signingKeyFingerprint||Te(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return{preparation:t,sender:n}}async textManifest(e,t,n){let i=Date.parse(e.expiresAt);if(!Number.isSafeInteger(i)||i<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:e.identity.tenantId,conversationId:e.conversationId,messageId:t.messageId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:C(s.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await Dn(D)}}async signFrame(e,t,n,i){let s=await D.subtle.importKey("pkcs8",I(n),"Ed25519",!1,["sign"]),a=await ei(e,t,s,D),o=await D.subtle.importKey("spki",I(i),"Ed25519",!1,["verify"]);if(!await Mn(e,t,a,o,D))throw new Error("inbox_identity_mismatch");return a}async protectShares(e,t,n){let i=await this.worker.split(Ut(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),s=D.getRandomValues(new Uint8Array(32)),a=[];for(let o=0;o<e.total;o++){let d=e.shareLayers[o];a.push({kind:"DATA",index:o,shareId:d.dataShareId,layerId:d.id,ciphertext:Buffer.from(await Tn(i.dataShares[o],s,n,e.messageId,D)).toString("base64")}),a.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await Tn(i.keyShares[o],s,n,e.messageId,D)).toString("base64")})}return{shareKey:s,shares:a}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=I(i.encryptionPublicKey);if(Te(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await D.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:Buffer.from(await ri(t,a,n,D)).toString("base64")}}))}async verifyOpening(e,t,n){let i=I(t.canonicalManifest),s=Hr(i);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!G(s.metadataDigest,n??await Dn(D)))throw new Error("inbox_manifest_mismatch");let a=s.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!a||!G(a.encryptionKeyFingerprint,C(Te(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=I(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Te(o)||!G(s.senderSigningKeyFingerprint,C(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await at(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let s=await ni(I(e.tenantWrappedShareKey),C(i),n,t.tenantId,t.messageId,D),a=[],o=[],d=new Set;for(let l of e.shares){let p=`${l.kind}:${l.index}`;if(d.has(p))throw new Error("duplicate_inbox_share");d.add(p);let m=await jr(I(l.ciphertext),s,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,D);(l.kind==="DATA"?a:o).push(m)}if(a.length!==o.length||a.length<2)throw new Error("incomplete_inbox_shares");let c=await this.worker.reconstruct(a,o,{threshold:a.length,total:a.length,messageId:t.messageId,manifestDigest:n});return Wr(c)}async decryptText(e,t,n,i,s,a){return Qr(await this.decryptContent(e,t,n,i,s,a))}async decryptContent(e,t,n,i,s,a){let o=await D.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Mn(n,t,I(e.signature),o,D))throw new Error("inbox_signature_invalid");let d=await D.subtle.importKey("pkcs8",I(a),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await ti(I(e.wrappedContentKey),d,i,D);return Jr(t,c,i,D)}};import{canonicalInboxManifest as ai,decodeInboxContentFrame as oi,decodeInboxFile as di,decryptInboxShare as ci,encodeInboxContentFrame as li,encodeInboxFile as pi,encryptInboxShare as On,inboxFileMetadataDigest as kn,sealInboxContent as ui,unwrapInboxShareKey as mi,wrapInboxShareKey as gi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var ot=class extends re{constructor(t){super(t);this.fileApi=t}async sendFile(t){t.signal?.throwIfAborted();let{preparation:n,sender:i}=await this.prepareSender(t),s=await this.fileManifest(t,n,i),a=ai(s),o=await at(a),d=pi(t.file),c;try{c=await ui(d,o,$)}finally{d.fill(0)}let{contentKey:l,frame:p}=c,m=await this.signFrame(s,p,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let y=await this.worker.split(li(p),{threshold:n.threshold,total:n.total,messageId:n.messageId,manifestDigest:o},t.signal,A=>t.onProgress?.(0,n.total*2,A.stage));t.signal?.throwIfAborted();let b=$.getRandomValues(new Uint8Array(32)),g=[];for(let A=0;A<n.total;A++){let H=n.shareLayers[A];g.push({reference:{kind:"DATA",index:A,shareId:H.dataShareId,layerId:H.id},bytes:await On(y.dataShares[A],b,o,n.messageId,$)}),g.push({reference:{kind:"KEY",index:A,shareId:H.keyShareId,layerId:H.id},bytes:await On(y.keyShares[A],b,o,n.messageId,$)})}let f=await this.wrapRecipientKeys(n,l,o),T=await gi(b,C(t.tenantKeyHex),o,s.tenantId,s.messageId,$);t.signal?.throwIfAborted();let x=await this.fileApi.stageInboxFile(t.conversationId,{messageId:n.messageId,senderDeviceId:i.deviceId,participantRevision:n.participantRevision,expiresAt:t.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(a).toString("base64"),signature:Buffer.from(m).toString("base64"),tenantWrappedShareKey:Buffer.from(T).toString("base64"),recipients:f,shares:g.map(A=>A.reference)},t.signal);if(x.messageId!==n.messageId||x.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let A=0;A<g.length;A++){t.signal?.throwIfAborted();let H=g[A];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,H.reference.shareId,H.bytes,t.signal),t.onProgress?.(A+1,g.length,"UPLOADING")}t.signal?.throwIfAborted();let k=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(k.messageId!==n.messageId||k.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return k}async openFile(t){t.signal?.throwIfAborted();let n=await this.fileApi.openInboxFile(t.conversationId,t.messageId,t.identity.deviceId,t.signal),i,s;try{let{manifest:o,manifestDigest:d,senderPublicDer:c}=await this.verifyOpening(t,n,await kn($)),l=await this.recoverFileFrame(t,n,o,d);s=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=di(s),t.signal?.throwIfAborted(),await t.save(i,{leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt}),t.signal?.throwIfAborted()}catch(o){try{await this.fileApi.releaseInboxMessage(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId)}catch{}throw o}finally{s?.fill(0)}let a=await this.ack(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId,t.signal);return t.signal?.throwIfAborted(),{name:i.name,mimeType:i.mimeType,size:i.bytes.length,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:a}}async fileManifest(t,n,i){let s=Date.parse(t.expiresAt);if(!Number.isSafeInteger(s)||s<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:t.identity.tenantId,conversationId:t.conversationId,messageId:n.messageId,senderId:t.identity.memberId,senderDeviceId:i.deviceId,senderSigningKeyFingerprint:C(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:C(a.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await kn($)}}async recoverFileFrame(t,n,i,s){let a=await mi(I(n.tenantWrappedShareKey),C(t.tenantKeyHex),s,i.tenantId,i.messageId,$),o=[],d=[],c=new Set;for(let p=0;p<n.shares.length;p++){t.signal?.throwIfAborted();let m=n.shares[p],y=`${m.kind}:${m.index}`;if(c.has(y))throw new Error("duplicate_inbox_share");c.add(y);let b=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,m.shareId,t.identity.deviceId,n.leaseId,t.signal),g=await ci(b,a,s,i.messageId,m.kind==="DATA"?"data":"key",m.index,$);(m.kind==="DATA"?o:d).push(g),t.onProgress?.(p+1,n.shares.length,"DOWNLOADING")}if(o.length!==d.length||o.length<2)throw new Error("incomplete_inbox_shares");t.signal?.throwIfAborted();let l=await this.worker.reconstruct(o,d,{threshold:o.length,total:o.length,messageId:i.messageId,manifestDigest:s},t.signal,p=>t.onProgress?.(n.shares.length,n.shares.length,p.stage));return t.signal?.throwIfAborted(),oi(l)}};import{createHash as Kn,webcrypto as Ii}from"node:crypto";import{canonicalInboxParentManifest as hi,decodeInboxParentManifest as yi,encodeInboxParentNormalFrame as fi,decodeInboxParentNormalFrame as Pi,sealInboxParentNormalBody as vi,openInboxParentNormalBody as bi,wrapInboxParentNormalKey as wi,unwrapInboxParentNormalKey as Ei,signInboxParentNormalFrame as Si,verifyInboxParentNormalFrame as Nn,encodeInboxText as Ri,decodeInboxText as xi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var V=Ii,De=r=>Kn("sha256").update(r).digest("hex"),dt=r=>Buffer.from(r).toString("base64"),ct=class{constructor(e){this.api=e}pending=new Map;async send(e){let t=this.digestInput(e),n=e.parentId?this.pending.get(e.parentId):void 0;if(n){if(n.inputDigest!==t)throw new Error("inbox_idempotency_conflict");let c=await this.api.publishNormalInboxMessage(e.conversationId,n.submission);return this.pending.delete(e.parentId),c}let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validatePreparation(e,i),a=this.createManifest(e,i,s),o=await this.createSubmission(e,i,s,a);this.rememberSubmission(a.parentId,t,o);let d=await this.api.publishNormalInboxMessage(e.conversationId,o);return this.pending.delete(a.parentId),d}digestInput(e){return Kn("sha256").update(JSON.stringify([e.conversationId,e.parentId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.text])).digest("hex")}validatePreparation(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||De(I(n.signingPublicKey))!==n.signingKeyFingerprint||De(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}createManifest(e,t,n){return{mode:"NORMAL",tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:e.parentId??t.parentId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:C(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let s=hi(i),{contentKey:a,frame:o}=await vi(Ri(e.text),i,V),d=await V.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await Si(i,o,d,V),l=await V.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Nn(i,o,c,l,V))throw new Error("inbox_identity_mismatch");let p=await Promise.all(t.recipients.map(m=>this.wrapRecipientKey(m,a,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:dt(s),frame:dt(fi(o)),signature:dt(c),recipients:p}}async wrapRecipientKey(e,t,n){let i=I(e.encryptionPublicKey);if(De(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await V.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:e.memberId,deviceId:e.deviceId,deviceVersion:e.deviceVersion,keyFingerprint:e.encryptionKeyFingerprint,wrappedContentKey:dt(await wi(t,s,n,V))}}rememberSubmission(e,t,n){if(this.pending.size>=32){let i=this.pending.keys().next().value;i&&this.pending.delete(i)}this.pending.set(e,{inputDigest:t,submission:n})}list(e,t,n){return this.api.listNormalInboxMessages(e,t,n)}async open(e){e.signal?.throwIfAborted();let t=await this.api.openNormalInboxMessage(e.conversationId,e.parentId,e.identity.deviceId,e.signal),n=yi(I(t.canonicalManifest));if(n.mode!=="NORMAL"||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch");let i=n.recipients.find(p=>p.memberId===e.identity.memberId&&p.deviceId===e.identity.deviceId);if(!i||!G(i.encryptionKeyFingerprint,C(De(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=I(t.senderSigningPublicKey);if(!G(n.senderSigningKeyFingerprint,C(De(s))))throw new Error("inbox_sender_key_mismatch");let a=Pi(I(t.frame)),o=await V.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Nn(n,a,I(t.signature),o,V))throw new Error("inbox_signature_invalid");let d=await V.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Ei(I(t.wrappedContentKey),d,n,V),l=xi(await bi(a,c,n,V));return e.signal?.throwIfAborted(),{text:l,parentId:t.parentId,sequence:t.sequence}}markRead(e){return this.api.markNormalInboxMessageRead(e.conversationId,e.parentId,e.identity.deviceId)}};import{createHash as Fn,webcrypto as Ai}from"node:crypto";import{canonicalInboxParentManifest as _i,decodeInboxParentManifest as Ci,decodeInboxManifest as Ti,encodeInboxParentNormalFrame as Di,decodeInboxParentNormalFrame as Mi,sealInboxParentNormalBody as Oi,openInboxParentNormalBody as ki,wrapInboxParentNormalKey as Ni,unwrapInboxParentNormalKey as Ki,signInboxParentNormalFrame as Ui,verifyInboxParentNormalFrame as Un,signInboxProtectedParent as Li,verifyInboxProtectedParent as Ln,inboxProtectedUnitCommitment as Fi,encodeInboxText as qi,decodeInboxText as Gi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var K=Ai,lt=r=>Buffer.from(r).toString("base64"),Me=r=>Fn("sha256").update(r).digest("hex"),pt=class{constructor(e,t){this.api=e;this.child=t??new re(e)}pending=new Map;child;async send(e){let t=Fn("sha256").update(JSON.stringify([e.conversationId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.segments])).digest("hex"),n=e.parentId?[e.parentId,this.pending.get(e.parentId)]:[...this.pending.entries()].find(([,o])=>o.digest===t),i=n?.[1];if(i){if(i.digest!==t)throw new Error("inbox_idempotency_conflict");try{e.onProgress?.(i.submission.protectedUnits.length,i.submission.protectedUnits.length)}catch{}let o=await this.api.publishInboxParent(e.conversationId,i.submission);return this.pending.delete(n[0]),o}let s=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(s.parentId,{digest:t,submission:s});let a=await this.api.publishInboxParent(e.conversationId,s);return this.pending.delete(s.parentId),a}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let t=e.segments.filter(y=>"protectedText"in y).length;if(t<1||t>4)throw new Error("invalid_inbox_parent_segments");let n=e.segments.length===1&&t===1?"PROTECTED":"MIXED";if(n==="MIXED"&&!e.segments.some(y=>"text"in y))throw new Error("invalid_inbox_parent_segments");let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validateSender(e,i),a=e.parentId??i.parentId,{protectedUnits:o,manifestUnits:d}=await this.prepareChildren(e,i,s),c=this.parentManifest(e,i,s,a,n,d),{frame:l,signature:p,recipients:m}=await this.signAndWrap(e,i,s,c);return{parentId:a,idempotencyKey:a,senderDeviceId:s.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:lt(_i(c)),signature:lt(p),frame:l,recipients:m,protectedUnits:o}}async prepareChildren(e,t,n){let i=[],s=[],a=e.segments.filter(o=>"protectedText"in o).length;for(let o=0;o<e.segments.length;o++){let d=e.segments[o];if(!("protectedText"in d))continue;let c=await this.child.prepare({conversationId:e.conversationId,text:d.protectedText,expiresAt:d.expiresAt,identity:e.identity,tenantKeyHex:e.tenantKeyHex}),l=Ti(I(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let p=await Fi(l,I(c.frame),I(c.submission.signature),K);i.push({position:o,frame:c.frame,child:c.submission}),s.push({unitId:c.submission.messageId,position:o,commitment:p});try{e.onProgress?.(i.length,a)}catch{}}return{protectedUnits:i,manifestUnits:s}}validateChildSnapshot(e,t,n,i){if(e.tenantId!==t.identity.tenantId||e.conversationId!==t.conversationId||e.senderId!==t.identity.memberId||e.senderDeviceId!==i.deviceId||e.participantRevision!==n.participantRevision||e.recipients.length!==n.recipients.length||e.recipients.some(s=>!n.recipients.some(a=>a.memberId===s.memberId&&a.deviceId===s.deviceId&&G(s.encryptionKeyFingerprint,C(a.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,t,n,i,s,a){return{mode:s,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:i,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:C(o.encryptionKeyFingerprint)})),protectedUnits:a}}async signAndWrap(e,t,n,i){let s=await K.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),a=await K.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(i.mode==="PROTECTED")return{signature:await this.signProtectedParent(i,s,a),recipients:this.recipientReferences(t)};let{frame:o,signature:d,contentKey:c}=await this.sealMixedParent(e,i,s,a);return{frame:o,signature:d,recipients:await this.wrapRecipients(t,c,i)}}async signProtectedParent(e,t,n){let i=await Li(e,t,K);if(!await Ln(e,i,n,K))throw new Error("inbox_identity_mismatch");return i}async sealMixedParent(e,t,n,i){let s=e.segments.map((d,c)=>"text"in d?{text:d.text}:{unitId:t.protectedUnits.find(l=>l.position===c).unitId}),a=await Oi(qi(JSON.stringify(s)),t,K),o=await Ui(t,a.frame,n,K);if(!await Un(t,a.frame,o,i,K))throw new Error("inbox_identity_mismatch");return{frame:lt(Di(a.frame)),signature:o,contentKey:a.contentKey}}recipientReferences(e){return e.recipients.map(t=>({memberId:t.memberId,deviceId:t.deviceId,deviceVersion:t.deviceVersion,keyFingerprint:t.encryptionKeyFingerprint}))}async wrapRecipients(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=I(i.encryptionPublicKey);if(Me(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await K.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:lt(await Ni(t,a,n,K))}}))}validateSender(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Me(I(n.signingPublicKey))!==n.signingKeyFingerprint||Me(I(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}list(e,t,n){return this.api.listInboxParents(e,t,n)}clearHistory(e,t){return this.api.clearInboxHistory(e,t)}async open(e){let{opened:t,manifest:n,segments:i}=await this.openAndVerify(e);return{parentId:t.parentId,sequence:t.sequence,mode:n.mode,segments:i}}async openAndVerify(e){e.signal?.throwIfAborted();let t=await this.api.openInboxParent(e.conversationId,e.parentId,e.identity.deviceId,e.signal),{manifest:n,senderKey:i}=await this.verifyOpening(e,t),s=n.mode==="PROTECTED"?await this.openProtectedParent(t,n,i):await this.openMixedParent(e,t,n,i);return e.signal?.throwIfAborted(),{opened:t,manifest:n,segments:s}}async verifyOpening(e,t){let n=Ci(I(t.canonicalManifest));return this.verifyManifestContext(e,t,n),this.verifyManifestUnits(t,n),this.verifyRecipient(e,n),{manifest:n,senderKey:await this.senderKey(t,n)}}verifyManifestContext(e,t,n){if(n.mode!==t.mode||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch")}verifyManifestUnits(e,t){if(t.protectedUnits.length!==e.protectedUnits.length||t.protectedUnits.some((n,i)=>n.unitId!==e.protectedUnits[i].unitId||n.position!==e.protectedUnits[i].position||!G(n.commitment,C(e.protectedUnits[i].commitment))))throw new Error("inbox_manifest_mismatch")}verifyRecipient(e,t){let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||!G(n.encryptionKeyFingerprint,C(Me(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,t){let n=I(e.senderSigningPublicKey);if(Me(n)!==e.senderSigningKeyFingerprint||!G(t.senderSigningKeyFingerprint,C(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return K.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await Ln(t,I(e.signature),n,K))throw new Error("inbox_signature_invalid");return[{unitId:t.protectedUnits[0].unitId,position:0,status:e.protectedUnits[0].status}]}async openMixedParent(e,t,n,i){if(!t.frame||!t.wrappedContentKey)throw new Error("inbox_missing_normal_body");let s=Mi(I(t.frame));if(!await Un(n,s,I(t.signature),i,K))throw new Error("inbox_signature_invalid");let a=await K.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await Ki(I(t.wrappedContentKey),a,n,K),d=JSON.parse(Gi(await ki(s,o,n,K)));return this.decodeSegments(d,t,n)}decodeSegments(e,t,n){if(!Array.isArray(e))throw new Error("invalid_inbox_parent_body");let i=e.map((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error("invalid_inbox_parent_body");let o=s;if(typeof o.text=="string"&&Object.keys(o).length===1)return{text:o.text};let d=n.protectedUnits.find(c=>c.position===a);if(!d||o.unitId!==d.unitId||Object.keys(o).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:d.unitId,position:a,status:t.protectedUnits.find(c=>c.unitId===d.unitId).status}});if(n.protectedUnits.some(s=>!i[s.position]||!("unitId"in i[s.position])))throw new Error("invalid_inbox_parent_body");return i}async revealUnit(e){let{manifest:t,segments:n}=await this.openAndVerify(e);if(!n.some(s=>"unitId"in s&&s.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let i=t.protectedUnits.find(s=>s.unitId===e.unitId);return this.child.openCommitted({conversationId:e.conversationId,messageId:e.unitId,identity:e.identity,tenantKeyHex:e.tenantKeyHex,signal:e.signal},i.commitment)}};export{ue as BusinessOrganizationSelectionError,xe as CorePlanMaterialBuilder,Io as DataAssetDefinitionService,q as ElementsApiRequestFailed,ae as ElementsClient,ve as GuidedCreateRecoveryError,Pe as GuidedPlanCreator,Ee as HttpAutomationRevealApiPort,ce as HttpElementsApiPort,Rn as HttpOperatorAuthTransport,Ye as HttpPlanEditPort,Se as HttpQuickPlanPort,Nr as InheritiFileInvalid,w as InvalidPlanDeclaration,N as InvalidPlanMaterial,Mt as MAX_INHERITI_FILE_BYTES,Ne as MasterKeyRelayCancellationFailed,ke as MasterKeyRelayExpired,Oe as MasterKeyRelayTimedOut,j as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,he as MemoryKeyVault,ye as MemoryStatePort,ot as NodeInboxFile,ct as NodeInboxNormal,pt as NodeInboxParent,re as NodeInboxText,S as OAuthProtocolError,An as OperatorAuthClient,_e as OperatorAuthError,Ce as OperatorReauthenticationRequired,_n as OperatorSessionController,ht as PLAN_CREATION_SERVER_STAGES,bo as PassphraseMasterKeySource,Ao as PlanAssetDeclaration,te as PlanRequestFailed,Ae as QuickPlanCreator,Ze as QuickPlanEditor,wo as RawMasterKeySource,z as RelayMasterKeySource,mt as StaticMasterKeyResolver,it as SystemOAuthClock,rt as WebOAuthCrypto,Ro as computePassphraseVerifier,Ke as createMasterKeyResolver,kr as createNodeAutomationRevealClient,Xa as createNodeElementsClient,Ja as createNodeQuickPlanCreator,Za as createNodeQuickPlanEditor,Fr as decodeAssetContainer,Eo as deriveMasterKey,Kr as exportProtectedRevealAsset,So as generateHexSeed,et as generateInheritiFileKey,Cn as inspectInheritiFileAccess,Ie as masterKeyRefFor,J as masterKeyRefKey,kt as oauthErrorCode,Dt as openInheritiFile,Vr as openInheritiFileAccess,Ot as openInheritiFileKey,Tt as readInheritiFileHeader,tt as sealInheritiFile,nt as sealInheritiFileKey,fr as selectBusinessOrganization,St as unwrapDekWithMasterKey,Z as validatePlanCreationInput,se as validatePlanCreationMaterial};
|
|
1
|
+
import{createNodeSharedConfigurationSdk as Ut,decodeAssetContainer as Hr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Vn,generateRSAOAEPKeyPair as zn}from"@safetech/inheriti-core-sdk/crypto";var Oe=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Ne=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},Ke=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},H=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 zn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(g=>new Promise(f=>setTimeout(f,g))),c=!0,l=!1,p,m=()=>p??=(async()=>{let g=new AbortController,f,T=new Promise((R,O)=>{f=setTimeout(()=>{g.abort(),O(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,g.signal),T])}finally{clearTimeout(f)}})(),y,w=new Promise((g,f)=>{y=()=>{c&&m().catch(()=>{}),f(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",y,{once:!0})});w.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let g=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),w]);if(g.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(g.status==="DELIVERED"&&g.sealedMasterKey){let f=(await Vn(g.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(f))throw new Error("invalid_master_key_material");return f}if(g.status==="EXPIRED")throw new Ne(s.sessionId);await $n(d,a,e)}throw new Oe(s.sessionId)}catch(g){if(c&&(!l||e?.aborted))try{await m()}catch(f){if(e?.aborted)throw new Ke(f)}throw g}finally{y&&e?.removeEventListener("abort",y)}}};async function $n(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function Ue(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||gt(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(Hn(e,r.applicationId)){let i=await r.source?.resolve();return i||gt(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return gt(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function Hn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function gt(r,e,t,n,i){if((await e()).relayAvailable)return new H({...r.relay,api:Wn(r.api,t)}).resolve(n,i)}function Wn(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 te(r){return`${r.system}:${r.contextId}`}function ye(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:${te(t)}`);this.ref=t;this.name="MasterKeyRequired"}},ht=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(te(e),t),this}async resolve(e){return this.sources.get(te(e))?.resolve()}};var fe=class{keys=new Map;async store(e,t){let n=te(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(te(e))?.slice()}async remove(e){let t=te(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ve=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 Le=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},v=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Fe=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"],yt={"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"]},ft=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],S=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},N=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function de(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new N("plan_material_field_unknown");if(It(r.dataShards,"data_shards_invalid"),It(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&It(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new N("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new N("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new N("material_operation_invalid")}function It(r,e){if(!Array.isArray(r))throw new N(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new N(e);if(t.data!==void 0&&typeof t.data!="string")throw new N(e)}}function ne(r){if(oe(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Yn(r.idempotencyKey))throw new S("idempotency_key_invalid");if(!r.name?.trim())throw new S("plan_name_required");if(!r.assets.length)throw new S("assets_required");let e=new Set;for(let t of r.assets){if(oe(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 S("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!qe.includes(t.type))throw new S("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new S("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 S("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new S("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new S("asset_field_names_invalid");if(jn(t.matchOrigins),!t.isBinary){let s=yt[t.type];if(!s||i.some(a=>!s.includes(a)))throw new S("asset_field_name_not_canonical")}}if(!r.participants.length)throw new S("participants_required");for(let t of r.participants){if(oe(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!qt(t.routingEmail))throw new S("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new S("participant_relationships_invalid")}Qn(r)}function jn(r){if(r===void 0)return;if(!r.length)throw new S("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new S("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new S("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof S?n:new S("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new S("asset_match_origins_duplicated")}function Qn(r){let e=r.policy;if(e&&oe(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new S("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){oe(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new S("authentication_mode_invalid")}if(e.moderation){oe(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new S("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new S("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new S("approval_mode_invalid")}let t=e.dms;if(!t)return;oe(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!qt(t.subjectEmail))throw new S("dms_subject_invalid");if(!r.participants.some(s=>Ft(s.routingEmail)===Ft(t.subjectEmail)))throw new S("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 S("dms_countdown_invalid")}function Yn(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 qt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Ft(r){return r.normalize("NFC").trim().toLowerCase()}function oe(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new S(t)}var be=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},Pe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),ne(e),Ge(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,s={}){ne(t);let a=await this.checkpoints.load(e);if(!a)throw new we("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await Gt(t))throw new we("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Ge(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});Ge(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});Ge(s.signal),de(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(l.stage),l.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,l),l}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await Gt(e),serverStage:t.stage})}},we=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Gt(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 Bt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Le(n.stage);return r.authorizeRevealAction(e,t)}function Xn(r){let e=r?.status;return e===400||e===401||e===403}async function Vt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Xn(s))throw s}return r.releaseRevealMaterial(e,t)}function Jn(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?er(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":Zn.has(r.stage)?"ENDED":"CONTINUING"}var Zn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function er(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 vt=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},D=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function ze(r,e,t={},n=!1){if(t.signal?.aborted)throw A();let i=await r.getPlan(e),s=await r.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):zt(s.id);if(t.signal?.aborted)throw A();let a=()=>r.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)});if(n||await a(),t.signal?.aborted)throw A();let o=t.idempotencyKey??crypto.randomUUID(),d;try{d=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:o,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let p=await r.getActivePlanReveal(e);throw!p||p.planId!==e||p.mode!==(t.mode??"DIRECT")||p.protectedCopy!==void 0&&p.protectedCopy!==(t.protectedCopy??!1)?l:zt(p.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let c;try{if(t.signal?.aborted)throw A();let l=await nr(r,d,t);if(t.signal?.aborted||(n&&await a(),t.signal?.aborted)||(re(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw A();let p=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id),t.signal?.aborted))throw A();let m;try{m=await ar(r,l,dr(p),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(re(t,"RECONSTRUCTING",l),t.signal?.aborted))throw A();try{c=await r.reconstructPlanMaterial(m)}catch(w){throw t.signal?.aborted?A():(await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:sr(w)}),w)}if(t.signal?.aborted)throw A();let y=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(re(t,"OPEN",y),t.signal?.aborted))throw A();return new Pt(r,y,i,c,t.signal)}catch(l){throw c?.fill(0),await Wt(r,d.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function zt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var tr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function nr(r,e,t){let n=await Z(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw A();if(t.onSession?.(n),t.onProgress?.({phase:Jn(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(tr.has(n.stage))throw new bt(n.stage);await wt(t.pollIntervalMs??1500,t.signal),n=await Z(()=>r.getReveal(e.id,t.signal),t.signal)}}var bt=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function re(r,e,t){r.onProgress?.({phase:e,session:t})}function wt(r,e){return e?.aborted?Promise.reject(A()):new Promise((t,n)=>{let i=setTimeout(a,Math.max(0,r)),s=()=>{clearTimeout(i),n(A())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Pt=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new vt;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 D("asset_selector_invalid");if(!this.client.assetDecoder)throw new D("asset_decoder_required");let n=e.map(({selector:s,options:a={}})=>{let o=rr(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new D("asset_not_found");if(d.isBinary)throw new D("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new D("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),i=[];try{for(let a of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:a.options.idempotencyKey??crypto.randomUUID(),assetId:a.asset.id,fieldName:a.field,action:a.options.action??"VIEW_FIELD",...a.options.destination===void 0?{}:{destination:a.options.destination},...a.options.origin===void 0?{}:{origin:a.options.origin}}));let s=n.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new D("asset_value_invalid");return{selector:a.selector,value:ir(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",$t(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new D("asset_selector_invalid");if(!this.client.assetDecoder)throw new D("asset_decoder_required");let n=this.plan.assets.find(a=>a.code===e||a.id===e);if(!n)throw new D("asset_not_found");if(!n.isBinary)throw new D("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!a||!(a.data instanceof Uint8Array))throw new D("asset_value_invalid");s=a.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",$t(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Wt(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 rr(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new D("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new D("asset_selector_invalid");return{asset:r.asset,field:r.field}}function ir(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new D("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new D("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?yt[t]:void 0)?.includes(e))return"";throw new D("asset_value_invalid")}return n[e]}function $t(r){if(r instanceof D)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 sr(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function ar(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await Z(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Be;let c=await Z(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(Ht(c,i.id,e.planId),!c.shares.includes(i.data))throw new Y;re(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await Z(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw A();if(!l?.trim())throw new Y;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw A();return{...t,shares:t.shares.filter(p=>p!==i).concat(c.shares.map((p,m)=>({id:`${c.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:p})))}}if(d!=="SK_MOBILE")throw new Y;if(n.signal?.aborted)throw A();return await r.distributeRevealCustodianShare(e.id),re(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await Z(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),re(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await wt(n.pollIntervalMs??1500,n.signal),s=await Z(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Be;if(!s.shareId||!s.deviceId)throw new Y;re(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Z(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw A();if(Ht(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new Y;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw A();return{...t,shares:t.shares.concat(d.shares.map((c,l)=>({id:`${d.id}:${l}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new Y;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(a),re(n,"WAITING_FOR_CUSTODIAN",a),n.signal?.aborted)throw A();await r.requestRevealCustodianRelease(e.id);let o=await or(r,e,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function Ht(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 Y}async function Z(r,e){if(e?.aborted)throw A();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(A()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw A();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function or(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Ve;let s=await Z(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Ve;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new Y}await wt(t.pollIntervalMs??1500,t.signal)}}var Y=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Be=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ve=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function dr(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function Wt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(a){if(!cr(a))throw a}return}let n=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(a.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(a){if(a?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:a}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function cr(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function A(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var ce=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 fe,this.state=t.state??new ve,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??ur(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 v;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new v;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new v;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new v;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new v;return ne(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new v;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new v;return de(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new v;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new be){if(this.requireApplication(),!this.api)throw new v;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 pr(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new J(e);return await this.keyVault.store(e,lr(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new v;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 v;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Fe;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=ye(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 v;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new v;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new v;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new v;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new v;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new v;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new v;return this.api.getReveal(e,t)}openReveal(e,t){return ze(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new v;return Vt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new v;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new v;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new v;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new v;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new v;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new v;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new v;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new v;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new v;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new v;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new v;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new v;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new v;return Bt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new v;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new v;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new v;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new v;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new v;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new v;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new v;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 St;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new J({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},St=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};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){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function ur(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return Ue({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Ue({...e,organizationId:r.organizationId})}var mr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],gr=["DIRECT","GOVERNED"],Qt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],hr=["ACTIVE","REVOKED"],Ir=["SK_MOBILE"],yr=["ACTIVE","INACTIVE"],fr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Yt(r){let e=M(r);return{items:B(e.items).map(Zt),nextCursor:e.nextCursor===null?null:I(e.nextCursor,"nextCursor")}}function Xt(r){let e=M(r);return{total:W(e.total,"total"),items:B(e.items).map(t=>{let n=M(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:B(n.details).map(i=>{let s=M(i);return{label:I(s.label,"log.detail.label"),value:I(s.value,"log.detail.value")}})}})}}function Jt(r){let e=M(r);return{total:W(e.total,"total"),items:B(e.items).map(t=>{let n=M(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=I(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:I(n.id,"log.id"),memberId:I(n.memberId,"log.memberId"),source:i,event:I(n.event,"log.event"),occurredOn:I(n.occurredOn,"log.occurredOn"),status:ee(n.status)}})}}function $e(r){let e=M(r),t=Zt(e),n=M(e.source),i=I(n.kind,"source.kind");return{...t,assets:B(e.assets).map(s=>{let a=M(s);return{id:I(a.id,"asset.id"),code:ee(a.code),type:G(I(a.type,"asset.type"),qe),name:I(a.name,"asset.name"),isBinary:br(a.isBinary,"asset.isBinary"),fieldNames:B(a.fieldNames).map(o=>I(o,"asset.fieldNames")),fileName:ee(a.fileName),mimeType:ee(a.mimeType),size:a.size===void 0||a.size===null?void 0:W(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:B(a.matchOrigins).map(o=>I(o,"asset.matchOrigins"))}}),participants:B(e.participants).map(s=>{let a=M(s);return{id:I(a.id,"participant.id"),displayName:I(a.displayName,"participant.displayName"),relationships:B(a.relationships).map(o=>G(I(o,"relationship"),Qt)),lifecycle:G(I(a.lifecycle,"participant.lifecycle"),hr)}}),revealPolicy:(()=>{let s=M(e.revealPolicy);return{masterKeyRelease:G(I(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:G(I(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=M(e.dms);return{subjectEmail:I(s.subjectEmail,"dms.subjectEmail"),countdownDays:W(s.countdownDays,"dms.countdownDays"),countdownHours:W(s.countdownHours,"dms.countdownHours"),countdownMinutes:W(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:G(I(n.system,"source.system"),["INHERITI_BUSINESS"]),status:G(I(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function Se(r){let e=M(r);return{operationId:I(e.operationId,"operationId"),stage:G(I(e.stage,"stage"),ft),outcome:G(I(e.outcome,"outcome"),fr),planId:ee(e.planId),lastErrorCode:ee(e.lastErrorCode),participants:e.participants===void 0?void 0:B(e.participants).map(t=>{let n=M(t);return{clientParticipantRef:I(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:I(n.planParticipantId,"planParticipantId"),relationships:B(n.relationships).map(i=>vr(I(i,"relationship"),Qt))}})}}function Zt(r){let e=M(r),t=M(e.assetSummary),n=M(e.governance),i=M(e.participantSummary);return{id:I(e.id,"id"),name:I(e.name,"name"),description:ee(e.description),status:G(I(e.status,"status"),mr),createdAt:I(e.createdAt,"createdAt"),configuredAt:ee(e.configuredAt),assetSummary:{count:W(t.count,"assetSummary.count"),types:B(t.types).map(s=>G(I(s,"assetType"),qe)),names:jt(t.names).map(s=>I(s,"assetSummary.names"))},governance:{mode:G(I(n.mode,"governance.mode"),gr),minimumApprovals:W(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:W(i.owners,"owners"),mergers:W(i.mergers,"mergers"),moderators:W(i.moderators,"moderators")},authentication:jt(e.authentication).map(s=>{let a=M(s);return{id:G(I(a.id,"authentication.id"),Ir),status:G(I(a.status,"authentication.status"),yr)}})}}function G(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function vr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function M(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function jt(r){return r==null?[]:B(r)}function B(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 br(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var ge=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function en(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 Pr(r,e){if(!e){if(r.length===0)throw new ge("organization_required");if(r.length>1)throw new ge("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new ge("organization_access_denied");return e}function wr(r){let e=E(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),createdAt:F(e.createdAt),...tn(e)}}function tn(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=E(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:u(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:F(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=E(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:P(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:F(i.revealedAt)}:{}}})}:{}}})}}function nn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(wr),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 rn(r){let e=E(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=E(t);return{unitId:u(n.unitId),position:P(n.position,0),commitment:u(n.commitment),status:u(n.status)}})}}function Et(r){let e=E(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:P(e.sequence,1),status:e.status}}function sn(r){let e=E(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),parentId:u(e.parentId),participantRevision:P(e.participantRevision,1),recipients:e.recipients.map(At)}}function an(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);return{parentId:u(n.parentId),sequence:P(n.sequence,1),senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),participantRevision:P(n.participantRevision,1),createdAt:F(n.createdAt),...tn(n)}}),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 on(r){return{readThroughSequence:P(E(r).readThroughSequence,0)}}function dn(r){return{clearedThroughSequence:P(E(r).clearedThroughSequence,0)}}function cn(r){let e=E(r);return{parentId:u(e.parentId),sequence:P(e.sequence,1),senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),canonicalManifest:u(e.canonicalManifest),frame:u(e.frame),signature:u(e.signature),wrappedContentKey:u(e.wrappedContentKey),senderSigningPublicKey:u(e.senderSigningPublicKey)}}function E(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function u(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function F(r){let e=u(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 At(r){let e=E(r);return{memberId:u(e.memberId),deviceId:u(e.deviceId),deviceVersion:P(e.deviceVersion,1),encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint)}}function he(r){let e=E(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:u(e.id),tenantId:u(e.tenantId),memberId:u(e.memberId),version:e.version,encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint),status:e.status,createdAt:F(e.createdAt),updatedAt:F(e.updatedAt)}}function He(r){let e=E(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:u(e.id),tenantId:u(e.tenantId),creatorMemberId:u(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(u),participantRevision:e.participantRevision,status:e.status,createdAt:F(e.createdAt),updatedAt:F(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=E(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:u(n.senderMemberId),createdAt:F(n.createdAt)}}return t}function ln(r){let e=E(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(He),total:e.total,limit:e.limit,offset:e.offset}}function pn(r){let e=E(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=At(t);return{memberId:n.memberId,name:u(E(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function un(r){let e=E(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:u(n.memberId),name:u(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:u(E(n.profilePicture).url)}}}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function mn(r){let e=E(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),messageId:u(e.messageId),participantRevision:P(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(At),shareLayers:e.shareLayers.map(t=>{let n=E(t),i=u(n.id),s=u(n.dataShareId),a=u(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:u(n.contractAddress),dataShareId:s,keyShareId:a};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function We(r){let e=E(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:u(e.messageId),status:e.status}}function gn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:u(n.id),status:n.status,senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),createdAt:F(n.createdAt),updatedAt:F(n.updatedAt),expiresAt:F(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let a=E(s);if(a.status!=="UNREAD"&&a.status!=="LEASED"&&a.status!=="CONSUMED"&&a.status!=="EXPIRED"&&a.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:u(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:F(a.consumedAt)}:{}}})),i}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0)}}function hn(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:F(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId),ciphertext:u(n.ciphertext)}})}}function In(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:F(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId)}})}}function le(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 pe(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var V=class extends Error{constructor(t,n,i,s){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ue=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,n,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":n},i)}confirmFileAccessDelivery(e,t,n){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":n})}createInboxFileAccess(e,t,n,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",n,void 0,void 0,i)}createRevealFileAccess(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,n)}cancelRevealFileAccess(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",n)}cancelInboxFileAccess(e,t,n,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let n=t;if(typeof n.publicKey!="string"||!n.publicKey||typeof n.fingerprint!="string"||!n.fingerprint||n.status!=="ACTIVE"&&n.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:n.publicKey,fingerprint:n.fingerprint,status:n.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:he(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:he(n)}async registerInboxDevice(e){return he(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return he(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return he(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return He(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return He(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 ln(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 pn(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 un(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return mn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return sn(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 We(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return Et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return Et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return nn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return dn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return an(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return cn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return on(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return We(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let a=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(a,"PUT",i,s),d=await je(o,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new V(o.status,le(d),pe(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return We(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return In(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,c=await this.requestBinary(d,"GET",void 0,a);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let l=Number(c.headers.get("content-length"));if(Number.isFinite(l)&&l>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let p=c.body.getReader(),m=[],y=0;try{for(;;){a?.throwIfAborted();let f=await p.read();if(f.done)break;if(y+=f.value.length,y>14*1024*1024)throw new Error("invalid_inbox_share_size");m.push(f.value)}}catch(f){throw await p.cancel().catch(()=>{}),f}let w=new Uint8Array(y),g=0;for(let f of m)w.set(f,g),g+=f.length;return w}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return gn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return hn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(en)}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 Yt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return $e(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 Xt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let n=new URLSearchParams;t.source&&n.set("source",t.source),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Jt(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){ne(e);let{idempotencyKey:t,...n}=e;return Se(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return Se(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return de(t),Se(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return Se(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,s,a){this.requireBusinessSelection(e),a?.throwIfAborted();let o=await this.getBearerToken();a?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[y,w]of Object.entries(s??{}))d.set(y,w);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:n?JSON.stringify(n):void 0};a&&(l.signal=a);let p=await this.transport(new URL(e,c),l);a?.throwIfAborted();let m=await je(p,a);if(a?.throwIfAborted(),!p.ok)throw new V(p.status,le(m),pe(m),p.headers.get("x-request-id")??void 0);if(!m.ok||m.result===void 0)throw new V(p.status,le(m),pe(m),p.headers.get("x-request-id")??void 0);return m.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let a=new Headers({"x-elements-environment":this.environment});s&&a.set("authorization",`Bearer ${s}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),n&&a.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:a,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await je(d,i);throw new V(d.status,le(c),pe(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let a=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});a&&o.set("authorization",`Bearer ${a}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId);for(let[p,m]of Object.entries(n??{}))o.set(p,m);t&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:o,body:t?JSON.stringify(t):void 0,signal:s}),l=await je(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new V(c.status,le(l),pe(l),c.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new V(400,"organization_selection_required")}};async function je(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 Tr}from"@safetech/inheriti-core-sdk/node";async function Rt(r,e){if(!e)throw new Error("master_key_required");let t=Sr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Er(r),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,a);return Ar(new Uint8Array(o))}function Sr(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 Er(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 Ar(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Ee=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await yn("plan_key_unwrap_failed",()=>Rt(e.planKey,t)),i=await crypto.subtle.importKey("raw",xt(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await yn("plan_share_decryption_failed",()=>Cr(o.data,i));_r(o.shareType)?a.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new Qe("plan_share_reconstruction_failed",xr(o))}}},Qe=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},Rr=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 xr(r){let e=r instanceof Error?r.message:void 0;if(e)return Rr.has(e)?e:void 0}async function yn(r,e){try{return await e()}catch{throw new Qe(r)}}function _r(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function Cr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=xt(r.slice(0,t)),i=xt(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function xt(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 me=class extends Ee{constructor(e){super(()=>Tr(e))}};var Ae=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 $e(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,s,a){a?.throwIfAborted();let o=await this.getAutomationBearerToken();if(a?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...s});n!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:a});a?.throwIfAborted();let l;try{l=await c.json()}catch{a?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new V(c.status,l&&le(l),l&&pe(l));return l?.result}};var _={invalidDeclaration:"plan_declaration_invalid",invalidShares:"plan_share_count_invalid",storageChanged:"plan_storage_context_changed",invalidMasterKeyContext:"invalid_master_key_context",reauthenticationRequired:"operator_reauthentication_required",relayFailed:"master_key_relay_failed",reconciliationRequired:"reconciliation_required"};var ie=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},Re=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,n,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:n.validatorShares,encryptedKey:n.encryptedKey})}preflight(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",fn(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",fn(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(_.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(_.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(_.relayFailed);return n}async request(e,t,n,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(_.reauthenticationRequired);s.set("authorization",`Bearer ${a}`),i!==void 0&&s.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,c=await this.transport(new URL(d,o),{method:n,headers:s,body:i===void 0?void 0:JSON.stringify(i)}),l={};try{l=await c.json()}catch{}if(!c.ok||l.ok!==!0)throw new ie(c.status,l.error);return l.result}};function fn(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var _e=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),Dr(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 N("custodian_share_required");let s=_t(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(_t(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(_t(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return xe(e.signal),{protectionProtocol:i.protocol,validatorShares:Ct(a.encryptedShares),dataShards:Ct(o.encryptedShares),backupShards:Ct(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:kr(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:Tt(n.encryptedShares[0]),dataShard:Tt(n.encryptedShares[1])}}};function _t(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Ct(r){return r.map(Tt)}function Tt(r){return{id:r.id,data:r.encryptedData}}function kr(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new N("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function Dr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new N("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new N("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new N("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new N("plan_secrets_declaration_mismatch")}}function xe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function vn(r,e,t,n,i,s,a){let o=n.mergeThreshold-(n.withCustodian?1:0);if(typeof n.withCustodian!="boolean"||!Number.isInteger(n.mergeThreshold)||o<1||o>r.totalShares)throw new Error(_.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new H({api:{startRelaySession:y=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,y),readRelaySession:y=>i.readRelaySession(r.organizationId,y)}}),p=new _e(s,l);a?.("encrypting");let m=await p.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return a?.("generating_shares"),p.generateShares({planId:r.planId,declaration:c,encrypted:m})}import{PlanAssetDeclaration as Mr}from"@safetech/inheriti-core-sdk/node";function bn(r){let e=kt({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function kt(r){if(!r.assets.length)throw new S("assets_required");let e=r.assets.map(s=>{if(s.meta.isMedia!==!0)return;let a="data"in s.secret?s.secret.data:void 0,o;if(a instanceof Blob&&(o=a.size),typeof a=="string")try{o=atob(a).length}catch{throw new S("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new S("binary_asset_metadata_invalid");return o}),t=Mr.create(r.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),n=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,r.assets[a].secret]))),i={idempotencyKey:r.planId,name:r.title,assets:n.map((s,a)=>{let o=s.meta.isMedia===!0;return{clientAssetRef:s.id,type:s.type,name:s.meta.name,fieldNames:o?[]:Object.keys(s.secret),isBinary:o,fileName:s.meta.fileName,mimeType:s.meta.mimeType,size:e[a]}}),participants:[]};return{assets:n,plan:i}}async function wn(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 Ce=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){return this.createPlan({...e,assets:[e.asset]},t)}async createPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!Array.isArray(e.assets)||!e.assets.length||e.assets.some(a=>!a?.meta?.name?.trim()))throw new Error(_.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(_.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(_.invalidShares);let n=await wn(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(_.reconciliationRequired);return i.promise}let s=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let i=kt({planId:e.planId,title:e.title,assets:e.assets}),s=this.material.get(e.planId);if(s&&(s.fingerprint!==t||s.masterKeySource!==e.masterKeySource))throw new Error(_.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(Ye(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(_.reconciliationRequired);if(!a&&s)throw new Error(_.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(_.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(_.invalidMasterKeyContext);if(!a){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(a=await this.statusOrMissing(e.organizationId,e.planId),!a)throw l}}a??=await this.port.status(e.organizationId,e.planId);let d=s?.encrypted??await vn(e,i,o,a,this.port,this.coreSdk,n);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),n?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),n?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),n?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!Ye(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return Ye(c)&&this.material.delete(e.planId),{planId:e.planId,status:Ye(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(_.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof ie&&n.status===404)return;throw n}}};function Ye(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var Xe=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}start(e,t,n,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:n},i)}async listEligibleCandidates(e,t,n){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),n&&i.set("namePrefix",n);let s=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(s))throw new Error("invalid_plan_edit_candidates");return s}async context(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(n))throw new Error("invalid_plan_edit_context");return n}async moderatorNames(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!n||typeof n!="object")throw new Error("invalid_plan_edit_participants");let i=n;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let s=new Map;for(let a of i.participants){if(!a||typeof a.id!="string"||!a.id||typeof a.displayName!="string"||!Array.isArray(a.relationships)||!a.relationships.every(o=>typeof o=="string")||typeof a.lifecycle!="string")throw new Error("invalid_plan_edit_participants");a.lifecycle==="ACTIVE"&&a.relationships.includes("MODERATOR")&&s.set(a.id,a.displayName)}return s}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(_.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(_.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(_.relayFailed);return n}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(n))}commit(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(n))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,n,i,s){let a=await this.getBearerToken();if(!a)throw new Error(_.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${a}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),s&&o.set("idempotency-key",s);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),c=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,l=await this.transport(new URL(c,d),{method:n,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),p={};try{p=await l.json()}catch{}if(!l.ok||p.ok!==!0){let m=Array.isArray(p.validationErrors)?p.validationErrors.join("; "):void 0;throw new ie(l.status,m||p.error)}return p.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(n=>!!n&&typeof n.id=="string"&&!!n.id&&typeof n.name=="string"&&n.status==="PROTECTED"&&typeof n.createdAt=="string"&&!!n.assetSummary&&Number.isSafeInteger(n.assetSummary.count)&&n.assetSummary.count>=0&&Array.isArray(n.assetSummary.types)&&n.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(n.assetSummary.names)&&n.assetSummary.names.every(i=>typeof i=="string")&&!!n.governance&&["DIRECT","GOVERNED"].includes(n.governance.mode)&&Number.isSafeInteger(n.governance.minimumApprovals)&&n.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var 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),s=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!s)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let a=this.revealedAssets,o=a?.organizationId===e.organizationId&&a.planId===e.planId&&a.editId===e.editId&&a.expiresAt>Date.now();a&&!o&&(this.revealedAssets=void 0);let d=s.masterKeyEncrypted?e.masterKey??(o?a.masterKey:void 0):void 0;s.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?a.assets:await this.revealAssets(e,d,s.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(l.map(p=>p.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&n===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:s,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),n=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(n>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return n}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new H({api:{startRelaySession:n=>this.port.startRelaySession(e.organizationId,t,n),readRelaySession:n=>this.port.readRelaySession(e.organizationId,n)}}).resolve()}async revealAssets(e,t,n,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=g=>{g!==o&&(o=g,i?.(g))},c=g=>{if(g.processId!==e.editId||g.planId&&g.planId!==e.planId)return;switch(g.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let f=this.approvalError(g);if(f?.startsWith("edit_authentication_")&&d("pending_auth"),f?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!g.moderatorParticipants||g.requiredModeratorApprovals===void 0||!g.approvalProcess)return;let T=g.moderatorParticipants.map(R=>R.memberId??R.userId);T.some(R=>typeof R!="string"||!R)||new Set(T).size!==T.length||i?.(o,{requiredApprovals:g.requiredModeratorApprovals,approvedModerators:g.approvalProcess.approvedModerators,moderators:g.moderatorParticipants.map((R,O)=>{let x=T[O],Q=R.flows.filter(Ie=>Ie.status==="PENDING"&&Ie.expiresAt&&Number.isFinite(Ie.expiresAt.getTime())).map(Ie=>Ie.expiresAt.getTime());return{id:x,displayName:a.get(x)||"Moderator",status:R.status,expiresAt:Q.length?new Date(Math.min(...Q)).toISOString():void 0}})})},l=await s.resume(e.planId,{onViewUpdate:c});if(l?.processId!==e.editId||l.planId&&l.planId!==e.planId)throw new Error("edit_merge_not_ready");c(l),this.assertApprovalOutcome(e.planId,l),l.status!=="READY_TO_REVEAL"&&l.status!=="REVEALED"&&await s.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let p=await s.getView(e.editId);if(p?.processId!==e.editId||p.planId&&p.planId!==e.planId)throw new Error("edit_merge_not_ready");c(p),this.assertApprovalOutcome(e.planId,p);let m=p?.status;if(m!=="READY_TO_REVEAL"&&m!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let y=null,w={onRevealed:g=>{y=g},onViewUpdate:c,onRevealStepUpdate:(g,f)=>{if(f==="IN_PROCESS")switch(g){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(n&&(w.onCustodianShareRequired=async(g,f)=>{switch(f.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let T=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),T==="SK_MOBILE")return s.distributeCustodianShareViaMobile(f.planId);if(T!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let R=e.proDevice;try{this.assertNotAborted(e.signal);let O=await s.getCustodianShareData(g);this.assertShare(O,f.planId),d("connecting_safekey_pro");let{deviceId:x}=await R.write(O,e.signal);if(this.assertNotAborted(e.signal),!x?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(f.planId,O.id,x,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(g,O.id);return}finally{R.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let T=e.proDevice;try{if(this.assertNotAborted(e.signal),!f.shareId||!f.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let R=await T.read({shareId:f.shareId,planId:f.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(R,f.planId,f.shareId),R.deviceId!==f.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:R.shares}}finally{T.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),m==="REVEALED"?await s.resumeReveal(e.editId,w,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},w,t),this.assertNotAborted(e.signal),!y)throw new Error("edit_assets_unavailable");return y}assertApprovalOutcome(e,t){let n=this.approvalError(t);if(n)throw this.clearRevealedAssets(e),new Error(n)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,n){if(!e||!e.id||e.id!==(n??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var Or=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))),Ze=class{constructor(e,t,n,i){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=i}async saveAssets(e,t,n,i,s,a){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,i);a?.("preparing");let c=await o.prepare(d);this.assertNotAborted(e.signal);let l={mergeProcessId:e.editId,protectionProtocol:c.protectionProtocol,validatorShares:this.transportShares(c.validatorShares),dataShards:this.transportShares(c.dataShards),backupShards:this.transportShares(c.backupShards),encryptedKey:c.encryptedKey,assetsMetadata:c.assetsMetadata,custodianPair:c.custodianPair};if(a?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,l),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:s,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,s,l,o,d,a)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let n=await this.configurationRepository().findByPlanId(e.planId),i=n?.editDistribution??n?.preparedDistribution;if(!t&&(!i||n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let s=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),dataShards:i.dataShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),backupShards:i.backupShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,s))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let a=await this.port.status(e.organizationId,e.editId);return a.id!==e.editId||a.planId!==e.planId||a.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,s),await this.port.commit(e.organizationId,e.planId,s),await this.isCommitted(e,s)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let n=await this.configurationRepository().findByPlanId(e.planId);if(n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let n=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await n.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await n.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,n,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:s,configuration:a}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,n,i,s,a){let o,d=c=>{let l;switch(c.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":l="distributing_validators";break;case"SHARES_DISTRIBUTION":l="distributing_data";break;case"FINALIZE":l="finalizing";break;default:return}l!==o&&(o=l,a?.(l))};try{await i.execute(s,{onLocalProcessUpdated:d})}catch(c){try{if(a?.("verifying"),await this.isCommitted(e,n))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&a?.(o),c}try{if(a?.("verifying"),!await this.isCommitted(e,n))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let n=await this.port.commitStatus(e.organizationId,e.editId);if(n.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(n.status)||n.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(Or(t.assetsMetadata)),s=await globalThis.crypto.subtle.digest("SHA-256",i),a=Array.from(new Uint8Array(s),c=>c.toString(16).padStart(2,"0")).join("");if(n.assetsMetadataHash!==a)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(c=>c.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(n.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var et=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new Je(e,t,n),this.reconfiguration=new Ze(e,t,n,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,n,i){return this.port.start(e,t,n,i)}async listAssets(e,t){let{assets:n}=await this.assetAccess.loadAssets(e,t);return n.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,n){let{assets:i}=await this.assetAccess.loadAssets(e,n),s=i.find(a=>a.id===t);if(!s)throw new Error("edit_asset_not_found");return structuredClone(s)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=s.findIndex(l=>l.id===e.assetId);if(a<0)throw new Error("edit_asset_not_found");let o=s[a];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},c=s.map((l,p)=>p===a?d:l);return this.reconfiguration.saveAssets(e,c,n.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=bn({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(s.map(d=>d.id)).has(a.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,s.concat(a),n.withCustodian,i,a.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function Sn({apiUrl:r,organizationId:e,planId:t,editId:n,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),c=new URL(r.endsWith("/")?r:`${r}/`);if(d.origin!==c.origin||!d.pathname.startsWith(c.pathname))throw new Error("unsupported_core_edit_route");let l=d.pathname.slice(c.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(l===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return s(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let p=Nr(l,d.searchParams,t,n),m=new Headers(o?.headers);m.set("x-organization-id",e),m.set("x-elements-environment",i);let y=c.pathname.endsWith("/integrations/")?`v1/${p}`:`integrations/v1/${p}`;return s(new URL(y,c),Object.assign({},o,{headers:m}))}}function Nr(r,e,t,n){if(r==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){let o=s[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(s[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(n)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as Kr}from"@safetech/inheriti-core-sdk/node";function En(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=ye(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new H({api:{startRelaySession:o=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>r.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>r.api.cancelMasterKeyRelaySession(o,d)}}),a=new ce(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(o,d,c)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,c)}}});return ze(a,e,t,!0)}}}function Ur(r){let e=new Ae(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{...En({api:e,reconstructor:new me(r.workerUrl),assetDecoder:Kr}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as tt,sealInheritiFile as nt,readInheritiFileHeader as Dt,openInheritiFile as Mt,InheritiFileInvalid as Lr,MAX_INHERITI_FILE_BYTES as Ot}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as rt,openInheritiFileKey as Nt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Fr(r){let{reveal:e,api:t,signal:n}=r;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(n);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let a=r.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(r.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>Ot-1024*1024)throw new Error("unsupported_protected_asset");let d=tt(),c,l=!1,p=!1;try{n?.throwIfAborted();let m=await rt(d,i.publicKey);l=!0;let y=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:m,openLimit:a},n);if(y.copyId!==r.copyId||y.status!=="PENDING")throw new Error("file_access_create_invalid");let w=await t.getFileAccess(r.copyId,n);for(;w.status==="PENDING";){if(n?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((f,T)=>{let R=()=>{clearTimeout(O),T(n?.reason)},O=setTimeout(()=>{n?.removeEventListener("abort",R),f()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",R,{once:!0})}),w=await t.getFileAccess(r.copyId,n)}if(w.status!=="READY"||w.origin!=="REVEAL"||w.copyId!==r.copyId||w.allowedUses!==a||!w.recipient||!w.deployment||w.expiresAt!==null&&(!Number.isFinite(Date.parse(w.expiresAt))||Date.parse(w.expiresAt)>s||Date.parse(w.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let g=await nt({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:w});g.fileKey.fill(0),c=g.fileBytes,n?.throwIfAborted(),await r.save({fileName:o.fileName,fileBytes:c}),p=!0}catch(m){if(l&&!p)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(y){throw new AggregateError([m,y],"protected_asset_export_and_cleanup_failed",{cause:m})}throw m}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as wo}from"@safetech/inheriti-core-sdk/node";function An(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var it=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),An(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return An(new Uint8Array(t))}},st=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var Te=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},q=class extends Te{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},b=class extends Te{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function at(r){if(r instanceof Te)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Rn=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:K(n,"issuer"),authorizationEndpoint:K(n,"authorization_endpoint"),tokenEndpoint:K(n,"token_endpoint"),deviceAuthorizationEndpoint:X(n,"device_authorization_endpoint"),endSessionEndpoint:X(n,"end_session_endpoint"),revocationEndpoint:X(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:K(t,"device_code"),userCode:K(t,"user_code"),verificationUri:K(t,"verification_uri"),verificationUriComplete:X(t,"verification_uri_complete"),expiresInSeconds:xn(t,"expires_in"),intervalSeconds:Kt(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async revoke(e){let t=await this.http(new URL(e.endpoint),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,token:e.refreshToken,token_type_hint:"refresh_token"}),signal:e.signal});if(!t.ok)throw new b(`oauth_http_${t.status}`)}async exchangeBusinessSession(e){return this.businessSession(e.apiUrl,"exchange",{providerAccessToken:e.providerAccessToken})}async refreshBusinessSession(e){return this.businessSession(e.apiUrl,"refresh",{refreshToken:e.refreshToken})}async revokeBusinessSession(e){await this.businessRequest(e.apiUrl,"revoke",{refreshToken:e.refreshToken},e.signal)}async businessSession(e,t,n){let i=await this.businessRequest(e,t,n);return{accessToken:K(i,"accessToken"),refreshToken:K(i,"refreshToken"),accessExpiresAt:K(i,"accessExpiresAt"),sessionExpiresAt:K(i,"sessionExpiresAt"),familyId:K(i,"familyId"),environment:Gr(i,"environment"),clientId:K(i,"clientId"),providerIssuer:K(i,"providerIssuer"),providerSubject:K(i,"providerSubject")}}async businessRequest(e,t,n,i){let s=e.endsWith("/")?e:`${e}/`,a=new URL(`operator-sessions/${t}`,s),o=await this.http(a,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"omit",signal:i,body:JSON.stringify(n)}),d={};try{d=await o.json()}catch{}if(!o.ok)throw new b(`business_http_${o.status}`);if(d.ok!==!0||!qr(d.result))throw new b("invalid_business_response");return d.result}async token(e,t){let n=await this.form(e,t);return{accessToken:K(n,"access_token"),refreshToken:X(n,"refresh_token"),idToken:X(n,"id_token"),tokenType:K(n,"token_type"),expiresInSeconds:xn(n,"expires_in"),refreshExpiresInSeconds:Kt(n,"refresh_expires_in"),scope:X(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let s=X(i,"error")??`oauth_http_${n.status}`;throw new b(s,X(i,"error_description")??s)}return i}};function qr(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Gr(r,e){let t=K(r,e);if(t!=="TEST"&&t!=="LIVE")throw new b("invalid_business_response");return t}function K(r,e){let t=X(r,e);if(!t)throw new b("invalid_oauth_response",`Missing ${e}`);return t}function X(r,e){return typeof r[e]=="string"?r[e]:void 0}function xn(r,e){let t=Kt(r,e);if(t===void 0)throw new b("invalid_oauth_response",`Missing ${e}`);return t}function Kt(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Br=600*1e3,ot=5,Vr=5,_n=5e3,zr=new WeakMap,$r=new WeakMap;async function Tn(r,e,t){let n=r.get(e),i,s=new Promise(a=>{i=a});r.set(e,s),n&&await n;try{return await t()}finally{r.get(e)===s&&r.delete(e),i()}}function se(r,e){return Tn(zr,r,e)}var Cn=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new b("business_api_url_required");this.crypto=e.crypto??new it,this.clock=e.clock??new st}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+Br;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",a),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:o}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new b("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new b("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new b("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new b("state_mismatch");let a=i.searchParams.get("error");if(a)throw new b(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new b("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 se(this.options.sessions,()=>this.options.sessions.save(l)),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new b("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(ot,t.intervalSeconds??ot),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new b("device_transaction_missing");let i=n,s=await this.getDiscovery(),a=Math.max(ot,i.intervalSeconds??ot),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await se(this.options.sessions,()=>this.options.sessions.save(c)),await this.options.transactions.remove(t),c}catch(d){let c=at(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=Vr,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new b("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e){if(this.isSafeIdBusinessMode()&&!this.isValidSafeIdBusinessSession(e))throw await this.clearIfUnchanged(e),new q;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new q;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new q;return e.expiresAt>this.clock.now()?e.accessToken:(await this.refreshExpired(e)).accessToken}}refresh(){return this.refreshExpired()}refreshExpired(e){if(this.refreshFlight)return this.refreshFlight;let t=this.performRefresh(e).finally(()=>{this.refreshFlight===t&&(this.refreshFlight=void 0)});return this.refreshFlight=t,t}async clear(){let e;if(await se(this.options.sessions,async()=>{try{e=await this.options.sessions.load()}finally{await this.options.sessions.clear()}}),this.isSafeIdBusinessMode()&&e&&this.isValidSafeIdBusinessSession(e)&&e.refreshToken){let i=new AbortController,s;try{await Promise.race([(async()=>{let a=await this.getDiscovery();a.revocationEndpoint&&this.options.transport.revoke&&await this.options.transport.revoke({endpoint:a.revocationEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken,signal:i.signal})})(),new Promise((a,o)=>{s=setTimeout(()=>{i.abort(),this.discovery=void 0,o(new b("provider_revoke_timeout"))},_n)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,n;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{n=setTimeout(()=>{t.abort(),s(new b("business_revoke_timeout"))},_n)})])}finally{n&&clearTimeout(n)}}async performRefresh(e){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.performProviderRefresh(e);let t=await this.options.sessions.load();if(!t||!this.isValidBusinessSession(t))throw t&&await this.clearIfUnchanged(t),new q;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new q;let n;try{n=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=at(i);if(s==="business_http_409"){let a=await se(this.options.sessions,async()=>{let o=await this.options.sessions.load();if(o&&this.isValidBusinessSession(o)&&o.refreshToken!==t.refreshToken&&o.familyId===t.familyId&&o.principal.subject===t.principal.subject)return o;o&&this.sameCredential(o,t)&&await this.options.sessions.clear()});if(a)return a;throw new q}throw s==="business_http_401"?(await this.clearIfCurrent(t),new q):i}try{let i=this.businessSession(n,t.principal,t);if(i.refreshToken===t.refreshToken)throw new b("refresh_token_rotation_missing");return await se(this.options.sessions,async()=>{let s=await this.options.sessions.load();if(s&&this.isValidBusinessSession(s)&&s.familyId===t.familyId&&s.principal.subject===t.principal.subject&&s.refreshToken!==t.refreshToken)return s;if(!s||!this.sameCredential(s,t))throw new q;return await this.options.sessions.save(i),i})}catch(i){throw await this.clearIfCurrent(t),i}}sameCredential(e,t){return this.isValidBusinessSession(e)&&e.familyId===t.familyId&&e.refreshToken===t.refreshToken&&e.principal.subject===t.principal.subject}async clearIfUnchanged(e){await se(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&t.kind===e.kind&&t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.principal?.subject===e.principal?.subject&&await this.options.sessions.clear()})}async clearIfCurrent(e){await se(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&this.sameCredential(t,e)&&await this.options.sessions.clear()})}async performProviderRefresh(e){return e??=await this.options.sessions.load(),Tn($r,this.options.sessions,async()=>{let t=await this.options.sessions.load();if(e&&t&&t.kind===e.kind&&t.refreshToken!==e.refreshToken&&t.expiresAt>this.clock.now()&&t.principal?.subject===e.principal?.subject&&t.principal?.sessionId===e.principal?.sessionId){if(this.isSafeIdBusinessMode()){if(this.isValidSafeIdBusinessSession(t))return t}else if(t.kind!=="business"&&t.kind!=="safeid-oidc-business")return t}return this.refreshProviderUnderLock()})}async refreshProviderUnderLock(){let e=await this.options.sessions.load();if(!e||(this.isSafeIdBusinessMode()?!this.isValidSafeIdBusinessSession(e):e.kind==="business"||e.kind==="safeid-oidc-business")||!e.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw e&&await this.clearIfUnchanged(e),new q;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=at(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new q):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),n)}try{if(!t.refreshToken)throw new b("refresh_token_rotation_missing");let n=await this.acceptProviderTokens(t,void 0,e);return await se(this.options.sessions,async()=>{let i=await this.options.sessions.load();if(!i||i.kind!==e.kind||i.refreshToken!==e.refreshToken||i.accessToken!==e.accessToken)throw new q;return await this.options.sessions.save(n),n})}catch(n){throw await this.clearIfUnchanged(e),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(U(e.issuer)!==U(this.options.configuration.issuer))throw new b("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}|${U(t)}|${n}|${i}|${this.options.businessApiUrl?this.isSafeIdBusinessMode()?"safeid-oidc":"business":"provider"}|${this.options.configuration.audience}`}async acceptTokens(e,t){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.acceptProviderTokens(e,t);let n=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,n)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new b("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 b("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new b("token_subject_mismatch")}return n}async acceptProviderTokens(e,t,n){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new q;let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access")),o={accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&a?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:a,principal:i};return this.isSafeIdBusinessMode()?{kind:"safeid-oidc-business",accessToken:o.accessToken,refreshToken:o.refreshToken,idToken:o.idToken,tokenType:o.tokenType,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,offlineAccessGranted:o.offlineAccessGranted,principal:o.principal,businessApiUrl:this.options.businessApiUrl,audience:this.options.configuration.audience,clientId:this.options.configuration.clientId,issuer:U(this.options.configuration.issuer),environment:this.options.configuration.environment}:o}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}isSafeIdBusinessMode(){return this.options.businessAuthority==="safeid-oidc"}isValidSafeIdBusinessSession(e){let t=e,n=t.principal;return t.kind==="safeid-oidc-business"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&(t.refreshExpiresAt===void 0||Number.isFinite(t.refreshExpiresAt))&&typeof t.issuer=="string"&&typeof t.businessApiUrl=="string"&&typeof t.audience=="string"&&typeof t.clientId=="string"&&(t.environment==="TEST"||t.environment==="LIVE")&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&typeof n.authorizedParty=="string"&&(n.environment==="TEST"||n.environment==="LIVE")&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&U(t.issuer)===U(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment&&U(n.issuer)===U(this.options.configuration.issuer)&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)}businessSession(e,t,n){if(U(e.providerIssuer)!==U(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||n&&e.familyId!==n.familyId)throw new b("business_identity_mismatch");let i=Date.parse(e.accessExpiresAt),s=Date.parse(e.sessionExpiresAt);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=this.clock.now()||s<=this.clock.now()||i>s)throw new b("invalid_business_expiry");return{kind:"business",familyId:e.familyId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenType:"Bearer",expiresAt:i,sessionExpiresAt:s,principal:{issuer:t.issuer,audience:t.audience,authorizedParty:t.authorizedParty,environment:t.environment,subject:t.subject,sessionId:t.sessionId,tokenId:t.tokenId,scopes:t.scopes,nonce:t.nonce}}}isValidBusinessSession(e){let t=e,n=t.principal;return t.kind==="business"&&typeof t.familyId=="string"&&t.familyId.length>0&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&Number.isFinite(t.sessionExpiresAt)&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&U(n.issuer)===U(this.options.configuration.issuer)&&typeof n.subject=="string"&&n.subject.length>0&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(U(e.issuer)!==U(i.issuer))throw new b("issuer_mismatch");if(!s.includes(i.audience))throw new b("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new b("client_mismatch");if(e.environment!==i.environment)throw new b("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new b("required_claim_missing");if(n&&e.nonce!==t)throw new b("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(U(e.issuer)!==U(n.issuer))throw new b("issuer_mismatch");if(!i.includes(n.clientId))throw new b("client_mismatch");if(e.authorizedParty!==n.clientId)throw new b("client_mismatch");if(!e.subject||!e.sessionId)throw new b("required_claim_missing");if(e.nonce!==t)throw new b("nonce_mismatch")}};function U(r){return r.replace(/\/+$/u,"")}var kn=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 _o,RawMasterKeySource as Co,deriveMasterKey as To,generateHexSeed as ko,computePassphraseVerifier as Do}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as Oo}from"@safetech/inheriti-core-sdk/node";function io(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",r.environment),e(s,Object.assign({},a,{headers:o}))},n=r.business?void 0:Ut({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),i=new ue(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new ce(n,{keyVault:r.keyVault,state:r.state,api:i,reconstructor:new me(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:Hr})}function so(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=Ut({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ce(new Re(r.apiUrl,r.environment,r.getBearerToken,e),t)}function ao(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=Ut({apiUrl:t,getBearerToken:r.getBearerToken,transport:Sn({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 et(new Xe(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as Wr}from"node:crypto";import{generateRSAOAEPKeyPair as jr}from"@safetech/inheriti-core-sdk/crypto";async function Dn(r){let e=Dt(r.fileBytes);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.copyId))throw new Error("invalid_startup_file");if(r.signal?.aborted)throw new Error("opening_cancelled");let t=await r.api.getFileAccess(e.copyId,r.signal);if(e.deployment!==t.deployment||e.origin!==t.origin||e.copyId!==t.copyId||e.recipient!==t.recipient||e.expiresAt!==t.expiresAt||e.allowedUses!==t.allowedUses)throw new Error("file_binding_mismatch");return{header:e,access:t}}async function Qr(r){let{api:e,sessionId:t,signal:n}=r;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t))throw new Error("invalid_opening_session");let i=Uint8Array.from(r.fileBytes),s,a,o=()=>{if(n?.aborted)throw new Error("opening_cancelled")};try{let{access:d}=await Dn({fileBytes:i,api:e,signal:n});if(d.status!=="READY"||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())throw new Error("file_access_unavailable");if(r.delivery==="REVEAL"&&d.origin!=="REVEAL")throw new Error("file_access_unavailable");o();let{publicKeyBase64:c,privateKey:l}=await jr(),p=Wr("sha256").update(c).digest("hex");o();let m=await e.requestFileAccessOpening(d.copyId,{sessionId:t,clientPublicKey:c,...r.delivery==="REVEAL"?{delivery:"REVEAL"}:{}});r.delivery==="REVEAL"&&r.onPairingCode?.(p.slice(0,12));let y=Math.min(Date.parse(m.expiresAt),Date.now()+3e5);if(!Number.isFinite(y))throw new Error("file_opening_expired");let w;for(;!n?.aborted&&Date.now()<y;){let T=await e.readFileAccessOpening(d.copyId,t,p,n);if(T.status==="READY"&&T.encryptedFileKey){w=T.encryptedFileKey;break}if(T.status==="EXPIRED"||T.status==="DELIVERY_CONFIRMED")throw new Error("file_opening_expired");o(),await new Promise(R=>{let O=()=>{clearTimeout(x),n?.removeEventListener("abort",O),R()},x=setTimeout(O,1e3);n?.addEventListener("abort",O,{once:!0})})}if(o(),!w)throw new Error("file_opening_expired");s=await Nt(w,l),o(),await e.confirmFileAccessDelivery(d.copyId,t,p);let g=await Mt(i,s,d);a=g.plaintext,o();let f={plaintext:a,header:g.header};return a=void 0,f}finally{i.fill(0),s?.fill(0),a?.fill(0)}}import{createHash as Yr,webcrypto as Xr}from"node:crypto";import{canonicalInboxManifest as Jr,decodeInboxManifest as Zr,decodeInboxContentFrame as ei,decodeInboxText as ti,decryptInboxShare as ni,encodeInboxContentFrame as Lt,encodeInboxText as ri,encryptInboxShare as Mn,inboxProtectedUnitCommitment as ii,inboxTextMetadataDigest as On,openInboxContent as si,sealInboxContent as ai,signInboxFrame as oi,unwrapInboxContentKey as di,unwrapInboxShareKey as ci,verifyInboxFrame as Nn,wrapInboxContentKey as li,wrapInboxShareKey as pi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as ui}from"@safetech/inheriti-core-sdk/workers/inbox.node";var j=Xr,k=j,C=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)},z=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),dt=async r=>new Uint8Array(await k.subtle.digest("SHA-256",Uint8Array.from(r))),ke=r=>Yr("sha256").update(r).digest("hex"),ae=class{constructor(e,t=new ui){this.api=e;this.worker=t}async send(e){let t=await this.prepare(e);return this.api.publishInboxMessage(e.conversationId,t.submission)}async prepare(e){let{preparation:t,sender:n}=await this.prepareSender(e),i=await this.textManifest(e,t,n),s=Jr(i),a=await dt(s),{contentKey:o,frame:d}=await ai(ri(e.text),a,k),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:p}=await this.protectShares(t,d,a),m=await this.wrapRecipientKeys(t,o,a),y=await pi(l,C(e.tenantKeyHex),a,i.tenantId,i.messageId,k);return{frame:Buffer.from(Lt(d)).toString("base64"),submission:{messageId:t.messageId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,expiresAt:e.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(c).toString("base64"),tenantWrappedShareKey:Buffer.from(y).toString("base64"),recipients:m,shares:p}}}async open(e){return this.openWithCommitment(e)}openCommitted(e,t){return this.openWithCommitment(e,t)}async openWithCommitment(e,t){let n=await this.api.openInboxMessage(e.conversationId,e.messageId,e.identity.deviceId),i;try{e.signal?.throwIfAborted();let{manifest:a,manifestDigest:o,senderPublicDer:d}=await this.verifyOpening(e,n),c=await this.recoverFrame(n,a,o,e.tenantKeyHex);if(t&&!z(t,await ii(a,Lt(c),h(n.signature),k)))throw new Error("inbox_parent_unit_mismatch");i=await this.decryptText(n,c,a,o,d,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(a){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId)}catch{}throw a}let s=await this.ack(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId,e.signal);return e.signal?.throwIfAborted(),{text:i,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:s}}async ack(e,t,n,i,s){for(let a=0;a<2;a++){s?.throwIfAborted();try{return await this.api.ackInboxMessage(e,t,n,i,s),s?.throwIfAborted(),"ACKNOWLEDGED"}catch(o){if(s?.throwIfAborted(),o instanceof V&&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||ke(h(n.signingPublicKey))!==n.signingKeyFingerprint||ke(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:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:C(s.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await On(k)}}async signFrame(e,t,n,i){let s=await k.subtle.importKey("pkcs8",h(n),"Ed25519",!1,["sign"]),a=await oi(e,t,s,k),o=await k.subtle.importKey("spki",h(i),"Ed25519",!1,["verify"]);if(!await Nn(e,t,a,o,k))throw new Error("inbox_identity_mismatch");return a}async protectShares(e,t,n){let i=await this.worker.split(Lt(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),s=k.getRandomValues(new Uint8Array(32)),a=[];for(let o=0;o<e.total;o++){let d=e.shareLayers[o];a.push({kind:"DATA",index:o,shareId:d.dataShareId,layerId:d.id,ciphertext:Buffer.from(await Mn(i.dataShares[o],s,n,e.messageId,k)).toString("base64")}),a.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await Mn(i.keyShares[o],s,n,e.messageId,k)).toString("base64")})}return{shareKey:s,shares:a}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=h(i.encryptionPublicKey);if(ke(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await k.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:Buffer.from(await li(t,a,n,k)).toString("base64")}}))}async verifyOpening(e,t,n){let i=h(t.canonicalManifest),s=Zr(i);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!z(s.metadataDigest,n??await On(k)))throw new Error("inbox_manifest_mismatch");let a=s.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!a||!z(a.encryptionKeyFingerprint,C(ke(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=h(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==ke(o)||!z(s.senderSigningKeyFingerprint,C(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await dt(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let s=await ci(h(e.tenantWrappedShareKey),C(i),n,t.tenantId,t.messageId,k),a=[],o=[],d=new Set;for(let l of e.shares){let p=`${l.kind}:${l.index}`;if(d.has(p))throw new Error("duplicate_inbox_share");d.add(p);let m=await ni(h(l.ciphertext),s,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,k);(l.kind==="DATA"?a:o).push(m)}if(a.length!==o.length||a.length<2)throw new Error("incomplete_inbox_shares");let c=await this.worker.reconstruct(a,o,{threshold:a.length,total:a.length,messageId:t.messageId,manifestDigest:n});return ei(c)}async decryptText(e,t,n,i,s,a){return ti(await this.decryptContent(e,t,n,i,s,a))}async decryptContent(e,t,n,i,s,a){let o=await k.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Nn(n,t,h(e.signature),o,k))throw new Error("inbox_signature_invalid");let d=await k.subtle.importKey("pkcs8",h(a),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await di(h(e.wrappedContentKey),d,i,k);return si(t,c,i,k)}};import{canonicalInboxManifest as mi,decodeInboxContentFrame as gi,decodeInboxFile as hi,decryptInboxShare as Ii,encodeInboxContentFrame as yi,encodeInboxFile as fi,encryptInboxShare as Kn,inboxFileMetadataDigest as Un,sealInboxContent as vi,unwrapInboxShareKey as bi,wrapInboxShareKey as Pi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var ct=class extends ae{constructor(t){super(t);this.fileApi=t}async sendFile(t){t.signal?.throwIfAborted();let{preparation:n,sender:i}=await this.prepareSender(t),s=await this.fileManifest(t,n,i),a=mi(s),o=await dt(a),d=fi(t.file),c;try{c=await vi(d,o,j)}finally{d.fill(0)}let{contentKey:l,frame:p}=c,m=await this.signFrame(s,p,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let y=await this.worker.split(yi(p),{threshold:n.threshold,total:n.total,messageId:n.messageId,manifestDigest:o},t.signal,x=>t.onProgress?.(0,n.total*2,x.stage));t.signal?.throwIfAborted();let w=j.getRandomValues(new Uint8Array(32)),g=[];for(let x=0;x<n.total;x++){let Q=n.shareLayers[x];g.push({reference:{kind:"DATA",index:x,shareId:Q.dataShareId,layerId:Q.id},bytes:await Kn(y.dataShares[x],w,o,n.messageId,j)}),g.push({reference:{kind:"KEY",index:x,shareId:Q.keyShareId,layerId:Q.id},bytes:await Kn(y.keyShares[x],w,o,n.messageId,j)})}let f=await this.wrapRecipientKeys(n,l,o),T=await Pi(w,C(t.tenantKeyHex),o,s.tenantId,s.messageId,j);t.signal?.throwIfAborted();let R=await this.fileApi.stageInboxFile(t.conversationId,{messageId:n.messageId,senderDeviceId:i.deviceId,participantRevision:n.participantRevision,expiresAt:t.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(a).toString("base64"),signature:Buffer.from(m).toString("base64"),tenantWrappedShareKey:Buffer.from(T).toString("base64"),recipients:f,shares:g.map(x=>x.reference)},t.signal);if(R.messageId!==n.messageId||R.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let x=0;x<g.length;x++){t.signal?.throwIfAborted();let Q=g[x];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,Q.reference.shareId,Q.bytes,t.signal),t.onProgress?.(x+1,g.length,"UPLOADING")}t.signal?.throwIfAborted();let O=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(O.messageId!==n.messageId||O.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return O}async openFile(t){t.signal?.throwIfAborted();let n=await this.fileApi.openInboxFile(t.conversationId,t.messageId,t.identity.deviceId,t.signal),i,s;try{let{manifest:o,manifestDigest:d,senderPublicDer:c}=await this.verifyOpening(t,n,await Un(j)),l=await this.recoverFileFrame(t,n,o,d);s=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=hi(s),t.signal?.throwIfAborted(),await t.save(i,{leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt}),t.signal?.throwIfAborted()}catch(o){try{await this.fileApi.releaseInboxMessage(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId)}catch{}throw o}finally{s?.fill(0)}let a=await this.ack(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId,t.signal);return t.signal?.throwIfAborted(),{name:i.name,mimeType:i.mimeType,size:i.bytes.length,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:a}}async fileManifest(t,n,i){let s=Date.parse(t.expiresAt);if(!Number.isSafeInteger(s)||s<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:t.identity.tenantId,conversationId:t.conversationId,messageId:n.messageId,senderId:t.identity.memberId,senderDeviceId:i.deviceId,senderSigningKeyFingerprint:C(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:C(a.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await Un(j)}}async recoverFileFrame(t,n,i,s){let a=await bi(h(n.tenantWrappedShareKey),C(t.tenantKeyHex),s,i.tenantId,i.messageId,j),o=[],d=[],c=new Set;for(let p=0;p<n.shares.length;p++){t.signal?.throwIfAborted();let m=n.shares[p],y=`${m.kind}:${m.index}`;if(c.has(y))throw new Error("duplicate_inbox_share");c.add(y);let w=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,m.shareId,t.identity.deviceId,n.leaseId,t.signal),g=await Ii(w,a,s,i.messageId,m.kind==="DATA"?"data":"key",m.index,j);(m.kind==="DATA"?o:d).push(g),t.onProgress?.(p+1,n.shares.length,"DOWNLOADING")}if(o.length!==d.length||o.length<2)throw new Error("incomplete_inbox_shares");t.signal?.throwIfAborted();let l=await this.worker.reconstruct(o,d,{threshold:o.length,total:o.length,messageId:i.messageId,manifestDigest:s},t.signal,p=>t.onProgress?.(n.shares.length,n.shares.length,p.stage));return t.signal?.throwIfAborted(),gi(l)}};import{createHash as Fn,webcrypto as wi}from"node:crypto";import{canonicalInboxParentManifest as Si,decodeInboxParentManifest as Ei,encodeInboxParentNormalFrame as Ai,decodeInboxParentNormalFrame as Ri,sealInboxParentNormalBody as xi,openInboxParentNormalBody as _i,wrapInboxParentNormalKey as Ci,unwrapInboxParentNormalKey as Ti,signInboxParentNormalFrame as ki,verifyInboxParentNormalFrame as Ln,encodeInboxText as Di,decodeInboxText as Mi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var $=wi,De=r=>Fn("sha256").update(r).digest("hex"),lt=r=>Buffer.from(r).toString("base64"),pt=class{constructor(e){this.api=e}pending=new Map;async send(e){let t=this.digestInput(e),n=e.parentId?this.pending.get(e.parentId):void 0;if(n){if(n.inputDigest!==t)throw new Error("inbox_idempotency_conflict");let c=await this.api.publishNormalInboxMessage(e.conversationId,n.submission);return this.pending.delete(e.parentId),c}let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validatePreparation(e,i),a=this.createManifest(e,i,s),o=await this.createSubmission(e,i,s,a);this.rememberSubmission(a.parentId,t,o);let d=await this.api.publishNormalInboxMessage(e.conversationId,o);return this.pending.delete(a.parentId),d}digestInput(e){return Fn("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:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:C(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let s=Si(i),{contentKey:a,frame:o}=await xi(Di(e.text),i,$),d=await $.subtle.importKey("pkcs8",h(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await ki(i,o,d,$),l=await $.subtle.importKey("spki",h(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Ln(i,o,c,l,$))throw new Error("inbox_identity_mismatch");let p=await Promise.all(t.recipients.map(m=>this.wrapRecipientKey(m,a,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:lt(s),frame:lt(Ai(o)),signature:lt(c),recipients:p}}async wrapRecipientKey(e,t,n){let i=h(e.encryptionPublicKey);if(De(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await $.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:lt(await Ci(t,s,n,$))}}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=Ei(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(p=>p.memberId===e.identity.memberId&&p.deviceId===e.identity.deviceId);if(!i||!z(i.encryptionKeyFingerprint,C(De(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=h(t.senderSigningPublicKey);if(!z(n.senderSigningKeyFingerprint,C(De(s))))throw new Error("inbox_sender_key_mismatch");let a=Ri(h(t.frame)),o=await $.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Ln(n,a,h(t.signature),o,$))throw new Error("inbox_signature_invalid");let d=await $.subtle.importKey("pkcs8",h(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Ti(h(t.wrappedContentKey),d,n,$),l=Mi(await _i(a,c,n,$));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 Bn,webcrypto as Oi}from"node:crypto";import{canonicalInboxParentManifest as Ni,decodeInboxParentManifest as Ki,decodeInboxManifest as Ui,encodeInboxParentNormalFrame as Li,decodeInboxParentNormalFrame as Fi,sealInboxParentNormalBody as qi,openInboxParentNormalBody as Gi,wrapInboxParentNormalKey as Bi,unwrapInboxParentNormalKey as Vi,signInboxParentNormalFrame as zi,verifyInboxParentNormalFrame as qn,signInboxProtectedParent as $i,verifyInboxProtectedParent as Gn,inboxProtectedUnitCommitment as Hi,encodeInboxText as Wi,decodeInboxText as ji}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var L=Oi,ut=r=>Buffer.from(r).toString("base64"),Me=r=>Bn("sha256").update(r).digest("hex"),mt=class{constructor(e,t){this.api=e;this.child=t??new ae(e)}pending=new Map;child;async send(e){let t=Bn("sha256").update(JSON.stringify([e.conversationId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.segments])).digest("hex"),n=e.parentId?[e.parentId,this.pending.get(e.parentId)]:[...this.pending.entries()].find(([,o])=>o.digest===t),i=n?.[1];if(i){if(i.digest!==t)throw new Error("inbox_idempotency_conflict");try{e.onProgress?.(i.submission.protectedUnits.length,i.submission.protectedUnits.length)}catch{}let o=await this.api.publishInboxParent(e.conversationId,i.submission);return this.pending.delete(n[0]),o}let s=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(s.parentId,{digest:t,submission:s});let a=await this.api.publishInboxParent(e.conversationId,s);return this.pending.delete(s.parentId),a}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let t=e.segments.filter(y=>"protectedText"in y).length;if(t<1||t>4)throw new Error("invalid_inbox_parent_segments");let n=e.segments.length===1&&t===1?"PROTECTED":"MIXED";if(n==="MIXED"&&!e.segments.some(y=>"text"in y))throw new Error("invalid_inbox_parent_segments");let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validateSender(e,i),a=e.parentId??i.parentId,{protectedUnits:o,manifestUnits:d}=await this.prepareChildren(e,i,s),c=this.parentManifest(e,i,s,a,n,d),{frame:l,signature:p,recipients:m}=await this.signAndWrap(e,i,s,c);return{parentId:a,idempotencyKey:a,senderDeviceId:s.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:ut(Ni(c)),signature:ut(p),frame:l,recipients:m,protectedUnits:o}}async prepareChildren(e,t,n){let i=[],s=[],a=e.segments.filter(o=>"protectedText"in o).length;for(let o=0;o<e.segments.length;o++){let d=e.segments[o];if(!("protectedText"in d))continue;let c=await this.child.prepare({conversationId:e.conversationId,text:d.protectedText,expiresAt:d.expiresAt,identity:e.identity,tenantKeyHex:e.tenantKeyHex}),l=Ui(h(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let p=await Hi(l,h(c.frame),h(c.submission.signature),L);i.push({position:o,frame:c.frame,child:c.submission}),s.push({unitId:c.submission.messageId,position:o,commitment:p});try{e.onProgress?.(i.length,a)}catch{}}return{protectedUnits:i,manifestUnits:s}}validateChildSnapshot(e,t,n,i){if(e.tenantId!==t.identity.tenantId||e.conversationId!==t.conversationId||e.senderId!==t.identity.memberId||e.senderDeviceId!==i.deviceId||e.participantRevision!==n.participantRevision||e.recipients.length!==n.recipients.length||e.recipients.some(s=>!n.recipients.some(a=>a.memberId===s.memberId&&a.deviceId===s.deviceId&&z(s.encryptionKeyFingerprint,C(a.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,t,n,i,s,a){return{mode:s,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:i,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:C(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:C(o.encryptionKeyFingerprint)})),protectedUnits:a}}async signAndWrap(e,t,n,i){let s=await L.subtle.importKey("pkcs8",h(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),a=await L.subtle.importKey("spki",h(n.signingPublicKey),"Ed25519",!1,["verify"]);if(i.mode==="PROTECTED")return{signature:await this.signProtectedParent(i,s,a),recipients:this.recipientReferences(t)};let{frame:o,signature:d,contentKey:c}=await this.sealMixedParent(e,i,s,a);return{frame:o,signature:d,recipients:await this.wrapRecipients(t,c,i)}}async signProtectedParent(e,t,n){let i=await $i(e,t,L);if(!await Gn(e,i,n,L))throw new Error("inbox_identity_mismatch");return i}async sealMixedParent(e,t,n,i){let s=e.segments.map((d,c)=>"text"in d?{text:d.text}:{unitId:t.protectedUnits.find(l=>l.position===c).unitId}),a=await qi(Wi(JSON.stringify(s)),t,L),o=await zi(t,a.frame,n,L);if(!await qn(t,a.frame,o,i,L))throw new Error("inbox_identity_mismatch");return{frame:ut(Li(a.frame)),signature:o,contentKey:a.contentKey}}recipientReferences(e){return e.recipients.map(t=>({memberId:t.memberId,deviceId:t.deviceId,deviceVersion:t.deviceVersion,keyFingerprint:t.encryptionKeyFingerprint}))}async wrapRecipients(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=h(i.encryptionPublicKey);if(Me(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await L.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:ut(await Bi(t,a,n,L))}}))}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),s=n.mode==="PROTECTED"?await this.openProtectedParent(t,n,i):await this.openMixedParent(e,t,n,i);return e.signal?.throwIfAborted(),{opened:t,manifest:n,segments:s}}async verifyOpening(e,t){let n=Ki(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||!z(n.commitment,C(e.protectedUnits[i].commitment))))throw new Error("inbox_manifest_mismatch")}verifyRecipient(e,t){let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||!z(n.encryptionKeyFingerprint,C(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||!z(t.senderSigningKeyFingerprint,C(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return L.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await Gn(t,h(e.signature),n,L))throw new Error("inbox_signature_invalid");return[{unitId:t.protectedUnits[0].unitId,position:0,status:e.protectedUnits[0].status}]}async openMixedParent(e,t,n,i){if(!t.frame||!t.wrappedContentKey)throw new Error("inbox_missing_normal_body");let s=Fi(h(t.frame));if(!await qn(n,s,h(t.signature),i,L))throw new Error("inbox_signature_invalid");let a=await L.subtle.importKey("pkcs8",h(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await Vi(h(t.wrappedContentKey),a,n,L),d=JSON.parse(ji(await Gi(s,o,n,L)));return this.decodeSegments(d,t,n)}decodeSegments(e,t,n){if(!Array.isArray(e))throw new Error("invalid_inbox_parent_body");let i=e.map((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error("invalid_inbox_parent_body");let o=s;if(typeof o.text=="string"&&Object.keys(o).length===1)return{text:o.text};let d=n.protectedUnits.find(c=>c.position===a);if(!d||o.unitId!==d.unitId||Object.keys(o).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:d.unitId,position:a,status:t.protectedUnits.find(c=>c.unitId===d.unitId).status}});if(n.protectedUnits.some(s=>!i[s.position]||!("unitId"in i[s.position])))throw new Error("invalid_inbox_parent_body");return i}async revealUnit(e){let{manifest:t,segments:n}=await this.openAndVerify(e);if(!n.some(s=>"unitId"in s&&s.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let i=t.protectedUnits.find(s=>s.unitId===e.unitId);return this.child.openCommitted({conversationId:e.conversationId,messageId:e.unitId,identity:e.identity,tenantKeyHex:e.tenantKeyHex,signal:e.signal},i.commitment)}};export{ge as BusinessOrganizationSelectionError,_e as CorePlanMaterialBuilder,wo as DataAssetDefinitionService,V as ElementsApiRequestFailed,ce as ElementsClient,we as GuidedCreateRecoveryError,Pe as GuidedPlanCreator,Ae as HttpAutomationRevealApiPort,ue as HttpElementsApiPort,Rn as HttpOperatorAuthTransport,Xe as HttpPlanEditPort,Re as HttpQuickPlanPort,Lr as InheritiFileInvalid,S as InvalidPlanDeclaration,N as InvalidPlanMaterial,Ot as MAX_INHERITI_FILE_BYTES,Ke as MasterKeyRelayCancellationFailed,Ne as MasterKeyRelayExpired,Oe as MasterKeyRelayTimedOut,J as MasterKeyRequired,be as MemoryGuidedCreateCheckpointStore,fe as MemoryKeyVault,ve as MemoryStatePort,ct as NodeInboxFile,pt as NodeInboxNormal,mt as NodeInboxParent,ae as NodeInboxText,b as OAuthProtocolError,Cn as OperatorAuthClient,Te as OperatorAuthError,q as OperatorReauthenticationRequired,kn as OperatorSessionController,ft as PLAN_CREATION_SERVER_STAGES,_o as PassphraseMasterKeySource,Oo as PlanAssetDeclaration,ie as PlanRequestFailed,Ce as QuickPlanCreator,et as QuickPlanEditor,Co as RawMasterKeySource,H as RelayMasterKeySource,ht as StaticMasterKeyResolver,st as SystemOAuthClock,it as WebOAuthCrypto,Do as computePassphraseVerifier,Ue as createMasterKeyResolver,Ur as createNodeAutomationRevealClient,io as createNodeElementsClient,so as createNodeQuickPlanCreator,ao as createNodeQuickPlanEditor,Hr as decodeAssetContainer,To as deriveMasterKey,Fr as exportProtectedRevealAsset,ko as generateHexSeed,tt as generateInheritiFileKey,Dn as inspectInheritiFileAccess,ye as masterKeyRefFor,te as masterKeyRefKey,at as oauthErrorCode,Mt as openInheritiFile,Qr as openInheritiFileAccess,Nt as openInheritiFileKey,Dt as readInheritiFileHeader,nt as sealInheritiFile,rt as sealInheritiFileKey,Pr as selectBusinessOrganization,Rt as unwrapDekWithMasterKey,ne as validatePlanCreationInput,de as validatePlanCreationMaterial};
|