@k-msg/core 0.25.1 → 0.26.0
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/errors.d.ts +47 -0
- package/dist/index.js +3 -3
- package/dist/index.js.map +6 -5
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +6 -5
- package/dist/types/delivery-status.d.ts +8 -0
- package/dist/types/message.d.ts +2 -0
- package/package.json +1 -1
package/dist/errors.d.ts
CHANGED
|
@@ -42,6 +42,49 @@ export interface ErrorRetryPolicy {
|
|
|
42
42
|
*/
|
|
43
43
|
retryAfterMs?: (error: KMsgError) => number | undefined;
|
|
44
44
|
}
|
|
45
|
+
export type ErrorRetryPolicyMode = "safe" | "compat";
|
|
46
|
+
export interface ErrorRetryPolicyIssue {
|
|
47
|
+
code: string;
|
|
48
|
+
message: string;
|
|
49
|
+
path: string;
|
|
50
|
+
}
|
|
51
|
+
export interface ErrorRetryPolicyValidationResult {
|
|
52
|
+
policy: ErrorRetryPolicy | null;
|
|
53
|
+
issues: ErrorRetryPolicyIssue[];
|
|
54
|
+
}
|
|
55
|
+
export interface ErrorRetryPolicyNormalizeOptions {
|
|
56
|
+
mode?: ErrorRetryPolicyMode;
|
|
57
|
+
}
|
|
58
|
+
export type ProviderErrorSource = "metadata" | "details" | "http" | "fallback" | "policy" | "input";
|
|
59
|
+
export interface NormalizedProviderErrorSources {
|
|
60
|
+
code: ProviderErrorSource;
|
|
61
|
+
classification: ProviderErrorSource;
|
|
62
|
+
providerErrorCode?: ProviderErrorSource;
|
|
63
|
+
providerErrorText?: ProviderErrorSource;
|
|
64
|
+
httpStatus?: ProviderErrorSource;
|
|
65
|
+
requestId?: ProviderErrorSource;
|
|
66
|
+
retryAfterMs?: ProviderErrorSource;
|
|
67
|
+
causeChain?: ProviderErrorSource;
|
|
68
|
+
attempt?: ProviderErrorSource;
|
|
69
|
+
}
|
|
70
|
+
export interface NormalizedProviderError {
|
|
71
|
+
code: KMsgErrorCode;
|
|
72
|
+
classification: ProviderRetryHint;
|
|
73
|
+
providerErrorCode?: string;
|
|
74
|
+
providerErrorText?: string;
|
|
75
|
+
httpStatus?: number;
|
|
76
|
+
requestId?: string;
|
|
77
|
+
retryAfterMs?: number;
|
|
78
|
+
causeChain?: unknown[];
|
|
79
|
+
attempt?: number;
|
|
80
|
+
sources: NormalizedProviderErrorSources;
|
|
81
|
+
}
|
|
82
|
+
export interface NormalizeProviderErrorOptions {
|
|
83
|
+
mode?: ErrorRetryPolicyMode;
|
|
84
|
+
policy?: ErrorRetryPolicy;
|
|
85
|
+
attempt?: number;
|
|
86
|
+
defaultCode?: KMsgErrorCode;
|
|
87
|
+
}
|
|
45
88
|
export declare const normalizeRetryAfterMs: (value: unknown) => number | undefined;
|
|
46
89
|
export declare class KMsgError extends Error {
|
|
47
90
|
readonly code: KMsgErrorCode;
|
|
@@ -74,6 +117,10 @@ export declare class KMsgError extends Error {
|
|
|
74
117
|
causeChain: unknown[] | undefined;
|
|
75
118
|
};
|
|
76
119
|
}
|
|
120
|
+
export declare function validateErrorRetryPolicy(input: unknown, options?: ErrorRetryPolicyNormalizeOptions): ErrorRetryPolicyValidationResult;
|
|
121
|
+
export declare function normalizeErrorRetryPolicy(input: unknown, options?: ErrorRetryPolicyNormalizeOptions): ErrorRetryPolicy | null;
|
|
122
|
+
export declare function parseErrorRetryPolicyFromJson(raw: string, options?: ErrorRetryPolicyNormalizeOptions): ErrorRetryPolicy | null;
|
|
123
|
+
export declare function normalizeProviderError(error: unknown, options?: NormalizeProviderErrorOptions): NormalizedProviderError;
|
|
77
124
|
export declare const ErrorUtils: {
|
|
78
125
|
isRetryable(error: unknown, policy?: ErrorRetryPolicy): boolean;
|
|
79
126
|
classifyForRetry(error: unknown, policy?: ErrorRetryPolicy): ProviderRetryHint;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var{defineProperty:B,getOwnPropertyNames:he,getOwnPropertyDescriptor:ue}=Object,me=Object.prototype.hasOwnProperty;var z=new WeakMap,ge=(e)=>{var t=z.get(e),i;if(t)return t;if(t=B({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function")he(e).map((r)=>!me.call(t,r)&&B(t,r,{get:()=>e[r],enumerable:!(i=ue(e,r))||i.enumerable}));return z.set(e,t),t};var Ce=(e,t)=>{for(var i in t)B(e,i,{get:t[i],enumerable:!0,configurable:!0,set:(r)=>t[i]=()=>r})};var Xe={};Ce(Xe,{validateFieldCryptoConfig:()=>ae,toCiphertextEnvelopeString:()=>Ne,setGlobalLogger:()=>je,selectActiveKidByRollout:()=>R,resolveFieldMode:()=>J,readRuntimeEnv:()=>Ye,ok:()=>X,normalizeRetryAfterMs:()=>q,normalizePhoneForHash:()=>de,normalizeMessageStatus:()=>Ze,loggerMiddleware:()=>Je,logger:()=>Ge,isCryptoEnvelope:()=>Ie,getRuntimeEnvSource:()=>le,getRolloutKnownKids:()=>U,getLogger:()=>K,fail:()=>L,createVaultTransitKeyResolver:()=>Me,createStaticKeyResolver:()=>j,createRollingKeyResolver:()=>ke,createRefreshableKeyResolver:()=>S,createNoopFieldCryptoProvider:()=>Be,createLogger:()=>W,createEnvKeyResolver:()=>Oe,createDefaultMasker:()=>V,createAwsKmsKeyResolver:()=>Re,createAesGcmFieldCryptoProvider:()=>_e,assertFieldCryptoConfig:()=>Ee,RetryHandler:()=>F,Result:()=>Ve,RateLimiter:()=>Z,QUEUED_MESSAGE_STATUS:()=>Qe,Logger:()=>T,LogLevel:()=>ye,KNOWN_MESSAGE_STATUSES:()=>We,KMsgErrorCode:()=>w,KMsgError:()=>h,FieldCryptoError:()=>v,ErrorUtils:()=>P,CircuitBreaker:()=>Q,BulkOperationHandler:()=>D});module.exports=ge(Xe);var w;((d)=>{d.INVALID_REQUEST="INVALID_REQUEST";d.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";d.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";d.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";d.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";d.NETWORK_ERROR="NETWORK_ERROR";d.NETWORK_TIMEOUT="NETWORK_TIMEOUT";d.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";d.PROVIDER_ERROR="PROVIDER_ERROR";d.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";d.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";d.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";d.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";d.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";d.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";d.UNKNOWN_ERROR="UNKNOWN_ERROR"})(w||={});var Ke={["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"}},ee=new Set(["NETWORK_ERROR","RATE_LIMIT_EXCEEDED","NETWORK_TIMEOUT","NETWORK_SERVICE_UNAVAILABLE","PROVIDER_ERROR","UNKNOWN_ERROR"]),te=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"]),C=(e)=>{if(typeof e!=="number"||Number.isNaN(e)||!Number.isFinite(e))return;return Math.trunc(e)},q=(e)=>{let t=C(e);if(t===void 0||t<0)return;return t},N=(e)=>{if(typeof e!=="string")return;return e.toLowerCase().trim()},ie=(e)=>{if(e>=500)return"retryable";if(e===408||e===425||e===429)return"retryable";return"non_retryable"},re=(e)=>{let t=e.toLowerCase();if(t.includes("timeout")||t.includes("temporar")||t.includes("network")||t.includes("retry"))return"retryable";return};class h extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(e,t,i,r={}){super(t);if(this.name="KMsgError",this.code=e,this.details=i,this.providerErrorCode=r.providerErrorCode,this.providerErrorText=r.providerErrorText,this.httpStatus=C(r.httpStatus),this.requestId=typeof r.requestId==="string"?r.requestId:void 0,this.retryAfterMs=C(r.retryAfterMs),this.attempt=C(r.attempt),Array.isArray(r.causeChain))this.causeChain=r.causeChain;else if(r.causeChain!==void 0)this.causeChain=[r.causeChain];if(Error.captureStackTrace)Error.captureStackTrace(this,h)}getLocalizedMessage(e="ko"){let t=Ke[this.code];if(t?.[e])return t[e];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 P={isRetryable(e,t={}){return P.classifyForRetry(e,t)==="retryable"},classifyForRetry(e,t={}){if(e instanceof h){if(new Set(t.retryableCodes??Array.from(ee)).has(e.code))return"retryable";if(new Set(t.nonRetryableCodes??Array.from(te)).has(e.code))return"non_retryable";if(e.httpStatus!==void 0)return ie(e.httpStatus);let a=re(e.message);if(a)return a;if(t.classifyByMessage&&e.message){let c=t.classifyByMessage(e.message);if(c)return c}if(t.fallback)return t.fallback;return"non_retryable"}let i=e&&typeof e==="object"?e:void 0,r=N(i?.status)??N(i?.statusCode)??N(i?.code),n=C(i?.status)??C(i?.statusCode)??C(i?.httpStatus);if(typeof r==="string"&&r.startsWith("5"))return"retryable";if(n!==void 0){if(t.classifyByStatusCode)return t.classifyByStatusCode(n);return ie(n)}let s=typeof i?.message==="string"?re(i.message):void 0;if(s)return s;if(t.classifyByMessage&&typeof i?.message==="string"){let o=t.classifyByMessage(i.message);if(o)return o}return t.fallback??"non_retryable"},resolveRetryAfterMs(e,t){if(t?.retryAfterMs){let i=t.retryAfterMs(e),r=q(i);if(r!==void 0)return r}if(e.retryAfterMs!==void 0)return q(e.retryAfterMs);if(e.code==="RATE_LIMIT_EXCEEDED"&&e.retryAfterMs===void 0)return;return},isUnknownStatus:(e)=>{if(e===void 0||Number.isNaN(e)||!Number.isFinite(e))return!1;return e<500},toRetryMetadata(e){return{providerErrorCode:e.providerErrorCode,providerErrorText:e.providerErrorText,httpStatus:e.httpStatus,requestId:e.requestId,retryAfterMs:e.retryAfterMs,attempt:e.attempt,causeChain:e.causeChain}},withAttempt(e,t){return new h(e.code,e.message,e.details,{...P.toRetryMetadata(e),attempt:C(t)})},DEFAULT_RETRYABLE_ERROR_CODES:ee,DEFAULT_NON_RETRYABLE_ERROR_CODES:te};function Fe(e){switch(e){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 v extends h{kind;fieldPath;failMode;openFallback;constructor(e,t,i,r={}){super(Fe(e),t,i,r);this.name="FieldCryptoError",this.kind=e,this.fieldPath=typeof r.fieldPath==="string"?r.fieldPath:void 0,this.failMode=r.failMode,this.openFallback=r.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}var be=["tenantId","providerId","messageId"];function k(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function Ae(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(e<=0||e>100)return;return e}function ne(e){let t=[];for(let i of e){let r=k(i.kid),n=Ae(i.percentage);if(!r||n===void 0)continue;t.push({kid:r,percentage:n})}return t}function Pe(e,t,i){let r=t.map((n)=>{let s=e[n];return typeof s==="string"?s:""}).join("|");return`${i}::${r}`}function we(e){let t=2166136261;for(let i=0;i<e.length;i+=1)t^=e.charCodeAt(i),t=t*16777619>>>0;return t>>>0}function ve(e,t){let i=0;for(let r of e)if(i+=r.percentage,t<i)return r.kid;return}function R(e,t,i){let r=ne(t.buckets),n=k(t.defaultKid)??k(i);if(r.length===0)return n;let s=k(t.seed)??"kmsg-rollout-v1",o=t.stickyFields??be,p=Pe(e,o,s),a=we(p)%100;return ve(r,a)??n}function U(e){return ne(e.buckets).map((t)=>t.kid)}function A(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function H(e){if(!Array.isArray(e))return[];return e.map((t)=>A(t)).filter((t)=>Boolean(t))}function $(e){let t=[],i=new Set;for(let r of e){let n=A(r);if(!n||i.has(n))continue;i.add(n),t.push(n)}return t}function Se(e){return A(e.providerId)??"default"}function j(e){let t=A(e.activeKid)??"default",i=$([t,...H(e.decryptKids)]);return{async resolveEncryptKey(){return{kid:t}},async resolveDecryptKeys(){return i}}}function S(e){let t=typeof e.cacheTtlMs==="number"&&e.cacheTtlMs>=0?Math.trunc(e.cacheTtlMs):30000,i=A(e.fallback?.activeKid),r=H(e.fallback?.decryptKids),n;async function s(o){let p=Date.now();if(n&&p<n.expiresAt)return n.value;let a=await e.provider.loadKeySet(o),c=A(a.activeKid)??i??Se(o),y=$([c,...H(a.decryptKids),...r]),l={activeKid:c,decryptKids:y,refreshedAt:Date.now()};return n={value:l,expiresAt:Date.now()+t},l}return{async resolveEncryptKey(o){return{kid:(await s(o)).activeKid}},async resolveDecryptKeys(o){let p=await s(o);return p.decryptKids??[p.activeKid]}}}function ke(e,t){return{async resolveEncryptKey(i){let r=await e.resolveEncryptKey(i);return{kid:R(i,t,r.kid)??r.kid}},async resolveDecryptKeys(i){let r=await e.resolveEncryptKey(i),n=e.resolveDecryptKeys?await e.resolveDecryptKeys(i):[r.kid],s=R(i,t,r.kid),o=U(t);return $([...s?[s]:[],r.kid,...n??[],...o])}}}function Re(e){return S({provider:{async loadKeySet(i){return e.client.getKeyState({...i,...e.keyAlias?{keyAlias:e.keyAlias}:{},...e.region?{region:e.region}:{}})}},cacheTtlMs:e.cacheTtlMs,fallback:{activeKid:e.fallbackActiveKid,decryptKids:e.fallbackDecryptKids}})}function x(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function se(e,t){return x(e[t])}function xe(e,t){if(!e)return[];return e.split(t).map((i)=>x(i)).filter((i)=>Boolean(i))}function Oe(e={}){let t=e.env??(typeof process<"u"?process.env:{}),i=x(e.delimiter)??",",r=e.activeKidEnv??"KMSG_ACTIVE_KID",n=e.decryptKidsEnv??"KMSG_DECRYPT_KIDS",s=se(t,r)??x(e.fallbackActiveKid)??"default",o=[s,...xe(se(t,n),i),...e.fallbackDecryptKids??[]];return j({activeKid:s,decryptKids:o})}function Me(e){return S({provider:{async loadKeySet(i){return e.client.getKeyState({...i,...e.mountPath?{mountPath:e.mountPath}:{},...e.keyName?{keyName:e.keyName}:{},...e.namespace?{namespace:e.namespace}:{}})}},cacheTtlMs:e.cacheTtlMs,fallback:{activeKid:e.fallbackActiveKid,decryptKids:e.fallbackDecryptKids}})}function G(e){return typeof e==="function"}function oe(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function J(e,t,i){let r=e.fields[t];if(r)return r;if(t.startsWith("metadata.")){let n=e.fields["metadata.*"];if(n)return n}return i}function ae(e,t={}){let i=[];if(!e||typeof e!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!e.provider||typeof e.provider!=="object")i.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!G(e.provider.encrypt))i.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!G(e.provider.decrypt))i.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!G(e.provider.hash))i.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!e.fields||typeof e.fields!=="object")i.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(e.fields);if(s.length===0)i.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[o,p]of s){if(!oe(o))i.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(p!=="plain"&&p!=="encrypt"&&p!=="encrypt+hash"&&p!=="mask")i.push({message:`unsupported field mode: ${String(p)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${o}`})}}let r=e.failMode??"closed",n=e.openFallback??"masked";if(r==="open"&&n==="plaintext"&&e.unsafeAllowPlaintextStorage!==!0)i.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(e.aadFields)){if(e.aadFields.length===0)i.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let s=0;s<e.aadFields.length;s+=1){let o=e.aadFields[s];if(!oe(o))i.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${s}]`})}}if(t.secureMode&&!t.compatPlainColumns){let s=J(e,"to","encrypt+hash"),o=J(e,"from","encrypt+hash");if(s==="plain")i.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(o==="plain")i.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:i.length===0,issues:i}}function Ee(e,t={}){let i=ae(e,t);if(i.valid)return;let r=i.issues[0];if(!r)throw new v("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:i.issues});throw new v("config",r.message,{rule:r.rule,path:r.path,hint:r.hint,issues:i.issues},{fieldPath:r.path})}function O(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),i=typeof globalThis<"u"?globalThis.Buffer:void 0;return(i?i.from(t).toString("base64"):btoa(String.fromCharCode(...t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function M(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.length%4===0?t:`${t}${"=".repeat(4-t.length%4)}`,r=typeof globalThis<"u"?globalThis.Buffer:void 0;if(r)return new Uint8Array(r.from(i,"base64"));let n=atob(i),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}function pe(e,t){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(t==="base64url")return M(e);return new TextEncoder().encode(e)}function Te(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);return Array.from(t).map((i)=>i.toString(16).padStart(2,"0")).join("")}function g(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function ce(e){let t=JSON.parse(e);if(!t||typeof t!=="object"||typeof t.v!=="number"||typeof t.alg!=="string"||typeof t.kid!=="string"||typeof t.iv!=="string"||typeof t.tag!=="string"||typeof t.ct!=="string")throw Error("Invalid ciphertext envelope");return t}function De(e){if(typeof e==="string")return e;return JSON.stringify(e)}function Ie(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.v==="number"&&typeof t.alg==="string"&&typeof t.kid==="string"&&typeof t.iv==="string"&&typeof t.tag==="string"&&typeof t.ct==="string"}function de(e){let t=String(e??"").trim();if(t.length===0)return"";let i=t.startsWith("+"),r=t.replace(/\D/g,"");return i?`+${r}`:r}function V(e=3,t=2){return(i)=>{let r=String(i??"");if(r.length<=e+t)return"*".repeat(Math.max(0,r.length));let n=r.slice(0,e),s=r.slice(-t);return`${n}${"*".repeat(r.length-e-t)}${s}`}}function _e(e){let t=e.algorithm??"A256GCM",i=e.keyEncoding??"base64url",r=e.hashKeyEncoding??i,n=new Map,s=new Map,o=(a)=>{let c=n.get(a);if(c)return c;let y=e.keys[a];if(!y)throw Error(`Unknown encryption key id: ${a}`);let l=pe(y,i),f=crypto.subtle.importKey("raw",g(l),"AES-GCM",!1,["encrypt","decrypt"]);return n.set(a,f),f},p=(a)=>{let c=s.get(a);if(c)return c;let y=e.hashKeys?.[a]??e.keys[a];if(!y)throw Error(`Unknown hash key id: ${a}`);let l=pe(y,r),f=crypto.subtle.importKey("raw",g(l),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return s.set(a,f),f};return{async encrypt(a){let c=a.kid??e.activeKid,y=await o(c),l=crypto.getRandomValues(new Uint8Array(12)),f=new TextEncoder().encode(JSON.stringify(a.aad??{})),u=new TextEncoder().encode(a.value),m=await crypto.subtle.encrypt({name:"AES-GCM",iv:g(l),additionalData:g(f),tagLength:128},y,g(u)),b=new Uint8Array(m),d=b.slice(b.length-16),I=b.slice(0,b.length-16);return{ciphertext:{v:1,alg:t,kid:c,iv:O(l),tag:O(d),ct:O(I)},kid:c}},async decrypt(a){let c=ce(a.ciphertext),y=a.candidateKids&&a.candidateKids.length>0?a.candidateKids:[c.kid],l=M(c.iv),f=M(c.tag),u=M(c.ct),m=new Uint8Array(u.length+f.length);m.set(u,0),m.set(f,u.length);let b=new TextEncoder().encode(JSON.stringify(a.aad??{})),d;for(let I of y)try{let _=await o(I),fe=await crypto.subtle.decrypt({name:"AES-GCM",iv:g(l),additionalData:g(b),tagLength:128},_,g(m));return new TextDecoder().decode(new Uint8Array(fe))}catch(_){d=_}throw Error(`Failed to decrypt ciphertext: ${d instanceof Error?d.message:String(d??"unknown")}`)},async hash(a){let c=a.kid??e.activeKid,y=await p(c),l=await crypto.subtle.sign("HMAC",y,g(new TextEncoder().encode(a.value)));return Te(l)},mask(a){return V()(a.value)}}}function Be(){return{encrypt(e){return{ciphertext:JSON.stringify({v:1,alg:"NOOP",kid:"noop",iv:"",tag:"",ct:e.value})}},decrypt(e){try{return ce(e.ciphertext).ct}catch{return e.ciphertext}},hash(e){let t=de(e.value);return O(new TextEncoder().encode(t))},mask(e){return V()(e.value)}}}function Ne(e){return De(e)}var ye;((n)=>{n.DEBUG="DEBUG";n.INFO="INFO";n.WARN="WARN";n.ERROR="ERROR"})(ye||={});var qe=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function Ue(e){let t=e.toLowerCase();return qe.some((i)=>t.includes(i.toLowerCase()))}function He(e){let t=e.trim();if(t.length<=4)return"***";if(t.includes("@")){let[n,s]=t.split("@");return`${n.slice(0,2)}${"*".repeat(Math.max(1,n.length-2))}@${s}`}let i=t.slice(0,3),r=t.slice(-2);return`${i}${"*".repeat(Math.max(1,t.length-5))}${r}`}function Y(e,t){if(t===void 0||t===null)return t;if(Ue(e)){if(typeof t==="string")return He(t);if(typeof t==="number"||typeof t==="boolean")return"***";if(Array.isArray(t))return"[REDACTED]";if(typeof t==="object")return"[REDACTED]"}if(Array.isArray(t))return t.map((i)=>Y(e,i));if(typeof t==="object"){let i={};for(let[r,n]of Object.entries(t))i[r]=Y(r,n);return i}return t}function $e(e){let t={};for(let[i,r]of Object.entries(e))t[i]=Y(i,r);return t}class T{config;context;constructor(e={},t={}){this.context=e,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...t}}shouldLog(e){let t=["DEBUG","INFO","WARN","ERROR"];return t.indexOf(e)>=t.indexOf(this.config.level)}formatMessage(e){let t=$e(e.context);if(this.config.enableJson)return JSON.stringify({level:e.level,message:e.message,timestamp:e.timestamp.toISOString(),context:t,...e.error&&{error:{name:e.error.name,message:e.error.message,stack:e.error.stack}},...e.duration&&{duration:e.duration}});let i=e.timestamp.toISOString(),r=this.config.enableColors?this.colorizeLevel(e.level):e.level,n=Object.keys(t).length>0?` [${Object.entries(t).map(([o,p])=>`${o}=${p}`).join(", ")}]`:"",s=`${i} ${r}${n}: ${e.message}`;if(e.duration!==void 0)s+=` (${e.duration}ms)`;if(e.error)s+=`
|
|
2
|
-
${
|
|
1
|
+
var{defineProperty:V,getOwnPropertyNames:Et,getOwnPropertyDescriptor:xt}=Object,Mt=Object.prototype.hasOwnProperty;var pt=new WeakMap,vt=(t)=>{var e=pt.get(t),n;if(e)return e;if(e=V({},"__esModule",{value:!0}),t&&typeof t==="object"||typeof t==="function")Et(t).map((i)=>!Mt.call(e,i)&&V(e,i,{get:()=>t[i],enumerable:!(n=xt(t,i))||n.enumerable}));return pt.set(t,e),e};var It=(t,e)=>{for(var n in e)V(t,n,{get:e[n],enumerable:!0,configurable:!0,set:(i)=>e[n]=()=>i})};var Oe={};It(Oe,{validateFieldCryptoConfig:()=>Pt,validateErrorRetryPolicy:()=>gt,toCiphertextEnvelopeString:()=>fe,setGlobalLogger:()=>he,selectActiveKidByRollout:()=>N,resolveFieldMode:()=>L,readRuntimeEnv:()=>Fe,parseErrorRetryPolicyFromJson:()=>$t,ok:()=>it,normalizeRetryAfterMs:()=>x,normalizeProviderError:()=>Gt,normalizePhoneForHash:()=>wt,normalizeMessageStatus:()=>Re,normalizeErrorRetryPolicy:()=>Kt,loggerMiddleware:()=>Ke,logger:()=>ge,isTerminalDeliveryStatus:()=>we,isPollableDeliveryStatus:()=>me,isKMsgTerminalStatus:()=>ue,isKMsgMessageType:()=>Te,isKMsgDeliveryStatus:()=>Se,isCryptoEnvelope:()=>pe,getRuntimeEnvSource:()=>bt,getRolloutKnownKids:()=>W,getPollableStatuses:()=>be,getLogger:()=>D,fail:()=>st,createVaultTransitKeyResolver:()=>ne,createStaticKeyResolver:()=>Q,createRollingKeyResolver:()=>Xt,createRefreshableKeyResolver:()=>v,createNoopFieldCryptoProvider:()=>oe,createLogger:()=>tt,createEnvKeyResolver:()=>ee,createDefaultMasker:()=>X,createAwsKmsKeyResolver:()=>zt,createAesGcmFieldCryptoProvider:()=>ye,assertFieldCryptoConfig:()=>ie,RetryHandler:()=>k,Result:()=>Ce,RateLimiter:()=>nt,QUEUED_MESSAGE_STATUS:()=>Ot,Logger:()=>$,LogLevel:()=>mt,KNOWN_MESSAGE_STATUSES:()=>ke,KMsgErrorCode:()=>O,KMsgError:()=>K,KMSG_TERMINAL_STATUSES:()=>Tt,KMSG_POLLABLE_STATUSES:()=>rt,KMSG_MESSAGE_TYPES:()=>Rt,KMSG_DELIVERY_STATUSES:()=>Dt,FieldCryptoError:()=>M,ErrorUtils:()=>R,CircuitBreaker:()=>et,BulkOperationHandler:()=>H});module.exports=vt(Oe);var O;((d)=>{d.INVALID_REQUEST="INVALID_REQUEST";d.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";d.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";d.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";d.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";d.NETWORK_ERROR="NETWORK_ERROR";d.NETWORK_TIMEOUT="NETWORK_TIMEOUT";d.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";d.PROVIDER_ERROR="PROVIDER_ERROR";d.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";d.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";d.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";d.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";d.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";d.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";d.UNKNOWN_ERROR="UNKNOWN_ERROR"})(O||={});var Nt={["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"}},_t=new Set(Object.values(O)),yt=new Set(["NETWORK_ERROR","RATE_LIMIT_EXCEEDED","NETWORK_TIMEOUT","NETWORK_SERVICE_UNAVAILABLE","PROVIDER_ERROR","UNKNOWN_ERROR"]),ot=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 e=P(t);if(e===void 0||e<0)return;return e},G=(t)=>{if(typeof t!=="string")return;return t.toLowerCase().trim()},Bt=(t)=>{if(typeof t!=="string")return;let e=t.trim();return e.length>0?e:void 0},S=(t)=>{return typeof t==="object"&&t!==null&&!Array.isArray(t)},m=(t,e)=>{for(let n of e)if(n in t)return t[n];return},Ut=(t)=>{return t.length>0?t:"$"},dt=(t)=>{return t==="compat"?"compat":"safe"},ft=(t)=>{if(t>=500)return"retryable";if(t===408||t===425||t===429)return"retryable";return"non_retryable"},ct=(t)=>{let e=t.toLowerCase();if(e.includes("timeout")||e.includes("temporar")||e.includes("network")||e.includes("retry"))return"retryable";return};class K extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(t,e,n,i={}){super(e);if(this.name="KMsgError",this.code=t,this.details=n,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 e=Nt[this.code];if(e?.[t])return e[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 b=(t,e)=>{let n=P(t);if(n!==void 0)return n;if(e==="compat"&&typeof t==="string"){let i=Number(t.trim());if(Number.isFinite(i))return Math.trunc(i)}return},J=(t,e)=>{let n=Bt(t);if(n)return n;if(e==="compat"&&(typeof t==="number"||typeof t==="boolean"))return String(t);return},ht=(t)=>{if(typeof t!=="string")return;let e=t.trim().toUpperCase();if(!_t.has(e))return;return e},T=(t,e)=>{t.push({...e,path:Ut(e.path)})},at=(t,e,n,i)=>{if(t===void 0)return[];let r=(()=>{if(Array.isArray(t))return t;if(n==="compat"&&typeof t==="string")return t.split(",").map((o)=>o.trim()).filter((o)=>o.length>0);return T(i,{code:"invalid_type",message:"expected array of KMsgErrorCode values",path:e}),[]})(),s=[],p=new Set;for(let o=0;o<r.length;o+=1){let y=r[o],f=ht(typeof y==="string"?y:n==="compat"?String(y):y);if(!f){T(i,{code:"unknown_code",message:`unknown retry policy code: ${String(y)}`,path:`${e}[${o}]`});continue}if(p.has(f)){T(i,{code:"duplicate_code",message:`duplicate retry policy code: ${f}`,path:`${e}[${o}]`});continue}p.add(f),s.push(f)}return s},qt=(t,e,n)=>{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(e==="compat"&&typeof t==="boolean")return t?"retryable":"non_retryable";T(n,{code:"invalid_fallback",message:`invalid fallback value: ${String(t)}`,path:"fallback"});return};function gt(t,e={}){let n=dt(e.mode),i=[];if(!S(t))return T(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 l of Object.keys(t)){if(r.has(l))continue;T(i,{code:"unknown_field",message:`unknown retry policy field: ${l}`,path:l})}let s=at(t.retryableCodes,"retryableCodes",n,i),p=at(t.nonRetryableCodes,"nonRetryableCodes",n,i),o=qt(t.fallback,n,i),y=new Set(s),f=new Set(p);for(let l of y){if(!f.has(l))continue;y.delete(l),T(i,{code:"conflicting_code",message:`code '${l}' is both retryable and nonRetryable; nonRetryable wins`,path:"retryableCodes"})}let a={...y.size>0?{retryableCodes:Array.from(y)}:{},...f.size>0?{nonRetryableCodes:Array.from(f)}:{},...o?{fallback:o}:{}};return{policy:a.retryableCodes!==void 0||a.nonRetryableCodes!==void 0||a.fallback!==void 0?a:null,issues:i}}function Kt(t,e={}){return gt(t,e).policy}function $t(t,e={}){if(typeof t!=="string"||t.trim().length===0)return null;try{let n=JSON.parse(t);return Kt(n,e)}catch{return null}}var lt=(t,e)=>{let n=t.response;if(!S(n))return;return b(m(n,["status","statusCode","httpStatus"]),e)},Ht=(t,e)=>{if(t instanceof K&&Array.isArray(t.causeChain))return t.causeChain.slice();if(S(t)){let s=t.causeChain;if(Array.isArray(s))return s.slice();let p=t.details;if(e==="compat"&&S(p)){let o=p.causeChain;if(Array.isArray(o))return o.slice();if(o!==void 0)return[o]}}let n=[],i=new Set,r=t;for(let s=0;s<8;s+=1){if(!S(r))break;let p=r.cause;if(p===void 0||i.has(p))break;i.add(p),n.push(p),r=p}return n.length>0?n:void 0},Vt=(t)=>{if(t instanceof Error&&typeof t.message==="string")return t.message;if(S(t)&&typeof t.message==="string")return t.message;return typeof t==="string"?t:"Unknown error"};function Gt(t,e={}){let n=dt(e.mode),r=e.defaultCode??"UNKNOWN_ERROR",s={code:"fallback",classification:e.policy?"policy":"fallback"},p,o,y,f,a,h,l,A=(c)=>{if(c.providerErrorCode!==void 0)p=c.providerErrorCode,s.providerErrorCode="metadata";if(c.providerErrorText!==void 0)o=c.providerErrorText,s.providerErrorText="metadata";if(c.httpStatus!==void 0)y=c.httpStatus,s.httpStatus="metadata";if(c.requestId!==void 0)f=c.requestId,s.requestId="metadata";if(c.retryAfterMs!==void 0)a=x(c.retryAfterMs),s.retryAfterMs="metadata";if(c.attempt!==void 0)h=b(c.attempt,n),s.attempt="metadata";if(Array.isArray(c.causeChain))l=c.causeChain.slice(),s.causeChain="metadata"},C=(c,F)=>{if(p===void 0){let g=J(m(c,["providerErrorCode","errorCode","resultCode"]),n);if(g!==void 0)p=g,s.providerErrorCode=F}if(o===void 0){let g=J(m(c,["providerErrorText","errorMessage","msg","message"]),n);if(g!==void 0)o=g,s.providerErrorText=F}if(y===void 0){let g=b(m(c,["httpStatus","statusCode","status"]),n)??lt(c,n);if(g!==void 0)y=g,s.httpStatus=F==="details"?"details":"http"}if(f===void 0){let g=J(m(c,["requestId","request_id","reqId","traceId"]),n);if(g!==void 0)f=g,s.requestId=F}if(a===void 0){let g=x(b(m(c,["retryAfterMs","retry_after_ms","retryAfter"]),n));if(g!==void 0)a=g,s.retryAfterMs=F}if(h===void 0){let g=b(c.attempt,n);if(g!==void 0&&g>0)h=g,s.attempt=F}};if(t instanceof K){if(r=t.code,s.code="input",A(t),n==="compat"&&S(t.details))C(t.details,"details")}else if(S(t)){let c=ht(m(t,["code","errorCode","resultCode"]));if(c!==void 0)r=c,s.code="input";else if(y===void 0){let F=b(m(t,["httpStatus","statusCode","status"]),n)??lt(t,n);if(F!==void 0&&F>=500)r="PROVIDER_ERROR",s.code="http"}if(C(t,"input"),n==="compat"&&S(t.details))C(t.details,"details")}if(l===void 0){let c=Ht(t,n);if(c!==void 0)l=c,s.causeChain="input"}if(e.attempt!==void 0&&b(e.attempt,n)!==void 0){let c=b(e.attempt,n);if(c!==void 0&&c>0)h=c,s.attempt="input"}let w=new K(r,Vt(t),void 0,{providerErrorCode:p,providerErrorText:o,httpStatus:y,requestId:f,retryAfterMs:a,attempt:h,causeChain:l}),d=R.classifyForRetry(w,e.policy);return{code:r,classification:d,...p!==void 0?{providerErrorCode:p}:{},...o!==void 0?{providerErrorText:o}:{},...y!==void 0?{httpStatus:y}:{},...f!==void 0?{requestId:f}:{},...a!==void 0?{retryAfterMs:a}:{},...h!==void 0?{attempt:h}:{},...l!==void 0?{causeChain:l}:{},sources:s}}var R={isRetryable(t,e={}){return R.classifyForRetry(t,e)==="retryable"},classifyForRetry(t,e={}){if(t instanceof K){if(new Set(e.retryableCodes??Array.from(yt)).has(t.code))return"retryable";if(new Set(e.nonRetryableCodes??Array.from(ot)).has(t.code))return"non_retryable";if(t.httpStatus!==void 0)return ft(t.httpStatus);let y=ct(t.message);if(y)return y;if(e.classifyByMessage&&t.message){let f=e.classifyByMessage(t.message);if(f)return f}if(e.fallback)return e.fallback;return"non_retryable"}let n=t&&typeof t==="object"?t:void 0,i=G(n?.status)??G(n?.statusCode)??G(n?.code),r=P(n?.status)??P(n?.statusCode)??P(n?.httpStatus);if(typeof i==="string"&&i.startsWith("5"))return"retryable";if(r!==void 0){if(e.classifyByStatusCode)return e.classifyByStatusCode(r);return ft(r)}let s=typeof n?.message==="string"?ct(n.message):void 0;if(s)return s;if(e.classifyByMessage&&typeof n?.message==="string"){let p=e.classifyByMessage(n.message);if(p)return p}return e.fallback??"non_retryable"},resolveRetryAfterMs(t,e){if(e?.retryAfterMs){let n=e.retryAfterMs(t),i=x(n);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,e){return new K(t.code,t.message,t.details,{...R.toRetryMetadata(t),attempt:P(e)})},DEFAULT_RETRYABLE_ERROR_CODES:yt,DEFAULT_NON_RETRYABLE_ERROR_CODES:ot};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,e,n,i={}){super(Jt(t),e,n,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 Wt=["tenantId","providerId","messageId"];function I(t){if(typeof t!=="string")return;let e=t.trim();return e.length>0?e:void 0}function Yt(t){if(typeof t!=="number"||!Number.isFinite(t))return;if(t<=0||t>100)return;return t}function Ct(t){let e=[];for(let n of t){let i=I(n.kid),r=Yt(n.percentage);if(!i||r===void 0)continue;e.push({kid:i,percentage:r})}return e}function jt(t,e,n){let i=e.map((r)=>{let s=t[r];return typeof s==="string"?s:""}).join("|");return`${n}::${i}`}function Qt(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=e*16777619>>>0;return e>>>0}function Zt(t,e){let n=0;for(let i of t)if(n+=i.percentage,e<n)return i.kid;return}function N(t,e,n){let i=Ct(e.buckets),r=I(e.defaultKid)??I(n);if(i.length===0)return r;let s=I(e.seed)??"kmsg-rollout-v1",p=e.stickyFields??Wt,o=jt(t,p,s),y=Qt(o)%100;return Zt(i,y)??r}function W(t){return Ct(t.buckets).map((e)=>e.kid)}function E(t){if(typeof t!=="string")return;let e=t.trim();return e.length>0?e:void 0}function Y(t){if(!Array.isArray(t))return[];return t.map((e)=>E(e)).filter((e)=>Boolean(e))}function j(t){let e=[],n=new Set;for(let i of t){let r=E(i);if(!r||n.has(r))continue;n.add(r),e.push(r)}return e}function Lt(t){return E(t.providerId)??"default"}function Q(t){let e=E(t.activeKid)??"default",n=j([e,...Y(t.decryptKids)]);return{async resolveEncryptKey(){return{kid:e}},async resolveDecryptKeys(){return n}}}function v(t){let e=typeof t.cacheTtlMs==="number"&&t.cacheTtlMs>=0?Math.trunc(t.cacheTtlMs):30000,n=E(t.fallback?.activeKid),i=Y(t.fallback?.decryptKids),r;async function s(p){let o=Date.now();if(r&&o<r.expiresAt)return r.value;let y=await t.provider.loadKeySet(p),f=E(y.activeKid)??n??Lt(p),a=j([f,...Y(y.decryptKids),...i]),h={activeKid:f,decryptKids:a,refreshedAt:Date.now()};return r={value:h,expiresAt:Date.now()+e},h}return{async resolveEncryptKey(p){return{kid:(await s(p)).activeKid}},async resolveDecryptKeys(p){let o=await s(p);return o.decryptKids??[o.activeKid]}}}function Xt(t,e){return{async resolveEncryptKey(n){let i=await t.resolveEncryptKey(n);return{kid:N(n,e,i.kid)??i.kid}},async resolveDecryptKeys(n){let i=await t.resolveEncryptKey(n),r=t.resolveDecryptKeys?await t.resolveDecryptKeys(n):[i.kid],s=N(n,e,i.kid),p=W(e);return j([...s?[s]:[],i.kid,...r??[],...p])}}}function zt(t){return v({provider:{async loadKeySet(n){return t.client.getKeyState({...n,...t.keyAlias?{keyAlias:t.keyAlias}:{},...t.region?{region:t.region}:{}})}},cacheTtlMs:t.cacheTtlMs,fallback:{activeKid:t.fallbackActiveKid,decryptKids:t.fallbackDecryptKids}})}function _(t){if(typeof t!=="string")return;let e=t.trim();return e.length>0?e:void 0}function Ft(t,e){return _(t[e])}function te(t,e){if(!t)return[];return t.split(e).map((n)=>_(n)).filter((n)=>Boolean(n))}function ee(t={}){let e=t.env??(typeof process<"u"?process.env:{}),n=_(t.delimiter)??",",i=t.activeKidEnv??"KMSG_ACTIVE_KID",r=t.decryptKidsEnv??"KMSG_DECRYPT_KIDS",s=Ft(e,i)??_(t.fallbackActiveKid)??"default",p=[s,...te(Ft(e,r),n),...t.fallbackDecryptKids??[]];return Q({activeKid:s,decryptKids:p})}function ne(t){return v({provider:{async loadKeySet(n){return t.client.getKeyState({...n,...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 e=t.trim();return e.length>0?e:void 0}function L(t,e,n){let i=t.fields[e];if(i)return i;if(e.startsWith("metadata.")){let r=t.fields["metadata.*"];if(r)return r}return n}function Pt(t,e={}){let n=[];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")n.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))n.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!Z(t.provider.decrypt))n.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!Z(t.provider.hash))n.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!t.fields||typeof t.fields!=="object")n.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)n.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,o]of s){if(!At(p))n.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(o!=="plain"&&o!=="encrypt"&&o!=="encrypt+hash"&&o!=="mask")n.push({message:`unsupported field mode: ${String(o)}`,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)n.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)n.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))n.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${s}]`})}}if(e.secureMode&&!e.compatPlainColumns){let s=L(t,"to","encrypt+hash"),p=L(t,"from","encrypt+hash");if(s==="plain")n.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")n.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:n.length===0,issues:n}}function ie(t,e={}){let n=Pt(t,e);if(n.valid)return;let i=n.issues[0];if(!i)throw new M("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:n.issues});throw new M("config",i.message,{rule:i.rule,path:i.path,hint:i.hint,issues:n.issues},{fieldPath:i.path})}function B(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n=typeof globalThis<"u"?globalThis.Buffer:void 0;return(n?n.from(e).toString("base64"):btoa(String.fromCharCode(...e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function U(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?e:`${e}${"=".repeat(4-e.length%4)}`,i=typeof globalThis<"u"?globalThis.Buffer:void 0;if(i)return new Uint8Array(i.from(n,"base64"));let r=atob(n),s=new Uint8Array(r.length);for(let p=0;p<r.length;p+=1)s[p]=r.charCodeAt(p);return s}function St(t,e){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(e==="base64url")return U(t);return new TextEncoder().encode(t)}function se(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);return Array.from(e).map((n)=>n.toString(16).padStart(2,"0")).join("")}function u(t){let e=new Uint8Array(t.byteLength);return e.set(t),e.buffer}function ut(t){let e=JSON.parse(t);if(!e||typeof e!=="object"||typeof e.v!=="number"||typeof e.alg!=="string"||typeof e.kid!=="string"||typeof e.iv!=="string"||typeof e.tag!=="string"||typeof e.ct!=="string")throw Error("Invalid ciphertext envelope");return e}function re(t){if(typeof t==="string")return t;return JSON.stringify(t)}function pe(t){if(!t||typeof t!=="object")return!1;let e=t;return typeof e.v==="number"&&typeof e.alg==="string"&&typeof e.kid==="string"&&typeof e.iv==="string"&&typeof e.tag==="string"&&typeof e.ct==="string"}function wt(t){let e=String(t??"").trim();if(e.length===0)return"";let n=e.startsWith("+"),i=e.replace(/\D/g,"");return n?`+${i}`:i}function X(t=3,e=2){return(n)=>{let i=String(n??"");if(i.length<=t+e)return"*".repeat(Math.max(0,i.length));let r=i.slice(0,t),s=i.slice(-e);return`${r}${"*".repeat(i.length-t-e)}${s}`}}function ye(t){let e=t.algorithm??"A256GCM",n=t.keyEncoding??"base64url",i=t.hashKeyEncoding??n,r=new Map,s=new Map,p=(y)=>{let f=r.get(y);if(f)return f;let a=t.keys[y];if(!a)throw Error(`Unknown encryption key id: ${y}`);let h=St(a,n),l=crypto.subtle.importKey("raw",u(h),"AES-GCM",!1,["encrypt","decrypt"]);return r.set(y,l),l},o=(y)=>{let f=s.get(y);if(f)return f;let a=t.hashKeys?.[y]??t.keys[y];if(!a)throw Error(`Unknown hash key id: ${y}`);let h=St(a,i),l=crypto.subtle.importKey("raw",u(h),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return s.set(y,l),l};return{async encrypt(y){let f=y.kid??t.activeKid,a=await p(f),h=crypto.getRandomValues(new Uint8Array(12)),l=new TextEncoder().encode(JSON.stringify(y.aad??{})),A=new TextEncoder().encode(y.value),C=await crypto.subtle.encrypt({name:"AES-GCM",iv:u(h),additionalData:u(l),tagLength:128},a,u(A)),w=new Uint8Array(C),d=w.slice(w.length-16),c=w.slice(0,w.length-16);return{ciphertext:{v:1,alg:e,kid:f,iv:B(h),tag:B(d),ct:B(c)},kid:f}},async decrypt(y){let f=ut(y.ciphertext),a=y.candidateKids&&y.candidateKids.length>0?y.candidateKids:[f.kid],h=U(f.iv),l=U(f.tag),A=U(f.ct),C=new Uint8Array(A.length+l.length);C.set(A,0),C.set(l,A.length);let w=new TextEncoder().encode(JSON.stringify(y.aad??{})),d;for(let c of a)try{let F=await p(c),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:u(h),additionalData:u(w),tagLength:128},F,u(C));return new TextDecoder().decode(new Uint8Array(g))}catch(F){d=F}throw Error(`Failed to decrypt ciphertext: ${d instanceof Error?d.message:String(d??"unknown")}`)},async hash(y){let f=y.kid??t.activeKid,a=await o(f),h=await crypto.subtle.sign("HMAC",a,u(new TextEncoder().encode(y.value)));return se(h)},mask(y){return X()(y.value)}}}function oe(){return{encrypt(t){return{ciphertext:JSON.stringify({v:1,alg:"NOOP",kid:"noop",iv:"",tag:"",ct:t.value})}},decrypt(t){try{return ut(t.ciphertext).ct}catch{return t.ciphertext}},hash(t){let e=wt(t.value);return B(new TextEncoder().encode(e))},mask(t){return X()(t.value)}}}function fe(t){return re(t)}var mt;((r)=>{r.DEBUG="DEBUG";r.INFO="INFO";r.WARN="WARN";r.ERROR="ERROR"})(mt||={});var ce=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function ae(t){let e=t.toLowerCase();return ce.some((n)=>e.includes(n.toLowerCase()))}function le(t){let e=t.trim();if(e.length<=4)return"***";if(e.includes("@")){let[r,s]=e.split("@");return`${r.slice(0,2)}${"*".repeat(Math.max(1,r.length-2))}@${s}`}let n=e.slice(0,3),i=e.slice(-2);return`${n}${"*".repeat(Math.max(1,e.length-5))}${i}`}function z(t,e){if(e===void 0||e===null)return e;if(ae(t)){if(typeof e==="string")return le(e);if(typeof e==="number"||typeof e==="boolean")return"***";if(Array.isArray(e))return"[REDACTED]";if(typeof e==="object")return"[REDACTED]"}if(Array.isArray(e))return e.map((n)=>z(t,n));if(typeof e==="object"){let n={};for(let[i,r]of Object.entries(e))n[i]=z(i,r);return n}return e}function de(t){let e={};for(let[n,i]of Object.entries(t))e[n]=z(n,i);return e}class ${config;context;constructor(t={},e={}){this.context=t,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...e}}shouldLog(t){let e=["DEBUG","INFO","WARN","ERROR"];return e.indexOf(t)>=e.indexOf(this.config.level)}formatMessage(t){let e=de(t.context);if(this.config.enableJson)return JSON.stringify({level:t.level,message:t.message,timestamp:t.timestamp.toISOString(),context:e,...t.error&&{error:{name:t.error.name,message:t.error.message,stack:t.error.stack}},...t.duration&&{duration:t.duration}});let n=t.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(t.level):t.level,r=Object.keys(e).length>0?` [${Object.entries(e).map(([p,o])=>`${p}=${o}`).join(", ")}]`:"",s=`${n} ${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 e=this.formatMessage(t);if(this.config.enableConsole)(t.level==="ERROR"?console.error:t.level==="WARN"?console.warn:console.log)(e);if(this.config.enableFile&&this.config.filePath);}debug(t,e={}){this.writeLog({level:"DEBUG",message:t,timestamp:new Date,context:{...this.context,...e}})}info(t,e={}){this.writeLog({level:"INFO",message:t,timestamp:new Date,context:{...this.context,...e}})}warn(t,e={},n){this.writeLog({level:"WARN",message:t,timestamp:new Date,context:{...this.context,...e},error:n})}error(t,e={},n){this.writeLog({level:"ERROR",message:t,timestamp:new Date,context:{...this.context,...e},error:n})}child(t){return new $({...this.context,...t},this.config)}time(t){let e=Date.now();return()=>{let n=Date.now()-e;this.info(`${t} completed`,{duration:n})}}async measure(t,e,n={}){let i=Date.now(),r={...n,operation:t};this.debug(`Starting ${t}`,r);try{let s=await e(),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,e){return new $(t,e)}function D(){if(!q)q=tt();return q}function he(t){q=t}var ge={debug:(t,e)=>D().debug(t,e),info:(t,e)=>D().info(t,e),warn:(t,e,n)=>D().warn(t,e,n),error:(t,e,n)=>D().error(t,e,n),child:(t)=>D().child(t),time:(t)=>D().time(t),measure:(t,e,n)=>D().measure(t,e,n)};function Ke(t){let e=tt({},t);return async(n,i)=>{let r=Date.now(),p={requestId:Math.random().toString(36).substring(7),method:n.req.method,path:n.req.path,userAgent:n.req.header("user-agent")||"unknown"};e.info("Request started",p);try{await i();let o=Date.now()-r;e.info("Request completed",{...p,status:n.res.status,duration:o})}catch(o){let y=Date.now()-r;throw e.error("Request failed",{...p,duration:y},o instanceof Error?o:Error(String(o))),o}}}class k{static defaultOptions={maxAttempts:3,initialDelay:1000,maxDelay:30000,backoffMultiplier:2,jitter:!0,retryCondition:(t)=>R.isRetryable(t)};static async execute(t,e={}){let n={...k.defaultOptions,...e},i,r=n.initialDelay;for(let s=1;s<=n.maxAttempts;s++)try{return await t()}catch(p){if(i=p,s===n.maxAttempts||!n.retryCondition(i,s))throw i;let o=n.jitter?r+Math.random()*r*0.1:r;n.onRetry?.(i,s),await new Promise((y)=>setTimeout(y,o)),r=Math.min(r*n.backoffMultiplier,n.maxDelay)}throw i}static createRetryableFunction(t,e={}){return async(...n)=>{return k.execute(()=>t(...n),e)}}}class H{static async execute(t,e,n={}){let i={concurrency:5,retryOptions:{maxAttempts:3,initialDelay:1000,maxDelay:1e4,backoffMultiplier:2,jitter:!0},failFast:!1,...n},r=Date.now(),s=[],p=[],o=0,y=k.createRetryableFunction(e,i.retryOptions),f=H.createBatches(t,i.concurrency);for(let h of f){let l=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{o++,i.onProgress?.(o,t.length,p.length)}});if(await Promise.allSettled(l),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,e){let n=[];for(let i=0;i<t.length;i+=e)n.push(t.slice(i,i+e));return n}}class et{options;state="CLOSED";failureCount=0;lastFailureTime=0;nextAttemptTime=0;constructor(t){this.options=t}async execute(t){let e=Date.now();switch(this.state){case"OPEN":if(e<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 n=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 n}catch(n){throw this.recordFailure(),n}}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 nt{maxRequests;windowMs;requests=[];constructor(t,e){this.maxRequests=t;this.windowMs=e}async acquire(){let t=Date.now();if(this.requests=this.requests.filter((e)=>t-e<this.windowMs),this.requests.length>=this.maxRequests){let e=Math.min(...this.requests),n=this.windowMs-(t-e);if(n>0)return await new Promise((i)=>setTimeout(i,n)),this.acquire()}this.requests.push(t)}canMakeRequest(){let t=Date.now();return this.requests=this.requests.filter((e)=>t-e<this.windowMs),this.requests.length<this.maxRequests}getRemainingRequests(){let t=Date.now();return this.requests=this.requests.filter((e)=>t-e<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}),Ce={map(t,e){if(t.isSuccess)return it(e(t.value));return t},flatMap(t,e){if(t.isSuccess)return e(t.value);return t},mapError(t,e){if(t.isFailure)return st(e(t.error));return t},unwrap(t){if(t.isSuccess)return t.value;throw t.error},unwrapOr(t,e){if(t.isSuccess)return t.value;return e},unwrapOrElse(t,e){if(t.isSuccess)return t.value;return e(t.error)},match(t,e){if(t.isSuccess)return e.ok(t.value);return e.fail(t.error)},async fromPromise(t){try{let e=await t;return it(e)}catch(e){return st(e)}},isOk(t){return t.isSuccess},isFail(t){return t.isFailure},tap(t,e){return e(t),t},tapOk(t,e){if(t.isSuccess)e(t.value);return t},tapErr(t,e){if(t.isFailure)e(t.error);return t},expect(t,e){if(t.isSuccess)return t.value;throw Error(e,{cause:t.error})}};function bt(){let t=globalThis;return t.__K_MSG_ENV__??t.__ENV__??t.process?.env??{}}function Fe(t){let e=bt()[t];if(typeof e==="string")return e;if(e===void 0)return;return String(e)}var Dt=["PENDING","SENT","DELIVERED","FAILED","CANCELLED","UNKNOWN"],Tt=["DELIVERED","FAILED","CANCELLED","UNKNOWN"],rt=["PENDING","SENT"],Ae=new Set(Dt),kt=new Set(Tt),Pe=new Set(rt);function Se(t){return Ae.has(t)}function ue(t){return kt.has(t)}function we(t){return kt.has(t)}function me(t){return Pe.has(t)}function be(){return rt}var Rt=["ALIMTALK","FRIENDTALK","SMS","LMS","MMS","NSA","VOICE","FAX","RCS_SMS","RCS_LMS","RCS_MMS","RCS_TPL","RCS_ITPL","RCS_LTPL"],De=new Set(Rt);function Te(t){return De.has(t)}var ke=["PENDING","SENT","FAILED"],Ot="PENDING",Re=(t)=>{let e=typeof t==="string"?t.trim().toUpperCase():"";if(e==="PENDING"||e==="SENT"||e==="FAILED")return e;return Ot};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=2092B819EDE446DB64756E2164756E21
|
|
5
5
|
//# sourceMappingURL=index.js.map
|