@k-msg/webhook 0.30.0 → 0.31.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/README.md +2 -0
- package/README_ko.md +2 -0
- package/dist/adapters/cloudflare/d1-delivery.store.d.ts +2 -0
- package/dist/adapters/cloudflare/index.cjs +42 -0
- package/dist/adapters/cloudflare/index.mjs +6 -71
- package/dist/crypto/field-crypto.d.ts +65 -1
- package/dist/dispatcher/load-balancer.d.ts +4 -0
- package/dist/dispatcher/queue.manager.d.ts +4 -0
- package/dist/index.cjs +5 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.mjs +3 -67
- package/dist/retry/retry.manager.d.ts +5 -1
- package/dist/runtime/persistence.d.ts +6 -0
- package/dist/runtime/types.d.ts +42 -0
- package/dist/runtime/webhook-runtime.service.d.ts +18 -2
- package/dist/services/webhook.registry.d.ts +1 -1
- package/dist/toolkit/index.cjs +13 -0
- package/dist/toolkit/index.mjs +12 -76
- package/package.json +11 -11
- package/dist/adapters/cloudflare/index.js +0 -107
- package/dist/index.js +0 -69
- package/dist/toolkit/index.js +0 -77
package/dist/toolkit/index.mjs
CHANGED
|
@@ -1,77 +1,13 @@
|
|
|
1
|
-
var nl=Object.defineProperty;var mr=(r,i)=>{for(var $ in i)nl(r,$,{get:i[$],enumerable:!0,configurable:!0,set:(o)=>i[$]=()=>o})};class B{listenersMap=new Map;on(r,i){let $=this.listenersMap.get(r)??new Set;return $.add(i),this.listenersMap.set(r,$),this}addListener(r,i){return this.on(r,i)}off(r,i){let $=this.listenersMap.get(r);if(!$)return this;if($.delete(i),$.size===0)this.listenersMap.delete(r);return this}removeListener(r,i){return this.off(r,i)}once(r,i){let $=(...o)=>{this.off(r,$),i(...o)};return this.on(r,$)}emit(r,...i){let $=this.listenersMap.get(r);if(!$||$.size===0)return!1;for(let o of[...$])o(...i);return!0}removeAllListeners(r){if(r)return this.listenersMap.delete(r),this;return this.listenersMap.clear(),this}}class qu extends B{config;pendingJobs=new Map;activeBatches=new Map;batchProcessor=null;defaultConfig={maxBatchSize:100,batchTimeoutMs:5000,maxConcurrentBatches:10,enablePrioritization:!0,priorityLevels:3};constructor(r={}){super();this.config={...this.defaultConfig,...r},this.startBatchProcessor()}async addJob(r){let i=r.endpoint.id;if(!this.pendingJobs.has(i))this.pendingJobs.set(i,[]);let $=this.pendingJobs.get(i);if(this.config.enablePrioritization)this.insertJobByPriority($,r);else $.push(r);if($.length>=this.config.maxBatchSize)await this.processBatchForEndpoint(i);this.emit("jobAdded",{endpointId:i,jobId:r.id,queueSize:$.length})}async processBatchForEndpoint(r){let i=this.pendingJobs.get(r);if(!i||i.length===0)return null;if(this.activeBatches.size>=this.config.maxConcurrentBatches)return this.emit("batchSkipped",{endpointId:r,reason:"max_concurrent_batches"}),null;let $=i.splice(0,this.config.maxBatchSize),o=this.createBatch(r,$);this.activeBatches.set(o.id,o);try{this.emit("batchStarted",{batchId:o.id,endpointId:r,jobCount:$.length}),await this.executeBatch(o,$),o.status="completed",this.emit("batchCompleted",{batchId:o.id,endpointId:r,success:!0})}catch(n){o.status="failed",this.emit("batchFailed",{batchId:o.id,endpointId:r,error:n instanceof Error?n.message:"Unknown error"}),this.requeueFailedJobs($)}finally{this.activeBatches.delete(o.id)}return o}async processAllBatches(){let r=[],i=Array.from(this.pendingJobs.keys());for(let $ of i){let o=await this.processBatchForEndpoint($);if(o)r.push(o)}return r}getBatchStats(){let r=Array.from(this.pendingJobs.keys()),i=r.reduce(($,o)=>{return $+(this.pendingJobs.get(o)?.length||0)},0);return{pendingJobsCount:i,activeBatchesCount:this.activeBatches.size,endpointsWithPendingJobs:r.length,averageQueueSize:r.length>0?i/r.length:0}}getPendingJobCount(r){return this.pendingJobs.get(r)?.length||0}startBatchProcessor(){this.batchProcessor=setInterval(async()=>{try{await this.processAllBatches()}catch(r){this.emit("processorError",r)}},this.config.batchTimeoutMs)}insertJobByPriority(r,i){let $=0;for(let o=0;o<r.length;o++){if(r[o].priority<=i.priority){$=o;break}$=o+1}r.splice($,0,i)}createBatch(r,i){return{id:`batch_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,endpointId:r,events:i.map(($)=>$.event),createdAt:new Date,scheduledAt:new Date,status:"processing"}}async executeBatch(r,i){if(!i[0]?.endpoint)throw Error("No endpoint found for batch");let o=i.map((n)=>this.executeJob(n));try{let n=await Promise.allSettled(o),t=n.filter((u)=>u.status==="fulfilled").length,v=n.length-t;if(this.emit("batchExecuted",{batchId:r.id,endpointId:r.endpointId,total:n.length,successful:t,failed:v}),v>0)throw Error(`Batch partially failed: ${v}/${n.length} jobs failed`)}catch(n){throw this.emit("batchExecutionError",{batchId:r.id,endpointId:r.endpointId,error:n instanceof Error?n.message:"Unknown error"}),n}}async executeJob(r){let i={id:`delivery_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,endpointId:r.endpoint.id,eventId:r.event.id,url:r.endpoint.url,httpMethod:"POST",headers:{"Content-Type":"application/json"},payload:JSON.stringify(r.event),attempts:[],status:"pending",createdAt:new Date},$=Math.random()>0.1;return i.attempts.push({attemptNumber:1,timestamp:new Date,httpStatus:$?200:500,responseBody:$?"OK":"Internal Server Error",error:$?void 0:"Server error",latencyMs:Math.floor(Math.random()*1000)+100}),i.status=$?"success":"failed",i.completedAt=new Date,i}requeueFailedJobs(r){for(let i of r)if(i.attempts++,i.attempts<i.maxAttempts){let n=1000*2**(i.attempts-1);i.nextRetryAt=new Date(Date.now()+n),i.scheduledAt=i.nextRetryAt,setTimeout(()=>{this.addJob(i).catch((t)=>{this.emit("requeueError",{jobId:i.id,error:t instanceof Error?t.message:"Unknown error"})})},n)}else this.emit("jobExhausted",{jobId:i.id,endpointId:i.endpoint.id,attempts:i.attempts})}async shutdown(){if(this.batchProcessor)clearInterval(this.batchProcessor),this.batchProcessor=null;let r=30000,i=Date.now();while(this.activeBatches.size>0&&Date.now()-i<r)await new Promise(($)=>setTimeout($,100));this.emit("shutdown",{pendingJobs:this.getBatchStats().pendingJobsCount,activeBatches:this.activeBatches.size})}}class Wu extends B{config;endpointHealth=new Map;endpoints=new Map;circuitBreakers=new Map;connectionCounts=new Map;roundRobinIndex=0;healthCheckInterval=null;defaultConfig={strategy:"round-robin",healthCheckInterval:30000,healthCheckTimeoutMs:5000,weights:{}};constructor(r={}){super();this.config={...this.defaultConfig,...r},this.startHealthChecks()}async registerEndpoint(r){let i={endpointId:r.id,isHealthy:!0,consecutiveFailures:0,lastHealthCheckAt:new Date,averageResponseTime:0,activeConnections:0};this.endpointHealth.set(r.id,i),this.endpoints.set(r.id,r),this.connectionCounts.set(r.id,0),await this.checkEndpointHealth(r),this.emit("endpointRegistered",{endpointId:r.id,isHealthy:i.isHealthy})}async unregisterEndpoint(r){this.endpointHealth.delete(r),this.endpoints.delete(r),this.circuitBreakers.delete(r),this.connectionCounts.delete(r),this.emit("endpointUnregistered",{endpointId:r})}async selectEndpoint(r){let i=r.filter((o)=>{let n=this.endpointHealth.get(o.id),t=this.circuitBreakers.get(o.id);return n?.isHealthy&&o.status==="active"&&t?.state!=="open"});if(i.length===0){let o=this.tryHalfOpenEndpoint(r);if(o)return o;return this.emit("noHealthyEndpoints",{totalEndpoints:r.length}),null}let $;switch(this.config.strategy){case"round-robin":$=this.selectRoundRobin(i);break;case"least-connections":$=this.selectLeastConnections(i);break;case"weighted":$=this.selectWeighted(i);break;case"random":$=this.selectRandom(i);break;default:$=i[0]}return this.incrementConnections($.id),this.emit("endpointSelected",{endpointId:$.id,strategy:this.config.strategy,availableEndpoints:i.length}),$}async onRequestComplete(r,i,$){this.decrementConnections(r);let o=this.endpointHealth.get(r);if(o){if(o.averageResponseTime===0)o.averageResponseTime=$;else o.averageResponseTime=o.averageResponseTime*0.8+$*0.2;if(i){o.consecutiveFailures=0,o.isHealthy=!0;let n=this.circuitBreakers.get(r);if(n){if(n.state==="half-open")n.state="closed",n.failureCount=0,this.emit("circuitBreakerClosed",{endpointId:r})}}else{if(o.consecutiveFailures++,o.consecutiveFailures>=3)o.isHealthy=!1,this.emit("endpointUnhealthy",{endpointId:r,consecutiveFailures:o.consecutiveFailures});this.updateCircuitBreaker(r,!1)}}this.emit("requestCompleted",{endpointId:r,success:i,responseTime:$,averageResponseTime:o?.averageResponseTime})}getEndpointHealth(r){return this.endpointHealth.get(r)||null}getAllEndpointHealth(){return Array.from(this.endpointHealth.values())}getStats(){let r=Array.from(this.endpointHealth.values()),i=Array.from(this.connectionCounts.values()).reduce((n,t)=>n+t,0),$=Array.from(this.circuitBreakers.values()).filter((n)=>n.state==="open").length,o=r.length>0?r.reduce((n,t)=>n+t.averageResponseTime,0)/r.length:0;return{totalEndpoints:r.length,healthyEndpoints:r.filter((n)=>n.isHealthy).length,activeConnections:i,circuitBreakersOpen:$,averageResponseTime:o}}selectRoundRobin(r){let i=r[this.roundRobinIndex%r.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%r.length,i}selectLeastConnections(r){return r.reduce((i,$)=>{let o=this.connectionCounts.get(i.id)||0;return(this.connectionCounts.get($.id)||0)<o?$:i})}selectWeighted(r){let i=this.config.weights||{},$=r.reduce((n,t)=>{return n+(i[t.id]||1)},0),o=Math.random()*$;for(let n of r){let t=i[n.id]||1;if(o-=t,o<=0)return n}return r[0]}selectRandom(r){let i=Math.floor(Math.random()*r.length);return r[i]}tryHalfOpenEndpoint(r){let i=new Date;for(let $ of r){let o=this.circuitBreakers.get($.id);if(o?.state==="open"&&o.nextRetryTime&&i>=o.nextRetryTime)return o.state="half-open",this.emit("circuitBreakerHalfOpen",{endpointId:$.id}),$}return null}updateCircuitBreaker(r,i){let $=this.circuitBreakers.get(r);if(!$)$={endpointId:r,state:"closed",failureCount:0},this.circuitBreakers.set(r,$);if(!i){if($.failureCount++,$.lastFailureTime=new Date,$.failureCount>=5&&$.state==="closed")$.state="open",$.nextRetryTime=new Date(Date.now()+60000),this.emit("circuitBreakerOpened",{endpointId:r,failureCount:$.failureCount,nextRetryTime:$.nextRetryTime})}}incrementConnections(r){let i=this.connectionCounts.get(r)||0;this.connectionCounts.set(r,i+1);let $=this.endpointHealth.get(r);if($)$.activeConnections=i+1}decrementConnections(r){let i=this.connectionCounts.get(r)||0,$=Math.max(0,i-1);this.connectionCounts.set(r,$);let o=this.endpointHealth.get(r);if(o)o.activeConnections=$}async checkEndpointHealth(r){let i=Date.now();try{let $=await fetch(r.url,{method:"HEAD",signal:AbortSignal.timeout(this.config.healthCheckTimeoutMs)}),o=Date.now()-i,n=$.ok;await this.onRequestComplete(r.id,n,o),this.emit("healthCheckCompleted",{endpointId:r.id,success:n,responseTime:o,httpStatus:$.status})}catch($){let o=Date.now()-i;await this.onRequestComplete(r.id,!1,o),this.emit("healthCheckFailed",{endpointId:r.id,error:$ instanceof Error?$.message:"Unknown error",responseTime:o})}}startHealthChecks(){this.healthCheckInterval=setInterval(async()=>{let r=Array.from(this.endpoints.values());for(let i of r)await this.checkEndpointHealth(i)},this.config.healthCheckInterval)}async shutdown(){if(this.healthCheckInterval)clearInterval(this.healthCheckInterval),this.healthCheckInterval=null;this.emit("shutdown",{totalEndpoints:this.endpointHealth.size,activeConnections:Array.from(this.connectionCounts.values()).reduce((r,i)=>r+i,0)})}}function T(r){if(!r)throw Error("File storage requires `fileAdapter`. Provide a runtime-specific adapter (Node fs, Worker KV/R2, etc.).");return r}function pn(r,i){let $=r.replace(/[\\/]+$/,""),o=i.replace(/^[\\/]+/,"");if(!$)return o;return`${$}/${o}`}function p(r){if(typeof r!=="object"||r===null)return!1;let i=r;return i.code==="ENOENT"||i.name==="NotFoundError"}class Ku extends B{config;queues=new Map;highPriorityQueue=[];mediumPriorityQueue=[];lowPriorityQueue=[];delayedJobs=new Map;ttlCleanupInterval=null;totalJobs=0;defaultConfig={maxQueueSize:1e4,persistToDisk:!1,compressionEnabled:!1,ttlMs:86400000};constructor(r={}){super();if(this.config={...this.defaultConfig,...r},this.queues.set("high",this.highPriorityQueue),this.queues.set("medium",this.mediumPriorityQueue),this.queues.set("low",this.lowPriorityQueue),this.config.persistToDisk&&this.config.diskPath)this.loadFromDisk().catch((i)=>{this.emit("diskLoadError",i)});this.startTTLCleanup()}async enqueue(r){if(this.totalJobs>=this.config.maxQueueSize)return this.emit("queueFull",{totalJobs:this.totalJobs,maxSize:this.config.maxQueueSize}),!1;if(r.scheduledAt>new Date)return await this.scheduleDelayedJob(r),!0;let i=this.getQueueName(r.priority),$=this.queues.get(i);if(!$)throw Error(`Invalid queue name: ${i}`);if($.push(r),this.totalJobs++,this.emit("jobEnqueued",{jobId:r.id,priority:r.priority,queueName:i,totalJobs:this.totalJobs}),this.config.persistToDisk)await this.saveToDisk().catch((o)=>{this.emit("diskSaveError",o)});return!0}async dequeue(){for(let[r,i]of this.queues.entries())if(i.length>0){let $=i.shift();if(this.totalJobs--,this.emit("jobDequeued",{jobId:$.id,queueName:r,totalJobs:this.totalJobs}),this.config.persistToDisk)await this.saveToDisk().catch((o)=>{this.emit("diskSaveError",o)});return $}return null}async dequeueFromPriority(r){let i=this.getQueueName(r),$=this.queues.get(i);if(!$||$.length===0)return null;let o=$.shift();return this.totalJobs--,this.emit("jobDequeued",{jobId:o.id,queueName:i,totalJobs:this.totalJobs}),o}peek(){for(let r of this.queues.values())if(r.length>0)return r[0];return null}async removeJob(r){for(let[$,o]of this.queues.entries()){let n=o.findIndex((t)=>t.id===r);if(n!==-1){if(o.splice(n,1),this.totalJobs--,this.emit("jobRemoved",{jobId:r,queueName:$,totalJobs:this.totalJobs}),this.config.persistToDisk)await this.saveToDisk().catch((t)=>{this.emit("diskSaveError",t)});return!0}}let i=this.delayedJobs.get(r);if(i)return clearTimeout(i),this.delayedJobs.delete(r),this.emit("delayedJobCanceled",{jobId:r}),!0;return!1}getStats(){return{totalJobs:this.totalJobs,highPriorityJobs:this.highPriorityQueue.length,mediumPriorityJobs:this.mediumPriorityQueue.length,lowPriorityJobs:this.lowPriorityQueue.length,delayedJobs:this.delayedJobs.size,queueUtilization:this.totalJobs/this.config.maxQueueSize*100}}async clear(){for(let r of this.queues.values())r.length=0;for(let r of this.delayedJobs.values())clearTimeout(r);if(this.delayedJobs.clear(),this.totalJobs=0,this.emit("queueCleared"),this.config.persistToDisk)await this.saveToDisk().catch((r)=>{this.emit("diskSaveError",r)})}async cleanupExpiredJobs(){let r=new Date,i=0;for(let[$,o]of this.queues.entries())for(let n=o.length-1;n>=0;n--){let t=o[n],v=r.getTime()-t.createdAt.getTime();if(v>this.config.ttlMs)o.splice(n,1),this.totalJobs--,i++,this.emit("jobExpired",{jobId:t.id,queueName:$,age:v})}if(i>0){if(this.emit("expiredJobsCleanup",{removedCount:i,totalJobs:this.totalJobs}),this.config.persistToDisk)await this.saveToDisk().catch(($)=>{this.emit("diskSaveError",$)})}return i}getQueueName(r){if(r>=8)return"high";if(r>=5)return"medium";return"low"}async scheduleDelayedJob(r){let i=r.scheduledAt.getTime()-Date.now(),$=setTimeout(async()=>{if(this.delayedJobs.delete(r.id),await this.enqueue({...r,scheduledAt:new Date}))this.emit("delayedJobActivated",{jobId:r.id})},i);this.delayedJobs.set(r.id,$),this.emit("jobScheduled",{jobId:r.id,scheduledAt:r.scheduledAt,delay:i})}startTTLCleanup(){if(this.ttlCleanupInterval)clearInterval(this.ttlCleanupInterval);this.ttlCleanupInterval=setInterval(async()=>{try{await this.cleanupExpiredJobs()}catch(r){this.emit("cleanupError",r)}},300000)}async saveToDisk(){if(!this.config.diskPath)return;try{let r=T(this.config.fileAdapter),i={queues:{high:this.highPriorityQueue,medium:this.mediumPriorityQueue,low:this.lowPriorityQueue},totalJobs:this.totalJobs,timestamp:new Date().toISOString()},$=JSON.stringify(i,null,2),o=pn(this.config.diskPath,"webhook-queue.json");await r.ensureDirForFile(o),await r.writeFile(o,$),this.emit("diskSaved",{filePath:o,totalJobs:this.totalJobs})}catch(r){throw this.emit("diskSaveError",r),r}}async loadFromDisk(){if(!this.config.diskPath)return;try{let r=T(this.config.fileAdapter),i=pn(this.config.diskPath,"webhook-queue.json"),$=await r.readFile(i),o=JSON.parse($);this.highPriorityQueue.length=0,this.mediumPriorityQueue.length=0,this.lowPriorityQueue.length=0,this.highPriorityQueue.push(...o.queues.high||[]),this.mediumPriorityQueue.push(...o.queues.medium||[]),this.lowPriorityQueue.push(...o.queues.low||[]),this.totalJobs=o.totalJobs||0,this.emit("diskLoaded",{filePath:i,totalJobs:this.totalJobs,timestamp:o.timestamp})}catch(r){if(!p(r))this.emit("diskLoadError",r)}}async shutdown(){if(this.ttlCleanupInterval)clearInterval(this.ttlCleanupInterval),this.ttlCleanupInterval=null;for(let r of this.delayedJobs.values())clearTimeout(r);if(this.delayedJobs.clear(),this.config.persistToDisk)await this.saveToDisk().catch((r)=>{this.emit("diskSaveError",r)});this.emit("shutdown",{totalJobs:this.totalJobs})}}class Lu extends B{config;deliveries=new Map;indexByEndpoint=new Map;indexByStatus=new Map;indexByDate=new Map;cleanupInterval=null;defaultConfig={type:"memory",retentionDays:30,enableCompression:!1,maxMemoryUsage:104857600};constructor(r={}){super();if(this.config={...this.defaultConfig,...r},this.initializeIndexes(),this.startCleanupTask(),this.config.type==="file"&&this.config.filePath)this.loadFromFile().catch((i)=>{this.emit("loadError",i)})}async saveDelivery(r){let i=this.deliveries.get(r.id);if(i)this.removeFromIndexes(i);if(this.config.type==="memory"&&this.config.maxMemoryUsage)await this.checkMemoryUsage();if(this.deliveries.set(r.id,r),this.addToIndexes(r),this.config.type==="file")await this.appendToFile(r);this.emit("deliverySaved",{deliveryId:r.id,endpointId:r.endpointId,status:r.status})}async getDelivery(r){return this.deliveries.get(r)||null}async searchDeliveries(r={},i={page:1,limit:100}){let $=null;if(r.endpointId){let c=this.indexByEndpoint.get(r.endpointId);$=c?new Set(c):new Set}if(r.status){let c=this.indexByStatus.get(r.status);if($)$=new Set(Array.from($).filter((l)=>c?.has(l)));else $=c?new Set(c):new Set}if(r.createdAfter||r.createdBefore){let c=this.getDeliveryIdsByDateRange(r.createdAfter,r.createdBefore);if($)$=new Set(Array.from($).filter((l)=>c.has(l)));else $=c}if(!$)$=new Set(this.deliveries.keys());let o=Array.from($).map((c)=>this.deliveries.get(c)).filter((c)=>this.matchesFilter(c,r));o.sort((c,l)=>{if(i.sortBy==="createdAt"||!i.sortBy){let P=l.createdAt.getTime()-c.createdAt.getTime();return i.sortOrder==="asc"?-P:P}let I=this.getFieldValue(c,i.sortBy),_=this.getFieldValue(l,i.sortBy),k=0;if(I<_)k=-1;else if(I>_)k=1;return i.sortOrder==="desc"?-k:k});let n=o.length,t=Math.ceil(n/i.limit),v=(i.page-1)*i.limit,u=v+i.limit;return{items:o.slice(v,u),totalCount:n,page:i.page,totalPages:t,hasNext:i.page<t,hasPrevious:i.page>1}}async getDeliveriesByEndpoint(r,i=100){let $=this.indexByEndpoint.get(r);if(!$)return[];return Array.from($).map((o)=>this.deliveries.get(o)).sort((o,n)=>n.createdAt.getTime()-o.createdAt.getTime()).slice(0,i)}async getFailedDeliveries(r,i=100){let $={status:"failed",endpointId:r};return(await this.searchDeliveries($,{page:1,limit:i})).items}async getDeliveryStats(r,i){let $={endpointId:r,createdAfter:i?.start,createdBefore:i?.end},n=(await this.searchDeliveries($,{page:1,limit:1e4})).items,t=n.filter((k)=>k.status==="success"),v=n.filter((k)=>k.status==="failed"),u=n.filter((k)=>k.status==="pending"),g=n.filter((k)=>k.status==="exhausted"),c=n.filter((k)=>k.completedAt),l=c.reduce((k,P)=>{let q=P.attempts[P.attempts.length-1];return k+(q?.latencyMs||0)},0),I=c.length>0?l/c.length:0,_={};for(let k of[...v,...g]){let P=k.attempts[k.attempts.length-1];if(P?.error)_[P.error]=(_[P.error]||0)+1;else if(P?.httpStatus){let q=`HTTP ${P.httpStatus}`;_[q]=(_[q]||0)+1}}return{totalDeliveries:n.length,successfulDeliveries:t.length,failedDeliveries:v.length,pendingDeliveries:u.length,exhaustedDeliveries:g.length,averageLatency:I,successRate:n.length>0?t.length/n.length*100:0,errorBreakdown:_}}async cleanupOldDeliveries(){if(!this.config.retentionDays)return 0;let r=new Date;r.setDate(r.getDate()-this.config.retentionDays);let i=Array.from(this.deliveries.values()).filter(($)=>$.createdAt<r);for(let $ of i)this.removeFromIndexes($),this.deliveries.delete($.id);if(i.length>0){if(this.emit("oldDeliveriesCleanup",{removedCount:i.length,cutoffDate:r}),this.config.type==="file")await this.saveToFile()}return i.length}getStorageStats(){let r=this.estimateMemoryUsage();return{totalDeliveries:this.deliveries.size,memoryUsage:r,indexSizes:{byEndpoint:this.indexByEndpoint.size,byStatus:this.indexByStatus.size,byDate:this.indexByDate.size}}}initializeIndexes(){let r=["pending","success","failed","exhausted"];for(let i of r)this.indexByStatus.set(i,new Set)}addToIndexes(r){if(!this.indexByEndpoint.has(r.endpointId))this.indexByEndpoint.set(r.endpointId,new Set);this.indexByEndpoint.get(r.endpointId).add(r.id);let i=this.indexByStatus.get(r.status);if(i)i.add(r.id);let $=r.createdAt.toISOString().split("T")[0];if(!this.indexByDate.has($))this.indexByDate.set($,new Set);this.indexByDate.get($).add(r.id)}removeFromIndexes(r){let i=this.indexByEndpoint.get(r.endpointId);if(i){if(i.delete(r.id),i.size===0)this.indexByEndpoint.delete(r.endpointId)}let $=this.indexByStatus.get(r.status);if($)$.delete(r.id);let o=r.createdAt.toISOString().split("T")[0],n=this.indexByDate.get(o);if(n){if(n.delete(r.id),n.size===0)this.indexByDate.delete(o)}}getDeliveryIdsByDateRange(r,i){let $=new Set;for(let[o,n]of this.indexByDate.entries()){let t=new Date(o);if(r&&t<r)continue;if(i&&t>i)continue;n.forEach((v)=>{$.add(v)})}return $}matchesFilter(r,i){if(i.eventId&&r.eventId!==i.eventId)return!1;if(i.httpStatusCode&&i.httpStatusCode.length>0){let $=r.attempts[r.attempts.length-1];if(!$?.httpStatus||!i.httpStatusCode.includes($.httpStatus))return!1}if(i.hasError!==void 0){let $=r.attempts.some((o)=>o.error);if(i.hasError!==$)return!1}if(i.completedAfter&&(!r.completedAt||r.completedAt<i.completedAfter))return!1;if(i.completedBefore&&(!r.completedAt||r.completedAt>i.completedBefore))return!1;return!0}getFieldValue(r,i){return i.split(".").reduce(($,o)=>$?.[o],r)}estimateMemoryUsage(){let r=0;for(let i of this.deliveries.values())r+=JSON.stringify(i).length*2;return r}async checkMemoryUsage(){if(!this.config.maxMemoryUsage)return;let r=this.estimateMemoryUsage();if(r>this.config.maxMemoryUsage){let i=Array.from(this.deliveries.values()).sort((n,t)=>n.createdAt.getTime()-t.createdAt.getTime()),$=0,o=this.config.maxMemoryUsage*0.8;for(let n of i){if(this.estimateMemoryUsage()<=o)break;this.removeFromIndexes(n),this.deliveries.delete(n.id),$++}if($>0)this.emit("memoryCleanup",{removedCount:$,previousUsage:r,currentUsage:this.estimateMemoryUsage()})}}startCleanupTask(){this.cleanupInterval=setInterval(async()=>{try{await this.cleanupOldDeliveries(),await this.checkMemoryUsage()}catch(r){this.emit("cleanupError",r)}},3600000)}async appendToFile(r){if(!this.config.filePath)return;try{let i=T(this.config.fileAdapter),$=JSON.stringify(r)+`
|
|
2
|
-
`;await i.ensureDirForFile(this.config.filePath),await i.appendFile(this.config.filePath,$)}catch(i){this.emit("appendError",i)}}async loadFromFile(){if(!this.config.filePath)return;try{let $=(await T(this.config.fileAdapter).readFile(this.config.filePath)).trim().split(`
|
|
3
|
-
|
|
4
|
-
`);
|
|
5
|
-
`),this.emit("dataSaved",{filePath:this.config.filePath,deliveryCount:this.deliveries.size})}catch(r){throw this.emit("saveError",r),r}}async shutdown(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;if(this.config.type==="file")await this.saveToFile().catch((r)=>{this.emit("saveError",r)});this.emit("shutdown",{deliveryCount:this.deliveries.size})}}var D={};mr(D,{xor:()=>u6,xid:()=>OU,void:()=>CU,uuidv7:()=>IU,uuidv6:()=>UU,uuidv4:()=>mU,uuid:()=>lU,util:()=>O,url:()=>kU,uppercase:()=>Rv,unknown:()=>Ln,union:()=>$g,undefined:()=>MU,ulid:()=>PU,uint64:()=>fU,uint32:()=>AU,tuple:()=>gg,trim:()=>av,treeifyError:()=>Si,transform:()=>w6,toUpperCase:()=>dv,toLowerCase:()=>yv,toJSONSchema:()=>Wn,templateLiteral:()=>Y6,symbol:()=>ZU,superRefine:()=>K6,success:()=>j6,stringbool:()=>T6,stringFormat:()=>qU,string:()=>Kn,strictObject:()=>dU,startsWith:()=>Zv,size:()=>Ev,set:()=>I6,safeParseAsync:()=>br,safeParse:()=>kr,safeExtend:()=>r6,safeEncodeAsync:()=>Xi,safeEncode:()=>Ji,safeDecodeAsync:()=>xi,safeDecode:()=>Fi,required:()=>o6,registry:()=>xn,regexes:()=>R,regex:()=>Av,refine:()=>W6,record:()=>lg,readonly:()=>G6,property:()=>Hv,promise:()=>Q6,prettifyError:()=>Pi,prefault:()=>O6,positive:()=>Gv,pipe:()=>F6,pick:()=>i6,partialRecord:()=>l6,partial:()=>$6,parseAsync:()=>$r,parse:()=>tr,overwrite:()=>or,optional:()=>wg,omit:()=>t6,object:()=>yU,number:()=>Hc,nullish:()=>S6,nullable:()=>Pg,null:()=>dc,normalize:()=>hv,nonpositive:()=>Qv,nonoptional:()=>N6,nonnegative:()=>qv,never:()=>ng,negative:()=>Yv,nativeEnum:()=>k6,nanoid:()=>wU,nan:()=>J6,multipleOf:()=>Wv,minimum:()=>ar,minSize:()=>Lv,minLength:()=>Tv,mime:()=>Cv,meta:()=>E6,merge:()=>n6,maximum:()=>hr,maxSize:()=>Kv,maxLength:()=>Vv,map:()=>U6,mac:()=>XU,lte:()=>hr,lt:()=>Yn,lowercase:()=>Bv,looseRecord:()=>m6,looseObject:()=>pU,locales:()=>Cr,literal:()=>b6,length:()=>ev,lazy:()=>Gg,ksuid:()=>NU,keyof:()=>aU,jwt:()=>QU,json:()=>e6,iso:()=>_u,ipv6:()=>zU,ipv4:()=>jU,invertCodec:()=>x6,intersection:()=>g6,int64:()=>RU,int32:()=>eU,int:()=>EU,instanceof:()=>V6,includes:()=>fv,httpUrl:()=>bU,hostname:()=>WU,hex:()=>KU,hash:()=>LU,guid:()=>gU,gte:()=>ar,gt:()=>Qn,globalRegistry:()=>C,function:()=>A6,formatError:()=>Di,float64:()=>TU,float32:()=>VU,flattenError:()=>wi,file:()=>_6,extend:()=>sU,exactOptional:()=>D6,enum:()=>Ig,endsWith:()=>Mv,encodeAsync:()=>ji,encode:()=>Oi,emoji:()=>_U,email:()=>cU,e164:()=>YU,discriminatedUnion:()=>c6,describe:()=>L6,decodeAsync:()=>zi,decode:()=>Ni,date:()=>hU,custom:()=>Qg,cuid2:()=>SU,cuid:()=>DU,core:()=>Fr,config:()=>K,coerce:()=>wu,codec:()=>X6,clone:()=>L,cidrv6:()=>FU,cidrv4:()=>JU,check:()=>q6,catchall:()=>v6,catch:()=>z6,boolean:()=>Cc,bigint:()=>BU,base64url:()=>GU,base64:()=>xU,array:()=>gu,any:()=>HU,_function:()=>A6,_default:()=>P6,ZodMiniXor:()=>og,ZodMiniXID:()=>Lc,ZodMiniVoid:()=>ig,ZodMiniUnknown:()=>sc,ZodMiniUnion:()=>lu,ZodMiniUndefined:()=>ac,ZodMiniUUID:()=>dr,ZodMiniURL:()=>uu,ZodMiniULID:()=>Kc,ZodMiniType:()=>z,ZodMiniTuple:()=>cg,ZodMiniTransform:()=>_g,ZodMiniTemplateLiteral:()=>Xg,ZodMiniSymbol:()=>hc,ZodMiniSuccess:()=>jg,ZodMiniStringFormat:()=>G,ZodMiniString:()=>Xr,ZodMiniSet:()=>Ug,ZodMiniRecord:()=>yr,ZodMiniReadonly:()=>Fg,ZodMiniPromise:()=>Yg,ZodMiniPrefault:()=>Ng,ZodMiniPipe:()=>ku,ZodMiniOptional:()=>Uu,ZodMiniObject:()=>Vn,ZodMiniNumberFormat:()=>xr,ZodMiniNumber:()=>sr,ZodMiniNullable:()=>Sg,ZodMiniNull:()=>yc,ZodMiniNonOptional:()=>Iu,ZodMiniNever:()=>rg,ZodMiniNanoID:()=>Qc,ZodMiniNaN:()=>Jg,ZodMiniMap:()=>mg,ZodMiniMAC:()=>Bc,ZodMiniLiteral:()=>kg,ZodMiniLazy:()=>xg,ZodMiniKSUID:()=>Ec,ZodMiniJWT:()=>Mc,ZodMiniIntersection:()=>ug,ZodMiniISOTime:()=>Bn,ZodMiniISODuration:()=>Rn,ZodMiniISODateTime:()=>en,ZodMiniISODate:()=>An,ZodMiniIPv6:()=>Tc,ZodMiniIPv4:()=>Vc,ZodMiniGUID:()=>Gc,ZodMiniFunction:()=>qg,ZodMiniFile:()=>bg,ZodMiniExactOptional:()=>Dg,ZodMiniEnum:()=>mu,ZodMiniEmoji:()=>Yc,ZodMiniEmail:()=>xc,ZodMiniE164:()=>Zc,ZodMiniDiscriminatedUnion:()=>vg,ZodMiniDefault:()=>Og,ZodMiniDate:()=>En,ZodMiniCustomStringFormat:()=>pr,ZodMiniCustom:()=>bu,ZodMiniCodec:()=>Tn,ZodMiniCatch:()=>zg,ZodMiniCUID2:()=>Wc,ZodMiniCUID:()=>qc,ZodMiniCIDRv6:()=>Ac,ZodMiniCIDRv4:()=>ec,ZodMiniBoolean:()=>rn,ZodMiniBigIntFormat:()=>cu,ZodMiniBigInt:()=>nn,ZodMiniBase64URL:()=>fc,ZodMiniBase64:()=>Rc,ZodMiniArray:()=>tg,ZodMiniAny:()=>pc,TimePrecision:()=>nv,NEVER:()=>sn,$output:()=>Xo,$input:()=>xo,$brand:()=>ri});var Fr={};mr(Fr,{version:()=>Nt,util:()=>O,treeifyError:()=>Si,toJSONSchema:()=>Wn,toDotPath:()=>Ru,safeParseAsync:()=>br,safeParse:()=>kr,safeEncodeAsync:()=>Xi,safeEncode:()=>Ji,safeDecodeAsync:()=>xi,safeDecode:()=>Fi,registry:()=>xn,regexes:()=>R,process:()=>F,prettifyError:()=>Pi,parseAsync:()=>$r,parse:()=>tr,meta:()=>tu,locales:()=>Cr,isValidJWT:()=>Dc,isValidBase64URL:()=>wc,isValidBase64:()=>Zt,initializeContext:()=>vr,globalRegistry:()=>C,globalConfig:()=>Ur,formatError:()=>Di,flattenError:()=>wi,finalize:()=>cr,extractDefs:()=>ur,encodeAsync:()=>ji,encode:()=>Oi,describe:()=>iu,decodeAsync:()=>zi,decode:()=>Ni,createToJSONSchemaMethod:()=>P4,createStandardJSONSchemaMethod:()=>ou,config:()=>K,clone:()=>L,_xor:()=>pm,_xid:()=>fo,_void:()=>Jv,_uuidv7:()=>Vo,_uuidv6:()=>Eo,_uuidv4:()=>Lo,_uuid:()=>Ko,_url:()=>Gn,_uppercase:()=>Rv,_unknown:()=>jv,_union:()=>dm,_undefined:()=>Pv,_ulid:()=>Ro,_uint64:()=>Dv,_uint32:()=>Uv,_tuple:()=>n4,_trim:()=>av,_transform:()=>c4,_toUpperCase:()=>dv,_toLowerCase:()=>yv,_templateLiteral:()=>w4,_symbol:()=>Sv,_superRefine:()=>nu,_success:()=>I4,_stringbool:()=>$u,_stringFormat:()=>Jr,_string:()=>Yo,_startsWith:()=>Zv,_slugify:()=>am,_size:()=>Ev,_set:()=>$4,_safeParseAsync:()=>In,_safeParse:()=>Un,_safeEncodeAsync:()=>au,_safeEncode:()=>Cu,_safeDecodeAsync:()=>yu,_safeDecode:()=>hu,_regex:()=>Av,_refine:()=>ru,_record:()=>i4,_readonly:()=>_4,_property:()=>Hv,_promise:()=>S4,_positive:()=>Gv,_pipe:()=>b4,_parseAsync:()=>mn,_parse:()=>ln,_overwrite:()=>or,_optional:()=>g4,_number:()=>vv,_nullable:()=>l4,_null:()=>Ov,_normalize:()=>hv,_nonpositive:()=>Qv,_nonoptional:()=>U4,_nonnegative:()=>qv,_never:()=>zv,_negative:()=>Yv,_nativeEnum:()=>v4,_nanoid:()=>eo,_nan:()=>xv,_multipleOf:()=>Wv,_minSize:()=>Lv,_minLength:()=>Tv,_min:()=>ar,_mime:()=>Cv,_maxSize:()=>Kv,_maxLength:()=>Vv,_max:()=>hr,_map:()=>t4,_mac:()=>Co,_lte:()=>hr,_lt:()=>Yn,_lowercase:()=>Bv,_literal:()=>u4,_length:()=>ev,_lazy:()=>D4,_ksuid:()=>Zo,_jwt:()=>rv,_isoTime:()=>$v,_isoDuration:()=>ov,_isoDateTime:()=>iv,_isoDate:()=>tv,_ipv6:()=>Ho,_ipv4:()=>Mo,_intersection:()=>r4,_int64:()=>wv,_int32:()=>mv,_int:()=>cv,_includes:()=>fv,_guid:()=>Wo,_gte:()=>ar,_gt:()=>Qn,_float64:()=>lv,_float32:()=>gv,_file:()=>pv,_enum:()=>o4,_endsWith:()=>Mv,_encodeAsync:()=>Mu,_encode:()=>fu,_emoji:()=>To,_email:()=>qo,_e164:()=>so,_discriminatedUnion:()=>sm,_default:()=>m4,_decodeAsync:()=>Hu,_decode:()=>Zu,_date:()=>Fv,_custom:()=>sv,_cuid2:()=>Bo,_cuid:()=>Ao,_coercedString:()=>Qo,_coercedNumber:()=>uv,_coercedDate:()=>Xv,_coercedBoolean:()=>kv,_coercedBigint:()=>_v,_cidrv6:()=>ao,_cidrv4:()=>ho,_check:()=>Fc,_catch:()=>k4,_boolean:()=>Iv,_bigint:()=>bv,_base64url:()=>po,_base64:()=>yo,_array:()=>ym,_any:()=>Nv,TimePrecision:()=>nv,NEVER:()=>sn,JSONSchemaGenerator:()=>vu,JSONSchema:()=>Xc,Doc:()=>wn,$output:()=>Xo,$input:()=>xo,$constructor:()=>m,$brand:()=>ri,$ZodXor:()=>u$,$ZodXID:()=>Wt,$ZodVoid:()=>$$,$ZodUnknown:()=>i$,$ZodUnion:()=>Rr,$ZodUndefined:()=>st,$ZodUUID:()=>Jt,$ZodURL:()=>Xt,$ZodULID:()=>qt,$ZodType:()=>N,$ZodTuple:()=>Jn,$ZodTransform:()=>_$,$ZodTemplateLiteral:()=>F$,$ZodSymbol:()=>pt,$ZodSuccess:()=>N$,$ZodStringFormat:()=>X,$ZodString:()=>jr,$ZodSet:()=>U$,$ZodRegistry:()=>Go,$ZodRecord:()=>l$,$ZodRealError:()=>A,$ZodReadonly:()=>J$,$ZodPromise:()=>x$,$ZodPreprocess:()=>yl,$ZodPrefault:()=>P$,$ZodPipe:()=>Xn,$ZodOptional:()=>Fn,$ZodObjectJIT:()=>al,$ZodObject:()=>zn,$ZodNumberFormat:()=>yt,$ZodNumber:()=>Nn,$ZodNullable:()=>D$,$ZodNull:()=>r$,$ZodNonOptional:()=>O$,$ZodNever:()=>t$,$ZodNanoID:()=>Gt,$ZodNaN:()=>z$,$ZodMap:()=>m$,$ZodMAC:()=>Bt,$ZodLiteral:()=>k$,$ZodLazy:()=>G$,$ZodKSUID:()=>Kt,$ZodJWT:()=>ht,$ZodIntersection:()=>g$,$ZodISOTime:()=>Vt,$ZodISODuration:()=>Tt,$ZodISODateTime:()=>Lt,$ZodISODate:()=>Et,$ZodIPv6:()=>At,$ZodIPv4:()=>et,$ZodGUID:()=>zt,$ZodFunction:()=>X$,$ZodFile:()=>b$,$ZodExactOptional:()=>w$,$ZodError:()=>_i,$ZodEnum:()=>I$,$ZodEncodeError:()=>Qr,$ZodEmoji:()=>xt,$ZodEmail:()=>Ft,$ZodE164:()=>Ct,$ZodDiscriminatedUnion:()=>c$,$ZodDefault:()=>S$,$ZodDate:()=>o$,$ZodCustomStringFormat:()=>at,$ZodCustom:()=>Y$,$ZodCodec:()=>fr,$ZodCheckUpperCase:()=>bt,$ZodCheckStringFormat:()=>Nr,$ZodCheckStartsWith:()=>wt,$ZodCheckSizeEquals:()=>gt,$ZodCheckRegex:()=>It,$ZodCheckProperty:()=>St,$ZodCheckOverwrite:()=>Ot,$ZodCheckNumberFormat:()=>ot,$ZodCheckMultipleOf:()=>$t,$ZodCheckMinSize:()=>ct,$ZodCheckMinLength:()=>mt,$ZodCheckMimeType:()=>Pt,$ZodCheckMaxSize:()=>ut,$ZodCheckMaxLength:()=>lt,$ZodCheckLowerCase:()=>kt,$ZodCheckLessThan:()=>bn,$ZodCheckLengthEquals:()=>Ut,$ZodCheckIncludes:()=>_t,$ZodCheckGreaterThan:()=>_n,$ZodCheckEndsWith:()=>Dt,$ZodCheckBigIntFormat:()=>vt,$ZodCheck:()=>x,$ZodCatch:()=>j$,$ZodCUID2:()=>Qt,$ZodCUID:()=>Yt,$ZodCIDRv6:()=>ft,$ZodCIDRv4:()=>Rt,$ZodBoolean:()=>Br,$ZodBigIntFormat:()=>dt,$ZodBigInt:()=>jn,$ZodBase64URL:()=>Ht,$ZodBase64:()=>Mt,$ZodAsyncError:()=>H,$ZodArray:()=>v$,$ZodAny:()=>n$});var Eu,sn=Object.freeze({status:"aborted"});function m(r,i,$){function o(u,g){if(!u._zod)Object.defineProperty(u,"_zod",{value:{def:g,constr:v,traits:new Set},enumerable:!1});if(u._zod.traits.has(r))return;u._zod.traits.add(r),i(u,g);let c=v.prototype,l=Object.keys(c);for(let I=0;I<l.length;I++){let _=l[I];if(!(_ in u))u[_]=c[_].bind(u)}}let n=$?.Parent??Object;class t extends n{}Object.defineProperty(t,"name",{value:r});function v(u){var g;let c=$?.Parent?new t:this;o(c,u),(g=c._zod).deferred??(g.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(v,"init",{value:o}),Object.defineProperty(v,Symbol.hasInstance,{value:(u)=>{if($?.Parent&&u instanceof $.Parent)return!0;return u?._zod?.traits?.has(r)}}),Object.defineProperty(v,"name",{value:r}),v}var ri=Symbol("zod_brand");class H extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Qr extends Error{constructor(r){super(`Encountered unidirectional transform during encode: ${r}`);this.name="ZodEncodeError"}}(Eu=globalThis).__zod_globalConfig??(Eu.__zod_globalConfig={});var Ur=globalThis.__zod_globalConfig;function K(r){if(r)Object.assign(Ur,r);return Ur}var O={};mr(O,{unwrapMessage:()=>qr,uint8ArrayToHex:()=>Pl,uint8ArrayToBase64url:()=>Dl,uint8ArrayToBase64:()=>eu,stringifyPrimitive:()=>w,slugify:()=>$i,shallowClone:()=>Pr,safeExtend:()=>Ui,required:()=>ki,randomString:()=>ml,propertyKeyTypes:()=>Lr,promiseAllObject:()=>ll,primitiveTypes:()=>vi,prefixIssues:()=>e,pick:()=>li,partial:()=>Ii,parsedType:()=>S,optionalKeys:()=>ui,omit:()=>mi,objectClone:()=>ul,numKeys:()=>Ul,nullish:()=>s,normalizeParams:()=>b,mergeDefs:()=>a,merge:()=>bl,jsonStringifyReplacer:()=>ii,joinValues:()=>U,issue:()=>Or,isPlainObject:()=>nr,isObject:()=>Ir,hexToUint8Array:()=>Sl,getSizableOrigin:()=>Er,getParsedType:()=>Il,getLengthableOrigin:()=>Vr,getEnumValues:()=>Wr,getElementAtPath:()=>gl,floatSafeRemainder:()=>ti,finalizeIssue:()=>E,extend:()=>gn,explicitlyAborted:()=>bi,escapeRegex:()=>f,esc:()=>un,defineLazy:()=>J,createTransparentProxy:()=>kl,cloneDef:()=>cl,clone:()=>L,cleanRegex:()=>Kr,cleanEnum:()=>_l,captureStackTrace:()=>cn,cached:()=>Sr,base64urlToUint8Array:()=>wl,base64ToUint8Array:()=>Tu,assignProp:()=>rr,assertNotEqual:()=>tl,assertNever:()=>ol,assertIs:()=>$l,assertEqual:()=>il,assert:()=>vl,allowsEval:()=>oi,aborted:()=>ir,NUMBER_FORMAT_RANGES:()=>ci,Class:()=>Au,BIGINT_FORMAT_RANGES:()=>gi});function il(r){return r}function tl(r){return r}function $l(r){}function ol(r){throw Error("Unexpected value in exhaustive check")}function vl(r){}function Wr(r){let i=Object.values(r).filter((o)=>typeof o==="number");return Object.entries(r).filter(([o,n])=>i.indexOf(+o)===-1).map(([o,n])=>n)}function U(r,i="|"){return r.map(($)=>w($)).join(i)}function ii(r,i){if(typeof i==="bigint")return i.toString();return i}function Sr(r){return{get value(){{let $=r();return Object.defineProperty(this,"value",{value:$}),$}throw Error("cached value already set")}}}function s(r){return r===null||r===void 0}function Kr(r){let i=r.startsWith("^")?1:0,$=r.endsWith("$")?r.length-1:r.length;return r.slice(i,$)}function ti(r,i){let $=r/i,o=Math.round($),n=Number.EPSILON*Math.max(Math.abs($),1);if(Math.abs($-o)<n)return 0;return $-o}var Vu=Symbol("evaluating");function J(r,i,$){let o=void 0;Object.defineProperty(r,i,{get(){if(o===Vu)return;if(o===void 0)o=Vu,o=$();return o},set(n){Object.defineProperty(r,i,{value:n})},configurable:!0})}function ul(r){return Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r))}function rr(r,i,$){Object.defineProperty(r,i,{value:$,writable:!0,enumerable:!0,configurable:!0})}function a(...r){let i={};for(let $ of r){let o=Object.getOwnPropertyDescriptors($);Object.assign(i,o)}return Object.defineProperties({},i)}function cl(r){return a(r._zod.def)}function gl(r,i){if(!i)return r;return i.reduce(($,o)=>$?.[o],r)}function ll(r){let i=Object.keys(r),$=i.map((o)=>r[o]);return Promise.all($).then((o)=>{let n={};for(let t=0;t<i.length;t++)n[i[t]]=o[t];return n})}function ml(r=10){let $="";for(let o=0;o<r;o++)$+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return $}function un(r){return JSON.stringify(r)}function $i(r){return r.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var cn="captureStackTrace"in Error?Error.captureStackTrace:(...r)=>{};function Ir(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)}var oi=Sr(()=>{if(Ur.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(r){return!1}});function nr(r){if(Ir(r)===!1)return!1;let i=r.constructor;if(i===void 0)return!0;if(typeof i!=="function")return!0;let $=i.prototype;if(Ir($)===!1)return!1;if(Object.prototype.hasOwnProperty.call($,"isPrototypeOf")===!1)return!1;return!0}function Pr(r){if(nr(r))return{...r};if(Array.isArray(r))return[...r];if(r instanceof Map)return new Map(r);if(r instanceof Set)return new Set(r);return r}function Ul(r){let i=0;for(let $ in r)if(Object.prototype.hasOwnProperty.call(r,$))i++;return i}var Il=(r)=>{let i=typeof r;switch(i){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(r)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(r))return"array";if(r===null)return"null";if(r.then&&typeof r.then==="function"&&r.catch&&typeof r.catch==="function")return"promise";if(typeof Map<"u"&&r instanceof Map)return"map";if(typeof Set<"u"&&r instanceof Set)return"set";if(typeof Date<"u"&&r instanceof Date)return"date";if(typeof File<"u"&&r instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${i}`)}},Lr=new Set(["string","number","symbol"]),vi=new Set(["string","number","bigint","boolean","symbol","undefined"]);function f(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function L(r,i,$){let o=new r._zod.constr(i??r._zod.def);if(!i||$?.parent)o._zod.parent=r;return o}function b(r){let i=r;if(!i)return{};if(typeof i==="string")return{error:()=>i};if(i?.message!==void 0){if(i?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");i.error=i.message}if(delete i.message,typeof i.error==="string")return{...i,error:()=>i.error};return i}function kl(r){let i;return new Proxy({},{get($,o,n){return i??(i=r()),Reflect.get(i,o,n)},set($,o,n,t){return i??(i=r()),Reflect.set(i,o,n,t)},has($,o){return i??(i=r()),Reflect.has(i,o)},deleteProperty($,o){return i??(i=r()),Reflect.deleteProperty(i,o)},ownKeys($){return i??(i=r()),Reflect.ownKeys(i)},getOwnPropertyDescriptor($,o){return i??(i=r()),Reflect.getOwnPropertyDescriptor(i,o)},defineProperty($,o,n){return i??(i=r()),Reflect.defineProperty(i,o,n)}})}function w(r){if(typeof r==="bigint")return r.toString()+"n";if(typeof r==="string")return`"${r}"`;return`${r}`}function ui(r){return Object.keys(r).filter((i)=>{return r[i]._zod.optin==="optional"&&r[i]._zod.optout==="optional"})}var ci={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},gi={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function li(r,i){let $=r._zod.def,o=$.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let t=a(r._zod.def,{get shape(){let v={};for(let u in i){if(!(u in $.shape))throw Error(`Unrecognized key: "${u}"`);if(!i[u])continue;v[u]=$.shape[u]}return rr(this,"shape",v),v},checks:[]});return L(r,t)}function mi(r,i){let $=r._zod.def,o=$.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let t=a(r._zod.def,{get shape(){let v={...r._zod.def.shape};for(let u in i){if(!(u in $.shape))throw Error(`Unrecognized key: "${u}"`);if(!i[u])continue;delete v[u]}return rr(this,"shape",v),v},checks:[]});return L(r,t)}function gn(r,i){if(!nr(i))throw Error("Invalid input to extend: expected a plain object");let $=r._zod.def.checks;if($&&$.length>0){let t=r._zod.def.shape;for(let v in i)if(Object.getOwnPropertyDescriptor(t,v)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=a(r._zod.def,{get shape(){let t={...r._zod.def.shape,...i};return rr(this,"shape",t),t}});return L(r,n)}function Ui(r,i){if(!nr(i))throw Error("Invalid input to safeExtend: expected a plain object");let $=a(r._zod.def,{get shape(){let o={...r._zod.def.shape,...i};return rr(this,"shape",o),o}});return L(r,$)}function bl(r,i){if(r._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let $=a(r._zod.def,{get shape(){let o={...r._zod.def.shape,...i._zod.def.shape};return rr(this,"shape",o),o},get catchall(){return i._zod.def.catchall},checks:i._zod.def.checks??[]});return L(r,$)}function Ii(r,i,$){let n=i._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let v=a(i._zod.def,{get shape(){let u=i._zod.def.shape,g={...u};if($)for(let c in $){if(!(c in u))throw Error(`Unrecognized key: "${c}"`);if(!$[c])continue;g[c]=r?new r({type:"optional",innerType:u[c]}):u[c]}else for(let c in u)g[c]=r?new r({type:"optional",innerType:u[c]}):u[c];return rr(this,"shape",g),g},checks:[]});return L(i,v)}function ki(r,i,$){let o=a(i._zod.def,{get shape(){let n=i._zod.def.shape,t={...n};if($)for(let v in $){if(!(v in t))throw Error(`Unrecognized key: "${v}"`);if(!$[v])continue;t[v]=new r({type:"nonoptional",innerType:n[v]})}else for(let v in n)t[v]=new r({type:"nonoptional",innerType:n[v]});return rr(this,"shape",t),t}});return L(i,o)}function ir(r,i=0){if(r.aborted===!0)return!0;for(let $=i;$<r.issues.length;$++)if(r.issues[$]?.continue!==!0)return!0;return!1}function bi(r,i=0){if(r.aborted===!0)return!0;for(let $=i;$<r.issues.length;$++)if(r.issues[$]?.continue===!1)return!0;return!1}function e(r,i){return i.map(($)=>{var o;return(o=$).path??(o.path=[]),$.path.unshift(r),$})}function qr(r){return typeof r==="string"?r:r?.message}function E(r,i,$){let o=r.message?r.message:qr(r.inst?._zod.def?.error?.(r))??qr(i?.error?.(r))??qr($.customError?.(r))??qr($.localeError?.(r))??"Invalid input",{inst:n,continue:t,input:v,...u}=r;if(u.path??(u.path=[]),u.message=o,i?.reportInput)u.input=v;return u}function Er(r){if(r instanceof Set)return"set";if(r instanceof Map)return"map";if(r instanceof File)return"file";return"unknown"}function Vr(r){if(Array.isArray(r))return"array";if(typeof r==="string")return"string";return"unknown"}function S(r){let i=typeof r;switch(i){case"number":return Number.isNaN(r)?"nan":"number";case"object":{if(r===null)return"null";if(Array.isArray(r))return"array";let $=r;if($&&Object.getPrototypeOf($)!==Object.prototype&&"constructor"in $&&$.constructor)return $.constructor.name}}return i}function Or(...r){let[i,$,o]=r;if(typeof i==="string")return{message:i,code:"custom",input:$,inst:o};return{...i}}function _l(r){return Object.entries(r).filter(([i,$])=>{return Number.isNaN(Number.parseInt(i,10))}).map((i)=>i[1])}function Tu(r){let i=atob(r),$=new Uint8Array(i.length);for(let o=0;o<i.length;o++)$[o]=i.charCodeAt(o);return $}function eu(r){let i="";for(let $=0;$<r.length;$++)i+=String.fromCharCode(r[$]);return btoa(i)}function wl(r){let i=r.replace(/-/g,"+").replace(/_/g,"/"),$="=".repeat((4-i.length%4)%4);return Tu(i+$)}function Dl(r){return eu(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Sl(r){let i=r.replace(/^0x/,"");if(i.length%2!==0)throw Error("Invalid hex string length");let $=new Uint8Array(i.length/2);for(let o=0;o<i.length;o+=2)$[o/2]=Number.parseInt(i.slice(o,o+2),16);return $}function Pl(r){return Array.from(r).map((i)=>i.toString(16).padStart(2,"0")).join("")}class Au{constructor(...r){}}var Bu=(r,i)=>{r.name="$ZodError",Object.defineProperty(r,"_zod",{value:r._zod,enumerable:!1}),Object.defineProperty(r,"issues",{value:i,enumerable:!1}),r.message=JSON.stringify(i,ii,2),Object.defineProperty(r,"toString",{value:()=>r.message,enumerable:!1})},_i=m("$ZodError",Bu),A=m("$ZodError",Bu,{Parent:Error});function wi(r,i=($)=>$.message){let $={},o=[];for(let n of r.issues)if(n.path.length>0)$[n.path[0]]=$[n.path[0]]||[],$[n.path[0]].push(i(n));else o.push(i(n));return{formErrors:o,fieldErrors:$}}function Di(r,i=($)=>$.message){let $={_errors:[]},o=(n,t=[])=>{for(let v of n.issues)if(v.code==="invalid_union"&&v.errors.length)v.errors.map((u)=>o({issues:u},[...t,...v.path]));else if(v.code==="invalid_key")o({issues:v.issues},[...t,...v.path]);else if(v.code==="invalid_element")o({issues:v.issues},[...t,...v.path]);else{let u=[...t,...v.path];if(u.length===0)$._errors.push(i(v));else{let g=$,c=0;while(c<u.length){let l=u[c];if(c!==u.length-1)g[l]=g[l]||{_errors:[]};else g[l]=g[l]||{_errors:[]},g[l]._errors.push(i(v));g=g[l],c++}}}};return o(r),$}function Si(r,i=($)=>$.message){let $={errors:[]},o=(n,t=[])=>{var v,u;for(let g of n.issues)if(g.code==="invalid_union"&&g.errors.length)g.errors.map((c)=>o({issues:c},[...t,...g.path]));else if(g.code==="invalid_key")o({issues:g.issues},[...t,...g.path]);else if(g.code==="invalid_element")o({issues:g.issues},[...t,...g.path]);else{let c=[...t,...g.path];if(c.length===0){$.errors.push(i(g));continue}let l=$,I=0;while(I<c.length){let _=c[I],k=I===c.length-1;if(typeof _==="string")l.properties??(l.properties={}),(v=l.properties)[_]??(v[_]={errors:[]}),l=l.properties[_];else l.items??(l.items=[]),(u=l.items)[_]??(u[_]={errors:[]}),l=l.items[_];if(k)l.errors.push(i(g));I++}}};return o(r),$}function Ru(r){let i=[],$=r.map((o)=>typeof o==="object"?o.key:o);for(let o of $)if(typeof o==="number")i.push(`[${o}]`);else if(typeof o==="symbol")i.push(`[${JSON.stringify(String(o))}]`);else if(/[^\w$]/.test(o))i.push(`[${JSON.stringify(o)}]`);else{if(i.length)i.push(".");i.push(o)}return i.join("")}function Pi(r){let i=[],$=[...r.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of $)if(i.push(`✖ ${o.message}`),o.path?.length)i.push(` → at ${Ru(o.path)}`);return i.join(`
|
|
6
|
-
`)}var ln=(r)=>(i,$,o,n)=>{let t=o?{...o,async:!1}:{async:!1},v=i._zod.run({value:$,issues:[]},t);if(v instanceof Promise)throw new H;if(v.issues.length){let u=new(n?.Err??r)(v.issues.map((g)=>E(g,t,K())));throw cn(u,n?.callee),u}return v.value},tr=ln(A),mn=(r)=>async(i,$,o,n)=>{let t=o?{...o,async:!0}:{async:!0},v=i._zod.run({value:$,issues:[]},t);if(v instanceof Promise)v=await v;if(v.issues.length){let u=new(n?.Err??r)(v.issues.map((g)=>E(g,t,K())));throw cn(u,n?.callee),u}return v.value},$r=mn(A),Un=(r)=>(i,$,o)=>{let n=o?{...o,async:!1}:{async:!1},t=i._zod.run({value:$,issues:[]},n);if(t instanceof Promise)throw new H;return t.issues.length?{success:!1,error:new(r??_i)(t.issues.map((v)=>E(v,n,K())))}:{success:!0,data:t.value}},kr=Un(A),In=(r)=>async(i,$,o)=>{let n=o?{...o,async:!0}:{async:!0},t=i._zod.run({value:$,issues:[]},n);if(t instanceof Promise)t=await t;return t.issues.length?{success:!1,error:new r(t.issues.map((v)=>E(v,n,K())))}:{success:!0,data:t.value}},br=In(A),fu=(r)=>(i,$,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ln(r)(i,$,n)},Oi=fu(A),Zu=(r)=>(i,$,o)=>{return ln(r)(i,$,o)},Ni=Zu(A),Mu=(r)=>async(i,$,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return mn(r)(i,$,n)},ji=Mu(A),Hu=(r)=>async(i,$,o)=>{return mn(r)(i,$,o)},zi=Hu(A),Cu=(r)=>(i,$,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Un(r)(i,$,n)},Ji=Cu(A),hu=(r)=>(i,$,o)=>{return Un(r)(i,$,o)},Fi=hu(A),au=(r)=>async(i,$,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return In(r)(i,$,n)},Xi=au(A),yu=(r)=>async(i,$,o)=>{return In(r)(i,$,o)},xi=yu(A);var R={};mr(R,{xid:()=>qi,uuid7:()=>Jl,uuid6:()=>zl,uuid4:()=>jl,uuid:()=>_r,uppercase:()=>tt,unicodeEmail:()=>du,undefined:()=>nt,ulid:()=>Qi,time:()=>hi,string:()=>yi,sha512_hex:()=>Hl,sha512_base64url:()=>hl,sha512_base64:()=>Cl,sha384_hex:()=>fl,sha384_base64url:()=>Ml,sha384_base64:()=>Zl,sha256_hex:()=>Al,sha256_base64url:()=>Rl,sha256_base64:()=>Bl,sha1_hex:()=>Vl,sha1_base64url:()=>el,sha1_base64:()=>Tl,rfc5322Email:()=>Xl,number:()=>Tr,null:()=>rt,nanoid:()=>Ki,md5_hex:()=>Kl,md5_base64url:()=>El,md5_base64:()=>Ll,mac:()=>Bi,lowercase:()=>it,ksuid:()=>Wi,ipv6:()=>Ai,ipv4:()=>ei,integer:()=>pi,idnEmail:()=>xl,httpProtocol:()=>Mi,html5Email:()=>Fl,hostname:()=>Ql,hex:()=>Wl,guid:()=>Ei,extendedDuration:()=>Nl,emoji:()=>Ti,email:()=>Vi,e164:()=>Hi,duration:()=>Li,domain:()=>ql,datetime:()=>ai,date:()=>Ci,cuid2:()=>Yi,cuid:()=>Gi,cidrv6:()=>fi,cidrv4:()=>Ri,browserEmail:()=>Gl,boolean:()=>si,bigint:()=>di,base64url:()=>kn,base64:()=>Zi});var Gi=/^[cC][0-9a-z]{6,}$/,Yi=/^[0-9a-z]+$/,Qi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,qi=/^[0-9a-vA-V]{20}$/,Wi=/^[A-Za-z0-9]{27}$/,Ki=/^[a-zA-Z0-9_-]{21}$/,Li=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Nl=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ei=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_r=(r)=>{if(!r)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${r}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},jl=_r(4),zl=_r(6),Jl=_r(7),Vi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Fl=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Xl=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,du=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,xl=du,Gl=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Yl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ti(){return new RegExp(Yl,"u")}var ei=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ai=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Bi=(r)=>{let i=f(r??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},Ri=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,fi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kn=/^[A-Za-z0-9_-]*$/,Ql=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,ql=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Mi=/^https?$/,Hi=/^\+[1-9]\d{6,14}$/,pu="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Ci=new RegExp(`^${pu}$`);function su(r){return typeof r.precision==="number"?r.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":r.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${r.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function hi(r){return new RegExp(`^${su(r)}$`)}function ai(r){let i=su({precision:r.precision}),$=["Z"];if(r.local)$.push("");if(r.offset)$.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${i}(?:${$.join("|")})`;return new RegExp(`^${pu}T(?:${o})$`)}var yi=(r)=>{let i=r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${i}$`)},di=/^-?\d+n?$/,pi=/^-?\d+$/,Tr=/^-?\d+(?:\.\d+)?$/,si=/^(?:true|false)$/i,rt=/^null$/i;var nt=/^undefined$/i;var it=/^[^A-Z]*$/,tt=/^[^a-z]*$/,Wl=/^[0-9a-fA-F]*$/;function er(r,i){return new RegExp(`^[A-Za-z0-9+/]{${r}}${i}$`)}function Ar(r){return new RegExp(`^[A-Za-z0-9_-]{${r}}$`)}var Kl=/^[0-9a-fA-F]{32}$/,Ll=er(22,"=="),El=Ar(22),Vl=/^[0-9a-fA-F]{40}$/,Tl=er(27,"="),el=Ar(27),Al=/^[0-9a-fA-F]{64}$/,Bl=er(43,"="),Rl=Ar(43),fl=/^[0-9a-fA-F]{96}$/,Zl=er(64,""),Ml=Ar(64),Hl=/^[0-9a-fA-F]{128}$/,Cl=er(86,"=="),hl=Ar(86);var x=m("$ZodCheck",(r,i)=>{var $;r._zod??(r._zod={}),r._zod.def=i,($=r._zod).onattach??($.onattach=[])}),nc={number:"number",bigint:"bigint",object:"date"},bn=m("$ZodCheckLessThan",(r,i)=>{x.init(r,i);let $=nc[typeof i.value];r._zod.onattach.push((o)=>{let n=o._zod.bag,t=(i.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(i.value<t)if(i.inclusive)n.maximum=i.value;else n.exclusiveMaximum=i.value}),r._zod.check=(o)=>{if(i.inclusive?o.value<=i.value:o.value<i.value)return;o.issues.push({origin:$,code:"too_big",maximum:typeof i.value==="object"?i.value.getTime():i.value,input:o.value,inclusive:i.inclusive,inst:r,continue:!i.abort})}}),_n=m("$ZodCheckGreaterThan",(r,i)=>{x.init(r,i);let $=nc[typeof i.value];r._zod.onattach.push((o)=>{let n=o._zod.bag,t=(i.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(i.value>t)if(i.inclusive)n.minimum=i.value;else n.exclusiveMinimum=i.value}),r._zod.check=(o)=>{if(i.inclusive?o.value>=i.value:o.value>i.value)return;o.issues.push({origin:$,code:"too_small",minimum:typeof i.value==="object"?i.value.getTime():i.value,input:o.value,inclusive:i.inclusive,inst:r,continue:!i.abort})}}),$t=m("$ZodCheckMultipleOf",(r,i)=>{x.init(r,i),r._zod.onattach.push(($)=>{var o;(o=$._zod.bag).multipleOf??(o.multipleOf=i.value)}),r._zod.check=($)=>{if(typeof $.value!==typeof i.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof $.value==="bigint"?$.value%i.value===BigInt(0):ti($.value,i.value)===0)return;$.issues.push({origin:typeof $.value,code:"not_multiple_of",divisor:i.value,input:$.value,inst:r,continue:!i.abort})}}),ot=m("$ZodCheckNumberFormat",(r,i)=>{x.init(r,i),i.format=i.format||"float64";let $=i.format?.includes("int"),o=$?"int":"number",[n,t]=ci[i.format];r._zod.onattach.push((v)=>{let u=v._zod.bag;if(u.format=i.format,u.minimum=n,u.maximum=t,$)u.pattern=pi}),r._zod.check=(v)=>{let u=v.value;if($){if(!Number.isInteger(u)){v.issues.push({expected:o,format:i.format,code:"invalid_type",continue:!1,input:u,inst:r});return}if(!Number.isSafeInteger(u)){if(u>0)v.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:r,origin:o,inclusive:!0,continue:!i.abort});else v.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:r,origin:o,inclusive:!0,continue:!i.abort});return}}if(u<n)v.issues.push({origin:"number",input:u,code:"too_small",minimum:n,inclusive:!0,inst:r,continue:!i.abort});if(u>t)v.issues.push({origin:"number",input:u,code:"too_big",maximum:t,inclusive:!0,inst:r,continue:!i.abort})}}),vt=m("$ZodCheckBigIntFormat",(r,i)=>{x.init(r,i);let[$,o]=gi[i.format];r._zod.onattach.push((n)=>{let t=n._zod.bag;t.format=i.format,t.minimum=$,t.maximum=o}),r._zod.check=(n)=>{let t=n.value;if(t<$)n.issues.push({origin:"bigint",input:t,code:"too_small",minimum:$,inclusive:!0,inst:r,continue:!i.abort});if(t>o)n.issues.push({origin:"bigint",input:t,code:"too_big",maximum:o,inclusive:!0,inst:r,continue:!i.abort})}}),ut=m("$ZodCheckMaxSize",(r,i)=>{var $;x.init(r,i),($=r._zod.def).when??($.when=(o)=>{let n=o.value;return!s(n)&&n.size!==void 0}),r._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(i.maximum<n)o._zod.bag.maximum=i.maximum}),r._zod.check=(o)=>{let n=o.value;if(n.size<=i.maximum)return;o.issues.push({origin:Er(n),code:"too_big",maximum:i.maximum,inclusive:!0,input:n,inst:r,continue:!i.abort})}}),ct=m("$ZodCheckMinSize",(r,i)=>{var $;x.init(r,i),($=r._zod.def).when??($.when=(o)=>{let n=o.value;return!s(n)&&n.size!==void 0}),r._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(i.minimum>n)o._zod.bag.minimum=i.minimum}),r._zod.check=(o)=>{let n=o.value;if(n.size>=i.minimum)return;o.issues.push({origin:Er(n),code:"too_small",minimum:i.minimum,inclusive:!0,input:n,inst:r,continue:!i.abort})}}),gt=m("$ZodCheckSizeEquals",(r,i)=>{var $;x.init(r,i),($=r._zod.def).when??($.when=(o)=>{let n=o.value;return!s(n)&&n.size!==void 0}),r._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=i.size,n.maximum=i.size,n.size=i.size}),r._zod.check=(o)=>{let n=o.value,t=n.size;if(t===i.size)return;let v=t>i.size;o.issues.push({origin:Er(n),...v?{code:"too_big",maximum:i.size}:{code:"too_small",minimum:i.size},inclusive:!0,exact:!0,input:o.value,inst:r,continue:!i.abort})}}),lt=m("$ZodCheckMaxLength",(r,i)=>{var $;x.init(r,i),($=r._zod.def).when??($.when=(o)=>{let n=o.value;return!s(n)&&n.length!==void 0}),r._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(i.maximum<n)o._zod.bag.maximum=i.maximum}),r._zod.check=(o)=>{let n=o.value;if(n.length<=i.maximum)return;let v=Vr(n);o.issues.push({origin:v,code:"too_big",maximum:i.maximum,inclusive:!0,input:n,inst:r,continue:!i.abort})}}),mt=m("$ZodCheckMinLength",(r,i)=>{var $;x.init(r,i),($=r._zod.def).when??($.when=(o)=>{let n=o.value;return!s(n)&&n.length!==void 0}),r._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(i.minimum>n)o._zod.bag.minimum=i.minimum}),r._zod.check=(o)=>{let n=o.value;if(n.length>=i.minimum)return;let v=Vr(n);o.issues.push({origin:v,code:"too_small",minimum:i.minimum,inclusive:!0,input:n,inst:r,continue:!i.abort})}}),Ut=m("$ZodCheckLengthEquals",(r,i)=>{var $;x.init(r,i),($=r._zod.def).when??($.when=(o)=>{let n=o.value;return!s(n)&&n.length!==void 0}),r._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=i.length,n.maximum=i.length,n.length=i.length}),r._zod.check=(o)=>{let n=o.value,t=n.length;if(t===i.length)return;let v=Vr(n),u=t>i.length;o.issues.push({origin:v,...u?{code:"too_big",maximum:i.length}:{code:"too_small",minimum:i.length},inclusive:!0,exact:!0,input:o.value,inst:r,continue:!i.abort})}}),Nr=m("$ZodCheckStringFormat",(r,i)=>{var $,o;if(x.init(r,i),r._zod.onattach.push((n)=>{let t=n._zod.bag;if(t.format=i.format,i.pattern)t.patterns??(t.patterns=new Set),t.patterns.add(i.pattern)}),i.pattern)($=r._zod).check??($.check=(n)=>{if(i.pattern.lastIndex=0,i.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:i.format,input:n.value,...i.pattern?{pattern:i.pattern.toString()}:{},inst:r,continue:!i.abort})});else(o=r._zod).check??(o.check=()=>{})}),It=m("$ZodCheckRegex",(r,i)=>{Nr.init(r,i),r._zod.check=($)=>{if(i.pattern.lastIndex=0,i.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:"regex",input:$.value,pattern:i.pattern.toString(),inst:r,continue:!i.abort})}}),kt=m("$ZodCheckLowerCase",(r,i)=>{i.pattern??(i.pattern=it),Nr.init(r,i)}),bt=m("$ZodCheckUpperCase",(r,i)=>{i.pattern??(i.pattern=tt),Nr.init(r,i)}),_t=m("$ZodCheckIncludes",(r,i)=>{x.init(r,i);let $=f(i.includes),o=new RegExp(typeof i.position==="number"?`^.{${i.position}}${$}`:$);i.pattern=o,r._zod.onattach.push((n)=>{let t=n._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(o)}),r._zod.check=(n)=>{if(n.value.includes(i.includes,i.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:i.includes,input:n.value,inst:r,continue:!i.abort})}}),wt=m("$ZodCheckStartsWith",(r,i)=>{x.init(r,i);let $=new RegExp(`^${f(i.prefix)}.*`);i.pattern??(i.pattern=$),r._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add($)}),r._zod.check=(o)=>{if(o.value.startsWith(i.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:i.prefix,input:o.value,inst:r,continue:!i.abort})}}),Dt=m("$ZodCheckEndsWith",(r,i)=>{x.init(r,i);let $=new RegExp(`.*${f(i.suffix)}$`);i.pattern??(i.pattern=$),r._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add($)}),r._zod.check=(o)=>{if(o.value.endsWith(i.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:i.suffix,input:o.value,inst:r,continue:!i.abort})}});function rc(r,i,$){if(r.issues.length)i.issues.push(...e($,r.issues))}var St=m("$ZodCheckProperty",(r,i)=>{x.init(r,i),r._zod.check=($)=>{let o=i.schema._zod.run({value:$.value[i.property],issues:[]},{});if(o instanceof Promise)return o.then((n)=>rc(n,$,i.property));rc(o,$,i.property);return}}),Pt=m("$ZodCheckMimeType",(r,i)=>{x.init(r,i);let $=new Set(i.mime);r._zod.onattach.push((o)=>{o._zod.bag.mime=i.mime}),r._zod.check=(o)=>{if($.has(o.value.type))return;o.issues.push({code:"invalid_value",values:i.mime,input:o.value.type,inst:r,continue:!i.abort})}}),Ot=m("$ZodCheckOverwrite",(r,i)=>{x.init(r,i),r._zod.check=($)=>{$.value=i.tx($.value)}});class wn{constructor(r=[]){if(this.content=[],this.indent=0,this)this.args=r}indented(r){this.indent+=1,r(this),this.indent-=1}write(r){if(typeof r==="function"){r(this,{execution:"sync"}),r(this,{execution:"async"});return}let $=r.split(`
|
|
7
|
-
|
|
8
|
-
`))}}var Nt={major:4,minor:4,patch:3};var N=m("$ZodType",(r,i)=>{var $;r??(r={}),r._zod.def=i,r._zod.bag=r._zod.bag||{},r._zod.version=Nt;let o=[...r._zod.def.checks??[]];if(r._zod.traits.has("$ZodCheck"))o.unshift(r);for(let n of o)for(let t of n._zod.onattach)t(r);if(o.length===0)($=r._zod).deferred??($.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let n=(v,u,g)=>{let c=ir(v),l;for(let I of u){if(I._zod.def.when){if(bi(v))continue;if(!I._zod.def.when(v))continue}else if(c)continue;let _=v.issues.length,k=I._zod.check(v);if(k instanceof Promise&&g?.async===!1)throw new H;if(l||k instanceof Promise)l=(l??Promise.resolve()).then(async()=>{if(await k,v.issues.length===_)return;if(!c)c=ir(v,_)});else{if(v.issues.length===_)continue;if(!c)c=ir(v,_)}}if(l)return l.then(()=>{return v});return v},t=(v,u,g)=>{if(ir(v))return v.aborted=!0,v;let c=n(u,o,g);if(c instanceof Promise){if(g.async===!1)throw new H;return c.then((l)=>r._zod.parse(l,g))}return r._zod.parse(c,g)};r._zod.run=(v,u)=>{if(u.skipChecks)return r._zod.parse(v,u);if(u.direction==="backward"){let c=r._zod.parse({value:v.value,issues:[]},{...u,skipChecks:!0});if(c instanceof Promise)return c.then((l)=>{return t(l,v,u)});return t(c,v,u)}let g=r._zod.parse(v,u);if(g instanceof Promise){if(u.async===!1)throw new H;return g.then((c)=>n(c,o,u))}return n(g,o,u)}}J(r,"~standard",()=>({validate:(n)=>{try{let t=kr(r,n);return t.success?{value:t.data}:{issues:t.error?.issues}}catch(t){return br(r,n).then((v)=>v.success?{value:v.data}:{issues:v.error?.issues})}},vendor:"zod",version:1}))}),jr=m("$ZodString",(r,i)=>{N.init(r,i),r._zod.pattern=[...r?._zod.bag?.patterns??[]].pop()??yi(r._zod.bag),r._zod.parse=($,o)=>{if(i.coerce)try{$.value=String($.value)}catch(n){}if(typeof $.value==="string")return $;return $.issues.push({expected:"string",code:"invalid_type",input:$.value,inst:r}),$}}),X=m("$ZodStringFormat",(r,i)=>{Nr.init(r,i),jr.init(r,i)}),zt=m("$ZodGUID",(r,i)=>{i.pattern??(i.pattern=Ei),X.init(r,i)}),Jt=m("$ZodUUID",(r,i)=>{if(i.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(o===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=_r(o))}else i.pattern??(i.pattern=_r());X.init(r,i)}),Ft=m("$ZodEmail",(r,i)=>{i.pattern??(i.pattern=Vi),X.init(r,i)}),Xt=m("$ZodURL",(r,i)=>{X.init(r,i),r._zod.check=($)=>{try{let o=$.value.trim();if(!i.normalize&&i.protocol?.source===Mi.source){if(!/^https?:\/\//i.test(o)){$.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:$.value,inst:r,continue:!i.abort});return}}let n=new URL(o);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(n.hostname))$.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:$.value,inst:r,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))$.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:$.value,inst:r,continue:!i.abort})}if(i.normalize)$.value=n.href;else $.value=o;return}catch(o){$.issues.push({code:"invalid_format",format:"url",input:$.value,inst:r,continue:!i.abort})}}}),xt=m("$ZodEmoji",(r,i)=>{i.pattern??(i.pattern=Ti()),X.init(r,i)}),Gt=m("$ZodNanoID",(r,i)=>{i.pattern??(i.pattern=Ki),X.init(r,i)}),Yt=m("$ZodCUID",(r,i)=>{i.pattern??(i.pattern=Gi),X.init(r,i)}),Qt=m("$ZodCUID2",(r,i)=>{i.pattern??(i.pattern=Yi),X.init(r,i)}),qt=m("$ZodULID",(r,i)=>{i.pattern??(i.pattern=Qi),X.init(r,i)}),Wt=m("$ZodXID",(r,i)=>{i.pattern??(i.pattern=qi),X.init(r,i)}),Kt=m("$ZodKSUID",(r,i)=>{i.pattern??(i.pattern=Wi),X.init(r,i)}),Lt=m("$ZodISODateTime",(r,i)=>{i.pattern??(i.pattern=ai(i)),X.init(r,i)}),Et=m("$ZodISODate",(r,i)=>{i.pattern??(i.pattern=Ci),X.init(r,i)}),Vt=m("$ZodISOTime",(r,i)=>{i.pattern??(i.pattern=hi(i)),X.init(r,i)}),Tt=m("$ZodISODuration",(r,i)=>{i.pattern??(i.pattern=Li),X.init(r,i)}),et=m("$ZodIPv4",(r,i)=>{i.pattern??(i.pattern=ei),X.init(r,i),r._zod.bag.format="ipv4"}),At=m("$ZodIPv6",(r,i)=>{i.pattern??(i.pattern=Ai),X.init(r,i),r._zod.bag.format="ipv6",r._zod.check=($)=>{try{new URL(`http://[${$.value}]`)}catch{$.issues.push({code:"invalid_format",format:"ipv6",input:$.value,inst:r,continue:!i.abort})}}}),Bt=m("$ZodMAC",(r,i)=>{i.pattern??(i.pattern=Bi(i.delimiter)),X.init(r,i),r._zod.bag.format="mac"}),Rt=m("$ZodCIDRv4",(r,i)=>{i.pattern??(i.pattern=Ri),X.init(r,i)}),ft=m("$ZodCIDRv6",(r,i)=>{i.pattern??(i.pattern=fi),X.init(r,i),r._zod.check=($)=>{let o=$.value.split("/");try{if(o.length!==2)throw Error();let[n,t]=o;if(!t)throw Error();let v=Number(t);if(`${v}`!==t)throw Error();if(v<0||v>128)throw Error();new URL(`http://[${n}]`)}catch{$.issues.push({code:"invalid_format",format:"cidrv6",input:$.value,inst:r,continue:!i.abort})}}});function Zt(r){if(r==="")return!0;if(/\s/.test(r))return!1;if(r.length%4!==0)return!1;try{return atob(r),!0}catch{return!1}}var Mt=m("$ZodBase64",(r,i)=>{i.pattern??(i.pattern=Zi),X.init(r,i),r._zod.bag.contentEncoding="base64",r._zod.check=($)=>{if(Zt($.value))return;$.issues.push({code:"invalid_format",format:"base64",input:$.value,inst:r,continue:!i.abort})}});function wc(r){if(!kn.test(r))return!1;let i=r.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),$=i.padEnd(Math.ceil(i.length/4)*4,"=");return Zt($)}var Ht=m("$ZodBase64URL",(r,i)=>{i.pattern??(i.pattern=kn),X.init(r,i),r._zod.bag.contentEncoding="base64url",r._zod.check=($)=>{if(wc($.value))return;$.issues.push({code:"invalid_format",format:"base64url",input:$.value,inst:r,continue:!i.abort})}}),Ct=m("$ZodE164",(r,i)=>{i.pattern??(i.pattern=Hi),X.init(r,i)});function Dc(r,i=null){try{let $=r.split(".");if($.length!==3)return!1;let[o]=$;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(i&&(!("alg"in n)||n.alg!==i))return!1;return!0}catch{return!1}}var ht=m("$ZodJWT",(r,i)=>{X.init(r,i),r._zod.check=($)=>{if(Dc($.value,i.alg))return;$.issues.push({code:"invalid_format",format:"jwt",input:$.value,inst:r,continue:!i.abort})}}),at=m("$ZodCustomStringFormat",(r,i)=>{X.init(r,i),r._zod.check=($)=>{if(i.fn($.value))return;$.issues.push({code:"invalid_format",format:i.format,input:$.value,inst:r,continue:!i.abort})}}),Nn=m("$ZodNumber",(r,i)=>{N.init(r,i),r._zod.pattern=r._zod.bag.pattern??Tr,r._zod.parse=($,o)=>{if(i.coerce)try{$.value=Number($.value)}catch(v){}let n=$.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return $;let t=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return $.issues.push({expected:"number",code:"invalid_type",input:n,inst:r,...t?{received:t}:{}}),$}}),yt=m("$ZodNumberFormat",(r,i)=>{ot.init(r,i),Nn.init(r,i)}),Br=m("$ZodBoolean",(r,i)=>{N.init(r,i),r._zod.pattern=si,r._zod.parse=($,o)=>{if(i.coerce)try{$.value=Boolean($.value)}catch(t){}let n=$.value;if(typeof n==="boolean")return $;return $.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:r}),$}}),jn=m("$ZodBigInt",(r,i)=>{N.init(r,i),r._zod.pattern=di,r._zod.parse=($,o)=>{if(i.coerce)try{$.value=BigInt($.value)}catch(n){}if(typeof $.value==="bigint")return $;return $.issues.push({expected:"bigint",code:"invalid_type",input:$.value,inst:r}),$}}),dt=m("$ZodBigIntFormat",(r,i)=>{vt.init(r,i),jn.init(r,i)}),pt=m("$ZodSymbol",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{let n=$.value;if(typeof n==="symbol")return $;return $.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:r}),$}}),st=m("$ZodUndefined",(r,i)=>{N.init(r,i),r._zod.pattern=nt,r._zod.values=new Set([void 0]),r._zod.parse=($,o)=>{let n=$.value;if(typeof n>"u")return $;return $.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:r}),$}}),r$=m("$ZodNull",(r,i)=>{N.init(r,i),r._zod.pattern=rt,r._zod.values=new Set([null]),r._zod.parse=($,o)=>{let n=$.value;if(n===null)return $;return $.issues.push({expected:"null",code:"invalid_type",input:n,inst:r}),$}}),n$=m("$ZodAny",(r,i)=>{N.init(r,i),r._zod.parse=($)=>$}),i$=m("$ZodUnknown",(r,i)=>{N.init(r,i),r._zod.parse=($)=>$}),t$=m("$ZodNever",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{return $.issues.push({expected:"never",code:"invalid_type",input:$.value,inst:r}),$}}),$$=m("$ZodVoid",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{let n=$.value;if(typeof n>"u")return $;return $.issues.push({expected:"void",code:"invalid_type",input:n,inst:r}),$}}),o$=m("$ZodDate",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{if(i.coerce)try{$.value=new Date($.value)}catch(u){}let n=$.value,t=n instanceof Date;if(t&&!Number.isNaN(n.getTime()))return $;return $.issues.push({expected:"date",code:"invalid_type",input:n,...t?{received:"Invalid Date"}:{},inst:r}),$}});function tc(r,i,$){if(r.issues.length)i.issues.push(...e($,r.issues));i.value[$]=r.value}var v$=m("$ZodArray",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{let n=$.value;if(!Array.isArray(n))return $.issues.push({expected:"array",code:"invalid_type",input:n,inst:r}),$;$.value=Array(n.length);let t=[];for(let v=0;v<n.length;v++){let u=n[v],g=i.element._zod.run({value:u,issues:[]},o);if(g instanceof Promise)t.push(g.then((c)=>tc(c,$,v)));else tc(g,$,v)}if(t.length)return Promise.all(t).then(()=>$);return $}});function On(r,i,$,o,n,t){let v=$ in o;if(r.issues.length){if(n&&t&&!v)return;i.issues.push(...e($,r.issues))}if(!v&&!n){if(!r.issues.length)i.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[$]});return}if(r.value===void 0){if(v)i.value[$]=void 0}else i.value[$]=r.value}function Sc(r){let i=Object.keys(r.shape);for(let o of i)if(!r.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let $=ui(r.shape);return{...r,keys:i,keySet:new Set(i),numKeys:i.length,optionalKeys:new Set($)}}function Pc(r,i,$,o,n,t){let v=[],u=n.keySet,g=n.catchall._zod,c=g.def.type,l=g.optin==="optional",I=g.optout==="optional";for(let _ in i){if(_==="__proto__")continue;if(u.has(_))continue;if(c==="never"){v.push(_);continue}let k=g.run({value:i[_],issues:[]},o);if(k instanceof Promise)r.push(k.then((P)=>On(P,$,_,i,l,I)));else On(k,$,_,i,l,I)}if(v.length)$.issues.push({code:"unrecognized_keys",keys:v,input:i,inst:t});if(!r.length)return $;return Promise.all(r).then(()=>{return $})}var zn=m("$ZodObject",(r,i)=>{if(N.init(r,i),!Object.getOwnPropertyDescriptor(i,"shape")?.get){let u=i.shape;Object.defineProperty(i,"shape",{get:()=>{let g={...u};return Object.defineProperty(i,"shape",{value:g}),g}})}let o=Sr(()=>Sc(i));J(r._zod,"propValues",()=>{let u=i.shape,g={};for(let c in u){let l=u[c]._zod;if(l.values){g[c]??(g[c]=new Set);for(let I of l.values)g[c].add(I)}}return g});let n=Ir,t=i.catchall,v;r._zod.parse=(u,g)=>{v??(v=o.value);let c=u.value;if(!n(c))return u.issues.push({expected:"object",code:"invalid_type",input:c,inst:r}),u;u.value={};let l=[],I=v.shape;for(let _ of v.keys){let k=I[_],P=k._zod.optin==="optional",q=k._zod.optout==="optional",Q=k._zod.run({value:c[_],issues:[]},g);if(Q instanceof Promise)l.push(Q.then((Y)=>On(Y,u,_,c,P,q)));else On(Q,u,_,c,P,q)}if(!t)return l.length?Promise.all(l).then(()=>u):u;return Pc(l,c,u,g,o.value,r)}}),al=m("$ZodObjectJIT",(r,i)=>{zn.init(r,i);let $=r._zod.parse,o=Sr(()=>Sc(i)),n=(_)=>{let k=new wn(["shape","payload","ctx"]),P=o.value,q=(M)=>{let j=un(M);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};k.write("const input = payload.value;");let Q=Object.create(null),Y=0;for(let M of P.keys)Q[M]=`key_${Y++}`;k.write("const newResult = {};");for(let M of P.keys){let j=Q[M],W=un(M),Yu=_[M],Qu=Yu?._zod?.optin==="optional",rl=Yu?._zod?.optout==="optional";if(k.write(`const ${j} = ${q(M)};`),Qu&&rl)k.write(`
|
|
9
|
-
|
|
10
|
-
if (${W} in input) {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
path: iss.path ? [${W}, ...iss.path] : [${W}]
|
|
14
|
-
})));
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
if (${j}.value === undefined) {
|
|
19
|
-
if (${W} in input) {
|
|
20
|
-
newResult[${W}] = undefined;
|
|
21
|
-
}
|
|
22
|
-
} else {
|
|
23
|
-
newResult[${W}] = ${j}.value;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
`);else if(!Qu)k.write(`
|
|
27
|
-
const ${j}_present = ${W} in input;
|
|
28
|
-
if (${j}.issues.length) {
|
|
29
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
30
|
-
...iss,
|
|
31
|
-
path: iss.path ? [${W}, ...iss.path] : [${W}]
|
|
32
|
-
})));
|
|
33
|
-
}
|
|
34
|
-
if (!${j}_present && !${j}.issues.length) {
|
|
35
|
-
payload.issues.push({
|
|
36
|
-
code: "invalid_type",
|
|
37
|
-
expected: "nonoptional",
|
|
38
|
-
input: undefined,
|
|
39
|
-
path: [${W}]
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
if (${j}_present) {
|
|
44
|
-
if (${j}.value === undefined) {
|
|
45
|
-
newResult[${W}] = undefined;
|
|
46
|
-
} else {
|
|
47
|
-
newResult[${W}] = ${j}.value;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
`);else k.write(`
|
|
52
|
-
if (${j}.issues.length) {
|
|
53
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
54
|
-
...iss,
|
|
55
|
-
path: iss.path ? [${W}, ...iss.path] : [${W}]
|
|
56
|
-
})));
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
if (${j}.value === undefined) {
|
|
60
|
-
if (${W} in input) {
|
|
61
|
-
newResult[${W}] = undefined;
|
|
62
|
-
}
|
|
63
|
-
} else {
|
|
64
|
-
newResult[${W}] = ${j}.value;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
`)}k.write("payload.value = newResult;"),k.write("return payload;");let sg=k.compile();return(M,j)=>sg(_,M,j)},t,v=Ir,u=!Ur.jitless,c=u&&oi.value,l=i.catchall,I;r._zod.parse=(_,k)=>{I??(I=o.value);let P=_.value;if(!v(P))return _.issues.push({expected:"object",code:"invalid_type",input:P,inst:r}),_;if(u&&c&&k?.async===!1&&k.jitless!==!0){if(!t)t=n(i.shape);if(_=t(_,k),!l)return _;return Pc([],P,_,k,I,r)}return $(_,k)}});function $c(r,i,$,o){for(let t of r)if(t.issues.length===0)return i.value=t.value,i;let n=r.filter((t)=>!ir(t));if(n.length===1)return i.value=n[0].value,n[0];return i.issues.push({code:"invalid_union",input:i.value,inst:$,errors:r.map((t)=>t.issues.map((v)=>E(v,o,K())))}),i}var Rr=m("$ZodUnion",(r,i)=>{N.init(r,i),J(r._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),J(r._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),J(r._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),J(r._zod,"pattern",()=>{if(i.options.every((o)=>o._zod.pattern)){let o=i.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>Kr(n.source)).join("|")})$`)}return});let $=i.options.length===1?i.options[0]._zod.run:null;r._zod.parse=(o,n)=>{if($)return $(o,n);let t=!1,v=[];for(let u of i.options){let g=u._zod.run({value:o.value,issues:[]},n);if(g instanceof Promise)v.push(g),t=!0;else{if(g.issues.length===0)return g;v.push(g)}}if(!t)return $c(v,o,r,n);return Promise.all(v).then((u)=>{return $c(u,o,r,n)})}});function oc(r,i,$,o){let n=r.filter((t)=>t.issues.length===0);if(n.length===1)return i.value=n[0].value,i;if(n.length===0)i.issues.push({code:"invalid_union",input:i.value,inst:$,errors:r.map((t)=>t.issues.map((v)=>E(v,o,K())))});else i.issues.push({code:"invalid_union",input:i.value,inst:$,errors:[],inclusive:!1});return i}var u$=m("$ZodXor",(r,i)=>{Rr.init(r,i),i.inclusive=!1;let $=i.options.length===1?i.options[0]._zod.run:null;r._zod.parse=(o,n)=>{if($)return $(o,n);let t=!1,v=[];for(let u of i.options){let g=u._zod.run({value:o.value,issues:[]},n);if(g instanceof Promise)v.push(g),t=!0;else v.push(g)}if(!t)return oc(v,o,r,n);return Promise.all(v).then((u)=>{return oc(u,o,r,n)})}}),c$=m("$ZodDiscriminatedUnion",(r,i)=>{i.inclusive=!1,Rr.init(r,i);let $=r._zod.parse;J(r._zod,"propValues",()=>{let n={};for(let t of i.options){let v=t._zod.propValues;if(!v||Object.keys(v).length===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(t)}"`);for(let[u,g]of Object.entries(v)){if(!n[u])n[u]=new Set;for(let c of g)n[u].add(c)}}return n});let o=Sr(()=>{let n=i.options,t=new Map;for(let v of n){let u=v._zod.propValues?.[i.discriminator];if(!u||u.size===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(v)}"`);for(let g of u){if(t.has(g))throw Error(`Duplicate discriminator value "${String(g)}"`);t.set(g,v)}}return t});r._zod.parse=(n,t)=>{let v=n.value;if(!Ir(v))return n.issues.push({code:"invalid_type",expected:"object",input:v,inst:r}),n;let u=o.value.get(v?.[i.discriminator]);if(u)return u._zod.run(n,t);if(i.unionFallback||t.direction==="backward")return $(n,t);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:i.discriminator,options:Array.from(o.value.keys()),input:v,path:[i.discriminator],inst:r}),n}}),g$=m("$ZodIntersection",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{let n=$.value,t=i.left._zod.run({value:n,issues:[]},o),v=i.right._zod.run({value:n,issues:[]},o);if(t instanceof Promise||v instanceof Promise)return Promise.all([t,v]).then(([g,c])=>{return vc($,g,c)});return vc($,t,v)}});function jt(r,i){if(r===i)return{valid:!0,data:r};if(r instanceof Date&&i instanceof Date&&+r===+i)return{valid:!0,data:r};if(nr(r)&&nr(i)){let $=Object.keys(i),o=Object.keys(r).filter((t)=>$.indexOf(t)!==-1),n={...r,...i};for(let t of o){let v=jt(r[t],i[t]);if(!v.valid)return{valid:!1,mergeErrorPath:[t,...v.mergeErrorPath]};n[t]=v.data}return{valid:!0,data:n}}if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return{valid:!1,mergeErrorPath:[]};let $=[];for(let o=0;o<r.length;o++){let n=r[o],t=i[o],v=jt(n,t);if(!v.valid)return{valid:!1,mergeErrorPath:[o,...v.mergeErrorPath]};$.push(v.data)}return{valid:!0,data:$}}return{valid:!1,mergeErrorPath:[]}}function vc(r,i,$){let o=new Map,n;for(let u of i.issues)if(u.code==="unrecognized_keys"){n??(n=u);for(let g of u.keys){if(!o.has(g))o.set(g,{});o.get(g).l=!0}}else r.issues.push(u);for(let u of $.issues)if(u.code==="unrecognized_keys")for(let g of u.keys){if(!o.has(g))o.set(g,{});o.get(g).r=!0}else r.issues.push(u);let t=[...o].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(t.length&&n)r.issues.push({...n,keys:t});if(ir(r))return r;let v=jt(i.value,$.value);if(!v.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(v.mergeErrorPath)}`);return r.value=v.data,r}var Jn=m("$ZodTuple",(r,i)=>{N.init(r,i);let $=i.items;r._zod.parse=(o,n)=>{let t=o.value;if(!Array.isArray(t))return o.issues.push({input:t,inst:r,expected:"tuple",code:"invalid_type"}),o;o.value=[];let v=[],u=uc($,"optin"),g=uc($,"optout");if(!i.rest){if(t.length<u)return o.issues.push({code:"too_small",minimum:u,inclusive:!0,input:t,inst:r,origin:"array"}),o;if(t.length>$.length)o.issues.push({code:"too_big",maximum:$.length,inclusive:!0,input:t,inst:r,origin:"array"})}let c=Array($.length);for(let l=0;l<$.length;l++){let I=$[l]._zod.run({value:t[l],issues:[]},n);if(I instanceof Promise)v.push(I.then((_)=>{c[l]=_}));else c[l]=I}if(i.rest){let l=$.length-1,I=t.slice($.length);for(let _ of I){l++;let k=i.rest._zod.run({value:_,issues:[]},n);if(k instanceof Promise)v.push(k.then((P)=>cc(P,o,l)));else cc(k,o,l)}}if(v.length)return Promise.all(v).then(()=>gc(c,o,$,t,g));return gc(c,o,$,t,g)}});function uc(r,i){for(let $=r.length-1;$>=0;$--)if(r[$]._zod[i]!=="optional")return $+1;return 0}function cc(r,i,$){if(r.issues.length)i.issues.push(...e($,r.issues));i.value[$]=r.value}function gc(r,i,$,o,n){for(let t=0;t<$.length;t++){let v=r[t],u=t<o.length;if(v.issues.length){if(!u&&t>=n){i.value.length=t;break}i.issues.push(...e(t,v.issues))}i.value[t]=v.value}for(let t=i.value.length-1;t>=o.length;t--)if($[t]._zod.optout==="optional"&&i.value[t]===void 0)i.value.length=t;else break;return i}var l$=m("$ZodRecord",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{let n=$.value;if(!nr(n))return $.issues.push({expected:"record",code:"invalid_type",input:n,inst:r}),$;let t=[],v=i.keyType._zod.values;if(v){$.value={};let u=new Set;for(let c of v)if(typeof c==="string"||typeof c==="number"||typeof c==="symbol"){u.add(typeof c==="number"?c.toString():c);let l=i.keyType._zod.run({value:c,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){$.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((k)=>E(k,o,K())),input:c,path:[c],inst:r});continue}let I=l.value,_=i.valueType._zod.run({value:n[c],issues:[]},o);if(_ instanceof Promise)t.push(_.then((k)=>{if(k.issues.length)$.issues.push(...e(c,k.issues));$.value[I]=k.value}));else{if(_.issues.length)$.issues.push(...e(c,_.issues));$.value[I]=_.value}}let g;for(let c in n)if(!u.has(c))g=g??[],g.push(c);if(g&&g.length>0)$.issues.push({code:"unrecognized_keys",input:n,inst:r,keys:g})}else{$.value={};for(let u of Reflect.ownKeys(n)){if(u==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,u))continue;let g=i.keyType._zod.run({value:u,issues:[]},o);if(g instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof u==="string"&&Tr.test(u)&&g.issues.length){let I=i.keyType._zod.run({value:Number(u),issues:[]},o);if(I instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(I.issues.length===0)g=I}if(g.issues.length){if(i.mode==="loose")$.value[u]=n[u];else $.issues.push({code:"invalid_key",origin:"record",issues:g.issues.map((I)=>E(I,o,K())),input:u,path:[u],inst:r});continue}let l=i.valueType._zod.run({value:n[u],issues:[]},o);if(l instanceof Promise)t.push(l.then((I)=>{if(I.issues.length)$.issues.push(...e(u,I.issues));$.value[g.value]=I.value}));else{if(l.issues.length)$.issues.push(...e(u,l.issues));$.value[g.value]=l.value}}}if(t.length)return Promise.all(t).then(()=>$);return $}}),m$=m("$ZodMap",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{let n=$.value;if(!(n instanceof Map))return $.issues.push({expected:"map",code:"invalid_type",input:n,inst:r}),$;let t=[];$.value=new Map;for(let[v,u]of n){let g=i.keyType._zod.run({value:v,issues:[]},o),c=i.valueType._zod.run({value:u,issues:[]},o);if(g instanceof Promise||c instanceof Promise)t.push(Promise.all([g,c]).then(([l,I])=>{lc(l,I,$,v,n,r,o)}));else lc(g,c,$,v,n,r,o)}if(t.length)return Promise.all(t).then(()=>$);return $}});function lc(r,i,$,o,n,t,v){if(r.issues.length)if(Lr.has(typeof o))$.issues.push(...e(o,r.issues));else $.issues.push({code:"invalid_key",origin:"map",input:n,inst:t,issues:r.issues.map((u)=>E(u,v,K()))});if(i.issues.length)if(Lr.has(typeof o))$.issues.push(...e(o,i.issues));else $.issues.push({origin:"map",code:"invalid_element",input:n,inst:t,key:o,issues:i.issues.map((u)=>E(u,v,K()))});$.value.set(r.value,i.value)}var U$=m("$ZodSet",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{let n=$.value;if(!(n instanceof Set))return $.issues.push({input:n,inst:r,expected:"set",code:"invalid_type"}),$;let t=[];$.value=new Set;for(let v of n){let u=i.valueType._zod.run({value:v,issues:[]},o);if(u instanceof Promise)t.push(u.then((g)=>mc(g,$)));else mc(u,$)}if(t.length)return Promise.all(t).then(()=>$);return $}});function mc(r,i){if(r.issues.length)i.issues.push(...r.issues);i.value.add(r.value)}var I$=m("$ZodEnum",(r,i)=>{N.init(r,i);let $=Wr(i.entries),o=new Set($);r._zod.values=o,r._zod.pattern=new RegExp(`^(${$.filter((n)=>Lr.has(typeof n)).map((n)=>typeof n==="string"?f(n):n.toString()).join("|")})$`),r._zod.parse=(n,t)=>{let v=n.value;if(o.has(v))return n;return n.issues.push({code:"invalid_value",values:$,input:v,inst:r}),n}}),k$=m("$ZodLiteral",(r,i)=>{if(N.init(r,i),i.values.length===0)throw Error("Cannot create literal schema with no valid values");let $=new Set(i.values);r._zod.values=$,r._zod.pattern=new RegExp(`^(${i.values.map((o)=>typeof o==="string"?f(o):o?f(o.toString()):String(o)).join("|")})$`),r._zod.parse=(o,n)=>{let t=o.value;if($.has(t))return o;return o.issues.push({code:"invalid_value",values:i.values,input:t,inst:r}),o}}),b$=m("$ZodFile",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{let n=$.value;if(n instanceof File)return $;return $.issues.push({expected:"file",code:"invalid_type",input:n,inst:r}),$}}),_$=m("$ZodTransform",(r,i)=>{N.init(r,i),r._zod.optin="optional",r._zod.parse=($,o)=>{if(o.direction==="backward")throw new Qr(r.constructor.name);let n=i.transform($.value,$);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((v)=>{return $.value=v,$.fallback=!0,$});if(n instanceof Promise)throw new H;return $.value=n,$.fallback=!0,$}});function Uc(r,i){if(i===void 0&&(r.issues.length||r.fallback))return{issues:[],value:void 0};return r}var Fn=m("$ZodOptional",(r,i)=>{N.init(r,i),r._zod.optin="optional",r._zod.optout="optional",J(r._zod,"values",()=>{return i.innerType._zod.values?new Set([...i.innerType._zod.values,void 0]):void 0}),J(r._zod,"pattern",()=>{let $=i.innerType._zod.pattern;return $?new RegExp(`^(${Kr($.source)})?$`):void 0}),r._zod.parse=($,o)=>{if(i.innerType._zod.optin==="optional"){let n=$.value,t=i.innerType._zod.run($,o);if(t instanceof Promise)return t.then((v)=>Uc(v,n));return Uc(t,n)}if($.value===void 0)return $;return i.innerType._zod.run($,o)}}),w$=m("$ZodExactOptional",(r,i)=>{Fn.init(r,i),J(r._zod,"values",()=>i.innerType._zod.values),J(r._zod,"pattern",()=>i.innerType._zod.pattern),r._zod.parse=($,o)=>{return i.innerType._zod.run($,o)}}),D$=m("$ZodNullable",(r,i)=>{N.init(r,i),J(r._zod,"optin",()=>i.innerType._zod.optin),J(r._zod,"optout",()=>i.innerType._zod.optout),J(r._zod,"pattern",()=>{let $=i.innerType._zod.pattern;return $?new RegExp(`^(${Kr($.source)}|null)$`):void 0}),J(r._zod,"values",()=>{return i.innerType._zod.values?new Set([...i.innerType._zod.values,null]):void 0}),r._zod.parse=($,o)=>{if($.value===null)return $;return i.innerType._zod.run($,o)}}),S$=m("$ZodDefault",(r,i)=>{N.init(r,i),r._zod.optin="optional",J(r._zod,"values",()=>i.innerType._zod.values),r._zod.parse=($,o)=>{if(o.direction==="backward")return i.innerType._zod.run($,o);if($.value===void 0)return $.value=i.defaultValue,$;let n=i.innerType._zod.run($,o);if(n instanceof Promise)return n.then((t)=>Ic(t,i));return Ic(n,i)}});function Ic(r,i){if(r.value===void 0)r.value=i.defaultValue;return r}var P$=m("$ZodPrefault",(r,i)=>{N.init(r,i),r._zod.optin="optional",J(r._zod,"values",()=>i.innerType._zod.values),r._zod.parse=($,o)=>{if(o.direction==="backward")return i.innerType._zod.run($,o);if($.value===void 0)$.value=i.defaultValue;return i.innerType._zod.run($,o)}}),O$=m("$ZodNonOptional",(r,i)=>{N.init(r,i),J(r._zod,"values",()=>{let $=i.innerType._zod.values;return $?new Set([...$].filter((o)=>o!==void 0)):void 0}),r._zod.parse=($,o)=>{let n=i.innerType._zod.run($,o);if(n instanceof Promise)return n.then((t)=>kc(t,r));return kc(n,r)}});function kc(r,i){if(!r.issues.length&&r.value===void 0)r.issues.push({code:"invalid_type",expected:"nonoptional",input:r.value,inst:i});return r}var N$=m("$ZodSuccess",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{if(o.direction==="backward")throw new Qr("ZodSuccess");let n=i.innerType._zod.run($,o);if(n instanceof Promise)return n.then((t)=>{return $.value=t.issues.length===0,$});return $.value=n.issues.length===0,$}}),j$=m("$ZodCatch",(r,i)=>{N.init(r,i),r._zod.optin="optional",J(r._zod,"optout",()=>i.innerType._zod.optout),J(r._zod,"values",()=>i.innerType._zod.values),r._zod.parse=($,o)=>{if(o.direction==="backward")return i.innerType._zod.run($,o);let n=i.innerType._zod.run($,o);if(n instanceof Promise)return n.then((t)=>{if($.value=t.value,t.issues.length)$.value=i.catchValue({...$,error:{issues:t.issues.map((v)=>E(v,o,K()))},input:$.value}),$.issues=[],$.fallback=!0;return $});if($.value=n.value,n.issues.length)$.value=i.catchValue({...$,error:{issues:n.issues.map((t)=>E(t,o,K()))},input:$.value}),$.issues=[],$.fallback=!0;return $}}),z$=m("$ZodNaN",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{if(typeof $.value!=="number"||!Number.isNaN($.value))return $.issues.push({input:$.value,inst:r,expected:"nan",code:"invalid_type"}),$;return $}}),Xn=m("$ZodPipe",(r,i)=>{N.init(r,i),J(r._zod,"values",()=>i.in._zod.values),J(r._zod,"optin",()=>i.in._zod.optin),J(r._zod,"optout",()=>i.out._zod.optout),J(r._zod,"propValues",()=>i.in._zod.propValues),r._zod.parse=($,o)=>{if(o.direction==="backward"){let t=i.out._zod.run($,o);if(t instanceof Promise)return t.then((v)=>Dn(v,i.in,o));return Dn(t,i.in,o)}let n=i.in._zod.run($,o);if(n instanceof Promise)return n.then((t)=>Dn(t,i.out,o));return Dn(n,i.out,o)}});function Dn(r,i,$){if(r.issues.length)return r.aborted=!0,r;return i._zod.run({value:r.value,issues:r.issues,fallback:r.fallback},$)}var fr=m("$ZodCodec",(r,i)=>{N.init(r,i),J(r._zod,"values",()=>i.in._zod.values),J(r._zod,"optin",()=>i.in._zod.optin),J(r._zod,"optout",()=>i.out._zod.optout),J(r._zod,"propValues",()=>i.in._zod.propValues),r._zod.parse=($,o)=>{if((o.direction||"forward")==="forward"){let t=i.in._zod.run($,o);if(t instanceof Promise)return t.then((v)=>Sn(v,i,o));return Sn(t,i,o)}else{let t=i.out._zod.run($,o);if(t instanceof Promise)return t.then((v)=>Sn(v,i,o));return Sn(t,i,o)}}});function Sn(r,i,$){if(r.issues.length)return r.aborted=!0,r;if(($.direction||"forward")==="forward"){let n=i.transform(r.value,r);if(n instanceof Promise)return n.then((t)=>Pn(r,t,i.out,$));return Pn(r,n,i.out,$)}else{let n=i.reverseTransform(r.value,r);if(n instanceof Promise)return n.then((t)=>Pn(r,t,i.in,$));return Pn(r,n,i.in,$)}}function Pn(r,i,$,o){if(r.issues.length)return r.aborted=!0,r;return $._zod.run({value:i,issues:r.issues},o)}var yl=m("$ZodPreprocess",(r,i)=>{Xn.init(r,i)}),J$=m("$ZodReadonly",(r,i)=>{N.init(r,i),J(r._zod,"propValues",()=>i.innerType._zod.propValues),J(r._zod,"values",()=>i.innerType._zod.values),J(r._zod,"optin",()=>i.innerType?._zod?.optin),J(r._zod,"optout",()=>i.innerType?._zod?.optout),r._zod.parse=($,o)=>{if(o.direction==="backward")return i.innerType._zod.run($,o);let n=i.innerType._zod.run($,o);if(n instanceof Promise)return n.then(bc);return bc(n)}});function bc(r){return r.value=Object.freeze(r.value),r}var F$=m("$ZodTemplateLiteral",(r,i)=>{N.init(r,i);let $=[];for(let o of i.parts)if(typeof o==="object"&&o!==null){if(!o._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...o._zod.traits].shift()}`);let n=o._zod.pattern instanceof RegExp?o._zod.pattern.source:o._zod.pattern;if(!n)throw Error(`Invalid template literal part: ${o._zod.traits}`);let t=n.startsWith("^")?1:0,v=n.endsWith("$")?n.length-1:n.length;$.push(n.slice(t,v))}else if(o===null||vi.has(typeof o))$.push(f(`${o}`));else throw Error(`Invalid template literal part: ${o}`);r._zod.pattern=new RegExp(`^${$.join("")}$`),r._zod.parse=(o,n)=>{if(typeof o.value!=="string")return o.issues.push({input:o.value,inst:r,expected:"string",code:"invalid_type"}),o;if(r._zod.pattern.lastIndex=0,!r._zod.pattern.test(o.value))return o.issues.push({input:o.value,inst:r,code:"invalid_format",format:i.format??"template_literal",pattern:r._zod.pattern.source}),o;return o}}),X$=m("$ZodFunction",(r,i)=>{return N.init(r,i),r._def=i,r._zod.def=i,r.implement=($)=>{if(typeof $!=="function")throw Error("implement() must be called with a function");return function(...o){let n=r._def.input?tr(r._def.input,o):o,t=Reflect.apply($,this,n);if(r._def.output)return tr(r._def.output,t);return t}},r.implementAsync=($)=>{if(typeof $!=="function")throw Error("implementAsync() must be called with a function");return async function(...o){let n=r._def.input?await $r(r._def.input,o):o,t=await Reflect.apply($,this,n);if(r._def.output)return await $r(r._def.output,t);return t}},r._zod.parse=($,o)=>{if(typeof $.value!=="function")return $.issues.push({code:"invalid_type",expected:"function",input:$.value,inst:r}),$;if(r._def.output&&r._def.output._zod.def.type==="promise")$.value=r.implementAsync($.value);else $.value=r.implement($.value);return $},r.input=(...$)=>{let o=r.constructor;if(Array.isArray($[0]))return new o({type:"function",input:new Jn({type:"tuple",items:$[0],rest:$[1]}),output:r._def.output});return new o({type:"function",input:$[0],output:r._def.output})},r.output=($)=>{return new r.constructor({type:"function",input:r._def.input,output:$})},r}),x$=m("$ZodPromise",(r,i)=>{N.init(r,i),r._zod.parse=($,o)=>{return Promise.resolve($.value).then((n)=>i.innerType._zod.run({value:n,issues:[]},o))}}),G$=m("$ZodLazy",(r,i)=>{N.init(r,i),J(r._zod,"innerType",()=>{let $=i;if(!$._cachedInner)$._cachedInner=i.getter();return $._cachedInner}),J(r._zod,"pattern",()=>r._zod.innerType?._zod?.pattern),J(r._zod,"propValues",()=>r._zod.innerType?._zod?.propValues),J(r._zod,"optin",()=>r._zod.innerType?._zod?.optin??void 0),J(r._zod,"optout",()=>r._zod.innerType?._zod?.optout??void 0),r._zod.parse=($,o)=>{return r._zod.innerType._zod.run($,o)}}),Y$=m("$ZodCustom",(r,i)=>{x.init(r,i),N.init(r,i),r._zod.parse=($,o)=>{return $},r._zod.check=($)=>{let o=$.value,n=i.fn(o);if(n instanceof Promise)return n.then((t)=>_c(t,$,o,r));_c(n,$,o,r);return}});function _c(r,i,$,o){if(!r){let n={code:"custom",input:$,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;i.issues.push(Or(n))}}var Cr={};mr(Cr,{zhTW:()=>Jo,zhCN:()=>zo,yo:()=>Fo,vi:()=>jo,uz:()=>No,ur:()=>Oo,uk:()=>Hr,ua:()=>Po,tr:()=>So,th:()=>Do,ta:()=>wo,sv:()=>_o,sl:()=>bo,ru:()=>ko,ro:()=>Io,pt:()=>Uo,ps:()=>lo,pl:()=>mo,ota:()=>go,no:()=>co,nl:()=>uo,ms:()=>vo,mk:()=>oo,lt:()=>$o,ko:()=>to,km:()=>Zr,kh:()=>io,ka:()=>no,ja:()=>ro,it:()=>s$,is:()=>p$,id:()=>d$,hy:()=>y$,hu:()=>a$,hr:()=>h$,he:()=>C$,frCA:()=>H$,fr:()=>M$,fi:()=>Z$,fa:()=>f$,es:()=>R$,eo:()=>B$,en:()=>A$,el:()=>e$,de:()=>T$,da:()=>V$,cs:()=>E$,ca:()=>L$,bg:()=>K$,be:()=>W$,az:()=>q$,ar:()=>Q$});var pl=()=>{let r={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function i(n){return r[n]??null}let $={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${n.expected}، ولكن تم إدخال ${u}`;return`مدخلات غير مقبولة: يفترض إدخال ${t}، ولكن تم إدخال ${u}`}case"invalid_value":if(n.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${w(n.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return` أكبر من اللازم: يفترض أن تكون ${n.origin??"القيمة"} ${t} ${n.maximum.toString()} ${v.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${n.origin??"القيمة"} ${t} ${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`أصغر من اللازم: يفترض لـ ${n.origin} أن يكون ${t} ${n.minimum.toString()} ${v.unit}`;return`أصغر من اللازم: يفترض لـ ${n.origin} أن يكون ${t} ${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${n.prefix}"`;if(t.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${t.suffix}"`;if(t.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${t.includes}"`;if(t.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${t.pattern}`;return`${$[t.format]??n.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${n.divisor}`;case"unrecognized_keys":return`معرف${n.keys.length>1?"ات":""} غريب${n.keys.length>1?"ة":""}: ${U(n.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${n.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${n.origin}`;default:return"مدخل غير مقبول"}}};function Q$(){return{localeError:pl()}}var sl=()=>{let r={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function i(n){return r[n]??null}let $={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Yanlış dəyər: gözlənilən instanceof ${n.expected}, daxil olan ${u}`;return`Yanlış dəyər: gözlənilən ${t}, daxil olan ${u}`}case"invalid_value":if(n.values.length===1)return`Yanlış dəyər: gözlənilən ${w(n.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Çox böyük: gözlənilən ${n.origin??"dəyər"} ${t}${n.maximum.toString()} ${v.unit??"element"}`;return`Çox böyük: gözlənilən ${n.origin??"dəyər"} ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Çox kiçik: gözlənilən ${n.origin} ${t}${n.minimum.toString()} ${v.unit}`;return`Çox kiçik: gözlənilən ${n.origin} ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Yanlış mətn: "${t.prefix}" ilə başlamalıdır`;if(t.format==="ends_with")return`Yanlış mətn: "${t.suffix}" ilə bitməlidir`;if(t.format==="includes")return`Yanlış mətn: "${t.includes}" daxil olmalıdır`;if(t.format==="regex")return`Yanlış mətn: ${t.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${$[t.format]??n.format}`}case"not_multiple_of":return`Yanlış ədəd: ${n.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${n.keys.length>1?"lar":""}: ${U(n.keys,", ")}`;case"invalid_key":return`${n.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${n.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function q$(){return{localeError:sl()}}function Oc(r,i,$,o){let n=Math.abs(r),t=n%10,v=n%100;if(v>=11&&v<=19)return o;if(t===1)return i;if(t>=2&&t<=4)return $;return o}var rm=()=>{let r={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function i(n){return r[n]??null}let $={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},o={nan:"NaN",number:"лік",array:"масіў"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Няправільны ўвод: чакаўся instanceof ${n.expected}, атрымана ${u}`;return`Няправільны ўвод: чакаўся ${t}, атрымана ${u}`}case"invalid_value":if(n.values.length===1)return`Няправільны ўвод: чакалася ${w(n.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v){let u=Number(n.maximum),g=Oc(u,v.unit.one,v.unit.few,v.unit.many);return`Занадта вялікі: чакалася, што ${n.origin??"значэнне"} павінна ${v.verb} ${t}${n.maximum.toString()} ${g}`}return`Занадта вялікі: чакалася, што ${n.origin??"значэнне"} павінна быць ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v){let u=Number(n.minimum),g=Oc(u,v.unit.one,v.unit.few,v.unit.many);return`Занадта малы: чакалася, што ${n.origin} павінна ${v.verb} ${t}${n.minimum.toString()} ${g}`}return`Занадта малы: чакалася, што ${n.origin} павінна быць ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${t.prefix}"`;if(t.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${t.suffix}"`;if(t.format==="includes")return`Няправільны радок: павінен змяшчаць "${t.includes}"`;if(t.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${t.pattern}`;return`Няправільны ${$[t.format]??n.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${n.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${n.keys.length>1?"ключы":"ключ"}: ${U(n.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${n.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${n.origin}`;default:return"Няправільны ўвод"}}};function W$(){return{localeError:rm()}}var nm=()=>{let r={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function i(n){return r[n]??null}let $={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},o={nan:"NaN",number:"число",array:"масив"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Невалиден вход: очакван instanceof ${n.expected}, получен ${u}`;return`Невалиден вход: очакван ${t}, получен ${u}`}case"invalid_value":if(n.values.length===1)return`Невалиден вход: очакван ${w(n.values[0])}`;return`Невалидна опция: очаквано едно от ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Твърде голямо: очаква се ${n.origin??"стойност"} да съдържа ${t}${n.maximum.toString()} ${v.unit??"елемента"}`;return`Твърде голямо: очаква се ${n.origin??"стойност"} да бъде ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Твърде малко: очаква се ${n.origin} да съдържа ${t}${n.minimum.toString()} ${v.unit}`;return`Твърде малко: очаква се ${n.origin} да бъде ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Невалиден низ: трябва да започва с "${t.prefix}"`;if(t.format==="ends_with")return`Невалиден низ: трябва да завършва с "${t.suffix}"`;if(t.format==="includes")return`Невалиден низ: трябва да включва "${t.includes}"`;if(t.format==="regex")return`Невалиден низ: трябва да съвпада с ${t.pattern}`;let v="Невалиден";if(t.format==="emoji")v="Невалидно";if(t.format==="datetime")v="Невалидно";if(t.format==="date")v="Невалидна";if(t.format==="time")v="Невалидно";if(t.format==="duration")v="Невалидна";return`${v} ${$[t.format]??n.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${n.divisor}`;case"unrecognized_keys":return`Неразпознат${n.keys.length>1?"и":""} ключ${n.keys.length>1?"ове":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${n.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${n.origin}`;default:return"Невалиден вход"}}};function K$(){return{localeError:nm()}}var im=()=>{let r={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function i(n){return r[n]??null}let $={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Tipus invàlid: s'esperava instanceof ${n.expected}, s'ha rebut ${u}`;return`Tipus invàlid: s'esperava ${t}, s'ha rebut ${u}`}case"invalid_value":if(n.values.length===1)return`Valor invàlid: s'esperava ${w(n.values[0])}`;return`Opció invàlida: s'esperava una de ${U(n.values," o ")}`;case"too_big":{let t=n.inclusive?"com a màxim":"menys de",v=i(n.origin);if(v)return`Massa gran: s'esperava que ${n.origin??"el valor"} contingués ${t} ${n.maximum.toString()} ${v.unit??"elements"}`;return`Massa gran: s'esperava que ${n.origin??"el valor"} fos ${t} ${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?"com a mínim":"més de",v=i(n.origin);if(v)return`Massa petit: s'esperava que ${n.origin} contingués ${t} ${n.minimum.toString()} ${v.unit}`;return`Massa petit: s'esperava que ${n.origin} fos ${t} ${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Format invàlid: ha de començar amb "${t.prefix}"`;if(t.format==="ends_with")return`Format invàlid: ha d'acabar amb "${t.suffix}"`;if(t.format==="includes")return`Format invàlid: ha d'incloure "${t.includes}"`;if(t.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${t.pattern}`;return`Format invàlid per a ${$[t.format]??n.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${n.divisor}`;case"unrecognized_keys":return`Clau${n.keys.length>1?"s":""} no reconeguda${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${n.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${n.origin}`;default:return"Entrada invàlida"}}};function L$(){return{localeError:im()}}var tm=()=>{let r={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function i(n){return r[n]??null}let $={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},o={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Neplatný vstup: očekáváno instanceof ${n.expected}, obdrženo ${u}`;return`Neplatný vstup: očekáváno ${t}, obdrženo ${u}`}case"invalid_value":if(n.values.length===1)return`Neplatný vstup: očekáváno ${w(n.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Hodnota je příliš velká: ${n.origin??"hodnota"} musí mít ${t}${n.maximum.toString()} ${v.unit??"prvků"}`;return`Hodnota je příliš velká: ${n.origin??"hodnota"} musí být ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Hodnota je příliš malá: ${n.origin??"hodnota"} musí mít ${t}${n.minimum.toString()} ${v.unit??"prvků"}`;return`Hodnota je příliš malá: ${n.origin??"hodnota"} musí být ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Neplatný řetězec: musí začínat na "${t.prefix}"`;if(t.format==="ends_with")return`Neplatný řetězec: musí končit na "${t.suffix}"`;if(t.format==="includes")return`Neplatný řetězec: musí obsahovat "${t.includes}"`;if(t.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${t.pattern}`;return`Neplatný formát ${$[t.format]??n.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${n.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${U(n.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${n.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${n.origin}`;default:return"Neplatný vstup"}}};function E$(){return{localeError:tm()}}var $m=()=>{let r={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function i(n){return r[n]??null}let $={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},o={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Ugyldigt input: forventede instanceof ${n.expected}, fik ${u}`;return`Ugyldigt input: forventede ${t}, fik ${u}`}case"invalid_value":if(n.values.length===1)return`Ugyldig værdi: forventede ${w(n.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin),u=o[n.origin]??n.origin;if(v)return`For stor: forventede ${u??"value"} ${v.verb} ${t} ${n.maximum.toString()} ${v.unit??"elementer"}`;return`For stor: forventede ${u??"value"} havde ${t} ${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin),u=o[n.origin]??n.origin;if(v)return`For lille: forventede ${u} ${v.verb} ${t} ${n.minimum.toString()} ${v.unit}`;return`For lille: forventede ${u} havde ${t} ${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Ugyldig streng: skal starte med "${t.prefix}"`;if(t.format==="ends_with")return`Ugyldig streng: skal ende med "${t.suffix}"`;if(t.format==="includes")return`Ugyldig streng: skal indeholde "${t.includes}"`;if(t.format==="regex")return`Ugyldig streng: skal matche mønsteret ${t.pattern}`;return`Ugyldig ${$[t.format]??n.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${U(n.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${n.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${n.origin}`;default:return"Ugyldigt input"}}};function V$(){return{localeError:$m()}}var om=()=>{let r={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function i(n){return r[n]??null}let $={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},o={nan:"NaN",number:"Zahl",array:"Array"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Ungültige Eingabe: erwartet instanceof ${n.expected}, erhalten ${u}`;return`Ungültige Eingabe: erwartet ${t}, erhalten ${u}`}case"invalid_value":if(n.values.length===1)return`Ungültige Eingabe: erwartet ${w(n.values[0])}`;return`Ungültige Option: erwartet eine von ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Zu groß: erwartet, dass ${n.origin??"Wert"} ${t}${n.maximum.toString()} ${v.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${n.origin??"Wert"} ${t}${n.maximum.toString()} ist`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Zu klein: erwartet, dass ${n.origin} ${t}${n.minimum.toString()} ${v.unit} hat`;return`Zu klein: erwartet, dass ${n.origin} ${t}${n.minimum.toString()} ist`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Ungültiger String: muss mit "${t.prefix}" beginnen`;if(t.format==="ends_with")return`Ungültiger String: muss mit "${t.suffix}" enden`;if(t.format==="includes")return`Ungültiger String: muss "${t.includes}" enthalten`;if(t.format==="regex")return`Ungültiger String: muss dem Muster ${t.pattern} entsprechen`;return`Ungültig: ${$[t.format]??n.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${n.divisor} sein`;case"unrecognized_keys":return`${n.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${U(n.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${n.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${n.origin}`;default:return"Ungültige Eingabe"}}};function T$(){return{localeError:om()}}var vm=()=>{let r={string:{unit:"χαρακτήρες",verb:"να έχει"},file:{unit:"bytes",verb:"να έχει"},array:{unit:"στοιχεία",verb:"να έχει"},set:{unit:"στοιχεία",verb:"να έχει"},map:{unit:"καταχωρήσεις",verb:"να έχει"}};function i(n){return r[n]??null}let $={regex:"είσοδος",email:"διεύθυνση email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ημερομηνία και ώρα",date:"ISO ημερομηνία",time:"ISO ώρα",duration:"ISO διάρκεια",ipv4:"διεύθυνση IPv4",ipv6:"διεύθυνση IPv6",mac:"διεύθυνση MAC",cidrv4:"εύρος IPv4",cidrv6:"εύρος IPv6",base64:"συμβολοσειρά κωδικοποιημένη σε base64",base64url:"συμβολοσειρά κωδικοποιημένη σε base64url",json_string:"συμβολοσειρά JSON",e164:"αριθμός E.164",jwt:"JWT",template_literal:"είσοδος"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(typeof n.expected==="string"&&/^[A-Z]/.test(n.expected))return`Μη έγκυρη είσοδος: αναμενόταν instanceof ${n.expected}, λήφθηκε ${u}`;return`Μη έγκυρη είσοδος: αναμενόταν ${t}, λήφθηκε ${u}`}case"invalid_value":if(n.values.length===1)return`Μη έγκυρη είσοδος: αναμενόταν ${w(n.values[0])}`;return`Μη έγκυρη επιλογή: αναμενόταν ένα από ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Πολύ μεγάλο: αναμενόταν ${n.origin??"τιμή"} να έχει ${t}${n.maximum.toString()} ${v.unit??"στοιχεία"}`;return`Πολύ μεγάλο: αναμενόταν ${n.origin??"τιμή"} να είναι ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Πολύ μικρό: αναμενόταν ${n.origin} να έχει ${t}${n.minimum.toString()} ${v.unit}`;return`Πολύ μικρό: αναμενόταν ${n.origin} να είναι ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${t.prefix}"`;if(t.format==="ends_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${t.suffix}"`;if(t.format==="includes")return`Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${t.includes}"`;if(t.format==="regex")return`Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${t.pattern}`;return`Μη έγκυρο: ${$[t.format]??n.format}`}case"not_multiple_of":return`Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${n.divisor}`;case"unrecognized_keys":return`Άγνωστ${n.keys.length>1?"α":"ο"} κλειδ${n.keys.length>1?"ιά":"ί"}: ${U(n.keys,", ")}`;case"invalid_key":return`Μη έγκυρο κλειδί στο ${n.origin}`;case"invalid_union":return"Μη έγκυρη είσοδος";case"invalid_element":return`Μη έγκυρη τιμή στο ${n.origin}`;default:return"Μη έγκυρη είσοδος"}}};function e$(){return{localeError:vm()}}var um=()=>{let r={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function i(n){return r[n]??null}let $={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;return`Invalid input: expected ${t}, received ${u}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${w(n.values[0])}`;return`Invalid option: expected one of ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Too big: expected ${n.origin??"value"} to have ${t}${n.maximum.toString()} ${v.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Too small: expected ${n.origin} to have ${t}${n.minimum.toString()} ${v.unit}`;return`Too small: expected ${n.origin} to be ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Invalid string: must start with "${t.prefix}"`;if(t.format==="ends_with")return`Invalid string: must end with "${t.suffix}"`;if(t.format==="includes")return`Invalid string: must include "${t.includes}"`;if(t.format==="regex")return`Invalid string: must match pattern ${t.pattern}`;return`Invalid ${$[t.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((v)=>`'${v}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function A$(){return{localeError:um()}}var cm=()=>{let r={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function i(n){return r[n]??null}let $={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},o={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Nevalida enigo: atendiĝis instanceof ${n.expected}, riceviĝis ${u}`;return`Nevalida enigo: atendiĝis ${t}, riceviĝis ${u}`}case"invalid_value":if(n.values.length===1)return`Nevalida enigo: atendiĝis ${w(n.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Tro granda: atendiĝis ke ${n.origin??"valoro"} havu ${t}${n.maximum.toString()} ${v.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${n.origin??"valoro"} havu ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Tro malgranda: atendiĝis ke ${n.origin} havu ${t}${n.minimum.toString()} ${v.unit}`;return`Tro malgranda: atendiĝis ke ${n.origin} estu ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${t.prefix}"`;if(t.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${t.suffix}"`;if(t.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${t.includes}"`;if(t.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${t.pattern}`;return`Nevalida ${$[t.format]??n.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${n.divisor}`;case"unrecognized_keys":return`Nekonata${n.keys.length>1?"j":""} ŝlosilo${n.keys.length>1?"j":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${n.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${n.origin}`;default:return"Nevalida enigo"}}};function B$(){return{localeError:cm()}}var gm=()=>{let r={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function i(n){return r[n]??null}let $={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Entrada inválida: se esperaba instanceof ${n.expected}, recibido ${u}`;return`Entrada inválida: se esperaba ${t}, recibido ${u}`}case"invalid_value":if(n.values.length===1)return`Entrada inválida: se esperaba ${w(n.values[0])}`;return`Opción inválida: se esperaba una de ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin),u=o[n.origin]??n.origin;if(v)return`Demasiado grande: se esperaba que ${u??"valor"} tuviera ${t}${n.maximum.toString()} ${v.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${u??"valor"} fuera ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin),u=o[n.origin]??n.origin;if(v)return`Demasiado pequeño: se esperaba que ${u} tuviera ${t}${n.minimum.toString()} ${v.unit}`;return`Demasiado pequeño: se esperaba que ${u} fuera ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Cadena inválida: debe comenzar con "${t.prefix}"`;if(t.format==="ends_with")return`Cadena inválida: debe terminar en "${t.suffix}"`;if(t.format==="includes")return`Cadena inválida: debe incluir "${t.includes}"`;if(t.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${t.pattern}`;return`Inválido ${$[t.format]??n.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${n.divisor}`;case"unrecognized_keys":return`Llave${n.keys.length>1?"s":""} desconocida${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Llave inválida en ${o[n.origin]??n.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${o[n.origin]??n.origin}`;default:return"Entrada inválida"}}};function R$(){return{localeError:gm()}}var lm=()=>{let r={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function i(n){return r[n]??null}let $={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},o={nan:"NaN",number:"عدد",array:"آرایه"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`ورودی نامعتبر: میبایست instanceof ${n.expected} میبود، ${u} دریافت شد`;return`ورودی نامعتبر: میبایست ${t} میبود، ${u} دریافت شد`}case"invalid_value":if(n.values.length===1)return`ورودی نامعتبر: میبایست ${w(n.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${U(n.values,"|")} میبود`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`خیلی بزرگ: ${n.origin??"مقدار"} باید ${t}${n.maximum.toString()} ${v.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${n.origin??"مقدار"} باید ${t}${n.maximum.toString()} باشد`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`خیلی کوچک: ${n.origin} باید ${t}${n.minimum.toString()} ${v.unit} باشد`;return`خیلی کوچک: ${n.origin} باید ${t}${n.minimum.toString()} باشد`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`رشته نامعتبر: باید با "${t.prefix}" شروع شود`;if(t.format==="ends_with")return`رشته نامعتبر: باید با "${t.suffix}" تمام شود`;if(t.format==="includes")return`رشته نامعتبر: باید شامل "${t.includes}" باشد`;if(t.format==="regex")return`رشته نامعتبر: باید با الگوی ${t.pattern} مطابقت داشته باشد`;return`${$[t.format]??n.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${n.divisor} باشد`;case"unrecognized_keys":return`کلید${n.keys.length>1?"های":""} ناشناس: ${U(n.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${n.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${n.origin}`;default:return"ورودی نامعتبر"}}};function f$(){return{localeError:lm()}}var mm=()=>{let r={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function i(n){return r[n]??null}let $={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Virheellinen tyyppi: odotettiin instanceof ${n.expected}, oli ${u}`;return`Virheellinen tyyppi: odotettiin ${t}, oli ${u}`}case"invalid_value":if(n.values.length===1)return`Virheellinen syöte: täytyy olla ${w(n.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Liian suuri: ${v.subject} täytyy olla ${t}${n.maximum.toString()} ${v.unit}`.trim();return`Liian suuri: arvon täytyy olla ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Liian pieni: ${v.subject} täytyy olla ${t}${n.minimum.toString()} ${v.unit}`.trim();return`Liian pieni: arvon täytyy olla ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${t.prefix}"`;if(t.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${t.suffix}"`;if(t.format==="includes")return`Virheellinen syöte: täytyy sisältää "${t.includes}"`;if(t.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${t.pattern}`;return`Virheellinen ${$[t.format]??n.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${n.divisor} monikerta`;case"unrecognized_keys":return`${n.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${U(n.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function Z$(){return{localeError:mm()}}var Um=()=>{let r={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function i(n){return r[n]??null}let $={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},o={string:"chaîne",number:"nombre",int:"entier",boolean:"booléen",bigint:"grand entier",symbol:"symbole",undefined:"indéfini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Entrée invalide : instanceof ${n.expected} attendu, ${u} reçu`;return`Entrée invalide : ${t} attendu, ${u} reçu`}case"invalid_value":if(n.values.length===1)return`Entrée invalide : ${w(n.values[0])} attendu`;return`Option invalide : une valeur parmi ${U(n.values,"|")} attendue`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Trop grand : ${o[n.origin]??"valeur"} doit ${v.verb} ${t}${n.maximum.toString()} ${v.unit??"élément(s)"}`;return`Trop grand : ${o[n.origin]??"valeur"} doit être ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Trop petit : ${o[n.origin]??"valeur"} doit ${v.verb} ${t}${n.minimum.toString()} ${v.unit}`;return`Trop petit : ${o[n.origin]??"valeur"} doit être ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Chaîne invalide : doit commencer par "${t.prefix}"`;if(t.format==="ends_with")return`Chaîne invalide : doit se terminer par "${t.suffix}"`;if(t.format==="includes")return`Chaîne invalide : doit inclure "${t.includes}"`;if(t.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${t.pattern}`;return`${$[t.format]??n.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${n.divisor}`;case"unrecognized_keys":return`Clé${n.keys.length>1?"s":""} non reconnue${n.keys.length>1?"s":""} : ${U(n.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${n.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${n.origin}`;default:return"Entrée invalide"}}};function M$(){return{localeError:Um()}}var Im=()=>{let r={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function i(n){return r[n]??null}let $={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Entrée invalide : attendu instanceof ${n.expected}, reçu ${u}`;return`Entrée invalide : attendu ${t}, reçu ${u}`}case"invalid_value":if(n.values.length===1)return`Entrée invalide : attendu ${w(n.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"≤":"<",v=i(n.origin);if(v)return`Trop grand : attendu que ${n.origin??"la valeur"} ait ${t}${n.maximum.toString()} ${v.unit}`;return`Trop grand : attendu que ${n.origin??"la valeur"} soit ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?"≥":">",v=i(n.origin);if(v)return`Trop petit : attendu que ${n.origin} ait ${t}${n.minimum.toString()} ${v.unit}`;return`Trop petit : attendu que ${n.origin} soit ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Chaîne invalide : doit commencer par "${t.prefix}"`;if(t.format==="ends_with")return`Chaîne invalide : doit se terminer par "${t.suffix}"`;if(t.format==="includes")return`Chaîne invalide : doit inclure "${t.includes}"`;if(t.format==="regex")return`Chaîne invalide : doit correspondre au motif ${t.pattern}`;return`${$[t.format]??n.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${n.divisor}`;case"unrecognized_keys":return`Clé${n.keys.length>1?"s":""} non reconnue${n.keys.length>1?"s":""} : ${U(n.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${n.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${n.origin}`;default:return"Entrée invalide"}}};function H$(){return{localeError:Im()}}var km=()=>{let r={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},i={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},$=(c)=>c?r[c]:void 0,o=(c)=>{let l=$(c);if(l)return l.label;return c??r.unknown.label},n=(c)=>`ה${o(c)}`,t=(c)=>{return($(c)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},v=(c)=>{if(!c)return null;return i[c]??null},u={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},g={nan:"NaN"};return(c)=>{switch(c.code){case"invalid_type":{let l=c.expected,I=g[l??""]??o(l),_=S(c.input),k=g[_]??r[_]?.label??_;if(/^[A-Z]/.test(c.expected))return`קלט לא תקין: צריך להיות instanceof ${c.expected}, התקבל ${k}`;return`קלט לא תקין: צריך להיות ${I}, התקבל ${k}`}case"invalid_value":{if(c.values.length===1)return`ערך לא תקין: הערך חייב להיות ${w(c.values[0])}`;let l=c.values.map((k)=>w(k));if(c.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${l[0]} או ${l[1]}`;let I=l[l.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${l.slice(0,-1).join(", ")} או ${I}`}case"too_big":{let l=v(c.origin),I=n(c.origin??"value");if(c.origin==="string")return`${l?.longLabel??"ארוך"} מדי: ${I} צריכה להכיל ${c.maximum.toString()} ${l?.unit??""} ${c.inclusive?"או פחות":"לכל היותר"}`.trim();if(c.origin==="number"){let P=c.inclusive?`קטן או שווה ל-${c.maximum}`:`קטן מ-${c.maximum}`;return`גדול מדי: ${I} צריך להיות ${P}`}if(c.origin==="array"||c.origin==="set"){let P=c.origin==="set"?"צריכה":"צריך",q=c.inclusive?`${c.maximum} ${l?.unit??""} או פחות`:`פחות מ-${c.maximum} ${l?.unit??""}`;return`גדול מדי: ${I} ${P} להכיל ${q}`.trim()}let _=c.inclusive?"<=":"<",k=t(c.origin??"value");if(l?.unit)return`${l.longLabel} מדי: ${I} ${k} ${_}${c.maximum.toString()} ${l.unit}`;return`${l?.longLabel??"גדול"} מדי: ${I} ${k} ${_}${c.maximum.toString()}`}case"too_small":{let l=v(c.origin),I=n(c.origin??"value");if(c.origin==="string")return`${l?.shortLabel??"קצר"} מדי: ${I} צריכה להכיל ${c.minimum.toString()} ${l?.unit??""} ${c.inclusive?"או יותר":"לפחות"}`.trim();if(c.origin==="number"){let P=c.inclusive?`גדול או שווה ל-${c.minimum}`:`גדול מ-${c.minimum}`;return`קטן מדי: ${I} צריך להיות ${P}`}if(c.origin==="array"||c.origin==="set"){let P=c.origin==="set"?"צריכה":"צריך";if(c.minimum===1&&c.inclusive){let Q=c.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${I} ${P} להכיל ${Q}`}let q=c.inclusive?`${c.minimum} ${l?.unit??""} או יותר`:`יותר מ-${c.minimum} ${l?.unit??""}`;return`קטן מדי: ${I} ${P} להכיל ${q}`.trim()}let _=c.inclusive?">=":">",k=t(c.origin??"value");if(l?.unit)return`${l.shortLabel} מדי: ${I} ${k} ${_}${c.minimum.toString()} ${l.unit}`;return`${l?.shortLabel??"קטן"} מדי: ${I} ${k} ${_}${c.minimum.toString()}`}case"invalid_format":{let l=c;if(l.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${l.prefix}"`;if(l.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${l.suffix}"`;if(l.format==="includes")return`המחרוזת חייבת לכלול "${l.includes}"`;if(l.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${l.pattern}`;let I=u[l.format],_=I?.label??l.format,P=(I?.gender??"m")==="f"?"תקינה":"תקין";return`${_} לא ${P}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${c.divisor}`;case"unrecognized_keys":return`מפתח${c.keys.length>1?"ות":""} לא מזוה${c.keys.length>1?"ים":"ה"}: ${U(c.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${n(c.origin??"array")}`;default:return"קלט לא תקין"}}};function C$(){return{localeError:km()}}var bm=()=>{let r={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function i(n){return r[n]??null}let $={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},o={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Neispravan unos: očekuje se instanceof ${n.expected}, a primljeno je ${u}`;return`Neispravan unos: očekuje se ${t}, a primljeno je ${u}`}case"invalid_value":if(n.values.length===1)return`Neispravna vrijednost: očekivano ${w(n.values[0])}`;return`Neispravna opcija: očekivano jedno od ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin),u=o[n.origin]??n.origin;if(v)return`Preveliko: očekivano da ${u??"vrijednost"} ima ${t}${n.maximum.toString()} ${v.unit??"elemenata"}`;return`Preveliko: očekivano da ${u??"vrijednost"} bude ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin),u=o[n.origin]??n.origin;if(v)return`Premalo: očekivano da ${u} ima ${t}${n.minimum.toString()} ${v.unit}`;return`Premalo: očekivano da ${u} bude ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Neispravan tekst: mora započinjati s "${t.prefix}"`;if(t.format==="ends_with")return`Neispravan tekst: mora završavati s "${t.suffix}"`;if(t.format==="includes")return`Neispravan tekst: mora sadržavati "${t.includes}"`;if(t.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${t.pattern}`;return`Neispravna ${$[t.format]??n.format}`}case"not_multiple_of":return`Neispravan broj: mora biti višekratnik od ${n.divisor}`;case"unrecognized_keys":return`Neprepoznat${n.keys.length>1?"i ključevi":" ključ"}: ${U(n.keys,", ")}`;case"invalid_key":return`Neispravan ključ u ${o[n.origin]??n.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${o[n.origin]??n.origin}`;default:return"Neispravan unos"}}};function h$(){return{localeError:bm()}}var _m=()=>{let r={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function i(n){return r[n]??null}let $={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},o={nan:"NaN",number:"szám",array:"tömb"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Érvénytelen bemenet: a várt érték instanceof ${n.expected}, a kapott érték ${u}`;return`Érvénytelen bemenet: a várt érték ${t}, a kapott érték ${u}`}case"invalid_value":if(n.values.length===1)return`Érvénytelen bemenet: a várt érték ${w(n.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Túl nagy: ${n.origin??"érték"} mérete túl nagy ${t}${n.maximum.toString()} ${v.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${n.origin??"érték"} túl nagy: ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Túl kicsi: a bemeneti érték ${n.origin} mérete túl kicsi ${t}${n.minimum.toString()} ${v.unit}`;return`Túl kicsi: a bemeneti érték ${n.origin} túl kicsi ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Érvénytelen string: "${t.prefix}" értékkel kell kezdődnie`;if(t.format==="ends_with")return`Érvénytelen string: "${t.suffix}" értékkel kell végződnie`;if(t.format==="includes")return`Érvénytelen string: "${t.includes}" értéket kell tartalmaznia`;if(t.format==="regex")return`Érvénytelen string: ${t.pattern} mintának kell megfelelnie`;return`Érvénytelen ${$[t.format]??n.format}`}case"not_multiple_of":return`Érvénytelen szám: ${n.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${n.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${n.origin}`;default:return"Érvénytelen bemenet"}}};function a$(){return{localeError:_m()}}function Nc(r,i,$){return Math.abs(r)===1?i:$}function zr(r){if(!r)return"";let i=["ա","ե","ը","ի","ո","ու","օ"],$=r[r.length-1];return r+(i.includes($)?"ն":"ը")}var wm=()=>{let r={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function i(n){return r[n]??null}let $={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},o={nan:"NaN",number:"թիվ",array:"զանգված"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${n.expected}, ստացվել է ${u}`;return`Սխալ մուտքագրում․ սպասվում էր ${t}, ստացվել է ${u}`}case"invalid_value":if(n.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${w(n.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v){let u=Number(n.maximum),g=Nc(u,v.unit.one,v.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${zr(n.origin??"արժեք")} կունենա ${t}${n.maximum.toString()} ${g}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${zr(n.origin??"արժեք")} լինի ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v){let u=Number(n.minimum),g=Nc(u,v.unit.one,v.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${zr(n.origin)} կունենա ${t}${n.minimum.toString()} ${g}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${zr(n.origin)} լինի ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${t.prefix}"-ով`;if(t.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${t.suffix}"-ով`;if(t.format==="includes")return`Սխալ տող․ պետք է պարունակի "${t.includes}"`;if(t.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${t.pattern} ձևաչափին`;return`Սխալ ${$[t.format]??n.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${n.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${n.keys.length>1?"ներ":""}. ${U(n.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${zr(n.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${zr(n.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function y$(){return{localeError:wm()}}var Dm=()=>{let r={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function i(n){return r[n]??null}let $={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Input tidak valid: diharapkan instanceof ${n.expected}, diterima ${u}`;return`Input tidak valid: diharapkan ${t}, diterima ${u}`}case"invalid_value":if(n.values.length===1)return`Input tidak valid: diharapkan ${w(n.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Terlalu besar: diharapkan ${n.origin??"value"} memiliki ${t}${n.maximum.toString()} ${v.unit??"elemen"}`;return`Terlalu besar: diharapkan ${n.origin??"value"} menjadi ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Terlalu kecil: diharapkan ${n.origin} memiliki ${t}${n.minimum.toString()} ${v.unit}`;return`Terlalu kecil: diharapkan ${n.origin} menjadi ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`String tidak valid: harus dimulai dengan "${t.prefix}"`;if(t.format==="ends_with")return`String tidak valid: harus berakhir dengan "${t.suffix}"`;if(t.format==="includes")return`String tidak valid: harus menyertakan "${t.includes}"`;if(t.format==="regex")return`String tidak valid: harus sesuai pola ${t.pattern}`;return`${$[t.format]??n.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${n.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${n.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${n.origin}`;default:return"Input tidak valid"}}};function d$(){return{localeError:Dm()}}var Sm=()=>{let r={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function i(n){return r[n]??null}let $={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},o={nan:"NaN",number:"númer",array:"fylki"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Rangt gildi: Þú slóst inn ${u} þar sem á að vera instanceof ${n.expected}`;return`Rangt gildi: Þú slóst inn ${u} þar sem á að vera ${t}`}case"invalid_value":if(n.values.length===1)return`Rangt gildi: gert ráð fyrir ${w(n.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Of stórt: gert er ráð fyrir að ${n.origin??"gildi"} hafi ${t}${n.maximum.toString()} ${v.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${n.origin??"gildi"} sé ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Of lítið: gert er ráð fyrir að ${n.origin} hafi ${t}${n.minimum.toString()} ${v.unit}`;return`Of lítið: gert er ráð fyrir að ${n.origin} sé ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Ógildur strengur: verður að byrja á "${t.prefix}"`;if(t.format==="ends_with")return`Ógildur strengur: verður að enda á "${t.suffix}"`;if(t.format==="includes")return`Ógildur strengur: verður að innihalda "${t.includes}"`;if(t.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${t.pattern}`;return`Rangt ${$[t.format]??n.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${n.divisor}`;case"unrecognized_keys":return`Óþekkt ${n.keys.length>1?"ir lyklar":"ur lykill"}: ${U(n.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${n.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${n.origin}`;default:return"Rangt gildi"}}};function p$(){return{localeError:Sm()}}var Pm=()=>{let r={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function i(n){return r[n]??null}let $={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"numero",array:"vettore"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Input non valido: atteso instanceof ${n.expected}, ricevuto ${u}`;return`Input non valido: atteso ${t}, ricevuto ${u}`}case"invalid_value":if(n.values.length===1)return`Input non valido: atteso ${w(n.values[0])}`;return`Opzione non valida: atteso uno tra ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Troppo grande: ${n.origin??"valore"} deve avere ${t}${n.maximum.toString()} ${v.unit??"elementi"}`;return`Troppo grande: ${n.origin??"valore"} deve essere ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Troppo piccolo: ${n.origin} deve avere ${t}${n.minimum.toString()} ${v.unit}`;return`Troppo piccolo: ${n.origin} deve essere ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Stringa non valida: deve iniziare con "${t.prefix}"`;if(t.format==="ends_with")return`Stringa non valida: deve terminare con "${t.suffix}"`;if(t.format==="includes")return`Stringa non valida: deve includere "${t.includes}"`;if(t.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${t.pattern}`;return`Input non valido: ${$[t.format]??n.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${n.divisor}`;case"unrecognized_keys":return`Chiav${n.keys.length>1?"i":"e"} non riconosciut${n.keys.length>1?"e":"a"}: ${U(n.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${n.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${n.origin}`;default:return"Input non valido"}}};function s$(){return{localeError:Pm()}}var Om=()=>{let r={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function i(n){return r[n]??null}let $={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},o={nan:"NaN",number:"数値",array:"配列"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`無効な入力: instanceof ${n.expected}が期待されましたが、${u}が入力されました`;return`無効な入力: ${t}が期待されましたが、${u}が入力されました`}case"invalid_value":if(n.values.length===1)return`無効な入力: ${w(n.values[0])}が期待されました`;return`無効な選択: ${U(n.values,"、")}のいずれかである必要があります`;case"too_big":{let t=n.inclusive?"以下である":"より小さい",v=i(n.origin);if(v)return`大きすぎる値: ${n.origin??"値"}は${n.maximum.toString()}${v.unit??"要素"}${t}必要があります`;return`大きすぎる値: ${n.origin??"値"}は${n.maximum.toString()}${t}必要があります`}case"too_small":{let t=n.inclusive?"以上である":"より大きい",v=i(n.origin);if(v)return`小さすぎる値: ${n.origin}は${n.minimum.toString()}${v.unit}${t}必要があります`;return`小さすぎる値: ${n.origin}は${n.minimum.toString()}${t}必要があります`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`無効な文字列: "${t.prefix}"で始まる必要があります`;if(t.format==="ends_with")return`無効な文字列: "${t.suffix}"で終わる必要があります`;if(t.format==="includes")return`無効な文字列: "${t.includes}"を含む必要があります`;if(t.format==="regex")return`無効な文字列: パターン${t.pattern}に一致する必要があります`;return`無効な${$[t.format]??n.format}`}case"not_multiple_of":return`無効な数値: ${n.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${n.keys.length>1?"群":""}: ${U(n.keys,"、")}`;case"invalid_key":return`${n.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${n.origin}内の無効な値`;default:return"無効な入力"}}};function ro(){return{localeError:Om()}}var Nm=()=>{let r={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function i(n){return r[n]??null}let $={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული ველი",base64url:"base64url-კოდირებული ველი",json_string:"JSON ველი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},o={nan:"NaN",number:"რიცხვი",string:"ველი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${n.expected}, მიღებული ${u}`;return`არასწორი შეყვანა: მოსალოდნელი ${t}, მიღებული ${u}`}case"invalid_value":if(n.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${w(n.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${U(n.values,"|")}-დან`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`ზედმეტად დიდი: მოსალოდნელი ${n.origin??"მნიშვნელობა"} ${v.verb} ${t}${n.maximum.toString()} ${v.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${n.origin??"მნიშვნელობა"} იყოს ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`ზედმეტად პატარა: მოსალოდნელი ${n.origin} ${v.verb} ${t}${n.minimum.toString()} ${v.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${n.origin} იყოს ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`არასწორი ველი: უნდა იწყებოდეს "${t.prefix}"-ით`;if(t.format==="ends_with")return`არასწორი ველი: უნდა მთავრდებოდეს "${t.suffix}"-ით`;if(t.format==="includes")return`არასწორი ველი: უნდა შეიცავდეს "${t.includes}"-ს`;if(t.format==="regex")return`არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${t.pattern}`;return`არასწორი ${$[t.format]??n.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${n.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${n.keys.length>1?"ები":"ი"}: ${U(n.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${n.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${n.origin}-ში`;default:return"არასწორი შეყვანა"}}};function no(){return{localeError:Nm()}}var jm=()=>{let r={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function i(n){return r[n]??null}let $={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},o={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${n.expected} ប៉ុន្តែទទួលបាន ${u}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${t} ប៉ុន្តែទទួលបាន ${u}`}case"invalid_value":if(n.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${w(n.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`ធំពេក៖ ត្រូវការ ${n.origin??"តម្លៃ"} ${t} ${n.maximum.toString()} ${v.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${n.origin??"តម្លៃ"} ${t} ${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`តូចពេក៖ ត្រូវការ ${n.origin} ${t} ${n.minimum.toString()} ${v.unit}`;return`តូចពេក៖ ត្រូវការ ${n.origin} ${t} ${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${t.prefix}"`;if(t.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${t.suffix}"`;if(t.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${t.includes}"`;if(t.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${t.pattern}`;return`មិនត្រឹមត្រូវ៖ ${$[t.format]??n.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${n.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${U(n.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${n.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${n.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function Zr(){return{localeError:jm()}}function io(){return Zr()}var zm=()=>{let r={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function i(n){return r[n]??null}let $={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`잘못된 입력: 예상 타입은 instanceof ${n.expected}, 받은 타입은 ${u}입니다`;return`잘못된 입력: 예상 타입은 ${t}, 받은 타입은 ${u}입니다`}case"invalid_value":if(n.values.length===1)return`잘못된 입력: 값은 ${w(n.values[0])} 이어야 합니다`;return`잘못된 옵션: ${U(n.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let t=n.inclusive?"이하":"미만",v=t==="미만"?"이어야 합니다":"여야 합니다",u=i(n.origin),g=u?.unit??"요소";if(u)return`${n.origin??"값"}이 너무 큽니다: ${n.maximum.toString()}${g} ${t}${v}`;return`${n.origin??"값"}이 너무 큽니다: ${n.maximum.toString()} ${t}${v}`}case"too_small":{let t=n.inclusive?"이상":"초과",v=t==="이상"?"이어야 합니다":"여야 합니다",u=i(n.origin),g=u?.unit??"요소";if(u)return`${n.origin??"값"}이 너무 작습니다: ${n.minimum.toString()}${g} ${t}${v}`;return`${n.origin??"값"}이 너무 작습니다: ${n.minimum.toString()} ${t}${v}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`잘못된 문자열: "${t.prefix}"(으)로 시작해야 합니다`;if(t.format==="ends_with")return`잘못된 문자열: "${t.suffix}"(으)로 끝나야 합니다`;if(t.format==="includes")return`잘못된 문자열: "${t.includes}"을(를) 포함해야 합니다`;if(t.format==="regex")return`잘못된 문자열: 정규식 ${t.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${$[t.format]??n.format}`}case"not_multiple_of":return`잘못된 숫자: ${n.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${U(n.keys,", ")}`;case"invalid_key":return`잘못된 키: ${n.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${n.origin}`;default:return"잘못된 입력"}}};function to(){return{localeError:zm()}}var Mr=(r)=>{return r.charAt(0).toUpperCase()+r.slice(1)};function jc(r){let i=Math.abs(r),$=i%10,o=i%100;if(o>=11&&o<=19||$===0)return"many";if($===1)return"one";return"few"}var Jm=()=>{let r={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function i(n,t,v,u){let g=r[n]??null;if(g===null)return g;return{unit:g.unit[t],verb:g.verb[u][v?"inclusive":"notInclusive"]}}let $={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},o={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Gautas tipas ${u}, o tikėtasi - instanceof ${n.expected}`;return`Gautas tipas ${u}, o tikėtasi - ${t}`}case"invalid_value":if(n.values.length===1)return`Privalo būti ${w(n.values[0])}`;return`Privalo būti vienas iš ${U(n.values,"|")} pasirinkimų`;case"too_big":{let t=o[n.origin]??n.origin,v=i(n.origin,jc(Number(n.maximum)),n.inclusive??!1,"smaller");if(v?.verb)return`${Mr(t??n.origin??"reikšmė")} ${v.verb} ${n.maximum.toString()} ${v.unit??"elementų"}`;let u=n.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${Mr(t??n.origin??"reikšmė")} turi būti ${u} ${n.maximum.toString()} ${v?.unit}`}case"too_small":{let t=o[n.origin]??n.origin,v=i(n.origin,jc(Number(n.minimum)),n.inclusive??!1,"bigger");if(v?.verb)return`${Mr(t??n.origin??"reikšmė")} ${v.verb} ${n.minimum.toString()} ${v.unit??"elementų"}`;let u=n.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${Mr(t??n.origin??"reikšmė")} turi būti ${u} ${n.minimum.toString()} ${v?.unit}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Eilutė privalo prasidėti "${t.prefix}"`;if(t.format==="ends_with")return`Eilutė privalo pasibaigti "${t.suffix}"`;if(t.format==="includes")return`Eilutė privalo įtraukti "${t.includes}"`;if(t.format==="regex")return`Eilutė privalo atitikti ${t.pattern}`;return`Neteisingas ${$[t.format]??n.format}`}case"not_multiple_of":return`Skaičius privalo būti ${n.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${n.keys.length>1?"i":"as"} rakt${n.keys.length>1?"ai":"as"}: ${U(n.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let t=o[n.origin]??n.origin;return`${Mr(t??n.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function $o(){return{localeError:Jm()}}var Fm=()=>{let r={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function i(n){return r[n]??null}let $={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},o={nan:"NaN",number:"број",array:"низа"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Грешен внес: се очекува instanceof ${n.expected}, примено ${u}`;return`Грешен внес: се очекува ${t}, примено ${u}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${w(n.values[0])}`;return`Грешана опција: се очекува една ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Премногу голем: се очекува ${n.origin??"вредноста"} да има ${t}${n.maximum.toString()} ${v.unit??"елементи"}`;return`Премногу голем: се очекува ${n.origin??"вредноста"} да биде ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Премногу мал: се очекува ${n.origin} да има ${t}${n.minimum.toString()} ${v.unit}`;return`Премногу мал: се очекува ${n.origin} да биде ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Неважечка низа: мора да започнува со "${t.prefix}"`;if(t.format==="ends_with")return`Неважечка низа: мора да завршува со "${t.suffix}"`;if(t.format==="includes")return`Неважечка низа: мора да вклучува "${t.includes}"`;if(t.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${t.pattern}`;return`Invalid ${$[t.format]??n.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${U(n.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${n.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${n.origin}`;default:return"Грешен внес"}}};function oo(){return{localeError:Fm()}}var Xm=()=>{let r={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function i(n){return r[n]??null}let $={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"nombor"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Input tidak sah: dijangka instanceof ${n.expected}, diterima ${u}`;return`Input tidak sah: dijangka ${t}, diterima ${u}`}case"invalid_value":if(n.values.length===1)return`Input tidak sah: dijangka ${w(n.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Terlalu besar: dijangka ${n.origin??"nilai"} ${v.verb} ${t}${n.maximum.toString()} ${v.unit??"elemen"}`;return`Terlalu besar: dijangka ${n.origin??"nilai"} adalah ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Terlalu kecil: dijangka ${n.origin} ${v.verb} ${t}${n.minimum.toString()} ${v.unit}`;return`Terlalu kecil: dijangka ${n.origin} adalah ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`String tidak sah: mesti bermula dengan "${t.prefix}"`;if(t.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${t.suffix}"`;if(t.format==="includes")return`String tidak sah: mesti mengandungi "${t.includes}"`;if(t.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${t.pattern}`;return`${$[t.format]??n.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${n.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${U(n.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${n.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${n.origin}`;default:return"Input tidak sah"}}};function vo(){return{localeError:Xm()}}var xm=()=>{let r={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function i(n){return r[n]??null}let $={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},o={nan:"NaN",number:"getal"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Ongeldige invoer: verwacht instanceof ${n.expected}, ontving ${u}`;return`Ongeldige invoer: verwacht ${t}, ontving ${u}`}case"invalid_value":if(n.values.length===1)return`Ongeldige invoer: verwacht ${w(n.values[0])}`;return`Ongeldige optie: verwacht één van ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin),u=n.origin==="date"?"laat":n.origin==="string"?"lang":"groot";if(v)return`Te ${u}: verwacht dat ${n.origin??"waarde"} ${t}${n.maximum.toString()} ${v.unit??"elementen"} ${v.verb}`;return`Te ${u}: verwacht dat ${n.origin??"waarde"} ${t}${n.maximum.toString()} is`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin),u=n.origin==="date"?"vroeg":n.origin==="string"?"kort":"klein";if(v)return`Te ${u}: verwacht dat ${n.origin} ${t}${n.minimum.toString()} ${v.unit} ${v.verb}`;return`Te ${u}: verwacht dat ${n.origin} ${t}${n.minimum.toString()} is`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Ongeldige tekst: moet met "${t.prefix}" beginnen`;if(t.format==="ends_with")return`Ongeldige tekst: moet op "${t.suffix}" eindigen`;if(t.format==="includes")return`Ongeldige tekst: moet "${t.includes}" bevatten`;if(t.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${t.pattern}`;return`Ongeldig: ${$[t.format]??n.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${n.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${n.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${n.origin}`;default:return"Ongeldige invoer"}}};function uo(){return{localeError:xm()}}var Gm=()=>{let r={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function i(n){return r[n]??null}let $={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"tall",array:"liste"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Ugyldig input: forventet instanceof ${n.expected}, fikk ${u}`;return`Ugyldig input: forventet ${t}, fikk ${u}`}case"invalid_value":if(n.values.length===1)return`Ugyldig verdi: forventet ${w(n.values[0])}`;return`Ugyldig valg: forventet en av ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`For stor(t): forventet ${n.origin??"value"} til å ha ${t}${n.maximum.toString()} ${v.unit??"elementer"}`;return`For stor(t): forventet ${n.origin??"value"} til å ha ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`For lite(n): forventet ${n.origin} til å ha ${t}${n.minimum.toString()} ${v.unit}`;return`For lite(n): forventet ${n.origin} til å ha ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Ugyldig streng: må starte med "${t.prefix}"`;if(t.format==="ends_with")return`Ugyldig streng: må ende med "${t.suffix}"`;if(t.format==="includes")return`Ugyldig streng: må inneholde "${t.includes}"`;if(t.format==="regex")return`Ugyldig streng: må matche mønsteret ${t.pattern}`;return`Ugyldig ${$[t.format]??n.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${U(n.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${n.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${n.origin}`;default:return"Ugyldig input"}}};function co(){return{localeError:Gm()}}var Ym=()=>{let r={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function i(n){return r[n]??null}let $={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},o={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Fâsit giren: umulan instanceof ${n.expected}, alınan ${u}`;return`Fâsit giren: umulan ${t}, alınan ${u}`}case"invalid_value":if(n.values.length===1)return`Fâsit giren: umulan ${w(n.values[0])}`;return`Fâsit tercih: mûteberler ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Fazla büyük: ${n.origin??"value"}, ${t}${n.maximum.toString()} ${v.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${n.origin??"value"}, ${t}${n.maximum.toString()} olmalıydı.`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Fazla küçük: ${n.origin}, ${t}${n.minimum.toString()} ${v.unit} sahip olmalıydı.`;return`Fazla küçük: ${n.origin}, ${t}${n.minimum.toString()} olmalıydı.`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Fâsit metin: "${t.prefix}" ile başlamalı.`;if(t.format==="ends_with")return`Fâsit metin: "${t.suffix}" ile bitmeli.`;if(t.format==="includes")return`Fâsit metin: "${t.includes}" ihtivâ etmeli.`;if(t.format==="regex")return`Fâsit metin: ${t.pattern} nakşına uymalı.`;return`Fâsit ${$[t.format]??n.format}`}case"not_multiple_of":return`Fâsit sayı: ${n.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`${n.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${n.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function go(){return{localeError:Ym()}}var Qm=()=>{let r={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function i(n){return r[n]??null}let $={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},o={nan:"NaN",number:"عدد",array:"ارې"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`ناسم ورودي: باید instanceof ${n.expected} وای, مګر ${u} ترلاسه شو`;return`ناسم ورودي: باید ${t} وای, مګر ${u} ترلاسه شو`}case"invalid_value":if(n.values.length===1)return`ناسم ورودي: باید ${w(n.values[0])} وای`;return`ناسم انتخاب: باید یو له ${U(n.values,"|")} څخه وای`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`ډیر لوی: ${n.origin??"ارزښت"} باید ${t}${n.maximum.toString()} ${v.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${n.origin??"ارزښت"} باید ${t}${n.maximum.toString()} وي`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`ډیر کوچنی: ${n.origin} باید ${t}${n.minimum.toString()} ${v.unit} ولري`;return`ډیر کوچنی: ${n.origin} باید ${t}${n.minimum.toString()} وي`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`ناسم متن: باید د "${t.prefix}" سره پیل شي`;if(t.format==="ends_with")return`ناسم متن: باید د "${t.suffix}" سره پای ته ورسيږي`;if(t.format==="includes")return`ناسم متن: باید "${t.includes}" ولري`;if(t.format==="regex")return`ناسم متن: باید د ${t.pattern} سره مطابقت ولري`;return`${$[t.format]??n.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${n.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${n.keys.length>1?"کلیډونه":"کلیډ"}: ${U(n.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${n.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${n.origin} کې`;default:return"ناسمه ورودي"}}};function lo(){return{localeError:Qm()}}var qm=()=>{let r={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function i(n){return r[n]??null}let $={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},o={nan:"NaN",number:"liczba",array:"tablica"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${n.expected}, otrzymano ${u}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${t}, otrzymano ${u}`}case"invalid_value":if(n.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${w(n.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Za duża wartość: oczekiwano, że ${n.origin??"wartość"} będzie mieć ${t}${n.maximum.toString()} ${v.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${n.origin??"wartość"} będzie wynosić ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Za mała wartość: oczekiwano, że ${n.origin??"wartość"} będzie mieć ${t}${n.minimum.toString()} ${v.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${n.origin??"wartość"} będzie wynosić ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${t.prefix}"`;if(t.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${t.suffix}"`;if(t.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${t.includes}"`;if(t.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${t.pattern}`;return`Nieprawidłow(y/a/e) ${$[t.format]??n.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${n.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${n.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${n.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function mo(){return{localeError:qm()}}var Wm=()=>{let r={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function i(n){return r[n]??null}let $={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN",number:"número",null:"nulo"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Tipo inválido: esperado instanceof ${n.expected}, recebido ${u}`;return`Tipo inválido: esperado ${t}, recebido ${u}`}case"invalid_value":if(n.values.length===1)return`Entrada inválida: esperado ${w(n.values[0])}`;return`Opção inválida: esperada uma das ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Muito grande: esperado que ${n.origin??"valor"} tivesse ${t}${n.maximum.toString()} ${v.unit??"elementos"}`;return`Muito grande: esperado que ${n.origin??"valor"} fosse ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Muito pequeno: esperado que ${n.origin} tivesse ${t}${n.minimum.toString()} ${v.unit}`;return`Muito pequeno: esperado que ${n.origin} fosse ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Texto inválido: deve começar com "${t.prefix}"`;if(t.format==="ends_with")return`Texto inválido: deve terminar com "${t.suffix}"`;if(t.format==="includes")return`Texto inválido: deve incluir "${t.includes}"`;if(t.format==="regex")return`Texto inválido: deve corresponder ao padrão ${t.pattern}`;return`${$[t.format]??n.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${n.divisor}`;case"unrecognized_keys":return`Chave${n.keys.length>1?"s":""} desconhecida${n.keys.length>1?"s":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Chave inválida em ${n.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${n.origin}`;default:return"Campo inválido"}}};function Uo(){return{localeError:Wm()}}var Km=()=>{let r={string:{unit:"caractere",verb:"să aibă"},file:{unit:"octeți",verb:"să aibă"},array:{unit:"elemente",verb:"să aibă"},set:{unit:"elemente",verb:"să aibă"},map:{unit:"intrări",verb:"să aibă"}};function i(n){return r[n]??null}let $={regex:"intrare",email:"adresă de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dată și oră ISO",date:"dată ISO",time:"oră ISO",duration:"durată ISO",ipv4:"adresă IPv4",ipv6:"adresă IPv6",mac:"adresă MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"șir codat base64",base64url:"șir codat base64url",json_string:"șir JSON",e164:"număr E.164",jwt:"JWT",template_literal:"intrare"},o={nan:"NaN",string:"șir",number:"număr",boolean:"boolean",function:"funcție",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"număr mare",void:"void",never:"never",map:"hartă",set:"set"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;return`Intrare invalidă: așteptat ${t}, primit ${u}`}case"invalid_value":if(n.values.length===1)return`Intrare invalidă: așteptat ${w(n.values[0])}`;return`Opțiune invalidă: așteptat una dintre ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Prea mare: așteptat ca ${n.origin??"valoarea"} ${v.verb} ${t}${n.maximum.toString()} ${v.unit??"elemente"}`;return`Prea mare: așteptat ca ${n.origin??"valoarea"} să fie ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Prea mic: așteptat ca ${n.origin} ${v.verb} ${t}${n.minimum.toString()} ${v.unit}`;return`Prea mic: așteptat ca ${n.origin} să fie ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Șir invalid: trebuie să înceapă cu "${t.prefix}"`;if(t.format==="ends_with")return`Șir invalid: trebuie să se termine cu "${t.suffix}"`;if(t.format==="includes")return`Șir invalid: trebuie să includă "${t.includes}"`;if(t.format==="regex")return`Șir invalid: trebuie să se potrivească cu modelul ${t.pattern}`;return`Format invalid: ${$[t.format]??n.format}`}case"not_multiple_of":return`Număr invalid: trebuie să fie multiplu de ${n.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${U(n.keys,", ")}`;case"invalid_key":return`Cheie invalidă în ${n.origin}`;case"invalid_union":return"Intrare invalidă";case"invalid_element":return`Valoare invalidă în ${n.origin}`;default:return"Intrare invalidă"}}};function Io(){return{localeError:Km()}}function zc(r,i,$,o){let n=Math.abs(r),t=n%10,v=n%100;if(v>=11&&v<=19)return o;if(t===1)return i;if(t>=2&&t<=4)return $;return o}var Lm=()=>{let r={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function i(n){return r[n]??null}let $={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},o={nan:"NaN",number:"число",array:"массив"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Неверный ввод: ожидалось instanceof ${n.expected}, получено ${u}`;return`Неверный ввод: ожидалось ${t}, получено ${u}`}case"invalid_value":if(n.values.length===1)return`Неверный ввод: ожидалось ${w(n.values[0])}`;return`Неверный вариант: ожидалось одно из ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v){let u=Number(n.maximum),g=zc(u,v.unit.one,v.unit.few,v.unit.many);return`Слишком большое значение: ожидалось, что ${n.origin??"значение"} будет иметь ${t}${n.maximum.toString()} ${g}`}return`Слишком большое значение: ожидалось, что ${n.origin??"значение"} будет ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v){let u=Number(n.minimum),g=zc(u,v.unit.one,v.unit.few,v.unit.many);return`Слишком маленькое значение: ожидалось, что ${n.origin} будет иметь ${t}${n.minimum.toString()} ${g}`}return`Слишком маленькое значение: ожидалось, что ${n.origin} будет ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Неверная строка: должна начинаться с "${t.prefix}"`;if(t.format==="ends_with")return`Неверная строка: должна заканчиваться на "${t.suffix}"`;if(t.format==="includes")return`Неверная строка: должна содержать "${t.includes}"`;if(t.format==="regex")return`Неверная строка: должна соответствовать шаблону ${t.pattern}`;return`Неверный ${$[t.format]??n.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${n.divisor}`;case"unrecognized_keys":return`Нераспознанн${n.keys.length>1?"ые":"ый"} ключ${n.keys.length>1?"и":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${n.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${n.origin}`;default:return"Неверные входные данные"}}};function ko(){return{localeError:Lm()}}var Em=()=>{let r={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function i(n){return r[n]??null}let $={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},o={nan:"NaN",number:"število",array:"tabela"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Neveljaven vnos: pričakovano instanceof ${n.expected}, prejeto ${u}`;return`Neveljaven vnos: pričakovano ${t}, prejeto ${u}`}case"invalid_value":if(n.values.length===1)return`Neveljaven vnos: pričakovano ${w(n.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Preveliko: pričakovano, da bo ${n.origin??"vrednost"} imelo ${t}${n.maximum.toString()} ${v.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${n.origin??"vrednost"} ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Premajhno: pričakovano, da bo ${n.origin} imelo ${t}${n.minimum.toString()} ${v.unit}`;return`Premajhno: pričakovano, da bo ${n.origin} ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Neveljaven niz: mora se začeti z "${t.prefix}"`;if(t.format==="ends_with")return`Neveljaven niz: mora se končati z "${t.suffix}"`;if(t.format==="includes")return`Neveljaven niz: mora vsebovati "${t.includes}"`;if(t.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${t.pattern}`;return`Neveljaven ${$[t.format]??n.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${n.divisor}`;case"unrecognized_keys":return`Neprepoznan${n.keys.length>1?"i ključi":" ključ"}: ${U(n.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${n.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${n.origin}`;default:return"Neveljaven vnos"}}};function bo(){return{localeError:Em()}}var Vm=()=>{let r={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function i(n){return r[n]??null}let $={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},o={nan:"NaN",number:"antal",array:"lista"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Ogiltig inmatning: förväntat instanceof ${n.expected}, fick ${u}`;return`Ogiltig inmatning: förväntat ${t}, fick ${u}`}case"invalid_value":if(n.values.length===1)return`Ogiltig inmatning: förväntat ${w(n.values[0])}`;return`Ogiltigt val: förväntade en av ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`För stor(t): förväntade ${n.origin??"värdet"} att ha ${t}${n.maximum.toString()} ${v.unit??"element"}`;return`För stor(t): förväntat ${n.origin??"värdet"} att ha ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`För lite(t): förväntade ${n.origin??"värdet"} att ha ${t}${n.minimum.toString()} ${v.unit}`;return`För lite(t): förväntade ${n.origin??"värdet"} att ha ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Ogiltig sträng: måste börja med "${t.prefix}"`;if(t.format==="ends_with")return`Ogiltig sträng: måste sluta med "${t.suffix}"`;if(t.format==="includes")return`Ogiltig sträng: måste innehålla "${t.includes}"`;if(t.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${t.pattern}"`;return`Ogiltig(t) ${$[t.format]??n.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${U(n.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${n.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${n.origin??"värdet"}`;default:return"Ogiltig input"}}};function _o(){return{localeError:Vm()}}var Tm=()=>{let r={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function i(n){return r[n]??null}let $={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${n.expected}, பெறப்பட்டது ${u}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${t}, பெறப்பட்டது ${u}`}case"invalid_value":if(n.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${w(n.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${U(n.values,"|")} இல் ஒன்று`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${n.origin??"மதிப்பு"} ${t}${n.maximum.toString()} ${v.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${n.origin??"மதிப்பு"} ${t}${n.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${n.origin} ${t}${n.minimum.toString()} ${v.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${n.origin} ${t}${n.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`தவறான சரம்: "${t.prefix}" இல் தொடங்க வேண்டும்`;if(t.format==="ends_with")return`தவறான சரம்: "${t.suffix}" இல் முடிவடைய வேண்டும்`;if(t.format==="includes")return`தவறான சரம்: "${t.includes}" ஐ உள்ளடக்க வேண்டும்`;if(t.format==="regex")return`தவறான சரம்: ${t.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${$[t.format]??n.format}`}case"not_multiple_of":return`தவறான எண்: ${n.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${n.keys.length>1?"கள்":""}: ${U(n.keys,", ")}`;case"invalid_key":return`${n.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${n.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function wo(){return{localeError:Tm()}}var em=()=>{let r={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function i(n){return r[n]??null}let $={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},o={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${n.expected} แต่ได้รับ ${u}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${t} แต่ได้รับ ${u}`}case"invalid_value":if(n.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${w(n.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"ไม่เกิน":"น้อยกว่า",v=i(n.origin);if(v)return`เกินกำหนด: ${n.origin??"ค่า"} ควรมี${t} ${n.maximum.toString()} ${v.unit??"รายการ"}`;return`เกินกำหนด: ${n.origin??"ค่า"} ควรมี${t} ${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?"อย่างน้อย":"มากกว่า",v=i(n.origin);if(v)return`น้อยกว่ากำหนด: ${n.origin} ควรมี${t} ${n.minimum.toString()} ${v.unit}`;return`น้อยกว่ากำหนด: ${n.origin} ควรมี${t} ${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${t.prefix}"`;if(t.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${t.suffix}"`;if(t.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${t.includes}" อยู่ในข้อความ`;if(t.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${t.pattern}`;return`รูปแบบไม่ถูกต้อง: ${$[t.format]??n.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${n.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${U(n.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${n.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${n.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function Do(){return{localeError:em()}}var Am=()=>{let r={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function i(n){return r[n]??null}let $={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Geçersiz değer: beklenen instanceof ${n.expected}, alınan ${u}`;return`Geçersiz değer: beklenen ${t}, alınan ${u}`}case"invalid_value":if(n.values.length===1)return`Geçersiz değer: beklenen ${w(n.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Çok büyük: beklenen ${n.origin??"değer"} ${t}${n.maximum.toString()} ${v.unit??"öğe"}`;return`Çok büyük: beklenen ${n.origin??"değer"} ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Çok küçük: beklenen ${n.origin} ${t}${n.minimum.toString()} ${v.unit}`;return`Çok küçük: beklenen ${n.origin} ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Geçersiz metin: "${t.prefix}" ile başlamalı`;if(t.format==="ends_with")return`Geçersiz metin: "${t.suffix}" ile bitmeli`;if(t.format==="includes")return`Geçersiz metin: "${t.includes}" içermeli`;if(t.format==="regex")return`Geçersiz metin: ${t.pattern} desenine uymalı`;return`Geçersiz ${$[t.format]??n.format}`}case"not_multiple_of":return`Geçersiz sayı: ${n.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${n.keys.length>1?"lar":""}: ${U(n.keys,", ")}`;case"invalid_key":return`${n.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${n.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function So(){return{localeError:Am()}}var Bm=()=>{let r={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function i(n){return r[n]??null}let $={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},o={nan:"NaN",number:"число",array:"масив"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Неправильні вхідні дані: очікується instanceof ${n.expected}, отримано ${u}`;return`Неправильні вхідні дані: очікується ${t}, отримано ${u}`}case"invalid_value":if(n.values.length===1)return`Неправильні вхідні дані: очікується ${w(n.values[0])}`;return`Неправильна опція: очікується одне з ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Занадто велике: очікується, що ${n.origin??"значення"} ${v.verb} ${t}${n.maximum.toString()} ${v.unit??"елементів"}`;return`Занадто велике: очікується, що ${n.origin??"значення"} буде ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Занадто мале: очікується, що ${n.origin} ${v.verb} ${t}${n.minimum.toString()} ${v.unit}`;return`Занадто мале: очікується, що ${n.origin} буде ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Неправильний рядок: повинен починатися з "${t.prefix}"`;if(t.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${t.suffix}"`;if(t.format==="includes")return`Неправильний рядок: повинен містити "${t.includes}"`;if(t.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${t.pattern}`;return`Неправильний ${$[t.format]??n.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${n.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${n.keys.length>1?"і":""}: ${U(n.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${n.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${n.origin}`;default:return"Неправильні вхідні дані"}}};function Hr(){return{localeError:Bm()}}function Po(){return Hr()}var Rm=()=>{let r={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function i(n){return r[n]??null}let $={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},o={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`غلط ان پٹ: instanceof ${n.expected} متوقع تھا، ${u} موصول ہوا`;return`غلط ان پٹ: ${t} متوقع تھا، ${u} موصول ہوا`}case"invalid_value":if(n.values.length===1)return`غلط ان پٹ: ${w(n.values[0])} متوقع تھا`;return`غلط آپشن: ${U(n.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`بہت بڑا: ${n.origin??"ویلیو"} کے ${t}${n.maximum.toString()} ${v.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${n.origin??"ویلیو"} کا ${t}${n.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`بہت چھوٹا: ${n.origin} کے ${t}${n.minimum.toString()} ${v.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${n.origin} کا ${t}${n.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`غلط سٹرنگ: "${t.prefix}" سے شروع ہونا چاہیے`;if(t.format==="ends_with")return`غلط سٹرنگ: "${t.suffix}" پر ختم ہونا چاہیے`;if(t.format==="includes")return`غلط سٹرنگ: "${t.includes}" شامل ہونا چاہیے`;if(t.format==="regex")return`غلط سٹرنگ: پیٹرن ${t.pattern} سے میچ ہونا چاہیے`;return`غلط ${$[t.format]??n.format}`}case"not_multiple_of":return`غلط نمبر: ${n.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${n.keys.length>1?"ز":""}: ${U(n.keys,"، ")}`;case"invalid_key":return`${n.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${n.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function Oo(){return{localeError:Rm()}}var fm=()=>{let r={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"},map:{unit:"yozuv",verb:"bo‘lishi kerak"}};function i(n){return r[n]??null}let $={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},o={nan:"NaN",number:"raqam",array:"massiv"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${n.expected}, qabul qilingan ${u}`;return`Noto‘g‘ri kirish: kutilgan ${t}, qabul qilingan ${u}`}case"invalid_value":if(n.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${w(n.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Juda katta: kutilgan ${n.origin??"qiymat"} ${t}${n.maximum.toString()} ${v.unit} ${v.verb}`;return`Juda katta: kutilgan ${n.origin??"qiymat"} ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Juda kichik: kutilgan ${n.origin} ${t}${n.minimum.toString()} ${v.unit} ${v.verb}`;return`Juda kichik: kutilgan ${n.origin} ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Noto‘g‘ri satr: "${t.prefix}" bilan boshlanishi kerak`;if(t.format==="ends_with")return`Noto‘g‘ri satr: "${t.suffix}" bilan tugashi kerak`;if(t.format==="includes")return`Noto‘g‘ri satr: "${t.includes}" ni o‘z ichiga olishi kerak`;if(t.format==="regex")return`Noto‘g‘ri satr: ${t.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${$[t.format]??n.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${n.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${n.keys.length>1?"lar":""}: ${U(n.keys,", ")}`;case"invalid_key":return`${n.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${n.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function No(){return{localeError:fm()}}var Zm=()=>{let r={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function i(n){return r[n]??null}let $={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},o={nan:"NaN",number:"số",array:"mảng"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${n.expected}, nhận được ${u}`;return`Đầu vào không hợp lệ: mong đợi ${t}, nhận được ${u}`}case"invalid_value":if(n.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${w(n.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Quá lớn: mong đợi ${n.origin??"giá trị"} ${v.verb} ${t}${n.maximum.toString()} ${v.unit??"phần tử"}`;return`Quá lớn: mong đợi ${n.origin??"giá trị"} ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Quá nhỏ: mong đợi ${n.origin} ${v.verb} ${t}${n.minimum.toString()} ${v.unit}`;return`Quá nhỏ: mong đợi ${n.origin} ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${t.prefix}"`;if(t.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${t.suffix}"`;if(t.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${t.includes}"`;if(t.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${t.pattern}`;return`${$[t.format]??n.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${n.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${U(n.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${n.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${n.origin}`;default:return"Đầu vào không hợp lệ"}}};function jo(){return{localeError:Zm()}}var Mm=()=>{let r={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function i(n){return r[n]??null}let $={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},o={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`无效输入:期望 instanceof ${n.expected},实际接收 ${u}`;return`无效输入:期望 ${t},实际接收 ${u}`}case"invalid_value":if(n.values.length===1)return`无效输入:期望 ${w(n.values[0])}`;return`无效选项:期望以下之一 ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`数值过大:期望 ${n.origin??"值"} ${t}${n.maximum.toString()} ${v.unit??"个元素"}`;return`数值过大:期望 ${n.origin??"值"} ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`数值过小:期望 ${n.origin} ${t}${n.minimum.toString()} ${v.unit}`;return`数值过小:期望 ${n.origin} ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`无效字符串:必须以 "${t.prefix}" 开头`;if(t.format==="ends_with")return`无效字符串:必须以 "${t.suffix}" 结尾`;if(t.format==="includes")return`无效字符串:必须包含 "${t.includes}"`;if(t.format==="regex")return`无效字符串:必须满足正则表达式 ${t.pattern}`;return`无效${$[t.format]??n.format}`}case"not_multiple_of":return`无效数字:必须是 ${n.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${U(n.keys,", ")}`;case"invalid_key":return`${n.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${n.origin} 中包含无效值(value)`;default:return"无效输入"}}};function zo(){return{localeError:Mm()}}var Hm=()=>{let r={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function i(n){return r[n]??null}let $={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`無效的輸入值:預期為 instanceof ${n.expected},但收到 ${u}`;return`無效的輸入值:預期為 ${t},但收到 ${u}`}case"invalid_value":if(n.values.length===1)return`無效的輸入值:預期為 ${w(n.values[0])}`;return`無效的選項:預期為以下其中之一 ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`數值過大:預期 ${n.origin??"值"} 應為 ${t}${n.maximum.toString()} ${v.unit??"個元素"}`;return`數值過大:預期 ${n.origin??"值"} 應為 ${t}${n.maximum.toString()}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`數值過小:預期 ${n.origin} 應為 ${t}${n.minimum.toString()} ${v.unit}`;return`數值過小:預期 ${n.origin} 應為 ${t}${n.minimum.toString()}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`無效的字串:必須以 "${t.prefix}" 開頭`;if(t.format==="ends_with")return`無效的字串:必須以 "${t.suffix}" 結尾`;if(t.format==="includes")return`無效的字串:必須包含 "${t.includes}"`;if(t.format==="regex")return`無效的字串:必須符合格式 ${t.pattern}`;return`無效的 ${$[t.format]??n.format}`}case"not_multiple_of":return`無效的數字:必須為 ${n.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${n.keys.length>1?"們":""}:${U(n.keys,"、")}`;case"invalid_key":return`${n.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${n.origin} 中有無效的值`;default:return"無效的輸入值"}}};function Jo(){return{localeError:Hm()}}var Cm=()=>{let r={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function i(n){return r[n]??null}let $={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},o={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(n)=>{switch(n.code){case"invalid_type":{let t=o[n.expected]??n.expected,v=S(n.input),u=o[v]??v;if(/^[A-Z]/.test(n.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${n.expected}, àmọ̀ a rí ${u}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${t}, àmọ̀ a rí ${u}`}case"invalid_value":if(n.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${w(n.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${U(n.values,"|")}`;case"too_big":{let t=n.inclusive?"<=":"<",v=i(n.origin);if(v)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${n.origin??"iye"} ${v.verb} ${t}${n.maximum} ${v.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${t}${n.maximum}`}case"too_small":{let t=n.inclusive?">=":">",v=i(n.origin);if(v)return`Kéré ju: a ní láti jẹ́ pé ${n.origin} ${v.verb} ${t}${n.minimum} ${v.unit}`;return`Kéré ju: a ní láti jẹ́ ${t}${n.minimum}`}case"invalid_format":{let t=n;if(t.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${t.prefix}"`;if(t.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${t.suffix}"`;if(t.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${t.includes}"`;if(t.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${t.pattern}`;return`Aṣìṣe: ${$[t.format]??n.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${n.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${U(n.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${n.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${n.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function Fo(){return{localeError:Cm()}}var Jc,Xo=Symbol("ZodOutput"),xo=Symbol("ZodInput");class Go{constructor(){this._map=new WeakMap,this._idmap=new Map}add(r,...i){let $=i[0];if(this._map.set(r,$),$&&typeof $==="object"&&"id"in $)this._idmap.set($.id,r);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(r){let i=this._map.get(r);if(i&&typeof i==="object"&&"id"in i)this._idmap.delete(i.id);return this._map.delete(r),this}get(r){let i=r._zod.parent;if(i){let $={...this.get(i)??{}};delete $.id;let o={...$,...this._map.get(r)};return Object.keys(o).length?o:void 0}return this._map.get(r)}has(r){return this._map.has(r)}}function xn(){return new Go}(Jc=globalThis).__zod_globalRegistry??(Jc.__zod_globalRegistry=xn());var C=globalThis.__zod_globalRegistry;function Yo(r,i){return new r({type:"string",...b(i)})}function Qo(r,i){return new r({type:"string",coerce:!0,...b(i)})}function qo(r,i){return new r({type:"string",format:"email",check:"string_format",abort:!1,...b(i)})}function Wo(r,i){return new r({type:"string",format:"guid",check:"string_format",abort:!1,...b(i)})}function Ko(r,i){return new r({type:"string",format:"uuid",check:"string_format",abort:!1,...b(i)})}function Lo(r,i){return new r({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...b(i)})}function Eo(r,i){return new r({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...b(i)})}function Vo(r,i){return new r({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...b(i)})}function Gn(r,i){return new r({type:"string",format:"url",check:"string_format",abort:!1,...b(i)})}function To(r,i){return new r({type:"string",format:"emoji",check:"string_format",abort:!1,...b(i)})}function eo(r,i){return new r({type:"string",format:"nanoid",check:"string_format",abort:!1,...b(i)})}function Ao(r,i){return new r({type:"string",format:"cuid",check:"string_format",abort:!1,...b(i)})}function Bo(r,i){return new r({type:"string",format:"cuid2",check:"string_format",abort:!1,...b(i)})}function Ro(r,i){return new r({type:"string",format:"ulid",check:"string_format",abort:!1,...b(i)})}function fo(r,i){return new r({type:"string",format:"xid",check:"string_format",abort:!1,...b(i)})}function Zo(r,i){return new r({type:"string",format:"ksuid",check:"string_format",abort:!1,...b(i)})}function Mo(r,i){return new r({type:"string",format:"ipv4",check:"string_format",abort:!1,...b(i)})}function Ho(r,i){return new r({type:"string",format:"ipv6",check:"string_format",abort:!1,...b(i)})}function Co(r,i){return new r({type:"string",format:"mac",check:"string_format",abort:!1,...b(i)})}function ho(r,i){return new r({type:"string",format:"cidrv4",check:"string_format",abort:!1,...b(i)})}function ao(r,i){return new r({type:"string",format:"cidrv6",check:"string_format",abort:!1,...b(i)})}function yo(r,i){return new r({type:"string",format:"base64",check:"string_format",abort:!1,...b(i)})}function po(r,i){return new r({type:"string",format:"base64url",check:"string_format",abort:!1,...b(i)})}function so(r,i){return new r({type:"string",format:"e164",check:"string_format",abort:!1,...b(i)})}function rv(r,i){return new r({type:"string",format:"jwt",check:"string_format",abort:!1,...b(i)})}var nv={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function iv(r,i){return new r({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...b(i)})}function tv(r,i){return new r({type:"string",format:"date",check:"string_format",...b(i)})}function $v(r,i){return new r({type:"string",format:"time",check:"string_format",precision:null,...b(i)})}function ov(r,i){return new r({type:"string",format:"duration",check:"string_format",...b(i)})}function vv(r,i){return new r({type:"number",checks:[],...b(i)})}function uv(r,i){return new r({type:"number",coerce:!0,checks:[],...b(i)})}function cv(r,i){return new r({type:"number",check:"number_format",abort:!1,format:"safeint",...b(i)})}function gv(r,i){return new r({type:"number",check:"number_format",abort:!1,format:"float32",...b(i)})}function lv(r,i){return new r({type:"number",check:"number_format",abort:!1,format:"float64",...b(i)})}function mv(r,i){return new r({type:"number",check:"number_format",abort:!1,format:"int32",...b(i)})}function Uv(r,i){return new r({type:"number",check:"number_format",abort:!1,format:"uint32",...b(i)})}function Iv(r,i){return new r({type:"boolean",...b(i)})}function kv(r,i){return new r({type:"boolean",coerce:!0,...b(i)})}function bv(r,i){return new r({type:"bigint",...b(i)})}function _v(r,i){return new r({type:"bigint",coerce:!0,...b(i)})}function wv(r,i){return new r({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...b(i)})}function Dv(r,i){return new r({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...b(i)})}function Sv(r,i){return new r({type:"symbol",...b(i)})}function Pv(r,i){return new r({type:"undefined",...b(i)})}function Ov(r,i){return new r({type:"null",...b(i)})}function Nv(r){return new r({type:"any"})}function jv(r){return new r({type:"unknown"})}function zv(r,i){return new r({type:"never",...b(i)})}function Jv(r,i){return new r({type:"void",...b(i)})}function Fv(r,i){return new r({type:"date",...b(i)})}function Xv(r,i){return new r({type:"date",coerce:!0,...b(i)})}function xv(r,i){return new r({type:"nan",...b(i)})}function Yn(r,i){return new bn({check:"less_than",...b(i),value:r,inclusive:!1})}function hr(r,i){return new bn({check:"less_than",...b(i),value:r,inclusive:!0})}function Qn(r,i){return new _n({check:"greater_than",...b(i),value:r,inclusive:!1})}function ar(r,i){return new _n({check:"greater_than",...b(i),value:r,inclusive:!0})}function Gv(r){return Qn(0,r)}function Yv(r){return Yn(0,r)}function Qv(r){return hr(0,r)}function qv(r){return ar(0,r)}function Wv(r,i){return new $t({check:"multiple_of",...b(i),value:r})}function Kv(r,i){return new ut({check:"max_size",...b(i),maximum:r})}function Lv(r,i){return new ct({check:"min_size",...b(i),minimum:r})}function Ev(r,i){return new gt({check:"size_equals",...b(i),size:r})}function Vv(r,i){return new lt({check:"max_length",...b(i),maximum:r})}function Tv(r,i){return new mt({check:"min_length",...b(i),minimum:r})}function ev(r,i){return new Ut({check:"length_equals",...b(i),length:r})}function Av(r,i){return new It({check:"string_format",format:"regex",...b(i),pattern:r})}function Bv(r){return new kt({check:"string_format",format:"lowercase",...b(r)})}function Rv(r){return new bt({check:"string_format",format:"uppercase",...b(r)})}function fv(r,i){return new _t({check:"string_format",format:"includes",...b(i),includes:r})}function Zv(r,i){return new wt({check:"string_format",format:"starts_with",...b(i),prefix:r})}function Mv(r,i){return new Dt({check:"string_format",format:"ends_with",...b(i),suffix:r})}function Hv(r,i,$){return new St({check:"property",property:r,schema:i,...b($)})}function Cv(r,i){return new Pt({check:"mime_type",mime:r,...b(i)})}function or(r){return new Ot({check:"overwrite",tx:r})}function hv(r){return or((i)=>i.normalize(r))}function av(){return or((r)=>r.trim())}function yv(){return or((r)=>r.toLowerCase())}function dv(){return or((r)=>r.toUpperCase())}function am(){return or((r)=>$i(r))}function ym(r,i,$){return new r({type:"array",element:i,...b($)})}function dm(r,i,$){return new r({type:"union",options:i,...b($)})}function pm(r,i,$){return new r({type:"union",options:i,inclusive:!1,...b($)})}function sm(r,i,$,o){return new r({type:"union",options:$,discriminator:i,...b(o)})}function r4(r,i,$){return new r({type:"intersection",left:i,right:$})}function n4(r,i,$,o){let n=$ instanceof N;return new r({type:"tuple",items:i,rest:n?$:null,...b(n?o:$)})}function i4(r,i,$,o){return new r({type:"record",keyType:i,valueType:$,...b(o)})}function t4(r,i,$,o){return new r({type:"map",keyType:i,valueType:$,...b(o)})}function $4(r,i,$){return new r({type:"set",valueType:i,...b($)})}function o4(r,i,$){let o=Array.isArray(i)?Object.fromEntries(i.map((n)=>[n,n])):i;return new r({type:"enum",entries:o,...b($)})}function v4(r,i,$){return new r({type:"enum",entries:i,...b($)})}function u4(r,i,$){return new r({type:"literal",values:Array.isArray(i)?i:[i],...b($)})}function pv(r,i){return new r({type:"file",...b(i)})}function c4(r,i){return new r({type:"transform",transform:i})}function g4(r,i){return new r({type:"optional",innerType:i})}function l4(r,i){return new r({type:"nullable",innerType:i})}function m4(r,i,$){return new r({type:"default",innerType:i,get defaultValue(){return typeof $==="function"?$():Pr($)}})}function U4(r,i,$){return new r({type:"nonoptional",innerType:i,...b($)})}function I4(r,i){return new r({type:"success",innerType:i})}function k4(r,i,$){return new r({type:"catch",innerType:i,catchValue:typeof $==="function"?$:()=>$})}function b4(r,i,$){return new r({type:"pipe",in:i,out:$})}function _4(r,i){return new r({type:"readonly",innerType:i})}function w4(r,i,$){return new r({type:"template_literal",parts:i,...b($)})}function D4(r,i){return new r({type:"lazy",getter:i})}function S4(r,i){return new r({type:"promise",innerType:i})}function sv(r,i,$){let o=b($);return o.abort??(o.abort=!0),new r({type:"custom",check:"custom",fn:i,...o})}function ru(r,i,$){return new r({type:"custom",check:"custom",fn:i,...b($)})}function nu(r,i){let $=Fc((o)=>{return o.addIssue=(n)=>{if(typeof n==="string")o.issues.push(Or(n,o.value,$._zod.def));else{let t=n;if(t.fatal)t.continue=!1;t.code??(t.code="custom"),t.input??(t.input=o.value),t.inst??(t.inst=$),t.continue??(t.continue=!$._zod.def.abort),o.issues.push(Or(t))}},r(o.value,o)},i);return $}function Fc(r,i){let $=new x({check:"custom",...b(i)});return $._zod.check=r,$}function iu(r){let i=new x({check:"describe"});return i._zod.onattach=[($)=>{let o=C.get($)??{};C.add($,{...o,description:r})}],i._zod.check=()=>{},i}function tu(r){let i=new x({check:"meta"});return i._zod.onattach=[($)=>{let o=C.get($)??{};C.add($,{...o,...r})}],i._zod.check=()=>{},i}function $u(r,i){let $=b(i),o=$.truthy??["true","1","yes","on","y","enabled"],n=$.falsy??["false","0","no","off","n","disabled"];if($.case!=="sensitive")o=o.map((k)=>typeof k==="string"?k.toLowerCase():k),n=n.map((k)=>typeof k==="string"?k.toLowerCase():k);let t=new Set(o),v=new Set(n),u=r.Codec??fr,g=r.Boolean??Br,l=new(r.String??jr)({type:"string",error:$.error}),I=new g({type:"boolean",error:$.error}),_=new u({type:"pipe",in:l,out:I,transform:(k,P)=>{let q=k;if($.case!=="sensitive")q=q.toLowerCase();if(t.has(q))return!0;else if(v.has(q))return!1;else return P.issues.push({code:"invalid_value",expected:"stringbool",values:[...t,...v],input:P.value,inst:_,continue:!1}),{}},reverseTransform:(k,P)=>{if(k===!0)return o[0]||"true";else return n[0]||"false"},error:$.error});return _}function Jr(r,i,$,o={}){let n=b(o),t={...b(o),check:"string_format",type:"string",format:i,fn:typeof $==="function"?$:(u)=>$.test(u),...n};if($ instanceof RegExp)t.pattern=$;return new r(t)}function vr(r){let i=r?.target??"draft-2020-12";if(i==="draft-4")i="draft-04";if(i==="draft-7")i="draft-07";return{processors:r.processors??{},metadataRegistry:r?.metadata??C,target:i,unrepresentable:r?.unrepresentable??"throw",override:r?.override??(()=>{}),io:r?.io??"output",counter:0,seen:new Map,cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0}}function F(r,i,$={path:[],schemaPath:[]}){var o;let n=r._zod.def,t=i.seen.get(r);if(t){if(t.count++,$.schemaPath.includes(r))t.cycle=$.path;return t.schema}let v={schema:{},count:1,cycle:void 0,path:$.path};i.seen.set(r,v);let u=r._zod.toJSONSchema?.();if(u)v.schema=u;else{let l={...$,schemaPath:[...$.schemaPath,r],path:$.path};if(r._zod.processJSONSchema)r._zod.processJSONSchema(i,v.schema,l);else{let _=v.schema,k=i.processors[n.type];if(!k)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);k(r,i,_,l)}let I=r._zod.parent;if(I){if(!v.ref)v.ref=I;F(I,i,l),i.seen.get(I).isParent=!0}}let g=i.metadataRegistry.get(r);if(g)Object.assign(v.schema,g);if(i.io==="input"&&V(r))delete v.schema.examples,delete v.schema.default;if(i.io==="input"&&"_prefault"in v.schema)(o=v.schema).default??(o.default=v.schema._prefault);return delete v.schema._prefault,i.seen.get(r).schema}function ur(r,i){let $=r.seen.get(i);if(!$)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let v of r.seen.entries()){let u=r.metadataRegistry.get(v[0])?.id;if(u){let g=o.get(u);if(g&&g!==v[0])throw Error(`Duplicate schema id "${u}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(u,v[0])}}let n=(v)=>{let u=r.target==="draft-2020-12"?"$defs":"definitions";if(r.external){let I=r.external.registry.get(v[0])?.id,_=r.external.uri??((P)=>P);if(I)return{ref:_(I)};let k=v[1].defId??v[1].schema.id??`schema${r.counter++}`;return v[1].defId=k,{defId:k,ref:`${_("__shared")}#/${u}/${k}`}}if(v[1]===$)return{ref:"#"};let c=`${"#"}/${u}/`,l=v[1].schema.id??`__schema${r.counter++}`;return{defId:l,ref:c+l}},t=(v)=>{if(v[1].schema.$ref)return;let u=v[1],{ref:g,defId:c}=n(v);if(u.def={...u.schema},c)u.defId=c;let l=u.schema;for(let I in l)delete l[I];l.$ref=g};if(r.cycles==="throw")for(let v of r.seen.entries()){let u=v[1];if(u.cycle)throw Error(`Cycle detected: #/${u.cycle?.join("/")}/<root>
|
|
68
|
-
|
|
69
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let v of r.seen.entries()){let u=v[1];if(i===v[0]){t(v);continue}if(r.external){let c=r.external.registry.get(v[0])?.id;if(i!==v[0]&&c){t(v);continue}}if(r.metadataRegistry.get(v[0])?.id){t(v);continue}if(u.cycle){t(v);continue}if(u.count>1){if(r.reused==="ref"){t(v);continue}}}}function cr(r,i){let $=r.seen.get(i);if(!$)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(u)=>{let g=r.seen.get(u);if(g.ref===null)return;let c=g.def??g.schema,l={...c},I=g.ref;if(g.ref=null,I){o(I);let k=r.seen.get(I),P=k.schema;if(P.$ref&&(r.target==="draft-07"||r.target==="draft-04"||r.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(P);else Object.assign(c,P);if(Object.assign(c,l),u._zod.parent===I)for(let Q in c){if(Q==="$ref"||Q==="allOf")continue;if(!(Q in l))delete c[Q]}if(P.$ref&&k.def)for(let Q in c){if(Q==="$ref"||Q==="allOf")continue;if(Q in k.def&&JSON.stringify(c[Q])===JSON.stringify(k.def[Q]))delete c[Q]}}let _=u._zod.parent;if(_&&_!==I){o(_);let k=r.seen.get(_);if(k?.schema.$ref){if(c.$ref=k.schema.$ref,k.def)for(let P in c){if(P==="$ref"||P==="allOf")continue;if(P in k.def&&JSON.stringify(c[P])===JSON.stringify(k.def[P]))delete c[P]}}}r.override({zodSchema:u,jsonSchema:c,path:g.path??[]})};for(let u of[...r.seen.entries()].reverse())o(u[0]);let n={};if(r.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(r.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if(r.target==="openapi-3.0");if(r.external?.uri){let u=r.external.registry.get(i)?.id;if(!u)throw Error("Schema is missing an `id` property");n.$id=r.external.uri(u)}Object.assign(n,$.def??$.schema);let t=r.metadataRegistry.get(i)?.id;if(t!==void 0&&n.id===t)delete n.id;let v=r.external?.defs??{};for(let u of r.seen.entries()){let g=u[1];if(g.def&&g.defId){if(g.def.id===g.defId)delete g.def.id;v[g.defId]=g.def}}if(r.external);else if(Object.keys(v).length>0)if(r.target==="draft-2020-12")n.$defs=v;else n.definitions=v;try{let u=JSON.parse(JSON.stringify(n));return Object.defineProperty(u,"~standard",{value:{...i["~standard"],jsonSchema:{input:ou(i,"input",r.processors),output:ou(i,"output",r.processors)}},enumerable:!1,writable:!1}),u}catch(u){throw Error("Error converting schema to JSON.")}}function V(r,i){let $=i??{seen:new Set};if($.seen.has(r))return!1;$.seen.add(r);let o=r._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return V(o.element,$);if(o.type==="set")return V(o.valueType,$);if(o.type==="lazy")return V(o.getter(),$);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return V(o.innerType,$);if(o.type==="intersection")return V(o.left,$)||V(o.right,$);if(o.type==="record"||o.type==="map")return V(o.keyType,$)||V(o.valueType,$);if(o.type==="pipe"){if(r._zod.traits.has("$ZodCodec"))return!0;return V(o.in,$)||V(o.out,$)}if(o.type==="object"){for(let n in o.shape)if(V(o.shape[n],$))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(V(n,$))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(V(n,$))return!0;if(o.rest&&V(o.rest,$))return!0;return!1}return!1}var P4=(r,i={})=>($)=>{let o=vr({...$,processors:i});return F(r,o),ur(o,r),cr(o,r)},ou=(r,i,$={})=>(o)=>{let{libraryOptions:n,target:t}=o??{},v=vr({...n??{},target:t,io:i,processors:$});return F(r,v),ur(v,r),cr(v,r)};var O4={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},N4=(r,i,$,o)=>{let n=$;n.type="string";let{minimum:t,maximum:v,format:u,patterns:g,contentEncoding:c}=r._zod.bag;if(typeof t==="number")n.minLength=t;if(typeof v==="number")n.maxLength=v;if(u){if(n.format=O4[u]??u,n.format==="")delete n.format;if(u==="time")delete n.format}if(c)n.contentEncoding=c;if(g&&g.size>0){let l=[...g];if(l.length===1)n.pattern=l[0].source;else if(l.length>1)n.allOf=[...l.map((I)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:I.source}))]}},j4=(r,i,$,o)=>{let n=$,{minimum:t,maximum:v,format:u,multipleOf:g,exclusiveMaximum:c,exclusiveMinimum:l}=r._zod.bag;if(typeof u==="string"&&u.includes("int"))n.type="integer";else n.type="number";let I=typeof l==="number"&&l>=(t??Number.NEGATIVE_INFINITY),_=typeof c==="number"&&c<=(v??Number.POSITIVE_INFINITY),k=i.target==="draft-04"||i.target==="openapi-3.0";if(I)if(k)n.minimum=l,n.exclusiveMinimum=!0;else n.exclusiveMinimum=l;else if(typeof t==="number")n.minimum=t;if(_)if(k)n.maximum=c,n.exclusiveMaximum=!0;else n.exclusiveMaximum=c;else if(typeof v==="number")n.maximum=v;if(typeof g==="number")n.multipleOf=g},z4=(r,i,$,o)=>{$.type="boolean"},J4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},F4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},X4=(r,i,$,o)=>{if(i.target==="openapi-3.0")$.type="string",$.nullable=!0,$.enum=[null];else $.type="null"},x4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},G4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Y4=(r,i,$,o)=>{$.not={}},Q4=(r,i,$,o)=>{},q4=(r,i,$,o)=>{},W4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},K4=(r,i,$,o)=>{let n=r._zod.def,t=Wr(n.entries);if(t.every((v)=>typeof v==="number"))$.type="number";if(t.every((v)=>typeof v==="string"))$.type="string";$.enum=t},L4=(r,i,$,o)=>{let n=r._zod.def,t=[];for(let v of n.values)if(v===void 0){if(i.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof v==="bigint")if(i.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else t.push(Number(v));else t.push(v);if(t.length===0);else if(t.length===1){let v=t[0];if($.type=v===null?"null":typeof v,i.target==="draft-04"||i.target==="openapi-3.0")$.enum=[v];else $.const=v}else{if(t.every((v)=>typeof v==="number"))$.type="number";if(t.every((v)=>typeof v==="string"))$.type="string";if(t.every((v)=>typeof v==="boolean"))$.type="boolean";if(t.every((v)=>v===null))$.type="null";$.enum=t}},E4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},V4=(r,i,$,o)=>{let n=$,t=r._zod.pattern;if(!t)throw Error("Pattern not found in template literal");n.type="string",n.pattern=t.source},T4=(r,i,$,o)=>{let n=$,t={type:"string",format:"binary",contentEncoding:"binary"},{minimum:v,maximum:u,mime:g}=r._zod.bag;if(v!==void 0)t.minLength=v;if(u!==void 0)t.maxLength=u;if(g)if(g.length===1)t.contentMediaType=g[0],Object.assign(n,t);else Object.assign(n,t),n.anyOf=g.map((c)=>({contentMediaType:c}));else Object.assign(n,t)},e4=(r,i,$,o)=>{$.type="boolean"},A4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},B4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},R4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},f4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},Z4=(r,i,$,o)=>{if(i.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},M4=(r,i,$,o)=>{let n=$,t=r._zod.def,{minimum:v,maximum:u}=r._zod.bag;if(typeof v==="number")n.minItems=v;if(typeof u==="number")n.maxItems=u;n.type="array",n.items=F(t.element,i,{...o,path:[...o.path,"items"]})},H4=(r,i,$,o)=>{let n=$,t=r._zod.def;n.type="object",n.properties={};let v=t.shape;for(let c in v)n.properties[c]=F(v[c],i,{...o,path:[...o.path,"properties",c]});let u=new Set(Object.keys(v)),g=new Set([...u].filter((c)=>{let l=t.shape[c]._zod;if(i.io==="input")return l.optin===void 0;else return l.optout===void 0}));if(g.size>0)n.required=Array.from(g);if(t.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!t.catchall){if(i.io==="output")n.additionalProperties=!1}else if(t.catchall)n.additionalProperties=F(t.catchall,i,{...o,path:[...o.path,"additionalProperties"]})},C4=(r,i,$,o)=>{let n=r._zod.def,t=n.inclusive===!1,v=n.options.map((u,g)=>F(u,i,{...o,path:[...o.path,t?"oneOf":"anyOf",g]}));if(t)$.oneOf=v;else $.anyOf=v},h4=(r,i,$,o)=>{let n=r._zod.def,t=F(n.left,i,{...o,path:[...o.path,"allOf",0]}),v=F(n.right,i,{...o,path:[...o.path,"allOf",1]}),u=(c)=>("allOf"in c)&&Object.keys(c).length===1,g=[...u(t)?t.allOf:[t],...u(v)?v.allOf:[v]];$.allOf=g},a4=(r,i,$,o)=>{let n=$,t=r._zod.def;n.type="array";let v=i.target==="draft-2020-12"?"prefixItems":"items",u=i.target==="draft-2020-12"?"items":i.target==="openapi-3.0"?"items":"additionalItems",g=t.items.map((_,k)=>F(_,i,{...o,path:[...o.path,v,k]})),c=t.rest?F(t.rest,i,{...o,path:[...o.path,u,...i.target==="openapi-3.0"?[t.items.length]:[]]}):null;if(i.target==="draft-2020-12"){if(n.prefixItems=g,c)n.items=c}else if(i.target==="openapi-3.0"){if(n.items={anyOf:g},c)n.items.anyOf.push(c);if(n.minItems=g.length,!c)n.maxItems=g.length}else if(n.items=g,c)n.additionalItems=c;let{minimum:l,maximum:I}=r._zod.bag;if(typeof l==="number")n.minItems=l;if(typeof I==="number")n.maxItems=I},y4=(r,i,$,o)=>{let n=$,t=r._zod.def;n.type="object";let v=t.keyType,g=v._zod.bag?.patterns;if(t.mode==="loose"&&g&&g.size>0){let l=F(t.valueType,i,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let I of g)n.patternProperties[I.source]=l}else{if(i.target==="draft-07"||i.target==="draft-2020-12")n.propertyNames=F(t.keyType,i,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=F(t.valueType,i,{...o,path:[...o.path,"additionalProperties"]})}let c=v._zod.values;if(c){let l=[...c].filter((I)=>typeof I==="string"||typeof I==="number");if(l.length>0)n.required=l}},d4=(r,i,$,o)=>{let n=r._zod.def,t=F(n.innerType,i,o),v=i.seen.get(r);if(i.target==="openapi-3.0")v.ref=n.innerType,$.nullable=!0;else $.anyOf=[t,{type:"null"}]},p4=(r,i,$,o)=>{let n=r._zod.def;F(n.innerType,i,o);let t=i.seen.get(r);t.ref=n.innerType},s4=(r,i,$,o)=>{let n=r._zod.def;F(n.innerType,i,o);let t=i.seen.get(r);t.ref=n.innerType,$.default=JSON.parse(JSON.stringify(n.defaultValue))},rU=(r,i,$,o)=>{let n=r._zod.def;F(n.innerType,i,o);let t=i.seen.get(r);if(t.ref=n.innerType,i.io==="input")$._prefault=JSON.parse(JSON.stringify(n.defaultValue))},nU=(r,i,$,o)=>{let n=r._zod.def;F(n.innerType,i,o);let t=i.seen.get(r);t.ref=n.innerType;let v;try{v=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}$.default=v},iU=(r,i,$,o)=>{let n=r._zod.def,t=n.in._zod.traits.has("$ZodTransform"),v=i.io==="input"?t?n.out:n.in:n.out;F(v,i,o);let u=i.seen.get(r);u.ref=v},tU=(r,i,$,o)=>{let n=r._zod.def;F(n.innerType,i,o);let t=i.seen.get(r);t.ref=n.innerType,$.readOnly=!0},$U=(r,i,$,o)=>{let n=r._zod.def;F(n.innerType,i,o);let t=i.seen.get(r);t.ref=n.innerType},oU=(r,i,$,o)=>{let n=r._zod.def;F(n.innerType,i,o);let t=i.seen.get(r);t.ref=n.innerType},vU=(r,i,$,o)=>{let n=r._zod.innerType;F(n,i,o);let t=i.seen.get(r);t.ref=n},qn={string:N4,number:j4,boolean:z4,bigint:J4,symbol:F4,null:X4,undefined:x4,void:G4,never:Y4,any:Q4,unknown:q4,date:W4,enum:K4,literal:L4,nan:E4,template_literal:V4,file:T4,success:e4,custom:A4,function:B4,transform:R4,map:f4,set:Z4,array:M4,object:H4,union:C4,intersection:h4,tuple:a4,record:y4,nullable:d4,nonoptional:p4,default:s4,prefault:rU,catch:nU,pipe:iU,readonly:tU,promise:$U,optional:oU,lazy:vU};function Wn(r,i){if("_idmap"in r){let o=r,n=vr({...i,processors:qn}),t={};for(let g of o._idmap.entries()){let[c,l]=g;F(l,n)}let v={},u={registry:o,uri:i?.uri,defs:t};n.external=u;for(let g of o._idmap.entries()){let[c,l]=g;ur(n,l),v[c]=cr(n,l)}if(Object.keys(t).length>0){let g=n.target==="draft-2020-12"?"$defs":"definitions";v.__shared={[g]:t}}return{schemas:v}}let $=vr({...i,processors:qn});return F(r,$),ur($,r),cr($,r)}class vu{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(r){this.ctx.counter=r}get seen(){return this.ctx.seen}constructor(r){let i=r?.target??"draft-2020-12";if(i==="draft-4")i="draft-04";if(i==="draft-7")i="draft-07";this.ctx=vr({processors:qn,target:i,...r?.metadata&&{metadata:r.metadata},...r?.unrepresentable&&{unrepresentable:r.unrepresentable},...r?.override&&{override:r.override},...r?.io&&{io:r.io}})}process(r,i={path:[],schemaPath:[]}){return F(r,this.ctx,i)}emit(r,i){if(i){if(i.cycles)this.ctx.cycles=i.cycles;if(i.reused)this.ctx.reused=i.reused;if(i.external)this.ctx.external=i.external}ur(this.ctx,r);let $=cr(this.ctx,r),{"~standard":o,...n}=$;return n}}var Xc={};var z=m("ZodMiniType",(r,i)=>{if(!r._zod)throw Error("Uninitialized schema in ZodMiniType.");N.init(r,i),r.def=i,r.type=i.type,r.parse=($,o)=>tr(r,$,o,{callee:r.parse}),r.safeParse=($,o)=>kr(r,$,o),r.parseAsync=async($,o)=>$r(r,$,o,{callee:r.parseAsync}),r.safeParseAsync=async($,o)=>br(r,$,o),r.check=(...$)=>{return r.clone({...i,checks:[...i.checks??[],...$.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]},{parent:!0})},r.with=r.check,r.clone=($,o)=>L(r,$,o),r.brand=()=>r,r.register=($,o)=>{return $.add(r,o),r},r.apply=($)=>$(r)}),Xr=m("ZodMiniString",(r,i)=>{jr.init(r,i),z.init(r,i)});function Kn(r){return Yo(Xr,r)}var G=m("ZodMiniStringFormat",(r,i)=>{X.init(r,i),Xr.init(r,i)}),xc=m("ZodMiniEmail",(r,i)=>{Ft.init(r,i),G.init(r,i)});function cU(r){return qo(xc,r)}var Gc=m("ZodMiniGUID",(r,i)=>{zt.init(r,i),G.init(r,i)});function gU(r){return Wo(Gc,r)}var dr=m("ZodMiniUUID",(r,i)=>{Jt.init(r,i),G.init(r,i)});function lU(r){return Ko(dr,r)}function mU(r){return Lo(dr,r)}function UU(r){return Eo(dr,r)}function IU(r){return Vo(dr,r)}var uu=m("ZodMiniURL",(r,i)=>{Xt.init(r,i),G.init(r,i)});function kU(r){return Gn(uu,r)}function bU(r){return Gn(uu,{protocol:R.httpProtocol,hostname:R.domain,...b(r)})}var Yc=m("ZodMiniEmoji",(r,i)=>{xt.init(r,i),G.init(r,i)});function _U(r){return To(Yc,r)}var Qc=m("ZodMiniNanoID",(r,i)=>{Gt.init(r,i),G.init(r,i)});function wU(r){return eo(Qc,r)}var qc=m("ZodMiniCUID",(r,i)=>{Yt.init(r,i),G.init(r,i)});function DU(r){return Ao(qc,r)}var Wc=m("ZodMiniCUID2",(r,i)=>{Qt.init(r,i),G.init(r,i)});function SU(r){return Bo(Wc,r)}var Kc=m("ZodMiniULID",(r,i)=>{qt.init(r,i),G.init(r,i)});function PU(r){return Ro(Kc,r)}var Lc=m("ZodMiniXID",(r,i)=>{Wt.init(r,i),G.init(r,i)});function OU(r){return fo(Lc,r)}var Ec=m("ZodMiniKSUID",(r,i)=>{Kt.init(r,i),G.init(r,i)});function NU(r){return Zo(Ec,r)}var Vc=m("ZodMiniIPv4",(r,i)=>{et.init(r,i),G.init(r,i)});function jU(r){return Mo(Vc,r)}var Tc=m("ZodMiniIPv6",(r,i)=>{At.init(r,i),G.init(r,i)});function zU(r){return Ho(Tc,r)}var ec=m("ZodMiniCIDRv4",(r,i)=>{Rt.init(r,i),G.init(r,i)});function JU(r){return ho(ec,r)}var Ac=m("ZodMiniCIDRv6",(r,i)=>{ft.init(r,i),G.init(r,i)});function FU(r){return ao(Ac,r)}var Bc=m("ZodMiniMAC",(r,i)=>{Bt.init(r,i),G.init(r,i)});function XU(r){return Co(Bc,r)}var Rc=m("ZodMiniBase64",(r,i)=>{Mt.init(r,i),G.init(r,i)});function xU(r){return yo(Rc,r)}var fc=m("ZodMiniBase64URL",(r,i)=>{Ht.init(r,i),G.init(r,i)});function GU(r){return po(fc,r)}var Zc=m("ZodMiniE164",(r,i)=>{Ct.init(r,i),G.init(r,i)});function YU(r){return so(Zc,r)}var Mc=m("ZodMiniJWT",(r,i)=>{ht.init(r,i),G.init(r,i)});function QU(r){return rv(Mc,r)}var pr=m("ZodMiniCustomStringFormat",(r,i)=>{at.init(r,i),G.init(r,i)});function qU(r,i,$={}){return Jr(pr,r,i,$)}function WU(r){return Jr(pr,"hostname",R.hostname,r)}function KU(r){return Jr(pr,"hex",R.hex,r)}function LU(r,i){let $=i?.enc??"hex",o=`${r}_${$}`,n=R[o];if(!n)throw Error(`Unrecognized hash format: ${o}`);return Jr(pr,o,n,i)}var sr=m("ZodMiniNumber",(r,i)=>{Nn.init(r,i),z.init(r,i)});function Hc(r){return vv(sr,r)}var xr=m("ZodMiniNumberFormat",(r,i)=>{yt.init(r,i),sr.init(r,i)});function EU(r){return cv(xr,r)}function VU(r){return gv(xr,r)}function TU(r){return lv(xr,r)}function eU(r){return mv(xr,r)}function AU(r){return Uv(xr,r)}var rn=m("ZodMiniBoolean",(r,i)=>{Br.init(r,i),z.init(r,i)});function Cc(r){return Iv(rn,r)}var nn=m("ZodMiniBigInt",(r,i)=>{jn.init(r,i),z.init(r,i)});function BU(r){return bv(nn,r)}var cu=m("ZodMiniBigIntFormat",(r,i)=>{dt.init(r,i),nn.init(r,i)});function RU(r){return wv(cu,r)}function fU(r){return Dv(cu,r)}var hc=m("ZodMiniSymbol",(r,i)=>{pt.init(r,i),z.init(r,i)});function ZU(r){return Sv(hc,r)}var ac=m("ZodMiniUndefined",(r,i)=>{st.init(r,i),z.init(r,i)});function MU(r){return Pv(ac,r)}var yc=m("ZodMiniNull",(r,i)=>{r$.init(r,i),z.init(r,i)});function dc(r){return Ov(yc,r)}var pc=m("ZodMiniAny",(r,i)=>{n$.init(r,i),z.init(r,i)});function HU(){return Nv(pc)}var sc=m("ZodMiniUnknown",(r,i)=>{i$.init(r,i),z.init(r,i)});function Ln(){return jv(sc)}var rg=m("ZodMiniNever",(r,i)=>{t$.init(r,i),z.init(r,i)});function ng(r){return zv(rg,r)}var ig=m("ZodMiniVoid",(r,i)=>{$$.init(r,i),z.init(r,i)});function CU(r){return Jv(ig,r)}var En=m("ZodMiniDate",(r,i)=>{o$.init(r,i),z.init(r,i)});function hU(r){return Fv(En,r)}var tg=m("ZodMiniArray",(r,i)=>{v$.init(r,i),z.init(r,i)});function gu(r,i){return new tg({type:"array",element:r,...b(i)})}function aU(r){let i=r._zod.def.shape;return Ig(Object.keys(i))}var Vn=m("ZodMiniObject",(r,i)=>{zn.init(r,i),z.init(r,i),J(r,"shape",()=>i.shape)});function yU(r,i){let $={type:"object",shape:r??{},...b(i)};return new Vn($)}function dU(r,i){return new Vn({type:"object",shape:r,catchall:ng(),...b(i)})}function pU(r,i){return new Vn({type:"object",shape:r,catchall:Ln(),...b(i)})}function sU(r,i){return gn(r,i)}function r6(r,i){return Ui(r,i)}function n6(r,i){return gn(r,i)}function i6(r,i){return li(r,i)}function t6(r,i){return mi(r,i)}function $6(r,i){return Ii(Uu,r,i)}function o6(r,i){return ki(Iu,r,i)}function v6(r,i){return r.clone({...r._zod.def,catchall:i})}var lu=m("ZodMiniUnion",(r,i)=>{Rr.init(r,i),z.init(r,i)});function $g(r,i){return new lu({type:"union",options:r,...b(i)})}var og=m("ZodMiniXor",(r,i)=>{lu.init(r,i),u$.init(r,i)});function u6(r,i){return new og({type:"union",options:r,inclusive:!1,...b(i)})}var vg=m("ZodMiniDiscriminatedUnion",(r,i)=>{c$.init(r,i),z.init(r,i)});function c6(r,i,$){return new vg({type:"union",options:i,discriminator:r,...b($)})}var ug=m("ZodMiniIntersection",(r,i)=>{g$.init(r,i),z.init(r,i)});function g6(r,i){return new ug({type:"intersection",left:r,right:i})}var cg=m("ZodMiniTuple",(r,i)=>{Jn.init(r,i),z.init(r,i)});function gg(r,i,$){let o=i instanceof N;return new cg({type:"tuple",items:r,rest:o?i:null,...b(o?$:i)})}var yr=m("ZodMiniRecord",(r,i)=>{l$.init(r,i),z.init(r,i)});function lg(r,i,$){if(!i||!i._zod)return new yr({type:"record",keyType:Kn(),valueType:r,...b(i)});return new yr({type:"record",keyType:r,valueType:i,...b($)})}function l6(r,i,$){let o=L(r);return o._zod.values=void 0,new yr({type:"record",keyType:o,valueType:i,...b($)})}function m6(r,i,$){return new yr({type:"record",keyType:r,valueType:i,mode:"loose",...b($)})}var mg=m("ZodMiniMap",(r,i)=>{m$.init(r,i),z.init(r,i)});function U6(r,i,$){return new mg({type:"map",keyType:r,valueType:i,...b($)})}var Ug=m("ZodMiniSet",(r,i)=>{U$.init(r,i),z.init(r,i)});function I6(r,i){return new Ug({type:"set",valueType:r,...b(i)})}var mu=m("ZodMiniEnum",(r,i)=>{I$.init(r,i),z.init(r,i),r.options=Object.values(i.entries)});function Ig(r,i){let $=Array.isArray(r)?Object.fromEntries(r.map((o)=>[o,o])):r;return new mu({type:"enum",entries:$,...b(i)})}function k6(r,i){return new mu({type:"enum",entries:r,...b(i)})}var kg=m("ZodMiniLiteral",(r,i)=>{k$.init(r,i),z.init(r,i)});function b6(r,i){return new kg({type:"literal",values:Array.isArray(r)?r:[r],...b(i)})}var bg=m("ZodMiniFile",(r,i)=>{b$.init(r,i),z.init(r,i)});function _6(r){return pv(bg,r)}var _g=m("ZodMiniTransform",(r,i)=>{_$.init(r,i),z.init(r,i)});function w6(r){return new _g({type:"transform",transform:r})}var Uu=m("ZodMiniOptional",(r,i)=>{Fn.init(r,i),z.init(r,i)});function wg(r){return new Uu({type:"optional",innerType:r})}var Dg=m("ZodMiniExactOptional",(r,i)=>{w$.init(r,i),z.init(r,i)});function D6(r){return new Dg({type:"optional",innerType:r})}var Sg=m("ZodMiniNullable",(r,i)=>{D$.init(r,i),z.init(r,i)});function Pg(r){return new Sg({type:"nullable",innerType:r})}function S6(r){return wg(Pg(r))}var Og=m("ZodMiniDefault",(r,i)=>{S$.init(r,i),z.init(r,i)});function P6(r,i){return new Og({type:"default",innerType:r,get defaultValue(){return typeof i==="function"?i():Pr(i)}})}var Ng=m("ZodMiniPrefault",(r,i)=>{P$.init(r,i),z.init(r,i)});function O6(r,i){return new Ng({type:"prefault",innerType:r,get defaultValue(){return typeof i==="function"?i():Pr(i)}})}var Iu=m("ZodMiniNonOptional",(r,i)=>{O$.init(r,i),z.init(r,i)});function N6(r,i){return new Iu({type:"nonoptional",innerType:r,...b(i)})}var jg=m("ZodMiniSuccess",(r,i)=>{N$.init(r,i),z.init(r,i)});function j6(r){return new jg({type:"success",innerType:r})}var zg=m("ZodMiniCatch",(r,i)=>{j$.init(r,i),z.init(r,i)});function z6(r,i){return new zg({type:"catch",innerType:r,catchValue:typeof i==="function"?i:()=>i})}var Jg=m("ZodMiniNaN",(r,i)=>{z$.init(r,i),z.init(r,i)});function J6(r){return xv(Jg,r)}var ku=m("ZodMiniPipe",(r,i)=>{Xn.init(r,i),z.init(r,i)});function F6(r,i){return new ku({type:"pipe",in:r,out:i})}var Tn=m("ZodMiniCodec",(r,i)=>{ku.init(r,i),fr.init(r,i)});function X6(r,i,$){return new Tn({type:"pipe",in:r,out:i,transform:$.decode,reverseTransform:$.encode})}function x6(r){let i=r._zod.def;return new Tn({type:"pipe",in:i.out,out:i.in,transform:i.reverseTransform,reverseTransform:i.transform})}var Fg=m("ZodMiniReadonly",(r,i)=>{J$.init(r,i),z.init(r,i)});function G6(r){return new Fg({type:"readonly",innerType:r})}var Xg=m("ZodMiniTemplateLiteral",(r,i)=>{F$.init(r,i),z.init(r,i)});function Y6(r,i){return new Xg({type:"template_literal",parts:r,...b(i)})}var xg=m("ZodMiniLazy",(r,i)=>{G$.init(r,i),z.init(r,i)});function Gg(r){return new xg({type:"lazy",getter:r})}var Yg=m("ZodMiniPromise",(r,i)=>{x$.init(r,i),z.init(r,i)});function Q6(r){return new Yg({type:"promise",innerType:r})}var bu=m("ZodMiniCustom",(r,i)=>{Y$.init(r,i),z.init(r,i)});function q6(r,i){let $=new x({check:"custom",...b(i)});return $._zod.check=r,$}function Qg(r,i){return sv(bu,r??(()=>!0),i)}function W6(r,i={}){return ru(bu,r,i)}function K6(r,i){return nu(r,i)}var L6=iu,E6=tu;function V6(r,i={}){let $=Qg((o)=>o instanceof r,i);return $._zod.bag.Class=r,$._zod.check=(o)=>{if(!(o.value instanceof r))o.issues.push({code:"invalid_type",expected:r.name,input:o.value,inst:$,path:[...$._zod.def.path??[]]})},$}var T6=(...r)=>$u({Codec:Tn,Boolean:rn,String:Xr},...r);function e6(){let r=Gg(()=>{return $g([Kn(),Hc(),Cc(),dc(),gu(r),lg(Kn(),r)])});return r}var qg=m("ZodMiniFunction",(r,i)=>{X$.init(r,i),z.init(r,i)});function A6(r){return new qg({type:"function",input:Array.isArray(r?.input)?gg(r?.input):r?.input??gu(Ln()),output:r?.output??Ln()})}var _u={};mr(_u,{time:()=>f6,duration:()=>Z6,datetime:()=>B6,date:()=>R6,ZodMiniISOTime:()=>Bn,ZodMiniISODuration:()=>Rn,ZodMiniISODateTime:()=>en,ZodMiniISODate:()=>An});var en=m("ZodMiniISODateTime",(r,i)=>{Lt.init(r,i),G.init(r,i)});function B6(r){return iv(en,r)}var An=m("ZodMiniISODate",(r,i)=>{Et.init(r,i),G.init(r,i)});function R6(r){return tv(An,r)}var Bn=m("ZodMiniISOTime",(r,i)=>{Vt.init(r,i),G.init(r,i)});function f6(r){return $v(Bn,r)}var Rn=m("ZodMiniISODuration",(r,i)=>{Tt.init(r,i),G.init(r,i)});function Z6(r){return ov(Rn,r)}var wu={};mr(wu,{string:()=>M6,number:()=>H6,date:()=>a6,boolean:()=>C6,bigint:()=>h6});function M6(r){return Qo(Xr,r)}function H6(r){return uv(sr,r)}function C6(r){return kv(rn,r)}function h6(r){return _v(nn,r)}function a6(r){return Xv(En,r)}var y;((j)=>{j.MESSAGE_SENT="message.sent";j.MESSAGE_DELIVERED="message.delivered";j.MESSAGE_FAILED="message.failed";j.MESSAGE_CLICKED="message.clicked";j.MESSAGE_READ="message.read";j.TEMPLATE_CREATED="template.created";j.TEMPLATE_APPROVED="template.approved";j.TEMPLATE_REJECTED="template.rejected";j.TEMPLATE_UPDATED="template.updated";j.TEMPLATE_DELETED="template.deleted";j.CHANNEL_CREATED="channel.created";j.CHANNEL_VERIFIED="channel.verified";j.SENDER_NUMBER_ADDED="sender_number.added";j.SENDER_NUMBER_VERIFIED="sender_number.verified";j.QUOTA_WARNING="system.quota_warning";j.QUOTA_EXCEEDED="system.quota_exceeded";j.PROVIDER_ERROR="system.provider_error";j.SYSTEM_MAINTENANCE="system.maintenance";j.ANOMALY_DETECTED="analytics.anomaly_detected";j.THRESHOLD_EXCEEDED="analytics.threshold_exceeded"})(y||={});var y6=D.object({providerId:D.optional(D.string()),channelId:D.optional(D.string()),templateId:D.optional(D.string()),messageId:D.optional(D.string()),userId:D.optional(D.string()),organizationId:D.optional(D.string()),correlationId:D.optional(D.string()),retryCount:D.optional(D.number())}),d6=D.object({maxRetries:D.number().check(D.minimum(0),D.maximum(10)),retryDelayMs:D.number().check(D.minimum(1000)),backoffMultiplier:D.number().check(D.minimum(1),D.maximum(5))}),p6=D.object({providerId:D.optional(D.array(D.string())),channelId:D.optional(D.array(D.string())),templateId:D.optional(D.array(D.string()))}),s6=D.object({attemptNumber:D.number(),timestamp:D.date(),httpStatus:D.optional(D.number()),responseBody:D.optional(D.string()),responseHeaders:D.optional(D.record(D.string(),D.string())),error:D.optional(D.string()),latencyMs:D.number()}),I_=D.object({id:D.string(),type:D.nativeEnum(y),timestamp:D.pipe(D.transform((r)=>{if(r instanceof Date)return r;if(typeof r==="string"||typeof r==="number")return new Date(r);return r}),D.date()),data:D.any(),metadata:y6,version:D.string()}),k_=D.object({id:D.string(),url:D.url(),name:D.optional(D.string()),description:D.optional(D.string()),active:D.boolean(),events:D.array(D.nativeEnum(y)),headers:D.optional(D.record(D.string(),D.string())),secret:D.optional(D.string()),retryConfig:D.optional(d6),filters:D.optional(p6),createdAt:D.date(),updatedAt:D.date(),lastTriggeredAt:D.optional(D.date()),status:D.enum(["active","inactive","error","suspended"])}),b_=D.object({id:D.string(),endpointId:D.string(),eventId:D.string(),eventType:D.optional(D.nativeEnum(y)),url:D.url(),httpMethod:D.enum(["POST","PUT","PATCH"]),headers:D.record(D.string(),D.string()),payload:D.string(),attempts:D.array(s6),status:D.enum(["pending","success","failed","exhausted"]),createdAt:D.date(),completedAt:D.optional(D.date()),nextRetryAt:D.optional(D.date())});class Kg extends B{config;endpoints=new Map;indexByUrl=new Map;indexByEvent=new Map;indexByStatus=new Map;defaultConfig={type:"memory",retentionDays:90};constructor(r={}){super();if(this.config={...this.defaultConfig,...r},this.initializeIndexes(),this.config.type==="file"&&this.config.filePath)this.loadFromFile().catch((i)=>{this.emit("loadError",i)})}async addEndpoint(r){if(this.indexByUrl.has(r.url)){if(this.indexByUrl.get(r.url)!==r.id)throw Error(`Endpoint with URL ${r.url} already exists with different ID`)}let i=this.endpoints.get(r.id);if(i)this.removeFromIndexes(i);if(this.endpoints.set(r.id,r),this.addToIndexes(r),this.config.type==="file")await this.saveToFile();this.emit("endpointAdded",{endpointId:r.id,url:r.url})}async updateEndpoint(r,i){let $=this.endpoints.get(r);if(!$)throw Error(`Endpoint ${r} not found`);if(i.url&&i.url!==$.url){if(this.indexByUrl.has(i.url)){if(this.indexByUrl.get(i.url)!==r)throw Error(`Endpoint with URL ${i.url} already exists`)}}this.removeFromIndexes($);let o={...$,...i,updatedAt:new Date};if(this.endpoints.set(r,o),this.addToIndexes(o),this.config.type==="file")await this.saveToFile();return this.emit("endpointUpdated",{endpointId:r,changes:Object.keys(i),oldUrl:$.url,newUrl:o.url}),o}async removeEndpoint(r){let i=this.endpoints.get(r);if(!i)return!1;if(this.removeFromIndexes(i),this.endpoints.delete(r),this.config.type==="file")await this.saveToFile();return this.emit("endpointRemoved",{endpointId:r,url:i.url}),!0}async getEndpoint(r){return this.endpoints.get(r)||null}async getEndpointByUrl(r){let i=this.indexByUrl.get(r);return i?this.endpoints.get(i)||null:null}async searchEndpoints(r={},i={page:1,limit:100}){let $=null;if(r.status){let c=this.indexByStatus.get(r.status);$=c?new Set(c):new Set}if(r.events&&r.events.length>0){let c=new Set;for(let l of r.events){let I=this.indexByEvent.get(l);if(I)I.forEach((_)=>{c.add(_)})}if($)$=new Set(Array.from($).filter((l)=>c.has(l)));else $=c}if(!$)$=new Set(this.endpoints.keys());let o=Array.from($).map((c)=>this.endpoints.get(c)).filter((c)=>this.matchesFilter(c,r));if(i.sortBy)o.sort((c,l)=>{let I=this.getFieldValue(c,i.sortBy),_=this.getFieldValue(l,i.sortBy),k=0;if(I<_)k=-1;else if(I>_)k=1;return i.sortOrder==="desc"?-k:k});let n=o.length,t=Math.ceil(n/i.limit),v=(i.page-1)*i.limit,u=v+i.limit;return{items:o.slice(v,u),totalCount:n,page:i.page,totalPages:t,hasNext:i.page<t,hasPrevious:i.page>1}}async getActiveEndpointsForEvent(r){let i=this.indexByEvent.get(r);if(!i)return[];return Array.from(i).map(($)=>this.endpoints.get($)).filter(($)=>$.status==="active")}getStats(){let r=this.endpoints.size,i=this.indexByStatus.get("active")?.size||0,$=this.indexByStatus.get("inactive")?.size||0,o=this.indexByStatus.get("error")?.size||0,n=this.indexByStatus.get("suspended")?.size||0,t={};for(let[v,u]of this.indexByEvent.entries())t[v]=u.size;return{totalEndpoints:r,activeEndpoints:i,inactiveEndpoints:$,errorEndpoints:o,suspendedEndpoints:n,eventSubscriptions:t}}async cleanupExpiredEndpoints(){if(!this.config.retentionDays)return 0;let r=new Date;r.setDate(r.getDate()-this.config.retentionDays);let i=Array.from(this.endpoints.values()).filter(($)=>{return $.status==="inactive"&&(!$.lastTriggeredAt||$.lastTriggeredAt<r)});for(let $ of i)await this.removeEndpoint($.id);if(i.length>0)this.emit("expiredEndpointsCleanup",{removedCount:i.length,cutoffDate:r});return i.length}initializeIndexes(){let r=Object.values(y);for(let $ of r)this.indexByEvent.set($,new Set);let i=["active","inactive","error","suspended"];for(let $ of i)this.indexByStatus.set($,new Set)}addToIndexes(r){this.indexByUrl.set(r.url,r.id);let i=this.indexByStatus.get(r.status);if(i)i.add(r.id);for(let $ of r.events){let o=this.indexByEvent.get($);if(o)o.add(r.id)}}removeFromIndexes(r){this.indexByUrl.delete(r.url);let i=this.indexByStatus.get(r.status);if(i)i.delete(r.id);for(let $ of r.events){let o=this.indexByEvent.get($);if(o)o.delete(r.id)}}matchesFilter(r,i){if(i.providerId&&i.providerId.length>0){if(!i.providerId.some((o)=>r.filters?.providerId?.includes(o)))return!1}if(i.channelId&&i.channelId.length>0){if(!i.channelId.some((o)=>r.filters?.channelId?.includes(o)))return!1}if(i.createdAfter&&r.createdAt<i.createdAfter)return!1;if(i.createdBefore&&r.createdAt>i.createdBefore)return!1;if(i.lastTriggeredAfter&&(!r.lastTriggeredAt||r.lastTriggeredAt<i.lastTriggeredAfter))return!1;if(i.lastTriggeredBefore&&(!r.lastTriggeredAt||r.lastTriggeredAt>i.lastTriggeredBefore))return!1;return!0}getFieldValue(r,i){return i.split(".").reduce(($,o)=>$?.[o],r)}async loadFromFile(){if(!this.config.filePath)return;try{let i=await T(this.config.fileAdapter).readFile(this.config.filePath),$=JSON.parse(i);for(let o of $.endpoints||[]){let n={...o,createdAt:new Date(o.createdAt),updatedAt:new Date(o.updatedAt),lastTriggeredAt:o.lastTriggeredAt?new Date(o.lastTriggeredAt):void 0};this.endpoints.set(n.id,n),this.addToIndexes(n)}this.emit("dataLoaded",{filePath:this.config.filePath,endpointCount:this.endpoints.size})}catch(r){if(!p(r))this.emit("loadError",r)}}async saveToFile(){if(!this.config.filePath)return;try{let r=T(this.config.fileAdapter),i={endpoints:Array.from(this.endpoints.values()),savedAt:new Date().toISOString()},$=JSON.stringify(i,null,2);await r.ensureDirForFile(this.config.filePath),await r.writeFile(this.config.filePath,$),this.emit("dataSaved",{filePath:this.config.filePath,endpointCount:this.endpoints.size})}catch(r){throw this.emit("saveError",r),r}}async shutdown(){if(this.config.type==="file")await this.saveToFile().catch((r)=>{this.emit("saveError",r)});this.emit("shutdown",{endpointCount:this.endpoints.size})}}class Lg extends B{config;events=new Map;indexByType=new Map;indexByDate=new Map;indexByProvider=new Map;indexByChannel=new Map;cleanupInterval=null;defaultConfig={type:"memory",retentionDays:7,enableCompression:!1,maxMemoryUsage:52428800};constructor(r={}){super();if(this.config={...this.defaultConfig,...r},this.initializeIndexes(),this.startCleanupTask(),this.config.type==="file"&&this.config.filePath)this.loadFromFile().catch((i)=>{this.emit("loadError",i)})}async saveEvent(r){if(this.events.has(r.id)){this.emit("duplicateEvent",{eventId:r.id});return}if(this.config.type==="memory"&&this.config.maxMemoryUsage)await this.checkMemoryUsage();if(this.events.set(r.id,r),this.addToIndexes(r),this.config.type==="file")await this.appendToFile(r);this.emit("eventSaved",{eventId:r.id,type:r.type,providerId:r.metadata.providerId})}async getEvent(r){return this.events.get(r)||null}async searchEvents(r={},i={page:1,limit:100}){let $=null;if(r.type&&r.type.length>0){let c=new Set;for(let l of r.type){let I=this.indexByType.get(l);if(I)I.forEach((_)=>{c.add(_)})}$=c}if(r.providerId&&r.providerId.length>0){let c=new Set;for(let l of r.providerId){let I=this.indexByProvider.get(l);if(I)I.forEach((_)=>{c.add(_)})}if($)$=new Set(Array.from($).filter((l)=>c.has(l)));else $=c}if(r.channelId&&r.channelId.length>0){let c=new Set;for(let l of r.channelId){let I=this.indexByChannel.get(l);if(I)I.forEach((_)=>{c.add(_)})}if($)$=new Set(Array.from($).filter((l)=>c.has(l)));else $=c}if(r.createdAfter||r.createdBefore){let c=this.getEventIdsByDateRange(r.createdAfter,r.createdBefore);if($)$=new Set(Array.from($).filter((l)=>c.has(l)));else $=c}if(!$)$=new Set(this.events.keys());let o=Array.from($).map((c)=>this.events.get(c)).filter((c)=>this.matchesFilter(c,r));o.sort((c,l)=>{if(i.sortBy==="timestamp"||!i.sortBy){let P=l.timestamp.getTime()-c.timestamp.getTime();return i.sortOrder==="asc"?-P:P}let I=this.getFieldValue(c,i.sortBy),_=this.getFieldValue(l,i.sortBy),k=0;if(I<_)k=-1;else if(I>_)k=1;return i.sortOrder==="desc"?-k:k});let n=o.length,t=Math.ceil(n/i.limit),v=(i.page-1)*i.limit,u=v+i.limit;return{items:o.slice(v,u),totalCount:n,page:i.page,totalPages:t,hasNext:i.page<t,hasPrevious:i.page>1}}async getEventsByType(r,i=100){let $=this.indexByType.get(r);if(!$)return[];return Array.from($).map((o)=>this.events.get(o)).sort((o,n)=>n.timestamp.getTime()-o.timestamp.getTime()).slice(0,i)}async getEventStats(r){let i={createdAfter:r?.start,createdBefore:r?.end},o=(await this.searchEvents(i,{page:1,limit:1e4})).items,n={};for(let g of Object.values(y))n[g]=0;let t={},v={},u={};for(let g of o){if(n[g.type]++,g.metadata.providerId)t[g.metadata.providerId]=(t[g.metadata.providerId]||0)+1;if(g.metadata.channelId)v[g.metadata.channelId]=(v[g.metadata.channelId]||0)+1;let c=g.timestamp.toISOString().substring(0,13);u[c]=(u[c]||0)+1}return{totalEvents:o.length,eventsByType:n,eventsByProvider:t,eventsByChannel:v,eventsPerHour:u}}async cleanupOldEvents(){if(!this.config.retentionDays)return 0;let r=new Date;r.setDate(r.getDate()-this.config.retentionDays);let i=Array.from(this.events.values()).filter(($)=>$.timestamp<r);for(let $ of i)this.removeFromIndexes($),this.events.delete($.id);if(i.length>0){if(this.emit("oldEventsCleanup",{removedCount:i.length,cutoffDate:r}),this.config.type==="file")await this.saveToFile()}return i.length}async cleanupDuplicateEvents(){let r=new Map;for(let $ of this.events.values()){let o=this.generateContentKey($);if(!r.has(o))r.set(o,[]);r.get(o).push($)}let i=0;for(let[$,o]of r.entries())if(o.length>1){o.sort((n,t)=>t.timestamp.getTime()-n.timestamp.getTime());for(let n=1;n<o.length;n++){let t=o[n];this.removeFromIndexes(t),this.events.delete(t.id),i++}}if(i>0){if(this.emit("duplicateEventsCleanup",{removedCount:i}),this.config.type==="file")await this.saveToFile()}return i}getStorageStats(){let r=this.estimateMemoryUsage();return{totalEvents:this.events.size,memoryUsage:r,indexSizes:{byType:this.indexByType.size,byDate:this.indexByDate.size,byProvider:this.indexByProvider.size,byChannel:this.indexByChannel.size}}}initializeIndexes(){let r=Object.values(y);for(let i of r)this.indexByType.set(i,new Set)}addToIndexes(r){let i=this.indexByType.get(r.type);if(i)i.add(r.id);let $=r.timestamp.toISOString().split("T")[0];if(!this.indexByDate.has($))this.indexByDate.set($,new Set);if(this.indexByDate.get($).add(r.id),r.metadata.providerId){if(!this.indexByProvider.has(r.metadata.providerId))this.indexByProvider.set(r.metadata.providerId,new Set);this.indexByProvider.get(r.metadata.providerId).add(r.id)}if(r.metadata.channelId){if(!this.indexByChannel.has(r.metadata.channelId))this.indexByChannel.set(r.metadata.channelId,new Set);this.indexByChannel.get(r.metadata.channelId).add(r.id)}}removeFromIndexes(r){let i=this.indexByType.get(r.type);if(i)i.delete(r.id);let $=r.timestamp.toISOString().split("T")[0],o=this.indexByDate.get($);if(o){if(o.delete(r.id),o.size===0)this.indexByDate.delete($)}if(r.metadata.providerId){let n=this.indexByProvider.get(r.metadata.providerId);if(n){if(n.delete(r.id),n.size===0)this.indexByProvider.delete(r.metadata.providerId)}}if(r.metadata.channelId){let n=this.indexByChannel.get(r.metadata.channelId);if(n){if(n.delete(r.id),n.size===0)this.indexByChannel.delete(r.metadata.channelId)}}}getEventIdsByDateRange(r,i){let $=new Set;for(let[o,n]of this.indexByDate.entries()){let t=new Date(o);if(r&&t<r)continue;if(i&&t>i)continue;n.forEach((v)=>{$.add(v)})}return $}matchesFilter(r,i){if(i.templateId&&i.templateId.length>0){if(!r.metadata.templateId||!i.templateId.includes(r.metadata.templateId))return!1}if(i.messageId&&i.messageId.length>0){if(!r.metadata.messageId||!i.messageId.includes(r.metadata.messageId))return!1}if(i.userId&&i.userId.length>0){if(!r.metadata.userId||!i.userId.includes(r.metadata.userId))return!1}if(i.organizationId&&i.organizationId.length>0){if(!r.metadata.organizationId||!i.organizationId.includes(r.metadata.organizationId))return!1}return!0}getFieldValue(r,i){return i.split(".").reduce(($,o)=>$?.[o],r)}estimateMemoryUsage(){let r=0;for(let i of this.events.values())r+=JSON.stringify(i).length*2;return r}async checkMemoryUsage(){if(!this.config.maxMemoryUsage)return;let r=this.estimateMemoryUsage();if(r>this.config.maxMemoryUsage){let i=Array.from(this.events.values()).sort((n,t)=>n.timestamp.getTime()-t.timestamp.getTime()),$=0,o=this.config.maxMemoryUsage*0.8;for(let n of i){if(this.estimateMemoryUsage()<=o)break;this.removeFromIndexes(n),this.events.delete(n.id),$++}if($>0)this.emit("memoryCleanup",{removedCount:$,previousUsage:r,currentUsage:this.estimateMemoryUsage()})}}generateContentKey(r){return`${r.type}_${r.metadata.messageId||""}_${r.metadata.templateId||""}_${JSON.stringify(r.data)}`}startCleanupTask(){this.cleanupInterval=setInterval(async()=>{try{await this.cleanupOldEvents(),await this.cleanupDuplicateEvents()}catch(r){this.emit("cleanupError",r)}},3600000)}async appendToFile(r){if(!this.config.filePath)return;try{let i=T(this.config.fileAdapter),$=JSON.stringify(r)+`
|
|
70
|
-
`;await i.ensureDirForFile(this.config.filePath),await i.appendFile(this.config.filePath,$)}catch(i){this.emit("appendError",i)}}async loadFromFile(){if(!this.config.filePath)return;try{let $=(await T(this.config.fileAdapter).readFile(this.config.filePath)).trim().split(`
|
|
71
|
-
`).filter((o)=>o.trim());for(let o of $)try{let n=JSON.parse(o),t={...n,timestamp:new Date(n.timestamp)};this.events.set(t.id,t),this.addToIndexes(t)}catch(n){this.emit("parseError",{line:o,error:n})}this.emit("dataLoaded",{filePath:this.config.filePath,eventCount:this.events.size})}catch(r){if(!p(r))this.emit("loadError",r)}}async saveToFile(){if(!this.config.filePath)return;try{let r=T(this.config.fileAdapter),i=Array.from(this.events.values()).map(($)=>JSON.stringify($)).join(`
|
|
72
|
-
`);await r.ensureDirForFile(this.config.filePath),await r.writeFile(this.config.filePath,i+`
|
|
73
|
-
`),this.emit("dataSaved",{filePath:this.config.filePath,eventCount:this.events.size})}catch(r){throw this.emit("saveError",r),r}}async shutdown(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;if(this.config.type==="file")await this.saveToFile().catch((r)=>{this.emit("saveError",r)});this.emit("shutdown",{eventCount:this.events.size})}}class fn{config;constructor(r){this.config={maxRetries:r.maxRetries,baseDelayMs:r.retryDelayMs,maxDelayMs:r.maxDelayMs||300000,backoffMultiplier:r.backoffMultiplier||2,jitter:r.jitter!==!1}}calculateNextRetry(r){if(r>=this.config.maxRetries)throw Error(`Maximum retry attempts (${this.config.maxRetries}) exceeded`);let i=this.config.baseDelayMs*this.config.backoffMultiplier**r;if(i=Math.min(i,this.config.maxDelayMs),this.config.jitter)i=i*(0.5+Math.random()*0.5);return new Date(Date.now()+i)}shouldRetry(r,i){if(r>=this.config.maxRetries)return!1;if(i)return this.isRetryableError(i);return!0}isRetryableError(r){let i=r.message.toLowerCase();return["timeout","network","connection","econnreset","enotfound","econnrefused","socket hang up"].some((o)=>i.includes(o))}shouldRetryStatus(r){if(r>=400&&r<500)return[408,429].includes(r);if(r>=500)return!0;return!1}calculateRetryStats(r){if(r.length===0)return{totalAttempts:0,successfulAttempts:0,failedAttempts:0,averageDelayMs:0,totalTimeMs:0};let i=r.filter((v)=>v.success).length,$=r.length-i,o=0;for(let v=1;v<r.length;v++)o+=r[v].timestamp.getTime()-r[v-1].timestamp.getTime();let n=r.length>1?o/(r.length-1):0,t=r.length>0?r[r.length-1].timestamp.getTime()-r[0].timestamp.getTime():0;return{totalAttempts:r.length,successfulAttempts:i,failedAttempts:$,averageDelayMs:n,totalTimeMs:t}}updateConfig(r){this.config={...this.config,...r}}getConfig(){return{...this.config}}getBackoffDelay(r){let i=this.config.baseDelayMs*this.config.backoffMultiplier**r;return Math.min(i,this.config.maxDelayMs)}}var Su;((Y)=>{Y.INVALID_REQUEST="INVALID_REQUEST";Y.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";Y.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";Y.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";Y.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";Y.NETWORK_ERROR="NETWORK_ERROR";Y.NETWORK_TIMEOUT="NETWORK_TIMEOUT";Y.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";Y.REQUEST_ABORTED="REQUEST_ABORTED";Y.PROVIDER_ERROR="PROVIDER_ERROR";Y.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";Y.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";Y.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";Y.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";Y.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";Y.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";Y.UNKNOWN_ERROR="UNKNOWN_ERROR"})(Su||={});var rI={["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"},["REQUEST_ABORTED"]:{ko:"요청이 취소되었습니다",en:"Request aborted"},["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"}},F_=new Set(Object.values(Su));var Du=(r)=>{if(typeof r!=="number"||Number.isNaN(r)||!Number.isFinite(r))return;return Math.trunc(r)};class Zn extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(r,i,$,o={}){super(i);if(this.name="KMsgError",this.code=r,this.details=$,this.providerErrorCode=o.providerErrorCode,this.providerErrorText=o.providerErrorText,this.httpStatus=Du(o.httpStatus),this.requestId=typeof o.requestId==="string"?o.requestId:void 0,this.retryAfterMs=Du(o.retryAfterMs),this.attempt=Du(o.attempt),Array.isArray(o.causeChain))this.causeChain=o.causeChain;else if(o.causeChain!==void 0)this.causeChain=[o.causeChain];let n=Error.captureStackTrace;if(n)n(this,Zn)}getLocalizedMessage(r="ko"){let i=rI[this.code];if(i?.[r])return i[r];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}}}function nI(r){switch(r){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 Gr extends Zn{kind;fieldPath;failMode;openFallback;constructor(r,i,$,o={}){super(nI(r),i,$,o);this.name="FieldCryptoError",this.kind=r,this.fieldPath=typeof o.fieldPath==="string"?o.fieldPath:void 0,this.failMode=o.failMode,this.openFallback=o.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}function Pu(r){return typeof r==="function"}function Eg(r){if(typeof r!=="string")return;let i=r.trim();return i.length>0?i:void 0}function Vg(r,i,$){let o=r.fields[i];if(o)return o;if(i.startsWith("metadata.")){let n=r.fields["metadata.*"];if(n)return n}return $}function iI(r,i={}){let $=[];if(!r||typeof r!=="object")return{valid:!1,issues:[{message:"fieldCrypto config must be an object",rule:"fieldCrypto.config.object",hint:"Provide a valid FieldCryptoConfig object"}]};if(!r.provider||typeof r.provider!=="object")$.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!Pu(r.provider.encrypt))$.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!Pu(r.provider.decrypt))$.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!Pu(r.provider.hash))$.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!r.fields||typeof r.fields!=="object")$.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 t=Object.entries(r.fields);if(t.length===0)$.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[v,u]of t){if(!Eg(v))$.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(u!=="plain"&&u!=="encrypt"&&u!=="encrypt+hash"&&u!=="mask")$.push({message:`unsupported field mode: ${String(u)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${v}`})}}let o=r.failMode??"closed",n=r.openFallback??"masked";if(o==="open"&&n==="plaintext"&&r.unsafeAllowPlaintextStorage!==!0)$.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(r.aadFields)){if(r.aadFields.length===0)$.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let t=0;t<r.aadFields.length;t+=1){let v=r.aadFields[t];if(!Eg(v))$.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${t}]`})}}if(i.secureMode&&!i.compatPlainColumns){let t=Vg(r,"to","encrypt+hash"),v=Vg(r,"from","encrypt+hash");if(t==="plain")$.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(v==="plain")$.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:$.length===0,issues:$}}function Ou(r,i={}){let $=iI(r,i);if($.valid)return;let o=$.issues[0];if(!o)throw new Gr("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:$.issues});throw new Gr("config",o.message,{rule:o.rule,path:o.path,hint:o.hint,issues:$.issues},{fieldPath:o.path})}function Tg(r=3,i=2){return($)=>{let o=String($??"");if(o.length<=r+i)return"*".repeat(Math.max(0,o.length));let n=o.slice(0,r),t=o.slice(-i);return`${n}${"*".repeat(o.length-r-i)}${t}`}}var tI=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"];function $I(r){let i=r.toLowerCase();return tI.some(($)=>i.includes($.toLowerCase()))}function oI(r){let i=r.trim();if(i.length<=4)return"***";if(i.includes("@")){let[n,t]=i.split("@");return`${n.slice(0,2)}${"*".repeat(Math.max(1,n.length-2))}@${t}`}let $=i.slice(0,3),o=i.slice(-2);return`${$}${"*".repeat(Math.max(1,i.length-5))}${o}`}function ju(r,i){if(i===void 0||i===null)return i;if($I(r)){if(typeof i==="string")return oI(i);if(typeof i==="number"||typeof i==="boolean")return"***";if(Array.isArray(i))return"[REDACTED]";if(typeof i==="object")return"[REDACTED]"}if(Array.isArray(i))return i.map(($)=>ju(r,$));if(typeof i==="object"){let $={};for(let[o,n]of Object.entries(i))$[o]=ju(o,n);return $}return i}function vI(r){let i={};for(let[$,o]of Object.entries(r))i[$]=ju($,o);return i}class zu{config;context;constructor(r={},i={}){this.context=r,this.config={level:"INFO",enableConsole:!0,enableJson:!1,enableColors:!0,...i}}shouldLog(r){let i=["DEBUG","INFO","WARN","ERROR"];return i.indexOf(r)>=i.indexOf(this.config.level)}formatMessage(r){let i=vI(r.context);if(this.config.enableJson)return JSON.stringify({level:r.level,message:r.message,timestamp:r.timestamp.toISOString(),context:i,...r.error&&{error:{name:r.error.name,message:r.error.message,stack:r.error.stack}},...r.duration&&{duration:r.duration}});let $=r.timestamp.toISOString(),o=this.config.enableColors?this.colorizeLevel(r.level):r.level,n=Object.keys(i).length>0?` [${Object.entries(i).map(([v,u])=>`${v}=${u}`).join(", ")}]`:"",t=`${$} ${o}${n}: ${r.message}`;if(r.duration!==void 0)t+=` (${r.duration}ms)`;if(r.error)t+=`
|
|
74
|
-
${r.error.stack}`;return t}colorizeLevel(r){if(!this.config.enableColors)return r;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[r]}${r}\x1B[0m`}writeLog(r){if(!this.shouldLog(r.level))return;let i=this.formatMessage(r);if(this.config.enableConsole)(r.level==="ERROR"?console.error:r.level==="WARN"?console.warn:console.log)(i);if(this.config.enableFile&&this.config.filePath);}debug(r,i={}){this.writeLog({level:"DEBUG",message:r,timestamp:new Date,context:{...this.context,...i}})}info(r,i={}){this.writeLog({level:"INFO",message:r,timestamp:new Date,context:{...this.context,...i}})}warn(r,i={},$){this.writeLog({level:"WARN",message:r,timestamp:new Date,context:{...this.context,...i},error:$})}error(r,i={},$){this.writeLog({level:"ERROR",message:r,timestamp:new Date,context:{...this.context,...i},error:$})}child(r){return new zu({...this.context,...r},this.config)}time(r){let i=Date.now();return()=>{let $=Date.now()-i;this.info(`${r} completed`,{duration:$})}}async measure(r,i,$={}){let o=Date.now(),n={...$,operation:r};this.debug(`Starting ${r}`,n);try{let t=await i(),v=Date.now()-o;return this.info(`Completed ${r}`,{...n,duration:v}),t}catch(t){let v=Date.now()-o;throw this.error(`Failed ${r}`,{...n,duration:v},t instanceof Error?t:Error(String(t))),t}}}var Nu;function uI(r,i){return new zu(r,i)}function wr(){if(!Nu)Nu=uI();return Nu}var eg={debug:(r,i)=>wr().debug(r,i),info:(r,i)=>wr().info(r,i),warn:(r,i,$)=>wr().warn(r,i,$),error:(r,i,$)=>wr().error(r,i,$),child:(r)=>wr().child(r),time:(r)=>wr().time(r),measure:(r,i,$)=>wr().measure(r,i,$)};/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function cI(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ag(r){if(!Number.isSafeInteger(r)||r<0)throw Error("positive integer expected, got "+r)}function Dr(r,...i){if(!cI(r))throw Error("Uint8Array expected");if(i.length>0&&!i.includes(r.length))throw Error("Uint8Array expected of length "+i+", got length="+r.length)}function Bg(r){if(typeof r!=="function"||typeof r.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");Ag(r.outputLen),Ag(r.blockLen)}function Yr(r,i=!0){if(r.destroyed)throw Error("Hash instance has been destroyed");if(i&&r.finished)throw Error("Hash#digest() has already been called")}function Rg(r,i){Dr(r);let $=i.outputLen;if(r.length<$)throw Error("digestInto() expects output buffer of length at least "+$)}function h(...r){for(let i=0;i<r.length;i++)r[i].fill(0)}function Mn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Z(r,i){return r<<32-i|r>>>i}function Hn(r,i){return r<<i|r>>>32-i>>>0}var gI=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),lI=Array.from({length:256},(r,i)=>i.toString(16).padStart(2,"0"));function Ju(r){if(Dr(r),gI)return r.toHex();let i="";for(let $=0;$<r.length;$++)i+=lI[r[$]];return i}function mI(r){if(typeof r!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function tn(r){if(typeof r==="string")r=mI(r);return Dr(r),r}class $n{}function Cn(r){let i=(o)=>r().update(tn(o)).digest(),$=r();return i.outputLen=$.outputLen,i.blockLen=$.blockLen,i.create=()=>r(),i}class Fu extends $n{constructor(r,i){super();this.finished=!1,this.destroyed=!1,Bg(r);let $=tn(i);if(this.iHash=r.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,n=new Uint8Array(o);n.set($.length>o?r.create().update($).digest():$);for(let t=0;t<n.length;t++)n[t]^=54;this.iHash.update(n),this.oHash=r.create();for(let t=0;t<n.length;t++)n[t]^=106;this.oHash.update(n),h(n)}update(r){return Yr(this),this.iHash.update(r),this}digestInto(r){Yr(this),Dr(r,this.outputLen),this.finished=!0,this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let r=new Uint8Array(this.oHash.outputLen);return this.digestInto(r),r}_cloneInto(r){r||(r=Object.create(Object.getPrototypeOf(this),{}));let{oHash:i,iHash:$,finished:o,destroyed:n,blockLen:t,outputLen:v}=this;return r=r,r.finished=o,r.destroyed=n,r.blockLen=t,r.outputLen=v,r.oHash=i._cloneInto(r.oHash),r.iHash=$._cloneInto(r.iHash),r}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var hn=(r,i,$)=>new Fu(r,i).update($).digest();hn.create=(r,i)=>new Fu(r,i);function UI(r,i,$,o){if(typeof r.setBigUint64==="function")return r.setBigUint64(i,$,o);let n=BigInt(32),t=BigInt(4294967295),v=Number($>>n&t),u=Number($&t),g=o?4:0,c=o?0:4;r.setUint32(i+g,v,o),r.setUint32(i+c,u,o)}function an(r,i,$){return r&i^~r&$}function yn(r,i,$){return r&i^r&$^i&$}class on extends $n{constructor(r,i,$,o){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=r,this.outputLen=i,this.padOffset=$,this.isLE=o,this.buffer=new Uint8Array(r),this.view=Mn(this.buffer)}update(r){Yr(this),r=tn(r),Dr(r);let{view:i,buffer:$,blockLen:o}=this,n=r.length;for(let t=0;t<n;){let v=Math.min(o-this.pos,n-t);if(v===o){let u=Mn(r);for(;o<=n-t;t+=o)this.process(u,t);continue}if($.set(r.subarray(t,t+v),this.pos),this.pos+=v,t+=v,this.pos===o)this.process(i,0),this.pos=0}return this.length+=r.length,this.roundClean(),this}digestInto(r){Yr(this),Rg(r,this),this.finished=!0;let{buffer:i,view:$,blockLen:o,isLE:n}=this,{pos:t}=this;if(i[t++]=128,h(this.buffer.subarray(t)),this.padOffset>o-t)this.process($,0),t=0;for(let l=t;l<o;l++)i[l]=0;UI($,o-8,BigInt(this.length*8),n),this.process($,0);let v=Mn(r),u=this.outputLen;if(u%4)throw Error("_sha2: outputLen should be aligned to 32bit");let g=u/4,c=this.get();if(g>c.length)throw Error("_sha2: outputLen bigger than state");for(let l=0;l<g;l++)v.setUint32(4*l,c[l],n)}digest(){let{buffer:r,outputLen:i}=this;this.digestInto(r);let $=r.slice(0,i);return this.destroy(),$}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:i,buffer:$,length:o,finished:n,destroyed:t,pos:v}=this;if(r.destroyed=t,r.finished=n,r.length=o,r.pos=v,o%i)r.buffer.set($);return r}clone(){return this._cloneInto()}}var d=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var vn=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),gr=new Uint32Array(80);class Xu extends on{constructor(){super(64,20,8,!1);this.A=vn[0]|0,this.B=vn[1]|0,this.C=vn[2]|0,this.D=vn[3]|0,this.E=vn[4]|0}get(){let{A:r,B:i,C:$,D:o,E:n}=this;return[r,i,$,o,n]}set(r,i,$,o,n){this.A=r|0,this.B=i|0,this.C=$|0,this.D=o|0,this.E=n|0}process(r,i){for(let u=0;u<16;u++,i+=4)gr[u]=r.getUint32(i,!1);for(let u=16;u<80;u++)gr[u]=Hn(gr[u-3]^gr[u-8]^gr[u-14]^gr[u-16],1);let{A:$,B:o,C:n,D:t,E:v}=this;for(let u=0;u<80;u++){let g,c;if(u<20)g=an(o,n,t),c=1518500249;else if(u<40)g=o^n^t,c=1859775393;else if(u<60)g=yn(o,n,t),c=2400959708;else g=o^n^t,c=3395469782;let l=Hn($,5)+g+v+c+gr[u]|0;v=t,t=n,n=Hn(o,30),o=$,$=l}$=$+this.A|0,o=o+this.B|0,n=n+this.C|0,t=t+this.D|0,v=v+this.E|0,this.set($,o,n,t,v)}roundClean(){h(gr)}destroy(){this.set(0,0,0,0,0),h(this.buffer)}}var fg=Cn(()=>new Xu);var Zg=fg;var II=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),lr=new Uint32Array(64);class Mg extends on{constructor(r=32){super(64,r,8,!1);this.A=d[0]|0,this.B=d[1]|0,this.C=d[2]|0,this.D=d[3]|0,this.E=d[4]|0,this.F=d[5]|0,this.G=d[6]|0,this.H=d[7]|0}get(){let{A:r,B:i,C:$,D:o,E:n,F:t,G:v,H:u}=this;return[r,i,$,o,n,t,v,u]}set(r,i,$,o,n,t,v,u){this.A=r|0,this.B=i|0,this.C=$|0,this.D=o|0,this.E=n|0,this.F=t|0,this.G=v|0,this.H=u|0}process(r,i){for(let l=0;l<16;l++,i+=4)lr[l]=r.getUint32(i,!1);for(let l=16;l<64;l++){let I=lr[l-15],_=lr[l-2],k=Z(I,7)^Z(I,18)^I>>>3,P=Z(_,17)^Z(_,19)^_>>>10;lr[l]=P+lr[l-7]+k+lr[l-16]|0}let{A:$,B:o,C:n,D:t,E:v,F:u,G:g,H:c}=this;for(let l=0;l<64;l++){let I=Z(v,6)^Z(v,11)^Z(v,25),_=c+I+an(v,u,g)+II[l]+lr[l]|0,P=(Z($,2)^Z($,13)^Z($,22))+yn($,o,n)|0;c=g,g=u,u=v,v=t+_|0,t=n,n=o,o=$,$=_+P|0}$=$+this.A|0,o=o+this.B|0,n=n+this.C|0,t=t+this.D|0,v=v+this.E|0,u=u+this.F|0,g=g+this.G|0,c=c+this.H|0,this.set($,o,n,t,v,u,g,c)}roundClean(){h(lr)}destroy(){this.set(0,0,0,0,0,0,0,0),h(this.buffer)}}var Hg=Cn(()=>new Mg);class dn{config;encoder=new TextEncoder;constructor(r){this.config={algorithm:r.algorithm||"sha256",header:r.signatureHeader||"X-Webhook-Signature",prefix:r.signaturePrefix||"sha256="}}createSignedPayload(r,i){return`${i}.${r}`}generateSignature(r,i){let $=this.generateSignatureDigest(r,i);return this.config.prefix?`${this.config.prefix}${$}`:$}generateSignatureWithTimestamp(r,i,$){return this.generateSignature(this.createSignedPayload(r,i),$)}verifySignature(r,i,$){try{let o=this.generateSignature(r,$);return this.constantTimeCompare(i,o)}catch(o){return eg.error("Signature verification failed",void 0,o instanceof Error?o:Error(String(o))),!1}}verifySignatureWithTimestamp(r,i,$,o){return this.verifySignature(this.createSignedPayload(r,i),$,o)}extractSignature(r){let i=this.config.header.toLowerCase();for(let[$,o]of Object.entries(r))if($.toLowerCase()===i)return o;return null}createSecurityHeaders(r,i){let $=Math.floor(Date.now()/1000).toString(),o=this.generateSignatureWithTimestamp(r,$,i);return{[this.config.header]:o,"X-Webhook-Timestamp":$,"X-Webhook-ID":this.generateWebhookId(),"User-Agent":"K-Message-Webhook/1.0"}}verifyTimestamp(r,i=300){try{let $=(()=>{if(/^[0-9]+$/.test(r.trim()))return parseInt(r,10);let t=new Date(r);if(Number.isNaN(t.getTime()))return NaN;return Math.floor(t.getTime()/1000)})(),o=Math.floor(Date.now()/1000);return Math.abs(o-$)<=i}catch{return!1}}generateWebhookId(){let r=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(r);else for(let i=0;i<r.length;i++)r[i]=Math.floor(Math.random()*256);return`wh_${Ju(r)}`}generateSignatureDigest(r,i){let $=this.encoder.encode(i),o=this.encoder.encode(r),n=this.config.algorithm==="sha1"?hn(Zg,$,o):hn(Hg,$,o);return Ju(n)}constantTimeCompare(r,i){if(r.length!==i.length)return!1;let $=0;for(let o=0;o<r.length;o++)$|=r.charCodeAt(o)^i.charCodeAt(o);return $===0}updateConfig(r){this.config={...this.config,...r}}getConfig(){return{...this.config}}}class xu{async fetch(r,i){return fetch(r,i)}}class Cg{responses=new Map;defaultResponse=new Response(JSON.stringify({status:"ok"}),{status:200,statusText:"OK",headers:{"content-type":"application/json"}});setMockResponse(r,i){this.responses.set(r,i)}setDefaultResponse(r){this.defaultResponse=r}async fetch(r,i){let $=this.responses.get(r);if($)return $;return this.defaultResponse}}class hg{config;httpClient;securityManager;retryManager;constructor(r,i){this.config=r,this.httpClient=i||new xu,this.securityManager=new dn(r),this.retryManager=new fn(r)}async dispatch(r,i){let $=JSON.stringify(r),o=(()=>{if(r.timestamp instanceof Date)return r.timestamp;let v=new Date(r.timestamp);return Number.isNaN(v.getTime())?new Date:v})(),n=Math.floor(o.getTime()/1000).toString(),t={id:this.generateDeliveryId(),endpointId:i.id,eventId:r.id,eventType:r.type,url:i.url,httpMethod:"POST",headers:this.buildHeaders(i,r,$,n),payload:$,attempts:[],status:"pending",createdAt:new Date};return await this.executeDelivery(t,i),t}async executeDelivery(r,i){let $=i.retryConfig?.maxRetries||this.config.maxRetries;for(let o=1;o<=$+1;o++){let n=await this.makeHttpRequest(r,i,o);if(r.attempts.push(n),n.httpStatus&&n.httpStatus>=200&&n.httpStatus<300){r.status="success",r.completedAt=new Date;return}if(!(o<=$&&this.shouldRetryAttempt(o,n))){r.status="failed",r.completedAt=new Date;return}let v=this.calculateRetryDelay(o,i);r.nextRetryAt=new Date(Date.now()+v),await this.sleep(v)}r.status="exhausted",r.completedAt=new Date}shouldRetryAttempt(r,i){if(typeof i.httpStatus==="number")return this.retryManager.shouldRetryStatus(i.httpStatus);if(i.error)return this.retryManager.shouldRetry(r,Error(i.error));return!0}async makeHttpRequest(r,i,$){let o=Date.now(),n={attemptNumber:$,timestamp:new Date,latencyMs:0};try{let t=await this.httpClient.fetch(r.url,{method:r.httpMethod,headers:r.headers,body:r.payload,signal:AbortSignal.timeout(this.config.timeoutMs)});n.httpStatus=t.status,n.responseBody=await t.text();let v={};if(t.headers.forEach((u,g)=>{v[g]=u}),n.responseHeaders=v,n.latencyMs=Date.now()-o,!t.ok)n.error=`HTTP ${t.status}: ${t.statusText}`}catch(t){n.latencyMs=Date.now()-o,n.error=t instanceof Error?t.message:"Unknown error"}return n}buildHeaders(r,i,$,o){let n={"Content-Type":"application/json","X-Webhook-ID":i.id,"X-Webhook-Event":i.type,"X-Webhook-Timestamp":o,"User-Agent":"K-Message-Webhook/1.0"};if(r.headers)Object.assign(n,r.headers);if(this.config.enableSecurity){let t=(typeof r.secret==="string"&&r.secret.length>0?r.secret:typeof this.config.secretKey==="string"&&this.config.secretKey.length>0?this.config.secretKey:void 0)||void 0;if(t){let v=this.securityManager.generateSignatureWithTimestamp($,o,t),u=this.securityManager.getConfig().header;n[u]=v}}return n}calculateRetryDelay(r,i){let $=i.retryConfig?.retryDelayMs||this.config.retryDelayMs,o=i.retryConfig?.backoffMultiplier||this.config.backoffMultiplier||2,n=$*o**r;if(typeof this.config.maxDelayMs==="number")n=Math.min(n,this.config.maxDelayMs);if(this.config.jitter!==!1)n=n*(0.5+Math.random()*0.5);return Math.max(0,Math.floor(n))}sleep(r){return new Promise((i)=>setTimeout(i,r))}generateDeliveryId(){return`delivery_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}async shutdown(){}}function Gu(r){if(typeof r!=="string")return;let i=r.trim();return i.length>0?i:void 0}function dg(r,i){let $=r.openFallback??"masked";if($==="plaintext"){if(!r.unsafeAllowPlaintextStorage)throw new Gr("policy","openFallback=plaintext requires unsafeAllowPlaintextStorage=true",{rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback"},{fieldPath:"openFallback",failMode:"open",openFallback:"plaintext"});return i}if($==="null")return"";return Tg()(i)}async function ag(r,i){let $=Gu(i.value);if(!$)return;if(!r||r.enabled===!1)return $;let o=r.failMode??"closed",n=r.keyResolver;try{let t={tenantId:i.tenantId,tableName:i.aad.tableName,fieldPath:i.path,messageId:i.aad.messageId,providerId:i.aad.providerId},v=n?Gu((await n.resolveEncryptKey(t)).kid):void 0,u=await r.provider.encrypt({value:$,path:i.path,aad:i.aad,...v?{kid:v}:{}});return typeof u.ciphertext==="string"?u.ciphertext:JSON.stringify(u.ciphertext)}catch(t){if(o==="closed")throw t;return dg(r,$)}}async function yg(r,i){let $=Gu(i.value);if(!$)return;if(!r||r.enabled===!1)return $;let o=r.failMode??"closed";try{let n={tenantId:i.tenantId,tableName:i.aad.tableName,fieldPath:i.path,messageId:i.aad.messageId,providerId:i.aad.providerId},t=r.keyResolver?.resolveDecryptKeys?await r.keyResolver.resolveDecryptKeys({...n,ciphertext:$}):void 0;return await r.provider.decrypt({ciphertext:$,path:i.path,aad:i.aad,...Array.isArray(t)&&t.length>0?{candidateKids:t}:{}})}catch(n){if(o==="closed")throw n;return dg(r,$)}}class pg{endpoints=new Map;deliveries=new Map;options;constructor(r={}){this.options=r,this.validateCryptoOptions(this.options.fieldCrypto)}async addEndpoint(r){this.endpoints.set(r.id,await this.protectEndpoint(r))}async updateEndpoint(r,i){if(!this.endpoints.has(r))throw Error(`Endpoint ${r} not found`);this.endpoints.set(r,await this.protectEndpoint(i))}async removeEndpoint(r){this.endpoints.delete(r)}async getEndpoint(r){let i=this.endpoints.get(r);if(!i)return null;return await this.revealEndpoint(i)}async listEndpoints(){return await Promise.all(Array.from(this.endpoints.values()).map((r)=>this.revealEndpoint(r)))}async addDelivery(r){this.deliveries.set(r.id,await this.protectDelivery(r))}async getDeliveries(r,i,$,o,n=100){let t=Array.from(this.deliveries.values());if(r)t=t.filter((u)=>u.endpointId===r);if(i)t=t.filter((u)=>u.createdAt>=i.start&&u.createdAt<=i.end);if($)t=t.filter((u)=>u.eventType===$);if(o)t=t.filter((u)=>u.status===o);let v=t.sort((u,g)=>g.createdAt.getTime()-u.createdAt.getTime()).slice(0,n);return await Promise.all(v.map((u)=>this.revealDelivery(u)))}async getFailedDeliveries(r,i){return(await this.getDeliveries(r,void 0,i,void 0,1000)).filter((o)=>o.status==="failed"||o.status==="exhausted")}async protectEndpoint(r){let i={tableName:"webhook_endpoint",messageId:r.id},$=await ag(this.options.fieldCrypto?.endpoint,{value:r.secret,path:"secret",aad:i,tenantId:this.options.fieldCrypto?.tenantId});return{...r,...$?{secret:$}:{}}}async revealEndpoint(r){let i={tableName:"webhook_endpoint",messageId:r.id},$=await yg(this.options.fieldCrypto?.endpoint,{value:r.secret,path:"secret",aad:i,tenantId:this.options.fieldCrypto?.tenantId});return{...r,...$?{secret:$}:{}}}async protectDelivery(r){let i={tableName:"webhook_delivery",messageId:r.id,providerId:r.endpointId},$=await ag(this.options.fieldCrypto?.delivery,{value:r.payload,path:"payload",aad:i,tenantId:this.options.fieldCrypto?.tenantId});return{...r,payload:$??r.payload}}async revealDelivery(r){let i={tableName:"webhook_delivery",messageId:r.id,providerId:r.endpointId},$=await yg(this.options.fieldCrypto?.delivery,{value:r.payload,path:"payload",aad:i,tenantId:this.options.fieldCrypto?.tenantId});return{...r,payload:$??r.payload}}validateCryptoOptions(r){if(!r)return;if(r.endpoint)Ou(r.endpoint);if(r.delivery)Ou(r.delivery)}}export{pg as WebhookRegistry,hg as WebhookDispatcher,dn as SecurityManager,fn as RetryManager,Ku as QueueManager,Cg as MockHttpClient,Wu as LoadBalancer,Lg as EventStore,Kg as EndpointManager,Lu as DeliveryStore,xu as DefaultHttpClient,qu as BatchDispatcher};
|
|
75
|
-
|
|
76
|
-
//# debugId=1D5D85D586E8E95664756E2164756E21
|
|
1
|
+
class A{listenersMap=new Map;on(e,t){let r=this.listenersMap.get(e)??new Set;return r.add(t),this.listenersMap.set(e,r),this}addListener(e,t){return this.on(e,t)}off(e,t){let r=this.listenersMap.get(e);if(!r)return this;if(r.delete(t),r.size===0)this.listenersMap.delete(e);return this}removeListener(e,t){return this.off(e,t)}once(e,t){let r=(...n)=>{this.off(e,r),t(...n)};return this.on(e,r)}emit(e,...t){let r=this.listenersMap.get(e);if(!r||r.size===0)return!1;for(let n of[...r])n(...t);return!0}removeAllListeners(e){if(e)return this.listenersMap.delete(e),this;return this.listenersMap.clear(),this}}class bt extends A{config;pendingJobs=new Map;activeBatches=new Map;batchProcessor=null;defaultConfig={maxBatchSize:100,batchTimeoutMs:5000,maxConcurrentBatches:10,enablePrioritization:!0,priorityLevels:3};constructor(e={}){super();this.config={...this.defaultConfig,...e},this.startBatchProcessor()}async addJob(e){let t=e.endpoint.id;if(!this.pendingJobs.has(t))this.pendingJobs.set(t,[]);let r=this.pendingJobs.get(t);if(this.config.enablePrioritization)this.insertJobByPriority(r,e);else r.push(e);if(r.length>=this.config.maxBatchSize)await this.processBatchForEndpoint(t);this.emit("jobAdded",{endpointId:t,jobId:e.id,queueSize:r.length})}async processBatchForEndpoint(e){let t=this.pendingJobs.get(e);if(!t||t.length===0)return null;if(this.activeBatches.size>=this.config.maxConcurrentBatches)return this.emit("batchSkipped",{endpointId:e,reason:"max_concurrent_batches"}),null;let r=t.splice(0,this.config.maxBatchSize),n=this.createBatch(e,r);this.activeBatches.set(n.id,n);try{this.emit("batchStarted",{batchId:n.id,endpointId:e,jobCount:r.length}),await this.executeBatch(n,r),n.status="completed",this.emit("batchCompleted",{batchId:n.id,endpointId:e,success:!0})}catch(o){n.status="failed",this.emit("batchFailed",{batchId:n.id,endpointId:e,error:o instanceof Error?o.message:"Unknown error"}),this.requeueFailedJobs(r)}finally{this.activeBatches.delete(n.id)}return n}async processAllBatches(){let e=[],t=Array.from(this.pendingJobs.keys());for(let r of t){let n=await this.processBatchForEndpoint(r);if(n)e.push(n)}return e}getBatchStats(){let e=Array.from(this.pendingJobs.keys()),t=e.reduce((r,n)=>r+(this.pendingJobs.get(n)?.length||0),0);return{pendingJobsCount:t,activeBatchesCount:this.activeBatches.size,endpointsWithPendingJobs:e.length,averageQueueSize:e.length>0?t/e.length:0}}getPendingJobCount(e){return this.pendingJobs.get(e)?.length||0}startBatchProcessor(){this.batchProcessor=setInterval(()=>{this.processAllBatches().catch((e)=>{this.emit("processorError",e)})},this.config.batchTimeoutMs)}insertJobByPriority(e,t){let r=0;for(let n=0;n<e.length;n++){if(e[n].priority<=t.priority){r=n;break}r=n+1}e.splice(r,0,t)}createBatch(e,t){return{id:`batch_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,endpointId:e,events:t.map((r)=>r.event),createdAt:new Date,scheduledAt:new Date,status:"processing"}}async executeBatch(e,t){if(!t[0]?.endpoint)throw Error("No endpoint found for batch");let n=t.map((o)=>this.executeJob(o));try{let o=await Promise.allSettled(n),i=o.filter((a)=>a.status==="fulfilled").length,s=o.length-i;if(this.emit("batchExecuted",{batchId:e.id,endpointId:e.endpointId,total:o.length,successful:i,failed:s}),s>0)throw Error(`Batch partially failed: ${s}/${o.length} jobs failed`)}catch(o){throw this.emit("batchExecutionError",{batchId:e.id,endpointId:e.endpointId,error:o instanceof Error?o.message:"Unknown error"}),o}}async executeJob(e){let t={id:`delivery_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,endpointId:e.endpoint.id,eventId:e.event.id,url:e.endpoint.url,httpMethod:"POST",headers:{"Content-Type":"application/json"},payload:JSON.stringify(e.event),attempts:[],status:"pending",createdAt:new Date},r=Math.random()>0.1;return t.attempts.push({attemptNumber:1,timestamp:new Date,httpStatus:r?200:500,responseBody:r?"OK":"Internal Server Error",error:r?void 0:"Server error",latencyMs:Math.floor(Math.random()*1000)+100}),t.status=r?"success":"failed",t.completedAt=new Date,t}requeueFailedJobs(e){for(let t of e)if(t.attempts++,t.attempts<t.maxAttempts){let o=1000*2**(t.attempts-1);t.nextRetryAt=new Date(Date.now()+o),t.scheduledAt=t.nextRetryAt,setTimeout(()=>{this.addJob(t).catch((i)=>{this.emit("requeueError",{jobId:t.id,error:i instanceof Error?i.message:"Unknown error"})})},o)}else this.emit("jobExhausted",{jobId:t.id,endpointId:t.endpoint.id,attempts:t.attempts})}async shutdown(){if(this.batchProcessor)clearInterval(this.batchProcessor),this.batchProcessor=null;let e=30000,t=Date.now();while(this.activeBatches.size>0&&Date.now()-t<e)await new Promise((r)=>setTimeout(r,100));this.emit("shutdown",{pendingJobs:this.getBatchStats().pendingJobsCount,activeBatches:this.activeBatches.size})}}var De;((y)=>{y.INVALID_REQUEST="INVALID_REQUEST";y.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED";y.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE";y.TEMPLATE_NOT_FOUND="TEMPLATE_NOT_FOUND";y.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED";y.NETWORK_ERROR="NETWORK_ERROR";y.NETWORK_TIMEOUT="NETWORK_TIMEOUT";y.NETWORK_SERVICE_UNAVAILABLE="NETWORK_SERVICE_UNAVAILABLE";y.REQUEST_ABORTED="REQUEST_ABORTED";y.PROVIDER_ERROR="PROVIDER_ERROR";y.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED";y.CRYPTO_CONFIG_ERROR="CRYPTO_CONFIG_ERROR";y.CRYPTO_ENCRYPT_FAILED="CRYPTO_ENCRYPT_FAILED";y.CRYPTO_DECRYPT_FAILED="CRYPTO_DECRYPT_FAILED";y.CRYPTO_HASH_FAILED="CRYPTO_HASH_FAILED";y.CRYPTO_POLICY_VIOLATION="CRYPTO_POLICY_VIOLATION";y.UNKNOWN_ERROR="UNKNOWN_ERROR"})(De||={});var en={["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"},["REQUEST_ABORTED"]:{ko:"요청이 취소되었습니다",en:"Request aborted"},["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"}},Ao=new Set(Object.values(De));var Ie=(e)=>{if(typeof e!=="number"||Number.isNaN(e)||!Number.isFinite(e))return;return Math.trunc(e)};class fe extends Error{code;details;providerErrorCode;providerErrorText;httpStatus;requestId;retryAfterMs;attempt;causeChain;constructor(e,t,r,n={}){super(t);if(this.name="KMsgError",this.code=e,this.details=r,this.providerErrorCode=n.providerErrorCode,this.providerErrorText=n.providerErrorText,this.httpStatus=Ie(n.httpStatus),this.requestId=typeof n.requestId==="string"?n.requestId:void 0,this.retryAfterMs=Ie(n.retryAfterMs),this.attempt=Ie(n.attempt),Array.isArray(n.causeChain))this.causeChain=n.causeChain;else if(n.causeChain!==void 0)this.causeChain=[n.causeChain];let o=Error.captureStackTrace;if(o)o(this,fe)}getLocalizedMessage(e="ko"){let t=en[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}}}function tn(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 _ extends fe{kind;fieldPath;failMode;openFallback;constructor(e,t,r,n={}){super(tn(e),t,r,n);this.name="FieldCryptoError",this.kind=e,this.fieldPath=typeof n.fieldPath==="string"?n.fieldPath:void 0,this.failMode=n.failMode,this.openFallback=n.openFallback}toJSON(){return{...super.toJSON(),kind:this.kind,fieldPath:this.fieldPath,failMode:this.failMode,openFallback:this.openFallback}}}function Me(e){return typeof e==="function"}function xt(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function vt(e,t,r){let n=e.fields[t];if(n)return n;if(t.startsWith("metadata.")){let o=e.fields["metadata.*"];if(o)return o}return r}var rn=["closed","open"],_t=["masked","plaintext","null"];function he(e){return e.failMode==="open"?"open":"closed"}function Te(e){let t=e.openFallback;return t!==void 0&&_t.includes(t)?t:"masked"}function nn(e,t={}){let r=[];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")r.push({message:"fieldCrypto provider is required",rule:"fieldCrypto.provider.required",path:"provider",hint:"Set provider with encrypt/decrypt/hash methods"});else{if(!Me(e.provider.encrypt))r.push({message:"provider.encrypt must be a function",rule:"fieldCrypto.provider.encrypt.required",path:"provider.encrypt"});if(!Me(e.provider.decrypt))r.push({message:"provider.decrypt must be a function",rule:"fieldCrypto.provider.decrypt.required",path:"provider.decrypt"});if(!Me(e.provider.hash))r.push({message:"provider.hash must be a function",rule:"fieldCrypto.provider.hash.required",path:"provider.hash"})}if(!e.fields||typeof e.fields!=="object")r.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 i=Object.entries(e.fields);if(i.length===0)r.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[s,a]of i){if(!xt(s))r.push({message:"field path must be a non-empty string",rule:"fieldCrypto.fields.path.non_empty",path:"fields"});if(a!=="plain"&&a!=="encrypt"&&a!=="encrypt+hash"&&a!=="mask")r.push({message:`unsupported field mode: ${String(a)}`,rule:"fieldCrypto.fields.mode.supported",path:`fields.${s}`})}}if(e.failMode!==void 0&&!rn.includes(e.failMode))r.push({message:`unsupported failMode: ${String(e.failMode)}`,rule:"fieldCrypto.fail_mode.supported",path:"failMode",hint:'Use "closed" (default) or "open"'});if(e.openFallback!==void 0&&!_t.includes(e.openFallback))r.push({message:`unsupported openFallback: ${String(e.openFallback)}`,rule:"fieldCrypto.open_fallback.supported",path:"openFallback",hint:'Use "masked" (default), "null", or "plaintext"'});let n=he(e),o=Te(e);if(n==="open"&&o==="plaintext"&&e.unsafeAllowPlaintextStorage!==!0)r.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)r.push({message:"aadFields must not be empty when provided",rule:"fieldCrypto.aad_fields.non_empty",path:"aadFields"});for(let i=0;i<e.aadFields.length;i+=1){let s=e.aadFields[i];if(!xt(s))r.push({message:"aadFields cannot include empty key",rule:"fieldCrypto.aad_fields.no_empty_key",path:`aadFields[${i}]`})}}if(t.secureMode&&!t.compatPlainColumns){let i=vt(e,"to","encrypt+hash"),s=vt(e,"from","encrypt+hash");if(i==="plain")r.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(s==="plain")r.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:r.length===0,issues:r}}function Fe(e,t={}){let r=nn(e,t);if(r.valid)return;let n=r.issues[0];if(!n)throw new _("config","fieldCrypto config validation failed",{rule:"fieldCrypto.config.invalid",issues:r.issues});throw new _("config",n.message,{rule:n.rule,path:n.path,hint:n.hint,issues:r.issues},{fieldPath:n.path})}function on(e){if(typeof e==="string")return e;return JSON.stringify(e)}function sn(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 Et(e=3,t=2){return(r)=>{let n=String(r??"");if(n.length<=e+t)return"*".repeat(Math.max(0,n.length));let o=n.slice(0,e),i=n.slice(-t);return`${o}${"*".repeat(n.length-e-t)}${i}`}}function an(e){let t=sn(e);if(t&&e.v===1&&e.alg==="A256GCM")return;let r=e&&typeof e==="object"?e:{};throw new _("policy","ciphertext envelope must be v1 A256GCM with string kid, iv, tag, and ct",{rule:"fieldCrypto.envelope.v1",shapeValid:t,v:r.v,alg:r.alg})}function wt(e){if(typeof e==="string")return e;an(e);let{v:t,alg:r,kid:n,iv:o,tag:i,ct:s}=e;return on({v:t,alg:r,kid:n,iv:o,tag:i,ct:s})}var cn=["to","from","phone","phoneNumber","recipient","sender","secret","apiKey","apiSecret","authorization","auth","token","password","payload","message","content","text"],te=String.raw`\w.[\]"'-`,un=new RegExp(String.raw`^[${te}]*(?:(?:secret|password|passwd|passphrase|token|credential|private[-_.]?key|api[-_.]?key)[${te}]*|auth(?:orization)?(?:[.[\]"'][${te}]*)?)$`,"i");function Ct(e){return un.test(e.replace(/\s+/g,"_"))}function ln(e){if(Ct(e))return!0;let t=e.toLowerCase();return cn.some((r)=>t.includes(r.toLowerCase()))}function At(e){let t=e.trim();if(t.length<=4)return"***";if(t.includes("@")){let[o,i]=t.split("@");return`${o.slice(0,2)}${"*".repeat(Math.max(1,o.length-2))}@${i}`}let r=t.slice(0,3),n=t.slice(-2);return`${r}${"*".repeat(Math.max(1,t.length-5))}${n}`}var dn=new RegExp([String.raw`(?:\+82[-.\s]?(?:\(0\)[-.\s]?|0)?|0)(?:1[016789]|2|70|80|50\d|[3-6]\d)[-.\s]?\d{3,4}[-.\s]?\d{4}`,String.raw`\(0\d{1,2}\)[-.\s]?\d{3,4}[-.\s]?\d{4}`,String.raw`1[5-9]\d{2}[-\s]\d{4}`].map((e)=>String.raw`(?<![\w+])${e}(?!\w)`).join("|"),"g"),pn=/(\b[a-z][\w+.-]{0,31}:\/\/[^\s/:@]*):[^\s/?#]*@/gi,fn=[String.raw`"(?:\\.|[^"\\\n])*"?`,String.raw`'(?:\\.|[^'\\\n])*'?`,String.raw`\\"(?:\\\\(?:\\.|[^\\\n])|\\[^"\\\n]|[^\\\n])*(?:\\")?`,String.raw`\\'(?:\\\\(?:\\.|[^\\\n])|\\[^'\\\n]|[^\\\n])*(?:\\')?`],hn=new RegExp(String.raw`(?<![${te}])((?:["']?(?:api|private)[ \t]+)?[${te}]+)((?:\\?["'])?\s*[:=]\s*)`,"gi"),kt=new RegExp(String.raw`${fn.join("|")}|((?:Bearer|Basic)\s+)?[^\s"',;&]+`,"iy");function mn(e){let t="",r=0;for(let n of e.matchAll(hn)){let[o,i=""]=n;if(n.index<r||!Ct(i))continue;let s=n.index+o.length;kt.lastIndex=s;let a=kt.exec(e);if(!a)continue;let l=/^\\?["']/.exec(a[0])?.[0];t+=e.slice(r,s),t+=l?`${l}[REDACTED]${l}`:`${a[1]??""}[REDACTED]`,r=s+a[0].length}return t+e.slice(r)}function me(e){return mn(e.replace(pn,"$1:[REDACTED]@").replace(dn,(t)=>At(t)))}function Oe(e,t){if(t===void 0||t===null)return t;if(ln(e)){if(typeof t==="string")return At(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((r)=>Oe(e,r));if(typeof t==="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=Oe(n,o);return r}if(typeof t==="string")return me(t);return t}function gn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Oe(r,n);return t}class Le{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=gn(e.context),r=me(e.message),n=e.error&&{name:e.error.name,message:me(e.error.message),stack:e.error.stack?me(e.error.stack):void 0};if(this.config.enableJson)return JSON.stringify({level:e.level,message:r,timestamp:e.timestamp.toISOString(),context:t,...n&&{error:n},...e.duration&&{duration:e.duration}});let o=e.timestamp.toISOString(),i=this.config.enableColors?this.colorizeLevel(e.level):e.level,s=Object.keys(t).length>0?` [${Object.entries(t).map(([l,c])=>`${l}=${c}`).join(", ")}]`:"",a=`${o} ${i}${s}: ${r}`;if(e.duration!==void 0)a+=` (${e.duration}ms)`;if(n)a+=`
|
|
2
|
+
${n.stack??`${n.name}: ${n.message}`}`;return a}colorizeLevel(e){if(!this.config.enableColors)return e;return`${{["DEBUG"]:"\x1B[36m",["INFO"]:"\x1B[32m",["WARN"]:"\x1B[33m",["ERROR"]:"\x1B[31m"}[e]}${e}\x1B[0m`}writeLog(e){if(!this.shouldLog(e.level))return;let t=this.formatMessage(e);if(this.config.enableConsole)(e.level==="ERROR"?console.error:e.level==="WARN"?console.warn:console.log)(t);if(this.config.enableFile&&this.config.filePath);}debug(e,t={}){this.writeLog({level:"DEBUG",message:e,timestamp:new Date,context:{...this.context,...t}})}info(e,t={}){this.writeLog({level:"INFO",message:e,timestamp:new Date,context:{...this.context,...t}})}warn(e,t={},r){this.writeLog({level:"WARN",message:e,timestamp:new Date,context:{...this.context,...t},error:r})}error(e,t={},r){this.writeLog({level:"ERROR",message:e,timestamp:new Date,context:{...this.context,...t},error:r})}child(e){return new Le({...this.context,...e},this.config)}time(e){let t=Date.now();return()=>{let r=Date.now()-t;this.info(`${e} completed`,{duration:r})}}async measure(e,t,r={}){let n=Date.now(),o={...r,operation:e};this.debug(`Starting ${e}`,o);try{let i=await t(),s=Date.now()-n;return this.info(`Completed ${e}`,{...o,duration:s}),i}catch(i){let s=Date.now()-n;throw this.error(`Failed ${e}`,{...o,duration:s},i instanceof Error?i:Error(String(i))),i}}}var Ze;function yn(e,t){return new Le(e,t)}function W(){if(!Ze)Ze=yn();return Ze}var Y={debug:(e,t)=>W().debug(e,t),info:(e,t)=>W().info(e,t),warn:(e,t,r)=>W().warn(e,t,r),error:(e,t,r)=>W().error(e,t,r),child:(e)=>W().child(e),time:(e)=>W().time(e),measure:(e,t,r)=>W().measure(e,t,r)};class Pt extends A{config;endpointHealth=new Map;endpoints=new Map;circuitBreakers=new Map;connectionCounts=new Map;roundRobinIndex=0;healthCheckInterval=null;defaultConfig={strategy:"round-robin",healthCheckInterval:30000,healthCheckTimeoutMs:5000,weights:{}};constructor(e={}){super();this.config={...this.defaultConfig,...e},this.startHealthChecks()}async registerEndpoint(e){let t={endpointId:e.id,isHealthy:!0,consecutiveFailures:0,lastHealthCheckAt:new Date,averageResponseTime:0,activeConnections:0};this.endpointHealth.set(e.id,t),this.endpoints.set(e.id,e),this.connectionCounts.set(e.id,0),await this.checkEndpointHealth(e),this.emit("endpointRegistered",{endpointId:e.id,isHealthy:t.isHealthy})}async unregisterEndpoint(e){this.endpointHealth.delete(e),this.endpoints.delete(e),this.circuitBreakers.delete(e),this.connectionCounts.delete(e),this.emit("endpointUnregistered",{endpointId:e})}async selectEndpoint(e){let t=e.filter((n)=>{let o=this.endpointHealth.get(n.id),i=this.circuitBreakers.get(n.id);return o?.isHealthy&&n.status==="active"&&i?.state!=="open"});if(t.length===0){let n=this.tryHalfOpenEndpoint(e);if(n)return n;return this.emit("noHealthyEndpoints",{totalEndpoints:e.length}),null}let r;switch(this.config.strategy){case"round-robin":r=this.selectRoundRobin(t);break;case"least-connections":r=this.selectLeastConnections(t);break;case"weighted":r=this.selectWeighted(t);break;case"random":r=this.selectRandom(t);break;default:r=t[0]}return this.incrementConnections(r.id),this.emit("endpointSelected",{endpointId:r.id,strategy:this.config.strategy,availableEndpoints:t.length}),r}async onRequestComplete(e,t,r){this.decrementConnections(e);let n=this.endpointHealth.get(e);if(n){if(n.averageResponseTime===0)n.averageResponseTime=r;else n.averageResponseTime=n.averageResponseTime*0.8+r*0.2;if(t){n.consecutiveFailures=0,n.isHealthy=!0;let o=this.circuitBreakers.get(e);if(o){if(o.state==="half-open")o.state="closed",o.failureCount=0,this.emit("circuitBreakerClosed",{endpointId:e})}}else{if(n.consecutiveFailures++,n.consecutiveFailures>=3)n.isHealthy=!1,this.emit("endpointUnhealthy",{endpointId:e,consecutiveFailures:n.consecutiveFailures});this.updateCircuitBreaker(e,!1)}}this.emit("requestCompleted",{endpointId:e,success:t,responseTime:r,averageResponseTime:n?.averageResponseTime})}getEndpointHealth(e){return this.endpointHealth.get(e)||null}getAllEndpointHealth(){return Array.from(this.endpointHealth.values())}getStats(){let e=Array.from(this.endpointHealth.values()),t=Array.from(this.connectionCounts.values()).reduce((o,i)=>o+i,0),r=Array.from(this.circuitBreakers.values()).filter((o)=>o.state==="open").length,n=e.length>0?e.reduce((o,i)=>o+i.averageResponseTime,0)/e.length:0;return{totalEndpoints:e.length,healthyEndpoints:e.filter((o)=>o.isHealthy).length,activeConnections:t,circuitBreakersOpen:r,averageResponseTime:n}}selectRoundRobin(e){let t=e[this.roundRobinIndex%e.length];return this.roundRobinIndex=(this.roundRobinIndex+1)%e.length,t}selectLeastConnections(e){return e.reduce((t,r)=>{let n=this.connectionCounts.get(t.id)||0;return(this.connectionCounts.get(r.id)||0)<n?r:t})}selectWeighted(e){let t=this.config.weights||{},r=e.reduce((o,i)=>o+(t[i.id]||1),0),n=Math.random()*r;for(let o of e){let i=t[o.id]||1;if(n-=i,n<=0)return o}return e[0]}selectRandom(e){let t=Math.floor(Math.random()*e.length);return e[t]}tryHalfOpenEndpoint(e){let t=new Date;for(let r of e){let n=this.circuitBreakers.get(r.id);if(n?.state==="open"&&n.nextRetryTime&&t>=n.nextRetryTime)return n.state="half-open",this.emit("circuitBreakerHalfOpen",{endpointId:r.id}),r}return null}updateCircuitBreaker(e,t){let r=this.circuitBreakers.get(e);if(!r)r={endpointId:e,state:"closed",failureCount:0},this.circuitBreakers.set(e,r);if(!t){if(r.failureCount++,r.lastFailureTime=new Date,r.failureCount>=5&&r.state==="closed")r.state="open",r.nextRetryTime=new Date(Date.now()+60000),this.emit("circuitBreakerOpened",{endpointId:e,failureCount:r.failureCount,nextRetryTime:r.nextRetryTime})}}incrementConnections(e){let t=this.connectionCounts.get(e)||0;this.connectionCounts.set(e,t+1);let r=this.endpointHealth.get(e);if(r)r.activeConnections=t+1}decrementConnections(e){let t=this.connectionCounts.get(e)||0,r=Math.max(0,t-1);this.connectionCounts.set(e,r);let n=this.endpointHealth.get(e);if(n)n.activeConnections=r}async checkEndpointHealth(e){let t=Date.now();try{let r=await fetch(e.url,{method:"HEAD",signal:AbortSignal.timeout(this.config.healthCheckTimeoutMs)}),n=Date.now()-t,o=r.ok;await this.onRequestComplete(e.id,o,n),this.emit("healthCheckCompleted",{endpointId:e.id,success:o,responseTime:n,httpStatus:r.status})}catch(r){let n=Date.now()-t;await this.onRequestComplete(e.id,!1,n),this.emit("healthCheckFailed",{endpointId:e.id,error:r instanceof Error?r.message:"Unknown error",responseTime:n})}}startHealthChecks(){this.healthCheckInterval=setInterval(()=>{this.checkAllEndpoints().catch((e)=>{Y.error("Webhook endpoint health check failed",void 0,e instanceof Error?e:Error(String(e)))})},this.config.healthCheckInterval)}async checkAllEndpoints(){let e=Array.from(this.endpoints.values());for(let t of e)await this.checkEndpointHealth(t)}async shutdown(){if(this.healthCheckInterval)clearInterval(this.healthCheckInterval),this.healthCheckInterval=null;this.emit("shutdown",{totalEndpoints:this.endpointHealth.size,activeConnections:Array.from(this.connectionCounts.values()).reduce((e,t)=>e+t,0)})}}function w(e){if(!e)throw Error("File storage requires `fileAdapter`. Provide a runtime-specific adapter (Node fs, Worker KV/R2, etc.).");return e}function Be(e,t){let r=e.replace(/[\\/]+$/,""),n=t.replace(/^[\\/]+/,"");if(!r)return n;return`${r}/${n}`}function T(e){if(typeof e!=="object"||e===null)return!1;let t=e;return t.code==="ENOENT"||t.name==="NotFoundError"}class St extends A{config;queues=new Map;highPriorityQueue=[];mediumPriorityQueue=[];lowPriorityQueue=[];delayedJobs=new Map;ttlCleanupInterval=null;totalJobs=0;defaultConfig={maxQueueSize:1e4,persistToDisk:!1,compressionEnabled:!1,ttlMs:86400000};constructor(e={}){super();if(this.config={...this.defaultConfig,...e},this.queues.set("high",this.highPriorityQueue),this.queues.set("medium",this.mediumPriorityQueue),this.queues.set("low",this.lowPriorityQueue),this.config.persistToDisk&&this.config.diskPath)this.loadFromDisk().catch((t)=>{this.emit("diskLoadError",t)});this.startTTLCleanup()}async enqueue(e){if(this.totalJobs>=this.config.maxQueueSize)return this.emit("queueFull",{totalJobs:this.totalJobs,maxSize:this.config.maxQueueSize}),!1;if(e.scheduledAt>new Date)return await this.scheduleDelayedJob(e),!0;let t=this.getQueueName(e.priority),r=this.queues.get(t);if(!r)throw Error(`Invalid queue name: ${t}`);if(r.push(e),this.totalJobs++,this.emit("jobEnqueued",{jobId:e.id,priority:e.priority,queueName:t,totalJobs:this.totalJobs}),this.config.persistToDisk)await this.saveToDisk().catch((n)=>{this.emit("diskSaveError",n)});return!0}async dequeue(){for(let[e,t]of this.queues.entries())if(t.length>0){let r=t.shift();if(this.totalJobs--,this.emit("jobDequeued",{jobId:r.id,queueName:e,totalJobs:this.totalJobs}),this.config.persistToDisk)await this.saveToDisk().catch((n)=>{this.emit("diskSaveError",n)});return r}return null}async dequeueFromPriority(e){let t=this.getQueueName(e),r=this.queues.get(t);if(!r||r.length===0)return null;let n=r.shift();return this.totalJobs--,this.emit("jobDequeued",{jobId:n.id,queueName:t,totalJobs:this.totalJobs}),n}peek(){for(let e of this.queues.values())if(e.length>0)return e[0];return null}async removeJob(e){for(let[r,n]of this.queues.entries()){let o=n.findIndex((i)=>i.id===e);if(o!==-1){if(n.splice(o,1),this.totalJobs--,this.emit("jobRemoved",{jobId:e,queueName:r,totalJobs:this.totalJobs}),this.config.persistToDisk)await this.saveToDisk().catch((i)=>{this.emit("diskSaveError",i)});return!0}}let t=this.delayedJobs.get(e);if(t)return clearTimeout(t),this.delayedJobs.delete(e),this.emit("delayedJobCanceled",{jobId:e}),!0;return!1}getStats(){return{totalJobs:this.totalJobs,highPriorityJobs:this.highPriorityQueue.length,mediumPriorityJobs:this.mediumPriorityQueue.length,lowPriorityJobs:this.lowPriorityQueue.length,delayedJobs:this.delayedJobs.size,queueUtilization:this.totalJobs/this.config.maxQueueSize*100}}async clear(){for(let e of this.queues.values())e.length=0;for(let e of this.delayedJobs.values())clearTimeout(e);if(this.delayedJobs.clear(),this.totalJobs=0,this.emit("queueCleared"),this.config.persistToDisk)await this.saveToDisk().catch((e)=>{this.emit("diskSaveError",e)})}async cleanupExpiredJobs(){let e=new Date,t=0;for(let[r,n]of this.queues.entries())for(let o=n.length-1;o>=0;o--){let i=n[o],s=e.getTime()-i.createdAt.getTime();if(s>this.config.ttlMs)n.splice(o,1),this.totalJobs--,t++,this.emit("jobExpired",{jobId:i.id,queueName:r,age:s})}if(t>0){if(this.emit("expiredJobsCleanup",{removedCount:t,totalJobs:this.totalJobs}),this.config.persistToDisk)await this.saveToDisk().catch((r)=>{this.emit("diskSaveError",r)})}return t}getQueueName(e){if(e>=8)return"high";if(e>=5)return"medium";return"low"}async scheduleDelayedJob(e){let t=e.scheduledAt.getTime()-Date.now(),r=setTimeout(()=>{this.activateDelayedJob(e).catch((n)=>{Y.error("Failed to activate delayed webhook job",{jobId:e.id},n instanceof Error?n:Error(String(n)))})},t);this.delayedJobs.set(e.id,r),this.emit("jobScheduled",{jobId:e.id,scheduledAt:e.scheduledAt,delay:t})}async activateDelayedJob(e){if(this.delayedJobs.delete(e.id),await this.enqueue({...e,scheduledAt:new Date}))this.emit("delayedJobActivated",{jobId:e.id})}startTTLCleanup(){if(this.ttlCleanupInterval)clearInterval(this.ttlCleanupInterval);this.ttlCleanupInterval=setInterval(()=>{this.cleanupExpiredJobs().catch((e)=>{this.emit("cleanupError",e)})},300000)}async saveToDisk(){if(!this.config.diskPath)return;try{let e=w(this.config.fileAdapter),t={queues:{high:this.highPriorityQueue,medium:this.mediumPriorityQueue,low:this.lowPriorityQueue},totalJobs:this.totalJobs,timestamp:new Date().toISOString()},r=JSON.stringify(t,null,2),n=Be(this.config.diskPath,"webhook-queue.json");await e.ensureDirForFile(n),await e.writeFile(n,r),this.emit("diskSaved",{filePath:n,totalJobs:this.totalJobs})}catch(e){throw this.emit("diskSaveError",e),e}}async loadFromDisk(){if(!this.config.diskPath)return;try{let e=w(this.config.fileAdapter),t=Be(this.config.diskPath,"webhook-queue.json"),r=await e.readFile(t),n=JSON.parse(r);this.highPriorityQueue.length=0,this.mediumPriorityQueue.length=0,this.lowPriorityQueue.length=0,this.highPriorityQueue.push(...n.queues.high||[]),this.mediumPriorityQueue.push(...n.queues.medium||[]),this.lowPriorityQueue.push(...n.queues.low||[]),this.totalJobs=n.totalJobs||0,this.emit("diskLoaded",{filePath:t,totalJobs:this.totalJobs,timestamp:n.timestamp})}catch(e){if(!T(e))this.emit("diskLoadError",e)}}async shutdown(){if(this.ttlCleanupInterval)clearInterval(this.ttlCleanupInterval),this.ttlCleanupInterval=null;for(let e of this.delayedJobs.values())clearTimeout(e);if(this.delayedJobs.clear(),this.config.persistToDisk)await this.saveToDisk().catch((e)=>{this.emit("diskSaveError",e)});this.emit("shutdown",{totalJobs:this.totalJobs})}}class $t extends A{config;deliveries=new Map;indexByEndpoint=new Map;indexByStatus=new Map;indexByDate=new Map;cleanupInterval=null;defaultConfig={type:"memory",retentionDays:30,enableCompression:!1,maxMemoryUsage:104857600};constructor(e={}){super();if(this.config={...this.defaultConfig,...e},this.initializeIndexes(),this.startCleanupTask(),this.config.type==="file"&&this.config.filePath)this.loadFromFile().catch((t)=>{this.emit("loadError",t)})}async saveDelivery(e){let t=this.deliveries.get(e.id);if(t)this.removeFromIndexes(t);if(this.config.type==="memory"&&this.config.maxMemoryUsage)await this.checkMemoryUsage();if(this.deliveries.set(e.id,e),this.addToIndexes(e),this.config.type==="file")await this.appendToFile(e);this.emit("deliverySaved",{deliveryId:e.id,endpointId:e.endpointId,status:e.status})}async getDelivery(e){return this.deliveries.get(e)||null}async searchDeliveries(e={},t={page:1,limit:100}){let r=null;if(e.endpointId){let c=this.indexByEndpoint.get(e.endpointId);r=c?new Set(c):new Set}if(e.status){let c=this.indexByStatus.get(e.status);if(r)r=new Set(Array.from(r).filter((u)=>c?.has(u)));else r=c?new Set(c):new Set}if(e.createdAfter||e.createdBefore){let c=this.getDeliveryIdsByDateRange(e.createdAfter,e.createdBefore);if(r)r=new Set(Array.from(r).filter((u)=>c.has(u)));else r=c}if(!r)r=new Set(this.deliveries.keys());let n=Array.from(r).map((c)=>this.deliveries.get(c)).filter((c)=>this.matchesFilter(c,e));n.sort((c,u)=>{if(t.sortBy==="createdAt"||!t.sortBy){let h=u.createdAt.getTime()-c.createdAt.getTime();return t.sortOrder==="asc"?-h:h}let p=this.getFieldValue(c,t.sortBy),d=this.getFieldValue(u,t.sortBy),f=0;if(p<d)f=-1;else if(p>d)f=1;return t.sortOrder==="desc"?-f:f});let o=n.length,i=Math.ceil(o/t.limit),s=(t.page-1)*t.limit,a=s+t.limit;return{items:n.slice(s,a),totalCount:o,page:t.page,totalPages:i,hasNext:t.page<i,hasPrevious:t.page>1}}async getDeliveriesByEndpoint(e,t=100){let r=this.indexByEndpoint.get(e);if(!r)return[];return Array.from(r).map((n)=>this.deliveries.get(n)).sort((n,o)=>o.createdAt.getTime()-n.createdAt.getTime()).slice(0,t)}async getFailedDeliveries(e,t=100){let r={status:"failed",endpointId:e};return(await this.searchDeliveries(r,{page:1,limit:t})).items}async getDeliveryStats(e,t){let r={endpointId:e,createdAfter:t?.start,createdBefore:t?.end},o=(await this.searchDeliveries(r,{page:1,limit:1e4})).items,i=o.filter((f)=>f.status==="success"),s=o.filter((f)=>f.status==="failed"),a=o.filter((f)=>f.status==="pending"),l=o.filter((f)=>f.status==="exhausted"),c=o.filter((f)=>f.completedAt),u=c.reduce((f,h)=>{let g=h.attempts[h.attempts.length-1];return f+(g?.latencyMs||0)},0),p=c.length>0?u/c.length:0,d={};for(let f of[...s,...l]){let h=f.attempts[f.attempts.length-1];if(h?.error)d[h.error]=(d[h.error]||0)+1;else if(h?.httpStatus){let g=`HTTP ${h.httpStatus}`;d[g]=(d[g]||0)+1}}return{totalDeliveries:o.length,successfulDeliveries:i.length,failedDeliveries:s.length,pendingDeliveries:a.length,exhaustedDeliveries:l.length,averageLatency:p,successRate:o.length>0?i.length/o.length*100:0,errorBreakdown:d}}async cleanupOldDeliveries(){if(!this.config.retentionDays)return 0;let e=new Date;e.setDate(e.getDate()-this.config.retentionDays);let t=Array.from(this.deliveries.values()).filter((r)=>r.createdAt<e);for(let r of t)this.removeFromIndexes(r),this.deliveries.delete(r.id);if(t.length>0){if(this.emit("oldDeliveriesCleanup",{removedCount:t.length,cutoffDate:e}),this.config.type==="file")await this.saveToFile()}return t.length}getStorageStats(){let e=this.estimateMemoryUsage();return{totalDeliveries:this.deliveries.size,memoryUsage:e,indexSizes:{byEndpoint:this.indexByEndpoint.size,byStatus:this.indexByStatus.size,byDate:this.indexByDate.size}}}initializeIndexes(){let e=["pending","success","failed","exhausted"];for(let t of e)this.indexByStatus.set(t,new Set)}addToIndexes(e){if(!this.indexByEndpoint.has(e.endpointId))this.indexByEndpoint.set(e.endpointId,new Set);this.indexByEndpoint.get(e.endpointId).add(e.id);let t=this.indexByStatus.get(e.status);if(t)t.add(e.id);let r=e.createdAt.toISOString().split("T")[0];if(!this.indexByDate.has(r))this.indexByDate.set(r,new Set);this.indexByDate.get(r).add(e.id)}removeFromIndexes(e){let t=this.indexByEndpoint.get(e.endpointId);if(t){if(t.delete(e.id),t.size===0)this.indexByEndpoint.delete(e.endpointId)}let r=this.indexByStatus.get(e.status);if(r)r.delete(e.id);let n=e.createdAt.toISOString().split("T")[0],o=this.indexByDate.get(n);if(o){if(o.delete(e.id),o.size===0)this.indexByDate.delete(n)}}getDeliveryIdsByDateRange(e,t){let r=new Set;for(let[n,o]of this.indexByDate.entries()){let i=new Date(n);if(e&&i<e)continue;if(t&&i>t)continue;o.forEach((s)=>{r.add(s)})}return r}matchesFilter(e,t){if(t.eventId&&e.eventId!==t.eventId)return!1;if(t.httpStatusCode&&t.httpStatusCode.length>0){let r=e.attempts[e.attempts.length-1];if(!r?.httpStatus||!t.httpStatusCode.includes(r.httpStatus))return!1}if(t.hasError!==void 0){let r=e.attempts.some((n)=>n.error);if(t.hasError!==r)return!1}if(t.completedAfter&&(!e.completedAt||e.completedAt<t.completedAfter))return!1;if(t.completedBefore&&(!e.completedAt||e.completedAt>t.completedBefore))return!1;return!0}getFieldValue(e,t){return t.split(".").reduce((r,n)=>r?.[n],e)}estimateMemoryUsage(){let e=0;for(let t of this.deliveries.values())e+=JSON.stringify(t).length*2;return e}async checkMemoryUsage(){if(!this.config.maxMemoryUsage)return;let e=this.estimateMemoryUsage();if(e>this.config.maxMemoryUsage){let t=Array.from(this.deliveries.values()).sort((o,i)=>o.createdAt.getTime()-i.createdAt.getTime()),r=0,n=this.config.maxMemoryUsage*0.8;for(let o of t){if(this.estimateMemoryUsage()<=n)break;this.removeFromIndexes(o),this.deliveries.delete(o.id),r++}if(r>0)this.emit("memoryCleanup",{removedCount:r,previousUsage:e,currentUsage:this.estimateMemoryUsage()})}}startCleanupTask(){this.cleanupInterval=setInterval(()=>{this.cleanupOldDeliveries().then(()=>this.checkMemoryUsage()).catch((e)=>{this.emit("cleanupError",e)})},3600000)}async appendToFile(e){if(!this.config.filePath)return;try{let t=w(this.config.fileAdapter),r=JSON.stringify(e)+`
|
|
3
|
+
`;await t.ensureDirForFile(this.config.filePath),await t.appendFile(this.config.filePath,r)}catch(t){this.emit("appendError",t)}}async loadFromFile(){if(!this.config.filePath)return;try{let r=(await w(this.config.fileAdapter).readFile(this.config.filePath)).trim().split(`
|
|
4
|
+
`).filter((n)=>n.trim());for(let n of r)try{let o=JSON.parse(n),i={...o,createdAt:new Date(o.createdAt),completedAt:o.completedAt?new Date(o.completedAt):void 0,nextRetryAt:o.nextRetryAt?new Date(o.nextRetryAt):void 0,attempts:o.attempts.map((s)=>({...s,timestamp:new Date(s.timestamp)}))};this.deliveries.set(i.id,i),this.addToIndexes(i)}catch(o){this.emit("parseError",{line:n,error:o})}this.emit("dataLoaded",{filePath:this.config.filePath,deliveryCount:this.deliveries.size})}catch(e){if(!T(e))this.emit("loadError",e)}}async saveToFile(){if(!this.config.filePath)return;try{let e=w(this.config.fileAdapter),t=Array.from(this.deliveries.values()).map((r)=>JSON.stringify(r)).join(`
|
|
5
|
+
`);await e.ensureDirForFile(this.config.filePath),await e.writeFile(this.config.filePath,t+`
|
|
6
|
+
`),this.emit("dataSaved",{filePath:this.config.filePath,deliveryCount:this.deliveries.size})}catch(e){throw this.emit("saveError",e),e}}async shutdown(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;if(this.config.type==="file")await this.saveToFile().catch((e)=>{this.emit("saveError",e)});this.emit("shutdown",{deliveryCount:this.deliveries.size})}}function Ue(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Rt(e,t){if(typeof t==="bigint")return t.toString();return t}class zt{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function It(e){return new zt(e)}function Dt(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Mt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}var We="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ge(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Tt(e){if(ge(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(ge(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}var Ft=new Set(["string","number","symbol"]);function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ye(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function E(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Ot(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}function Z(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Lt(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function K(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function re(e){return typeof e==="string"?e:e?.message}function je(e,t,r){var n;for(let o=t;o<e.length;o++)(n=e[o]).schema??(n.schema=r)}function O(e,t,r){var n;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(n=e).schema??(n.schema=e.inst);else e.schema=e.inst;let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:re(e.inst?._zod.def?.error?.(e))??re(i?.(e))??re(t?.error?.(e))??re(r.customError?.(e))??re(r.localeError?.(e))??"Invalid input",a={};for(let l of Object.keys(e)){if(l==="inst"||l==="schema"||l==="continue"||l==="input"||l==="__proto__")continue;a[l]=e[l]}if(a.path??(a.path=[]),a.message=s,t?.reportInput)a.input=e.input;return a}function Bt(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);if(n.get)Object.defineProperty(e,r,{...n,enumerable:!1});else bn(e,r,n.value)}}function j(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function Nt(e,t,r){return j(e,t,r,!1)}function bn(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:j(this,t,r.bind(this))},set(n){j(this,t,n)}})}function xn(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Ne,F=!1,vn={configurable:!0,get(){F=!0;return}};function R(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&Ne!==e._zod){Ne=void 0;return}Ne=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,vn);let o=F;F=!1;try{let i=r(this);if(F)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i});return F=F||o,i}catch(i){throw delete this[t],F=F||o,i}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function Ut(e,t,r,n){let o=xn(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,i),i.value=r(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:i})}})}var Wt;var Ke={value:void 0,enumerable:!1},jt="captureStackTrace"in Error?Error:null;function _n(e){let t=jt;if(t){let r=t.stackTraceLimit;if(typeof r==="number"){try{t.stackTraceLimit=0}catch{return jt=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function m(e,t,r,n){let o={};function i(d){this.def=d,this.constr=p,this.traits=new Set}i.prototype=o;let s=r,a=s&&new WeakSet;function l(d,f){if(!d._zod){Ke.value=new i(f);try{Object.defineProperty(d,"_zod",Ke)}finally{Ke.value=void 0}}else if(d._zod.traits.has(e))return;if(d._zod.traits.add(e),t(d,f),a){let g=Object.getPrototypeOf(d),C=d._zod.constr.prototype,y=g;while(y&&y!==C)y=Object.getPrototypeOf(y);let G=y??g;if(!a.has(G))a.add(G),Bt(G,s)}let h=p.prototype;for(let g in h){if(!Object.prototype.hasOwnProperty.call(h,g))continue;if(!(g in d))d[g]=h[g].bind(d)}}let c=n?.Parent??Object;class u extends c{}Object.defineProperty(u,"name",{value:e});function p(d){let f=n?.Parent?_n(u):this;l(f,d);let h=f._zod.deferred;if(h){for(let C of h)C();f._zod.deferred=void 0}let g=globalThis.__zod_globalConfig?.postProcessor;if(g)g(f);return f}return Object.defineProperty(p,"init",{value:l}),Object.defineProperty(p,Symbol.hasInstance,{value:(d)=>{if(n?.Parent&&d instanceof n.Parent)return!0;return d?._zod?.traits?.has(e)}}),Object.defineProperty(p,"name",{value:e}),p}class I extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class He extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Wt=globalThis).__zod_globalConfig??(Wt.__zod_globalConfig={});var H=globalThis.__zod_globalConfig;function L(e){if(e)Object.assign(H,e);return H}function En(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Rt,2)),e.message}function wn(e){this._zod.message=e}var kn={get:En,set:wn,enumerable:!0,configurable:!0},Ve={value:void 0,enumerable:!1},Kt=new WeakSet([Object.prototype,Error.prototype]),Ht=(e,t)=>{e.name="$ZodError",Ve.value=t,Object.defineProperty(e,"issues",Ve),Ve.value=void 0,Object.defineProperty(e,"message",kn);let r=Object.getPrototypeOf(e);if(!Kt.has(r))Kt.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}})},Vo=m("$ZodError",Ht),ne=m("$ZodError",Ht,void 0,{Parent:Error});var An=(e)=>{let t=(r,n,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new I;if(a.issues.length){let l=new(i?.Err??e)(a.issues.map((c)=>O(c,s,L())));throw We(l,i?.callee??t),l}return a.value};return t},qe=An(ne),Pn=(e)=>{let t=async(r,n,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let l=new(i?.Err??e)(a.issues.map((c)=>O(c,s,L())));throw We(l,i?.callee??t),l}return a.value};return t},Ge=Pn(ne),Sn=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new I;return i.issues.length?Jt(e,i.issues,o):{success:!0,data:i.value}},Ye=Sn(ne);function Jt(e,t,r){let n;return{success:!1,get error(){if(!n)n=new e(t.map((o)=>O(o,r,L()))),t=void 0,r=void 0;return n},set error(o){n=o,t=void 0,r=void 0}}}var $n=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?Jt(e,i.issues,o):{success:!0,data:i.value}},Xe=$n(ne);var Vt=/^https?$/;var qt=/^[\s\S]{0,}$/;var Qe=/^-?\d+(?:\.\d+)?$/,Gt=/^(?:true|false)$/i;var Q=m("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])});var be={number:"number",bigint:"bigint",object:"date"},Xt=m("$ZodCheckLessThan",(e,t)=>{Q.init(e,t);let r=be[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:be[typeof n.value]??r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Qt=m("$ZodCheckGreaterThan",(e,t)=>{Q.init(e,t);let r=be[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:be[typeof n.value]??r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var er=m("$ZodCheckStringFormat",(e,t)=>{var r,n;if(Q.init(e,t),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})});var rr={major:4,minor:6,patch:5};var k=m("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=rr;let n=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(let i of o)for(let s of i._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(a,l,c)=>{if(a.memo)return a;let u=Z(a),p;for(let d of l){if(d._zod.def.when){if(Lt(a))continue;if(!d._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,h=d._zod.check(a);if(h instanceof Promise&&c?.async===!1)throw new I;if(p||h instanceof Promise)p=(p??Promise.resolve()).then(async()=>{if(await h,a.issues.length===f)return;if(je(a.issues,f,e),!u)u=Z(a,f)});else{if(a.issues.length===f)continue;if(je(a.issues,f,e),!u)u=Z(a,f)}}if(p)return p.then(()=>a);return a},s=(a,l,c)=>{if(Z(a))return a.aborted=!0,a;let u=i(l,o,c);if(u instanceof Promise){if(c.async===!1)throw new I;return u.then((p)=>e._zod.parse(p,c))}return e._zod.parse(u,c)};e._zod.run=(a,l)=>{if(l.skipChecks)return e._zod.parse(a,l);if(l.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});if(u instanceof Promise)return u.then((p)=>s(p,a,l));return s(u,a,l)}let c=e._zod.parse(a,l);if(c instanceof Promise){if(l.async===!1)throw new I;return c.then((u)=>i(u,o,l))}return i(c,o,l)}}},{get "~standard"(){return Nt(this,"~standard",In(this))},set "~standard"(e){j(this,"~standard",e)}}),sr=(e,t)=>e.issues.length?{issues:e.issues.map((r)=>O(r,t,L()))}:{value:e.value};async function zn(e,t){let r={async:!0};return sr(await e._zod.run({value:t,issues:[]},r),r)}function In(e){return{validate:(t)=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return sr(n,r)}catch(n){}return zn(e,t)},vendor:"zod",version:1}}var et=m("$ZodString",(e,t)=>{k.init(e,t),e._zod.pattern=t.pattern??qt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),tt=m("$ZodStringFormat",(e,t)=>{er.init(e,t),et.init(e,t)});var ar=1,ve=2;function Dn(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function Mn(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Dn(e)||ve;return Tn(e,t)}function Tn(e,t){if(!t.normalize&&t.protocol?.source===Vt.source&&!/^https?:\/\//i.test(e))return ar;try{if(typeof URL<"u"){let r=URL;if(typeof r.parse==="function")return r.parse(e)??ve}return new URL(e)}catch{return ve}}var Fn=/[\t\n\r]/g;function nr(e){return e.replace(Fn,"")}function Zn(e,t){return t.lastIndex=0,t.test(e.hostname)}function On(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var cr=m("$ZodURL",(e,t)=>{tt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim(),o=Mn(n,t);if(o===ar){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(o===ve){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(o===!0){r.value=nr(n);return}if(t.hostname&&!Zn(o,t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort});if(t.protocol&&!On(o,t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort});r.value=t.normalize?o.href:nr(n);return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}});var ur=m("$ZodNumber",(e,t)=>{k.init(e,t),e._zod.pattern=Qe,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}});var lr=m("$ZodBoolean",(e,t)=>{k.init(e,t),e._zod.pattern=Gt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var dr=m("$ZodAny",(e,t)=>{k.init(e,t),e._zod.parse=(r)=>r});var pr=m("$ZodDate",(e,t)=>{k.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(a){}let o=r.value,i=o instanceof Date;if(i&&!Number.isNaN(o.getTime()))return r;return r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});function or(e,t,r){if(e.issues.length)t.issues.push(...K(r,e.issues));t.value[r]=e.value}var fr=m("$ZodArray",(e,t)=>{k.init(e,t);let r=H.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=r?r.alloc(e,n,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let l=0;l<i.length;l++){let c=i[l],u=t.element._zod.run({value:c,issues:[]},o);if(u instanceof Promise)s.push(u.then((p)=>or(p,n,l)));else if(or(u,n,l),a&&u.issues.length!==0&&Z(u))break}if(s.length)return Promise.all(s).then(()=>n);return n}});function _e(e,t,r,n,o,i){let s=r in n,a=i==="optional";if(!s&&a&&o==="optional")return;if(e.issues.length){if(o!==void 0&&a&&!s)return;t.issues.push(...K(r,e.issues))}if(!s&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(s||o==="defaulted"&&!a)t.value[r]=void 0}else t.value[r]=e.value}var Ln=[];function Bn(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:Ln,o=n.length?[...t,...n]:t;for(let s of o)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=Ot(e.shape);return{...e,allKeys:o,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function Nn(e,t,r,n,o,i,s){let a=[],l=o.keySet,c=o.catchall._zod,u=c.def.type,{optin:p,optout:d}=c,f=0;for(let h in t){if(s&&r.issues.length!==f){if(Z(r,f))break;f=r.issues.length}if(l.has(h))continue;if(h==="__proto__"){if(u==="never")a.push(h);continue}if(u==="never"){a.push(h);continue}let g=c.run({value:t[h],issues:[]},n);if(g instanceof Promise)e.push(g.then((C)=>_e(C,r,h,t,p,d)));else _e(g,r,h,t,p,d)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i,continue:!0});if(!e.length)return r;return Promise.all(e).then(()=>r)}var hr=m("$ZodObject",(e,t)=>{k.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){let c=()=>{let u={...n};return Object.defineProperty(t,"shape",{value:u}),c.raw=u,u};c.raw=n,Object.defineProperty(t,"shape",{get:c})}let o=It(()=>Bn(t));R(e,"propValues",(c)=>{let u=c.def.shape,p={};for(let d in u){let f=u[d]._zod;if(f.values){if(!Object.prototype.hasOwnProperty.call(p,d))Mt(p,d,new Set);for(let h of f.values)p[d].add(h);if(f.optin!==void 0)p[d].add(void 0)}}return p});let i=ge,s=t.catchall,a,l=H.memoizer;l?.attach(e),e._zod.parse=(c,u)=>{a??(a=o.value);let p=c.value;if(!i(p))return c.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),c;c.value=l?l.alloc(e,c,{},u):{};let d=[],f=a.shape,h=u?.abortEarly,g=c.issues.length;for(let C of a.allKeys){if(h&&c.issues.length!==g){if(Z(c,g))break;g=c.issues.length}if(C==="__proto__")continue;let y=f[C],G=y._zod.optin,yt=y._zod.optout,v=y._zod.run({value:p[C],issues:[]},u);if(v instanceof Promise)d.push(v.then((Qr)=>_e(Qr,c,C,p,G,yt)));else _e(v,c,C,p,G,yt)}if(!s)return d.length?Promise.all(d).then(()=>c):c;return Nn(d,p,c,u,o.value,e,h===!0)}});var mr=m("$ZodRecord",(e,t)=>{k.init(e,t);let r=H.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let i=n.value;if(!Tt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let s=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},o):{};let l=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(l.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let p=t.keyType._zod.run({value:u,issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map((h)=>O(h,o,L())),input:u,path:[u],inst:e});continue}let d=p.value;if(d==="__proto__")continue;let f=t.valueType._zod.run({value:i[u],issues:[]},o);if(f instanceof Promise)s.push(f.then((h)=>{if(h.issues.length)n.issues.push(...K(u,h.issues));n.value[d]=h.value}));else{if(f.issues.length)n.issues.push(...K(u,f.issues));n.value[d]=f.value}}let c;for(let u in i)if(!l.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;n.value[u]=i[u]}else c=c??[],c.push(u);if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c,continue:!0})}else{n.value=r?r.alloc(e,n,{},o):{};let l;for(let c of Reflect.ownKeys(i)){if(c==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,c))continue;let u=t.keyType._zod.run({value:c,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof c==="string"&&Qe.test(c)&&u.issues.length){let h=t.keyType._zod.run({value:Number(c),issues:[]},o);if(h instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(h.issues.length===0)u=h}if(u.issues.length){if(t.mode==="loose")n.value[c]=i[c];else if(a)l=l??[],l.push(c);else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((h)=>O(h,o,L())),input:c,path:[c],inst:e});continue}let d=u.value;if(d==="__proto__")continue;let f=t.valueType._zod.run({value:i[c],issues:[]},o);if(f instanceof Promise)s.push(f.then((h)=>{if(h.issues.length)n.issues.push(...K(c,h.issues));n.value[d]=h.value}));else{if(f.issues.length)n.issues.push(...K(c,f.issues));n.value[d]=f.value}}if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l,continue:!0})}if(s.length)return Promise.all(s).then(()=>n);return n}});var gr=m("$ZodEnum",(e,t)=>{k.init(e,t);let r=Ue(t.entries),n=new Set(r);e._zod.values=n,R(e,"pattern",(o)=>{let i=Ue(o.def.entries).filter((s)=>Ft.has(typeof s));return new RegExp(i.length?`^(${i.map((s)=>Zt(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,i)=>{let s=o.value;if(n.has(s))return o;return o.issues.push({code:"invalid_value",values:r,input:s,inst:e}),o}});var yr=m("$ZodTransform",(e,t)=>{k.init(e,t),e._zod.optin="optional",H.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new He(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((s)=>(r.value=s,r));if(o instanceof Promise)throw new I;return r.value=o,r}});function ir(e,t){return e.value=t.issues.length?void 0:t.value,e}var br=m("$ZodOptional",(e,t)=>{k.init(e,t),R(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",R(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),R(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Dt(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((i)=>ir(r,i));return ir(r,o)}return t.innerType._zod.run(r,n)}});var xr=m("$ZodPipe",(e,t)=>{k.init(e,t),R(e,"values",(r)=>r.def.in._zod.values),R(e,"optin",(r)=>r.def.in._zod.optin),R(e,"optout",(r)=>r.def.out._zod.optout),R(e,"propValues",(r)=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>xe(s,t.in,n));return xe(i,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>xe(i,t.out,n));return xe(o,t.out,n)}});function xe(e,t,r){if(e.issues.some((n)=>n.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},r)}function vr(e){if(e.checks)e.checks=[...e.checks];return e}function _r(e,t){return new e(vr({type:"string",...E(t)}))}function Er(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...E(t)})}function wr(e,t){return new e(vr({type:"number",checks:[],...E(t)}))}function kr(e,t){return new e({type:"boolean",...E(t)})}function Cr(e){return new e({type:"any"})}function Ar(e,t){return new e({type:"date",...E(t)})}function Ee(e,t){return new Xt({check:"less_than",...E(t),value:e,inclusive:!0})}function oe(e,t){return new Qt({check:"greater_than",...E(t),value:e,inclusive:!0})}var P=m("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");k.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){j(this,"with",e)},parse(e,t){return qe(this,e,t,{callee:this.parse})},parseAsync(e,t){return Ge(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Ye(this,e,t)},safeParseAsync(e,t){return Xe(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0})},clone(e,t){return ye(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),Sr=m("ZodMiniString",(e,t)=>{et.init(e,t),P.init(e,t)});function b(e){return _r(Sr,e)}var jn=m("ZodMiniStringFormat",(e,t)=>{tt.init(e,t),Sr.init(e,t)});var Kn=m("ZodMiniURL",(e,t)=>{cr.init(e,t),jn.init(e,t)});function $r(e){return Er(Kn,e)}var Hn=m("ZodMiniNumber",(e,t)=>{ur.init(e,t),P.init(e,t)});function J(e){return wr(Hn,e)}var Jn=m("ZodMiniBoolean",(e,t)=>{lr.init(e,t),P.init(e,t)});function Vn(e){return kr(Jn,e)}var qn=m("ZodMiniAny",(e,t)=>{dr.init(e,t),P.init(e,t)});function Gn(){return Cr(qn)}var Yn=m("ZodMiniDate",(e,t)=>{pr.init(e,t),P.init(e,t)});function B(e){return Ar(Yn,e)}var Xn=m("ZodMiniArray",(e,t)=>{fr.init(e,t),P.init(e,t)});function ie(e,t){return new Xn({type:"array",element:e,...E(t)})}var Qn=m("ZodMiniObject",(e,t)=>{hr.init(e,t),P.init(e,t),Ut(e,"shape",(r)=>r._zod.def.shape,!1)});function V(e,t){let r={type:"object",shape:e??{},...E(t)};return new Qn(r)}var Pr=m("ZodMiniRecord",(e,t)=>{mr.init(e,t),P.init(e,t)});function rt(e,t,r){if(!t||!t._zod)return new Pr({type:"record",keyType:b(),valueType:e,...E(t)});return new Pr({type:"record",keyType:e,valueType:t,...E(r)})}var Rr=m("ZodMiniEnum",(e,t)=>{gr.init(e,t),P.init(e,t),e.options=[...e._zod.values]});function nt(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Rr({type:"enum",entries:r,...E(t)})}function ot(e,t){return new Rr({type:"enum",entries:e,...E(t)})}var eo=m("ZodMiniTransform",(e,t)=>{yr.init(e,t),P.init(e,t)});function to(e){return new eo({type:"transform",transform:e})}var ro=m("ZodMiniOptional",(e,t)=>{br.init(e,t),P.init(e,t)});function x(e){return new ro({type:"optional",innerType:e})}var no=m("ZodMiniPipe",(e,t)=>{xr.init(e,t),P.init(e,t)});function oo(e,t){return new no({type:"pipe",in:e,out:t})}var D;((v)=>{v.MESSAGE_SENT="message.sent";v.MESSAGE_DELIVERED="message.delivered";v.MESSAGE_FAILED="message.failed";v.MESSAGE_CLICKED="message.clicked";v.MESSAGE_READ="message.read";v.TEMPLATE_CREATED="template.created";v.TEMPLATE_APPROVED="template.approved";v.TEMPLATE_REJECTED="template.rejected";v.TEMPLATE_UPDATED="template.updated";v.TEMPLATE_DELETED="template.deleted";v.CHANNEL_CREATED="channel.created";v.CHANNEL_VERIFIED="channel.verified";v.SENDER_NUMBER_ADDED="sender_number.added";v.SENDER_NUMBER_VERIFIED="sender_number.verified";v.QUOTA_WARNING="system.quota_warning";v.QUOTA_EXCEEDED="system.quota_exceeded";v.PROVIDER_ERROR="system.provider_error";v.SYSTEM_MAINTENANCE="system.maintenance";v.ANOMALY_DETECTED="analytics.anomaly_detected";v.THRESHOLD_EXCEEDED="analytics.threshold_exceeded"})(D||={});var so=V({providerId:x(b()),channelId:x(b()),templateId:x(b()),messageId:x(b()),userId:x(b()),organizationId:x(b()),correlationId:x(b()),retryCount:x(J())}),ao=V({maxRetries:J().check(oe(0),Ee(10)),retryDelayMs:J().check(oe(1000)),backoffMultiplier:J().check(oe(1),Ee(5))}),co=V({providerId:x(ie(b())),channelId:x(ie(b())),templateId:x(ie(b()))}),uo=V({attemptNumber:J(),timestamp:B(),httpStatus:x(J()),responseBody:x(b()),responseHeaders:x(rt(b(),b())),error:x(b()),latencyMs:J()}),Vc=V({id:b(),type:ot(D),timestamp:oo(to((e)=>{if(e instanceof Date)return e;if(typeof e==="string"||typeof e==="number")return new Date(e);return e}),B()),data:Gn(),metadata:so,version:b()}),qc=V({id:b(),url:$r(),name:x(b()),description:x(b()),active:Vn(),events:ie(ot(D)),headers:x(rt(b(),b())),secret:x(b()),retryConfig:x(ao),filters:x(co),createdAt:B(),updatedAt:B(),lastTriggeredAt:x(B()),status:nt(["active","inactive","error","suspended"])}),Gc=V({id:b(),endpointId:b(),eventId:b(),eventType:x(ot(D)),url:$r(),httpMethod:nt(["POST","PUT","PATCH"]),headers:rt(b(),b()),payload:b(),attempts:ie(uo),status:nt(["pending","success","failed","exhausted"]),createdAt:B(),completedAt:x(B()),nextRetryAt:x(B())});class zr extends A{config;endpoints=new Map;indexByUrl=new Map;indexByEvent=new Map;indexByStatus=new Map;defaultConfig={type:"memory",retentionDays:90};constructor(e={}){super();if(this.config={...this.defaultConfig,...e},this.initializeIndexes(),this.config.type==="file"&&this.config.filePath)this.loadFromFile().catch((t)=>{this.emit("loadError",t)})}async addEndpoint(e){if(this.indexByUrl.has(e.url)){if(this.indexByUrl.get(e.url)!==e.id)throw Error(`Endpoint with URL ${e.url} already exists with different ID`)}let t=this.endpoints.get(e.id);if(t)this.removeFromIndexes(t);if(this.endpoints.set(e.id,e),this.addToIndexes(e),this.config.type==="file")await this.saveToFile();this.emit("endpointAdded",{endpointId:e.id,url:e.url})}async updateEndpoint(e,t){let r=this.endpoints.get(e);if(!r)throw Error(`Endpoint ${e} not found`);if(t.url&&t.url!==r.url){if(this.indexByUrl.has(t.url)){if(this.indexByUrl.get(t.url)!==e)throw Error(`Endpoint with URL ${t.url} already exists`)}}this.removeFromIndexes(r);let n={...r,...t,updatedAt:new Date};if(this.endpoints.set(e,n),this.addToIndexes(n),this.config.type==="file")await this.saveToFile();return this.emit("endpointUpdated",{endpointId:e,changes:Object.keys(t),oldUrl:r.url,newUrl:n.url}),n}async removeEndpoint(e){let t=this.endpoints.get(e);if(!t)return!1;if(this.removeFromIndexes(t),this.endpoints.delete(e),this.config.type==="file")await this.saveToFile();return this.emit("endpointRemoved",{endpointId:e,url:t.url}),!0}async getEndpoint(e){return this.endpoints.get(e)||null}async getEndpointByUrl(e){let t=this.indexByUrl.get(e);return t?this.endpoints.get(t)||null:null}async searchEndpoints(e={},t={page:1,limit:100}){let r=null;if(e.status){let c=this.indexByStatus.get(e.status);r=c?new Set(c):new Set}if(e.events&&e.events.length>0){let c=new Set;for(let u of e.events){let p=this.indexByEvent.get(u);if(p)p.forEach((d)=>{c.add(d)})}if(r)r=new Set(Array.from(r).filter((u)=>c.has(u)));else r=c}if(!r)r=new Set(this.endpoints.keys());let n=Array.from(r).map((c)=>this.endpoints.get(c)).filter((c)=>this.matchesFilter(c,e));if(t.sortBy)n.sort((c,u)=>{let p=this.getFieldValue(c,t.sortBy),d=this.getFieldValue(u,t.sortBy),f=0;if(p<d)f=-1;else if(p>d)f=1;return t.sortOrder==="desc"?-f:f});let o=n.length,i=Math.ceil(o/t.limit),s=(t.page-1)*t.limit,a=s+t.limit;return{items:n.slice(s,a),totalCount:o,page:t.page,totalPages:i,hasNext:t.page<i,hasPrevious:t.page>1}}async getActiveEndpointsForEvent(e){let t=this.indexByEvent.get(e);if(!t)return[];return Array.from(t).map((r)=>this.endpoints.get(r)).filter((r)=>r.status==="active")}getStats(){let e=this.endpoints.size,t=this.indexByStatus.get("active")?.size||0,r=this.indexByStatus.get("inactive")?.size||0,n=this.indexByStatus.get("error")?.size||0,o=this.indexByStatus.get("suspended")?.size||0,i={};for(let[s,a]of this.indexByEvent.entries())i[s]=a.size;return{totalEndpoints:e,activeEndpoints:t,inactiveEndpoints:r,errorEndpoints:n,suspendedEndpoints:o,eventSubscriptions:i}}async cleanupExpiredEndpoints(){if(!this.config.retentionDays)return 0;let e=new Date;e.setDate(e.getDate()-this.config.retentionDays);let t=Array.from(this.endpoints.values()).filter((r)=>r.status==="inactive"&&(!r.lastTriggeredAt||r.lastTriggeredAt<e));for(let r of t)await this.removeEndpoint(r.id);if(t.length>0)this.emit("expiredEndpointsCleanup",{removedCount:t.length,cutoffDate:e});return t.length}initializeIndexes(){let e=Object.values(D);for(let r of e)this.indexByEvent.set(r,new Set);let t=["active","inactive","error","suspended"];for(let r of t)this.indexByStatus.set(r,new Set)}addToIndexes(e){this.indexByUrl.set(e.url,e.id);let t=this.indexByStatus.get(e.status);if(t)t.add(e.id);for(let r of e.events){let n=this.indexByEvent.get(r);if(n)n.add(e.id)}}removeFromIndexes(e){this.indexByUrl.delete(e.url);let t=this.indexByStatus.get(e.status);if(t)t.delete(e.id);for(let r of e.events){let n=this.indexByEvent.get(r);if(n)n.delete(e.id)}}matchesFilter(e,t){if(t.providerId&&t.providerId.length>0){if(!t.providerId.some((n)=>e.filters?.providerId?.includes(n)))return!1}if(t.channelId&&t.channelId.length>0){if(!t.channelId.some((n)=>e.filters?.channelId?.includes(n)))return!1}if(t.createdAfter&&e.createdAt<t.createdAfter)return!1;if(t.createdBefore&&e.createdAt>t.createdBefore)return!1;if(t.lastTriggeredAfter&&(!e.lastTriggeredAt||e.lastTriggeredAt<t.lastTriggeredAfter))return!1;if(t.lastTriggeredBefore&&(!e.lastTriggeredAt||e.lastTriggeredAt>t.lastTriggeredBefore))return!1;return!0}getFieldValue(e,t){return t.split(".").reduce((r,n)=>r?.[n],e)}async loadFromFile(){if(!this.config.filePath)return;try{let t=await w(this.config.fileAdapter).readFile(this.config.filePath),r=JSON.parse(t);for(let n of r.endpoints||[]){let o={...n,createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt),lastTriggeredAt:n.lastTriggeredAt?new Date(n.lastTriggeredAt):void 0};this.endpoints.set(o.id,o),this.addToIndexes(o)}this.emit("dataLoaded",{filePath:this.config.filePath,endpointCount:this.endpoints.size})}catch(e){if(!T(e))this.emit("loadError",e)}}async saveToFile(){if(!this.config.filePath)return;try{let e=w(this.config.fileAdapter),t={endpoints:Array.from(this.endpoints.values()),savedAt:new Date().toISOString()},r=JSON.stringify(t,null,2);await e.ensureDirForFile(this.config.filePath),await e.writeFile(this.config.filePath,r),this.emit("dataSaved",{filePath:this.config.filePath,endpointCount:this.endpoints.size})}catch(e){throw this.emit("saveError",e),e}}async shutdown(){if(this.config.type==="file")await this.saveToFile().catch((e)=>{this.emit("saveError",e)});this.emit("shutdown",{endpointCount:this.endpoints.size})}}class Ir extends A{config;events=new Map;indexByType=new Map;indexByDate=new Map;indexByProvider=new Map;indexByChannel=new Map;cleanupInterval=null;defaultConfig={type:"memory",retentionDays:7,enableCompression:!1,maxMemoryUsage:52428800};constructor(e={}){super();if(this.config={...this.defaultConfig,...e},this.initializeIndexes(),this.startCleanupTask(),this.config.type==="file"&&this.config.filePath)this.loadFromFile().catch((t)=>{this.emit("loadError",t)})}async saveEvent(e){if(this.events.has(e.id)){this.emit("duplicateEvent",{eventId:e.id});return}if(this.config.type==="memory"&&this.config.maxMemoryUsage)await this.checkMemoryUsage();if(this.events.set(e.id,e),this.addToIndexes(e),this.config.type==="file")await this.appendToFile(e);this.emit("eventSaved",{eventId:e.id,type:e.type,providerId:e.metadata.providerId})}async getEvent(e){return this.events.get(e)||null}async searchEvents(e={},t={page:1,limit:100}){let r=null;if(e.type&&e.type.length>0){let c=new Set;for(let u of e.type){let p=this.indexByType.get(u);if(p)p.forEach((d)=>{c.add(d)})}r=c}if(e.providerId&&e.providerId.length>0){let c=new Set;for(let u of e.providerId){let p=this.indexByProvider.get(u);if(p)p.forEach((d)=>{c.add(d)})}if(r)r=new Set(Array.from(r).filter((u)=>c.has(u)));else r=c}if(e.channelId&&e.channelId.length>0){let c=new Set;for(let u of e.channelId){let p=this.indexByChannel.get(u);if(p)p.forEach((d)=>{c.add(d)})}if(r)r=new Set(Array.from(r).filter((u)=>c.has(u)));else r=c}if(e.createdAfter||e.createdBefore){let c=this.getEventIdsByDateRange(e.createdAfter,e.createdBefore);if(r)r=new Set(Array.from(r).filter((u)=>c.has(u)));else r=c}if(!r)r=new Set(this.events.keys());let n=Array.from(r).map((c)=>this.events.get(c)).filter((c)=>this.matchesFilter(c,e));n.sort((c,u)=>{if(t.sortBy==="timestamp"||!t.sortBy){let h=u.timestamp.getTime()-c.timestamp.getTime();return t.sortOrder==="asc"?-h:h}let p=this.getFieldValue(c,t.sortBy),d=this.getFieldValue(u,t.sortBy),f=0;if(p<d)f=-1;else if(p>d)f=1;return t.sortOrder==="desc"?-f:f});let o=n.length,i=Math.ceil(o/t.limit),s=(t.page-1)*t.limit,a=s+t.limit;return{items:n.slice(s,a),totalCount:o,page:t.page,totalPages:i,hasNext:t.page<i,hasPrevious:t.page>1}}async getEventsByType(e,t=100){let r=this.indexByType.get(e);if(!r)return[];return Array.from(r).map((n)=>this.events.get(n)).sort((n,o)=>o.timestamp.getTime()-n.timestamp.getTime()).slice(0,t)}async getEventStats(e){let t={createdAfter:e?.start,createdBefore:e?.end},n=(await this.searchEvents(t,{page:1,limit:1e4})).items,o={};for(let l of Object.values(D))o[l]=0;let i={},s={},a={};for(let l of n){if(o[l.type]++,l.metadata.providerId)i[l.metadata.providerId]=(i[l.metadata.providerId]||0)+1;if(l.metadata.channelId)s[l.metadata.channelId]=(s[l.metadata.channelId]||0)+1;let c=l.timestamp.toISOString().substring(0,13);a[c]=(a[c]||0)+1}return{totalEvents:n.length,eventsByType:o,eventsByProvider:i,eventsByChannel:s,eventsPerHour:a}}async cleanupOldEvents(){if(!this.config.retentionDays)return 0;let e=new Date;e.setDate(e.getDate()-this.config.retentionDays);let t=Array.from(this.events.values()).filter((r)=>r.timestamp<e);for(let r of t)this.removeFromIndexes(r),this.events.delete(r.id);if(t.length>0){if(this.emit("oldEventsCleanup",{removedCount:t.length,cutoffDate:e}),this.config.type==="file")await this.saveToFile()}return t.length}async cleanupDuplicateEvents(){let e=new Map;for(let r of this.events.values()){let n=this.generateContentKey(r);if(!e.has(n))e.set(n,[]);e.get(n).push(r)}let t=0;for(let[r,n]of e.entries())if(n.length>1){n.sort((o,i)=>i.timestamp.getTime()-o.timestamp.getTime());for(let o=1;o<n.length;o++){let i=n[o];this.removeFromIndexes(i),this.events.delete(i.id),t++}}if(t>0){if(this.emit("duplicateEventsCleanup",{removedCount:t}),this.config.type==="file")await this.saveToFile()}return t}getStorageStats(){let e=this.estimateMemoryUsage();return{totalEvents:this.events.size,memoryUsage:e,indexSizes:{byType:this.indexByType.size,byDate:this.indexByDate.size,byProvider:this.indexByProvider.size,byChannel:this.indexByChannel.size}}}initializeIndexes(){let e=Object.values(D);for(let t of e)this.indexByType.set(t,new Set)}addToIndexes(e){let t=this.indexByType.get(e.type);if(t)t.add(e.id);let r=e.timestamp.toISOString().split("T")[0];if(!this.indexByDate.has(r))this.indexByDate.set(r,new Set);if(this.indexByDate.get(r).add(e.id),e.metadata.providerId){if(!this.indexByProvider.has(e.metadata.providerId))this.indexByProvider.set(e.metadata.providerId,new Set);this.indexByProvider.get(e.metadata.providerId).add(e.id)}if(e.metadata.channelId){if(!this.indexByChannel.has(e.metadata.channelId))this.indexByChannel.set(e.metadata.channelId,new Set);this.indexByChannel.get(e.metadata.channelId).add(e.id)}}removeFromIndexes(e){let t=this.indexByType.get(e.type);if(t)t.delete(e.id);let r=e.timestamp.toISOString().split("T")[0],n=this.indexByDate.get(r);if(n){if(n.delete(e.id),n.size===0)this.indexByDate.delete(r)}if(e.metadata.providerId){let o=this.indexByProvider.get(e.metadata.providerId);if(o){if(o.delete(e.id),o.size===0)this.indexByProvider.delete(e.metadata.providerId)}}if(e.metadata.channelId){let o=this.indexByChannel.get(e.metadata.channelId);if(o){if(o.delete(e.id),o.size===0)this.indexByChannel.delete(e.metadata.channelId)}}}getEventIdsByDateRange(e,t){let r=new Set;for(let[n,o]of this.indexByDate.entries()){let i=new Date(n);if(e&&i<e)continue;if(t&&i>t)continue;o.forEach((s)=>{r.add(s)})}return r}matchesFilter(e,t){if(t.templateId&&t.templateId.length>0){if(!e.metadata.templateId||!t.templateId.includes(e.metadata.templateId))return!1}if(t.messageId&&t.messageId.length>0){if(!e.metadata.messageId||!t.messageId.includes(e.metadata.messageId))return!1}if(t.userId&&t.userId.length>0){if(!e.metadata.userId||!t.userId.includes(e.metadata.userId))return!1}if(t.organizationId&&t.organizationId.length>0){if(!e.metadata.organizationId||!t.organizationId.includes(e.metadata.organizationId))return!1}return!0}getFieldValue(e,t){return t.split(".").reduce((r,n)=>r?.[n],e)}estimateMemoryUsage(){let e=0;for(let t of this.events.values())e+=JSON.stringify(t).length*2;return e}async checkMemoryUsage(){if(!this.config.maxMemoryUsage)return;let e=this.estimateMemoryUsage();if(e>this.config.maxMemoryUsage){let t=Array.from(this.events.values()).sort((o,i)=>o.timestamp.getTime()-i.timestamp.getTime()),r=0,n=this.config.maxMemoryUsage*0.8;for(let o of t){if(this.estimateMemoryUsage()<=n)break;this.removeFromIndexes(o),this.events.delete(o.id),r++}if(r>0)this.emit("memoryCleanup",{removedCount:r,previousUsage:e,currentUsage:this.estimateMemoryUsage()})}}generateContentKey(e){return`${e.type}_${e.metadata.messageId||""}_${e.metadata.templateId||""}_${JSON.stringify(e.data)}`}startCleanupTask(){this.cleanupInterval=setInterval(()=>{this.cleanupOldEvents().then(()=>this.cleanupDuplicateEvents()).catch((e)=>{this.emit("cleanupError",e)})},3600000)}async appendToFile(e){if(!this.config.filePath)return;try{let t=w(this.config.fileAdapter),r=JSON.stringify(e)+`
|
|
7
|
+
`;await t.ensureDirForFile(this.config.filePath),await t.appendFile(this.config.filePath,r)}catch(t){this.emit("appendError",t)}}async loadFromFile(){if(!this.config.filePath)return;try{let r=(await w(this.config.fileAdapter).readFile(this.config.filePath)).trim().split(`
|
|
8
|
+
`).filter((n)=>n.trim());for(let n of r)try{let o=JSON.parse(n),i={...o,timestamp:new Date(o.timestamp)};this.events.set(i.id,i),this.addToIndexes(i)}catch(o){this.emit("parseError",{line:n,error:o})}this.emit("dataLoaded",{filePath:this.config.filePath,eventCount:this.events.size})}catch(e){if(!T(e))this.emit("loadError",e)}}async saveToFile(){if(!this.config.filePath)return;try{let e=w(this.config.fileAdapter),t=Array.from(this.events.values()).map((r)=>JSON.stringify(r)).join(`
|
|
9
|
+
`);await e.ensureDirForFile(this.config.filePath),await e.writeFile(this.config.filePath,t+`
|
|
10
|
+
`),this.emit("dataSaved",{filePath:this.config.filePath,eventCount:this.events.size})}catch(e){throw this.emit("saveError",e),e}}async shutdown(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;if(this.config.type==="file")await this.saveToFile().catch((e)=>{this.emit("saveError",e)});this.emit("shutdown",{eventCount:this.events.size})}}class we{config;constructor(e){this.config={maxRetries:e.maxRetries,baseDelayMs:e.retryDelayMs,maxDelayMs:e.maxDelayMs||300000,backoffMultiplier:e.backoffMultiplier||2,jitter:e.jitter!==!1}}calculateNextRetry(e){if(e>=this.config.maxRetries)throw Error(`Maximum retry attempts (${this.config.maxRetries}) exceeded`);let t=this.config.baseDelayMs*this.config.backoffMultiplier**e;if(t=Math.min(t,this.config.maxDelayMs),this.config.jitter)t=t*(0.5+Math.random()*0.5);return new Date(Date.now()+t)}shouldRetry(e,t){if(e>=this.config.maxRetries)return!1;if(t)return this.isRetryableError(t);return!0}isRetryableError(e){let t=e.message.toLowerCase();return["timeout","network","connection","econnreset","enotfound","econnrefused","socket hang up"].some((n)=>t.includes(n))}shouldRetryStatus(e){if(e>=400&&e<500)return[408,429].includes(e);if(e>=500)return!0;return!1}calculateRetryStats(e){if(e.length===0)return{totalAttempts:0,successfulAttempts:0,failedAttempts:0,averageDelayMs:0,totalTimeMs:0};let t=e.filter((s)=>s.success).length,r=e.length-t,n=0;for(let s=1;s<e.length;s++)n+=e[s].timestamp.getTime()-e[s-1].timestamp.getTime();let o=e.length>1?n/(e.length-1):0,i=e.length>0?e[e.length-1].timestamp.getTime()-e[0].timestamp.getTime():0;return{totalAttempts:e.length,successfulAttempts:t,failedAttempts:r,averageDelayMs:o,totalTimeMs:i}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}getBackoffDelay(e){let t=this.config.baseDelayMs*this.config.backoffMultiplier**e;return Math.min(t,this.config.maxDelayMs)}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function lo(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Dr(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function q(e,...t){if(!lo(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Mr(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");Dr(e.outputLen),Dr(e.blockLen)}function ee(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Tr(e,t){q(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function z(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ke(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function S(e,t){return e<<32-t|e>>>t}function Ce(e,t){return e<<t|e>>>32-t>>>0}var po=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),fo=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function it(e){if(q(e),po)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=fo[e[r]];return t}function ho(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function se(e){if(typeof e==="string")e=ho(e);return q(e),e}class ae{}function Ae(e){let t=(n)=>e().update(se(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}class st extends ae{constructor(e,t){super();this.finished=!1,this.destroyed=!1,Mr(e);let r=se(t);if(this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),z(o)}update(e){return ee(this),this.iHash.update(e),this}digestInto(e){ee(this),q(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:s}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Pe=(e,t,r)=>new st(e,t).update(r).digest();Pe.create=(e,t)=>new st(e,t);function mo(e,t,r,n){if(typeof e.setBigUint64==="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),l=n?4:0,c=n?0:4;e.setUint32(t+l,s,n),e.setUint32(t+c,a,n)}function Se(e,t,r){return e&t^~e&r}function $e(e,t,r){return e&t^e&r^t&r}class ce extends ae{constructor(e,t,r,n){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ke(this.buffer)}update(e){ee(this),e=se(e),q(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){let a=ke(e);for(;n<=o-i;i+=n)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){ee(this),Tr(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,z(this.buffer.subarray(i)),this.padOffset>n-i)this.process(r,0),i=0;for(let u=i;u<n;u++)t[u]=0;mo(r,n-8,BigInt(this.length*8),o),this.process(r,0);let s=ke(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");let l=a/4,c=this.get();if(l>c.length)throw Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)s.setUint32(4*u,c[u],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=o,e.length=n,e.pos=s,n%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var M=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ue=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),N=new Uint32Array(80);class at extends ce{constructor(){super(64,20,8,!1);this.A=ue[0]|0,this.B=ue[1]|0,this.C=ue[2]|0,this.D=ue[3]|0,this.E=ue[4]|0}get(){let{A:e,B:t,C:r,D:n,E:o}=this;return[e,t,r,n,o]}set(e,t,r,n,o){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0}process(e,t){for(let a=0;a<16;a++,t+=4)N[a]=e.getUint32(t,!1);for(let a=16;a<80;a++)N[a]=Ce(N[a-3]^N[a-8]^N[a-14]^N[a-16],1);let{A:r,B:n,C:o,D:i,E:s}=this;for(let a=0;a<80;a++){let l,c;if(a<20)l=Se(n,o,i),c=1518500249;else if(a<40)l=n^o^i,c=1859775393;else if(a<60)l=$e(n,o,i),c=2400959708;else l=n^o^i,c=3395469782;let u=Ce(r,5)+l+s+c+N[a]|0;s=i,i=o,o=Ce(n,30),n=r,r=u}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,this.set(r,n,o,i,s)}roundClean(){z(N)}destroy(){this.set(0,0,0,0,0),z(this.buffer)}}var Fr=Ae(()=>new at);var Zr=Fr;var go=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),U=new Uint32Array(64);class Or extends ce{constructor(e=32){super(64,e,8,!1);this.A=M[0]|0,this.B=M[1]|0,this.C=M[2]|0,this.D=M[3]|0,this.E=M[4]|0,this.F=M[5]|0,this.G=M[6]|0,this.H=M[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)U[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let p=U[u-15],d=U[u-2],f=S(p,7)^S(p,18)^p>>>3,h=S(d,17)^S(d,19)^d>>>10;U[u]=h+U[u-7]+f+U[u-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:l,H:c}=this;for(let u=0;u<64;u++){let p=S(s,6)^S(s,11)^S(s,25),d=c+p+Se(s,a,l)+go[u]+U[u]|0,h=(S(r,2)^S(r,13)^S(r,22))+$e(r,n,o)|0;c=l,l=a,a=s,s=i+d|0,i=o,o=n,n=r,r=d+h|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(r,n,o,i,s,a,l,c)}roundClean(){z(U)}destroy(){this.set(0,0,0,0,0,0,0,0),z(this.buffer)}}var Lr=Ae(()=>new Or);class Re{config;encoder=new TextEncoder;constructor(e){this.config={algorithm:e.algorithm||"sha256",header:e.signatureHeader||"X-Webhook-Signature",prefix:e.signaturePrefix||"sha256="}}createSignedPayload(e,t){return`${t}.${e}`}generateSignature(e,t){let r=this.generateSignatureDigest(e,t);return this.config.prefix?`${this.config.prefix}${r}`:r}generateSignatureWithTimestamp(e,t,r){return this.generateSignature(this.createSignedPayload(e,t),r)}verifySignature(e,t,r){try{let n=this.generateSignature(e,r);return this.constantTimeCompare(t,n)}catch(n){return Y.error("Signature verification failed",void 0,n instanceof Error?n:Error(String(n))),!1}}verifySignatureWithTimestamp(e,t,r,n){return this.verifySignature(this.createSignedPayload(e,t),r,n)}extractSignature(e){let t=this.config.header.toLowerCase();for(let[r,n]of Object.entries(e))if(r.toLowerCase()===t)return n;return null}createSecurityHeaders(e,t){let r=Math.floor(Date.now()/1000).toString(),n=this.generateSignatureWithTimestamp(e,r,t);return{[this.config.header]:n,"X-Webhook-Timestamp":r,"X-Webhook-ID":this.generateWebhookId(),"User-Agent":"K-Message-Webhook/1.0"}}verifyTimestamp(e,t=300){try{let r=(()=>{if(/^[0-9]+$/.test(e.trim()))return parseInt(e,10);let i=new Date(e);if(Number.isNaN(i.getTime()))return NaN;return Math.floor(i.getTime()/1000)})(),n=Math.floor(Date.now()/1000);return Math.abs(n-r)<=t}catch{return!1}}generateWebhookId(){let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return`wh_${it(e)}`}generateSignatureDigest(e,t){let r=this.encoder.encode(t),n=this.encoder.encode(e),o=this.config.algorithm==="sha1"?Pe(Zr,r,n):Pe(Lr,r,n);return it(o)}constantTimeCompare(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}}class ct{async fetch(e,t){return fetch(e,t)}}class Br{responses=new Map;defaultResponse=new Response(JSON.stringify({status:"ok"}),{status:200,statusText:"OK",headers:{"content-type":"application/json"}});setMockResponse(e,t){this.responses.set(e,t)}setDefaultResponse(e){this.defaultResponse=e}async fetch(e,t){let r=this.responses.get(e);if(r)return r;return this.defaultResponse}}class Nr{config;httpClient;securityManager;retryManager;constructor(e,t){this.config=e,this.httpClient=t||new ct,this.securityManager=new Re(e),this.retryManager=new we(e)}async dispatch(e,t){let r=JSON.stringify(e),n=(()=>{if(e.timestamp instanceof Date)return e.timestamp;let s=new Date(e.timestamp);return Number.isNaN(s.getTime())?new Date:s})(),o=Math.floor(n.getTime()/1000).toString(),i={id:this.generateDeliveryId(),endpointId:t.id,eventId:e.id,eventType:e.type,url:t.url,httpMethod:"POST",headers:this.buildHeaders(t,e,r,o),payload:r,attempts:[],status:"pending",createdAt:new Date};return await this.executeDelivery(i,t),i}async executeDelivery(e,t){let r=t.retryConfig?.maxRetries??this.config.maxRetries;for(let n=1;n<=r+1;n++){let o=await this.makeHttpRequest(e,t,n);if(e.attempts.push(o),o.httpStatus&&o.httpStatus>=200&&o.httpStatus<300){e.status="success",e.completedAt=new Date;return}if(!(n<=r&&this.shouldRetryAttempt(o))){e.status="failed",e.completedAt=new Date;return}let s=this.calculateRetryDelay(n,t);e.nextRetryAt=new Date(Date.now()+s),await this.sleep(s)}e.status="exhausted",e.completedAt=new Date}shouldRetryAttempt(e){if(typeof e.httpStatus==="number")return this.retryManager.shouldRetryStatus(e.httpStatus);if(e.error)return this.retryManager.isRetryableError(Error(e.error));return!0}async makeHttpRequest(e,t,r){let n=Date.now(),o={attemptNumber:r,timestamp:new Date,latencyMs:0};try{let i=await this.httpClient.fetch(e.url,{method:e.httpMethod,headers:e.headers,body:e.payload,redirect:"manual",signal:AbortSignal.timeout(this.config.timeoutMs)});o.httpStatus=i.status,o.responseBody=await i.text();let s={};if(i.headers.forEach((a,l)=>{s[l]=a}),o.responseHeaders=s,o.latencyMs=Date.now()-n,!i.ok)o.error=`HTTP ${i.status}: ${i.statusText}`}catch(i){o.latencyMs=Date.now()-n,o.error=i instanceof Error?i.message:"Unknown error"}return o}buildHeaders(e,t,r,n){let o={"Content-Type":"application/json","X-Webhook-ID":t.id,"X-Webhook-Event":t.type,"X-Webhook-Timestamp":n,"User-Agent":"K-Message-Webhook/1.0"};if(e.headers)Object.assign(o,e.headers);if(this.config.enableSecurity){let i=(typeof e.secret==="string"&&e.secret.length>0?e.secret:typeof this.config.secretKey==="string"&&this.config.secretKey.length>0?this.config.secretKey:void 0)||void 0;if(i){let s=this.securityManager.generateSignatureWithTimestamp(r,n,i),a=this.securityManager.getConfig().header;o[a]=s}}return o}calculateRetryDelay(e,t){let r=t.retryConfig?.retryDelayMs||this.config.retryDelayMs,n=t.retryConfig?.backoffMultiplier||this.config.backoffMultiplier||2,o=r*n**e;if(typeof this.config.maxDelayMs==="number")o=Math.min(o,this.config.maxDelayMs);if(this.config.jitter!==!1)o=o*(0.5+Math.random()*0.5);return Math.max(0,Math.floor(o))}sleep(e){return new Promise((t)=>setTimeout(t,e))}generateDeliveryId(){return`delivery_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}async shutdown(){}}function yo(e,t){return t.updatedAt.getTime()-e.updatedAt.getTime()}function bo(e,t){let r=t.createdAt.getTime()-e.createdAt.getTime();if(r!==0)return r;if(e.id<t.id)return 1;if(e.id>t.id)return-1;return 0}function ut(e,t){let r=e.createdAt.getTime(),n=t.createdAt.getTime();return r<n||r===n&&e.id<t.id}function xo(e,t){if(t.endpointId&&e.endpointId!==t.endpointId)return!1;if(t.eventType&&e.eventType!==t.eventType)return!1;if(t.before&&!ut(e,t.before))return!1;if(t.status&&e.status!==t.status)return!1;return!0}class Ur{endpoints=new Map;async add(e){this.endpoints.set(e.id,e)}async update(e,t){if(!this.endpoints.has(e))throw Error(`Webhook endpoint ${e} not found`);this.endpoints.set(e,t)}async remove(e){this.endpoints.delete(e)}async get(e){return this.endpoints.get(e)??null}async list(){return Array.from(this.endpoints.values()).sort(yo)}}class Wr{deliveries=new Map;async add(e){this.deliveries.set(e.id,e)}async replace(e){this.deliveries.set(e.id,e)}async list(e={}){let t=Array.from(this.deliveries.values()).filter((n)=>xo(n,e)).sort(bo),r=typeof e.limit==="number"&&Number.isFinite(e.limit)?Math.max(0,Math.floor(e.limit)):100;return t.slice(0,r)}}function Iu(){return{endpointStore:new Ur,deliveryStore:new Wr}}function lt(e){if(typeof e!=="string")return;let t=e.trim();return t.length>0?t:void 0}function Jr(e,t){let r=Te(e);if(r==="plaintext"){if(!e.unsafeAllowPlaintextStorage)throw new _("policy","openFallback=plaintext requires unsafeAllowPlaintextStorage=true",{rule:"fieldCrypto.fail_open.plaintext_guard",path:"openFallback"},{fieldPath:"openFallback",failMode:"open",openFallback:"plaintext"});return t}if(r==="null")return"";return Et()(t)}function Vr(e,t,r){if(e instanceof _){if(e.fieldPath)return e;return new _(e.kind,e.message,e.details,{providerErrorCode:e.providerErrorCode,providerErrorText:e.providerErrorText,httpStatus:e.httpStatus,requestId:e.requestId,retryAfterMs:e.retryAfterMs,attempt:e.attempt,openFallback:e.openFallback,fieldPath:t,failMode:"closed",causeChain:[e]})}return new _(r,`Field crypto ${r} failed for ${t}`,{cause:e instanceof Error?e.message:String(e)},{fieldPath:t,failMode:"closed",causeChain:[e]})}function dt(e,t){return t?{...e,tenantId:t}:e}async function qr(e,t){let r=lt(t.value);if(!r)return;if(!e||e.enabled===!1)return r;let n=he(e),o=e.keyResolver;try{let i={tenantId:t.tenantId,tableName:t.aad.tableName,fieldPath:t.path,messageId:t.aad.messageId,providerId:t.aad.providerId},s=o?await o.resolveEncryptKey(i):void 0,a=lt(s?.kid),l=await e.provider.encrypt({value:r,path:t.path,aad:dt(t.aad,t.tenantId),...a?{kid:a}:{}});return wt(l.ciphertext)}catch(i){if(n==="closed")throw Vr(i,t.path,"encrypt");return Jr(e,r)}}async function pt(e,t){let r=lt(t.value);if(!r)return;if(!e||e.enabled===!1)return r;let n=he(e);try{let o={tenantId:t.tenantId,tableName:t.aad.tableName,fieldPath:t.path,messageId:t.aad.messageId,providerId:t.aad.providerId},i=e.keyResolver?.resolveDecryptKeys?await e.keyResolver.resolveDecryptKeys({...o,ciphertext:r}):void 0,s=(a)=>e.provider.decrypt({ciphertext:r,path:t.path,aad:a,...Array.isArray(i)&&i.length>0?{candidateKids:i}:{}});if(!t.tenantId)return await s(t.aad);if(!t.acceptLegacyAad)return await s(dt(t.aad,t.tenantId));try{return await s(dt(t.aad,t.tenantId))}catch(a){try{return await s(t.aad)}catch(l){throw AggregateError([a,l],"decrypt failed with both the tenant-bound and the legacy AAD")}}}catch(o){if(n==="closed")throw Vr(o,t.path,"decrypt");return Jr(e,r)}}var vo=["encrypt","encrypt+hash"];function jr(e,t){if(e.enabled===!1)return;let r=e.fields[t];if(r!==void 0&&vo.includes(r))return;throw new _("config",r===void 0?`webhook storage always encrypts ${t}; set fields.${t} to "encrypt" or "encrypt+hash"`:`webhook storage always encrypts ${t}; fields.${t} must be "encrypt" or "encrypt+hash", not "${r}"`,{rule:"fieldCrypto.webhook.encrypt_only",path:`fields.${t}`},{fieldPath:`fields.${t}`})}function ft(e){if(!e)return;if(e.endpoint)Fe(e.endpoint),jr(e.endpoint,"secret");if(e.delivery)Fe(e.delivery),jr(e.delivery,"payload")}function ht(e,t){if(t===void 0)return e;if(t)return{...e,secret:t};let r={...e};return delete r.secret,r}function mt(e){return{tableName:"webhook_endpoint",messageId:e.id}}function gt(e){return{tableName:"webhook_delivery",messageId:e.id,providerId:e.endpointId}}async function le(e,t){let r=await qr(t?.endpoint,{value:e.secret,path:"secret",aad:mt(e),tenantId:t?.tenantId});return ht(e,r)}async function de(e,t){let r=await pt(t?.endpoint,{value:e.secret,path:"secret",aad:mt(e),tenantId:t?.tenantId,acceptLegacyAad:t?.acceptLegacyAad});return ht(e,r)}async function pe(e,t){let r=await qr(t?.delivery,{value:e.payload,path:"payload",aad:gt(e),tenantId:t?.tenantId});return{...e,payload:r??e.payload}}async function ze(e,t){let r=await pt(t?.delivery,{value:e.payload,path:"payload",aad:gt(e),tenantId:t?.tenantId,acceptLegacyAad:t?.acceptLegacyAad});return{...e,payload:r??e.payload}}function Fu(e,t){if(!t?.endpoint)return e;return{async add(r){await e.add(await le(r,t))},async update(r,n){await e.update(r,await le(n,t))},async remove(r){await e.remove(r)},async get(r){let n=await e.get(r);if(!n)return null;return await de(n,t)},async list(){let r=await e.list();return await Promise.all(r.map((n)=>de(n,t)))}}}function Zu(e,t){if(!t?.delivery)return e;let r=e.replace?.bind(e);return{async add(n){await e.add(await pe(n,t))},async list(n){let o=await e.list(n);return await Promise.all(o.map((i)=>ze(i,t)))},...r?{async replace(n){await r(await pe(n,t))}}:{}}}var _o=200,Kr=3;function Hr(e){return e?{...e,failMode:"closed"}:void 0}async function Gr(e,t){try{return await pt(e,t),!0}catch{return!1}}async function Yr(e,t,r,n){try{return await e()}catch(o){throw new _("decrypt",`Cannot migrate webhook ${t} ${r}: its ${n} could not be read with the tenant-bound or the legacy AAD (see causeChain)`,{recordId:r},{fieldPath:n,failMode:"closed",causeChain:[o]})}}async function Eo(e,t,r,n){let o={...n,acceptLegacyAad:!0};for(let i=1;;i+=1){let s=await e.get(t);if(!s)return!1;let a={value:s.secret,path:"secret",aad:mt(s),tenantId:n.tenantId};if(await Gr(r,a))return!1;let l=await Yr(()=>de(s,o),"endpoint",t,"secret"),{secret:c}=await le(l,n),u=await e.get(t);if(!u)return!1;if(u.secret===s.secret)return await e.update(t,ht(u,c)),!0;if(i===Kr)throw new _("config",`Cannot migrate webhook endpoint ${t}: its secret changed during each of ${Kr} attempts; pause endpoint updates and run the migration again`,{rule:"fieldCrypto.webhook.tenant_migration",path:"secret"},{fieldPath:"secret"})}}async function Ou(e,t){ft(t);let r=t.tenantId;if(typeof r!=="string"||r.trim().length===0)throw new _("config","migrating webhook ciphertext to the tenant requires fieldCrypto.tenantId",{rule:"fieldCrypto.webhook.tenant_migration",path:"tenantId"},{fieldPath:"tenantId"});let n=e.deliveryStore,o=n.replace?.bind(n);if(t.delivery!==void 0&&t.delivery.enabled!==!1&&!o)throw new _("config","migrating webhook deliveries needs a delivery store with replace(); the built-in stores implement it",{rule:"fieldCrypto.webhook.tenant_migration",path:"deliveryStore"},{fieldPath:"deliveryStore"});let s={tenantId:r,endpoint:Hr(t.endpoint),delivery:Hr(t.delivery)},a={...s,acceptLegacyAad:!0},l={endpoints:0,deliveries:0},c=s.endpoint;if(c&&c.enabled!==!1){let p=e.endpointStore;for(let{id:d}of await p.list())if(await Eo(p,d,c,s))l.endpoints+=1}let u=s.delivery;if(o&&u&&u.enabled!==!1){let p;for(;;){let d=await n.list({limit:_o,...p?{before:p}:{}}),f=d[0],h=d.at(-1);if(!f||!h)break;if(p&&!ut(f,p))throw new _("config","migrating webhook deliveries needs a delivery store whose list() honors the `before` cursor; the built-in stores do",{rule:"fieldCrypto.webhook.tenant_migration",path:"deliveryStore"},{fieldPath:"deliveryStore"});for(let g of d){let C={value:g.payload,path:"payload",aad:gt(g),tenantId:r};if(await Gr(u,C))continue;let y=await Yr(()=>ze(g,a),"delivery",g.id,"payload");await o(await pe(y,s)),l.deliveries+=1}p={createdAt:h.createdAt,id:h.id}}}return l}class Xr{endpoints=new Map;deliveries=new Map;options;constructor(e={}){this.options=e,this.validateCryptoOptions(this.options.fieldCrypto)}async addEndpoint(e){this.endpoints.set(e.id,await this.protectEndpoint(e))}async updateEndpoint(e,t){if(!this.endpoints.has(e))throw Error(`Endpoint ${e} not found`);this.endpoints.set(e,await this.protectEndpoint(t))}async removeEndpoint(e){this.endpoints.delete(e)}async getEndpoint(e){let t=this.endpoints.get(e);if(!t)return null;return await this.revealEndpoint(t)}async listEndpoints(){return await Promise.all(Array.from(this.endpoints.values()).map((e)=>this.revealEndpoint(e)))}async addDelivery(e){this.deliveries.set(e.id,await this.protectDelivery(e))}async getDeliveries(e,t,r,n,o=100){let i=Array.from(this.deliveries.values());if(e)i=i.filter((a)=>a.endpointId===e);if(t)i=i.filter((a)=>a.createdAt>=t.start&&a.createdAt<=t.end);if(r)i=i.filter((a)=>a.eventType===r);if(n)i=i.filter((a)=>a.status===n);let s=i.sort((a,l)=>l.createdAt.getTime()-a.createdAt.getTime()).slice(0,o);return await Promise.all(s.map((a)=>this.revealDelivery(a)))}async getFailedDeliveries(e,t){return(await this.getDeliveries(e,void 0,t,void 0,1000)).filter((n)=>n.status==="failed"||n.status==="exhausted")}protectEndpoint(e){return le(e,this.options.fieldCrypto)}revealEndpoint(e){return de(e,this.options.fieldCrypto)}protectDelivery(e){return pe(e,this.options.fieldCrypto)}revealDelivery(e){return ze(e,this.options.fieldCrypto)}validateCryptoOptions(e){ft(e)}}export{bt as BatchDispatcher,ct as DefaultHttpClient,$t as DeliveryStore,zr as EndpointManager,Ir as EventStore,Pt as LoadBalancer,Br as MockHttpClient,St as QueueManager,we as RetryManager,Re as SecurityManager,Nr as WebhookDispatcher,Xr as WebhookRegistry};
|
|
11
|
+
|
|
12
|
+
//# debugId=A784A8219E602B0964756E2164756E21
|
|
77
13
|
//# sourceMappingURL=index.mjs.map
|