@k-msg/core 0.29.5 → 0.29.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- var{defineProperty:V,getOwnPropertyNames:Et,getOwnPropertyDescriptor:xt}=Object,Mt=Object.prototype.hasOwnProperty;function vt(t){return this[t]}var _t=(t)=>{var n=(pt??=new WeakMap).get(t),e;if(n)return n;if(n=V({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function"){for(var i of Et(t))if(!Mt.call(n,i))V(n,i,{get:vt.bind(t,i),enumerable:!(e=xt(t,i))||e.enumerable})}return pt.set(t,n),n},pt;var Nt=(t)=>t;function It(t,n){this[t]=Nt.bind(null,n)}var Ut=(t,n)=>{for(var e in n)V(t,e,{get:n[e],enumerable:!0,configurable:!0,set:It.bind(n,e)})};var vn={};Ut(vn,{validateFieldCryptoConfig:()=>Pt,validateErrorRetryPolicy:()=>gt,toCiphertextEnvelopeString:()=>ln,setGlobalLogger:()=>Fn,selectActiveKidByRollout:()=>N,resolveFieldMode:()=>L,readRuntimeEnv:()=>Sn,parseErrorRetryPolicyFromJson:()=>Gt,ok:()=>it,normalizeRetryAfterMs:()=>x,normalizeProviderError:()=>Yt,normalizePhoneForHash:()=>bt,normalizeMessageStatus:()=>Mn,normalizeErrorRetryPolicy:()=>Kt,loggerMiddleware:()=>Pn,logger:()=>An,isTerminalDeliveryStatus:()=>mn,isPollableDeliveryStatus:()=>Tn,isKMsgTerminalStatus:()=>Dn,isKMsgMessageType:()=>En,isKMsgDeliveryStatus:()=>kn,isCryptoEnvelope:()=>on,getRuntimeEnvSource:()=>kt,getRolloutKnownKids:()=>W,getPollableStatuses:()=>On,getLogger:()=>D,fail:()=>st,createVaultTransitKeyResolver:()=>pn,createStaticKeyResolver:()=>Q,createRollingKeyResolver:()=>nn,createRefreshableKeyResolver:()=>v,createNoopFieldCryptoProvider:()=>dn,createLogger:()=>tt,createEnvKeyResolver:()=>rn,createDefaultMasker:()=>X,createAwsKmsKeyResolver:()=>en,createAesGcmFieldCryptoProvider:()=>an,assertFieldCryptoConfig:()=>yn,RetryHandler:()=>T,Result:()=>wn,RateLimiter:()=>et,QUEUED_MESSAGE_STATUS:()=>Rt,Logger:()=>$,LogLevel:()=>ut,KNOWN_MESSAGE_STATUSES:()=>xn,KMsgErrorCode:()=>R,KMsgError:()=>K,KMSG_TERMINAL_STATUSES:()=>mt,KMSG_POLLABLE_STATUSES:()=>rt,KMSG_MESSAGE_TYPES:()=>Ot,KMSG_DELIVERY_STATUSES:()=>Dt,FieldCryptoError:()=>M,ErrorUtils:()=>O,CircuitBreaker:()=>nt,BulkOperationHandler:()=>H});module.exports=_t(vn);var R;((l)=>{l.INVALID_REQUEST="INVALID_REQUEST";l.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";l.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";l.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";l.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";l.NETWORK_ERROR="NETWORK_ERROR";l.NETWORK_TIMEOUT="NETWORK_TIMEOUT";l.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";l.PROVIDER_ERROR="PROVIDER_ERROR";l.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";l.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";l.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";l.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";l.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";l.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";l.UNKNOWN_ERROR="UNKNOWN_ERROR"})(R||={});var Bt={["INVALID_REQUEST"]:{ko:"잘못된 요청입니다",en:"Invalid request"},["AUTHENTICATION_FAILED"]:{ko:"인증에 실패했습니다",en:"Authentication failed"},["INSUFFICIENT_BALANCE"]:{ko:"잔액이 부족합니다",en:"Insufficient balance"},["TEMPLATE_NOT_FOUND"]:{ko:"템플릿을 찾을 수 없습니다",en:"Template not found"},["RATE_LIMIT_EXCEEDED"]:{ko:"요청 한도를 초과했습니다",en:"Rate limit exceeded"},["NETWORK_ERROR"]:{ko:"네트워크 오류가 발생했습니다",en:"Network error"},["NETWORK_TIMEOUT"]:{ko:"네트워크 요청 시간이 초과되었습니다",en:"Network timeout"},["NETWORK_SERVICE_UNAVAILABLE"]:{ko:"서비스를 일시적으로 사용할 수 없습니다",en:"Service temporarily unavailable"},["PROVIDER_ERROR"]:{ko:"제공자 오류가 발생했습니다",en:"Provider error"},["MESSAGE_SEND_FAILED"]:{ko:"메시지 전송에 실패했습니다",en:"Message send failed"},["CRYPTO_CONFIG_ERROR"]:{ko:"암호화 설정 오류가 발생했습니다",en:"Crypto configuration error"},["CRYPTO_ENCRYPT_FAILED"]:{ko:"암호화에 실패했습니다",en:"Encryption failed"},["CRYPTO_DECRYPT_FAILED"]:{ko:"복호화에 실패했습니다",en:"Decryption failed"},["CRYPTO_HASH_FAILED"]:{ko:"해시 생성에 실패했습니다",en:"Hash generation failed"},["CRYPTO_POLICY_VIOLATION"]:{ko:"암호화 정책 위반이 발생했습니다",en:"Crypto policy violation"},["UNKNOWN_ERROR"]:{ko:"알 수 없는 오류가 발생했습니다",en:"Unknown error"}},qt=new Set(Object.values(R)),yt=new Set(["NETWORK_ERROR","RATE_LIMIT_EXCEEDED","NETWORK_TIMEOUT","NETWORK_SERVICE_UNAVAILABLE","PROVIDER_ERROR","UNKNOWN_ERROR"]),ft=new Set(["INVALID_REQUEST","AUTHENTICATION_FAILED","INSUFFICIENT_BALANCE","TEMPLATE_NOT_FOUND","MESSAGE_SEND_FAILED","CRYPTO_CONFIG_ERROR","CRYPTO_ENCRYPT_FAILED","CRYPTO_DECRYPT_FAILED","CRYPTO_HASH_FAILED","CRYPTO_POLICY_VIOLATION"]),P=(t)=>{if(typeof t!=="number"||Number.isNaN(t)||!Number.isFinite(t))return;return Math.trunc(t)},x=(t)=>{let n=P(t);if(n===void 0||n<0)return;return n},G=(t)=>{if(typeof t!=="string")return;return t.toLowerCase().trim()},$t=(t)=>{if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0},w=(t)=>{return typeof t==="object"&&t!==null&&!Array.isArray(t)},u=(t,n)=>{for(let e of n)if(e in t)return t[e];return},Ht=(t)=>{return t.length>0?t:"$"},lt=(t)=>{return t==="compat"?"compat":"safe"},ct=(t)=>{if(t>=500)return"retryable";if(t===408||t===425||t===429)return"retryable";return"non_retryable"},ot=(t)=>{let n=t.toLowerCase();if(n.includes("timeout")||n.includes("temporar")||n.includes("network")||n.includes("retry"))return"retryable";return};class K extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(t,n,e,i={}){super(n);if(this.name="KMsgError",this.code=t,this.details=e,this.providerErrorCode=i.providerErrorCode,this.providerErrorText=i.providerErrorText,this.httpStatus=P(i.httpStatus),this.requestId=typeof i.requestId==="string"?i.requestId:void 0,this.retryAfterMs=P(i.retryAfterMs),this.attempt=P(i.attempt),Array.isArray(i.causeChain))this.causeChain=i.causeChain;else if(i.causeChain!==void 0)this.causeChain=[i.causeChain];if(Error.captureStackTrace)Error.captureStackTrace(this,K)}getLocalizedMessage(t="ko"){let n=Bt[this.code];if(n?.[t])return n[t];return this.message}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,providerErrorCode:this.providerErrorCode,providerErrorText:this.providerErrorText,httpStatus:this.httpStatus,requestId:this.requestId,retryAfterMs:this.retryAfterMs,attempt:this.attempt,causeChain:this.causeChain}}}var k=(t,n)=>{let e=P(t);if(e!==void 0)return e;if(n==="compat"&&typeof t==="string"){let i=Number(t.trim());if(Number.isFinite(i))return Math.trunc(i)}return},J=(t,n)=>{let e=$t(t);if(e)return e;if(n==="compat"&&(typeof t==="number"||typeof t==="boolean"))return String(t);return},ht=(t)=>{if(typeof t!=="string")return;let n=t.trim().toUpperCase();if(!qt.has(n))return;return n},m=(t,n)=>{t.push({...n,path:Ht(n.path)})},at=(t,n,e,i)=>{if(t===void 0)return[];let r=(()=>{if(Array.isArray(t))return t;if(e==="compat"&&typeof t==="string")return t.split(",").map((f)=>f.trim()).filter((f)=>f.length>0);return m(i,{code:"invalid_type",message:"expected array of KMsgErrorCode values",path:n}),[]})(),s=[],p=new Set;for(let f=0;f<r.length;f+=1){let y=r[f],c=ht(typeof y==="string"?y:e==="compat"?String(y):y);if(!c){m(i,{code:"unknown_code",message:`unknown retry policy code: ${String(y)}`,path:`${n}[${f}]`});continue}if(p.has(c)){m(i,{code:"duplicate_code",message:`duplicate retry policy code: ${c}`,path:`${n}[${f}]`});continue}p.add(c),s.push(c)}return s},Vt=(t,n,e)=>{if(t===void 0)return;if(typeof t==="string"){let i=t.trim().toLowerCase();if(i==="retryable")return"retryable";if(i==="non_retryable"||i==="non-retryable")return"non_retryable"}if(n==="compat"&&typeof t==="boolean")return t?"retryable":"non_retryable";m(e,{code:"invalid_fallback",message:`invalid fallback value: ${String(t)}`,path:"fallback"});return};function gt(t,n={}){let e=lt(n.mode),i=[];if(!w(t))return m(i,{code:"invalid_root",message:"retry policy must be an object",path:"$"}),{policy:null,issues:i};let r=new Set(["retryableCodes","nonRetryableCodes","fallback"]);for(let d of Object.keys(t)){if(r.has(d))continue;m(i,{code:"unknown_field",message:`unknown retry policy field: ${d}`,path:d})}let s=at(t.retryableCodes,"retryableCodes",e,i),p=at(t.nonRetryableCodes,"nonRetryableCodes",e,i),f=Vt(t.fallback,e,i),y=new Set(s),c=new Set(p);for(let d of y){if(!c.has(d))continue;y.delete(d),m(i,{code:"conflicting_code",message:`code '${d}' is both retryable and nonRetryable; nonRetryable wins`,path:"retryableCodes"})}let a={...y.size>0?{retryableCodes:Array.from(y)}:{},...c.size>0?{nonRetryableCodes:Array.from(c)}:{},...f?{fallback:f}:{}};return{policy:a.retryableCodes!==void 0||a.nonRetryableCodes!==void 0||a.fallback!==void 0?a:null,issues:i}}function Kt(t,n={}){return gt(t,n).policy}function Gt(t,n={}){if(typeof t!=="string"||t.trim().length===0)return null;try{let e=JSON.parse(t);return Kt(e,n)}catch{return null}}var dt=(t,n)=>{let e=t.response;if(!w(e))return;return k(u(e,["status","statusCode","httpStatus"]),n)},Jt=(t,n)=>{if(t instanceof K&&Array.isArray(t.causeChain))return t.causeChain.slice();if(w(t)){let s=t.causeChain;if(Array.isArray(s))return s.slice();let p=t.details;if(n==="compat"&&w(p)){let f=p.causeChain;if(Array.isArray(f))return f.slice();if(f!==void 0)return[f]}}let e=[],i=new Set,r=t;for(let s=0;s<8;s+=1){if(!w(r))break;let p=r.cause;if(p===void 0||i.has(p))break;i.add(p),e.push(p),r=p}return e.length>0?e:void 0},Wt=(t)=>{if(t instanceof Error&&typeof t.message==="string")return t.message;if(w(t)&&typeof t.message==="string")return t.message;return typeof t==="string"?t:"Unknown error"};function Yt(t,n={}){let e=lt(n.mode),r=n.defaultCode??"UNKNOWN_ERROR",s={code:"fallback",classification:n.policy?"policy":"fallback"},p,f,y,c,a,h,d,A=(o)=>{if(o.providerErrorCode!==void 0)p=o.providerErrorCode,s.providerErrorCode="metadata";if(o.providerErrorText!==void 0)f=o.providerErrorText,s.providerErrorText="metadata";if(o.httpStatus!==void 0)y=o.httpStatus,s.httpStatus="metadata";if(o.requestId!==void 0)c=o.requestId,s.requestId="metadata";if(o.retryAfterMs!==void 0)a=x(o.retryAfterMs),s.retryAfterMs="metadata";if(o.attempt!==void 0)h=k(o.attempt,e),s.attempt="metadata";if(Array.isArray(o.causeChain))d=o.causeChain.slice(),s.causeChain="metadata"},C=(o,F)=>{if(p===void 0){let g=J(u(o,["providerErrorCode","errorCode","resultCode"]),e);if(g!==void 0)p=g,s.providerErrorCode=F}if(f===void 0){let g=J(u(o,["providerErrorText","errorMessage","msg","message"]),e);if(g!==void 0)f=g,s.providerErrorText=F}if(y===void 0){let g=k(u(o,["httpStatus","statusCode","status"]),e)??dt(o,e);if(g!==void 0)y=g,s.httpStatus=F==="details"?"details":"http"}if(c===void 0){let g=J(u(o,["requestId","request_id","reqId","traceId"]),e);if(g!==void 0)c=g,s.requestId=F}if(a===void 0){let g=x(k(u(o,["retryAfterMs","retry_after_ms","retryAfter"]),e));if(g!==void 0)a=g,s.retryAfterMs=F}if(h===void 0){let g=k(o.attempt,e);if(g!==void 0&&g>0)h=g,s.attempt=F}};if(t instanceof K){if(r=t.code,s.code="input",A(t),e==="compat"&&w(t.details))C(t.details,"details")}else if(w(t)){let o=ht(u(t,["code","errorCode","resultCode"]));if(o!==void 0)r=o,s.code="input";else if(y===void 0){let F=k(u(t,["httpStatus","statusCode","status"]),e)??dt(t,e);if(F!==void 0&&F>=500)r="PROVIDER_ERROR",s.code="http"}if(C(t,"input"),e==="compat"&&w(t.details))C(t.details,"details")}if(d===void 0){let o=Jt(t,e);if(o!==void 0)d=o,s.causeChain="input"}if(n.attempt!==void 0&&k(n.attempt,e)!==void 0){let o=k(n.attempt,e);if(o!==void 0&&o>0)h=o,s.attempt="input"}let b=new K(r,Wt(t),void 0,{providerErrorCode:p,providerErrorText:f,httpStatus:y,requestId:c,retryAfterMs:a,attempt:h,causeChain:d}),l=O.classifyForRetry(b,n.policy);return{code:r,classification:l,...p!==void 0?{providerErrorCode:p}:{},...f!==void 0?{providerErrorText:f}:{},...y!==void 0?{httpStatus:y}:{},...c!==void 0?{requestId:c}:{},...a!==void 0?{retryAfterMs:a}:{},...h!==void 0?{attempt:h}:{},...d!==void 0?{causeChain:d}:{},sources:s}}var O={isRetryable(t,n={}){return O.classifyForRetry(t,n)==="retryable"},classifyForRetry(t,n={}){if(t instanceof K){if(new Set(n.retryableCodes??Array.from(yt)).has(t.code))return"retryable";if(new Set(n.nonRetryableCodes??Array.from(ft)).has(t.code))return"non_retryable";if(t.httpStatus!==void 0)return ct(t.httpStatus);let y=ot(t.message);if(y)return y;if(n.classifyByMessage&&t.message){let c=n.classifyByMessage(t.message);if(c)return c}if(n.fallback)return n.fallback;return"non_retryable"}let e=t&&typeof t==="object"?t:void 0,i=G(e?.status)??G(e?.statusCode)??G(e?.code),r=P(e?.status)??P(e?.statusCode)??P(e?.httpStatus);if(typeof i==="string"&&i.startsWith("5"))return"retryable";if(r!==void 0){if(n.classifyByStatusCode)return n.classifyByStatusCode(r);return ct(r)}let s=typeof e?.message==="string"?ot(e.message):void 0;if(s)return s;if(n.classifyByMessage&&typeof e?.message==="string"){let p=n.classifyByMessage(e.message);if(p)return p}return n.fallback??"non_retryable"},resolveRetryAfterMs(t,n){if(n?.retryAfterMs){let e=n.retryAfterMs(t),i=x(e);if(i!==void 0)return i}if(t.retryAfterMs!==void 0)return x(t.retryAfterMs);if(t.code==="RATE_LIMIT_EXCEEDED"&&t.retryAfterMs===void 0)return;return},isUnknownStatus:(t)=>{if(t===void 0||Number.isNaN(t)||!Number.isFinite(t))return!1;return t<500},toRetryMetadata(t){return{providerErrorCode:t.providerErrorCode,providerErrorText:t.providerErrorText,httpStatus:t.httpStatus,requestId:t.requestId,retryAfterMs:t.retryAfterMs,attempt:t.attempt,causeChain:t.causeChain}},withAttempt(t,n){return new K(t.code,t.message,t.details,{...O.toRetryMetadata(t),attempt:P(n)})},DEFAULT_RETRYABLE_ERROR_CODES:yt,DEFAULT_NON_RETRYABLE_ERROR_CODES:ft};function jt(t){switch(t){case"config":return"CRYPTO_CONFIG_ERROR";case"encrypt":return"CRYPTO_ENCRYPT_FAILED";case"decrypt":return"CRYPTO_DECRYPT_FAILED";case"hash":return"CRYPTO_HASH_FAILED";case"policy":return"CRYPTO_POLICY_VIOLATION"}}class M extends K{kind;fieldPath;failMode;openFallback;constructor(t,n,e,i={}){super(jt(t),n,e,i);this.name="FieldCryptoError",this.kind=t,this.fieldPath=typeof i.fieldPath==="string"?i.fieldPath:void 0,this.failMode=i.failMode,this.openFallback=i.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}var Qt=["tenantId","providerId","messageId"];function _(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Zt(t){if(typeof t!=="number"||!Number.isFinite(t))return;if(t<=0||t>100)return;return t}function Ct(t){let n=[];for(let e of t){let i=_(e.kid),r=Zt(e.percentage);if(!i||r===void 0)continue;n.push({kid:i,percentage:r})}return n}function Lt(t,n,e){let i=n.map((r)=>{let s=t[r];return typeof s==="string"?s:""}).join("|");return`${e}::${i}`}function Xt(t){let n=2166136261;for(let e=0;e<t.length;e+=1)n^=t.charCodeAt(e),n=n*16777619>>>0;return n>>>0}function zt(t,n){let e=0;for(let i of t)if(e+=i.percentage,n<e)return i.kid;return}function N(t,n,e){let i=Ct(n.buckets),r=_(n.defaultKid)??_(e);if(i.length===0)return r;let s=_(n.seed)??"kmsg-rollout-v1",p=n.stickyFields??Qt,f=Lt(t,p,s),y=Xt(f)%100;return zt(i,y)??r}function W(t){return Ct(t.buckets).map((n)=>n.kid)}function E(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Y(t){if(!Array.isArray(t))return[];return t.map((n)=>E(n)).filter((n)=>Boolean(n))}function j(t){let n=[],e=new Set;for(let i of t){let r=E(i);if(!r||e.has(r))continue;e.add(r),n.push(r)}return n}function tn(t){return E(t.providerId)??"default"}function Q(t){let n=E(t.activeKid)??"default",e=j([n,...Y(t.decryptKids)]);return{async resolveEncryptKey(){return{kid:n}},async resolveDecryptKeys(){return e}}}function v(t){let n=typeof t.cacheTtlMs==="number"&&t.cacheTtlMs>=0?Math.trunc(t.cacheTtlMs):30000,e=E(t.fallback?.activeKid),i=Y(t.fallback?.decryptKids),r;async function s(p){let f=Date.now();if(r&&f<r.expiresAt)return r.value;let y=await t.provider.loadKeySet(p),c=E(y.activeKid)??e??tn(p),a=j([c,...Y(y.decryptKids),...i]),h={activeKid:c,decryptKids:a,refreshedAt:Date.now()};return r={value:h,expiresAt:Date.now()+n},h}return{async resolveEncryptKey(p){return{kid:(await s(p)).activeKid}},async resolveDecryptKeys(p){let f=await s(p);return f.decryptKids??[f.activeKid]}}}function nn(t,n){return{async resolveEncryptKey(e){let i=await t.resolveEncryptKey(e);return{kid:N(e,n,i.kid)??i.kid}},async resolveDecryptKeys(e){let i=await t.resolveEncryptKey(e),r=t.resolveDecryptKeys?await t.resolveDecryptKeys(e):[i.kid],s=N(e,n,i.kid),p=W(n);return j([...s?[s]:[],i.kid,...r??[],...p])}}}function en(t){return v({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.keyAlias?{keyAlias:t.keyAlias}:{},...t.region?{region:t.region}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function I(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Ft(t,n){return I(t[n])}function sn(t,n){if(!t)return[];return t.split(n).map((e)=>I(e)).filter((e)=>Boolean(e))}function rn(t={}){let n=t.env??(typeof process<"u"?process.env:{}),e=I(t.delimiter)??",",i=t.activeKidEnv??"KMSG_ACTIVE_KID",r=t.decryptKidsEnv??"KMSG_DECRYPT_KIDS",s=Ft(n,i)??I(t.fallbackActiveKid)??"default",p=[s,...sn(Ft(n,r),e),...t.fallbackDecryptKids??[]];return Q({activeKid:s,decryptKids:p})}function pn(t){return v({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.mountPath?{mountPath:t.mountPath}:{},...t.keyName?{keyName:t.keyName}:{},...t.namespace?{namespace:t.namespace}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function Z(t){return typeof t==="function"}function At(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function L(t,n,e){let i=t.fields[n];if(i)return i;if(n.startsWith("metadata.")){let r=t.fields["metadata.*"];if(r)return r}return e}function Pt(t,n={}){let e=[];if(!t||typeof t!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!t.provider||typeof t.provider!=="object")e.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!Z(t.provider.encrypt))e.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!Z(t.provider.decrypt))e.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!Z(t.provider.hash))e.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!t.fields||typeof t.fields!=="object")e.push({message:"fieldCrypto.fields must be an object",rule:"fieldCrypto.fields.object",path:"fields",hint:"Define policies such as to, from, metadata.phoneNumber"});else{let s=Object.entries(t.fields);if(s.length===0)e.push({message:"fieldCrypto.fields must not be empty",rule:"fieldCrypto.fields.non_empty",path:"fields",hint:"Add at least one field mode mapping"});for(let[p,f]of s){if(!At(p))e.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(f!=="plain"&&f!=="encrypt"&&f!=="encrypt+hash"&&f!=="mask")e.push({message:`unsupported field mode: ${String(f)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${p}`})}}let i=t.failMode??"closed",r=t.openFallback??"masked";if(i==="open"&&r==="plaintext"&&t.unsafeAllowPlaintextStorage!==!0)e.push({message:"openFallback=plaintext requires unsafeAllowPlaintextStorage=true",rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback",hint:"Use masked/null fallback, or explicitly enable unsafe plaintext"});if(Array.isArray(t.aadFields)){if(t.aadFields.length===0)e.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let s=0;s<t.aadFields.length;s+=1){let p=t.aadFields[s];if(!At(p))e.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${s}]`})}}if(n.secureMode&&!n.compatPlainColumns){let s=L(t,"to","encrypt+hash"),p=L(t,"from","encrypt+hash");if(s==="plain")e.push({message:"secure mode requires non-plain policy for `to` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.to_non_plain",path:"fields.to",hint:"Use encrypt+hash for lookup fields"});if(p==="plain")e.push({message:"secure mode requires non-plain policy for `from` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.from_non_plain",path:"fields.from",hint:"Use encrypt+hash for lookup fields"})}return{valid:e.length===0,issues:e}}function yn(t,n={}){let e=Pt(t,n);if(e.valid)return;let i=e.issues[0];if(!i)throw new M("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:e.issues});throw new M("config",i.message,{rule:i.rule,path:i.path,hint:i.hint,issues:e.issues},{fieldPath:i.path})}function U(t){let n=t instanceof Uint8Array?t:new Uint8Array(t),e=typeof globalThis<"u"?globalThis.Buffer:void 0;return(e?e.from(n).toString("base64"):btoa(String.fromCharCode(...n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function B(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),e=n.length%4===0?n:`${n}${"=".repeat(4-n.length%4)}`,i=typeof globalThis<"u"?globalThis.Buffer:void 0;if(i)return new Uint8Array(i.from(e,"base64"));let r=atob(e),s=new Uint8Array(r.length);for(let p=0;p<r.length;p+=1)s[p]=r.charCodeAt(p);return s}function wt(t,n){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(n==="base64url")return B(t);return new TextEncoder().encode(t)}function fn(t){let n=t instanceof Uint8Array?t:new Uint8Array(t);return Array.from(n).map((e)=>e.toString(16).padStart(2,"0")).join("")}function S(t){let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function St(t){let n=JSON.parse(t);if(!n||typeof n!=="object"||typeof n.v!=="number"||typeof n.alg!=="string"||typeof n.kid!=="string"||typeof n.iv!=="string"||typeof n.tag!=="string"||typeof n.ct!=="string")throw Error("Invalid ciphertext envelope");return n}function cn(t){if(typeof t==="string")return t;return JSON.stringify(t)}function on(t){if(!t||typeof t!=="object")return!1;let n=t;return typeof n.v==="number"&&typeof n.alg==="string"&&typeof n.kid==="string"&&typeof n.iv==="string"&&typeof n.tag==="string"&&typeof n.ct==="string"}function bt(t){let n=String(t??"").trim();if(n.length===0)return"";let e=n.startsWith("+"),i=n.replace(/\D/g,"");return e?`+${i}`:i}function X(t=3,n=2){return(e)=>{let i=String(e??"");if(i.length<=t+n)return"*".repeat(Math.max(0,i.length));let r=i.slice(0,t),s=i.slice(-n);return`${r}${"*".repeat(i.length-t-n)}${s}`}}function an(t){let n=t.algorithm??"A256GCM",e=t.keyEncoding??"base64url",i=t.hashKeyEncoding??e,r=new Map,s=new Map,p=(y)=>{let c=r.get(y);if(c)return c;let a=t.keys[y];if(!a)throw Error(`Unknown encryption key id: ${y}`);let h=wt(a,e),d=crypto.subtle.importKey("raw",S(h),"AES-GCM",!1,["encrypt","decrypt"]);return r.set(y,d),d},f=(y)=>{let c=s.get(y);if(c)return c;let a=t.hashKeys?.[y]??t.keys[y];if(!a)throw Error(`Unknown hash key id: ${y}`);let h=wt(a,i),d=crypto.subtle.importKey("raw",S(h),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return s.set(y,d),d};return{async encrypt(y){let c=y.kid??t.activeKid,a=await p(c),h=crypto.getRandomValues(new Uint8Array(12)),d=new TextEncoder().encode(JSON.stringify(y.aad??{})),A=new TextEncoder().encode(y.value),C=await crypto.subtle.encrypt({name:"AES-GCM",iv:S(h),additionalData:S(d),tagLength:128},a,S(A)),b=new Uint8Array(C),l=b.slice(b.length-16),o=b.slice(0,b.length-16);return{ciphertext:{v:1,alg:n,kid:c,iv:U(h),tag:U(l),ct:U(o)},kid:c}},async decrypt(y){let c=St(y.ciphertext),a=y.candidateKids&&y.candidateKids.length>0?y.candidateKids:[c.kid],h=B(c.iv),d=B(c.tag),A=B(c.ct),C=new Uint8Array(A.length+d.length);C.set(A,0),C.set(d,A.length);let b=new TextEncoder().encode(JSON.stringify(y.aad??{})),l;for(let o of a)try{let F=await p(o),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:S(h),additionalData:S(b),tagLength:128},F,S(C));return new TextDecoder().decode(new Uint8Array(g))}catch(F){l=F}throw Error(`Failed to decrypt ciphertext: ${l instanceof Error?l.message:String(l??"unknown")}`)},async hash(y){let c=y.kid??t.activeKid,a=await f(c),h=await crypto.subtle.sign("HMAC",a,S(new TextEncoder().encode(y.value)));return fn(h)},mask(y){return X()(y.value)}}}function dn(){return{encrypt(t){return{ciphertext:JSON.stringify({v:1,alg:"NOOP",kid:"noop",iv:"",tag:"",ct:t.value})}},decrypt(t){try{return St(t.ciphertext).ct}catch{return t.ciphertext}},hash(t){let n=bt(t.value);return U(new TextEncoder().encode(n))},mask(t){return X()(t.value)}}}function ln(t){return cn(t)}var ut;((r)=>{r.DEBUG="DEBUG";r.INFO="INFO";r.WARN="WARN";r.ERROR="ERROR"})(ut||={});var hn=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function gn(t){let n=t.toLowerCase();return hn.some((e)=>n.includes(e.toLowerCase()))}function Kn(t){let n=t.trim();if(n.length<=4)return"***";if(n.includes("@")){let[r,s]=n.split("@");return`${r.slice(0,2)}${"*".repeat(Math.max(1,r.length-2))}@${s}`}let e=n.slice(0,3),i=n.slice(-2);return`${e}${"*".repeat(Math.max(1,n.length-5))}${i}`}function z(t,n){if(n===void 0||n===null)return n;if(gn(t)){if(typeof n==="string")return Kn(n);if(typeof n==="number"||typeof n==="boolean")return"***";if(Array.isArray(n))return"[REDACTED]";if(typeof n==="object")return"[REDACTED]"}if(Array.isArray(n))return n.map((e)=>z(t,e));if(typeof n==="object"){let e={};for(let[i,r]of Object.entries(n))e[i]=z(i,r);return e}return n}function Cn(t){let n={};for(let[e,i]of Object.entries(t))n[e]=z(e,i);return n}class ${config;context;constructor(t={},n={}){this.context=t,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...n}}shouldLog(t){let n=["DEBUG","INFO","WARN","ERROR"];return n.indexOf(t)>=n.indexOf(this.config.level)}formatMessage(t){let n=Cn(t.context);if(this.config.enableJson)return JSON.stringify({level:t.level,message:t.message,timestamp:t.timestamp.toISOString(),context:n,...t.error&&{error:{name:t.error.name,message:t.error.message,stack:t.error.stack}},...t.duration&&{duration:t.duration}});let e=t.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(t.level):t.level,r=Object.keys(n).length>0?` [${Object.entries(n).map(([p,f])=>`${p}=${f}`).join(", ")}]`:"",s=`${e} ${i}${r}: ${t.message}`;if(t.duration!==void 0)s+=` (${t.duration}ms)`;if(t.error)s+=`
2
- ${t.error.stack}`;return s}colorizeLevel(t){if(!this.config.enableColors)return t;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[t]}${t}\x1B[0m`}writeLog(t){if(!this.shouldLog(t.level))return;let n=this.formatMessage(t);if(this.config.enableConsole)(t.level==="ERROR"?console.error:t.level==="WARN"?console.warn:console.log)(n);if(this.config.enableFile&&this.config.filePath);}debug(t,n={}){this.writeLog({level:"DEBUG",message:t,timestamp:new Date,context:{...this.context,...n}})}info(t,n={}){this.writeLog({level:"INFO",message:t,timestamp:new Date,context:{...this.context,...n}})}warn(t,n={},e){this.writeLog({level:"WARN",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}error(t,n={},e){this.writeLog({level:"ERROR",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}child(t){return new $({...this.context,...t},this.config)}time(t){let n=Date.now();return()=>{let e=Date.now()-n;this.info(`${t} completed`,{duration:e})}}async measure(t,n,e={}){let i=Date.now(),r={...e,operation:t};this.debug(`Starting ${t}`,r);try{let s=await n(),p=Date.now()-i;return this.info(`Completed ${t}`,{...r,duration:p}),s}catch(s){let p=Date.now()-i;throw this.error(`Failed ${t}`,{...r,duration:p},s instanceof Error?s:Error(String(s))),s}}}var q;function tt(t,n){return new $(t,n)}function D(){if(!q)q=tt();return q}function Fn(t){q=t}var An={debug:(t,n)=>D().debug(t,n),info:(t,n)=>D().info(t,n),warn:(t,n,e)=>D().warn(t,n,e),error:(t,n,e)=>D().error(t,n,e),child:(t)=>D().child(t),time:(t)=>D().time(t),measure:(t,n,e)=>D().measure(t,n,e)};function Pn(t){let n=tt({},t);return async(e,i)=>{let r=Date.now(),p={requestId:Math.random().toString(36).substring(7),method:e.req.method,path:e.req.path,userAgent:e.req.header("user-agent")||"unknown"};n.info("Request started",p);try{await i();let f=Date.now()-r;n.info("Request completed",{...p,status:e.res.status,duration:f})}catch(f){let y=Date.now()-r;throw n.error("Request failed",{...p,duration:y},f instanceof Error?f:Error(String(f))),f}}}class T{static defaultOptions={maxAttempts:3,initialDelay:1000,maxDelay:30000,backoffMultiplier:2,jitter:!0,retryCondition:(t)=>O.isRetryable(t)};static async execute(t,n={}){let e={...T.defaultOptions,...n},i,r=e.initialDelay;for(let s=1;s<=e.maxAttempts;s++)try{return await t()}catch(p){if(i=p,s===e.maxAttempts||!e.retryCondition(i,s))throw i;let f=e.jitter?r+Math.random()*r*0.1:r;e.onRetry?.(i,s),await new Promise((y)=>setTimeout(y,f)),r=Math.min(r*e.backoffMultiplier,e.maxDelay)}throw i}static createRetryableFunction(t,n={}){return async(...e)=>{return T.execute(()=>t(...e),n)}}}class H{static async execute(t,n,e={}){let i={concurrency:5,retryOptions:{maxAttempts:3,initialDelay:1000,maxDelay:1e4,backoffMultiplier:2,jitter:!0},failFast:!1,...e},r=Date.now(),s=[],p=[],f=0,y=T.createRetryableFunction(n,i.retryOptions),c=H.createBatches(t,i.concurrency);for(let h of c){let d=h.map(async(A)=>{try{let C=await y(A);s.push({item:A,result:C})}catch(C){if(p.push({item:A,error:C}),i.failFast)throw new K("MESSAGE_SEND_FAILED",`Bulk operation failed fast after ${p.length} failures`,{totalItems:t.length,failedCount:p.length})}finally{f++,i.onProgress?.(f,t.length,p.length)}});if(await Promise.allSettled(d),i.failFast&&p.length>0)break}let a=Date.now()-r;return{successful:s,failed:p,summary:{total:t.length,successful:s.length,failed:p.length,duration:a}}}static createBatches(t,n){let e=[];for(let i=0;i<t.length;i+=n)e.push(t.slice(i,i+n));return e}}class nt{options;state="CLOSED";failureCount=0;lastFailureTime=0;nextAttemptTime=0;constructor(t){this.options=t}async execute(t){let n=Date.now();switch(this.state){case"OPEN":if(n<this.nextAttemptTime)throw new K("NETWORK_SERVICE_UNAVAILABLE","Circuit breaker is OPEN",{state:this.state,nextAttemptTime:this.nextAttemptTime});this.state="HALF_OPEN",this.options.onHalfOpen?.();break;case"HALF_OPEN":break;case"CLOSED":break}try{let e=await Promise.race([t(),new Promise((i,r)=>setTimeout(()=>r(new K("NETWORK_TIMEOUT","Circuit breaker timeout",{timeout:this.options.timeout})),this.options.timeout))]);if(this.state==="HALF_OPEN")this.state="CLOSED",this.failureCount=0,this.options.onClose?.();return e}catch(e){throw this.recordFailure(),e}}recordFailure(){if(this.failureCount++,this.lastFailureTime=Date.now(),this.failureCount>=this.options.failureThreshold)this.state="OPEN",this.nextAttemptTime=this.lastFailureTime+this.options.resetTimeout,this.options.onOpen?.()}getState(){return this.state}getFailureCount(){return this.failureCount}reset(){this.state="CLOSED",this.failureCount=0,this.lastFailureTime=0,this.nextAttemptTime=0}}class et{maxRequests;windowMs;requests=[];constructor(t,n){this.maxRequests=t;this.windowMs=n}async acquire(){let t=Date.now();if(this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length>=this.maxRequests){let n=Math.min(...this.requests),e=this.windowMs-(t-n);if(e>0)return await new Promise((i)=>setTimeout(i,e)),this.acquire()}this.requests.push(t)}canMakeRequest(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length<this.maxRequests}getRemainingRequests(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),Math.max(0,this.maxRequests-this.requests.length)}}var it=(t)=>({isSuccess:!0,isFailure:!1,value:t}),st=(t)=>({isSuccess:!1,isFailure:!0,error:t}),wn={map(t,n){if(t.isSuccess)return it(n(t.value));return t},flatMap(t,n){if(t.isSuccess)return n(t.value);return t},mapError(t,n){if(t.isFailure)return st(n(t.error));return t},unwrap(t){if(t.isSuccess)return t.value;throw t.error},unwrapOr(t,n){if(t.isSuccess)return t.value;return n},unwrapOrElse(t,n){if(t.isSuccess)return t.value;return n(t.error)},match(t,n){if(t.isSuccess)return n.ok(t.value);return n.fail(t.error)},async fromPromise(t){try{let n=await t;return it(n)}catch(n){return st(n)}},isOk(t){return t.isSuccess},isFail(t){return t.isFailure},tap(t,n){return n(t),t},tapOk(t,n){if(t.isSuccess)n(t.value);return t},tapErr(t,n){if(t.isFailure)n(t.error);return t},expect(t,n){if(t.isSuccess)return t.value;throw Error(n,{cause:t.error})}};function kt(){let t=globalThis;return t.__K_MSG_ENV__??t.__ENV__??t.process?.env??{}}function Sn(t){let n=kt()[t];if(typeof n==="string")return n;if(n===void 0)return;return String(n)}var Dt=["PENDING","SENT","DELIVERED","FAILED","CANCELLED","UNKNOWN"],mt=["DELIVERED","FAILED","CANCELLED","UNKNOWN"],rt=["PENDING","SENT"],bn=new Set(Dt),Tt=new Set(mt),un=new Set(rt);function kn(t){return bn.has(t)}function Dn(t){return Tt.has(t)}function mn(t){return Tt.has(t)}function Tn(t){return un.has(t)}function On(){return rt}var Ot=["ALIMTALK","FRIENDTALK","SMS","LMS","MMS","NSA","VOICE","FAX","RCS_SMS","RCS_LMS","RCS_MMS","RCS_TPL","RCS_ITPL","RCS_LTPL"],Rn=new Set(Ot);function En(t){return Rn.has(t)}var xn=["PENDING","SENT","FAILED"],Rt="PENDING",Mn=(t)=>{let n=typeof t==="string"?t.trim().toUpperCase():"";if(n==="PENDING"||n==="SENT"||n==="FAILED")return n;return Rt};
1
+ var{defineProperty:V,getOwnPropertyNames:Et,getOwnPropertyDescriptor:xt}=Object,Mt=Object.prototype.hasOwnProperty;function vt(t){return this[t]}var _t=(t)=>{var n=(pt??=new WeakMap).get(t),e;if(n)return n;if(n=V({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function"){for(var i of Et(t))if(!Mt.call(n,i))V(n,i,{get:vt.bind(t,i),enumerable:!(e=xt(t,i))||e.enumerable})}return pt.set(t,n),n},pt;var Nt=(t)=>t;function It(t,n){this[t]=Nt.bind(null,n)}var Ut=(t,n)=>{for(var e in n)V(t,e,{get:n[e],enumerable:!0,configurable:!0,set:It.bind(n,e)})};var vn={};Ut(vn,{validateFieldCryptoConfig:()=>Pt,validateErrorRetryPolicy:()=>gt,toCiphertextEnvelopeString:()=>ln,setGlobalLogger:()=>Fn,selectActiveKidByRollout:()=>N,resolveFieldMode:()=>L,readRuntimeEnv:()=>Sn,parseErrorRetryPolicyFromJson:()=>Gt,ok:()=>it,normalizeRetryAfterMs:()=>x,normalizeProviderError:()=>Yt,normalizePhoneForHash:()=>bt,normalizeMessageStatus:()=>Mn,normalizeErrorRetryPolicy:()=>Kt,loggerMiddleware:()=>Pn,logger:()=>An,isTerminalDeliveryStatus:()=>mn,isPollableDeliveryStatus:()=>Tn,isKMsgTerminalStatus:()=>kn,isKMsgMessageType:()=>En,isKMsgDeliveryStatus:()=>Dn,isCryptoEnvelope:()=>cn,getRuntimeEnvSource:()=>Dt,getRolloutKnownKids:()=>W,getPollableStatuses:()=>On,getLogger:()=>k,fail:()=>st,createVaultTransitKeyResolver:()=>pn,createStaticKeyResolver:()=>Q,createRollingKeyResolver:()=>nn,createRefreshableKeyResolver:()=>v,createNoopFieldCryptoProvider:()=>dn,createLogger:()=>tt,createEnvKeyResolver:()=>rn,createDefaultMasker:()=>X,createAwsKmsKeyResolver:()=>en,createAesGcmFieldCryptoProvider:()=>an,assertFieldCryptoConfig:()=>yn,RetryHandler:()=>T,Result:()=>wn,RateLimiter:()=>et,QUEUED_MESSAGE_STATUS:()=>Rt,Logger:()=>$,LogLevel:()=>ut,KNOWN_MESSAGE_STATUSES:()=>xn,KMsgErrorCode:()=>R,KMsgError:()=>K,KMSG_TERMINAL_STATUSES:()=>mt,KMSG_POLLABLE_STATUSES:()=>rt,KMSG_MESSAGE_TYPES:()=>Ot,KMSG_DELIVERY_STATUSES:()=>kt,FieldCryptoError:()=>M,ErrorUtils:()=>O,CircuitBreaker:()=>nt,BulkOperationHandler:()=>H});module.exports=_t(vn);var R;((l)=>{l.INVALID_REQUEST="INVALID_REQUEST";l.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";l.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";l.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";l.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";l.NETWORK_ERROR="NETWORK_ERROR";l.NETWORK_TIMEOUT="NETWORK_TIMEOUT";l.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";l.PROVIDER_ERROR="PROVIDER_ERROR";l.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";l.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";l.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";l.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";l.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";l.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";l.UNKNOWN_ERROR="UNKNOWN_ERROR"})(R||={});var Bt={["INVALID_REQUEST"]:{ko:"잘못된 요청입니다",en:"Invalid request"},["AUTHENTICATION_FAILED"]:{ko:"인증에 실패했습니다",en:"Authentication failed"},["INSUFFICIENT_BALANCE"]:{ko:"잔액이 부족합니다",en:"Insufficient balance"},["TEMPLATE_NOT_FOUND"]:{ko:"템플릿을 찾을 수 없습니다",en:"Template not found"},["RATE_LIMIT_EXCEEDED"]:{ko:"요청 한도를 초과했습니다",en:"Rate limit exceeded"},["NETWORK_ERROR"]:{ko:"네트워크 오류가 발생했습니다",en:"Network error"},["NETWORK_TIMEOUT"]:{ko:"네트워크 요청 시간이 초과되었습니다",en:"Network timeout"},["NETWORK_SERVICE_UNAVAILABLE"]:{ko:"서비스를 일시적으로 사용할 수 없습니다",en:"Service temporarily unavailable"},["PROVIDER_ERROR"]:{ko:"제공자 오류가 발생했습니다",en:"Provider error"},["MESSAGE_SEND_FAILED"]:{ko:"메시지 전송에 실패했습니다",en:"Message send failed"},["CRYPTO_CONFIG_ERROR"]:{ko:"암호화 설정 오류가 발생했습니다",en:"Crypto configuration error"},["CRYPTO_ENCRYPT_FAILED"]:{ko:"암호화에 실패했습니다",en:"Encryption failed"},["CRYPTO_DECRYPT_FAILED"]:{ko:"복호화에 실패했습니다",en:"Decryption failed"},["CRYPTO_HASH_FAILED"]:{ko:"해시 생성에 실패했습니다",en:"Hash generation failed"},["CRYPTO_POLICY_VIOLATION"]:{ko:"암호화 정책 위반이 발생했습니다",en:"Crypto policy violation"},["UNKNOWN_ERROR"]:{ko:"알 수 없는 오류가 발생했습니다",en:"Unknown error"}},qt=new Set(Object.values(R)),yt=new Set(["NETWORK_ERROR","RATE_LIMIT_EXCEEDED","NETWORK_TIMEOUT","NETWORK_SERVICE_UNAVAILABLE","PROVIDER_ERROR","UNKNOWN_ERROR"]),ft=new Set(["INVALID_REQUEST","AUTHENTICATION_FAILED","INSUFFICIENT_BALANCE","TEMPLATE_NOT_FOUND","MESSAGE_SEND_FAILED","CRYPTO_CONFIG_ERROR","CRYPTO_ENCRYPT_FAILED","CRYPTO_DECRYPT_FAILED","CRYPTO_HASH_FAILED","CRYPTO_POLICY_VIOLATION"]),P=(t)=>{if(typeof t!=="number"||Number.isNaN(t)||!Number.isFinite(t))return;return Math.trunc(t)},x=(t)=>{let n=P(t);if(n===void 0||n<0)return;return n},G=(t)=>{if(typeof t!=="string")return;return t.toLowerCase().trim()},$t=(t)=>{if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0},w=(t)=>{return typeof t==="object"&&t!==null&&!Array.isArray(t)},u=(t,n)=>{for(let e of n)if(e in t)return t[e];return},Ht=(t)=>{return t.length>0?t:"$"},lt=(t)=>{return t==="compat"?"compat":"safe"},ot=(t)=>{if(t>=500)return"retryable";if(t===408||t===425||t===429)return"retryable";return"non_retryable"},ct=(t)=>{let n=t.toLowerCase();if(n.includes("timeout")||n.includes("temporar")||n.includes("network")||n.includes("retry"))return"retryable";return};class K extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(t,n,e,i={}){super(n);if(this.name="KMsgError",this.code=t,this.details=e,this.providerErrorCode=i.providerErrorCode,this.providerErrorText=i.providerErrorText,this.httpStatus=P(i.httpStatus),this.requestId=typeof i.requestId==="string"?i.requestId:void 0,this.retryAfterMs=P(i.retryAfterMs),this.attempt=P(i.attempt),Array.isArray(i.causeChain))this.causeChain=i.causeChain;else if(i.causeChain!==void 0)this.causeChain=[i.causeChain];let r=Error.captureStackTrace;if(r)r(this,K)}getLocalizedMessage(t="ko"){let n=Bt[this.code];if(n?.[t])return n[t];return this.message}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,providerErrorCode:this.providerErrorCode,providerErrorText:this.providerErrorText,httpStatus:this.httpStatus,requestId:this.requestId,retryAfterMs:this.retryAfterMs,attempt:this.attempt,causeChain:this.causeChain}}}var D=(t,n)=>{let e=P(t);if(e!==void 0)return e;if(n==="compat"&&typeof t==="string"){let i=Number(t.trim());if(Number.isFinite(i))return Math.trunc(i)}return},J=(t,n)=>{let e=$t(t);if(e)return e;if(n==="compat"&&(typeof t==="number"||typeof t==="boolean"))return String(t);return},ht=(t)=>{if(typeof t!=="string")return;let n=t.trim().toUpperCase();if(!qt.has(n))return;return n},m=(t,n)=>{t.push({...n,path:Ht(n.path)})},at=(t,n,e,i)=>{if(t===void 0)return[];let r=(()=>{if(Array.isArray(t))return t;if(e==="compat"&&typeof t==="string")return t.split(",").map((f)=>f.trim()).filter((f)=>f.length>0);return m(i,{code:"invalid_type",message:"expected array of KMsgErrorCode values",path:n}),[]})(),s=[],p=new Set;for(let f=0;f<r.length;f+=1){let y=r[f],o=ht(typeof y==="string"?y:e==="compat"?String(y):y);if(!o){m(i,{code:"unknown_code",message:`unknown retry policy code: ${String(y)}`,path:`${n}[${f}]`});continue}if(p.has(o)){m(i,{code:"duplicate_code",message:`duplicate retry policy code: ${o}`,path:`${n}[${f}]`});continue}p.add(o),s.push(o)}return s},Vt=(t,n,e)=>{if(t===void 0)return;if(typeof t==="string"){let i=t.trim().toLowerCase();if(i==="retryable")return"retryable";if(i==="non_retryable"||i==="non-retryable")return"non_retryable"}if(n==="compat"&&typeof t==="boolean")return t?"retryable":"non_retryable";m(e,{code:"invalid_fallback",message:`invalid fallback value: ${String(t)}`,path:"fallback"});return};function gt(t,n={}){let e=lt(n.mode),i=[];if(!w(t))return m(i,{code:"invalid_root",message:"retry policy must be an object",path:"$"}),{policy:null,issues:i};let r=new Set(["retryableCodes","nonRetryableCodes","fallback"]);for(let d of Object.keys(t)){if(r.has(d))continue;m(i,{code:"unknown_field",message:`unknown retry policy field: ${d}`,path:d})}let s=at(t.retryableCodes,"retryableCodes",e,i),p=at(t.nonRetryableCodes,"nonRetryableCodes",e,i),f=Vt(t.fallback,e,i),y=new Set(s),o=new Set(p);for(let d of y){if(!o.has(d))continue;y.delete(d),m(i,{code:"conflicting_code",message:`code '${d}' is both retryable and nonRetryable; nonRetryable wins`,path:"retryableCodes"})}let a={...y.size>0?{retryableCodes:Array.from(y)}:{},...o.size>0?{nonRetryableCodes:Array.from(o)}:{},...f?{fallback:f}:{}};return{policy:a.retryableCodes!==void 0||a.nonRetryableCodes!==void 0||a.fallback!==void 0?a:null,issues:i}}function Kt(t,n={}){return gt(t,n).policy}function Gt(t,n={}){if(typeof t!=="string"||t.trim().length===0)return null;try{let e=JSON.parse(t);return Kt(e,n)}catch{return null}}var dt=(t,n)=>{let e=t.response;if(!w(e))return;return D(u(e,["status","statusCode","httpStatus"]),n)},Jt=(t,n)=>{if(t instanceof K&&Array.isArray(t.causeChain))return t.causeChain.slice();if(w(t)){let s=t.causeChain;if(Array.isArray(s))return s.slice();let p=t.details;if(n==="compat"&&w(p)){let f=p.causeChain;if(Array.isArray(f))return f.slice();if(f!==void 0)return[f]}}let e=[],i=new Set,r=t;for(let s=0;s<8;s+=1){if(!w(r))break;let p=r.cause;if(p===void 0||i.has(p))break;i.add(p),e.push(p),r=p}return e.length>0?e:void 0},Wt=(t)=>{if(t instanceof Error&&typeof t.message==="string")return t.message;if(w(t)&&typeof t.message==="string")return t.message;return typeof t==="string"?t:"Unknown error"};function Yt(t,n={}){let e=lt(n.mode),r=n.defaultCode??"UNKNOWN_ERROR",s={code:"fallback",classification:n.policy?"policy":"fallback"},p,f,y,o,a,h,d,A=(c)=>{if(c.providerErrorCode!==void 0)p=c.providerErrorCode,s.providerErrorCode="metadata";if(c.providerErrorText!==void 0)f=c.providerErrorText,s.providerErrorText="metadata";if(c.httpStatus!==void 0)y=c.httpStatus,s.httpStatus="metadata";if(c.requestId!==void 0)o=c.requestId,s.requestId="metadata";if(c.retryAfterMs!==void 0)a=x(c.retryAfterMs),s.retryAfterMs="metadata";if(c.attempt!==void 0)h=D(c.attempt,e),s.attempt="metadata";if(Array.isArray(c.causeChain))d=c.causeChain.slice(),s.causeChain="metadata"},C=(c,F)=>{if(p===void 0){let g=J(u(c,["providerErrorCode","errorCode","resultCode"]),e);if(g!==void 0)p=g,s.providerErrorCode=F}if(f===void 0){let g=J(u(c,["providerErrorText","errorMessage","msg","message"]),e);if(g!==void 0)f=g,s.providerErrorText=F}if(y===void 0){let g=D(u(c,["httpStatus","statusCode","status"]),e)??dt(c,e);if(g!==void 0)y=g,s.httpStatus=F==="details"?"details":"http"}if(o===void 0){let g=J(u(c,["requestId","request_id","reqId","traceId"]),e);if(g!==void 0)o=g,s.requestId=F}if(a===void 0){let g=x(D(u(c,["retryAfterMs","retry_after_ms","retryAfter"]),e));if(g!==void 0)a=g,s.retryAfterMs=F}if(h===void 0){let g=D(c.attempt,e);if(g!==void 0&&g>0)h=g,s.attempt=F}};if(t instanceof K){if(r=t.code,s.code="input",A(t),e==="compat"&&w(t.details))C(t.details,"details")}else if(w(t)){let c=ht(u(t,["code","errorCode","resultCode"]));if(c!==void 0)r=c,s.code="input";else if(y===void 0){let F=D(u(t,["httpStatus","statusCode","status"]),e)??dt(t,e);if(F!==void 0&&F>=500)r="PROVIDER_ERROR",s.code="http"}if(C(t,"input"),e==="compat"&&w(t.details))C(t.details,"details")}if(d===void 0){let c=Jt(t,e);if(c!==void 0)d=c,s.causeChain="input"}if(n.attempt!==void 0&&D(n.attempt,e)!==void 0){let c=D(n.attempt,e);if(c!==void 0&&c>0)h=c,s.attempt="input"}let b=new K(r,Wt(t),void 0,{providerErrorCode:p,providerErrorText:f,httpStatus:y,requestId:o,retryAfterMs:a,attempt:h,causeChain:d}),l=O.classifyForRetry(b,n.policy);return{code:r,classification:l,...p!==void 0?{providerErrorCode:p}:{},...f!==void 0?{providerErrorText:f}:{},...y!==void 0?{httpStatus:y}:{},...o!==void 0?{requestId:o}:{},...a!==void 0?{retryAfterMs:a}:{},...h!==void 0?{attempt:h}:{},...d!==void 0?{causeChain:d}:{},sources:s}}var O={isRetryable(t,n={}){return O.classifyForRetry(t,n)==="retryable"},classifyForRetry(t,n={}){if(t instanceof K){if(new Set(n.retryableCodes??Array.from(yt)).has(t.code))return"retryable";if(new Set(n.nonRetryableCodes??Array.from(ft)).has(t.code))return"non_retryable";if(t.httpStatus!==void 0)return ot(t.httpStatus);let y=ct(t.message);if(y)return y;if(n.classifyByMessage&&t.message){let o=n.classifyByMessage(t.message);if(o)return o}if(n.fallback)return n.fallback;return"non_retryable"}let e=t&&typeof t==="object"?t:void 0,i=G(e?.status)??G(e?.statusCode)??G(e?.code),r=P(e?.status)??P(e?.statusCode)??P(e?.httpStatus);if(typeof i==="string"&&i.startsWith("5"))return"retryable";if(r!==void 0){if(n.classifyByStatusCode)return n.classifyByStatusCode(r);return ot(r)}let s=typeof e?.message==="string"?ct(e.message):void 0;if(s)return s;if(n.classifyByMessage&&typeof e?.message==="string"){let p=n.classifyByMessage(e.message);if(p)return p}return n.fallback??"non_retryable"},resolveRetryAfterMs(t,n){if(n?.retryAfterMs){let e=n.retryAfterMs(t),i=x(e);if(i!==void 0)return i}if(t.retryAfterMs!==void 0)return x(t.retryAfterMs);if(t.code==="RATE_LIMIT_EXCEEDED"&&t.retryAfterMs===void 0)return;return},isUnknownStatus:(t)=>{if(t===void 0||Number.isNaN(t)||!Number.isFinite(t))return!1;return t<500},toRetryMetadata(t){return{providerErrorCode:t.providerErrorCode,providerErrorText:t.providerErrorText,httpStatus:t.httpStatus,requestId:t.requestId,retryAfterMs:t.retryAfterMs,attempt:t.attempt,causeChain:t.causeChain}},withAttempt(t,n){return new K(t.code,t.message,t.details,{...O.toRetryMetadata(t),attempt:P(n)})},DEFAULT_RETRYABLE_ERROR_CODES:yt,DEFAULT_NON_RETRYABLE_ERROR_CODES:ft};function jt(t){switch(t){case"config":return"CRYPTO_CONFIG_ERROR";case"encrypt":return"CRYPTO_ENCRYPT_FAILED";case"decrypt":return"CRYPTO_DECRYPT_FAILED";case"hash":return"CRYPTO_HASH_FAILED";case"policy":return"CRYPTO_POLICY_VIOLATION"}}class M extends K{kind;fieldPath;failMode;openFallback;constructor(t,n,e,i={}){super(jt(t),n,e,i);this.name="FieldCryptoError",this.kind=t,this.fieldPath=typeof i.fieldPath==="string"?i.fieldPath:void 0,this.failMode=i.failMode,this.openFallback=i.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}var Qt=["tenantId","providerId","messageId"];function _(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Zt(t){if(typeof t!=="number"||!Number.isFinite(t))return;if(t<=0||t>100)return;return t}function Ct(t){let n=[];for(let e of t){let i=_(e.kid),r=Zt(e.percentage);if(!i||r===void 0)continue;n.push({kid:i,percentage:r})}return n}function Lt(t,n,e){let i=n.map((r)=>{let s=t[r];return typeof s==="string"?s:""}).join("|");return`${e}::${i}`}function Xt(t){let n=2166136261;for(let e=0;e<t.length;e+=1)n^=t.charCodeAt(e),n=n*16777619>>>0;return n>>>0}function zt(t,n){let e=0;for(let i of t)if(e+=i.percentage,n<e)return i.kid;return}function N(t,n,e){let i=Ct(n.buckets),r=_(n.defaultKid)??_(e);if(i.length===0)return r;let s=_(n.seed)??"kmsg-rollout-v1",p=n.stickyFields??Qt,f=Lt(t,p,s),y=Xt(f)%100;return zt(i,y)??r}function W(t){return Ct(t.buckets).map((n)=>n.kid)}function E(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Y(t){if(!Array.isArray(t))return[];return t.map((n)=>E(n)).filter((n)=>Boolean(n))}function j(t){let n=[],e=new Set;for(let i of t){let r=E(i);if(!r||e.has(r))continue;e.add(r),n.push(r)}return n}function tn(t){return E(t.providerId)??"default"}function Q(t){let n=E(t.activeKid)??"default",e=j([n,...Y(t.decryptKids)]);return{async resolveEncryptKey(){return{kid:n}},async resolveDecryptKeys(){return e}}}function v(t){let n=typeof t.cacheTtlMs==="number"&&t.cacheTtlMs>=0?Math.trunc(t.cacheTtlMs):30000,e=E(t.fallback?.activeKid),i=Y(t.fallback?.decryptKids),r;async function s(p){let f=Date.now();if(r&&f<r.expiresAt)return r.value;let y=await t.provider.loadKeySet(p),o=E(y.activeKid)??e??tn(p),a=j([o,...Y(y.decryptKids),...i]),h={activeKid:o,decryptKids:a,refreshedAt:Date.now()};return r={value:h,expiresAt:Date.now()+n},h}return{async resolveEncryptKey(p){return{kid:(await s(p)).activeKid}},async resolveDecryptKeys(p){let f=await s(p);return f.decryptKids??[f.activeKid]}}}function nn(t,n){return{async resolveEncryptKey(e){let i=await t.resolveEncryptKey(e);return{kid:N(e,n,i.kid)??i.kid}},async resolveDecryptKeys(e){let i=await t.resolveEncryptKey(e),r=t.resolveDecryptKeys?await t.resolveDecryptKeys(e):[i.kid],s=N(e,n,i.kid),p=W(n);return j([...s?[s]:[],i.kid,...r??[],...p])}}}function en(t){return v({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.keyAlias?{keyAlias:t.keyAlias}:{},...t.region?{region:t.region}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function I(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Ft(t,n){return I(t[n])}function sn(t,n){if(!t)return[];return t.split(n).map((e)=>I(e)).filter((e)=>Boolean(e))}function rn(t={}){let n=globalThis.process?.env,e=t.env??n??{},i=I(t.delimiter)??",",r=t.activeKidEnv??"KMSG_ACTIVE_KID",s=t.decryptKidsEnv??"KMSG_DECRYPT_KIDS",p=Ft(e,r)??I(t.fallbackActiveKid)??"default",f=[p,...sn(Ft(e,s),i),...t.fallbackDecryptKids??[]];return Q({activeKid:p,decryptKids:f})}function pn(t){return v({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.mountPath?{mountPath:t.mountPath}:{},...t.keyName?{keyName:t.keyName}:{},...t.namespace?{namespace:t.namespace}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function Z(t){return typeof t==="function"}function At(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function L(t,n,e){let i=t.fields[n];if(i)return i;if(n.startsWith("metadata.")){let r=t.fields["metadata.*"];if(r)return r}return e}function Pt(t,n={}){let e=[];if(!t||typeof t!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!t.provider||typeof t.provider!=="object")e.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!Z(t.provider.encrypt))e.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!Z(t.provider.decrypt))e.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!Z(t.provider.hash))e.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!t.fields||typeof t.fields!=="object")e.push({message:"fieldCrypto.fields must be an object",rule:"fieldCrypto.fields.object",path:"fields",hint:"Define policies such as to, from, metadata.phoneNumber"});else{let s=Object.entries(t.fields);if(s.length===0)e.push({message:"fieldCrypto.fields must not be empty",rule:"fieldCrypto.fields.non_empty",path:"fields",hint:"Add at least one field mode mapping"});for(let[p,f]of s){if(!At(p))e.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(f!=="plain"&&f!=="encrypt"&&f!=="encrypt+hash"&&f!=="mask")e.push({message:`unsupported field mode: ${String(f)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${p}`})}}let i=t.failMode??"closed",r=t.openFallback??"masked";if(i==="open"&&r==="plaintext"&&t.unsafeAllowPlaintextStorage!==!0)e.push({message:"openFallback=plaintext requires unsafeAllowPlaintextStorage=true",rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback",hint:"Use masked/null fallback, or explicitly enable unsafe plaintext"});if(Array.isArray(t.aadFields)){if(t.aadFields.length===0)e.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let s=0;s<t.aadFields.length;s+=1){let p=t.aadFields[s];if(!At(p))e.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${s}]`})}}if(n.secureMode&&!n.compatPlainColumns){let s=L(t,"to","encrypt+hash"),p=L(t,"from","encrypt+hash");if(s==="plain")e.push({message:"secure mode requires non-plain policy for `to` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.to_non_plain",path:"fields.to",hint:"Use encrypt+hash for lookup fields"});if(p==="plain")e.push({message:"secure mode requires non-plain policy for `from` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.from_non_plain",path:"fields.from",hint:"Use encrypt+hash for lookup fields"})}return{valid:e.length===0,issues:e}}function yn(t,n={}){let e=Pt(t,n);if(e.valid)return;let i=e.issues[0];if(!i)throw new M("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:e.issues});throw new M("config",i.message,{rule:i.rule,path:i.path,hint:i.hint,issues:e.issues},{fieldPath:i.path})}function U(t){let n=t instanceof Uint8Array?t:new Uint8Array(t),e=typeof globalThis<"u"?globalThis.Buffer:void 0;return(e?e.from(n).toString("base64"):btoa(String.fromCharCode(...n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function B(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),e=n.length%4===0?n:`${n}${"=".repeat(4-n.length%4)}`,i=typeof globalThis<"u"?globalThis.Buffer:void 0;if(i)return new Uint8Array(i.from(e,"base64"));let r=atob(e),s=new Uint8Array(r.length);for(let p=0;p<r.length;p+=1)s[p]=r.charCodeAt(p);return s}function wt(t,n){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(n==="base64url")return B(t);return new TextEncoder().encode(t)}function fn(t){let n=t instanceof Uint8Array?t:new Uint8Array(t);return Array.from(n).map((e)=>e.toString(16).padStart(2,"0")).join("")}function S(t){let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function St(t){let n=JSON.parse(t);if(!n||typeof n!=="object"||typeof n.v!=="number"||typeof n.alg!=="string"||typeof n.kid!=="string"||typeof n.iv!=="string"||typeof n.tag!=="string"||typeof n.ct!=="string")throw Error("Invalid ciphertext envelope");return n}function on(t){if(typeof t==="string")return t;return JSON.stringify(t)}function cn(t){if(!t||typeof t!=="object")return!1;let n=t;return typeof n.v==="number"&&typeof n.alg==="string"&&typeof n.kid==="string"&&typeof n.iv==="string"&&typeof n.tag==="string"&&typeof n.ct==="string"}function bt(t){let n=String(t??"").trim();if(n.length===0)return"";let e=n.startsWith("+"),i=n.replace(/\D/g,"");return e?`+${i}`:i}function X(t=3,n=2){return(e)=>{let i=String(e??"");if(i.length<=t+n)return"*".repeat(Math.max(0,i.length));let r=i.slice(0,t),s=i.slice(-n);return`${r}${"*".repeat(i.length-t-n)}${s}`}}function an(t){let n=t.algorithm??"A256GCM",e=t.keyEncoding??"base64url",i=t.hashKeyEncoding??e,r=new Map,s=new Map,p=(y)=>{let o=r.get(y);if(o)return o;let a=t.keys[y];if(!a)throw Error(`Unknown encryption key id: ${y}`);let h=wt(a,e),d=crypto.subtle.importKey("raw",S(h),"AES-GCM",!1,["encrypt","decrypt"]);return r.set(y,d),d},f=(y)=>{let o=s.get(y);if(o)return o;let a=t.hashKeys?.[y]??t.keys[y];if(!a)throw Error(`Unknown hash key id: ${y}`);let h=wt(a,i),d=crypto.subtle.importKey("raw",S(h),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return s.set(y,d),d};return{async encrypt(y){let o=y.kid??t.activeKid,a=await p(o),h=crypto.getRandomValues(new Uint8Array(12)),d=new TextEncoder().encode(JSON.stringify(y.aad??{})),A=new TextEncoder().encode(y.value),C=await crypto.subtle.encrypt({name:"AES-GCM",iv:S(h),additionalData:S(d),tagLength:128},a,S(A)),b=new Uint8Array(C),l=b.slice(b.length-16),c=b.slice(0,b.length-16);return{ciphertext:{v:1,alg:n,kid:o,iv:U(h),tag:U(l),ct:U(c)},kid:o}},async decrypt(y){let o=St(y.ciphertext),a=y.candidateKids&&y.candidateKids.length>0?y.candidateKids:[o.kid],h=B(o.iv),d=B(o.tag),A=B(o.ct),C=new Uint8Array(A.length+d.length);C.set(A,0),C.set(d,A.length);let b=new TextEncoder().encode(JSON.stringify(y.aad??{})),l;for(let c of a)try{let F=await p(c),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:S(h),additionalData:S(b),tagLength:128},F,S(C));return new TextDecoder().decode(new Uint8Array(g))}catch(F){l=F}throw Error(`Failed to decrypt ciphertext: ${l instanceof Error?l.message:String(l??"unknown")}`)},async hash(y){let o=y.kid??t.activeKid,a=await f(o),h=await crypto.subtle.sign("HMAC",a,S(new TextEncoder().encode(y.value)));return fn(h)},mask(y){return X()(y.value)}}}function dn(){return{encrypt(t){return{ciphertext:JSON.stringify({v:1,alg:"NOOP",kid:"noop",iv:"",tag:"",ct:t.value})}},decrypt(t){try{return St(t.ciphertext).ct}catch{return t.ciphertext}},hash(t){let n=bt(t.value);return U(new TextEncoder().encode(n))},mask(t){return X()(t.value)}}}function ln(t){return on(t)}var ut;((r)=>{r.DEBUG="DEBUG";r.INFO="INFO";r.WARN="WARN";r.ERROR="ERROR"})(ut||={});var hn=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function gn(t){let n=t.toLowerCase();return hn.some((e)=>n.includes(e.toLowerCase()))}function Kn(t){let n=t.trim();if(n.length<=4)return"***";if(n.includes("@")){let[r,s]=n.split("@");return`${r.slice(0,2)}${"*".repeat(Math.max(1,r.length-2))}@${s}`}let e=n.slice(0,3),i=n.slice(-2);return`${e}${"*".repeat(Math.max(1,n.length-5))}${i}`}function z(t,n){if(n===void 0||n===null)return n;if(gn(t)){if(typeof n==="string")return Kn(n);if(typeof n==="number"||typeof n==="boolean")return"***";if(Array.isArray(n))return"[REDACTED]";if(typeof n==="object")return"[REDACTED]"}if(Array.isArray(n))return n.map((e)=>z(t,e));if(typeof n==="object"){let e={};for(let[i,r]of Object.entries(n))e[i]=z(i,r);return e}return n}function Cn(t){let n={};for(let[e,i]of Object.entries(t))n[e]=z(e,i);return n}class ${config;context;constructor(t={},n={}){this.context=t,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...n}}shouldLog(t){let n=["DEBUG","INFO","WARN","ERROR"];return n.indexOf(t)>=n.indexOf(this.config.level)}formatMessage(t){let n=Cn(t.context);if(this.config.enableJson)return JSON.stringify({level:t.level,message:t.message,timestamp:t.timestamp.toISOString(),context:n,...t.error&&{error:{name:t.error.name,message:t.error.message,stack:t.error.stack}},...t.duration&&{duration:t.duration}});let e=t.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(t.level):t.level,r=Object.keys(n).length>0?` [${Object.entries(n).map(([p,f])=>`${p}=${f}`).join(", ")}]`:"",s=`${e} ${i}${r}: ${t.message}`;if(t.duration!==void 0)s+=` (${t.duration}ms)`;if(t.error)s+=`
2
+ ${t.error.stack}`;return s}colorizeLevel(t){if(!this.config.enableColors)return t;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[t]}${t}\x1B[0m`}writeLog(t){if(!this.shouldLog(t.level))return;let n=this.formatMessage(t);if(this.config.enableConsole)(t.level==="ERROR"?console.error:t.level==="WARN"?console.warn:console.log)(n);if(this.config.enableFile&&this.config.filePath);}debug(t,n={}){this.writeLog({level:"DEBUG",message:t,timestamp:new Date,context:{...this.context,...n}})}info(t,n={}){this.writeLog({level:"INFO",message:t,timestamp:new Date,context:{...this.context,...n}})}warn(t,n={},e){this.writeLog({level:"WARN",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}error(t,n={},e){this.writeLog({level:"ERROR",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}child(t){return new $({...this.context,...t},this.config)}time(t){let n=Date.now();return()=>{let e=Date.now()-n;this.info(`${t} completed`,{duration:e})}}async measure(t,n,e={}){let i=Date.now(),r={...e,operation:t};this.debug(`Starting ${t}`,r);try{let s=await n(),p=Date.now()-i;return this.info(`Completed ${t}`,{...r,duration:p}),s}catch(s){let p=Date.now()-i;throw this.error(`Failed ${t}`,{...r,duration:p},s instanceof Error?s:Error(String(s))),s}}}var q;function tt(t,n){return new $(t,n)}function k(){if(!q)q=tt();return q}function Fn(t){q=t}var An={debug:(t,n)=>k().debug(t,n),info:(t,n)=>k().info(t,n),warn:(t,n,e)=>k().warn(t,n,e),error:(t,n,e)=>k().error(t,n,e),child:(t)=>k().child(t),time:(t)=>k().time(t),measure:(t,n,e)=>k().measure(t,n,e)};function Pn(t){let n=tt({},t);return async(e,i)=>{let r=Date.now(),p={requestId:Math.random().toString(36).substring(7),method:e.req.method,path:e.req.path,userAgent:e.req.header("user-agent")||"unknown"};n.info("Request started",p);try{await i();let f=Date.now()-r;n.info("Request completed",{...p,status:e.res.status,duration:f})}catch(f){let y=Date.now()-r;throw n.error("Request failed",{...p,duration:y},f instanceof Error?f:Error(String(f))),f}}}class T{static defaultOptions={maxAttempts:3,initialDelay:1000,maxDelay:30000,backoffMultiplier:2,jitter:!0,retryCondition:(t)=>O.isRetryable(t)};static async execute(t,n={}){let e={...T.defaultOptions,...n},i,r=e.initialDelay;for(let s=1;s<=e.maxAttempts;s++)try{return await t()}catch(p){if(i=p,s===e.maxAttempts||!e.retryCondition(i,s))throw i;let f=e.jitter?r+Math.random()*r*0.1:r;e.onRetry?.(i,s),await new Promise((y)=>setTimeout(y,f)),r=Math.min(r*e.backoffMultiplier,e.maxDelay)}throw i}static createRetryableFunction(t,n={}){return async(...e)=>{return T.execute(()=>t(...e),n)}}}class H{static async execute(t,n,e={}){let i={concurrency:5,retryOptions:{maxAttempts:3,initialDelay:1000,maxDelay:1e4,backoffMultiplier:2,jitter:!0},failFast:!1,...e},r=Date.now(),s=[],p=[],f=0,y=T.createRetryableFunction(n,i.retryOptions),o=H.createBatches(t,i.concurrency);for(let h of o){let d=h.map(async(A)=>{try{let C=await y(A);s.push({item:A,result:C})}catch(C){if(p.push({item:A,error:C}),i.failFast)throw new K("MESSAGE_SEND_FAILED",`Bulk operation failed fast after ${p.length} failures`,{totalItems:t.length,failedCount:p.length})}finally{f++,i.onProgress?.(f,t.length,p.length)}});if(await Promise.allSettled(d),i.failFast&&p.length>0)break}let a=Date.now()-r;return{successful:s,failed:p,summary:{total:t.length,successful:s.length,failed:p.length,duration:a}}}static createBatches(t,n){let e=[];for(let i=0;i<t.length;i+=n)e.push(t.slice(i,i+n));return e}}class nt{options;state="CLOSED";failureCount=0;lastFailureTime=0;nextAttemptTime=0;constructor(t){this.options=t}async execute(t){let n=Date.now();switch(this.state){case"OPEN":if(n<this.nextAttemptTime)throw new K("NETWORK_SERVICE_UNAVAILABLE","Circuit breaker is OPEN",{state:this.state,nextAttemptTime:this.nextAttemptTime});this.state="HALF_OPEN",this.options.onHalfOpen?.();break;case"HALF_OPEN":break;case"CLOSED":break}try{let e=await Promise.race([t(),new Promise((i,r)=>setTimeout(()=>r(new K("NETWORK_TIMEOUT","Circuit breaker timeout",{timeout:this.options.timeout})),this.options.timeout))]);if(this.state==="HALF_OPEN")this.state="CLOSED",this.failureCount=0,this.options.onClose?.();return e}catch(e){throw this.recordFailure(),e}}recordFailure(){if(this.failureCount++,this.lastFailureTime=Date.now(),this.failureCount>=this.options.failureThreshold)this.state="OPEN",this.nextAttemptTime=this.lastFailureTime+this.options.resetTimeout,this.options.onOpen?.()}getState(){return this.state}getFailureCount(){return this.failureCount}reset(){this.state="CLOSED",this.failureCount=0,this.lastFailureTime=0,this.nextAttemptTime=0}}class et{maxRequests;windowMs;requests=[];constructor(t,n){this.maxRequests=t;this.windowMs=n}async acquire(){let t=Date.now();if(this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length>=this.maxRequests){let n=Math.min(...this.requests),e=this.windowMs-(t-n);if(e>0)return await new Promise((i)=>setTimeout(i,e)),this.acquire()}this.requests.push(t)}canMakeRequest(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length<this.maxRequests}getRemainingRequests(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),Math.max(0,this.maxRequests-this.requests.length)}}var it=(t)=>({isSuccess:!0,isFailure:!1,value:t}),st=(t)=>({isSuccess:!1,isFailure:!0,error:t}),wn={map(t,n){if(t.isSuccess)return it(n(t.value));return t},flatMap(t,n){if(t.isSuccess)return n(t.value);return t},mapError(t,n){if(t.isFailure)return st(n(t.error));return t},unwrap(t){if(t.isSuccess)return t.value;throw t.error},unwrapOr(t,n){if(t.isSuccess)return t.value;return n},unwrapOrElse(t,n){if(t.isSuccess)return t.value;return n(t.error)},match(t,n){if(t.isSuccess)return n.ok(t.value);return n.fail(t.error)},async fromPromise(t){try{let n=await t;return it(n)}catch(n){return st(n)}},isOk(t){return t.isSuccess},isFail(t){return t.isFailure},tap(t,n){return n(t),t},tapOk(t,n){if(t.isSuccess)n(t.value);return t},tapErr(t,n){if(t.isFailure)n(t.error);return t},expect(t,n){if(t.isSuccess)return t.value;throw Error(n,{cause:t.error})}};function Dt(){let t=globalThis;return t.__K_MSG_ENV__??t.__ENV__??t.process?.env??{}}function Sn(t){let n=Dt()[t];if(typeof n==="string")return n;if(n===void 0)return;return String(n)}var kt=["PENDING","SENT","DELIVERED","FAILED","CANCELLED","UNKNOWN"],mt=["DELIVERED","FAILED","CANCELLED","UNKNOWN"],rt=["PENDING","SENT"],bn=new Set(kt),Tt=new Set(mt),un=new Set(rt);function Dn(t){return bn.has(t)}function kn(t){return Tt.has(t)}function mn(t){return Tt.has(t)}function Tn(t){return un.has(t)}function On(){return rt}var Ot=["ALIMTALK","FRIENDTALK","SMS","LMS","MMS","NSA","VOICE","FAX","RCS_SMS","RCS_LMS","RCS_MMS","RCS_TPL","RCS_ITPL","RCS_LTPL"],Rn=new Set(Ot);function En(t){return Rn.has(t)}var xn=["PENDING","SENT","FAILED"],Rt="PENDING",Mn=(t)=>{let n=typeof t==="string"?t.trim().toUpperCase():"";if(n==="PENDING"||n==="SENT"||n==="FAILED")return n;return Rt};
3
3
 
4
- //# debugId=A10DDBAAE5CA74B864756E2164756E21
4
+ //# debugId=E16D0DFAC995D1EC64756E2164756E21
5
5
  //# sourceMappingURL=index.js.map
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- var E;((l)=>{l.INVALID_REQUEST="INVALID_REQUEST";l.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";l.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";l.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";l.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";l.NETWORK_ERROR="NETWORK_ERROR";l.NETWORK_TIMEOUT="NETWORK_TIMEOUT";l.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";l.PROVIDER_ERROR="PROVIDER_ERROR";l.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";l.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";l.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";l.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";l.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";l.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";l.UNKNOWN_ERROR="UNKNOWN_ERROR"})(E||={});var At={["INVALID_REQUEST"]:{ko:"잘못된 요청입니다",en:"Invalid request"},["AUTHENTICATION_FAILED"]:{ko:"인증에 실패했습니다",en:"Authentication failed"},["INSUFFICIENT_BALANCE"]:{ko:"잔액이 부족합니다",en:"Insufficient balance"},["TEMPLATE_NOT_FOUND"]:{ko:"템플릿을 찾을 수 없습니다",en:"Template not found"},["RATE_LIMIT_EXCEEDED"]:{ko:"요청 한도를 초과했습니다",en:"Rate limit exceeded"},["NETWORK_ERROR"]:{ko:"네트워크 오류가 발생했습니다",en:"Network error"},["NETWORK_TIMEOUT"]:{ko:"네트워크 요청 시간이 초과되었습니다",en:"Network timeout"},["NETWORK_SERVICE_UNAVAILABLE"]:{ko:"서비스를 일시적으로 사용할 수 없습니다",en:"Service temporarily unavailable"},["PROVIDER_ERROR"]:{ko:"제공자 오류가 발생했습니다",en:"Provider error"},["MESSAGE_SEND_FAILED"]:{ko:"메시지 전송에 실패했습니다",en:"Message send failed"},["CRYPTO_CONFIG_ERROR"]:{ko:"암호화 설정 오류가 발생했습니다",en:"Crypto configuration error"},["CRYPTO_ENCRYPT_FAILED"]:{ko:"암호화에 실패했습니다",en:"Encryption failed"},["CRYPTO_DECRYPT_FAILED"]:{ko:"복호화에 실패했습니다",en:"Decryption failed"},["CRYPTO_HASH_FAILED"]:{ko:"해시 생성에 실패했습니다",en:"Hash generation failed"},["CRYPTO_POLICY_VIOLATION"]:{ko:"암호화 정책 위반이 발생했습니다",en:"Crypto policy violation"},["UNKNOWN_ERROR"]:{ko:"알 수 없는 오류가 발생했습니다",en:"Unknown error"}},Pt=new Set(Object.values(E)),Q=new Set(["NETWORK_ERROR","RATE_LIMIT_EXCEEDED","NETWORK_TIMEOUT","NETWORK_SERVICE_UNAVAILABLE","PROVIDER_ERROR","UNKNOWN_ERROR"]),Z=new Set(["INVALID_REQUEST","AUTHENTICATION_FAILED","INSUFFICIENT_BALANCE","TEMPLATE_NOT_FOUND","MESSAGE_SEND_FAILED","CRYPTO_CONFIG_ERROR","CRYPTO_ENCRYPT_FAILED","CRYPTO_DECRYPT_FAILED","CRYPTO_HASH_FAILED","CRYPTO_POLICY_VIOLATION"]),P=(t)=>{if(typeof t!=="number"||Number.isNaN(t)||!Number.isFinite(t))return;return Math.trunc(t)},x=(t)=>{let n=P(t);if(n===void 0||n<0)return;return n},q=(t)=>{if(typeof t!=="string")return;return t.toLowerCase().trim()},wt=(t)=>{if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0},w=(t)=>{return typeof t==="object"&&t!==null&&!Array.isArray(t)},u=(t,n)=>{for(let e of n)if(e in t)return t[e];return},St=(t)=>{return t.length>0?t:"$"},nt=(t)=>{return t==="compat"?"compat":"safe"},L=(t)=>{if(t>=500)return"retryable";if(t===408||t===425||t===429)return"retryable";return"non_retryable"},X=(t)=>{let n=t.toLowerCase();if(n.includes("timeout")||n.includes("temporar")||n.includes("network")||n.includes("retry"))return"retryable";return};class K extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(t,n,e,i={}){super(n);if(this.name="KMsgError",this.code=t,this.details=e,this.providerErrorCode=i.providerErrorCode,this.providerErrorText=i.providerErrorText,this.httpStatus=P(i.httpStatus),this.requestId=typeof i.requestId==="string"?i.requestId:void 0,this.retryAfterMs=P(i.retryAfterMs),this.attempt=P(i.attempt),Array.isArray(i.causeChain))this.causeChain=i.causeChain;else if(i.causeChain!==void 0)this.causeChain=[i.causeChain];if(Error.captureStackTrace)Error.captureStackTrace(this,K)}getLocalizedMessage(t="ko"){let n=At[this.code];if(n?.[t])return n[t];return this.message}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,providerErrorCode:this.providerErrorCode,providerErrorText:this.providerErrorText,httpStatus:this.httpStatus,requestId:this.requestId,retryAfterMs:this.retryAfterMs,attempt:this.attempt,causeChain:this.causeChain}}}var k=(t,n)=>{let e=P(t);if(e!==void 0)return e;if(n==="compat"&&typeof t==="string"){let i=Number(t.trim());if(Number.isFinite(i))return Math.trunc(i)}return},$=(t,n)=>{let e=wt(t);if(e)return e;if(n==="compat"&&(typeof t==="number"||typeof t==="boolean"))return String(t);return},et=(t)=>{if(typeof t!=="string")return;let n=t.trim().toUpperCase();if(!Pt.has(n))return;return n},D=(t,n)=>{t.push({...n,path:St(n.path)})},z=(t,n,e,i)=>{if(t===void 0)return[];let r=(()=>{if(Array.isArray(t))return t;if(e==="compat"&&typeof t==="string")return t.split(",").map((f)=>f.trim()).filter((f)=>f.length>0);return D(i,{code:"invalid_type",message:"expected array of KMsgErrorCode values",path:n}),[]})(),s=[],p=new Set;for(let f=0;f<r.length;f+=1){let y=r[f],c=et(typeof y==="string"?y:e==="compat"?String(y):y);if(!c){D(i,{code:"unknown_code",message:`unknown retry policy code: ${String(y)}`,path:`${n}[${f}]`});continue}if(p.has(c)){D(i,{code:"duplicate_code",message:`duplicate retry policy code: ${c}`,path:`${n}[${f}]`});continue}p.add(c),s.push(c)}return s},bt=(t,n,e)=>{if(t===void 0)return;if(typeof t==="string"){let i=t.trim().toLowerCase();if(i==="retryable")return"retryable";if(i==="non_retryable"||i==="non-retryable")return"non_retryable"}if(n==="compat"&&typeof t==="boolean")return t?"retryable":"non_retryable";D(e,{code:"invalid_fallback",message:`invalid fallback value: ${String(t)}`,path:"fallback"});return};function ut(t,n={}){let e=nt(n.mode),i=[];if(!w(t))return D(i,{code:"invalid_root",message:"retry policy must be an object",path:"$"}),{policy:null,issues:i};let r=new Set(["retryableCodes","nonRetryableCodes","fallback"]);for(let d of Object.keys(t)){if(r.has(d))continue;D(i,{code:"unknown_field",message:`unknown retry policy field: ${d}`,path:d})}let s=z(t.retryableCodes,"retryableCodes",e,i),p=z(t.nonRetryableCodes,"nonRetryableCodes",e,i),f=bt(t.fallback,e,i),y=new Set(s),c=new Set(p);for(let d of y){if(!c.has(d))continue;y.delete(d),D(i,{code:"conflicting_code",message:`code '${d}' is both retryable and nonRetryable; nonRetryable wins`,path:"retryableCodes"})}let a={...y.size>0?{retryableCodes:Array.from(y)}:{},...c.size>0?{nonRetryableCodes:Array.from(c)}:{},...f?{fallback:f}:{}};return{policy:a.retryableCodes!==void 0||a.nonRetryableCodes!==void 0||a.fallback!==void 0?a:null,issues:i}}function kt(t,n={}){return ut(t,n).policy}function zt(t,n={}){if(typeof t!=="string"||t.trim().length===0)return null;try{let e=JSON.parse(t);return kt(e,n)}catch{return null}}var tt=(t,n)=>{let e=t.response;if(!w(e))return;return k(u(e,["status","statusCode","httpStatus"]),n)},Dt=(t,n)=>{if(t instanceof K&&Array.isArray(t.causeChain))return t.causeChain.slice();if(w(t)){let s=t.causeChain;if(Array.isArray(s))return s.slice();let p=t.details;if(n==="compat"&&w(p)){let f=p.causeChain;if(Array.isArray(f))return f.slice();if(f!==void 0)return[f]}}let e=[],i=new Set,r=t;for(let s=0;s<8;s+=1){if(!w(r))break;let p=r.cause;if(p===void 0||i.has(p))break;i.add(p),e.push(p),r=p}return e.length>0?e:void 0},mt=(t)=>{if(t instanceof Error&&typeof t.message==="string")return t.message;if(w(t)&&typeof t.message==="string")return t.message;return typeof t==="string"?t:"Unknown error"};function tn(t,n={}){let e=nt(n.mode),r=n.defaultCode??"UNKNOWN_ERROR",s={code:"fallback",classification:n.policy?"policy":"fallback"},p,f,y,c,a,h,d,A=(o)=>{if(o.providerErrorCode!==void 0)p=o.providerErrorCode,s.providerErrorCode="metadata";if(o.providerErrorText!==void 0)f=o.providerErrorText,s.providerErrorText="metadata";if(o.httpStatus!==void 0)y=o.httpStatus,s.httpStatus="metadata";if(o.requestId!==void 0)c=o.requestId,s.requestId="metadata";if(o.retryAfterMs!==void 0)a=x(o.retryAfterMs),s.retryAfterMs="metadata";if(o.attempt!==void 0)h=k(o.attempt,e),s.attempt="metadata";if(Array.isArray(o.causeChain))d=o.causeChain.slice(),s.causeChain="metadata"},C=(o,F)=>{if(p===void 0){let g=$(u(o,["providerErrorCode","errorCode","resultCode"]),e);if(g!==void 0)p=g,s.providerErrorCode=F}if(f===void 0){let g=$(u(o,["providerErrorText","errorMessage","msg","message"]),e);if(g!==void 0)f=g,s.providerErrorText=F}if(y===void 0){let g=k(u(o,["httpStatus","statusCode","status"]),e)??tt(o,e);if(g!==void 0)y=g,s.httpStatus=F==="details"?"details":"http"}if(c===void 0){let g=$(u(o,["requestId","request_id","reqId","traceId"]),e);if(g!==void 0)c=g,s.requestId=F}if(a===void 0){let g=x(k(u(o,["retryAfterMs","retry_after_ms","retryAfter"]),e));if(g!==void 0)a=g,s.retryAfterMs=F}if(h===void 0){let g=k(o.attempt,e);if(g!==void 0&&g>0)h=g,s.attempt=F}};if(t instanceof K){if(r=t.code,s.code="input",A(t),e==="compat"&&w(t.details))C(t.details,"details")}else if(w(t)){let o=et(u(t,["code","errorCode","resultCode"]));if(o!==void 0)r=o,s.code="input";else if(y===void 0){let F=k(u(t,["httpStatus","statusCode","status"]),e)??tt(t,e);if(F!==void 0&&F>=500)r="PROVIDER_ERROR",s.code="http"}if(C(t,"input"),e==="compat"&&w(t.details))C(t.details,"details")}if(d===void 0){let o=Dt(t,e);if(o!==void 0)d=o,s.causeChain="input"}if(n.attempt!==void 0&&k(n.attempt,e)!==void 0){let o=k(n.attempt,e);if(o!==void 0&&o>0)h=o,s.attempt="input"}let b=new K(r,mt(t),void 0,{providerErrorCode:p,providerErrorText:f,httpStatus:y,requestId:c,retryAfterMs:a,attempt:h,causeChain:d}),l=R.classifyForRetry(b,n.policy);return{code:r,classification:l,...p!==void 0?{providerErrorCode:p}:{},...f!==void 0?{providerErrorText:f}:{},...y!==void 0?{httpStatus:y}:{},...c!==void 0?{requestId:c}:{},...a!==void 0?{retryAfterMs:a}:{},...h!==void 0?{attempt:h}:{},...d!==void 0?{causeChain:d}:{},sources:s}}var R={isRetryable(t,n={}){return R.classifyForRetry(t,n)==="retryable"},classifyForRetry(t,n={}){if(t instanceof K){if(new Set(n.retryableCodes??Array.from(Q)).has(t.code))return"retryable";if(new Set(n.nonRetryableCodes??Array.from(Z)).has(t.code))return"non_retryable";if(t.httpStatus!==void 0)return L(t.httpStatus);let y=X(t.message);if(y)return y;if(n.classifyByMessage&&t.message){let c=n.classifyByMessage(t.message);if(c)return c}if(n.fallback)return n.fallback;return"non_retryable"}let e=t&&typeof t==="object"?t:void 0,i=q(e?.status)??q(e?.statusCode)??q(e?.code),r=P(e?.status)??P(e?.statusCode)??P(e?.httpStatus);if(typeof i==="string"&&i.startsWith("5"))return"retryable";if(r!==void 0){if(n.classifyByStatusCode)return n.classifyByStatusCode(r);return L(r)}let s=typeof e?.message==="string"?X(e.message):void 0;if(s)return s;if(n.classifyByMessage&&typeof e?.message==="string"){let p=n.classifyByMessage(e.message);if(p)return p}return n.fallback??"non_retryable"},resolveRetryAfterMs(t,n){if(n?.retryAfterMs){let e=n.retryAfterMs(t),i=x(e);if(i!==void 0)return i}if(t.retryAfterMs!==void 0)return x(t.retryAfterMs);if(t.code==="RATE_LIMIT_EXCEEDED"&&t.retryAfterMs===void 0)return;return},isUnknownStatus:(t)=>{if(t===void 0||Number.isNaN(t)||!Number.isFinite(t))return!1;return t<500},toRetryMetadata(t){return{providerErrorCode:t.providerErrorCode,providerErrorText:t.providerErrorText,httpStatus:t.httpStatus,requestId:t.requestId,retryAfterMs:t.retryAfterMs,attempt:t.attempt,causeChain:t.causeChain}},withAttempt(t,n){return new K(t.code,t.message,t.details,{...R.toRetryMetadata(t),attempt:P(n)})},DEFAULT_RETRYABLE_ERROR_CODES:Q,DEFAULT_NON_RETRYABLE_ERROR_CODES:Z};function Tt(t){switch(t){case"config":return"CRYPTO_CONFIG_ERROR";case"encrypt":return"CRYPTO_ENCRYPT_FAILED";case"decrypt":return"CRYPTO_DECRYPT_FAILED";case"hash":return"CRYPTO_HASH_FAILED";case"policy":return"CRYPTO_POLICY_VIOLATION"}}class M extends K{kind;fieldPath;failMode;openFallback;constructor(t,n,e,i={}){super(Tt(t),n,e,i);this.name="FieldCryptoError",this.kind=t,this.fieldPath=typeof i.fieldPath==="string"?i.fieldPath:void 0,this.failMode=i.failMode,this.openFallback=i.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}var Ot=["tenantId","providerId","messageId"];function v(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Rt(t){if(typeof t!=="number"||!Number.isFinite(t))return;if(t<=0||t>100)return;return t}function it(t){let n=[];for(let e of t){let i=v(e.kid),r=Rt(e.percentage);if(!i||r===void 0)continue;n.push({kid:i,percentage:r})}return n}function Et(t,n,e){let i=n.map((r)=>{let s=t[r];return typeof s==="string"?s:""}).join("|");return`${e}::${i}`}function xt(t){let n=2166136261;for(let e=0;e<t.length;e+=1)n^=t.charCodeAt(e),n=n*16777619>>>0;return n>>>0}function Mt(t,n){let e=0;for(let i of t)if(e+=i.percentage,n<e)return i.kid;return}function H(t,n,e){let i=it(n.buckets),r=v(n.defaultKid)??v(e);if(i.length===0)return r;let s=v(n.seed)??"kmsg-rollout-v1",p=n.stickyFields??Ot,f=Et(t,p,s),y=xt(f)%100;return Mt(i,y)??r}function st(t){return it(t.buckets).map((n)=>n.kid)}function T(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function V(t){if(!Array.isArray(t))return[];return t.map((n)=>T(n)).filter((n)=>Boolean(n))}function G(t){let n=[],e=new Set;for(let i of t){let r=T(i);if(!r||e.has(r))continue;e.add(r),n.push(r)}return n}function vt(t){return T(t.providerId)??"default"}function rt(t){let n=T(t.activeKid)??"default",e=G([n,...V(t.decryptKids)]);return{async resolveEncryptKey(){return{kid:n}},async resolveDecryptKeys(){return e}}}function _(t){let n=typeof t.cacheTtlMs==="number"&&t.cacheTtlMs>=0?Math.trunc(t.cacheTtlMs):30000,e=T(t.fallback?.activeKid),i=V(t.fallback?.decryptKids),r;async function s(p){let f=Date.now();if(r&&f<r.expiresAt)return r.value;let y=await t.provider.loadKeySet(p),c=T(y.activeKid)??e??vt(p),a=G([c,...V(y.decryptKids),...i]),h={activeKid:c,decryptKids:a,refreshedAt:Date.now()};return r={value:h,expiresAt:Date.now()+n},h}return{async resolveEncryptKey(p){return{kid:(await s(p)).activeKid}},async resolveDecryptKeys(p){let f=await s(p);return f.decryptKids??[f.activeKid]}}}function yn(t,n){return{async resolveEncryptKey(e){let i=await t.resolveEncryptKey(e);return{kid:H(e,n,i.kid)??i.kid}},async resolveDecryptKeys(e){let i=await t.resolveEncryptKey(e),r=t.resolveDecryptKeys?await t.resolveDecryptKeys(e):[i.kid],s=H(e,n,i.kid),p=st(n);return G([...s?[s]:[],i.kid,...r??[],...p])}}}function on(t){return _({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.keyAlias?{keyAlias:t.keyAlias}:{},...t.region?{region:t.region}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function N(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function pt(t,n){return N(t[n])}function _t(t,n){if(!t)return[];return t.split(n).map((e)=>N(e)).filter((e)=>Boolean(e))}function ln(t={}){let n=t.env??(typeof process<"u"?process.env:{}),e=N(t.delimiter)??",",i=t.activeKidEnv??"KMSG_ACTIVE_KID",r=t.decryptKidsEnv??"KMSG_DECRYPT_KIDS",s=pt(n,i)??N(t.fallbackActiveKid)??"default",p=[s,..._t(pt(n,r),e),...t.fallbackDecryptKids??[]];return rt({activeKid:s,decryptKids:p})}function Kn(t){return _({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.mountPath?{mountPath:t.mountPath}:{},...t.keyName?{keyName:t.keyName}:{},...t.namespace?{namespace:t.namespace}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function J(t){return typeof t==="function"}function yt(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function ft(t,n,e){let i=t.fields[n];if(i)return i;if(n.startsWith("metadata.")){let r=t.fields["metadata.*"];if(r)return r}return e}function Nt(t,n={}){let e=[];if(!t||typeof t!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!t.provider||typeof t.provider!=="object")e.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!J(t.provider.encrypt))e.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!J(t.provider.decrypt))e.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!J(t.provider.hash))e.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!t.fields||typeof t.fields!=="object")e.push({message:"fieldCrypto.fields must be an object",rule:"fieldCrypto.fields.object",path:"fields",hint:"Define policies such as to, from, metadata.phoneNumber"});else{let s=Object.entries(t.fields);if(s.length===0)e.push({message:"fieldCrypto.fields must not be empty",rule:"fieldCrypto.fields.non_empty",path:"fields",hint:"Add at least one field mode mapping"});for(let[p,f]of s){if(!yt(p))e.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(f!=="plain"&&f!=="encrypt"&&f!=="encrypt+hash"&&f!=="mask")e.push({message:`unsupported field mode: ${String(f)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${p}`})}}let i=t.failMode??"closed",r=t.openFallback??"masked";if(i==="open"&&r==="plaintext"&&t.unsafeAllowPlaintextStorage!==!0)e.push({message:"openFallback=plaintext requires unsafeAllowPlaintextStorage=true",rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback",hint:"Use masked/null fallback, or explicitly enable unsafe plaintext"});if(Array.isArray(t.aadFields)){if(t.aadFields.length===0)e.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let s=0;s<t.aadFields.length;s+=1){let p=t.aadFields[s];if(!yt(p))e.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${s}]`})}}if(n.secureMode&&!n.compatPlainColumns){let s=ft(t,"to","encrypt+hash"),p=ft(t,"from","encrypt+hash");if(s==="plain")e.push({message:"secure mode requires non-plain policy for `to` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.to_non_plain",path:"fields.to",hint:"Use encrypt+hash for lookup fields"});if(p==="plain")e.push({message:"secure mode requires non-plain policy for `from` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.from_non_plain",path:"fields.from",hint:"Use encrypt+hash for lookup fields"})}return{valid:e.length===0,issues:e}}function An(t,n={}){let e=Nt(t,n);if(e.valid)return;let i=e.issues[0];if(!i)throw new M("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:e.issues});throw new M("config",i.message,{rule:i.rule,path:i.path,hint:i.hint,issues:e.issues},{fieldPath:i.path})}function I(t){let n=t instanceof Uint8Array?t:new Uint8Array(t),e=typeof globalThis<"u"?globalThis.Buffer:void 0;return(e?e.from(n).toString("base64"):btoa(String.fromCharCode(...n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function U(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),e=n.length%4===0?n:`${n}${"=".repeat(4-n.length%4)}`,i=typeof globalThis<"u"?globalThis.Buffer:void 0;if(i)return new Uint8Array(i.from(e,"base64"));let r=atob(e),s=new Uint8Array(r.length);for(let p=0;p<r.length;p+=1)s[p]=r.charCodeAt(p);return s}function ct(t,n){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(n==="base64url")return U(t);return new TextEncoder().encode(t)}function It(t){let n=t instanceof Uint8Array?t:new Uint8Array(t);return Array.from(n).map((e)=>e.toString(16).padStart(2,"0")).join("")}function S(t){let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function ot(t){let n=JSON.parse(t);if(!n||typeof n!=="object"||typeof n.v!=="number"||typeof n.alg!=="string"||typeof n.kid!=="string"||typeof n.iv!=="string"||typeof n.tag!=="string"||typeof n.ct!=="string")throw Error("Invalid ciphertext envelope");return n}function Ut(t){if(typeof t==="string")return t;return JSON.stringify(t)}function wn(t){if(!t||typeof t!=="object")return!1;let n=t;return typeof n.v==="number"&&typeof n.alg==="string"&&typeof n.kid==="string"&&typeof n.iv==="string"&&typeof n.tag==="string"&&typeof n.ct==="string"}function Bt(t){let n=String(t??"").trim();if(n.length===0)return"";let e=n.startsWith("+"),i=n.replace(/\D/g,"");return e?`+${i}`:i}function at(t=3,n=2){return(e)=>{let i=String(e??"");if(i.length<=t+n)return"*".repeat(Math.max(0,i.length));let r=i.slice(0,t),s=i.slice(-n);return`${r}${"*".repeat(i.length-t-n)}${s}`}}function Sn(t){let n=t.algorithm??"A256GCM",e=t.keyEncoding??"base64url",i=t.hashKeyEncoding??e,r=new Map,s=new Map,p=(y)=>{let c=r.get(y);if(c)return c;let a=t.keys[y];if(!a)throw Error(`Unknown encryption key id: ${y}`);let h=ct(a,e),d=crypto.subtle.importKey("raw",S(h),"AES-GCM",!1,["encrypt","decrypt"]);return r.set(y,d),d},f=(y)=>{let c=s.get(y);if(c)return c;let a=t.hashKeys?.[y]??t.keys[y];if(!a)throw Error(`Unknown hash key id: ${y}`);let h=ct(a,i),d=crypto.subtle.importKey("raw",S(h),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return s.set(y,d),d};return{async encrypt(y){let c=y.kid??t.activeKid,a=await p(c),h=crypto.getRandomValues(new Uint8Array(12)),d=new TextEncoder().encode(JSON.stringify(y.aad??{})),A=new TextEncoder().encode(y.value),C=await crypto.subtle.encrypt({name:"AES-GCM",iv:S(h),additionalData:S(d),tagLength:128},a,S(A)),b=new Uint8Array(C),l=b.slice(b.length-16),o=b.slice(0,b.length-16);return{ciphertext:{v:1,alg:n,kid:c,iv:I(h),tag:I(l),ct:I(o)},kid:c}},async decrypt(y){let c=ot(y.ciphertext),a=y.candidateKids&&y.candidateKids.length>0?y.candidateKids:[c.kid],h=U(c.iv),d=U(c.tag),A=U(c.ct),C=new Uint8Array(A.length+d.length);C.set(A,0),C.set(d,A.length);let b=new TextEncoder().encode(JSON.stringify(y.aad??{})),l;for(let o of a)try{let F=await p(o),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:S(h),additionalData:S(b),tagLength:128},F,S(C));return new TextDecoder().decode(new Uint8Array(g))}catch(F){l=F}throw Error(`Failed to decrypt ciphertext: ${l instanceof Error?l.message:String(l??"unknown")}`)},async hash(y){let c=y.kid??t.activeKid,a=await f(c),h=await crypto.subtle.sign("HMAC",a,S(new TextEncoder().encode(y.value)));return It(h)},mask(y){return at()(y.value)}}}function bn(){return{encrypt(t){return{ciphertext:JSON.stringify({v:1,alg:"NOOP",kid:"noop",iv:"",tag:"",ct:t.value})}},decrypt(t){try{return ot(t.ciphertext).ct}catch{return t.ciphertext}},hash(t){let n=Bt(t.value);return I(new TextEncoder().encode(n))},mask(t){return at()(t.value)}}}function un(t){return Ut(t)}var qt;((r)=>{r.DEBUG="DEBUG";r.INFO="INFO";r.WARN="WARN";r.ERROR="ERROR"})(qt||={});var $t=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function Ht(t){let n=t.toLowerCase();return $t.some((e)=>n.includes(e.toLowerCase()))}function Vt(t){let n=t.trim();if(n.length<=4)return"***";if(n.includes("@")){let[r,s]=n.split("@");return`${r.slice(0,2)}${"*".repeat(Math.max(1,r.length-2))}@${s}`}let e=n.slice(0,3),i=n.slice(-2);return`${e}${"*".repeat(Math.max(1,n.length-5))}${i}`}function W(t,n){if(n===void 0||n===null)return n;if(Ht(t)){if(typeof n==="string")return Vt(n);if(typeof n==="number"||typeof n==="boolean")return"***";if(Array.isArray(n))return"[REDACTED]";if(typeof n==="object")return"[REDACTED]"}if(Array.isArray(n))return n.map((e)=>W(t,e));if(typeof n==="object"){let e={};for(let[i,r]of Object.entries(n))e[i]=W(i,r);return e}return n}function Gt(t){let n={};for(let[e,i]of Object.entries(t))n[e]=W(e,i);return n}class Y{config;context;constructor(t={},n={}){this.context=t,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...n}}shouldLog(t){let n=["DEBUG","INFO","WARN","ERROR"];return n.indexOf(t)>=n.indexOf(this.config.level)}formatMessage(t){let n=Gt(t.context);if(this.config.enableJson)return JSON.stringify({level:t.level,message:t.message,timestamp:t.timestamp.toISOString(),context:n,...t.error&&{error:{name:t.error.name,message:t.error.message,stack:t.error.stack}},...t.duration&&{duration:t.duration}});let e=t.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(t.level):t.level,r=Object.keys(n).length>0?` [${Object.entries(n).map(([p,f])=>`${p}=${f}`).join(", ")}]`:"",s=`${e} ${i}${r}: ${t.message}`;if(t.duration!==void 0)s+=` (${t.duration}ms)`;if(t.error)s+=`
2
- ${t.error.stack}`;return s}colorizeLevel(t){if(!this.config.enableColors)return t;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[t]}${t}\x1B[0m`}writeLog(t){if(!this.shouldLog(t.level))return;let n=this.formatMessage(t);if(this.config.enableConsole)(t.level==="ERROR"?console.error:t.level==="WARN"?console.warn:console.log)(n);if(this.config.enableFile&&this.config.filePath);}debug(t,n={}){this.writeLog({level:"DEBUG",message:t,timestamp:new Date,context:{...this.context,...n}})}info(t,n={}){this.writeLog({level:"INFO",message:t,timestamp:new Date,context:{...this.context,...n}})}warn(t,n={},e){this.writeLog({level:"WARN",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}error(t,n={},e){this.writeLog({level:"ERROR",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}child(t){return new Y({...this.context,...t},this.config)}time(t){let n=Date.now();return()=>{let e=Date.now()-n;this.info(`${t} completed`,{duration:e})}}async measure(t,n,e={}){let i=Date.now(),r={...e,operation:t};this.debug(`Starting ${t}`,r);try{let s=await n(),p=Date.now()-i;return this.info(`Completed ${t}`,{...r,duration:p}),s}catch(s){let p=Date.now()-i;throw this.error(`Failed ${t}`,{...r,duration:p},s instanceof Error?s:Error(String(s))),s}}}var B;function dt(t,n){return new Y(t,n)}function m(){if(!B)B=dt();return B}function Dn(t){B=t}var mn={debug:(t,n)=>m().debug(t,n),info:(t,n)=>m().info(t,n),warn:(t,n,e)=>m().warn(t,n,e),error:(t,n,e)=>m().error(t,n,e),child:(t)=>m().child(t),time:(t)=>m().time(t),measure:(t,n,e)=>m().measure(t,n,e)};function Tn(t){let n=dt({},t);return async(e,i)=>{let r=Date.now(),p={requestId:Math.random().toString(36).substring(7),method:e.req.method,path:e.req.path,userAgent:e.req.header("user-agent")||"unknown"};n.info("Request started",p);try{await i();let f=Date.now()-r;n.info("Request completed",{...p,status:e.res.status,duration:f})}catch(f){let y=Date.now()-r;throw n.error("Request failed",{...p,duration:y},f instanceof Error?f:Error(String(f))),f}}}class O{static defaultOptions={maxAttempts:3,initialDelay:1000,maxDelay:30000,backoffMultiplier:2,jitter:!0,retryCondition:(t)=>R.isRetryable(t)};static async execute(t,n={}){let e={...O.defaultOptions,...n},i,r=e.initialDelay;for(let s=1;s<=e.maxAttempts;s++)try{return await t()}catch(p){if(i=p,s===e.maxAttempts||!e.retryCondition(i,s))throw i;let f=e.jitter?r+Math.random()*r*0.1:r;e.onRetry?.(i,s),await new Promise((y)=>setTimeout(y,f)),r=Math.min(r*e.backoffMultiplier,e.maxDelay)}throw i}static createRetryableFunction(t,n={}){return async(...e)=>{return O.execute(()=>t(...e),n)}}}class j{static async execute(t,n,e={}){let i={concurrency:5,retryOptions:{maxAttempts:3,initialDelay:1000,maxDelay:1e4,backoffMultiplier:2,jitter:!0},failFast:!1,...e},r=Date.now(),s=[],p=[],f=0,y=O.createRetryableFunction(n,i.retryOptions),c=j.createBatches(t,i.concurrency);for(let h of c){let d=h.map(async(A)=>{try{let C=await y(A);s.push({item:A,result:C})}catch(C){if(p.push({item:A,error:C}),i.failFast)throw new K("MESSAGE_SEND_FAILED",`Bulk operation failed fast after ${p.length} failures`,{totalItems:t.length,failedCount:p.length})}finally{f++,i.onProgress?.(f,t.length,p.length)}});if(await Promise.allSettled(d),i.failFast&&p.length>0)break}let a=Date.now()-r;return{successful:s,failed:p,summary:{total:t.length,successful:s.length,failed:p.length,duration:a}}}static createBatches(t,n){let e=[];for(let i=0;i<t.length;i+=n)e.push(t.slice(i,i+n));return e}}class lt{options;state="CLOSED";failureCount=0;lastFailureTime=0;nextAttemptTime=0;constructor(t){this.options=t}async execute(t){let n=Date.now();switch(this.state){case"OPEN":if(n<this.nextAttemptTime)throw new K("NETWORK_SERVICE_UNAVAILABLE","Circuit breaker is OPEN",{state:this.state,nextAttemptTime:this.nextAttemptTime});this.state="HALF_OPEN",this.options.onHalfOpen?.();break;case"HALF_OPEN":break;case"CLOSED":break}try{let e=await Promise.race([t(),new Promise((i,r)=>setTimeout(()=>r(new K("NETWORK_TIMEOUT","Circuit breaker timeout",{timeout:this.options.timeout})),this.options.timeout))]);if(this.state==="HALF_OPEN")this.state="CLOSED",this.failureCount=0,this.options.onClose?.();return e}catch(e){throw this.recordFailure(),e}}recordFailure(){if(this.failureCount++,this.lastFailureTime=Date.now(),this.failureCount>=this.options.failureThreshold)this.state="OPEN",this.nextAttemptTime=this.lastFailureTime+this.options.resetTimeout,this.options.onOpen?.()}getState(){return this.state}getFailureCount(){return this.failureCount}reset(){this.state="CLOSED",this.failureCount=0,this.lastFailureTime=0,this.nextAttemptTime=0}}class ht{maxRequests;windowMs;requests=[];constructor(t,n){this.maxRequests=t;this.windowMs=n}async acquire(){let t=Date.now();if(this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length>=this.maxRequests){let n=Math.min(...this.requests),e=this.windowMs-(t-n);if(e>0)return await new Promise((i)=>setTimeout(i,e)),this.acquire()}this.requests.push(t)}canMakeRequest(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length<this.maxRequests}getRemainingRequests(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),Math.max(0,this.maxRequests-this.requests.length)}}var gt=(t)=>({isSuccess:!0,isFailure:!1,value:t}),Kt=(t)=>({isSuccess:!1,isFailure:!0,error:t}),Vn={map(t,n){if(t.isSuccess)return gt(n(t.value));return t},flatMap(t,n){if(t.isSuccess)return n(t.value);return t},mapError(t,n){if(t.isFailure)return Kt(n(t.error));return t},unwrap(t){if(t.isSuccess)return t.value;throw t.error},unwrapOr(t,n){if(t.isSuccess)return t.value;return n},unwrapOrElse(t,n){if(t.isSuccess)return t.value;return n(t.error)},match(t,n){if(t.isSuccess)return n.ok(t.value);return n.fail(t.error)},async fromPromise(t){try{let n=await t;return gt(n)}catch(n){return Kt(n)}},isOk(t){return t.isSuccess},isFail(t){return t.isFailure},tap(t,n){return n(t),t},tapOk(t,n){if(t.isSuccess)n(t.value);return t},tapErr(t,n){if(t.isFailure)n(t.error);return t},expect(t,n){if(t.isSuccess)return t.value;throw Error(n,{cause:t.error})}};function Jt(){let t=globalThis;return t.__K_MSG_ENV__??t.__ENV__??t.process?.env??{}}function Jn(t){let n=Jt()[t];if(typeof n==="string")return n;if(n===void 0)return;return String(n)}var Wt=["PENDING","SENT","DELIVERED","FAILED","CANCELLED","UNKNOWN"],Yt=["DELIVERED","FAILED","CANCELLED","UNKNOWN"],Ct=["PENDING","SENT"],jt=new Set(Wt),Ft=new Set(Yt),Qt=new Set(Ct);function Yn(t){return jt.has(t)}function jn(t){return Ft.has(t)}function Qn(t){return Ft.has(t)}function Zn(t){return Qt.has(t)}function Ln(){return Ct}var Zt=["ALIMTALK","FRIENDTALK","SMS","LMS","MMS","NSA","VOICE","FAX","RCS_SMS","RCS_LMS","RCS_MMS","RCS_TPL","RCS_ITPL","RCS_LTPL"],Lt=new Set(Zt);function zn(t){return Lt.has(t)}var te=["PENDING","SENT","FAILED"],Xt="PENDING",ne=(t)=>{let n=typeof t==="string"?t.trim().toUpperCase():"";if(n==="PENDING"||n==="SENT"||n==="FAILED")return n;return Xt};export{Nt as validateFieldCryptoConfig,ut as validateErrorRetryPolicy,un as toCiphertextEnvelopeString,Dn as setGlobalLogger,H as selectActiveKidByRollout,ft as resolveFieldMode,Jn as readRuntimeEnv,zt as parseErrorRetryPolicyFromJson,gt as ok,x as normalizeRetryAfterMs,tn as normalizeProviderError,Bt as normalizePhoneForHash,ne as normalizeMessageStatus,kt as normalizeErrorRetryPolicy,Tn as loggerMiddleware,mn as logger,Qn as isTerminalDeliveryStatus,Zn as isPollableDeliveryStatus,jn as isKMsgTerminalStatus,zn as isKMsgMessageType,Yn as isKMsgDeliveryStatus,wn as isCryptoEnvelope,Jt as getRuntimeEnvSource,st as getRolloutKnownKids,Ln as getPollableStatuses,m as getLogger,Kt as fail,Kn as createVaultTransitKeyResolver,rt as createStaticKeyResolver,yn as createRollingKeyResolver,_ as createRefreshableKeyResolver,bn as createNoopFieldCryptoProvider,dt as createLogger,ln as createEnvKeyResolver,at as createDefaultMasker,on as createAwsKmsKeyResolver,Sn as createAesGcmFieldCryptoProvider,An as assertFieldCryptoConfig,O as RetryHandler,Vn as Result,ht as RateLimiter,Xt as QUEUED_MESSAGE_STATUS,Y as Logger,qt as LogLevel,te as KNOWN_MESSAGE_STATUSES,E as KMsgErrorCode,K as KMsgError,Yt as KMSG_TERMINAL_STATUSES,Ct as KMSG_POLLABLE_STATUSES,Zt as KMSG_MESSAGE_TYPES,Wt as KMSG_DELIVERY_STATUSES,M as FieldCryptoError,R as ErrorUtils,lt as CircuitBreaker,j as BulkOperationHandler};
1
+ var E;((l)=>{l.INVALID_REQUEST="INVALID_REQUEST";l.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";l.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";l.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";l.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";l.NETWORK_ERROR="NETWORK_ERROR";l.NETWORK_TIMEOUT="NETWORK_TIMEOUT";l.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";l.PROVIDER_ERROR="PROVIDER_ERROR";l.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";l.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";l.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";l.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";l.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";l.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";l.UNKNOWN_ERROR="UNKNOWN_ERROR"})(E||={});var At={["INVALID_REQUEST"]:{ko:"잘못된 요청입니다",en:"Invalid request"},["AUTHENTICATION_FAILED"]:{ko:"인증에 실패했습니다",en:"Authentication failed"},["INSUFFICIENT_BALANCE"]:{ko:"잔액이 부족합니다",en:"Insufficient balance"},["TEMPLATE_NOT_FOUND"]:{ko:"템플릿을 찾을 수 없습니다",en:"Template not found"},["RATE_LIMIT_EXCEEDED"]:{ko:"요청 한도를 초과했습니다",en:"Rate limit exceeded"},["NETWORK_ERROR"]:{ko:"네트워크 오류가 발생했습니다",en:"Network error"},["NETWORK_TIMEOUT"]:{ko:"네트워크 요청 시간이 초과되었습니다",en:"Network timeout"},["NETWORK_SERVICE_UNAVAILABLE"]:{ko:"서비스를 일시적으로 사용할 수 없습니다",en:"Service temporarily unavailable"},["PROVIDER_ERROR"]:{ko:"제공자 오류가 발생했습니다",en:"Provider error"},["MESSAGE_SEND_FAILED"]:{ko:"메시지 전송에 실패했습니다",en:"Message send failed"},["CRYPTO_CONFIG_ERROR"]:{ko:"암호화 설정 오류가 발생했습니다",en:"Crypto configuration error"},["CRYPTO_ENCRYPT_FAILED"]:{ko:"암호화에 실패했습니다",en:"Encryption failed"},["CRYPTO_DECRYPT_FAILED"]:{ko:"복호화에 실패했습니다",en:"Decryption failed"},["CRYPTO_HASH_FAILED"]:{ko:"해시 생성에 실패했습니다",en:"Hash generation failed"},["CRYPTO_POLICY_VIOLATION"]:{ko:"암호화 정책 위반이 발생했습니다",en:"Crypto policy violation"},["UNKNOWN_ERROR"]:{ko:"알 수 없는 오류가 발생했습니다",en:"Unknown error"}},Pt=new Set(Object.values(E)),Q=new Set(["NETWORK_ERROR","RATE_LIMIT_EXCEEDED","NETWORK_TIMEOUT","NETWORK_SERVICE_UNAVAILABLE","PROVIDER_ERROR","UNKNOWN_ERROR"]),Z=new Set(["INVALID_REQUEST","AUTHENTICATION_FAILED","INSUFFICIENT_BALANCE","TEMPLATE_NOT_FOUND","MESSAGE_SEND_FAILED","CRYPTO_CONFIG_ERROR","CRYPTO_ENCRYPT_FAILED","CRYPTO_DECRYPT_FAILED","CRYPTO_HASH_FAILED","CRYPTO_POLICY_VIOLATION"]),P=(t)=>{if(typeof t!=="number"||Number.isNaN(t)||!Number.isFinite(t))return;return Math.trunc(t)},x=(t)=>{let n=P(t);if(n===void 0||n<0)return;return n},q=(t)=>{if(typeof t!=="string")return;return t.toLowerCase().trim()},wt=(t)=>{if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0},w=(t)=>{return typeof t==="object"&&t!==null&&!Array.isArray(t)},u=(t,n)=>{for(let e of n)if(e in t)return t[e];return},St=(t)=>{return t.length>0?t:"$"},nt=(t)=>{return t==="compat"?"compat":"safe"},L=(t)=>{if(t>=500)return"retryable";if(t===408||t===425||t===429)return"retryable";return"non_retryable"},X=(t)=>{let n=t.toLowerCase();if(n.includes("timeout")||n.includes("temporar")||n.includes("network")||n.includes("retry"))return"retryable";return};class K extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(t,n,e,i={}){super(n);if(this.name="KMsgError",this.code=t,this.details=e,this.providerErrorCode=i.providerErrorCode,this.providerErrorText=i.providerErrorText,this.httpStatus=P(i.httpStatus),this.requestId=typeof i.requestId==="string"?i.requestId:void 0,this.retryAfterMs=P(i.retryAfterMs),this.attempt=P(i.attempt),Array.isArray(i.causeChain))this.causeChain=i.causeChain;else if(i.causeChain!==void 0)this.causeChain=[i.causeChain];let r=Error.captureStackTrace;if(r)r(this,K)}getLocalizedMessage(t="ko"){let n=At[this.code];if(n?.[t])return n[t];return this.message}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,providerErrorCode:this.providerErrorCode,providerErrorText:this.providerErrorText,httpStatus:this.httpStatus,requestId:this.requestId,retryAfterMs:this.retryAfterMs,attempt:this.attempt,causeChain:this.causeChain}}}var D=(t,n)=>{let e=P(t);if(e!==void 0)return e;if(n==="compat"&&typeof t==="string"){let i=Number(t.trim());if(Number.isFinite(i))return Math.trunc(i)}return},$=(t,n)=>{let e=wt(t);if(e)return e;if(n==="compat"&&(typeof t==="number"||typeof t==="boolean"))return String(t);return},et=(t)=>{if(typeof t!=="string")return;let n=t.trim().toUpperCase();if(!Pt.has(n))return;return n},k=(t,n)=>{t.push({...n,path:St(n.path)})},z=(t,n,e,i)=>{if(t===void 0)return[];let r=(()=>{if(Array.isArray(t))return t;if(e==="compat"&&typeof t==="string")return t.split(",").map((f)=>f.trim()).filter((f)=>f.length>0);return k(i,{code:"invalid_type",message:"expected array of KMsgErrorCode values",path:n}),[]})(),s=[],p=new Set;for(let f=0;f<r.length;f+=1){let y=r[f],o=et(typeof y==="string"?y:e==="compat"?String(y):y);if(!o){k(i,{code:"unknown_code",message:`unknown retry policy code: ${String(y)}`,path:`${n}[${f}]`});continue}if(p.has(o)){k(i,{code:"duplicate_code",message:`duplicate retry policy code: ${o}`,path:`${n}[${f}]`});continue}p.add(o),s.push(o)}return s},bt=(t,n,e)=>{if(t===void 0)return;if(typeof t==="string"){let i=t.trim().toLowerCase();if(i==="retryable")return"retryable";if(i==="non_retryable"||i==="non-retryable")return"non_retryable"}if(n==="compat"&&typeof t==="boolean")return t?"retryable":"non_retryable";k(e,{code:"invalid_fallback",message:`invalid fallback value: ${String(t)}`,path:"fallback"});return};function ut(t,n={}){let e=nt(n.mode),i=[];if(!w(t))return k(i,{code:"invalid_root",message:"retry policy must be an object",path:"$"}),{policy:null,issues:i};let r=new Set(["retryableCodes","nonRetryableCodes","fallback"]);for(let d of Object.keys(t)){if(r.has(d))continue;k(i,{code:"unknown_field",message:`unknown retry policy field: ${d}`,path:d})}let s=z(t.retryableCodes,"retryableCodes",e,i),p=z(t.nonRetryableCodes,"nonRetryableCodes",e,i),f=bt(t.fallback,e,i),y=new Set(s),o=new Set(p);for(let d of y){if(!o.has(d))continue;y.delete(d),k(i,{code:"conflicting_code",message:`code '${d}' is both retryable and nonRetryable; nonRetryable wins`,path:"retryableCodes"})}let a={...y.size>0?{retryableCodes:Array.from(y)}:{},...o.size>0?{nonRetryableCodes:Array.from(o)}:{},...f?{fallback:f}:{}};return{policy:a.retryableCodes!==void 0||a.nonRetryableCodes!==void 0||a.fallback!==void 0?a:null,issues:i}}function Dt(t,n={}){return ut(t,n).policy}function zt(t,n={}){if(typeof t!=="string"||t.trim().length===0)return null;try{let e=JSON.parse(t);return Dt(e,n)}catch{return null}}var tt=(t,n)=>{let e=t.response;if(!w(e))return;return D(u(e,["status","statusCode","httpStatus"]),n)},kt=(t,n)=>{if(t instanceof K&&Array.isArray(t.causeChain))return t.causeChain.slice();if(w(t)){let s=t.causeChain;if(Array.isArray(s))return s.slice();let p=t.details;if(n==="compat"&&w(p)){let f=p.causeChain;if(Array.isArray(f))return f.slice();if(f!==void 0)return[f]}}let e=[],i=new Set,r=t;for(let s=0;s<8;s+=1){if(!w(r))break;let p=r.cause;if(p===void 0||i.has(p))break;i.add(p),e.push(p),r=p}return e.length>0?e:void 0},mt=(t)=>{if(t instanceof Error&&typeof t.message==="string")return t.message;if(w(t)&&typeof t.message==="string")return t.message;return typeof t==="string"?t:"Unknown error"};function tn(t,n={}){let e=nt(n.mode),r=n.defaultCode??"UNKNOWN_ERROR",s={code:"fallback",classification:n.policy?"policy":"fallback"},p,f,y,o,a,h,d,A=(c)=>{if(c.providerErrorCode!==void 0)p=c.providerErrorCode,s.providerErrorCode="metadata";if(c.providerErrorText!==void 0)f=c.providerErrorText,s.providerErrorText="metadata";if(c.httpStatus!==void 0)y=c.httpStatus,s.httpStatus="metadata";if(c.requestId!==void 0)o=c.requestId,s.requestId="metadata";if(c.retryAfterMs!==void 0)a=x(c.retryAfterMs),s.retryAfterMs="metadata";if(c.attempt!==void 0)h=D(c.attempt,e),s.attempt="metadata";if(Array.isArray(c.causeChain))d=c.causeChain.slice(),s.causeChain="metadata"},C=(c,F)=>{if(p===void 0){let g=$(u(c,["providerErrorCode","errorCode","resultCode"]),e);if(g!==void 0)p=g,s.providerErrorCode=F}if(f===void 0){let g=$(u(c,["providerErrorText","errorMessage","msg","message"]),e);if(g!==void 0)f=g,s.providerErrorText=F}if(y===void 0){let g=D(u(c,["httpStatus","statusCode","status"]),e)??tt(c,e);if(g!==void 0)y=g,s.httpStatus=F==="details"?"details":"http"}if(o===void 0){let g=$(u(c,["requestId","request_id","reqId","traceId"]),e);if(g!==void 0)o=g,s.requestId=F}if(a===void 0){let g=x(D(u(c,["retryAfterMs","retry_after_ms","retryAfter"]),e));if(g!==void 0)a=g,s.retryAfterMs=F}if(h===void 0){let g=D(c.attempt,e);if(g!==void 0&&g>0)h=g,s.attempt=F}};if(t instanceof K){if(r=t.code,s.code="input",A(t),e==="compat"&&w(t.details))C(t.details,"details")}else if(w(t)){let c=et(u(t,["code","errorCode","resultCode"]));if(c!==void 0)r=c,s.code="input";else if(y===void 0){let F=D(u(t,["httpStatus","statusCode","status"]),e)??tt(t,e);if(F!==void 0&&F>=500)r="PROVIDER_ERROR",s.code="http"}if(C(t,"input"),e==="compat"&&w(t.details))C(t.details,"details")}if(d===void 0){let c=kt(t,e);if(c!==void 0)d=c,s.causeChain="input"}if(n.attempt!==void 0&&D(n.attempt,e)!==void 0){let c=D(n.attempt,e);if(c!==void 0&&c>0)h=c,s.attempt="input"}let b=new K(r,mt(t),void 0,{providerErrorCode:p,providerErrorText:f,httpStatus:y,requestId:o,retryAfterMs:a,attempt:h,causeChain:d}),l=R.classifyForRetry(b,n.policy);return{code:r,classification:l,...p!==void 0?{providerErrorCode:p}:{},...f!==void 0?{providerErrorText:f}:{},...y!==void 0?{httpStatus:y}:{},...o!==void 0?{requestId:o}:{},...a!==void 0?{retryAfterMs:a}:{},...h!==void 0?{attempt:h}:{},...d!==void 0?{causeChain:d}:{},sources:s}}var R={isRetryable(t,n={}){return R.classifyForRetry(t,n)==="retryable"},classifyForRetry(t,n={}){if(t instanceof K){if(new Set(n.retryableCodes??Array.from(Q)).has(t.code))return"retryable";if(new Set(n.nonRetryableCodes??Array.from(Z)).has(t.code))return"non_retryable";if(t.httpStatus!==void 0)return L(t.httpStatus);let y=X(t.message);if(y)return y;if(n.classifyByMessage&&t.message){let o=n.classifyByMessage(t.message);if(o)return o}if(n.fallback)return n.fallback;return"non_retryable"}let e=t&&typeof t==="object"?t:void 0,i=q(e?.status)??q(e?.statusCode)??q(e?.code),r=P(e?.status)??P(e?.statusCode)??P(e?.httpStatus);if(typeof i==="string"&&i.startsWith("5"))return"retryable";if(r!==void 0){if(n.classifyByStatusCode)return n.classifyByStatusCode(r);return L(r)}let s=typeof e?.message==="string"?X(e.message):void 0;if(s)return s;if(n.classifyByMessage&&typeof e?.message==="string"){let p=n.classifyByMessage(e.message);if(p)return p}return n.fallback??"non_retryable"},resolveRetryAfterMs(t,n){if(n?.retryAfterMs){let e=n.retryAfterMs(t),i=x(e);if(i!==void 0)return i}if(t.retryAfterMs!==void 0)return x(t.retryAfterMs);if(t.code==="RATE_LIMIT_EXCEEDED"&&t.retryAfterMs===void 0)return;return},isUnknownStatus:(t)=>{if(t===void 0||Number.isNaN(t)||!Number.isFinite(t))return!1;return t<500},toRetryMetadata(t){return{providerErrorCode:t.providerErrorCode,providerErrorText:t.providerErrorText,httpStatus:t.httpStatus,requestId:t.requestId,retryAfterMs:t.retryAfterMs,attempt:t.attempt,causeChain:t.causeChain}},withAttempt(t,n){return new K(t.code,t.message,t.details,{...R.toRetryMetadata(t),attempt:P(n)})},DEFAULT_RETRYABLE_ERROR_CODES:Q,DEFAULT_NON_RETRYABLE_ERROR_CODES:Z};function Tt(t){switch(t){case"config":return"CRYPTO_CONFIG_ERROR";case"encrypt":return"CRYPTO_ENCRYPT_FAILED";case"decrypt":return"CRYPTO_DECRYPT_FAILED";case"hash":return"CRYPTO_HASH_FAILED";case"policy":return"CRYPTO_POLICY_VIOLATION"}}class M extends K{kind;fieldPath;failMode;openFallback;constructor(t,n,e,i={}){super(Tt(t),n,e,i);this.name="FieldCryptoError",this.kind=t,this.fieldPath=typeof i.fieldPath==="string"?i.fieldPath:void 0,this.failMode=i.failMode,this.openFallback=i.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}var Ot=["tenantId","providerId","messageId"];function v(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function Rt(t){if(typeof t!=="number"||!Number.isFinite(t))return;if(t<=0||t>100)return;return t}function it(t){let n=[];for(let e of t){let i=v(e.kid),r=Rt(e.percentage);if(!i||r===void 0)continue;n.push({kid:i,percentage:r})}return n}function Et(t,n,e){let i=n.map((r)=>{let s=t[r];return typeof s==="string"?s:""}).join("|");return`${e}::${i}`}function xt(t){let n=2166136261;for(let e=0;e<t.length;e+=1)n^=t.charCodeAt(e),n=n*16777619>>>0;return n>>>0}function Mt(t,n){let e=0;for(let i of t)if(e+=i.percentage,n<e)return i.kid;return}function H(t,n,e){let i=it(n.buckets),r=v(n.defaultKid)??v(e);if(i.length===0)return r;let s=v(n.seed)??"kmsg-rollout-v1",p=n.stickyFields??Ot,f=Et(t,p,s),y=xt(f)%100;return Mt(i,y)??r}function st(t){return it(t.buckets).map((n)=>n.kid)}function T(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function V(t){if(!Array.isArray(t))return[];return t.map((n)=>T(n)).filter((n)=>Boolean(n))}function G(t){let n=[],e=new Set;for(let i of t){let r=T(i);if(!r||e.has(r))continue;e.add(r),n.push(r)}return n}function vt(t){return T(t.providerId)??"default"}function rt(t){let n=T(t.activeKid)??"default",e=G([n,...V(t.decryptKids)]);return{async resolveEncryptKey(){return{kid:n}},async resolveDecryptKeys(){return e}}}function _(t){let n=typeof t.cacheTtlMs==="number"&&t.cacheTtlMs>=0?Math.trunc(t.cacheTtlMs):30000,e=T(t.fallback?.activeKid),i=V(t.fallback?.decryptKids),r;async function s(p){let f=Date.now();if(r&&f<r.expiresAt)return r.value;let y=await t.provider.loadKeySet(p),o=T(y.activeKid)??e??vt(p),a=G([o,...V(y.decryptKids),...i]),h={activeKid:o,decryptKids:a,refreshedAt:Date.now()};return r={value:h,expiresAt:Date.now()+n},h}return{async resolveEncryptKey(p){return{kid:(await s(p)).activeKid}},async resolveDecryptKeys(p){let f=await s(p);return f.decryptKids??[f.activeKid]}}}function yn(t,n){return{async resolveEncryptKey(e){let i=await t.resolveEncryptKey(e);return{kid:H(e,n,i.kid)??i.kid}},async resolveDecryptKeys(e){let i=await t.resolveEncryptKey(e),r=t.resolveDecryptKeys?await t.resolveDecryptKeys(e):[i.kid],s=H(e,n,i.kid),p=st(n);return G([...s?[s]:[],i.kid,...r??[],...p])}}}function cn(t){return _({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.keyAlias?{keyAlias:t.keyAlias}:{},...t.region?{region:t.region}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function N(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function pt(t,n){return N(t[n])}function _t(t,n){if(!t)return[];return t.split(n).map((e)=>N(e)).filter((e)=>Boolean(e))}function ln(t={}){let n=globalThis.process?.env,e=t.env??n??{},i=N(t.delimiter)??",",r=t.activeKidEnv??"KMSG_ACTIVE_KID",s=t.decryptKidsEnv??"KMSG_DECRYPT_KIDS",p=pt(e,r)??N(t.fallbackActiveKid)??"default",f=[p,..._t(pt(e,s),i),...t.fallbackDecryptKids??[]];return rt({activeKid:p,decryptKids:f})}function Kn(t){return _({provider:{async loadKeySet(e){return t.client.getKeyState({...e,...t.mountPath?{mountPath:t.mountPath}:{},...t.keyName?{keyName:t.keyName}:{},...t.namespace?{namespace:t.namespace}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function J(t){return typeof t==="function"}function yt(t){if(typeof t!=="string")return;let n=t.trim();return n.length>0?n:void 0}function ft(t,n,e){let i=t.fields[n];if(i)return i;if(n.startsWith("metadata.")){let r=t.fields["metadata.*"];if(r)return r}return e}function Nt(t,n={}){let e=[];if(!t||typeof t!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!t.provider||typeof t.provider!=="object")e.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!J(t.provider.encrypt))e.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!J(t.provider.decrypt))e.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!J(t.provider.hash))e.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!t.fields||typeof t.fields!=="object")e.push({message:"fieldCrypto.fields must be an object",rule:"fieldCrypto.fields.object",path:"fields",hint:"Define policies such as to, from, metadata.phoneNumber"});else{let s=Object.entries(t.fields);if(s.length===0)e.push({message:"fieldCrypto.fields must not be empty",rule:"fieldCrypto.fields.non_empty",path:"fields",hint:"Add at least one field mode mapping"});for(let[p,f]of s){if(!yt(p))e.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(f!=="plain"&&f!=="encrypt"&&f!=="encrypt+hash"&&f!=="mask")e.push({message:`unsupported field mode: ${String(f)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${p}`})}}let i=t.failMode??"closed",r=t.openFallback??"masked";if(i==="open"&&r==="plaintext"&&t.unsafeAllowPlaintextStorage!==!0)e.push({message:"openFallback=plaintext requires unsafeAllowPlaintextStorage=true",rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback",hint:"Use masked/null fallback, or explicitly enable unsafe plaintext"});if(Array.isArray(t.aadFields)){if(t.aadFields.length===0)e.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let s=0;s<t.aadFields.length;s+=1){let p=t.aadFields[s];if(!yt(p))e.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${s}]`})}}if(n.secureMode&&!n.compatPlainColumns){let s=ft(t,"to","encrypt+hash"),p=ft(t,"from","encrypt+hash");if(s==="plain")e.push({message:"secure mode requires non-plain policy for `to` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.to_non_plain",path:"fields.to",hint:"Use encrypt+hash for lookup fields"});if(p==="plain")e.push({message:"secure mode requires non-plain policy for `from` when compatPlainColumns=false",rule:"fieldCrypto.secure_mode.from_non_plain",path:"fields.from",hint:"Use encrypt+hash for lookup fields"})}return{valid:e.length===0,issues:e}}function An(t,n={}){let e=Nt(t,n);if(e.valid)return;let i=e.issues[0];if(!i)throw new M("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:e.issues});throw new M("config",i.message,{rule:i.rule,path:i.path,hint:i.hint,issues:e.issues},{fieldPath:i.path})}function I(t){let n=t instanceof Uint8Array?t:new Uint8Array(t),e=typeof globalThis<"u"?globalThis.Buffer:void 0;return(e?e.from(n).toString("base64"):btoa(String.fromCharCode(...n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function U(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),e=n.length%4===0?n:`${n}${"=".repeat(4-n.length%4)}`,i=typeof globalThis<"u"?globalThis.Buffer:void 0;if(i)return new Uint8Array(i.from(e,"base64"));let r=atob(e),s=new Uint8Array(r.length);for(let p=0;p<r.length;p+=1)s[p]=r.charCodeAt(p);return s}function ot(t,n){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(n==="base64url")return U(t);return new TextEncoder().encode(t)}function It(t){let n=t instanceof Uint8Array?t:new Uint8Array(t);return Array.from(n).map((e)=>e.toString(16).padStart(2,"0")).join("")}function S(t){let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function ct(t){let n=JSON.parse(t);if(!n||typeof n!=="object"||typeof n.v!=="number"||typeof n.alg!=="string"||typeof n.kid!=="string"||typeof n.iv!=="string"||typeof n.tag!=="string"||typeof n.ct!=="string")throw Error("Invalid ciphertext envelope");return n}function Ut(t){if(typeof t==="string")return t;return JSON.stringify(t)}function wn(t){if(!t||typeof t!=="object")return!1;let n=t;return typeof n.v==="number"&&typeof n.alg==="string"&&typeof n.kid==="string"&&typeof n.iv==="string"&&typeof n.tag==="string"&&typeof n.ct==="string"}function Bt(t){let n=String(t??"").trim();if(n.length===0)return"";let e=n.startsWith("+"),i=n.replace(/\D/g,"");return e?`+${i}`:i}function at(t=3,n=2){return(e)=>{let i=String(e??"");if(i.length<=t+n)return"*".repeat(Math.max(0,i.length));let r=i.slice(0,t),s=i.slice(-n);return`${r}${"*".repeat(i.length-t-n)}${s}`}}function Sn(t){let n=t.algorithm??"A256GCM",e=t.keyEncoding??"base64url",i=t.hashKeyEncoding??e,r=new Map,s=new Map,p=(y)=>{let o=r.get(y);if(o)return o;let a=t.keys[y];if(!a)throw Error(`Unknown encryption key id: ${y}`);let h=ot(a,e),d=crypto.subtle.importKey("raw",S(h),"AES-GCM",!1,["encrypt","decrypt"]);return r.set(y,d),d},f=(y)=>{let o=s.get(y);if(o)return o;let a=t.hashKeys?.[y]??t.keys[y];if(!a)throw Error(`Unknown hash key id: ${y}`);let h=ot(a,i),d=crypto.subtle.importKey("raw",S(h),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return s.set(y,d),d};return{async encrypt(y){let o=y.kid??t.activeKid,a=await p(o),h=crypto.getRandomValues(new Uint8Array(12)),d=new TextEncoder().encode(JSON.stringify(y.aad??{})),A=new TextEncoder().encode(y.value),C=await crypto.subtle.encrypt({name:"AES-GCM",iv:S(h),additionalData:S(d),tagLength:128},a,S(A)),b=new Uint8Array(C),l=b.slice(b.length-16),c=b.slice(0,b.length-16);return{ciphertext:{v:1,alg:n,kid:o,iv:I(h),tag:I(l),ct:I(c)},kid:o}},async decrypt(y){let o=ct(y.ciphertext),a=y.candidateKids&&y.candidateKids.length>0?y.candidateKids:[o.kid],h=U(o.iv),d=U(o.tag),A=U(o.ct),C=new Uint8Array(A.length+d.length);C.set(A,0),C.set(d,A.length);let b=new TextEncoder().encode(JSON.stringify(y.aad??{})),l;for(let c of a)try{let F=await p(c),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:S(h),additionalData:S(b),tagLength:128},F,S(C));return new TextDecoder().decode(new Uint8Array(g))}catch(F){l=F}throw Error(`Failed to decrypt ciphertext: ${l instanceof Error?l.message:String(l??"unknown")}`)},async hash(y){let o=y.kid??t.activeKid,a=await f(o),h=await crypto.subtle.sign("HMAC",a,S(new TextEncoder().encode(y.value)));return It(h)},mask(y){return at()(y.value)}}}function bn(){return{encrypt(t){return{ciphertext:JSON.stringify({v:1,alg:"NOOP",kid:"noop",iv:"",tag:"",ct:t.value})}},decrypt(t){try{return ct(t.ciphertext).ct}catch{return t.ciphertext}},hash(t){let n=Bt(t.value);return I(new TextEncoder().encode(n))},mask(t){return at()(t.value)}}}function un(t){return Ut(t)}var qt;((r)=>{r.DEBUG="DEBUG";r.INFO="INFO";r.WARN="WARN";r.ERROR="ERROR"})(qt||={});var $t=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function Ht(t){let n=t.toLowerCase();return $t.some((e)=>n.includes(e.toLowerCase()))}function Vt(t){let n=t.trim();if(n.length<=4)return"***";if(n.includes("@")){let[r,s]=n.split("@");return`${r.slice(0,2)}${"*".repeat(Math.max(1,r.length-2))}@${s}`}let e=n.slice(0,3),i=n.slice(-2);return`${e}${"*".repeat(Math.max(1,n.length-5))}${i}`}function W(t,n){if(n===void 0||n===null)return n;if(Ht(t)){if(typeof n==="string")return Vt(n);if(typeof n==="number"||typeof n==="boolean")return"***";if(Array.isArray(n))return"[REDACTED]";if(typeof n==="object")return"[REDACTED]"}if(Array.isArray(n))return n.map((e)=>W(t,e));if(typeof n==="object"){let e={};for(let[i,r]of Object.entries(n))e[i]=W(i,r);return e}return n}function Gt(t){let n={};for(let[e,i]of Object.entries(t))n[e]=W(e,i);return n}class Y{config;context;constructor(t={},n={}){this.context=t,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...n}}shouldLog(t){let n=["DEBUG","INFO","WARN","ERROR"];return n.indexOf(t)>=n.indexOf(this.config.level)}formatMessage(t){let n=Gt(t.context);if(this.config.enableJson)return JSON.stringify({level:t.level,message:t.message,timestamp:t.timestamp.toISOString(),context:n,...t.error&&{error:{name:t.error.name,message:t.error.message,stack:t.error.stack}},...t.duration&&{duration:t.duration}});let e=t.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(t.level):t.level,r=Object.keys(n).length>0?` [${Object.entries(n).map(([p,f])=>`${p}=${f}`).join(", ")}]`:"",s=`${e} ${i}${r}: ${t.message}`;if(t.duration!==void 0)s+=` (${t.duration}ms)`;if(t.error)s+=`
2
+ ${t.error.stack}`;return s}colorizeLevel(t){if(!this.config.enableColors)return t;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[t]}${t}\x1B[0m`}writeLog(t){if(!this.shouldLog(t.level))return;let n=this.formatMessage(t);if(this.config.enableConsole)(t.level==="ERROR"?console.error:t.level==="WARN"?console.warn:console.log)(n);if(this.config.enableFile&&this.config.filePath);}debug(t,n={}){this.writeLog({level:"DEBUG",message:t,timestamp:new Date,context:{...this.context,...n}})}info(t,n={}){this.writeLog({level:"INFO",message:t,timestamp:new Date,context:{...this.context,...n}})}warn(t,n={},e){this.writeLog({level:"WARN",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}error(t,n={},e){this.writeLog({level:"ERROR",message:t,timestamp:new Date,context:{...this.context,...n},error:e})}child(t){return new Y({...this.context,...t},this.config)}time(t){let n=Date.now();return()=>{let e=Date.now()-n;this.info(`${t} completed`,{duration:e})}}async measure(t,n,e={}){let i=Date.now(),r={...e,operation:t};this.debug(`Starting ${t}`,r);try{let s=await n(),p=Date.now()-i;return this.info(`Completed ${t}`,{...r,duration:p}),s}catch(s){let p=Date.now()-i;throw this.error(`Failed ${t}`,{...r,duration:p},s instanceof Error?s:Error(String(s))),s}}}var B;function dt(t,n){return new Y(t,n)}function m(){if(!B)B=dt();return B}function kn(t){B=t}var mn={debug:(t,n)=>m().debug(t,n),info:(t,n)=>m().info(t,n),warn:(t,n,e)=>m().warn(t,n,e),error:(t,n,e)=>m().error(t,n,e),child:(t)=>m().child(t),time:(t)=>m().time(t),measure:(t,n,e)=>m().measure(t,n,e)};function Tn(t){let n=dt({},t);return async(e,i)=>{let r=Date.now(),p={requestId:Math.random().toString(36).substring(7),method:e.req.method,path:e.req.path,userAgent:e.req.header("user-agent")||"unknown"};n.info("Request started",p);try{await i();let f=Date.now()-r;n.info("Request completed",{...p,status:e.res.status,duration:f})}catch(f){let y=Date.now()-r;throw n.error("Request failed",{...p,duration:y},f instanceof Error?f:Error(String(f))),f}}}class O{static defaultOptions={maxAttempts:3,initialDelay:1000,maxDelay:30000,backoffMultiplier:2,jitter:!0,retryCondition:(t)=>R.isRetryable(t)};static async execute(t,n={}){let e={...O.defaultOptions,...n},i,r=e.initialDelay;for(let s=1;s<=e.maxAttempts;s++)try{return await t()}catch(p){if(i=p,s===e.maxAttempts||!e.retryCondition(i,s))throw i;let f=e.jitter?r+Math.random()*r*0.1:r;e.onRetry?.(i,s),await new Promise((y)=>setTimeout(y,f)),r=Math.min(r*e.backoffMultiplier,e.maxDelay)}throw i}static createRetryableFunction(t,n={}){return async(...e)=>{return O.execute(()=>t(...e),n)}}}class j{static async execute(t,n,e={}){let i={concurrency:5,retryOptions:{maxAttempts:3,initialDelay:1000,maxDelay:1e4,backoffMultiplier:2,jitter:!0},failFast:!1,...e},r=Date.now(),s=[],p=[],f=0,y=O.createRetryableFunction(n,i.retryOptions),o=j.createBatches(t,i.concurrency);for(let h of o){let d=h.map(async(A)=>{try{let C=await y(A);s.push({item:A,result:C})}catch(C){if(p.push({item:A,error:C}),i.failFast)throw new K("MESSAGE_SEND_FAILED",`Bulk operation failed fast after ${p.length} failures`,{totalItems:t.length,failedCount:p.length})}finally{f++,i.onProgress?.(f,t.length,p.length)}});if(await Promise.allSettled(d),i.failFast&&p.length>0)break}let a=Date.now()-r;return{successful:s,failed:p,summary:{total:t.length,successful:s.length,failed:p.length,duration:a}}}static createBatches(t,n){let e=[];for(let i=0;i<t.length;i+=n)e.push(t.slice(i,i+n));return e}}class lt{options;state="CLOSED";failureCount=0;lastFailureTime=0;nextAttemptTime=0;constructor(t){this.options=t}async execute(t){let n=Date.now();switch(this.state){case"OPEN":if(n<this.nextAttemptTime)throw new K("NETWORK_SERVICE_UNAVAILABLE","Circuit breaker is OPEN",{state:this.state,nextAttemptTime:this.nextAttemptTime});this.state="HALF_OPEN",this.options.onHalfOpen?.();break;case"HALF_OPEN":break;case"CLOSED":break}try{let e=await Promise.race([t(),new Promise((i,r)=>setTimeout(()=>r(new K("NETWORK_TIMEOUT","Circuit breaker timeout",{timeout:this.options.timeout})),this.options.timeout))]);if(this.state==="HALF_OPEN")this.state="CLOSED",this.failureCount=0,this.options.onClose?.();return e}catch(e){throw this.recordFailure(),e}}recordFailure(){if(this.failureCount++,this.lastFailureTime=Date.now(),this.failureCount>=this.options.failureThreshold)this.state="OPEN",this.nextAttemptTime=this.lastFailureTime+this.options.resetTimeout,this.options.onOpen?.()}getState(){return this.state}getFailureCount(){return this.failureCount}reset(){this.state="CLOSED",this.failureCount=0,this.lastFailureTime=0,this.nextAttemptTime=0}}class ht{maxRequests;windowMs;requests=[];constructor(t,n){this.maxRequests=t;this.windowMs=n}async acquire(){let t=Date.now();if(this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length>=this.maxRequests){let n=Math.min(...this.requests),e=this.windowMs-(t-n);if(e>0)return await new Promise((i)=>setTimeout(i,e)),this.acquire()}this.requests.push(t)}canMakeRequest(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),this.requests.length<this.maxRequests}getRemainingRequests(){let t=Date.now();return this.requests=this.requests.filter((n)=>t-n<this.windowMs),Math.max(0,this.maxRequests-this.requests.length)}}var gt=(t)=>({isSuccess:!0,isFailure:!1,value:t}),Kt=(t)=>({isSuccess:!1,isFailure:!0,error:t}),Vn={map(t,n){if(t.isSuccess)return gt(n(t.value));return t},flatMap(t,n){if(t.isSuccess)return n(t.value);return t},mapError(t,n){if(t.isFailure)return Kt(n(t.error));return t},unwrap(t){if(t.isSuccess)return t.value;throw t.error},unwrapOr(t,n){if(t.isSuccess)return t.value;return n},unwrapOrElse(t,n){if(t.isSuccess)return t.value;return n(t.error)},match(t,n){if(t.isSuccess)return n.ok(t.value);return n.fail(t.error)},async fromPromise(t){try{let n=await t;return gt(n)}catch(n){return Kt(n)}},isOk(t){return t.isSuccess},isFail(t){return t.isFailure},tap(t,n){return n(t),t},tapOk(t,n){if(t.isSuccess)n(t.value);return t},tapErr(t,n){if(t.isFailure)n(t.error);return t},expect(t,n){if(t.isSuccess)return t.value;throw Error(n,{cause:t.error})}};function Jt(){let t=globalThis;return t.__K_MSG_ENV__??t.__ENV__??t.process?.env??{}}function Jn(t){let n=Jt()[t];if(typeof n==="string")return n;if(n===void 0)return;return String(n)}var Wt=["PENDING","SENT","DELIVERED","FAILED","CANCELLED","UNKNOWN"],Yt=["DELIVERED","FAILED","CANCELLED","UNKNOWN"],Ct=["PENDING","SENT"],jt=new Set(Wt),Ft=new Set(Yt),Qt=new Set(Ct);function Yn(t){return jt.has(t)}function jn(t){return Ft.has(t)}function Qn(t){return Ft.has(t)}function Zn(t){return Qt.has(t)}function Ln(){return Ct}var Zt=["ALIMTALK","FRIENDTALK","SMS","LMS","MMS","NSA","VOICE","FAX","RCS_SMS","RCS_LMS","RCS_MMS","RCS_TPL","RCS_ITPL","RCS_LTPL"],Lt=new Set(Zt);function zn(t){return Lt.has(t)}var te=["PENDING","SENT","FAILED"],Xt="PENDING",ne=(t)=>{let n=typeof t==="string"?t.trim().toUpperCase():"";if(n==="PENDING"||n==="SENT"||n==="FAILED")return n;return Xt};export{Nt as validateFieldCryptoConfig,ut as validateErrorRetryPolicy,un as toCiphertextEnvelopeString,kn as setGlobalLogger,H as selectActiveKidByRollout,ft as resolveFieldMode,Jn as readRuntimeEnv,zt as parseErrorRetryPolicyFromJson,gt as ok,x as normalizeRetryAfterMs,tn as normalizeProviderError,Bt as normalizePhoneForHash,ne as normalizeMessageStatus,Dt as normalizeErrorRetryPolicy,Tn as loggerMiddleware,mn as logger,Qn as isTerminalDeliveryStatus,Zn as isPollableDeliveryStatus,jn as isKMsgTerminalStatus,zn as isKMsgMessageType,Yn as isKMsgDeliveryStatus,wn as isCryptoEnvelope,Jt as getRuntimeEnvSource,st as getRolloutKnownKids,Ln as getPollableStatuses,m as getLogger,Kt as fail,Kn as createVaultTransitKeyResolver,rt as createStaticKeyResolver,yn as createRollingKeyResolver,_ as createRefreshableKeyResolver,bn as createNoopFieldCryptoProvider,dt as createLogger,ln as createEnvKeyResolver,at as createDefaultMasker,cn as createAwsKmsKeyResolver,Sn as createAesGcmFieldCryptoProvider,An as assertFieldCryptoConfig,O as RetryHandler,Vn as Result,ht as RateLimiter,Xt as QUEUED_MESSAGE_STATUS,Y as Logger,qt as LogLevel,te as KNOWN_MESSAGE_STATUSES,E as KMsgErrorCode,K as KMsgError,Yt as KMSG_TERMINAL_STATUSES,Ct as KMSG_POLLABLE_STATUSES,Zt as KMSG_MESSAGE_TYPES,Wt as KMSG_DELIVERY_STATUSES,M as FieldCryptoError,R as ErrorUtils,lt as CircuitBreaker,j as BulkOperationHandler};
3
3
 
4
- //# debugId=28C35CCFF2625FAA64756E2164756E21
4
+ //# debugId=D66CA62885B2215B64756E2164756E21
5
5
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k-msg/core",
3
- "version": "0.29.5",
3
+ "version": "0.29.7",
4
4
  "packageManager": "bun@1.3.11",
5
5
  "description": "Core types and interfaces for K-Message platform",
6
6
  "type": "module",
@@ -39,8 +39,8 @@
39
39
  "zod": "^4.0.14"
40
40
  },
41
41
  "devDependencies": {
42
- "@types/bun": "^1.3.11",
43
- "typescript": "^5.7.2"
42
+ "@types/bun": "^1.3.14",
43
+ "typescript": "^6.0.3"
44
44
  },
45
45
  "peerDependencies": {},
46
46
  "files": [