@safetech/inheriti-client-sdk 1.17.30 → 1.17.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node-base.js CHANGED
@@ -1 +1 @@
1
- import{createNodeSharedConfigurationSdk as wt,decodeAssetContainer as _n}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Rr,generateRSAOAEPKeyPair as Sr}from"@safetech/inheriti-core-sdk/crypto";var _e=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Ce=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},xe=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},G=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:r,privateKey:i}=await Sr();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(r),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(m=>new Promise(v=>setTimeout(v,m))),c=!0,l=!1,u,f=()=>u??=(async()=>{let m=new AbortController,v,U=new Promise((_,V)=>{v=setTimeout(()=>{m.abort(),V(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,m.signal),U])}finally{clearTimeout(v)}})(),E,R=new Promise((m,v)=>{E=()=>{c&&f().catch(()=>{}),v(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",E,{once:!0})});R.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 m=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),R]);if(m.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(m.status==="DELIVERED"&&m.sealedMasterKey){let v=(await Rr(m.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(v))throw new Error("invalid_master_key_material");return v}if(m.status==="EXPIRED")throw new Ce(s.sessionId);await br(d,a,e)}throw new _e(s.sessionId)}catch(m){if(c&&(!l||e?.aborted))try{await f()}catch(v){if(e?.aborted)throw new xe(v)}throw m}finally{E&&e?.removeEventListener("abort",E)}}};async function br(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),n(e).then(r,i).finally(()=>t.removeEventListener("abort",s))})}function Te(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let i=await n.source?.resolve();return i||et(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(Ar(e,n.applicationId)){let i=await n.source?.resolve();return i||et(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return et(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function Ar(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function et(n,e,t,r,i){if((await e()).relayAvailable)return new G({...n.relay,api:_r(n.api,t)}).resolve(r,i)}function _r(n,e){return{startRelaySession:t=>e?n.startMasterKeyRelaySession(t,e):n.startMasterKeyRelaySession(t),readRelaySession:(t,r)=>n.readMasterKeyRelaySession(t,r),cancelRelaySession:(t,r)=>n.cancelMasterKeyRelaySession(t,r)}}function Q(n){return`${n.system}:${n.contextId}`}function me(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var H=class extends Error{constructor(t){super(`master_key_required:${Q(t)}`);this.ref=t;this.name="MasterKeyRequired"}},tt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(Q(e),t),this}async resolve(e){return this.sources.get(Q(e))?.resolve()}};var ge=class{keys=new Map;async store(e,t){let r=Q(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,i)}async load(e){return this.keys.get(Q(e))?.slice()}async remove(e){let t=Q(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var he=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 ke=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},g=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Oe=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var De=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],nt={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},it=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],P=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},k=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function re(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new k("plan_material_field_unknown");if(rt(n.dataShards,"data_shards_invalid"),rt(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&rt(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new k("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new k("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new k("material_operation_invalid")}function rt(n,e){if(!Array.isArray(n))throw new k(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new k(e);if(t.data!==void 0&&typeof t.data!="string")throw new k(e)}}function Y(n){if(te(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Tr(n.idempotencyKey))throw new P("idempotency_key_invalid");if(!n.name?.trim())throw new P("plan_name_required");if(!n.assets.length)throw new P("assets_required");let e=new Set;for(let t of n.assets){if(te(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 P("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!De.includes(t.type))throw new P("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new P("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 P("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new P("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new P("asset_field_names_invalid");if(Cr(t.matchOrigins),!t.isBinary){let s=nt[t.type];if(!s||i.some(a=>!s.includes(a)))throw new P("asset_field_name_not_canonical")}}if(!n.participants.length)throw new P("participants_required");for(let t of n.participants){if(te(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!St(t.routingEmail))throw new P("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new P("participant_relationships_invalid")}xr(n)}function Cr(n){if(n===void 0)return;if(!n.length)throw new P("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new P("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new P("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof P?r:new P("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new P("asset_match_origins_duplicated")}function xr(n){let e=n.policy;if(e&&te(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new P("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){te(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new P("authentication_mode_invalid")}if(e.moderation){te(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new P("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new P("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new P("approval_mode_invalid")}let t=e.dms;if(!t)return;te(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!St(t.subjectEmail))throw new P("dms_subject_invalid");if(!n.participants.some(s=>Rt(s.routingEmail)===Rt(t.subjectEmail)))throw new P("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(i)||t.countdownDays<0||r<0||r>23||i<0||i>59||t.countdownDays+r+i===0)throw new P("dms_countdown_invalid")}function Tr(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(n)}function St(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function Rt(n){return n.normalize("NFC").trim().toLowerCase()}function te(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new P(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)}},ye=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),Y(e),Me(t.signal);let r=await this.api.startPlanCreation(e);return r.outcome==="COMPLETED"||r.outcome==="CANCELED"?await this.checkpoints.remove(r.operationId):await this.saveCheckpoint(e,r),t.onProgress?.(r.stage),r}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,r,i,s={}){Y(t);let a=await this.checkpoints.load(e);if(!a)throw new Ie("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await bt(t))throw new Ie("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;Me(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:s.signal});Me(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});Me(s.signal),re(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 bt(e),serverStage:t.stage})}},Ie=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function bt(n){let e=JSON.stringify({name:n.name.normalize("NFC").trim(),description:n.description?.normalize("NFC").trim()??null,assets:n.assets.map(r=>({...r,fieldNames:[...r.fieldNames??[]]})).sort((r,i)=>r.clientAssetRef.localeCompare(i.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,i)=>r.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:n.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function Me(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function At(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new ke(r.stage);return n.authorizeRevealAction(e,t)}function kr(n){let e=n?.status;return e===400||e===401||e===403}async function _t(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(s){if(!kr(s))throw s}return n.releaseRevealMaterial(e,t)}var st={reason:500,commitSha:64,workflow:200,pipeline:300,target:200,image:300,version:100};function X(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("operation_context_invalid");let e=n;for(let r of Object.keys(e))if(!Object.hasOwn(st,r))throw new Error("operation_context_invalid");let t={};for(let r of Object.keys(st)){if(!Object.hasOwn(e,r))continue;let i=e[r];if(typeof i!="string"||!i.trim()||i.length>st[r]||/[\x00-\x1f\x7f-\x9f]/.test(i)||r==="commitSha"&&(i.length<7||!/^[0-9a-fA-F]+$/.test(i)))throw new Error("operation_context_invalid");t[r]=i.trim()}return t}function Or(n){return n.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":n.stage==="STARTING"?"STARTING":n.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":n.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":n.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":n.stage==="WAITING_FOR_PARTICIPANTS"?Mr(n):n.stage==="DENIED"?"DENIED":n.stage==="EXPIRED"?"EXPIRED":n.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":n.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":n.stage==="MATERIAL_RELEASED"||n.stage==="RECONSTRUCTED"?"RECONSTRUCTING":n.stage==="ACTIONS_OPEN"?"OPEN":Dr.has(n.stage)?"ENDED":"CONTINUING"}var Dr=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Mr(n){return n.governanceGate==="DMS"?"WAITING_FOR_DMS":n.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":n.governanceGate==="AUTHENTICATION"||n.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var at=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},C=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ke(n,e,t={},r=!1){let i=t.operationContext===void 0?void 0:X(t.operationContext);if(i!==void 0&&!r)throw new Error("operation_context_automation_only");if(t.signal?.aborted)throw S();let s=await n.getPlan(e),a=await n.getActivePlanReveal(e);if(a)throw a.planId!==e||a.mode!==(t.mode??"DIRECT")||a.protectedCopy!==void 0&&a.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Ct(a.id);if(t.signal?.aborted)throw S();let o=()=>n.prepareReveal(e,t.signal,async u=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(u)});if(r||await o(),t.signal?.aborted)throw S();let d=t.idempotencyKey??crypto.randomUUID(),c;try{c=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:d,...t.protectedCopy?{protectedCopy:!0}:{},...i!==void 0?{operationContext:i}:{}})}catch(u){if(u?.code!=="merge_process_already_active")throw u;let f=await n.getActivePlanReveal(e);throw!f||f.planId!==e||f.mode!==(t.mode??"DIRECT")||f.protectedCopy!==void 0&&f.protectedCopy!==(t.protectedCopy??!1)?u:Ct(f.id)}if(c.protectedCopy!==void 0&&c.protectedCopy!==(t.protectedCopy??!1))throw await n.closeReveal(c.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let l;try{if(t.signal?.aborted)throw S();let u=await Ur(n,c,t);if(t.signal?.aborted||(r&&await o(),t.signal?.aborted)||(Z(t,"RELEASING_MATERIAL",u),t.signal?.aborted))throw S();let f=await n.releaseRevealMaterial(u.id,u.materialVersion??"1");if(t.signal?.aborted||(u.mode==="GOVERNED"&&await n.markRevealSharesCollected(u.id),t.signal?.aborted))throw S();let E;try{E=await zr(n,u,Fr(f),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(Z(t,"RECONSTRUCTING",u),t.signal?.aborted))throw S();try{l=await n.reconstructPlanMaterial(E)}catch(m){throw t.signal?.aborted?S():(await n.reportRevealReconstruction(u.id,{status:"FAILED",errorCode:qr(m)}),m)}if(t.signal?.aborted)throw S();let R=await n.reportRevealReconstruction(u.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(Z(t,"OPEN",R),t.signal?.aborted))throw S();return new dt(n,R,s,l,t.signal)}catch(u){throw l?.fill(0),await kt(n,c.id,t.signal?.aborted?"CANCELED":"ERROR"),u}}function Ct(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var Nr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Ur(n,e,t){let r=await j(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw S();if(t.onSession?.(r),t.onProgress?.({phase:Or(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(Nr.has(r.stage))throw new ot(r.stage);await ct(t.pollIntervalMs??1500,t.signal),r=await j(()=>n.getReveal(e.id,t.signal),t.signal)}}var ot=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function Z(n,e,t){n.onProgress?.({phase:e,session:t})}function ct(n,e){return e?.aborted?Promise.reject(S()):new Promise((t,r)=>{let i=setTimeout(a,Math.max(0,n)),s=()=>{clearTimeout(i),r(S())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var dt=class{constructor(e,t,r,i,s){this.client=e;this.session=t;this.plan=r;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 at;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([i])=>{r=i?.value}),r}async consumeFields(e,t){if(e.length===0)throw new C("asset_selector_invalid");if(!this.client.assetDecoder)throw new C("asset_decoder_required");let r=e.map(({selector:s,options:a={}})=>{let o=Kr(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new C("asset_not_found");if(d.isBinary)throw new C("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new C("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 r)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=r.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new C("asset_value_invalid");return{selector:a.selector,value:Lr(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",xt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new C("asset_selector_invalid");if(!this.client.assetDecoder)throw new C("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new C("asset_not_found");if(!r.isBinary)throw new C("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===r.id||o.id===r.code);if(!a||!(a.data instanceof Uint8Array))throw new C("asset_value_invalid");s=a.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",xt(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,r){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...r===void 0?{}:{errorCode:r}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=kt(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 Kr(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new C("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new C("asset_selector_invalid");return{asset:n.asset,field:n.field}}function Lr(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new C("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new C("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?nt[t]:void 0)?.includes(e))return"";throw new C("asset_value_invalid")}return r[e]}function xt(n){if(n instanceof C)return n.code;let e=n?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function qr(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function zr(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await j(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new Ne;let c=await j(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(Tt(c,i.id,e.planId),!c.shares.includes(i.data))throw new B;Z(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await j(()=>r.proDevice.write(c,r.signal),r.signal);if(r.signal?.aborted)throw S();if(!l?.trim())throw new B;if(await n.claimRevealCustodianShare(e.id,c.id,l),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,c.id),r.signal?.aborted))throw S();return{...t,shares:t.shares.filter(u=>u!==i).concat(c.shares.map((u,f)=>({id:`${c.id}:${f}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new B;if(r.signal?.aborted)throw S();return await n.distributeRevealCustodianShare(e.id),Z(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await j(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),Z(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ct(r.pollIntervalMs??1500,r.signal),s=await j(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!r.proDevice)throw new Ne;if(!s.shareId||!s.deviceId)throw new B;Z(r,"CONNECTING_SAFEKEY_PRO",e);let d=await j(()=>r.proDevice.read({shareId:s.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw S();if(Tt(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new B;if(await n.collectRevealCustodianShare(e.id,s.shareId),r.signal?.aborted)throw S();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 B;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),Z(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw S();await n.requestRevealCustodianRelease(e.id);let o=await Gr(n,e,r);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 Tt(n,e,t){if(n?.id!==e||n.planId!==t||!Array.isArray(n.shares)||n.shares.length===0||n.shares.some(r=>typeof r!="string"||!r))throw new B}async function j(n,e){if(e?.aborted)throw S();if(!e)return n();let t,r=new Promise((i,s)=>{t=()=>s(S()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw S();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Gr(n,e,t){let r=Date.parse(e.expiresAt),i=Number.isFinite(r)?Math.min(r,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Ue;let s=await j(()=>n.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Ue;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new B}await ct(t.pollIntervalMs??1500,t.signal)}}var B=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Ne=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ue=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Fr(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function kt(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!Vr(a))throw a}return}let r=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([n.closeReveal(e,t,r.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 Vr(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function S(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var ne=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 ge,this.state=t.state??new he,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Hr(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new g;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new g;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new g;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new g;return this.api.listMemberLogs(e,t)}listOrganizationMembers(e){if(!this.api)throw new g;return this.api.listOrganizationMembers(e)}listOrganizationAuditTrail(e){if(!this.api)throw new g;return this.api.listOrganizationAuditTrail(e)}getOrganizationInsights(e){if(!this.api)throw new g;return this.api.getOrganizationInsights(e)}getPlanResponsibilities(e){if(!this.api)throw new g;return this.api.getPlanResponsibilities(e)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return Y(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new g;return re(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new g;return new ye(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),r=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",r)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new H({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let i=await this.keyVault.load(e);if(i)return $r(i);let s=await this.masterKeys?.resolve(e,t,r);if(!s)throw new H(e);return await this.keyVault.store(e,Br(s)),s}async prepareReveal(e,t,r){if(!this.api)throw new g;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,r)}}async revealPlan(e,t){await this.prepareReveal(e);let r=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(r)}collectPlanMaterial(e,t){if(!this.api)throw new g;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Oe;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,r){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new H({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=me(e);if(!i)throw new H({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new g;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new g;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new g;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,r){if(!this.api)throw new g;return this.api.createRevealFileAccess(e,t,r)}cancelRevealFileAccess(e,t,r){if(!this.api)throw new g;return this.api.cancelRevealFileAccess(e,t,r)}getActivePlanReveal(e){if(!this.api)throw new g;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new g;return this.api.getReveal(e,t)}openReveal(e,t){return Ke(this,e,t)}async withReveal(e,t,r){let i=await this.openReveal(e,t);try{let s=await r(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new g;return _t(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new g;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new g;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new g;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new g;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new g;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new g;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new g;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new g;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new g;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new g;return At(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new g;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new g;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new g;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new g;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new g;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new g;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let r=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=r.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||r.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let r=await this.reconstructPlanMaterial(t);if(!this.api)throw new g;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),r}useCase(e,t){if(!this.coreSdk)throw new lt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new H({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},lt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Br(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function $r(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Hr(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return Te({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return Te({...e,organizationId:n.organizationId})}var jr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Wr=["DIRECT","GOVERNED"],Dt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Qr=["ACTIVE","REVOKED"],Yr=["SK_MOBILE"],Xr=["ACTIVE","INACTIVE"],Zr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Mt(n){let e=x(n);return{items:L(e.items).map(Kt),nextCursor:e.nextCursor===null?null:h(e.nextCursor,"nextCursor")}}function Nt(n){let e=x(n);return{total:F(e.total,"total"),items:L(e.items).map(t=>{let r=x(t);if("eventData"in r)throw new Error("invalid_elements_response");return{id:h(r.id,"log.id"),planId:h(r.planId,"log.planId"),tenantId:h(r.tenantId,"log.tenantId"),event:h(r.event,"log.event"),occurredOn:h(r.occurredOn,"log.occurredOn"),status:W(r.status),title:h(r.title,"log.title"),details:L(r.details).map(i=>{let s=x(i);return{label:h(s.label,"log.detail.label"),value:h(s.value,"log.detail.value")}})}})}}function Ut(n){let e=x(n);return{total:F(e.total,"total"),items:L(e.items).map(t=>{let r=x(t);if("eventData"in r)throw new Error("invalid_elements_response");let i=h(r.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:h(r.id,"log.id"),memberId:h(r.memberId,"log.memberId"),source:i,event:h(r.event,"log.event"),occurredOn:h(r.occurredOn,"log.occurredOn"),status:W(r.status)}})}}function Le(n){let e=x(n),t=Kt(e),r=x(e.source),i=h(r.kind,"source.kind");return{...t,assets:L(e.assets).map(s=>{let a=x(s);return{id:h(a.id,"asset.id"),code:W(a.code),type:K(h(a.type,"asset.type"),De),name:h(a.name,"asset.name"),isBinary:en(a.isBinary,"asset.isBinary"),fieldNames:L(a.fieldNames).map(o=>h(o,"asset.fieldNames")),fileName:W(a.fileName),mimeType:W(a.mimeType),size:a.size===void 0||a.size===null?void 0:F(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:L(a.matchOrigins).map(o=>h(o,"asset.matchOrigins"))}}),participants:L(e.participants).map(s=>{let a=x(s);return{id:h(a.id,"participant.id"),displayName:h(a.displayName,"participant.displayName"),relationships:L(a.relationships).map(o=>K(h(o,"relationship"),Dt)),lifecycle:K(h(a.lifecycle,"participant.lifecycle"),Qr)}}),revealPolicy:(()=>{let s=x(e.revealPolicy);return{masterKeyRelease:K(h(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:K(h(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=x(e.dms);return{subjectEmail:h(s.subjectEmail,"dms.subjectEmail"),countdownDays:F(s.countdownDays,"dms.countdownDays"),countdownHours:F(s.countdownHours,"dms.countdownHours"),countdownMinutes:F(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:K(h(r.system,"source.system"),["INHERITI_BUSINESS"]),status:K(h(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ve(n){let e=x(n);return{operationId:h(e.operationId,"operationId"),stage:K(h(e.stage,"stage"),it),outcome:K(h(e.outcome,"outcome"),Zr),planId:W(e.planId),lastErrorCode:W(e.lastErrorCode),participants:e.participants===void 0?void 0:L(e.participants).map(t=>{let r=x(t);return{clientParticipantRef:h(r.clientParticipantRef,"clientParticipantRef"),planParticipantId:h(r.planParticipantId,"planParticipantId"),relationships:L(r.relationships).map(i=>Jr(h(i,"relationship"),Dt))}})}}function Kt(n){let e=x(n),t=x(e.assetSummary),r=x(e.governance),i=x(e.participantSummary);return{id:h(e.id,"id"),name:h(e.name,"name"),description:W(e.description),status:K(h(e.status,"status"),jr),createdAt:h(e.createdAt,"createdAt"),configuredAt:W(e.configuredAt),assetSummary:{count:F(t.count,"assetSummary.count"),types:L(t.types).map(s=>K(h(s,"assetType"),De)),names:Ot(t.names).map(s=>h(s,"assetSummary.names"))},governance:{mode:K(h(r.mode,"governance.mode"),Wr),minimumApprovals:F(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:F(i.owners,"owners"),mergers:F(i.mergers,"mergers"),moderators:F(i.moderators,"moderators")},authentication:Ot(e.authentication).map(s=>{let a=x(s);return{id:K(h(a.id,"authentication.id"),Yr),status:K(h(a.status,"authentication.status"),Xr)}})}}function K(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function Jr(n,e){if(!e.includes(n))throw new Error("invalid_elements_response");return n}function x(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function Ot(n){return n==null?[]:L(n)}function L(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function h(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function W(n){return n==null?void 0:h(n,"optional")}function F(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function en(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function q(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function ie(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function b(n){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function pt(n){return n==null?void 0:b(n)}function T(n){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function tn(n){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function Lt(n){let e=q(n);return{total:T(e.total),items:ie(e.items).map(t=>{let r=q(t);return{id:b(r.id),displayName:b(r.displayName),role:b(r.role),status:b(r.status)}})}}function qt(n){let e=q(n);return{total:T(e.total),shownCount:T(e.shownCount),totalCount:T(e.totalCount),nextCursor:e.nextCursor==null?null:b(e.nextCursor),hasMore:tn(e.hasMore),items:ie(e.items).map(t=>{let r=q(t);if("eventData"in r)throw new Error("invalid_elements_response");return{id:b(r.id),occurredOn:b(r.occurredOn),actorName:b(r.actorName),actorRole:b(r.actorRole),category:b(r.category),action:b(r.action),subject:b(r.subject),status:b(r.status),sourceEvent:b(r.sourceEvent),planId:pt(r.planId),planName:pt(r.planName),responsibleMemberName:pt(r.responsibleMemberName)}})}}function zt(n){let e=q(n),t=q(e.stats),r=q(e.planAccessResults);return{stats:{totalPlans:T(t.totalPlans),plansCreatedThisMonth:T(t.plansCreatedThisMonth),activeMembers:T(t.activeMembers),totalSeats:t.totalSeats==null?null:T(t.totalSeats),accessRequests30d:T(t.accessRequests30d),accessRequestsPrevious30d:T(t.accessRequestsPrevious30d),pendingApprovals:T(t.pendingApprovals)},plansOverTime:ie(e.plansOverTime).map(i=>{let s=q(i);return{month:b(s.month),count:T(s.count)}}),planTypes:ie(e.planTypes).map(i=>{let s=q(i);return{type:b(s.type),count:T(s.count)}}),accessModerationActivity:ie(e.accessModerationActivity).map(i=>{let s=q(i);return{week:b(s.week),requests:T(s.requests),approvals:T(s.approvals)}}),planAccessResults:{success:T(r.success),aborted:T(r.aborted),expired:T(r.expired)}}}function Gt(n){let e=q(n);return{planId:b(e.planId),participants:ie(e.participants).map(t=>{let r=q(t);return{id:b(r.id),displayName:b(r.displayName),relationships:ie(r.relationships).map(i=>b(i)),lifecycle:b(r.lifecycle)}})}}function qe(n,e){if(Object.keys(n).some(t=>!e.includes(t)))throw new Error("organization_query_field_unknown")}var de=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Ft(n){if(!n||typeof n!="object"||!("items"in n)||!Array.isArray(n.items)||!n.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return n.items.map(({id:e,name:t})=>({id:e,name:t}))}function rn(n,e){if(!e){if(n.length===0)throw new de("organization_required");if(n.length>1)throw new de("organization_selection_required");return n[0].id}if(!n.some(({id:t})=>t===e))throw new de("organization_access_denied");return e}function nn(n){let e=w(n);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:I(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:I(e.participantRevision,1),createdAt:M(e.createdAt),...Vt(e)}}function Vt(n){if(n.recipientStatuses===void 0)return{};if(!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:n.recipientStatuses.map(e=>{let t=w(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:M(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(r=>{let i=w(r);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:I(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:M(i.revealedAt)}:{}}})}:{}}})}}function Bt(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(nn),total:I(e.total,0),limit:I(e.limit,1),offset:I(e.offset,0),unreadCount:I(e.unreadCount,0),readThroughSequence:I(e.readThroughSequence,0)}}function $t(n){let e=w(n);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:I(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:I(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:I(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let r=w(t);return{unitId:p(r.unitId),position:I(r.position,0),commitment:p(r.commitment),status:p(r.status)}})}}function ut(n){let e=w(n);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:I(e.sequence,1),status:e.status}}function Ht(n){let e=w(n);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:I(e.participantRevision,1),recipients:e.recipients.map(mt)}}function jt(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=w(t);return{parentId:p(r.parentId),sequence:I(r.sequence,1),senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),participantRevision:I(r.participantRevision,1),createdAt:M(r.createdAt),...Vt(r)}}),total:I(e.total,0),limit:I(e.limit,1),offset:I(e.offset,0),unreadCount:I(e.unreadCount,0),readThroughSequence:I(e.readThroughSequence,0)}}function Wt(n){return{readThroughSequence:I(w(n).readThroughSequence,0)}}function Qt(n){return{clearedThroughSequence:I(w(n).clearedThroughSequence,0)}}function Yt(n){let e=w(n);return{parentId:p(e.parentId),sequence:I(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:I(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function w(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_inbox_response");return n}function p(n){if(typeof n!="string"||!n)throw new Error("invalid_inbox_response");return n}function M(n){let e=p(n);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function I(n,e){if(!Number.isSafeInteger(n)||n<e)throw new Error("invalid_inbox_response");return n}function mt(n){let e=w(n);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:I(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function ce(n){let e=w(n);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:M(e.createdAt),updatedAt:M(e.updatedAt)}}function ze(n){let e=w(n);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:M(e.createdAt),updatedAt:M(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let r=w(e.latestMessage);if(r.contentKind!=="TEXT"&&r.contentKind!=="FILE"&&r.contentKind!=="NORMAL"&&r.contentKind!=="MIXED"&&r.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:r.contentKind,senderMemberId:p(r.senderMemberId),createdAt:M(r.createdAt)}}return t}function Xt(n){let e=w(n);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(ze),total:e.total,limit:e.limit,offset:e.offset}}function Zt(n){let e=w(n);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=mt(t);return{memberId:r.memberId,name:p(w(t).name),deviceId:r.deviceId,deviceVersion:r.deviceVersion,encryptionPublicKey:r.encryptionPublicKey,encryptionKeyFingerprint:r.encryptionKeyFingerprint,signingPublicKey:r.signingPublicKey,signingKeyFingerprint:r.signingKeyFingerprint}}),limit:I(e.limit,1),offset:I(e.offset,0),nextOffset:e.nextOffset===null?null:I(e.nextOffset,0)}}function Jt(n){let e=w(n);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=w(t);if(typeof r.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(r.memberId),name:p(r.name),ready:r.ready,...r.profilePicture===void 0?{}:{profilePicture:{url:p(w(r.profilePicture).url)}}}}),limit:I(e.limit,1),offset:I(e.offset,0),nextOffset:e.nextOffset===null?null:I(e.nextOffset,0)}}function er(n){let e=w(n);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),messageId:p(e.messageId),participantRevision:I(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(mt),shareLayers:e.shareLayers.map(t=>{let r=w(t),i=p(r.id),s=p(r.dataShareId),a=p(r.keyShareId);if(r.type==="INHERITI_CHAIN")return{id:i,type:r.type,contractAddress:p(r.contractAddress),dataShareId:s,keyShareId:a};if(r.type==="INHERITI_VAULT"||r.type==="GOOGLE_DRIVE"||r.type==="DROPBOX"||r.type==="ONEDRIVE")return{id:i,type:r.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function Ge(n){let e=w(n);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:p(e.messageId),status:e.status}}function tr(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=w(t);if(r.status!=="PREPARING"&&r.status!=="AVAILABLE"&&r.status!=="FAILED"&&r.status!=="DELETING")throw new Error("invalid_inbox_response");if(r.contentKind!==void 0&&r.contentKind!=="TEXT"&&r.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(r.recipientStatus!==void 0&&r.recipientStatus!=="UNREAD"&&r.recipientStatus!=="LEASED"&&r.recipientStatus!=="CONSUMED"&&r.recipientStatus!=="EXPIRED"&&r.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(r.recipientStatuses!==void 0&&!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:p(r.id),status:r.status,senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),createdAt:M(r.createdAt),updatedAt:M(r.updatedAt),expiresAt:M(r.expiresAt)};return r.contentKind&&(i.contentKind=r.contentKind),r.recipientStatus&&(i.recipientStatus=r.recipientStatus),Array.isArray(r.recipientStatuses)&&(i.recipientStatuses=r.recipientStatuses.map(s=>{let a=w(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:p(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:M(a.consumedAt)}:{}}})),i}),total:I(e.total,0),limit:I(e.limit,1),offset:I(e.offset,0)}}function rr(n){let e=w(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:M(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:I(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=w(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:I(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId),ciphertext:p(r.ciphertext)}})}}function nr(n){let e=w(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:M(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:I(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=w(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:I(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId)}})}}function Fe(n){return typeof n=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(n)&&Number.isFinite(Date.parse(n))}function se(n){return typeof n.error=="string"?/^[a-z][a-z0-9_]*$/.test(n.error)?n.error:typeof n.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(n.validationErrors)?n.validationErrors:n.error||void 0:n.error?.code??n.name??n.message}function ae(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var z=class extends Error{constructor(t,r,i,s){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},le=class{constructor(e,t,r,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=r;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,r,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":r},i)}confirmFileAccessDelivery(e,t,r){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":r})}createInboxFileAccess(e,t,r,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",r,void 0,void 0,i)}createRevealFileAccess(e,t,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,r)}cancelRevealFileAccess(e,t,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",r)}cancelInboxFileAccess(e,t,r,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(r)}`,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 r=t;if(typeof r.publicKey!="string"||!r.publicKey||typeof r.fingerprint!="string"||!r.fingerprint||r.status!=="ACTIVE"&&r.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:r.publicKey,fingerprint:r.fingerprint,status:r.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:ce(t)}async getMemberInboxDevice(e,t){let r=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return r===null?null:ce(r)}async registerInboxDevice(e){return ce(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return ce(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return ce(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return ze(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return ze(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Xt(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Zt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Jt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return er(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Ht(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let r={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Ge(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",r))}async publishNormalInboxMessage(e,t){return ut(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return ut(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},r){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return Bt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,r))}async openInboxParent(e,t,r,i){let s=new URLSearchParams({deviceId:r});return $t(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 Qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},r){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,r))}async openNormalInboxMessage(e,t,r,i){let s=new URLSearchParams({deviceId:r});return Yt(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,r){return Wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:r}))}async stageInboxFile(e,t,r){return Ge(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,r))}async uploadInboxFileShare(e,t,r,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(r)}`,o=await this.requestBinary(a,"PUT",i,s),d=await Ve(o,s);if(!d.ok||d.result?.shareId!==r||d.result.status!=="STORED")throw new z(o.status,se(d),ae(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,r){return Ge(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,r))}async openInboxFile(e,t,r,i){return nr(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:r},void 0,void 0,i))}async downloadInboxFileShare(e,t,r,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}?${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 u=c.body.getReader(),f=[],E=0;try{for(;;){a?.throwIfAborted();let v=await u.read();if(v.done)break;if(E+=v.value.length,E>14*1024*1024)throw new Error("invalid_inbox_share_size");f.push(v.value)}}catch(v){throw await u.cancel().catch(()=>{}),v}let R=new Uint8Array(E),m=0;for(let v of f)R.set(v,m),m+=v.length;return R}async listInboxMessages(e,t={},r){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return tr(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,r))}async openInboxMessage(e,t,r){return rr(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:r}))}async ackInboxMessage(e,t,r,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:r,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,r,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:r,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Ft)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let r=t.size?`?${t}`:"";return Mt(await this.request(`v1/plans${r}`,"GET"))}async getPlan(e){return Le(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let r=new URLSearchParams;t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return Nt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let r=new URLSearchParams;t.source&&r.set("source",t.source),t.from&&r.set("from",t.from),t.to&&r.set("to",t.to),t.q&&r.set("q",t.q),t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return Ut(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listOrganizationMembers(e={}){if(this.requireOrganizationSelection(),qe(e,["limit","offset"]),e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>100))throw new Error("organization_query_limit_invalid");if(e.offset!==void 0&&(!Number.isSafeInteger(e.offset)||e.offset<0))throw new Error("organization_query_offset_invalid");let t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),Lt(await this.request(`v1/organization/members${t.size?`?${t}`:""}`,"GET"))}async listOrganizationAuditTrail(e){if(this.requireOrganizationSelection(),qe(e,["from","to","limit","cursor","category","memberId","responsibleMemberId"]),!Fe(e.from)||!Fe(e.to)||Date.parse(e.from)>Date.parse(e.to))throw new Error("organization_query_date_invalid");if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>500))throw new Error("organization_query_limit_invalid");if(e.cursor!==void 0&&!/^[1-9]\d*$/.test(e.cursor))throw new Error("organization_query_cursor_invalid");let t=new URLSearchParams({from:e.from,to:e.to});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor!==void 0&&t.set("cursor",e.cursor),e.category!==void 0&&t.set("category",e.category),e.memberId!==void 0&&t.set("memberId",e.memberId),e.responsibleMemberId!==void 0&&t.set("responsibleMemberId",e.responsibleMemberId),qt(await this.request(`v1/organization/audit-trail?${t}`,"GET"))}async getOrganizationInsights(e={}){if(this.requireOrganizationSelection(),qe(e,["from","to"]),e.from===void 0!=(e.to===void 0)||e.from!==void 0&&(!Fe(e.from)||!Fe(e.to)||Date.parse(e.from)>Date.parse(e.to)))throw new Error("organization_query_date_invalid");let t=new URLSearchParams;return e.from!==void 0&&e.to!==void 0&&(t.set("from",e.from),t.set("to",e.to)),zt(await this.request(`v1/organization/insights${t.size?`?${t}`:""}`,"GET"))}async getPlanResponsibilities(e){if(this.requireOrganizationSelection(),!e)throw new Error("plan_id_required");return Gt(await this.request(`v1/plans/${encodeURIComponent(e)}/responsibilities`,"GET"))}async startPlanCreation(e){Y(e);let{idempotencyKey:t,...r}=e;return ve(await this.request("v1/plan-creations","POST",r,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ve(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return re(t),ve(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ve(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){if(t.operationContext!==void 0)throw new Error("operation_context_automation_only");let{idempotencyKey:r,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":r})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:r})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,r)}abortPlanAccess(e,t){let r=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${r}?revealId=${encodeURIComponent(t)}`:r,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;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,r,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[E,R]of Object.entries(s??{}))d.set(E,R);r&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:r?JSON.stringify(r):void 0};a&&(l.signal=a);let u=await this.transport(new URL(e,c),l);a?.throwIfAborted();let f=await Ve(u,a);if(a?.throwIfAborted(),!u.ok)throw new z(u.status,se(f),ae(f),u.headers.get("x-request-id")??void 0);if(!f.ok||f.result===void 0)throw new z(u.status,se(f),ae(f),u.headers.get("x-request-id")??void 0);return f.result}async requestBinary(e,t,r,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),r&&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:r?Buffer.from(r):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await Ve(d,i);throw new z(d.status,se(c),ae(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,r,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[u,f]of Object.entries(r??{}))o.set(u,f);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 Ve(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new z(c.status,se(l),ae(l),c.headers.get("x-request-id")??void 0)}requireOrganizationSelection(){if(!this.business?.organizationId)throw new z(400,"organization_selection_required")}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new z(400,"organization_selection_required")}};async function Ve(n,e){try{return await n.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as un}from"@safetech/inheriti-core-sdk/node";async function gt(n,e){if(!e)throw new Error("master_key_required");let t=sn(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=an(n),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,a);return on(new Uint8Array(o))}function sn(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function an(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function on(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Pe=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await ir("plan_key_unwrap_failed",()=>gt(e.planKey,t)),i=await crypto.subtle.importKey("raw",ht(r),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await ir("plan_share_decryption_failed",()=>pn(o.data,i));ln(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 Be("plan_share_reconstruction_failed",cn(o))}}},Be=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},dn=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 cn(n){let e=n instanceof Error?n.message:void 0;if(e)return dn.has(e)?e:void 0}async function ir(n,e){try{return await e()}catch{throw new Be(n)}}function ln(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function pn(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=ht(n.slice(0,t)),i=ht(n.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(s)}function ht(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i+=1)r[i]=e.charCodeAt(i);return t}var oe=class extends Pe{constructor(e){super(()=>un(e))}};var we=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){let r=t.operationContext===void 0?void 0:X(t.operationContext);return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey,...r===void 0?{}:{operationContext:r}},!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 Le(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,r){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,r)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let r=this.firstRelayStates.get(e);return r?(this.firstRelayStates.delete(e),Promise.resolve(r)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,r,i=!0,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});r!==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:r===void 0?void 0:JSON.stringify(r),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 z(c.status,l&&se(l),l&&ae(l));return l?.result}};var A={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 J=class extends Error{constructor(t,r){super(r??`plan_request_failed_${t}`);this.status=t;this.code=r}},Ee=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,r,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:r,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:r.validatorShares,encryptedKey:r.encryptedKey})}preflight(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",sr(r))}configure(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",sr(r))}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(A.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(A.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(A.relayFailed);return r}async request(e,t,r,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(A.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:r,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 J(c.status,l.error);return l.result}};function sr(n){return{protectionProtocol:n.protectionProtocol,operation:"FINALIZE",dataShards:n.dataShards,backupShards:n.backupShards,encryptedKey:n.encryptedKey,assetsMetadata:n.assetsMetadata,custodianPair:n.custodianShard}}var Se=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),gn(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,r=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:r,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(Re(e.signal),!i.custodianPair)throw new k("custodian_share_required");let s=ft(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(ft(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(ft(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return Re(e.signal),{protectionProtocol:i.protocol,validatorShares:yt(a.encryptedShares),dataShards:yt(o.encryptedShares),backupShards:yt(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:mn(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let r=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:It(r.encryptedShares[0]),dataShard:It(r.encryptedShares[1])}}};function ft(n){return n.map(e=>({id:crypto.randomUUID(),data:e}))}function yt(n){return n.map(It)}function It(n){return{id:n.id,data:n.encryptedData}}function mn(n,e){let t={};for(let r of n){let i=e.assets.find(s=>s.clientAssetRef===r.id);if(!i)throw new k("plan_secrets_declaration_mismatch");t[r.id]={type:r.type,meta:{name:r.meta.name,notes:r.meta.notes,...r.meta.isMedia===void 0?{}:{isMedia:r.meta.isMedia},...r.meta.mimeType===void 0?{}:{mimeType:r.meta.mimeType},...r.meta.fileName===void 0?{}:{fileName:r.meta.fileName},...r.meta.code===void 0?{}:{code:r.meta.code},...r.meta.matchOrigins===void 0?{}:{matchOrigins:[...r.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function gn(n,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new k("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new k("share_threshold_invalid");if(e.assets.length!==n.assets.length)throw new k("plan_secrets_declaration_mismatch");let t=new Map(n.assets.map(r=>[r.clientAssetRef,r]));for(let r of e.assets){let i=t.get(r.id);if(!i||i.type!==r.type)throw new k("plan_secrets_declaration_mismatch")}}function Re(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function ar(n,e,t,r,i,s,a){let o=r.mergeThreshold-(r.withCustodian?1:0);if(typeof r.withCustodian!="boolean"||!Number.isInteger(r.mergeThreshold)||o<1||o>n.totalShares)throw new Error(A.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:r.withCustodian?"FORCE":"BYPASS"};let l=n.masterKeySource??new G({api:{startRelaySession:E=>i.startRelaySession(n.organizationId,t.masterKeyAcquisition,E),readRelaySession:E=>i.readRelaySession(n.organizationId,E)}}),u=new Se(s,l);a?.("encrypting");let f=await u.encrypt({planId:n.planId,declaration:c,secrets:{assets:d,totalShares:n.totalShares,threshold:o}});return a?.("generating_shares"),u.generateShares({planId:n.planId,declaration:c,encrypted:f})}import{PlanAssetDeclaration as hn}from"@safetech/inheriti-core-sdk/node";function or(n){let e=vt({planId:n.planId,title:n.title,assets:[n.asset]});return{asset:e.assets[0],plan:e.plan}}function vt(n){if(!n.assets.length)throw new P("assets_required");let e=n.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 P("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new P("binary_asset_metadata_invalid");return o}),t=hn.create(n.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),r=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,n.assets[a].secret]))),i={idempotencyKey:n.planId,name:n.title,assets:r.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:r,plan:i}}async function cr(n){let e=await Promise.all(n.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([r],[i])=>r.localeCompare(i)).map(async([r,i])=>[r,i instanceof Blob?await dr(new Uint8Array(await i.arrayBuffer())):i]))})));return dr(new TextEncoder().encode(JSON.stringify({organizationId:n.organizationId,planId:n.planId,title:n.title,description:n.description??null,audience:n.audience??null,totalShares:n.totalShares,assets:e})))}async function dr(n){let e=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var be=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(A.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(A.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(A.invalidShares);let r=await cr(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==r)throw new Error(A.reconciliationRequired);return i.promise}let s=this.performCreate(e,r,t);this.flights.set(e.planId,{fingerprint:r,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,r){let i=vt({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(A.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if($e(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(A.reconciliationRequired);if(!a&&s)throw new Error(A.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(A.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(A.invalidMasterKeyContext);if(!a){r?.("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 ar(e,i,o,a,this.port,this.coreSdk,r);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),r?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),r?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),r?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!$e(await this.statusOrMissing(e.organizationId,e.planId)))throw l}r?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return $e(c)&&this.material.delete(e.planId),{planId:e.planId,status:$e(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(A.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(r){if(r instanceof J&&r.status===404)return;throw r}}};function $e(n){return n?.status==="PROTECTED"||n?.status==="CONFIGURED"}var He=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}start(e,t,r,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:r},i)}async listEligibleCandidates(e,t,r){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),r&&i.set("namePrefix",r);let 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 r=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(r))throw new Error("invalid_plan_edit_context");return r}async moderatorNames(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!r||typeof r!="object")throw new Error("invalid_plan_edit_participants");let i=r;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let 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,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(A.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(A.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(A.relayFailed);return r}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(r))}commit(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(r))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,r,i,s){let a=await this.getBearerToken();if(!a)throw new Error(A.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:r,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),u={};try{u=await l.json()}catch{}if(!l.ok||u.ok!==!0){let f=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new J(l.status,f||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(r=>!!r&&typeof r.id=="string"&&!!r.id&&typeof r.name=="string"&&r.status==="PROTECTED"&&typeof r.createdAt=="string"&&!!r.assetSummary&&Number.isSafeInteger(r.assetSummary.count)&&r.assetSummary.count>=0&&Array.isArray(r.assetSummary.types)&&r.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(r.assetSummary.names)&&r.assetSummary.names.every(i=>typeof i=="string")&&!!r.governance&&["DIRECT","GOVERNED"].includes(r.governance.mode)&&Number.isSafeInteger(r.governance.minimumApprovals)&&r.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var je=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.recoveryStore=r}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let r=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),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(u=>u.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&r===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:s,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),r=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(r>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return r}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new G({api:{startRelaySession:r=>this.port.startRelaySession(e.organizationId,t,r),readRelaySession:r=>this.port.readRelaySession(e.organizationId,r)}}).resolve()}async revealAssets(e,t,r,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=m=>{m!==o&&(o=m,i?.(m))},c=m=>{if(m.processId!==e.editId||m.planId&&m.planId!==e.planId)return;switch(m.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let v=this.approvalError(m);if(v?.startsWith("edit_authentication_")&&d("pending_auth"),v?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!m.moderatorParticipants||m.requiredModeratorApprovals===void 0||!m.approvalProcess)return;let U=m.moderatorParticipants.map(_=>_.memberId??_.userId);U.some(_=>typeof _!="string"||!_)||new Set(U).size!==U.length||i?.(o,{requiredApprovals:m.requiredModeratorApprovals,approvedModerators:m.approvalProcess.approvedModerators,moderators:m.moderatorParticipants.map((_,V)=>{let pe=U[V],Et=_.flows.filter(ue=>ue.status==="PENDING"&&ue.expiresAt&&Number.isFinite(ue.expiresAt.getTime())).map(ue=>ue.expiresAt.getTime());return{id:pe,displayName:a.get(pe)||"Moderator",status:_.status,expiresAt:Et.length?new Date(Math.min(...Et)).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 u=await s.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");c(u),this.assertApprovalOutcome(e.planId,u);let f=u?.status;if(f!=="READY_TO_REVEAL"&&f!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let E=null,R={onRevealed:m=>{E=m},onViewUpdate:c,onRevealStepUpdate:(m,v)=>{if(v==="IN_PROCESS")switch(m){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(r&&(R.onCustodianShareRequired=async(m,v)=>{switch(v.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let U=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),U==="SK_MOBILE")return s.distributeCustodianShareViaMobile(v.planId);if(U!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let _=e.proDevice;try{this.assertNotAborted(e.signal);let V=await s.getCustodianShareData(m);this.assertShare(V,v.planId),d("connecting_safekey_pro");let{deviceId:pe}=await _.write(V,e.signal);if(this.assertNotAborted(e.signal),!pe?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(v.planId,V.id,pe,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(m,V.id);return}finally{_.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 U=e.proDevice;try{if(this.assertNotAborted(e.signal),!v.shareId||!v.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let _=await U.read({shareId:v.shareId,planId:v.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(_,v.planId,v.shareId),_.deviceId!==v.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:_.shares}}finally{U.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),f==="REVEALED"?await s.resumeReveal(e.editId,R,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},R,t),this.assertNotAborted(e.signal),!E)throw new Error("edit_assets_unavailable");return E}assertApprovalOutcome(e,t){let r=this.approvalError(t);if(r)throw this.clearRevealedAssets(e),new Error(r)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,r){if(!e||!e.id||e.id!==(r??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var fn=n=>JSON.stringify(n??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([r],[i])=>r<i?-1:r>i?1:0))),We=class{constructor(e,t,r,i){this.port=e;this.coreSdk=t;this.recoveryStore=r;this.clearRevealedAssets=i}async saveAssets(e,t,r,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,r,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 r=await this.configurationRepository().findByPlanId(e.planId),i=r?.editDistribution??r?.preparedDistribution;if(!t&&(!i||r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let 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(!r?.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 r=await this.configurationRepository().findByPlanId(e.planId);if(r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let r=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await r.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await r.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,r,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:r,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,r,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,r))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,r))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let r=await this.port.commitStatus(e.organizationId,e.editId);if(r.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(r.status)||r.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(fn(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(r.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(r.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var Qe=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.assetAccess=new je(e,t,r),this.reconfiguration=new We(e,t,r,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,r,i){return this.port.start(e,t,r,i)}async listAssets(e,t){let{assets:r}=await this.assetAccess.loadAssets(e,t);return r.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,r){let{assets:i}=await this.assetAccess.loadAssets(e,r),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:r,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,u)=>u===a?d:l);return this.reconfiguration.saveAssets(e,c,r.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:r,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=or({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),r.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 lr({apiUrl:n,organizationId:e,planId:t,editId:r,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),c=new URL(n.endsWith("/")?n:`${n}/`);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 u=yn(l,d.searchParams,t,r),f=new Headers(o?.headers);f.set("x-organization-id",e),f.set("x-elements-environment",i);let E=c.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return s(new URL(E,c),Object.assign({},o,{headers:f}))}}function yn(n,e,t,r){if(n==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(n);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]!==r||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(n);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(r)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(r)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as In}from"@safetech/inheriti-core-sdk/node";function pr(n){return{async openReveal(e,t={}){let r=t.operationContext===void 0?void 0:X(t.operationContext);if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let i=await n.api.planKeyReference(e),s=me(i);if(!i.masterKeyWrapped||!s||i.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new G({api:{startRelaySession:d=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,d),readRelaySession:(d,c)=>n.api.readMasterKeyRelaySession(d,c),cancelRelaySession:(d,c)=>n.api.cancelMasterKeyRelaySession(d,c)}}),o=new ne(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(d,c,l)=>{if(d.system!==s.system||d.contextId!==s.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(c,l)}}});return Ke(o,e,{...t,...r===void 0?{}:{operationContext:r}},!0)}}}function vn(n){let e=new we(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{supportsOperationContext:!0,...pr({api:e,reconstructor:new oe(n.workerUrl),assetDecoder:In}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as ur,sealInheritiFile as mr,readInheritiFileHeader as hs,openInheritiFile as fs,InheritiFileInvalid as ys,MAX_INHERITI_FILE_BYTES as gr}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as hr,openInheritiFileKey as Ps}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Pn(n){let{reveal:e,api:t,signal:r}=n;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(r);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=n.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(n.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>gr-1024*1024)throw new Error("unsupported_protected_asset");let d=ur(),c,l=!1,u=!1;try{r?.throwIfAborted();let f=await hr(d,i.publicKey);l=!0;let E=await t.createRevealFileAccess(e.session.id,{copyId:n.copyId,envelopeId:n.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:f,openLimit:a},r);if(E.copyId!==n.copyId||E.status!=="PENDING")throw new Error("file_access_create_invalid");let R=await t.getFileAccess(n.copyId,r);for(;R.status==="PENDING";){if(r?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((v,U)=>{let _=()=>{clearTimeout(V),U(r?.reason)},V=setTimeout(()=>{r?.removeEventListener("abort",_),v()},Math.min(500,Math.max(1,s-Date.now())));r?.addEventListener("abort",_,{once:!0})}),R=await t.getFileAccess(n.copyId,r)}if(R.status!=="READY"||R.origin!=="REVEAL"||R.copyId!==n.copyId||R.allowedUses!==a||!R.recipient||!R.deployment||R.expiresAt!==null&&(!Number.isFinite(Date.parse(R.expiresAt))||Date.parse(R.expiresAt)>s||Date.parse(R.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let m=await mr({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:R});m.fileKey.fill(0),c=m.fileBytes,r?.throwIfAborted(),await n.save({fileName:o.fileName,fileBytes:c}),u=!0}catch(f){if(l&&!u)try{await t.cancelRevealFileAccess(e.session.id,n.copyId)}catch(E){throw new AggregateError([f,E],"protected_asset_export_and_cleanup_failed",{cause:f})}throw f}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as ua}from"@safetech/inheriti-core-sdk/node";function fr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Ye=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),fr(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return fr(new Uint8Array(t))}},Xe=class{now(){return Date.now()}sleep(e,t){return new Promise((r,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var Ae=class extends Error{constructor(t,r=t){super(r);this.code=t;this.name="OperatorAuthError"}},N=class extends Ae{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},y=class extends Ae{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Ze(n){if(n instanceof Ae)return n.code;if(typeof n!="object"||n===null)return;let e=n.code??n.error;return typeof e=="string"?e:void 0}var yr=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,r=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:O(r,"issuer"),authorizationEndpoint:O(r,"authorization_endpoint"),tokenEndpoint:O(r,"token_endpoint"),deviceAuthorizationEndpoint:$(r,"device_authorization_endpoint"),endSessionEndpoint:$(r,"end_session_endpoint"),revocationEndpoint:$(r,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:O(t,"device_code"),userCode:O(t,"user_code"),verificationUri:O(t,"verification_uri"),verificationUriComplete:$(t,"verification_uri_complete"),expiresInSeconds:Ir(t,"expires_in"),intervalSeconds:Pt(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 y(`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,r){let i=await this.businessRequest(e,t,r);return{accessToken:O(i,"accessToken"),refreshToken:O(i,"refreshToken"),accessExpiresAt:O(i,"accessExpiresAt"),sessionExpiresAt:O(i,"sessionExpiresAt"),familyId:O(i,"familyId"),environment:En(i,"environment"),clientId:O(i,"clientId"),providerIssuer:O(i,"providerIssuer"),providerSubject:O(i,"providerSubject")}}async businessRequest(e,t,r,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(r)}),d={};try{d=await o.json()}catch{}if(!o.ok)throw new y(`business_http_${o.status}`);if(d.ok!==!0||!wn(d.result))throw new y("invalid_business_response");return d.result}async token(e,t){let r=await this.form(e,t);return{accessToken:O(r,"access_token"),refreshToken:$(r,"refresh_token"),idToken:$(r,"id_token"),tokenType:O(r,"token_type"),expiresInSeconds:Ir(r,"expires_in"),refreshExpiresInSeconds:Pt(r,"refresh_expires_in"),scope:$(r,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let r=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await r.json()}catch{}if(!r.ok){let s=$(i,"error")??`oauth_http_${r.status}`;throw new y(s,$(i,"error_description")??s)}return i}};function wn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function En(n,e){let t=O(n,e);if(t!=="TEST"&&t!=="LIVE")throw new y("invalid_business_response");return t}function O(n,e){let t=$(n,e);if(!t)throw new y("invalid_oauth_response",`Missing ${e}`);return t}function $(n,e){return typeof n[e]=="string"?n[e]:void 0}function Ir(n,e){let t=Pt(n,e);if(t===void 0)throw new y("invalid_oauth_response",`Missing ${e}`);return t}function Pt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Rn=600*1e3,Je=5,Sn=5,vr=5e3,bn=new WeakMap,An=new WeakMap;async function wr(n,e,t){let r=n.get(e),i,s=new Promise(a=>{i=a});n.set(e,s),r&&await r;try{return await t()}finally{n.get(e)===s&&n.delete(e),i()}}function ee(n,e){return wr(bn,n,e)}var Pr=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new y("business_api_url_required");this.crypto=e.crypto??new Ye,this.clock=e.clock??new Xe}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),r=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+Rn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:r,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",r),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"),r=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!r||r.kind!=="authorization-code")throw new y("authorization_transaction_missing");if(r.expiresAt<=this.clock.now())throw new y("authorization_transaction_expired");let i=new URL(e),s=new URL(r.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new y("redirect_uri_mismatch");if(i.searchParams.get("state")!==r.state)throw new y("state_mismatch");let a=i.searchParams.get("error");if(a)throw new y(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new y("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:r.codeVerifier,redirectUri:r.redirectUri}),l=await this.acceptTokens(c,r.nonce);return await ee(this.options.sessions,()=>this.options.sessions.save(l)),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new y("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),r=Math.max(Je,t.intervalSeconds??Je),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:r,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+r*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),r=await this.options.transactions.load(t);if(!r||r.kind!=="device-code"||r.consumed)throw new y("device_transaction_missing");let i=r,s=await this.getDiscovery(),a=Math.max(Je,i.intervalSeconds??Je),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 ee(this.options.sessions,()=>this.options.sessions.save(c)),await this.options.transactions.remove(t),c}catch(d){let c=Ze(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=Sn,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new y("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 N;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new N;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new N;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 ee(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 y("provider_revoke_timeout"))},vr)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,r;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{r=setTimeout(()=>{t.abort(),s(new y("business_revoke_timeout"))},vr)})])}finally{r&&clearTimeout(r)}}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 N;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new N;let r;try{r=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=Ze(i);if(s==="business_http_409"){let a=await ee(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 N}throw s==="business_http_401"?(await this.clearIfCurrent(t),new N):i}try{let i=this.businessSession(r,t.principal,t);if(i.refreshToken===t.refreshToken)throw new y("refresh_token_rotation_missing");return await ee(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 N;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 ee(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 ee(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(),wr(An,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 N;let t;try{let r=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:r.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(r){let i=Ze(r);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new N):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),r)}try{if(!t.refreshToken)throw new y("refresh_token_rotation_missing");let r=await this.acceptProviderTokens(t,void 0,e);return await ee(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 N;return await this.options.sessions.save(r),r})}catch(r){throw await this.clearIfUnchanged(e),r}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(D(e.issuer)!==D(this.options.configuration.issuer))throw new y("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:r,redirectUri:i}=this.options.configuration;return`${e}|${D(t)}|${r}|${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 r=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,r)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new y("unsupported_token_type");let r=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(r,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new y("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==r.subject||i.sessionId!==r.sessionId)throw new y("token_subject_mismatch")}return r}async acceptProviderTokens(e,t,r){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new N;let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?r?this.isOfflineSession(r):!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:D(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,r=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 r=="object"&&r!==null&&typeof r.issuer=="string"&&typeof r.authorizedParty=="string"&&(r.environment==="TEST"||r.environment==="LIVE")&&(typeof r.audience=="string"||Array.isArray(r.audience)&&r.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&D(t.issuer)===D(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&r.authorizedParty===this.options.configuration.clientId&&r.environment===this.options.configuration.environment&&D(r.issuer)===D(this.options.configuration.issuer)&&(typeof r.audience=="string"?[r.audience]:r.audience).includes(this.options.configuration.audience)}businessSession(e,t,r){if(D(e.providerIssuer)!==D(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||r&&e.familyId!==r.familyId)throw new y("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 y("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,r=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 r=="object"&&r!==null&&typeof r.issuer=="string"&&D(r.issuer)===D(this.options.configuration.issuer)&&typeof r.subject=="string"&&r.subject.length>0&&(typeof r.audience=="string"||Array.isArray(r.audience)&&r.audience.every(i=>typeof i=="string"))&&(typeof r.audience=="string"?[r.audience]:r.audience).includes(this.options.configuration.audience)&&r.authorizedParty===this.options.configuration.clientId&&r.environment===this.options.configuration.environment}assertPrincipal(e,t,r){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(D(e.issuer)!==D(i.issuer))throw new y("issuer_mismatch");if(!s.includes(i.audience))throw new y("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new y("client_mismatch");if(e.environment!==i.environment)throw new y("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new y("required_claim_missing");if(r&&e.nonce!==t)throw new y("nonce_mismatch")}assertIdentity(e,t){let r=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(D(e.issuer)!==D(r.issuer))throw new y("issuer_mismatch");if(!i.includes(r.clientId))throw new y("client_mismatch");if(e.authorizedParty!==r.clientId)throw new y("client_mismatch");if(!e.subject||!e.sessionId)throw new y("required_claim_missing");if(e.nonce!==t)throw new y("nonce_mismatch")}};function D(n){return n.replace(/\/+$/u,"")}var Er=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};import{PassphraseMasterKeySource as Ia,RawMasterKeySource as va,deriveMasterKey as Pa,generateHexSeed as wa,computePassphraseVerifier as Ea}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as Sa}from"@safetech/inheriti-core-sdk/node";function Ws(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",n.environment),e(s,Object.assign({},a,{headers:o}))},r=n.business?void 0:wt({apiUrl:n.apiUrl,getBearerToken:n.getBearerToken,transport:t,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners}),i=new le(n.apiUrl,n.environment,n.getBearerToken,t,n.business?{organizationId:n.organizationId}:void 0);return new ne(r,{keyVault:n.keyVault,state:n.state,api:i,reconstructor:new oe(n.workerUrl),masterKeys:n.masterKeys,masterKey:n.masterKey,applicationId:n.applicationId,organizationId:n.organizationId,assetDecoder:_n})}function Qs(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=wt({apiUrl:new URL(n.apiUrl).origin,getBearerToken:n.getBearerToken,transport:e,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new be(new Ee(n.apiUrl,n.environment,n.getBearerToken,e),t)}function Ys(n){if(!n.payloadStorage||!n.secureSessionStorage||!n.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=n.transport??globalThis.fetch.bind(globalThis),t=new URL(n.apiUrl).origin,r=wt({apiUrl:t,getBearerToken:n.getBearerToken,transport:lr({apiUrl:t,organizationId:n.organizationId,planId:n.planId,editId:n.editId,environment:n.environment,transport:e}),secureSessionStorage:n.secureSessionStorage,payloadStorage:n.payloadStorage,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new Qe(new He(n.apiUrl,n.environment,n.getBearerToken,e),r,n.editRecoveryStore)}export{de as BusinessOrganizationSelectionError,Se as CorePlanMaterialBuilder,ua as DataAssetDefinitionService,z as ElementsApiRequestFailed,ne as ElementsClient,Ie as GuidedCreateRecoveryError,ye as GuidedPlanCreator,we as HttpAutomationRevealApiPort,le as HttpElementsApiPort,yr as HttpOperatorAuthTransport,He as HttpPlanEditPort,Ee as HttpQuickPlanPort,P as InvalidPlanDeclaration,k as InvalidPlanMaterial,xe as MasterKeyRelayCancellationFailed,Ce as MasterKeyRelayExpired,_e as MasterKeyRelayTimedOut,H as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,ge as MemoryKeyVault,he as MemoryStatePort,y as OAuthProtocolError,Pr as OperatorAuthClient,Ae as OperatorAuthError,N as OperatorReauthenticationRequired,Er as OperatorSessionController,it as PLAN_CREATION_SERVER_STAGES,Ia as PassphraseMasterKeySource,Sa as PlanAssetDeclaration,J as PlanRequestFailed,be as QuickPlanCreator,Qe as QuickPlanEditor,va as RawMasterKeySource,G as RelayMasterKeySource,tt as StaticMasterKeyResolver,Xe as SystemOAuthClock,Ye as WebOAuthCrypto,Ea as computePassphraseVerifier,Te as createMasterKeyResolver,vn as createNodeAutomationRevealClient,Ws as createNodeElementsClient,Qs as createNodeQuickPlanCreator,Ys as createNodeQuickPlanEditor,_n as decodeAssetContainer,Pa as deriveMasterKey,Pn as exportProtectedRevealAsset,wa as generateHexSeed,me as masterKeyRefFor,Q as masterKeyRefKey,Ze as oauthErrorCode,rn as selectBusinessOrganization,gt as unwrapDekWithMasterKey,X as validateOperationContext,Y as validatePlanCreationInput,re as validatePlanCreationMaterial};
1
+ import{createNodeSharedConfigurationSdk as wt,decodeAssetContainer as _n}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Rr,generateRSAOAEPKeyPair as Sr}from"@safetech/inheriti-core-sdk/crypto";var _e=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Ce=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},xe=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},G=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:r,privateKey:i}=await Sr();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(r),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(m=>new Promise(v=>setTimeout(v,m))),c=!0,l=!1,u,f=()=>u??=(async()=>{let m=new AbortController,v,U=new Promise((_,V)=>{v=setTimeout(()=>{m.abort(),V(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,m.signal),U])}finally{clearTimeout(v)}})(),E,R=new Promise((m,v)=>{E=()=>{c&&f().catch(()=>{}),v(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",E,{once:!0})});R.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 m=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),R]);if(m.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(m.status==="DELIVERED"&&m.sealedMasterKey){let v=(await Rr(m.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(v))throw new Error("invalid_master_key_material");return v}if(m.status==="EXPIRED")throw new Ce(s.sessionId);await br(d,a,e)}throw new _e(s.sessionId)}catch(m){if(c&&(!l||e?.aborted))try{await f()}catch(v){if(e?.aborted)throw new xe(v)}throw m}finally{E&&e?.removeEventListener("abort",E)}}};async function br(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),n(e).then(r,i).finally(()=>t.removeEventListener("abort",s))})}function Te(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let i=await n.source?.resolve();return i||et(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(Ar(e,n.applicationId)){let i=await n.source?.resolve();return i||et(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return et(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function Ar(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function et(n,e,t,r,i){if((await e()).relayAvailable)return new G({...n.relay,api:_r(n.api,t)}).resolve(r,i)}function _r(n,e){return{startRelaySession:t=>e?n.startMasterKeyRelaySession(t,e):n.startMasterKeyRelaySession(t),readRelaySession:(t,r)=>n.readMasterKeyRelaySession(t,r),cancelRelaySession:(t,r)=>n.cancelMasterKeyRelaySession(t,r)}}function Q(n){return`${n.system}:${n.contextId}`}function me(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var H=class extends Error{constructor(t){super(`master_key_required:${Q(t)}`);this.ref=t;this.name="MasterKeyRequired"}},tt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(Q(e),t),this}async resolve(e){return this.sources.get(Q(e))?.resolve()}};var ge=class{keys=new Map;async store(e,t){let r=Q(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,i)}async load(e){return this.keys.get(Q(e))?.slice()}async remove(e){let t=Q(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var he=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 ke=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},g=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Oe=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var De=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],nt={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","ipSource","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},it=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],P=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},k=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function re(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new k("plan_material_field_unknown");if(rt(n.dataShards,"data_shards_invalid"),rt(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&rt(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new k("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new k("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new k("material_operation_invalid")}function rt(n,e){if(!Array.isArray(n))throw new k(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new k(e);if(t.data!==void 0&&typeof t.data!="string")throw new k(e)}}function Y(n){if(te(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Tr(n.idempotencyKey))throw new P("idempotency_key_invalid");if(!n.name?.trim())throw new P("plan_name_required");if(!n.assets.length)throw new P("assets_required");let e=new Set;for(let t of n.assets){if(te(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 P("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!De.includes(t.type))throw new P("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new P("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 P("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new P("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new P("asset_field_names_invalid");if(Cr(t.matchOrigins),!t.isBinary){let s=nt[t.type];if(!s||i.some(a=>!s.includes(a)))throw new P("asset_field_name_not_canonical")}}if(!n.participants.length)throw new P("participants_required");for(let t of n.participants){if(te(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!St(t.routingEmail))throw new P("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new P("participant_relationships_invalid")}xr(n)}function Cr(n){if(n===void 0)return;if(!n.length)throw new P("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new P("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new P("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof P?r:new P("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new P("asset_match_origins_duplicated")}function xr(n){let e=n.policy;if(e&&te(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new P("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){te(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new P("authentication_mode_invalid")}if(e.moderation){te(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new P("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new P("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new P("approval_mode_invalid")}let t=e.dms;if(!t)return;te(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!St(t.subjectEmail))throw new P("dms_subject_invalid");if(!n.participants.some(s=>Rt(s.routingEmail)===Rt(t.subjectEmail)))throw new P("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(i)||t.countdownDays<0||r<0||r>23||i<0||i>59||t.countdownDays+r+i===0)throw new P("dms_countdown_invalid")}function Tr(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(n)}function St(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function Rt(n){return n.normalize("NFC").trim().toLowerCase()}function te(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new P(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)}},ye=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),Y(e),Me(t.signal);let r=await this.api.startPlanCreation(e);return r.outcome==="COMPLETED"||r.outcome==="CANCELED"?await this.checkpoints.remove(r.operationId):await this.saveCheckpoint(e,r),t.onProgress?.(r.stage),r}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,r,i,s={}){Y(t);let a=await this.checkpoints.load(e);if(!a)throw new Ie("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await bt(t))throw new Ie("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;Me(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:s.signal});Me(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});Me(s.signal),re(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 bt(e),serverStage:t.stage})}},Ie=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function bt(n){let e=JSON.stringify({name:n.name.normalize("NFC").trim(),description:n.description?.normalize("NFC").trim()??null,assets:n.assets.map(r=>({...r,fieldNames:[...r.fieldNames??[]]})).sort((r,i)=>r.clientAssetRef.localeCompare(i.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,i)=>r.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:n.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function Me(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function At(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new ke(r.stage);return n.authorizeRevealAction(e,t)}function kr(n){let e=n?.status;return e===400||e===401||e===403}async function _t(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(s){if(!kr(s))throw s}return n.releaseRevealMaterial(e,t)}var st={reason:500,commitSha:64,workflow:200,pipeline:300,target:200,image:300,version:100};function X(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("operation_context_invalid");let e=n;for(let r of Object.keys(e))if(!Object.hasOwn(st,r))throw new Error("operation_context_invalid");let t={};for(let r of Object.keys(st)){if(!Object.hasOwn(e,r))continue;let i=e[r];if(typeof i!="string"||!i.trim()||i.length>st[r]||/[\x00-\x1f\x7f-\x9f]/.test(i)||r==="commitSha"&&(i.length<7||!/^[0-9a-fA-F]+$/.test(i)))throw new Error("operation_context_invalid");t[r]=i.trim()}return t}function Or(n){return n.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":n.stage==="STARTING"?"STARTING":n.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":n.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":n.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":n.stage==="WAITING_FOR_PARTICIPANTS"?Mr(n):n.stage==="DENIED"?"DENIED":n.stage==="EXPIRED"?"EXPIRED":n.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":n.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":n.stage==="MATERIAL_RELEASED"||n.stage==="RECONSTRUCTED"?"RECONSTRUCTING":n.stage==="ACTIONS_OPEN"?"OPEN":Dr.has(n.stage)?"ENDED":"CONTINUING"}var Dr=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Mr(n){return n.governanceGate==="DMS"?"WAITING_FOR_DMS":n.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":n.governanceGate==="AUTHENTICATION"||n.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var at=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},C=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ke(n,e,t={},r=!1){let i=t.operationContext===void 0?void 0:X(t.operationContext);if(i!==void 0&&!r)throw new Error("operation_context_automation_only");if(t.signal?.aborted)throw S();let s=await n.getPlan(e),a=await n.getActivePlanReveal(e);if(a)throw a.planId!==e||a.mode!==(t.mode??"DIRECT")||a.protectedCopy!==void 0&&a.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Ct(a.id);if(t.signal?.aborted)throw S();let o=()=>n.prepareReveal(e,t.signal,async u=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(u)});if(r||await o(),t.signal?.aborted)throw S();let d=t.idempotencyKey??crypto.randomUUID(),c;try{c=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:d,...t.protectedCopy?{protectedCopy:!0}:{},...i!==void 0?{operationContext:i}:{}})}catch(u){if(u?.code!=="merge_process_already_active")throw u;let f=await n.getActivePlanReveal(e);throw!f||f.planId!==e||f.mode!==(t.mode??"DIRECT")||f.protectedCopy!==void 0&&f.protectedCopy!==(t.protectedCopy??!1)?u:Ct(f.id)}if(c.protectedCopy!==void 0&&c.protectedCopy!==(t.protectedCopy??!1))throw await n.closeReveal(c.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let l;try{if(t.signal?.aborted)throw S();let u=await Ur(n,c,t);if(t.signal?.aborted||(r&&await o(),t.signal?.aborted)||(Z(t,"RELEASING_MATERIAL",u),t.signal?.aborted))throw S();let f=await n.releaseRevealMaterial(u.id,u.materialVersion??"1");if(t.signal?.aborted||(u.mode==="GOVERNED"&&await n.markRevealSharesCollected(u.id),t.signal?.aborted))throw S();let E;try{E=await zr(n,u,Fr(f),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(Z(t,"RECONSTRUCTING",u),t.signal?.aborted))throw S();try{l=await n.reconstructPlanMaterial(E)}catch(m){throw t.signal?.aborted?S():(await n.reportRevealReconstruction(u.id,{status:"FAILED",errorCode:qr(m)}),m)}if(t.signal?.aborted)throw S();let R=await n.reportRevealReconstruction(u.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(Z(t,"OPEN",R),t.signal?.aborted))throw S();return new dt(n,R,s,l,t.signal)}catch(u){throw l?.fill(0),await kt(n,c.id,t.signal?.aborted?"CANCELED":"ERROR"),u}}function Ct(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var Nr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Ur(n,e,t){let r=await j(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw S();if(t.onSession?.(r),t.onProgress?.({phase:Or(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(Nr.has(r.stage))throw new ot(r.stage);await ct(t.pollIntervalMs??1500,t.signal),r=await j(()=>n.getReveal(e.id,t.signal),t.signal)}}var ot=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function Z(n,e,t){n.onProgress?.({phase:e,session:t})}function ct(n,e){return e?.aborted?Promise.reject(S()):new Promise((t,r)=>{let i=setTimeout(a,Math.max(0,n)),s=()=>{clearTimeout(i),r(S())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var dt=class{constructor(e,t,r,i,s){this.client=e;this.session=t;this.plan=r;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 at;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([i])=>{r=i?.value}),r}async consumeFields(e,t){if(e.length===0)throw new C("asset_selector_invalid");if(!this.client.assetDecoder)throw new C("asset_decoder_required");let r=e.map(({selector:s,options:a={}})=>{let o=Kr(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new C("asset_not_found");if(d.isBinary)throw new C("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new C("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 r)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=r.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new C("asset_value_invalid");return{selector:a.selector,value:Lr(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",xt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new C("asset_selector_invalid");if(!this.client.assetDecoder)throw new C("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new C("asset_not_found");if(!r.isBinary)throw new C("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===r.id||o.id===r.code);if(!a||!(a.data instanceof Uint8Array))throw new C("asset_value_invalid");s=a.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",xt(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,r){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...r===void 0?{}:{errorCode:r}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=kt(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 Kr(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new C("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new C("asset_selector_invalid");return{asset:n.asset,field:n.field}}function Lr(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new C("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new C("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?nt[t]:void 0)?.includes(e))return"";throw new C("asset_value_invalid")}return r[e]}function xt(n){if(n instanceof C)return n.code;let e=n?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function qr(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function zr(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await j(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new Ne;let c=await j(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(Tt(c,i.id,e.planId),!c.shares.includes(i.data))throw new B;Z(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await j(()=>r.proDevice.write(c,r.signal),r.signal);if(r.signal?.aborted)throw S();if(!l?.trim())throw new B;if(await n.claimRevealCustodianShare(e.id,c.id,l),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,c.id),r.signal?.aborted))throw S();return{...t,shares:t.shares.filter(u=>u!==i).concat(c.shares.map((u,f)=>({id:`${c.id}:${f}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new B;if(r.signal?.aborted)throw S();return await n.distributeRevealCustodianShare(e.id),Z(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await j(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),Z(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ct(r.pollIntervalMs??1500,r.signal),s=await j(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!r.proDevice)throw new Ne;if(!s.shareId||!s.deviceId)throw new B;Z(r,"CONNECTING_SAFEKEY_PRO",e);let d=await j(()=>r.proDevice.read({shareId:s.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw S();if(Tt(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new B;if(await n.collectRevealCustodianShare(e.id,s.shareId),r.signal?.aborted)throw S();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 B;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),Z(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw S();await n.requestRevealCustodianRelease(e.id);let o=await Gr(n,e,r);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 Tt(n,e,t){if(n?.id!==e||n.planId!==t||!Array.isArray(n.shares)||n.shares.length===0||n.shares.some(r=>typeof r!="string"||!r))throw new B}async function j(n,e){if(e?.aborted)throw S();if(!e)return n();let t,r=new Promise((i,s)=>{t=()=>s(S()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw S();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Gr(n,e,t){let r=Date.parse(e.expiresAt),i=Number.isFinite(r)?Math.min(r,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Ue;let s=await j(()=>n.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Ue;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new B}await ct(t.pollIntervalMs??1500,t.signal)}}var B=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Ne=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ue=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Fr(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function kt(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!Vr(a))throw a}return}let r=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([n.closeReveal(e,t,r.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 Vr(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function S(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var ne=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 ge,this.state=t.state??new he,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Hr(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new g;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new g;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new g;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new g;return this.api.listMemberLogs(e,t)}listOrganizationMembers(e){if(!this.api)throw new g;return this.api.listOrganizationMembers(e)}listOrganizationAuditTrail(e){if(!this.api)throw new g;return this.api.listOrganizationAuditTrail(e)}getOrganizationInsights(e){if(!this.api)throw new g;return this.api.getOrganizationInsights(e)}getPlanResponsibilities(e){if(!this.api)throw new g;return this.api.getPlanResponsibilities(e)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return Y(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new g;return re(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new g;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new g;return new ye(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),r=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",r)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new H({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let i=await this.keyVault.load(e);if(i)return $r(i);let s=await this.masterKeys?.resolve(e,t,r);if(!s)throw new H(e);return await this.keyVault.store(e,Br(s)),s}async prepareReveal(e,t,r){if(!this.api)throw new g;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,r)}}async revealPlan(e,t){await this.prepareReveal(e);let r=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(r)}collectPlanMaterial(e,t){if(!this.api)throw new g;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Oe;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,r){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new H({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=me(e);if(!i)throw new H({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new g;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new g;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new g;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,r){if(!this.api)throw new g;return this.api.createRevealFileAccess(e,t,r)}cancelRevealFileAccess(e,t,r){if(!this.api)throw new g;return this.api.cancelRevealFileAccess(e,t,r)}getActivePlanReveal(e){if(!this.api)throw new g;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new g;return this.api.getReveal(e,t)}openReveal(e,t){return Ke(this,e,t)}async withReveal(e,t,r){let i=await this.openReveal(e,t);try{let s=await r(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new g;return _t(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new g;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new g;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new g;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new g;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new g;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new g;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new g;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new g;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new g;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new g;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new g;return At(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new g;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new g;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new g;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new g;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new g;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new g;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let r=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=r.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||r.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let r=await this.reconstructPlanMaterial(t);if(!this.api)throw new g;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),r}useCase(e,t){if(!this.coreSdk)throw new lt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new H({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},lt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Br(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function $r(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Hr(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return Te({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return Te({...e,organizationId:n.organizationId})}var jr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Wr=["DIRECT","GOVERNED"],Dt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Qr=["ACTIVE","REVOKED"],Yr=["SK_MOBILE"],Xr=["ACTIVE","INACTIVE"],Zr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Mt(n){let e=x(n);return{items:L(e.items).map(Kt),nextCursor:e.nextCursor===null?null:h(e.nextCursor,"nextCursor")}}function Nt(n){let e=x(n);return{total:F(e.total,"total"),items:L(e.items).map(t=>{let r=x(t);if("eventData"in r)throw new Error("invalid_elements_response");return{id:h(r.id,"log.id"),planId:h(r.planId,"log.planId"),tenantId:h(r.tenantId,"log.tenantId"),event:h(r.event,"log.event"),occurredOn:h(r.occurredOn,"log.occurredOn"),status:W(r.status),title:h(r.title,"log.title"),details:L(r.details).map(i=>{let s=x(i);return{label:h(s.label,"log.detail.label"),value:h(s.value,"log.detail.value")}})}})}}function Ut(n){let e=x(n);return{total:F(e.total,"total"),items:L(e.items).map(t=>{let r=x(t);if("eventData"in r)throw new Error("invalid_elements_response");let i=h(r.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:h(r.id,"log.id"),memberId:h(r.memberId,"log.memberId"),source:i,event:h(r.event,"log.event"),occurredOn:h(r.occurredOn,"log.occurredOn"),status:W(r.status)}})}}function Le(n){let e=x(n),t=Kt(e),r=x(e.source),i=h(r.kind,"source.kind");return{...t,assets:L(e.assets).map(s=>{let a=x(s);return{id:h(a.id,"asset.id"),code:W(a.code),type:K(h(a.type,"asset.type"),De),name:h(a.name,"asset.name"),isBinary:en(a.isBinary,"asset.isBinary"),fieldNames:L(a.fieldNames).map(o=>h(o,"asset.fieldNames")),fileName:W(a.fileName),mimeType:W(a.mimeType),size:a.size===void 0||a.size===null?void 0:F(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:L(a.matchOrigins).map(o=>h(o,"asset.matchOrigins"))}}),participants:L(e.participants).map(s=>{let a=x(s);return{id:h(a.id,"participant.id"),displayName:h(a.displayName,"participant.displayName"),relationships:L(a.relationships).map(o=>K(h(o,"relationship"),Dt)),lifecycle:K(h(a.lifecycle,"participant.lifecycle"),Qr)}}),revealPolicy:(()=>{let s=x(e.revealPolicy);return{masterKeyRelease:K(h(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:K(h(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=x(e.dms);return{subjectEmail:h(s.subjectEmail,"dms.subjectEmail"),countdownDays:F(s.countdownDays,"dms.countdownDays"),countdownHours:F(s.countdownHours,"dms.countdownHours"),countdownMinutes:F(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:K(h(r.system,"source.system"),["INHERITI_BUSINESS"]),status:K(h(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ve(n){let e=x(n);return{operationId:h(e.operationId,"operationId"),stage:K(h(e.stage,"stage"),it),outcome:K(h(e.outcome,"outcome"),Zr),planId:W(e.planId),lastErrorCode:W(e.lastErrorCode),participants:e.participants===void 0?void 0:L(e.participants).map(t=>{let r=x(t);return{clientParticipantRef:h(r.clientParticipantRef,"clientParticipantRef"),planParticipantId:h(r.planParticipantId,"planParticipantId"),relationships:L(r.relationships).map(i=>Jr(h(i,"relationship"),Dt))}})}}function Kt(n){let e=x(n),t=x(e.assetSummary),r=x(e.governance),i=x(e.participantSummary);return{id:h(e.id,"id"),name:h(e.name,"name"),description:W(e.description),status:K(h(e.status,"status"),jr),createdAt:h(e.createdAt,"createdAt"),configuredAt:W(e.configuredAt),assetSummary:{count:F(t.count,"assetSummary.count"),types:L(t.types).map(s=>K(h(s,"assetType"),De)),names:Ot(t.names).map(s=>h(s,"assetSummary.names"))},governance:{mode:K(h(r.mode,"governance.mode"),Wr),minimumApprovals:F(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:F(i.owners,"owners"),mergers:F(i.mergers,"mergers"),moderators:F(i.moderators,"moderators")},authentication:Ot(e.authentication).map(s=>{let a=x(s);return{id:K(h(a.id,"authentication.id"),Yr),status:K(h(a.status,"authentication.status"),Xr)}})}}function K(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function Jr(n,e){if(!e.includes(n))throw new Error("invalid_elements_response");return n}function x(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function Ot(n){return n==null?[]:L(n)}function L(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function h(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function W(n){return n==null?void 0:h(n,"optional")}function F(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function en(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function q(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function ie(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function b(n){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function pt(n){return n==null?void 0:b(n)}function T(n){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function tn(n){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function Lt(n){let e=q(n);return{total:T(e.total),items:ie(e.items).map(t=>{let r=q(t);return{id:b(r.id),displayName:b(r.displayName),role:b(r.role),status:b(r.status)}})}}function qt(n){let e=q(n);return{total:T(e.total),shownCount:T(e.shownCount),totalCount:T(e.totalCount),nextCursor:e.nextCursor==null?null:b(e.nextCursor),hasMore:tn(e.hasMore),items:ie(e.items).map(t=>{let r=q(t);if("eventData"in r)throw new Error("invalid_elements_response");return{id:b(r.id),occurredOn:b(r.occurredOn),actorName:b(r.actorName),actorRole:b(r.actorRole),category:b(r.category),action:b(r.action),subject:b(r.subject),status:b(r.status),sourceEvent:b(r.sourceEvent),planId:pt(r.planId),planName:pt(r.planName),responsibleMemberName:pt(r.responsibleMemberName)}})}}function zt(n){let e=q(n),t=q(e.stats),r=q(e.planAccessResults);return{stats:{totalPlans:T(t.totalPlans),plansCreatedThisMonth:T(t.plansCreatedThisMonth),activeMembers:T(t.activeMembers),totalSeats:t.totalSeats==null?null:T(t.totalSeats),accessRequests30d:T(t.accessRequests30d),accessRequestsPrevious30d:T(t.accessRequestsPrevious30d),pendingApprovals:T(t.pendingApprovals)},plansOverTime:ie(e.plansOverTime).map(i=>{let s=q(i);return{month:b(s.month),count:T(s.count)}}),planTypes:ie(e.planTypes).map(i=>{let s=q(i);return{type:b(s.type),count:T(s.count)}}),accessModerationActivity:ie(e.accessModerationActivity).map(i=>{let s=q(i);return{week:b(s.week),requests:T(s.requests),approvals:T(s.approvals)}}),planAccessResults:{success:T(r.success),aborted:T(r.aborted),expired:T(r.expired)}}}function Gt(n){let e=q(n);return{planId:b(e.planId),participants:ie(e.participants).map(t=>{let r=q(t);return{id:b(r.id),displayName:b(r.displayName),relationships:ie(r.relationships).map(i=>b(i)),lifecycle:b(r.lifecycle)}})}}function qe(n,e){if(Object.keys(n).some(t=>!e.includes(t)))throw new Error("organization_query_field_unknown")}var de=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Ft(n){if(!n||typeof n!="object"||!("items"in n)||!Array.isArray(n.items)||!n.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return n.items.map(({id:e,name:t})=>({id:e,name:t}))}function rn(n,e){if(!e){if(n.length===0)throw new de("organization_required");if(n.length>1)throw new de("organization_selection_required");return n[0].id}if(!n.some(({id:t})=>t===e))throw new de("organization_access_denied");return e}function nn(n){let e=w(n);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:I(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:I(e.participantRevision,1),createdAt:M(e.createdAt),...Vt(e)}}function Vt(n){if(n.recipientStatuses===void 0)return{};if(!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:n.recipientStatuses.map(e=>{let t=w(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:M(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(r=>{let i=w(r);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:I(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:M(i.revealedAt)}:{}}})}:{}}})}}function Bt(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(nn),total:I(e.total,0),limit:I(e.limit,1),offset:I(e.offset,0),unreadCount:I(e.unreadCount,0),readThroughSequence:I(e.readThroughSequence,0)}}function $t(n){let e=w(n);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:I(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:I(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:I(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let r=w(t);return{unitId:p(r.unitId),position:I(r.position,0),commitment:p(r.commitment),status:p(r.status)}})}}function ut(n){let e=w(n);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:I(e.sequence,1),status:e.status}}function Ht(n){let e=w(n);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:I(e.participantRevision,1),recipients:e.recipients.map(mt)}}function jt(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=w(t);return{parentId:p(r.parentId),sequence:I(r.sequence,1),senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),participantRevision:I(r.participantRevision,1),createdAt:M(r.createdAt),...Vt(r)}}),total:I(e.total,0),limit:I(e.limit,1),offset:I(e.offset,0),unreadCount:I(e.unreadCount,0),readThroughSequence:I(e.readThroughSequence,0)}}function Wt(n){return{readThroughSequence:I(w(n).readThroughSequence,0)}}function Qt(n){return{clearedThroughSequence:I(w(n).clearedThroughSequence,0)}}function Yt(n){let e=w(n);return{parentId:p(e.parentId),sequence:I(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:I(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function w(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_inbox_response");return n}function p(n){if(typeof n!="string"||!n)throw new Error("invalid_inbox_response");return n}function M(n){let e=p(n);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function I(n,e){if(!Number.isSafeInteger(n)||n<e)throw new Error("invalid_inbox_response");return n}function mt(n){let e=w(n);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:I(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function ce(n){let e=w(n);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:M(e.createdAt),updatedAt:M(e.updatedAt)}}function ze(n){let e=w(n);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:M(e.createdAt),updatedAt:M(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let r=w(e.latestMessage);if(r.contentKind!=="TEXT"&&r.contentKind!=="FILE"&&r.contentKind!=="NORMAL"&&r.contentKind!=="MIXED"&&r.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:r.contentKind,senderMemberId:p(r.senderMemberId),createdAt:M(r.createdAt)}}return t}function Xt(n){let e=w(n);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(ze),total:e.total,limit:e.limit,offset:e.offset}}function Zt(n){let e=w(n);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=mt(t);return{memberId:r.memberId,name:p(w(t).name),deviceId:r.deviceId,deviceVersion:r.deviceVersion,encryptionPublicKey:r.encryptionPublicKey,encryptionKeyFingerprint:r.encryptionKeyFingerprint,signingPublicKey:r.signingPublicKey,signingKeyFingerprint:r.signingKeyFingerprint}}),limit:I(e.limit,1),offset:I(e.offset,0),nextOffset:e.nextOffset===null?null:I(e.nextOffset,0)}}function Jt(n){let e=w(n);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=w(t);if(typeof r.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(r.memberId),name:p(r.name),ready:r.ready,...r.profilePicture===void 0?{}:{profilePicture:{url:p(w(r.profilePicture).url)}}}}),limit:I(e.limit,1),offset:I(e.offset,0),nextOffset:e.nextOffset===null?null:I(e.nextOffset,0)}}function er(n){let e=w(n);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),messageId:p(e.messageId),participantRevision:I(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(mt),shareLayers:e.shareLayers.map(t=>{let r=w(t),i=p(r.id),s=p(r.dataShareId),a=p(r.keyShareId),o=p(r.type);if(o==="INHERITI_HSM")throw new Error("invalid_inbox_response");return o==="INHERITI_CHAIN"?{id:i,type:o,contractAddress:p(r.contractAddress),dataShareId:s,keyShareId:a}:{id:i,type:o,dataShareId:s,keyShareId:a}})}}function Ge(n){let e=w(n);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:p(e.messageId),status:e.status}}function tr(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=w(t);if(r.status!=="PREPARING"&&r.status!=="AVAILABLE"&&r.status!=="FAILED"&&r.status!=="DELETING")throw new Error("invalid_inbox_response");if(r.contentKind!==void 0&&r.contentKind!=="TEXT"&&r.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(r.recipientStatus!==void 0&&r.recipientStatus!=="UNREAD"&&r.recipientStatus!=="LEASED"&&r.recipientStatus!=="CONSUMED"&&r.recipientStatus!=="EXPIRED"&&r.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(r.recipientStatuses!==void 0&&!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:p(r.id),status:r.status,senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),createdAt:M(r.createdAt),updatedAt:M(r.updatedAt),expiresAt:M(r.expiresAt)};return r.contentKind&&(i.contentKind=r.contentKind),r.recipientStatus&&(i.recipientStatus=r.recipientStatus),Array.isArray(r.recipientStatuses)&&(i.recipientStatuses=r.recipientStatuses.map(s=>{let a=w(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:p(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:M(a.consumedAt)}:{}}})),i}),total:I(e.total,0),limit:I(e.limit,1),offset:I(e.offset,0)}}function rr(n){let e=w(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:M(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:I(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=w(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:I(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId),ciphertext:p(r.ciphertext)}})}}function nr(n){let e=w(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:M(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:I(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=w(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:I(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId)}})}}function Fe(n){return typeof n=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(n)&&Number.isFinite(Date.parse(n))}function se(n){return typeof n.error=="string"?/^[a-z][a-z0-9_]*$/.test(n.error)?n.error:typeof n.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(n.validationErrors)?n.validationErrors:n.error||void 0:n.error?.code??n.name??n.message}function ae(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var z=class extends Error{constructor(t,r,i,s){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},le=class{constructor(e,t,r,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=r;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,r,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":r},i)}confirmFileAccessDelivery(e,t,r){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":r})}createInboxFileAccess(e,t,r,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",r,void 0,void 0,i)}createRevealFileAccess(e,t,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,r)}cancelRevealFileAccess(e,t,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",r)}cancelInboxFileAccess(e,t,r,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(r)}`,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 r=t;if(typeof r.publicKey!="string"||!r.publicKey||typeof r.fingerprint!="string"||!r.fingerprint||r.status!=="ACTIVE"&&r.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:r.publicKey,fingerprint:r.fingerprint,status:r.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:ce(t)}async getMemberInboxDevice(e,t){let r=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return r===null?null:ce(r)}async registerInboxDevice(e){return ce(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return ce(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return ce(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return ze(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return ze(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Xt(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Zt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Jt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return er(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Ht(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let r={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Ge(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",r))}async publishNormalInboxMessage(e,t){return ut(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return ut(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},r){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return Bt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,r))}async openInboxParent(e,t,r,i){let s=new URLSearchParams({deviceId:r});return $t(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 Qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},r){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,r))}async openNormalInboxMessage(e,t,r,i){let s=new URLSearchParams({deviceId:r});return Yt(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,r){return Wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:r}))}async stageInboxFile(e,t,r){return Ge(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,r))}async uploadInboxFileShare(e,t,r,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(r)}`,o=await this.requestBinary(a,"PUT",i,s),d=await Ve(o,s);if(!d.ok||d.result?.shareId!==r||d.result.status!=="STORED")throw new z(o.status,se(d),ae(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,r){return Ge(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,r))}async openInboxFile(e,t,r,i){return nr(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:r},void 0,void 0,i))}async downloadInboxFileShare(e,t,r,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}?${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 u=c.body.getReader(),f=[],E=0;try{for(;;){a?.throwIfAborted();let v=await u.read();if(v.done)break;if(E+=v.value.length,E>14*1024*1024)throw new Error("invalid_inbox_share_size");f.push(v.value)}}catch(v){throw await u.cancel().catch(()=>{}),v}let R=new Uint8Array(E),m=0;for(let v of f)R.set(v,m),m+=v.length;return R}async listInboxMessages(e,t={},r){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return tr(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,r))}async openInboxMessage(e,t,r){return rr(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:r}))}async ackInboxMessage(e,t,r,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:r,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,r,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:r,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Ft)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let r=t.size?`?${t}`:"";return Mt(await this.request(`v1/plans${r}`,"GET"))}async getPlan(e){return Le(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let r=new URLSearchParams;t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return Nt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let r=new URLSearchParams;t.source&&r.set("source",t.source),t.from&&r.set("from",t.from),t.to&&r.set("to",t.to),t.q&&r.set("q",t.q),t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return Ut(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listOrganizationMembers(e={}){if(this.requireOrganizationSelection(),qe(e,["limit","offset"]),e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>100))throw new Error("organization_query_limit_invalid");if(e.offset!==void 0&&(!Number.isSafeInteger(e.offset)||e.offset<0))throw new Error("organization_query_offset_invalid");let t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),Lt(await this.request(`v1/organization/members${t.size?`?${t}`:""}`,"GET"))}async listOrganizationAuditTrail(e){if(this.requireOrganizationSelection(),qe(e,["from","to","limit","cursor","category","memberId","responsibleMemberId"]),!Fe(e.from)||!Fe(e.to)||Date.parse(e.from)>Date.parse(e.to))throw new Error("organization_query_date_invalid");if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>500))throw new Error("organization_query_limit_invalid");if(e.cursor!==void 0&&!/^[1-9]\d*$/.test(e.cursor))throw new Error("organization_query_cursor_invalid");let t=new URLSearchParams({from:e.from,to:e.to});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor!==void 0&&t.set("cursor",e.cursor),e.category!==void 0&&t.set("category",e.category),e.memberId!==void 0&&t.set("memberId",e.memberId),e.responsibleMemberId!==void 0&&t.set("responsibleMemberId",e.responsibleMemberId),qt(await this.request(`v1/organization/audit-trail?${t}`,"GET"))}async getOrganizationInsights(e={}){if(this.requireOrganizationSelection(),qe(e,["from","to"]),e.from===void 0!=(e.to===void 0)||e.from!==void 0&&(!Fe(e.from)||!Fe(e.to)||Date.parse(e.from)>Date.parse(e.to)))throw new Error("organization_query_date_invalid");let t=new URLSearchParams;return e.from!==void 0&&e.to!==void 0&&(t.set("from",e.from),t.set("to",e.to)),zt(await this.request(`v1/organization/insights${t.size?`?${t}`:""}`,"GET"))}async getPlanResponsibilities(e){if(this.requireOrganizationSelection(),!e)throw new Error("plan_id_required");return Gt(await this.request(`v1/plans/${encodeURIComponent(e)}/responsibilities`,"GET"))}async startPlanCreation(e){Y(e);let{idempotencyKey:t,...r}=e;return ve(await this.request("v1/plan-creations","POST",r,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ve(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return re(t),ve(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ve(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){if(t.operationContext!==void 0)throw new Error("operation_context_automation_only");let{idempotencyKey:r,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":r})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:r})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,r)}abortPlanAccess(e,t){let r=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${r}?revealId=${encodeURIComponent(t)}`:r,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;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,r,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[E,R]of Object.entries(s??{}))d.set(E,R);r&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:r?JSON.stringify(r):void 0};a&&(l.signal=a);let u=await this.transport(new URL(e,c),l);a?.throwIfAborted();let f=await Ve(u,a);if(a?.throwIfAborted(),!u.ok)throw new z(u.status,se(f),ae(f),u.headers.get("x-request-id")??void 0);if(!f.ok||f.result===void 0)throw new z(u.status,se(f),ae(f),u.headers.get("x-request-id")??void 0);return f.result}async requestBinary(e,t,r,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),r&&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:r?Buffer.from(r):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await Ve(d,i);throw new z(d.status,se(c),ae(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,r,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[u,f]of Object.entries(r??{}))o.set(u,f);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 Ve(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new z(c.status,se(l),ae(l),c.headers.get("x-request-id")??void 0)}requireOrganizationSelection(){if(!this.business?.organizationId)throw new z(400,"organization_selection_required")}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new z(400,"organization_selection_required")}};async function Ve(n,e){try{return await n.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as un}from"@safetech/inheriti-core-sdk/node";async function gt(n,e){if(!e)throw new Error("master_key_required");let t=sn(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=an(n),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,a);return on(new Uint8Array(o))}function sn(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function an(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function on(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Pe=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await ir("plan_key_unwrap_failed",()=>gt(e.planKey,t)),i=await crypto.subtle.importKey("raw",ht(r),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await ir("plan_share_decryption_failed",()=>pn(o.data,i));ln(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 Be("plan_share_reconstruction_failed",cn(o))}}},Be=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},dn=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 cn(n){let e=n instanceof Error?n.message:void 0;if(e)return dn.has(e)?e:void 0}async function ir(n,e){try{return await e()}catch{throw new Be(n)}}function ln(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function pn(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=ht(n.slice(0,t)),i=ht(n.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(s)}function ht(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i+=1)r[i]=e.charCodeAt(i);return t}var oe=class extends Pe{constructor(e){super(()=>un(e))}};var we=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){let r=t.operationContext===void 0?void 0:X(t.operationContext);return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey,...r===void 0?{}:{operationContext:r}},!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 Le(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,r){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,r)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let r=this.firstRelayStates.get(e);return r?(this.firstRelayStates.delete(e),Promise.resolve(r)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,r,i=!0,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});r!==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:r===void 0?void 0:JSON.stringify(r),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 z(c.status,l&&se(l),l&&ae(l));return l?.result}};var A={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 J=class extends Error{constructor(t,r){super(r??`plan_request_failed_${t}`);this.status=t;this.code=r}},Ee=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,r,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:r,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:r.validatorShares,encryptedKey:r.encryptedKey})}preflight(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",sr(r))}configure(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",sr(r))}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(A.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(A.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(A.relayFailed);return r}async request(e,t,r,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(A.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:r,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 J(c.status,l.error);return l.result}};function sr(n){return{protectionProtocol:n.protectionProtocol,operation:"FINALIZE",dataShards:n.dataShards,backupShards:n.backupShards,encryptedKey:n.encryptedKey,assetsMetadata:n.assetsMetadata,custodianPair:n.custodianShard}}var Se=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),gn(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,r=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:r,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(Re(e.signal),!i.custodianPair)throw new k("custodian_share_required");let s=ft(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(ft(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(ft(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return Re(e.signal),{protectionProtocol:i.protocol,validatorShares:yt(a.encryptedShares),dataShards:yt(o.encryptedShares),backupShards:yt(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:mn(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let r=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:It(r.encryptedShares[0]),dataShard:It(r.encryptedShares[1])}}};function ft(n){return n.map(e=>({id:crypto.randomUUID(),data:e}))}function yt(n){return n.map(It)}function It(n){return{id:n.id,data:n.encryptedData}}function mn(n,e){let t={};for(let r of n){let i=e.assets.find(s=>s.clientAssetRef===r.id);if(!i)throw new k("plan_secrets_declaration_mismatch");t[r.id]={type:r.type,meta:{name:r.meta.name,notes:r.meta.notes,...r.meta.isMedia===void 0?{}:{isMedia:r.meta.isMedia},...r.meta.mimeType===void 0?{}:{mimeType:r.meta.mimeType},...r.meta.fileName===void 0?{}:{fileName:r.meta.fileName},...r.meta.code===void 0?{}:{code:r.meta.code},...r.meta.matchOrigins===void 0?{}:{matchOrigins:[...r.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function gn(n,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new k("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new k("share_threshold_invalid");if(e.assets.length!==n.assets.length)throw new k("plan_secrets_declaration_mismatch");let t=new Map(n.assets.map(r=>[r.clientAssetRef,r]));for(let r of e.assets){let i=t.get(r.id);if(!i||i.type!==r.type)throw new k("plan_secrets_declaration_mismatch")}}function Re(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function ar(n,e,t,r,i,s,a){let o=r.mergeThreshold-(r.withCustodian?1:0);if(typeof r.withCustodian!="boolean"||!Number.isInteger(r.mergeThreshold)||o<1||o>n.totalShares)throw new Error(A.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:r.withCustodian?"FORCE":"BYPASS"};let l=n.masterKeySource??new G({api:{startRelaySession:E=>i.startRelaySession(n.organizationId,t.masterKeyAcquisition,E),readRelaySession:E=>i.readRelaySession(n.organizationId,E)}}),u=new Se(s,l);a?.("encrypting");let f=await u.encrypt({planId:n.planId,declaration:c,secrets:{assets:d,totalShares:n.totalShares,threshold:o}});return a?.("generating_shares"),u.generateShares({planId:n.planId,declaration:c,encrypted:f})}import{PlanAssetDeclaration as hn}from"@safetech/inheriti-core-sdk/node";function or(n){let e=vt({planId:n.planId,title:n.title,assets:[n.asset]});return{asset:e.assets[0],plan:e.plan}}function vt(n){if(!n.assets.length)throw new P("assets_required");let e=n.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 P("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new P("binary_asset_metadata_invalid");return o}),t=hn.create(n.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),r=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,n.assets[a].secret]))),i={idempotencyKey:n.planId,name:n.title,assets:r.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:r,plan:i}}async function cr(n){let e=await Promise.all(n.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([r],[i])=>r.localeCompare(i)).map(async([r,i])=>[r,i instanceof Blob?await dr(new Uint8Array(await i.arrayBuffer())):i]))})));return dr(new TextEncoder().encode(JSON.stringify({organizationId:n.organizationId,planId:n.planId,title:n.title,description:n.description??null,audience:n.audience??null,totalShares:n.totalShares,assets:e})))}async function dr(n){let e=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var be=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(A.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(A.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(A.invalidShares);let r=await cr(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==r)throw new Error(A.reconciliationRequired);return i.promise}let s=this.performCreate(e,r,t);this.flights.set(e.planId,{fingerprint:r,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,r){let i=vt({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(A.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if($e(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(A.reconciliationRequired);if(!a&&s)throw new Error(A.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(A.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(A.invalidMasterKeyContext);if(!a){r?.("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 ar(e,i,o,a,this.port,this.coreSdk,r);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),r?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),r?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),r?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!$e(await this.statusOrMissing(e.organizationId,e.planId)))throw l}r?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return $e(c)&&this.material.delete(e.planId),{planId:e.planId,status:$e(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(A.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(r){if(r instanceof J&&r.status===404)return;throw r}}};function $e(n){return n?.status==="PROTECTED"||n?.status==="CONFIGURED"}var He=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}start(e,t,r,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:r},i)}async listEligibleCandidates(e,t,r){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),r&&i.set("namePrefix",r);let 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 r=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(r))throw new Error("invalid_plan_edit_context");return r}async moderatorNames(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!r||typeof r!="object")throw new Error("invalid_plan_edit_participants");let i=r;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let 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,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(A.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(A.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(A.relayFailed);return r}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(r))}commit(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(r))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,r,i,s){let a=await this.getBearerToken();if(!a)throw new Error(A.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:r,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),u={};try{u=await l.json()}catch{}if(!l.ok||u.ok!==!0){let f=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new J(l.status,f||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(r=>!!r&&typeof r.id=="string"&&!!r.id&&typeof r.name=="string"&&r.status==="PROTECTED"&&typeof r.createdAt=="string"&&!!r.assetSummary&&Number.isSafeInteger(r.assetSummary.count)&&r.assetSummary.count>=0&&Array.isArray(r.assetSummary.types)&&r.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(r.assetSummary.names)&&r.assetSummary.names.every(i=>typeof i=="string")&&!!r.governance&&["DIRECT","GOVERNED"].includes(r.governance.mode)&&Number.isSafeInteger(r.governance.minimumApprovals)&&r.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var je=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.recoveryStore=r}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let r=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),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(u=>u.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&r===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:s,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),r=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(r>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return r}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new G({api:{startRelaySession:r=>this.port.startRelaySession(e.organizationId,t,r),readRelaySession:r=>this.port.readRelaySession(e.organizationId,r)}}).resolve()}async revealAssets(e,t,r,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=m=>{m!==o&&(o=m,i?.(m))},c=m=>{if(m.processId!==e.editId||m.planId&&m.planId!==e.planId)return;switch(m.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let v=this.approvalError(m);if(v?.startsWith("edit_authentication_")&&d("pending_auth"),v?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!m.moderatorParticipants||m.requiredModeratorApprovals===void 0||!m.approvalProcess)return;let U=m.moderatorParticipants.map(_=>_.memberId??_.userId);U.some(_=>typeof _!="string"||!_)||new Set(U).size!==U.length||i?.(o,{requiredApprovals:m.requiredModeratorApprovals,approvedModerators:m.approvalProcess.approvedModerators,moderators:m.moderatorParticipants.map((_,V)=>{let pe=U[V],Et=_.flows.filter(ue=>ue.status==="PENDING"&&ue.expiresAt&&Number.isFinite(ue.expiresAt.getTime())).map(ue=>ue.expiresAt.getTime());return{id:pe,displayName:a.get(pe)||"Moderator",status:_.status,expiresAt:Et.length?new Date(Math.min(...Et)).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 u=await s.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");c(u),this.assertApprovalOutcome(e.planId,u);let f=u?.status;if(f!=="READY_TO_REVEAL"&&f!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let E=null,R={onRevealed:m=>{E=m},onViewUpdate:c,onRevealStepUpdate:(m,v)=>{if(v==="IN_PROCESS")switch(m){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(r&&(R.onCustodianShareRequired=async(m,v)=>{switch(v.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let U=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),U==="SK_MOBILE")return s.distributeCustodianShareViaMobile(v.planId);if(U!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let _=e.proDevice;try{this.assertNotAborted(e.signal);let V=await s.getCustodianShareData(m);this.assertShare(V,v.planId),d("connecting_safekey_pro");let{deviceId:pe}=await _.write(V,e.signal);if(this.assertNotAborted(e.signal),!pe?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(v.planId,V.id,pe,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(m,V.id);return}finally{_.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 U=e.proDevice;try{if(this.assertNotAborted(e.signal),!v.shareId||!v.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let _=await U.read({shareId:v.shareId,planId:v.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(_,v.planId,v.shareId),_.deviceId!==v.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:_.shares}}finally{U.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),f==="REVEALED"?await s.resumeReveal(e.editId,R,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},R,t),this.assertNotAborted(e.signal),!E)throw new Error("edit_assets_unavailable");return E}assertApprovalOutcome(e,t){let r=this.approvalError(t);if(r)throw this.clearRevealedAssets(e),new Error(r)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,r){if(!e||!e.id||e.id!==(r??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var fn=n=>JSON.stringify(n??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([r],[i])=>r<i?-1:r>i?1:0))),We=class{constructor(e,t,r,i){this.port=e;this.coreSdk=t;this.recoveryStore=r;this.clearRevealedAssets=i}async saveAssets(e,t,r,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,r,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 r=await this.configurationRepository().findByPlanId(e.planId),i=r?.editDistribution??r?.preparedDistribution;if(!t&&(!i||r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let 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(!r?.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 r=await this.configurationRepository().findByPlanId(e.planId);if(r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let r=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await r.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await r.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,r,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:r,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,r,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,r))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,r))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let r=await this.port.commitStatus(e.organizationId,e.editId);if(r.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(r.status)||r.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(fn(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(r.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(r.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var Qe=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.assetAccess=new je(e,t,r),this.reconfiguration=new We(e,t,r,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,r,i){return this.port.start(e,t,r,i)}async listAssets(e,t){let{assets:r}=await this.assetAccess.loadAssets(e,t);return r.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,r){let{assets:i}=await this.assetAccess.loadAssets(e,r),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:r,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,u)=>u===a?d:l);return this.reconfiguration.saveAssets(e,c,r.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:r,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=or({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),r.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 lr({apiUrl:n,organizationId:e,planId:t,editId:r,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),c=new URL(n.endsWith("/")?n:`${n}/`);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 u=yn(l,d.searchParams,t,r),f=new Headers(o?.headers);f.set("x-organization-id",e),f.set("x-elements-environment",i);let E=c.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return s(new URL(E,c),Object.assign({},o,{headers:f}))}}function yn(n,e,t,r){if(n==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(n);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]!==r||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(n);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(r)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(r)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as In}from"@safetech/inheriti-core-sdk/node";function pr(n){return{async openReveal(e,t={}){let r=t.operationContext===void 0?void 0:X(t.operationContext);if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let i=await n.api.planKeyReference(e),s=me(i);if(!i.masterKeyWrapped||!s||i.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new G({api:{startRelaySession:d=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,d),readRelaySession:(d,c)=>n.api.readMasterKeyRelaySession(d,c),cancelRelaySession:(d,c)=>n.api.cancelMasterKeyRelaySession(d,c)}}),o=new ne(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(d,c,l)=>{if(d.system!==s.system||d.contextId!==s.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(c,l)}}});return Ke(o,e,{...t,...r===void 0?{}:{operationContext:r}},!0)}}}function vn(n){let e=new we(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{supportsOperationContext:!0,...pr({api:e,reconstructor:new oe(n.workerUrl),assetDecoder:In}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as ur,sealInheritiFile as mr,readInheritiFileHeader as hs,openInheritiFile as fs,InheritiFileInvalid as ys,MAX_INHERITI_FILE_BYTES as gr}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as hr,openInheritiFileKey as Ps}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Pn(n){let{reveal:e,api:t,signal:r}=n;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(r);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=n.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(n.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>gr-1024*1024)throw new Error("unsupported_protected_asset");let d=ur(),c,l=!1,u=!1;try{r?.throwIfAborted();let f=await hr(d,i.publicKey);l=!0;let E=await t.createRevealFileAccess(e.session.id,{copyId:n.copyId,envelopeId:n.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:f,openLimit:a},r);if(E.copyId!==n.copyId||E.status!=="PENDING")throw new Error("file_access_create_invalid");let R=await t.getFileAccess(n.copyId,r);for(;R.status==="PENDING";){if(r?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((v,U)=>{let _=()=>{clearTimeout(V),U(r?.reason)},V=setTimeout(()=>{r?.removeEventListener("abort",_),v()},Math.min(500,Math.max(1,s-Date.now())));r?.addEventListener("abort",_,{once:!0})}),R=await t.getFileAccess(n.copyId,r)}if(R.status!=="READY"||R.origin!=="REVEAL"||R.copyId!==n.copyId||R.allowedUses!==a||!R.recipient||!R.deployment||R.expiresAt!==null&&(!Number.isFinite(Date.parse(R.expiresAt))||Date.parse(R.expiresAt)>s||Date.parse(R.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let m=await mr({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:R});m.fileKey.fill(0),c=m.fileBytes,r?.throwIfAborted(),await n.save({fileName:o.fileName,fileBytes:c}),u=!0}catch(f){if(l&&!u)try{await t.cancelRevealFileAccess(e.session.id,n.copyId)}catch(E){throw new AggregateError([f,E],"protected_asset_export_and_cleanup_failed",{cause:f})}throw f}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as ua}from"@safetech/inheriti-core-sdk/node";function fr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Ye=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),fr(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return fr(new Uint8Array(t))}},Xe=class{now(){return Date.now()}sleep(e,t){return new Promise((r,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var Ae=class extends Error{constructor(t,r=t){super(r);this.code=t;this.name="OperatorAuthError"}},N=class extends Ae{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},y=class extends Ae{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Ze(n){if(n instanceof Ae)return n.code;if(typeof n!="object"||n===null)return;let e=n.code??n.error;return typeof e=="string"?e:void 0}var yr=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,r=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:O(r,"issuer"),authorizationEndpoint:O(r,"authorization_endpoint"),tokenEndpoint:O(r,"token_endpoint"),deviceAuthorizationEndpoint:$(r,"device_authorization_endpoint"),endSessionEndpoint:$(r,"end_session_endpoint"),revocationEndpoint:$(r,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:O(t,"device_code"),userCode:O(t,"user_code"),verificationUri:O(t,"verification_uri"),verificationUriComplete:$(t,"verification_uri_complete"),expiresInSeconds:Ir(t,"expires_in"),intervalSeconds:Pt(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 y(`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,r){let i=await this.businessRequest(e,t,r);return{accessToken:O(i,"accessToken"),refreshToken:O(i,"refreshToken"),accessExpiresAt:O(i,"accessExpiresAt"),sessionExpiresAt:O(i,"sessionExpiresAt"),familyId:O(i,"familyId"),environment:En(i,"environment"),clientId:O(i,"clientId"),providerIssuer:O(i,"providerIssuer"),providerSubject:O(i,"providerSubject")}}async businessRequest(e,t,r,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(r)}),d={};try{d=await o.json()}catch{}if(!o.ok)throw new y(`business_http_${o.status}`);if(d.ok!==!0||!wn(d.result))throw new y("invalid_business_response");return d.result}async token(e,t){let r=await this.form(e,t);return{accessToken:O(r,"access_token"),refreshToken:$(r,"refresh_token"),idToken:$(r,"id_token"),tokenType:O(r,"token_type"),expiresInSeconds:Ir(r,"expires_in"),refreshExpiresInSeconds:Pt(r,"refresh_expires_in"),scope:$(r,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let r=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await r.json()}catch{}if(!r.ok){let s=$(i,"error")??`oauth_http_${r.status}`;throw new y(s,$(i,"error_description")??s)}return i}};function wn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function En(n,e){let t=O(n,e);if(t!=="TEST"&&t!=="LIVE")throw new y("invalid_business_response");return t}function O(n,e){let t=$(n,e);if(!t)throw new y("invalid_oauth_response",`Missing ${e}`);return t}function $(n,e){return typeof n[e]=="string"?n[e]:void 0}function Ir(n,e){let t=Pt(n,e);if(t===void 0)throw new y("invalid_oauth_response",`Missing ${e}`);return t}function Pt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Rn=600*1e3,Je=5,Sn=5,vr=5e3,bn=new WeakMap,An=new WeakMap;async function wr(n,e,t){let r=n.get(e),i,s=new Promise(a=>{i=a});n.set(e,s),r&&await r;try{return await t()}finally{n.get(e)===s&&n.delete(e),i()}}function ee(n,e){return wr(bn,n,e)}var Pr=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new y("business_api_url_required");this.crypto=e.crypto??new Ye,this.clock=e.clock??new Xe}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),r=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+Rn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:r,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",r),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"),r=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!r||r.kind!=="authorization-code")throw new y("authorization_transaction_missing");if(r.expiresAt<=this.clock.now())throw new y("authorization_transaction_expired");let i=new URL(e),s=new URL(r.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new y("redirect_uri_mismatch");if(i.searchParams.get("state")!==r.state)throw new y("state_mismatch");let a=i.searchParams.get("error");if(a)throw new y(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new y("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:r.codeVerifier,redirectUri:r.redirectUri}),l=await this.acceptTokens(c,r.nonce);return await ee(this.options.sessions,()=>this.options.sessions.save(l)),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new y("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),r=Math.max(Je,t.intervalSeconds??Je),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:r,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+r*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),r=await this.options.transactions.load(t);if(!r||r.kind!=="device-code"||r.consumed)throw new y("device_transaction_missing");let i=r,s=await this.getDiscovery(),a=Math.max(Je,i.intervalSeconds??Je),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 ee(this.options.sessions,()=>this.options.sessions.save(c)),await this.options.transactions.remove(t),c}catch(d){let c=Ze(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=Sn,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new y("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 N;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new N;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new N;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 ee(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 y("provider_revoke_timeout"))},vr)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,r;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{r=setTimeout(()=>{t.abort(),s(new y("business_revoke_timeout"))},vr)})])}finally{r&&clearTimeout(r)}}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 N;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new N;let r;try{r=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=Ze(i);if(s==="business_http_409"){let a=await ee(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 N}throw s==="business_http_401"?(await this.clearIfCurrent(t),new N):i}try{let i=this.businessSession(r,t.principal,t);if(i.refreshToken===t.refreshToken)throw new y("refresh_token_rotation_missing");return await ee(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 N;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 ee(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 ee(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(),wr(An,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 N;let t;try{let r=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:r.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(r){let i=Ze(r);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new N):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),r)}try{if(!t.refreshToken)throw new y("refresh_token_rotation_missing");let r=await this.acceptProviderTokens(t,void 0,e);return await ee(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 N;return await this.options.sessions.save(r),r})}catch(r){throw await this.clearIfUnchanged(e),r}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(D(e.issuer)!==D(this.options.configuration.issuer))throw new y("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:r,redirectUri:i}=this.options.configuration;return`${e}|${D(t)}|${r}|${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 r=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,r)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new y("unsupported_token_type");let r=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(r,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new y("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==r.subject||i.sessionId!==r.sessionId)throw new y("token_subject_mismatch")}return r}async acceptProviderTokens(e,t,r){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new N;let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?r?this.isOfflineSession(r):!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:D(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,r=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 r=="object"&&r!==null&&typeof r.issuer=="string"&&typeof r.authorizedParty=="string"&&(r.environment==="TEST"||r.environment==="LIVE")&&(typeof r.audience=="string"||Array.isArray(r.audience)&&r.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&D(t.issuer)===D(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&r.authorizedParty===this.options.configuration.clientId&&r.environment===this.options.configuration.environment&&D(r.issuer)===D(this.options.configuration.issuer)&&(typeof r.audience=="string"?[r.audience]:r.audience).includes(this.options.configuration.audience)}businessSession(e,t,r){if(D(e.providerIssuer)!==D(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||r&&e.familyId!==r.familyId)throw new y("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 y("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,r=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 r=="object"&&r!==null&&typeof r.issuer=="string"&&D(r.issuer)===D(this.options.configuration.issuer)&&typeof r.subject=="string"&&r.subject.length>0&&(typeof r.audience=="string"||Array.isArray(r.audience)&&r.audience.every(i=>typeof i=="string"))&&(typeof r.audience=="string"?[r.audience]:r.audience).includes(this.options.configuration.audience)&&r.authorizedParty===this.options.configuration.clientId&&r.environment===this.options.configuration.environment}assertPrincipal(e,t,r){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(D(e.issuer)!==D(i.issuer))throw new y("issuer_mismatch");if(!s.includes(i.audience))throw new y("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new y("client_mismatch");if(e.environment!==i.environment)throw new y("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new y("required_claim_missing");if(r&&e.nonce!==t)throw new y("nonce_mismatch")}assertIdentity(e,t){let r=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(D(e.issuer)!==D(r.issuer))throw new y("issuer_mismatch");if(!i.includes(r.clientId))throw new y("client_mismatch");if(e.authorizedParty!==r.clientId)throw new y("client_mismatch");if(!e.subject||!e.sessionId)throw new y("required_claim_missing");if(e.nonce!==t)throw new y("nonce_mismatch")}};function D(n){return n.replace(/\/+$/u,"")}var Er=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};import{PassphraseMasterKeySource as Ia,RawMasterKeySource as va,deriveMasterKey as Pa,generateHexSeed as wa,computePassphraseVerifier as Ea}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as Sa}from"@safetech/inheriti-core-sdk/node";function Ws(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",n.environment),e(s,Object.assign({},a,{headers:o}))},r=n.business?void 0:wt({apiUrl:n.apiUrl,getBearerToken:n.getBearerToken,transport:t,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners}),i=new le(n.apiUrl,n.environment,n.getBearerToken,t,n.business?{organizationId:n.organizationId}:void 0);return new ne(r,{keyVault:n.keyVault,state:n.state,api:i,reconstructor:new oe(n.workerUrl),masterKeys:n.masterKeys,masterKey:n.masterKey,applicationId:n.applicationId,organizationId:n.organizationId,assetDecoder:_n})}function Qs(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=wt({apiUrl:new URL(n.apiUrl).origin,getBearerToken:n.getBearerToken,transport:e,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new be(new Ee(n.apiUrl,n.environment,n.getBearerToken,e),t)}function Ys(n){if(!n.payloadStorage||!n.secureSessionStorage||!n.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=n.transport??globalThis.fetch.bind(globalThis),t=new URL(n.apiUrl).origin,r=wt({apiUrl:t,getBearerToken:n.getBearerToken,transport:lr({apiUrl:t,organizationId:n.organizationId,planId:n.planId,editId:n.editId,environment:n.environment,transport:e}),secureSessionStorage:n.secureSessionStorage,payloadStorage:n.payloadStorage,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new Qe(new He(n.apiUrl,n.environment,n.getBearerToken,e),r,n.editRecoveryStore)}export{de as BusinessOrganizationSelectionError,Se as CorePlanMaterialBuilder,ua as DataAssetDefinitionService,z as ElementsApiRequestFailed,ne as ElementsClient,Ie as GuidedCreateRecoveryError,ye as GuidedPlanCreator,we as HttpAutomationRevealApiPort,le as HttpElementsApiPort,yr as HttpOperatorAuthTransport,He as HttpPlanEditPort,Ee as HttpQuickPlanPort,P as InvalidPlanDeclaration,k as InvalidPlanMaterial,xe as MasterKeyRelayCancellationFailed,Ce as MasterKeyRelayExpired,_e as MasterKeyRelayTimedOut,H as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,ge as MemoryKeyVault,he as MemoryStatePort,y as OAuthProtocolError,Pr as OperatorAuthClient,Ae as OperatorAuthError,N as OperatorReauthenticationRequired,Er as OperatorSessionController,it as PLAN_CREATION_SERVER_STAGES,Ia as PassphraseMasterKeySource,Sa as PlanAssetDeclaration,J as PlanRequestFailed,be as QuickPlanCreator,Qe as QuickPlanEditor,va as RawMasterKeySource,G as RelayMasterKeySource,tt as StaticMasterKeyResolver,Xe as SystemOAuthClock,Ye as WebOAuthCrypto,Ea as computePassphraseVerifier,Te as createMasterKeyResolver,vn as createNodeAutomationRevealClient,Ws as createNodeElementsClient,Qs as createNodeQuickPlanCreator,Ys as createNodeQuickPlanEditor,_n as decodeAssetContainer,Pa as deriveMasterKey,Pn as exportProtectedRevealAsset,wa as generateHexSeed,me as masterKeyRefFor,Q as masterKeyRefKey,Ze as oauthErrorCode,rn as selectBusinessOrganization,gt as unwrapDekWithMasterKey,X as validateOperationContext,Y as validatePlanCreationInput,re as validatePlanCreationMaterial};