@safetech/inheriti-client-sdk 1.17.29 → 1.17.30

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