@safetech/inheriti-client-sdk 1.17.25 → 1.17.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{decodeAssetContainer as vt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Me,generateRSAOAEPKeyPair as Ne}from"@safetech/inheriti-core-sdk/crypto";var te=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ne=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},re=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},D=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:s}=await Ne();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let i=await this.options.api.startRelaySession(r),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(f=>new Promise(v=>setTimeout(v,f))),u=!0,c=!1,y,C=()=>y??=(async()=>{let f=new AbortController,v,De=new Promise((Rt,Oe)=>{v=setTimeout(()=>{f.abort(),Oe(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(i.sessionId,f.signal),De])}finally{clearTimeout(v)}})(),_,M=new Promise((f,v)=>{_=()=>{u&&C().catch(()=>{}),v(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",_,{once:!0})});M.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(i),c=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let f=await Promise.race([this.options.api.readRelaySession(i.sessionId,e),M]);if(f.status!=="PENDING"&&(u=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(f.status==="DELIVERED"&&f.sealedMasterKey){let v=(await Me(f.sealedMasterKey,s)).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(f.status==="EXPIRED")throw new ne(i.sessionId);await Ke(d,a,e)}throw new te(i.sessionId)}catch(f){if(u&&(!c||e?.aborted))try{await C()}catch(v){if(e?.aborted)throw new re(v)}throw f}finally{_&&e?.removeEventListener("abort",_)}}};async function Ke(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,s)=>{let i=()=>s(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",i,{once:!0}),n(e).then(r,s).finally(()=>t.removeEventListener("abort",i))})}function se(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let s=await n.source?.resolve();return s||ie(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(ke(e,n.applicationId)){let s=await n.source?.resolve();return s||ie(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return ie(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function ke(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function ie(n,e,t,r,s){if((await e()).relayAvailable)return new D({...n.relay,api:Ue(n.api,t)}).resolve(r,s)}function Ue(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 N(n){return`${n.system}:${n.contextId}`}function G(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var S=class extends Error{constructor(t){super(`master_key_required:${N(t)}`);this.ref=t;this.name="MasterKeyRequired"}};var F=class{keys=new Map;async store(e,t){let r=N(e),s=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,s)}async load(e){return this.keys.get(N(e))?.slice()}async remove(e){let t=N(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var $=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 V=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},l=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var z=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var B=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],oe={"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"]};var p=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},b=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function K(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new b("plan_material_field_unknown");if(ae(n.dataShards,"data_shards_invalid"),ae(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&ae(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new b("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new b("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new b("material_operation_invalid")}function ae(n,e){if(!Array.isArray(n))throw new b(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new b(e);if(t.data!==void 0&&typeof t.data!="string")throw new b(e)}}function O(n){if(x(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Ge(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(x(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),!B.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 s=t.fieldNames??[];if(t.isBinary&&(s.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new p("binary_asset_metadata_invalid");if(!t.isBinary&&(!s.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new p("structured_asset_metadata_invalid");if(new Set(s).size!==s.length||s.some(i=>!i.trim()))throw new p("asset_field_names_invalid");if(Le(t.matchOrigins),!t.isBinary){let i=oe[t.type];if(!i||s.some(a=>!i.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(x(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!fe(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")}qe(n)}function Le(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 qe(n){let e=n.policy;if(e&&x(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"){x(e.authentication,["mode"],"plan_authentication_field_unknown");let i=e.authentication.mode;if(i!==void 0&&i!=="EXCLUSIVE"&&i!=="ALL_REQUIRED")throw new p("authentication_mode_invalid")}if(e.moderation){x(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let i=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(i.length===0)throw new p("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>i.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;x(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,s=t.countdownMinutes??0;if(!fe(t.subjectEmail))throw new p("dms_subject_invalid");if(!n.participants.some(i=>ye(i.routingEmail)===ye(t.subjectEmail)))throw new p("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(s)||t.countdownDays<0||r<0||r>23||s<0||s>59||t.countdownDays+r+s===0)throw new p("dms_countdown_invalid")}function Ge(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 fe(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function ye(n){return n.normalize("NFC").trim().toLowerCase()}function x(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new p(t)}var W=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)}},j=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),O(e),H(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,s,i={}){O(t);let a=await this.checkpoints.load(e);if(!a)throw new Y("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await he(t))throw new Y("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(i.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;H(i.signal),i.onProgress?.("ENCRYPTING");let d=await s.encrypt({planId:o.planId,declaration:t,secrets:r,signal:i.signal});H(i.signal),i.onProgress?.("GENERATING_SHARES");let u=await s.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:i.signal});H(i.signal),K(u);let c=await this.api.supplyPlanCreationMaterial(e,u);return i.onProgress?.(c.stage),c.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,c),c}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await he(e),serverStage:t.stage})}},Y=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function he(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,s)=>r.clientAssetRef.localeCompare(s.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,s)=>r.clientParticipantRef.localeCompare(s.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 H(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function ve(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new V(r.stage);return n.authorizeRevealAction(e,t)}function Fe(n){let e=n?.status;return e===400||e===401||e===403}async function Re(n,e,t,r){let s=await n.getReveal(e);try{await r(s.planId)}catch(i){if(!Fe(i))throw i}return n.releaseRevealMaterial(e,t)}function $e(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"?ze(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":Ve.has(n.stage)?"ENDED":"CONTINUING"}var Ve=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function ze(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 de=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},I=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Q(n,e,t={},r=!1){if(t.signal?.aborted)throw m();let s=await n.getPlan(e),i=await n.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")||i.protectedCopy!==void 0&&i.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Pe(i.id);if(t.signal?.aborted)throw m();let a=()=>n.prepareReveal(e,t.signal,async c=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(c)});if(r||await a(),t.signal?.aborted)throw m();let o=t.idempotencyKey??crypto.randomUUID(),d;try{d=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:o,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(c){if(c?.code!=="merge_process_already_active")throw c;let y=await n.getActivePlanReveal(e);throw!y||y.planId!==e||y.mode!==(t.mode??"DIRECT")||y.protectedCopy!==void 0&&y.protectedCopy!==(t.protectedCopy??!1)?c:Pe(y.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await n.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let u;try{if(t.signal?.aborted)throw m();let c=await He(n,d,t);if(t.signal?.aborted||(r&&await a(),t.signal?.aborted)||(w(t,"RELEASING_MATERIAL",c),t.signal?.aborted))throw m();let y=await n.releaseRevealMaterial(c.id,c.materialVersion??"1");if(t.signal?.aborted||(c.mode==="GOVERNED"&&await n.markRevealSharesCollected(c.id),t.signal?.aborted))throw m();let C;try{C=await Xe(n,c,Ze(y),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(w(t,"RECONSTRUCTING",c),t.signal?.aborted))throw m();try{u=await n.reconstructPlanMaterial(C)}catch(M){throw t.signal?.aborted?m():(await n.reportRevealReconstruction(c.id,{status:"FAILED",errorCode:Ye(M)}),M)}if(t.signal?.aborted)throw m();let _=await n.reportRevealReconstruction(c.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(w(t,"OPEN",_),t.signal?.aborted))throw m();return new ce(n,_,s,u,t.signal)}catch(c){throw u?.fill(0),await Ae(n,d.id,t.signal?.aborted?"CANCELED":"ERROR"),c}}function Pe(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var Be=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function He(n,e,t){let r=await E(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw m();if(t.onSession?.(r),t.onProgress?.({phase:$e(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(Be.has(r.stage))throw new le(r.stage);await pe(t.pollIntervalMs??1500,t.signal),r=await E(()=>n.getReveal(e.id,t.signal),t.signal)}}var le=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function w(n,e,t){n.onProgress?.({phase:e,session:t})}function pe(n,e){return e?.aborted?Promise.reject(m()):new Promise((t,r)=>{let s=setTimeout(a,Math.max(0,n)),i=()=>{clearTimeout(s),r(m())};function a(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var ce=class{constructor(e,t,r,s,i){this.client=e;this.session=t;this.plan=r;this.plaintext=s;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,2147483647)),this.abortListener=i?()=>{this.close("CANCELED").catch(()=>{})}:void 0,i&&this.abortListener&&i.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new de;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([s])=>{r=s?.value}),r}async consumeFields(e,t){if(e.length===0)throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=e.map(({selector:i,options:a={}})=>{let o=We(i),d=this.plan.assets.find(u=>(u.code??u.id)===o.asset);if(!d)throw new I("asset_not_found");if(d.isBinary)throw new I("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new I("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),s=[];try{for(let a of r)s.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 i=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 I("asset_value_invalid");return{selector:a.selector,value:je(o.data,a.field,a.asset.type)}});await t(i)}catch(i){throw await Promise.all(s.map(a=>this.reportAction(a.id,"FAILED",be(i)))),i}await Promise.all(s.map(i=>this.reportAction(i.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new I("asset_not_found");if(!r.isBinary)throw new I("action_not_allowed");let s=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),i;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 I("asset_value_invalid");i=a.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:i})}catch(a){throw await this.reportAction(s.id,"FAILED",be(a)),a}finally{i?.fill(0)}await this.reportAction(s.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=Ae(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 We(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new I("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new I("asset_selector_invalid");return{asset:n.asset,field:n.field}}function je(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new I("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new I("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?oe[t]:void 0)?.includes(e))return"";throw new I("asset_value_invalid")}return r[e]}function be(n){if(n instanceof I)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 Ye(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Xe(n,e,t,r){let s=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(s){let d=await E(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new X;let u=await E(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(Ee(u,s.id,e.planId),!u.shares.includes(s.data))throw new P;w(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:c}=await E(()=>r.proDevice.write(u,r.signal),r.signal);if(r.signal?.aborted)throw m();if(!c?.trim())throw new P;if(await n.claimRevealCustodianShare(e.id,u.id,c),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,u.id),r.signal?.aborted))throw m();return{...t,shares:t.shares.filter(y=>y!==s).concat(u.shares.map((y,C)=>({id:`${u.id}:${C}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:y})))}}if(d!=="SK_MOBILE")throw new P;if(r.signal?.aborted)throw m();return await n.distributeRevealCustodianShare(e.id),w(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let i=await E(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),w(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await pe(r.pollIntervalMs??1500,r.signal),i=await E(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(i.status==="CLAIMED"&&i.deviceType==="SK_PRO"){if(!r.proDevice)throw new X;if(!i.shareId||!i.deviceId)throw new P;w(r,"CONNECTING_SAFEKEY_PRO",e);let d=await E(()=>r.proDevice.read({shareId:i.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw m();if(Ee(d,i.shareId,e.planId),d.deviceId!==i.deviceId)throw new P;if(await n.collectRevealCustodianShare(e.id,i.shareId),r.signal?.aborted)throw m();return{...t,shares:t.shares.concat(d.shares.map((u,c)=>({id:`${d.id}:${c}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new P;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),w(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw m();await n.requestRevealCustodianRelease(e.id);let o=await Qe(n,e.id,r);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,u)=>({id:`${o.id}:${u}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function Ee(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 P}async function E(n,e){if(e?.aborted)throw m();if(!e)return n();let t,r=new Promise((s,i)=>{t=()=>i(m()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw m();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Qe(n,e,t){let r=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let s=await E(()=>n.getRevealCustodianShare(e,t.signal),t.signal);if(s&&s.status!=="PENDING"){let i=s;if(i.shares?.length)return i;throw new P}if(Date.now()>=r)throw new ue;await pe(t.pollIntervalMs??1500,t.signal)}}var P=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},X=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 Ze(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Ae(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!Je(a))throw a}return}let r=new AbortController,s,i=new Promise((a,o)=>{s=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([n.closeReveal(e,t,r.signal),i]);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(s)}}function Je(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function m(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var k=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 F,this.state=t.state??new $,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??nt(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 l;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new l;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new l;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new l;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new l;return O(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new l;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new l;return K(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new l;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new W){if(this.requireApplication(),!this.api)throw new l;return new j(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 S({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let s=await this.keyVault.load(e);if(s)return tt(s);let i=await this.masterKeys?.resolve(e,t,r);if(!i)throw new S(e);return await this.keyVault.store(e,et(i)),i}async prepareReveal(e,t,r){if(!this.api)throw new l;let s=await this.api.planKeyReference(e);if(!s.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(s,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 l;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new z;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 S({system:"INHERITI_BUSINESS",contextId:this.organizationId});let s=G(e);if(!s)throw new S({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(s,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new l;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new l;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new l;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,r){if(!this.api)throw new l;return this.api.createRevealFileAccess(e,t,r)}cancelRevealFileAccess(e,t,r){if(!this.api)throw new l;return this.api.cancelRevealFileAccess(e,t,r)}getActivePlanReveal(e){if(!this.api)throw new l;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new l;return this.api.getReveal(e,t)}openReveal(e,t){return Q(this,e,t)}async withReveal(e,t,r){let s=await this.openReveal(e,t);try{let i=await r(s);return await s.close("COMPLETED"),i}catch(i){throw await s.close(t.signal?.aborted?"CANCELED":"ERROR"),i}}async releaseRevealMaterial(e,t){if(!this.api)throw new l;return Re(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new l;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new l;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new l;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new l;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new l;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new l;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new l;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new l;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new l;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new l;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new l;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new l;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new l;return ve(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new l;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new l;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new l;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new l;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new l;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new l;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),s=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let i=r.validatorShares.map(u=>Object.assign({},u,{shareType:"VALIDATOR_SHARD"})),a=s.dataShards.map(u=>Object.assign({},u,{shareType:"DATA_SHARD"})),o=s.backupShards.map(u=>Object.assign({},u,{shareType:"BACKUP_SHARD"})),d=s.keyShards.map(u=>Object.assign({},u,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:s.dek||r.dek,shares:i.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 l;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 me;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new S({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},me=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function et(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 tt(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function nt(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return se({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return se({...e,organizationId:n.organizationId})}function Se(n){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let r=await n.api.planKeyReference(e),s=G(r);if(!r.masterKeyWrapped||!s||r.planId!==e)throw new Error("automation_plan_key_reference_invalid");let i=new D({api:{startRelaySession:o=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>n.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>n.api.cancelMasterKeyRelaySession(o,d)}}),a=new k(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(o,d,u)=>{if(o.system!==s.system||o.contextId!==s.contextId)throw new Error("automation_plan_key_reference_mismatch");return i.resolve(d,u)}}});return Q(a,e,t,!0)}}}var rt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],it=["DIRECT","GOVERNED"],st=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],at=["ACTIVE","REVOKED"],ot=["SK_MOBILE"],dt=["ACTIVE","INACTIVE"];function ge(n){let e=R(n),t=lt(e),r=R(e.source),s=g(r.kind,"source.kind");return{...t,assets:T(e.assets).map(i=>{let a=R(i);return{id:g(a.id,"asset.id"),code:U(a.code),type:h(g(a.type,"asset.type"),B),name:g(a.name,"asset.name"),isBinary:ct(a.isBinary,"asset.isBinary"),fieldNames:T(a.fieldNames).map(o=>g(o,"asset.fieldNames")),fileName:U(a.fileName),mimeType:U(a.mimeType),size:a.size===void 0||a.size===null?void 0:A(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:T(a.matchOrigins).map(o=>g(o,"asset.matchOrigins"))}}),participants:T(e.participants).map(i=>{let a=R(i);return{id:g(a.id,"participant.id"),displayName:g(a.displayName,"participant.displayName"),relationships:T(a.relationships).map(o=>h(g(o,"relationship"),st)),lifecycle:h(g(a.lifecycle,"participant.lifecycle"),at)}}),revealPolicy:(()=>{let i=R(e.revealPolicy);return{masterKeyRelease:h(g(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:h(g(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=R(e.dms);return{subjectEmail:g(i.subjectEmail,"dms.subjectEmail"),countdownDays:A(i.countdownDays,"dms.countdownDays"),countdownHours:A(i.countdownHours,"dms.countdownHours"),countdownMinutes:A(i.countdownMinutes,"dms.countdownMinutes")}})(),source:s==="NATIVE"?{kind:"NATIVE"}:s==="BRIDGED"?{kind:"BRIDGED",system:h(g(r.system,"source.system"),["INHERITI_BUSINESS"]),status:h(g(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:s}}}function lt(n){let e=R(n),t=R(e.assetSummary),r=R(e.governance),s=R(e.participantSummary);return{id:g(e.id,"id"),name:g(e.name,"name"),description:U(e.description),status:h(g(e.status,"status"),rt),createdAt:g(e.createdAt,"createdAt"),configuredAt:U(e.configuredAt),assetSummary:{count:A(t.count,"assetSummary.count"),types:T(t.types).map(i=>h(g(i,"assetType"),B)),names:we(t.names).map(i=>g(i,"assetSummary.names"))},governance:{mode:h(g(r.mode,"governance.mode"),it),minimumApprovals:A(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:A(s.owners,"owners"),mergers:A(s.mergers,"mergers"),moderators:A(s.moderators,"moderators")},authentication:we(e.authentication).map(i=>{let a=R(i);return{id:h(g(a.id,"authentication.id"),ot),status:h(g(a.status,"authentication.status"),dt)}})}}function h(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function R(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function we(n){return n==null?[]:T(n)}function T(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function g(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function U(n){return n==null?void 0:g(n,"optional")}function A(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function ct(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function Ce(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 _e(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var Z=class extends Error{constructor(t,r,s,i){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=s;this.requestId=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}};var J=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return ge(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,...s}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",s,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:s,...i}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",i,!0,{"idempotency-key":s})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!1);try{let s=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!s.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,s),{sessionId:e,expiresAt:s.expiresAt}}catch(s){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),s}}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,s=!0,i,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}`,...i});r!==void 0&&d.set("content-type","application/json");let u=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 c;try{c=await u.json()}catch{a?.throwIfAborted()}if(!u.ok||c&&c.ok===!1||s&&c?.result===void 0)throw new Z(u.status,c&&Ce(c),c&&_e(c));return c?.result}};import{createNodeSsdpV2Processor as ht}from"@safetech/inheriti-core-sdk/node";async function xe(n,e){if(!e)throw new Error("master_key_required");let t=ut(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),s=pt(n),i=s.slice(0,12),a=s.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,a);return mt(new Uint8Array(o))}function ut(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 pt(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 mt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var L=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await Te("plan_key_unwrap_failed",()=>xe(e.planKey,t)),s=await crypto.subtle.importKey("raw",Ie(r),{name:"AES-GCM"},!1,["decrypt"]),i=[],a=[];for(let o of e.shares){let d=await Te("plan_share_decryption_failed",()=>ft(o.data,s));yt(o.shareType)?a.push(d):i.push(d)}try{return await this.processor().reconstruct(i,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new ee("plan_share_reconstruction_failed",It(o))}}},ee=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},gt=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 It(n){let e=n instanceof Error?n.message:void 0;if(e)return gt.has(e)?e:void 0}async function Te(n,e){try{return await e()}catch{throw new ee(n)}}function yt(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function ft(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=Ie(n.slice(0,t)),s=Ie(n.slice(t+1)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,s);return new TextDecoder().decode(i)}function Ie(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let s=0;s<e.length;s+=1)r[s]=e.charCodeAt(s);return t}var q=class extends L{constructor(e){super(()=>ht(e))}};function Wn(n){let e=new J(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{...Se({api:e,reconstructor:new q(n.workerUrl),assetDecoder:vt}),getPlan:t=>e.getPlan(t)}}export{Wn as createNodeAutomationRevealClient};
1
+ import{decodeAssetContainer as vt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Me,generateRSAOAEPKeyPair as Ne}from"@safetech/inheriti-core-sdk/crypto";var ne=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},re=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ie=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},D=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:s}=await Ne();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let i=await this.options.api.startRelaySession(r),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(y=>new Promise(v=>setTimeout(v,y))),u=!0,c=!1,f,C=()=>f??=(async()=>{let y=new AbortController,v,De=new Promise((Rt,Oe)=>{v=setTimeout(()=>{y.abort(),Oe(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(i.sessionId,y.signal),De])}finally{clearTimeout(v)}})(),_,M=new Promise((y,v)=>{_=()=>{u&&C().catch(()=>{}),v(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",_,{once:!0})});M.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(i),c=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let y=await Promise.race([this.options.api.readRelaySession(i.sessionId,e),M]);if(y.status!=="PENDING"&&(u=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(y.status==="DELIVERED"&&y.sealedMasterKey){let v=(await Me(y.sealedMasterKey,s)).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(y.status==="EXPIRED")throw new re(i.sessionId);await Ke(d,a,e)}throw new ne(i.sessionId)}catch(y){if(u&&(!c||e?.aborted))try{await C()}catch(v){if(e?.aborted)throw new ie(v)}throw y}finally{_&&e?.removeEventListener("abort",_)}}};async function Ke(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,s)=>{let i=()=>s(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",i,{once:!0}),n(e).then(r,s).finally(()=>t.removeEventListener("abort",i))})}function ae(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let s=await n.source?.resolve();return s||se(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(ke(e,n.applicationId)){let s=await n.source?.resolve();return s||se(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return se(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function ke(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function se(n,e,t,r,s){if((await e()).relayAvailable)return new D({...n.relay,api:Ue(n.api,t)}).resolve(r,s)}function Ue(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 N(n){return`${n.system}:${n.contextId}`}function G(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var S=class extends Error{constructor(t){super(`master_key_required:${N(t)}`);this.ref=t;this.name="MasterKeyRequired"}};var F=class{keys=new Map;async store(e,t){let r=N(e),s=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,s)}async load(e){return this.keys.get(N(e))?.slice()}async remove(e){let t=N(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var $=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 V=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},l=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var z=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var B=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],de={"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"]};var p=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},b=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function K(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new b("plan_material_field_unknown");if(oe(n.dataShards,"data_shards_invalid"),oe(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&oe(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new b("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new b("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new b("material_operation_invalid")}function oe(n,e){if(!Array.isArray(n))throw new b(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new b(e);if(t.data!==void 0&&typeof t.data!="string")throw new b(e)}}function O(n){if(x(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Ge(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(x(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),!B.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 s=t.fieldNames??[];if(t.isBinary&&(s.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new p("binary_asset_metadata_invalid");if(!t.isBinary&&(!s.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new p("structured_asset_metadata_invalid");if(new Set(s).size!==s.length||s.some(i=>!i.trim()))throw new p("asset_field_names_invalid");if(Le(t.matchOrigins),!t.isBinary){let i=de[t.type];if(!i||s.some(a=>!i.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(x(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!ye(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")}qe(n)}function Le(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 qe(n){let e=n.policy;if(e&&x(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"){x(e.authentication,["mode"],"plan_authentication_field_unknown");let i=e.authentication.mode;if(i!==void 0&&i!=="EXCLUSIVE"&&i!=="ALL_REQUIRED")throw new p("authentication_mode_invalid")}if(e.moderation){x(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let i=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(i.length===0)throw new p("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>i.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;x(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,s=t.countdownMinutes??0;if(!ye(t.subjectEmail))throw new p("dms_subject_invalid");if(!n.participants.some(i=>fe(i.routingEmail)===fe(t.subjectEmail)))throw new p("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(s)||t.countdownDays<0||r<0||r>23||s<0||s>59||t.countdownDays+r+s===0)throw new p("dms_countdown_invalid")}function Ge(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 ye(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function fe(n){return n.normalize("NFC").trim().toLowerCase()}function x(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new p(t)}var W=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)}},j=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),O(e),H(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,s,i={}){O(t);let a=await this.checkpoints.load(e);if(!a)throw new Y("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await he(t))throw new Y("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(i.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;H(i.signal),i.onProgress?.("ENCRYPTING");let d=await s.encrypt({planId:o.planId,declaration:t,secrets:r,signal:i.signal});H(i.signal),i.onProgress?.("GENERATING_SHARES");let u=await s.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:i.signal});H(i.signal),K(u);let c=await this.api.supplyPlanCreationMaterial(e,u);return i.onProgress?.(c.stage),c.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,c),c}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await he(e),serverStage:t.stage})}},Y=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function he(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,s)=>r.clientAssetRef.localeCompare(s.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,s)=>r.clientParticipantRef.localeCompare(s.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 H(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function ve(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new V(r.stage);return n.authorizeRevealAction(e,t)}function Fe(n){let e=n?.status;return e===400||e===401||e===403}async function Re(n,e,t,r){let s=await n.getReveal(e);try{await r(s.planId)}catch(i){if(!Fe(i))throw i}return n.releaseRevealMaterial(e,t)}function $e(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"?ze(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":Ve.has(n.stage)?"ENDED":"CONTINUING"}var Ve=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function ze(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 le=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},I=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Z(n,e,t={},r=!1){if(t.signal?.aborted)throw m();let s=await n.getPlan(e),i=await n.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")||i.protectedCopy!==void 0&&i.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Pe(i.id);if(t.signal?.aborted)throw m();let a=()=>n.prepareReveal(e,t.signal,async c=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(c)});if(r||await a(),t.signal?.aborted)throw m();let o=t.idempotencyKey??crypto.randomUUID(),d;try{d=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:o,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(c){if(c?.code!=="merge_process_already_active")throw c;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)?c:Pe(f.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await n.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let u;try{if(t.signal?.aborted)throw m();let c=await He(n,d,t);if(t.signal?.aborted||(r&&await a(),t.signal?.aborted)||(w(t,"RELEASING_MATERIAL",c),t.signal?.aborted))throw m();let f=await n.releaseRevealMaterial(c.id,c.materialVersion??"1");if(t.signal?.aborted||(c.mode==="GOVERNED"&&await n.markRevealSharesCollected(c.id),t.signal?.aborted))throw m();let C;try{C=await Xe(n,c,Ze(f),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(w(t,"RECONSTRUCTING",c),t.signal?.aborted))throw m();try{u=await n.reconstructPlanMaterial(C)}catch(M){throw t.signal?.aborted?m():(await n.reportRevealReconstruction(c.id,{status:"FAILED",errorCode:Ye(M)}),M)}if(t.signal?.aborted)throw m();let _=await n.reportRevealReconstruction(c.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(w(t,"OPEN",_),t.signal?.aborted))throw m();return new ue(n,_,s,u,t.signal)}catch(c){throw u?.fill(0),await Ae(n,d.id,t.signal?.aborted?"CANCELED":"ERROR"),c}}function Pe(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var Be=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function He(n,e,t){let r=await E(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw m();if(t.onSession?.(r),t.onProgress?.({phase:$e(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(Be.has(r.stage))throw new ce(r.stage);await pe(t.pollIntervalMs??1500,t.signal),r=await E(()=>n.getReveal(e.id,t.signal),t.signal)}}var ce=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function w(n,e,t){n.onProgress?.({phase:e,session:t})}function pe(n,e){return e?.aborted?Promise.reject(m()):new Promise((t,r)=>{let s=setTimeout(a,Math.max(0,n)),i=()=>{clearTimeout(s),r(m())};function a(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var ue=class{constructor(e,t,r,s,i){this.client=e;this.session=t;this.plan=r;this.plaintext=s;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,2147483647)),this.abortListener=i?()=>{this.close("CANCELED").catch(()=>{})}:void 0,i&&this.abortListener&&i.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new le;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([s])=>{r=s?.value}),r}async consumeFields(e,t){if(e.length===0)throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=e.map(({selector:i,options:a={}})=>{let o=We(i),d=this.plan.assets.find(u=>(u.code??u.id)===o.asset);if(!d)throw new I("asset_not_found");if(d.isBinary)throw new I("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new I("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),s=[];try{for(let a of r)s.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 i=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 I("asset_value_invalid");return{selector:a.selector,value:je(o.data,a.field,a.asset.type)}});await t(i)}catch(i){throw await Promise.all(s.map(a=>this.reportAction(a.id,"FAILED",be(i)))),i}await Promise.all(s.map(i=>this.reportAction(i.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new I("asset_not_found");if(!r.isBinary)throw new I("action_not_allowed");let s=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),i;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 I("asset_value_invalid");i=a.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:i})}catch(a){throw await this.reportAction(s.id,"FAILED",be(a)),a}finally{i?.fill(0)}await this.reportAction(s.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=Ae(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 We(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new I("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new I("asset_selector_invalid");return{asset:n.asset,field:n.field}}function je(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new I("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new I("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?de[t]:void 0)?.includes(e))return"";throw new I("asset_value_invalid")}return r[e]}function be(n){if(n instanceof I)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 Ye(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Xe(n,e,t,r){let s=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(s){let d=await E(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new X;let u=await E(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(Ee(u,s.id,e.planId),!u.shares.includes(s.data))throw new P;w(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:c}=await E(()=>r.proDevice.write(u,r.signal),r.signal);if(r.signal?.aborted)throw m();if(!c?.trim())throw new P;if(await n.claimRevealCustodianShare(e.id,u.id,c),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,u.id),r.signal?.aborted))throw m();return{...t,shares:t.shares.filter(f=>f!==s).concat(u.shares.map((f,C)=>({id:`${u.id}:${C}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:f})))}}if(d!=="SK_MOBILE")throw new P;if(r.signal?.aborted)throw m();return await n.distributeRevealCustodianShare(e.id),w(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let i=await E(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),w(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await pe(r.pollIntervalMs??1500,r.signal),i=await E(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(i.status==="CLAIMED"&&i.deviceType==="SK_PRO"){if(!r.proDevice)throw new X;if(!i.shareId||!i.deviceId)throw new P;w(r,"CONNECTING_SAFEKEY_PRO",e);let d=await E(()=>r.proDevice.read({shareId:i.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw m();if(Ee(d,i.shareId,e.planId),d.deviceId!==i.deviceId)throw new P;if(await n.collectRevealCustodianShare(e.id,i.shareId),r.signal?.aborted)throw m();return{...t,shares:t.shares.concat(d.shares.map((u,c)=>({id:`${d.id}:${c}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new P;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),w(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw m();await n.requestRevealCustodianRelease(e.id);let o=await Qe(n,e,r);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,u)=>({id:`${o.id}:${u}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function Ee(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 P}async function E(n,e){if(e?.aborted)throw m();if(!e)return n();let t,r=new Promise((s,i)=>{t=()=>i(m()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw m();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Qe(n,e,t){let r=Date.parse(e.expiresAt),s=Number.isFinite(r)?Math.min(r,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=s)throw new Q;let i=await E(()=>n.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=s)throw new Q;if(i&&i.status!=="PENDING"){let a=i;if(a.shares?.length)return a;throw new P}await pe(t.pollIntervalMs??1500,t.signal)}}var P=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},X=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Q=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Ze(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Ae(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!Je(a))throw a}return}let r=new AbortController,s,i=new Promise((a,o)=>{s=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([n.closeReveal(e,t,r.signal),i]);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(s)}}function Je(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function m(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var k=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 F,this.state=t.state??new $,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??nt(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 l;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new l;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new l;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new l;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new l;return O(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new l;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new l;return K(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new l;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new W){if(this.requireApplication(),!this.api)throw new l;return new j(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 S({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let s=await this.keyVault.load(e);if(s)return tt(s);let i=await this.masterKeys?.resolve(e,t,r);if(!i)throw new S(e);return await this.keyVault.store(e,et(i)),i}async prepareReveal(e,t,r){if(!this.api)throw new l;let s=await this.api.planKeyReference(e);if(!s.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(s,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 l;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new z;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 S({system:"INHERITI_BUSINESS",contextId:this.organizationId});let s=G(e);if(!s)throw new S({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(s,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new l;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new l;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new l;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,r){if(!this.api)throw new l;return this.api.createRevealFileAccess(e,t,r)}cancelRevealFileAccess(e,t,r){if(!this.api)throw new l;return this.api.cancelRevealFileAccess(e,t,r)}getActivePlanReveal(e){if(!this.api)throw new l;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new l;return this.api.getReveal(e,t)}openReveal(e,t){return Z(this,e,t)}async withReveal(e,t,r){let s=await this.openReveal(e,t);try{let i=await r(s);return await s.close("COMPLETED"),i}catch(i){throw await s.close(t.signal?.aborted?"CANCELED":"ERROR"),i}}async releaseRevealMaterial(e,t){if(!this.api)throw new l;return Re(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new l;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new l;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new l;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new l;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new l;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new l;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new l;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new l;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new l;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new l;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new l;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new l;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new l;return ve(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new l;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new l;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new l;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new l;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new l;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new l;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),s=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let i=r.validatorShares.map(u=>Object.assign({},u,{shareType:"VALIDATOR_SHARD"})),a=s.dataShards.map(u=>Object.assign({},u,{shareType:"DATA_SHARD"})),o=s.backupShards.map(u=>Object.assign({},u,{shareType:"BACKUP_SHARD"})),d=s.keyShards.map(u=>Object.assign({},u,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:s.dek||r.dek,shares:i.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 l;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 me;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new S({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},me=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function et(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 tt(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function nt(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 ae({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return ae({...e,organizationId:n.organizationId})}function Se(n){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let r=await n.api.planKeyReference(e),s=G(r);if(!r.masterKeyWrapped||!s||r.planId!==e)throw new Error("automation_plan_key_reference_invalid");let i=new D({api:{startRelaySession:o=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>n.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>n.api.cancelMasterKeyRelaySession(o,d)}}),a=new k(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(o,d,u)=>{if(o.system!==s.system||o.contextId!==s.contextId)throw new Error("automation_plan_key_reference_mismatch");return i.resolve(d,u)}}});return Z(a,e,t,!0)}}}var rt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],it=["DIRECT","GOVERNED"],st=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],at=["ACTIVE","REVOKED"],ot=["SK_MOBILE"],dt=["ACTIVE","INACTIVE"];function ge(n){let e=R(n),t=lt(e),r=R(e.source),s=g(r.kind,"source.kind");return{...t,assets:T(e.assets).map(i=>{let a=R(i);return{id:g(a.id,"asset.id"),code:U(a.code),type:h(g(a.type,"asset.type"),B),name:g(a.name,"asset.name"),isBinary:ct(a.isBinary,"asset.isBinary"),fieldNames:T(a.fieldNames).map(o=>g(o,"asset.fieldNames")),fileName:U(a.fileName),mimeType:U(a.mimeType),size:a.size===void 0||a.size===null?void 0:A(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:T(a.matchOrigins).map(o=>g(o,"asset.matchOrigins"))}}),participants:T(e.participants).map(i=>{let a=R(i);return{id:g(a.id,"participant.id"),displayName:g(a.displayName,"participant.displayName"),relationships:T(a.relationships).map(o=>h(g(o,"relationship"),st)),lifecycle:h(g(a.lifecycle,"participant.lifecycle"),at)}}),revealPolicy:(()=>{let i=R(e.revealPolicy);return{masterKeyRelease:h(g(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:h(g(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=R(e.dms);return{subjectEmail:g(i.subjectEmail,"dms.subjectEmail"),countdownDays:A(i.countdownDays,"dms.countdownDays"),countdownHours:A(i.countdownHours,"dms.countdownHours"),countdownMinutes:A(i.countdownMinutes,"dms.countdownMinutes")}})(),source:s==="NATIVE"?{kind:"NATIVE"}:s==="BRIDGED"?{kind:"BRIDGED",system:h(g(r.system,"source.system"),["INHERITI_BUSINESS"]),status:h(g(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:s}}}function lt(n){let e=R(n),t=R(e.assetSummary),r=R(e.governance),s=R(e.participantSummary);return{id:g(e.id,"id"),name:g(e.name,"name"),description:U(e.description),status:h(g(e.status,"status"),rt),createdAt:g(e.createdAt,"createdAt"),configuredAt:U(e.configuredAt),assetSummary:{count:A(t.count,"assetSummary.count"),types:T(t.types).map(i=>h(g(i,"assetType"),B)),names:we(t.names).map(i=>g(i,"assetSummary.names"))},governance:{mode:h(g(r.mode,"governance.mode"),it),minimumApprovals:A(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:A(s.owners,"owners"),mergers:A(s.mergers,"mergers"),moderators:A(s.moderators,"moderators")},authentication:we(e.authentication).map(i=>{let a=R(i);return{id:h(g(a.id,"authentication.id"),ot),status:h(g(a.status,"authentication.status"),dt)}})}}function h(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function R(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function we(n){return n==null?[]:T(n)}function T(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function g(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function U(n){return n==null?void 0:g(n,"optional")}function A(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function ct(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function Ce(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 _e(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var J=class extends Error{constructor(t,r,s,i){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=s;this.requestId=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}};var ee=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return ge(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,...s}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",s,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:s,...i}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",i,!0,{"idempotency-key":s})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!1);try{let s=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!s.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,s),{sessionId:e,expiresAt:s.expiresAt}}catch(s){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),s}}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,s=!0,i,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}`,...i});r!==void 0&&d.set("content-type","application/json");let u=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 c;try{c=await u.json()}catch{a?.throwIfAborted()}if(!u.ok||c&&c.ok===!1||s&&c?.result===void 0)throw new J(u.status,c&&Ce(c),c&&_e(c));return c?.result}};import{createNodeSsdpV2Processor as ht}from"@safetech/inheriti-core-sdk/node";async function xe(n,e){if(!e)throw new Error("master_key_required");let t=ut(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),s=pt(n),i=s.slice(0,12),a=s.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,a);return mt(new Uint8Array(o))}function ut(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 pt(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 mt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var L=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await Te("plan_key_unwrap_failed",()=>xe(e.planKey,t)),s=await crypto.subtle.importKey("raw",Ie(r),{name:"AES-GCM"},!1,["decrypt"]),i=[],a=[];for(let o of e.shares){let d=await Te("plan_share_decryption_failed",()=>yt(o.data,s));ft(o.shareType)?a.push(d):i.push(d)}try{return await this.processor().reconstruct(i,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new te("plan_share_reconstruction_failed",It(o))}}},te=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},gt=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 It(n){let e=n instanceof Error?n.message:void 0;if(e)return gt.has(e)?e:void 0}async function Te(n,e){try{return await e()}catch{throw new te(n)}}function ft(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function yt(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=Ie(n.slice(0,t)),s=Ie(n.slice(t+1)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,s);return new TextDecoder().decode(i)}function Ie(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let s=0;s<e.length;s+=1)r[s]=e.charCodeAt(s);return t}var q=class extends L{constructor(e){super(()=>ht(e))}};function Wn(n){let e=new ee(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{...Se({api:e,reconstructor:new q(n.workerUrl),assetDecoder:vt}),getPlan:t=>e.getPlan(t)}}export{Wn as createNodeAutomationRevealClient};