@stacksjs/bun-router 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-03m2j6h7.js +2 -0
- package/dist/chunk-08cw7ejr.js +3 -0
- package/dist/chunk-0e4g0fyv.js +62 -0
- package/dist/chunk-0mmn02yw.js +2 -0
- package/dist/chunk-126c9qm3.js +2 -0
- package/dist/chunk-12p13817.js +2 -0
- package/dist/chunk-14v65c37.js +4 -0
- package/dist/{chunk-s3dn1kwx.js → chunk-1b6a7t3v.js} +2 -2
- package/dist/chunk-1wenkmk0.js +2 -0
- package/dist/chunk-2152npfd.js +2 -0
- package/dist/chunk-26w23krx.js +2 -0
- package/dist/chunk-2g8m379z.js +10 -0
- package/dist/{chunk-5mxby3fd.js → chunk-2rr178et.js} +2 -2
- package/dist/chunk-2w8f3swz.js +29 -0
- package/dist/chunk-3y4gaz7v.js +82 -0
- package/dist/chunk-4r1x4afz.js +12 -0
- package/dist/chunk-4wyw66zk.js +2 -0
- package/dist/chunk-4z5sf8ag.js +2 -0
- package/dist/{chunk-krkchy8v.js → chunk-58tfvayh.js} +3 -3
- package/dist/{chunk-ex5fkjah.js → chunk-5dp83qcx.js} +43 -43
- package/dist/chunk-5f0d9j9a.js +2 -0
- package/dist/{chunk-zhx0hxdd.js → chunk-5z52b0fc.js} +7 -7
- package/dist/{chunk-kc659vhx.js → chunk-5zrnk2kq.js} +3 -3
- package/dist/chunk-6dmqtdnq.js +2 -0
- package/dist/{chunk-5s1pr62n.js → chunk-6e91956t.js} +2 -2
- package/dist/{chunk-jrf5a2ap.js → chunk-6rv8w5jk.js} +1 -1
- package/dist/{chunk-5n0ckcmc.js → chunk-6x1feysm.js} +2 -2
- package/dist/chunk-7y72hm1x.js +2 -0
- package/dist/{chunk-zetqzgf3.js → chunk-8hbhfh6b.js} +6 -6
- package/dist/{chunk-5ncn73tp.js → chunk-8kfzygg5.js} +2 -2
- package/dist/chunk-8wydx2we.js +2 -0
- package/dist/chunk-8zjnjvv7.js +2 -0
- package/dist/chunk-988h4bzr.js +2 -0
- package/dist/chunk-9b6a58ac.js +2 -0
- package/dist/chunk-a8fcaywb.js +2 -0
- package/dist/chunk-bfjwn7yg.js +2 -0
- package/dist/chunk-bp2522mm.js +2 -0
- package/dist/chunk-bswe62q4.js +48 -0
- package/dist/chunk-c3v796c8.js +943 -0
- package/dist/chunk-ccqmwdry.js +2 -0
- package/dist/chunk-ck0crwnx.js +2 -0
- package/dist/chunk-cqgkxcb4.js +2 -0
- package/dist/chunk-dntnakjy.js +2 -0
- package/dist/{chunk-67wgad4f.js → chunk-ettdpnrw.js} +2 -2
- package/dist/{chunk-csfrpsp7.js → chunk-ezqwq17j.js} +10 -10
- package/dist/chunk-ezx3qsez.js +2 -0
- package/dist/{chunk-73k79n7q.js → chunk-f72nnjy4.js} +360 -360
- package/dist/chunk-fna5n0ey.js +246 -0
- package/dist/chunk-fqhckdt8.js +2 -0
- package/dist/chunk-fr6hbx25.js +2 -0
- package/dist/{chunk-vr10sbbh.js → chunk-g9cwng6w.js} +1 -1
- package/dist/chunk-gd3za5x0.js +2 -0
- package/dist/chunk-gf28608k.js +2 -0
- package/dist/chunk-h1dj6v8q.js +3 -0
- package/dist/chunk-hjxe7k2g.js +2 -0
- package/dist/chunk-hrkgznbn.js +2 -0
- package/dist/chunk-j6h5v0br.js +2 -0
- package/dist/{chunk-0gjq8ttx.js → chunk-mgb01qdv.js} +2 -2
- package/dist/chunk-n24c9whp.js +2 -0
- package/dist/{chunk-kxp888dn.js → chunk-n2j24b0h.js} +244 -244
- package/dist/{chunk-vv3gb1m5.js → chunk-nhmtg01n.js} +2 -2
- package/dist/chunk-p0qhpnqh.js +70 -0
- package/dist/chunk-p0w1x8y2.js +3 -0
- package/dist/{chunk-9ght4n4r.js → chunk-p3dk1w2w.js} +11 -11
- package/dist/{chunk-6sjvhy5f.js → chunk-q4e9pxs7.js} +2 -2
- package/dist/chunk-q5dv1kyy.js +2 -0
- package/dist/chunk-qnqgf9tq.js +2 -0
- package/dist/chunk-qvwy1808.js +898 -0
- package/dist/{chunk-5s0pnsd6.js → chunk-r18f77vc.js} +4 -4
- package/dist/chunk-r63za1mr.js +2 -0
- package/dist/{chunk-6s1kbajm.js → chunk-rft8gw92.js} +1 -1
- package/dist/chunk-ryvmyskt.js +4211 -0
- package/dist/chunk-sa6mx308.js +2 -0
- package/dist/chunk-va0pc7hx.js +2 -0
- package/dist/chunk-vcp8dnjq.js +412 -0
- package/dist/chunk-vg1erq1q.js +2 -0
- package/dist/{chunk-hmgedrmr.js → chunk-w0jv49ch.js} +3 -3
- package/dist/{chunk-0t5vz87j.js → chunk-wm805tte.js} +19 -19
- package/dist/chunk-xj9h6mc9.js +2 -0
- package/dist/chunk-ytvzwrq3.js +51 -0
- package/dist/{chunk-w4r464v5.js → chunk-zde7ebc4.js} +2 -2
- package/dist/chunk-zmqsv2xy.js +2 -0
- package/dist/cli.js +57 -66
- package/dist/container/index.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +29 -29
- package/dist/typed/client.d.ts +89 -0
- package/dist/typed/contract.d.ts +34 -0
- package/dist/typed/endpoint.d.ts +90 -0
- package/dist/typed/index.d.ts +14 -0
- package/dist/typed/router.d.ts +141 -0
- package/package.json +1 -1
- package/dist/chunk-30rkn2ym.js +0 -2
- package/dist/chunk-38cmrard.js +0 -2
- package/dist/chunk-3qna6dwd.js +0 -2
- package/dist/chunk-4d5fmta0.js +0 -2
- package/dist/chunk-4x3b4b4q.js +0 -2
- package/dist/chunk-6xed4va1.js +0 -2
- package/dist/chunk-748n6ydj.js +0 -2
- package/dist/chunk-7rsf8tes.js +0 -898
- package/dist/chunk-8aspmtf1.js +0 -2
- package/dist/chunk-8yfdg595.js +0 -2
- package/dist/chunk-90eze7av.js +0 -3
- package/dist/chunk-9dvwyej7.js +0 -2
- package/dist/chunk-a2w45krb.js +0 -2
- package/dist/chunk-a547f2ab.js +0 -48
- package/dist/chunk-bqdycvtc.js +0 -2
- package/dist/chunk-cd03rk3x.js +0 -2
- package/dist/chunk-ct0m17q5.js +0 -2
- package/dist/chunk-dhbvvr5h.js +0 -2
- package/dist/chunk-dhptcsya.js +0 -943
- package/dist/chunk-dq93zag9.js +0 -2
- package/dist/chunk-edrtesh7.js +0 -2
- package/dist/chunk-ejcws37w.js +0 -2
- package/dist/chunk-ex890p45.js +0 -51
- package/dist/chunk-f69cpnhw.js +0 -2
- package/dist/chunk-fjf53b44.js +0 -2
- package/dist/chunk-fjzye4qj.js +0 -2
- package/dist/chunk-gfd23b6t.js +0 -2
- package/dist/chunk-habv0vef.js +0 -12
- package/dist/chunk-hz6fc788.js +0 -2
- package/dist/chunk-jff6j9y3.js +0 -10
- package/dist/chunk-jmeb7n8k.js +0 -70
- package/dist/chunk-jy2jhcpy.js +0 -246
- package/dist/chunk-m249t3je.js +0 -3
- package/dist/chunk-m9yabnjx.js +0 -2
- package/dist/chunk-mekrq9wd.js +0 -2
- package/dist/chunk-mmxv535f.js +0 -82
- package/dist/chunk-mypn7jss.js +0 -2
- package/dist/chunk-n18x1k3c.js +0 -2
- package/dist/chunk-nkddjzsa.js +0 -2
- package/dist/chunk-pjmhqmr9.js +0 -2
- package/dist/chunk-qyrnsaq1.js +0 -2
- package/dist/chunk-r19ff2qm.js +0 -62
- package/dist/chunk-r338fssq.js +0 -2
- package/dist/chunk-s36z58x2.js +0 -29
- package/dist/chunk-s79dd325.js +0 -471
- package/dist/chunk-ta38j9em.js +0 -2
- package/dist/chunk-tpfgntwj.js +0 -4211
- package/dist/chunk-vw8rwv6e.js +0 -2
- package/dist/chunk-wcrqs5z9.js +0 -2
- package/dist/chunk-x6d1rmwa.js +0 -2
- package/dist/chunk-x7ft15zz.js +0 -2
- package/dist/chunk-x8trwn7j.js +0 -3
- package/dist/chunk-xhepdj1f.js +0 -2
- package/dist/chunk-xv2em0q4.js +0 -4
- package/dist/chunk-ypw6g0te.js +0 -2
- package/dist/chunk-z8szsm21.js +0 -2
- package/dist/chunk-zfbh14qe.js +0 -2
- /package/dist/{chunk-a3wahyg7.js → chunk-nf3kv7kv.js} +0 -0
package/dist/chunk-dq93zag9.js
DELETED
package/dist/chunk-edrtesh7.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Kf as a,Lf as b,Mf as c,Nf as d,Of as e,Pf as f,Qf as g,Rf as h,Sf as i,Tf as j,Uf as k,Vf as l,Wf as m,Xf as n}from"./chunk-zetqzgf3.js";import"./chunk-tpfgntwj.js";import"./chunk-jff6j9y3.js";import"./chunk-csfrpsp7.js";import"./chunk-0t5vz87j.js";import"./chunk-krkchy8v.js";import"./chunk-brpgjyqg.js";import"./chunk-5mxby3fd.js";import"./chunk-5be9x5cq.js";import"./chunk-jmeb7n8k.js";import"./chunk-kc659vhx.js";import"./chunk-a3wahyg7.js";export{i as streamingSuspenseDirective,m as streamToResponse,g as streamTemplateSimple,a as streamTemplate,d as renderStreamingPage,k as registerStreamingDirectives,e as processStreamDirectives,l as processSectionDirectives,j as islandDirective,n as generateHydrationRuntime,f as extractStreamBoundaries,h as createStreamRenderer,b as buildSuspenseResolveScript,c as SUSPENSE_RESOLVER_RUNTIME};
|
package/dist/chunk-ejcws37w.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{We as o,Xe as p,Ye as q}from"./chunk-6s1kbajm.js";import{cf as a,df as b,ef as c,ff as d,gf as e,hf as f,if as g,jf as h,kf as i,lf as j,mf as k,nf as l,of as m,pf as n}from"./chunk-m249t3je.js";import"./chunk-brpgjyqg.js";import"./chunk-a3wahyg7.js";export{n as useOptimistic,l as untrack,a as state,g as runMountCallbacks,h as runDestroyCallbacks,i as pendingLifecycleCounts,m as peek,e as onMount,f as onDestroy,j as isSignal,k as isDerived,p as generateSignalsRuntimeDev,o as generateSignalsRuntime,c as effect,b as derived,q as default,d as batch};
|
package/dist/chunk-ex890p45.js
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Zu as _}from"./chunk-a3wahyg7.js";import{existsSync as Le,statSync as Be}from"fs";import{join as At,relative as St,resolve as $e}from"path";import Q from"process";import{Buffer as S}from"buffer";import{createCipheriv as Tt,createDecipheriv as Ot,randomBytes as se}from"crypto";import{closeSync as oe,createReadStream as _e,createWriteStream as Ft,existsSync as K,fsyncSync as Ie,openSync as We,writeFileSync as Nt}from"fs";import{access as jt,constants as Ue,mkdir as kt,readdir as Y,rename as Ze,stat as k,unlink as z,writeFile as le}from"fs/promises";import{isAbsolute as Pt,join as P,resolve as Rt}from"path";import p from"process";import{pipeline as Dt}from"stream/promises";import{createGzip as Ve}from"zlib";import R from"process";import T from"process";import H from"process";import{existsSync as G}from"fs";import{resolve as ce}from"path";import{existsSync as Mt}from"fs";import{existsSync as de,mkdirSync as Lt,readdirSync as Bt,readFileSync as $t,writeFileSync as _t}from"fs";import{homedir as D}from"os";import{dirname as Ke,resolve as E}from"path";import j from"process";import{existsSync as It,readdirSync as Wt}from"fs";import{extname as fe,resolve as Ye}from"path";import Ut from"process";import{basename as kr,extname as Pr,join as Rr,relative as Dr,resolve as Je,sep as Mr}from"path";import{pathToFileURL as Lr}from"url";import{mkdir as et,writeFile as Wr}from"fs/promises";import{dirname as Ur,join as Zr}from"path";import{mkdir as Vr,writeFile as Kr}from"fs/promises";import{dirname as Yr,isAbsolute as zr,relative as Hr}from"path";import Gr from"process";import{mkdir as Se,writeFile as Te}from"fs/promises";import{dirname as te,isAbsolute as qr,relative as Xr,sep as Qr}from"path";var Zt=Object.defineProperty,Vt=(e)=>e;function Kt(e,t){this[e]=Vt.bind(null,t)}var Yt=(e,t)=>{for(var r in t)Zt(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Kt.bind(t,r)})},F=(e,t)=>()=>(e&&(t=e(e=0)),t),zt=import.meta.require;class Oe{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),a=i??this.options.ttl,s=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:a,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Le(e))return!0;return Be(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=Le(r)?Be(r):null,a=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:a},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Fe{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let a=await t(),s=performance.now()-i;return this.recordMetric({operation:e,duration:s,timestamp:n,...r}),a}catch(a){let s=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:n,...r}),a}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,a)=>n+a,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ht(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Gt(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function qt(e){return e.getStats().size*2}var M,Z,tt,V=F(()=>{M=new Oe,Z=new Fe,tt={createKey:Ht,isEquivalent:Gt,estimateMemoryUsage:qt}});function Xt(e,t={}){let r=Q.cwd();while(r.includes("storage"))r=$e(r,"..");let i=$e(r,e||"");if(t?.relative)return St(Q.cwd(),i);return i}function w(){if(T.env.NODE_ENV==="test"||T.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Qt(){if(T.env.NODE_ENV==="test"||T.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof T<"u"){let e=T.type;if(e==="renderer"||e==="worker")return!1;return!!(T.versions&&(T.versions.node||T.versions.bun))}return!1}class rt{async format(e){let t=await Qt(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:R.pid,hostname:t(),environment:R.env.NODE_ENV||"development",platform:R.platform,version:R.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R.env.NODE_ENV||R.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class re{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...I},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new rt,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??p.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),a=this.generateKey();this.currentKeyId=n,this.keys.set(n,a),this.encryptionKeys.set(n,{key:a,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...X,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...X};return{...X,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:I.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!w()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,a=3,s=1000;while(n<a)try{try{try{await jt(this.config.logDirectory,Ue.F_OK|Ue.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await kt(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:S.from(e);try{if(!K(this.currentLogFile))await le(this.currentLogFile,"",{mode:420});if(i=We(this.currentLogFile,"a",420),Nt(i,l,{flag:"a"}),Ie(i),i!==void 0)oe(i),i=void 0;if((await k(this.currentLogFile)).size===0){if(await le(this.currentLogFile,l,{flag:"w",mode:420}),(await k(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let c=o;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(n<a-1){let f=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${a}:`,f);let u=s*2**n;await new Promise((h)=>setTimeout(h,u)),n++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(i!==void 0)try{oe(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(n===a-1){let c=l,f=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),l}n++;let o=s*2**(n-1);await new Promise((c)=>setTimeout(c,o))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return P(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return P(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return P(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(w())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,s],[,l])=>l.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,a=Math.max(1,n);if(i.length>a)for(let[s]of i.slice(a))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return se(16).toString("hex")}generateKey(){return se(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=se(16),i=Tt("aes-256-gcm",t,r),n=S.isBuffer(e)?e:S.from(e,"utf8"),a=i.update(n),s=i.final(),l=a.length+s.length,o=i.getAuthTag(),c=S.allocUnsafe(16+l+16);return r.copy(c,0),a.copy(c,16),s.copy(c,16+a.length),o.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Ve(),n=[];i.on("data",(a)=>n.push(a)),i.on("end",()=>t(S.from(S.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(w())return;if(!this.shouldWriteToFile())return;let e=await k(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Y(this.config.logDirectory),a=n.filter((o)=>o.startsWith(this.name)&&/\.log\.\d+$/.test(o)).sort((o,c)=>{let f=Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),s=a.length>0?Number.parseInt(a[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${s}`;if(await k(r).catch(()=>null))try{if(await Ze(r,l),t.compress)try{let o=`${l}.gz`;await this.compressLogFile(l,o),await z(l)}catch(o){console.error("Error compressing rotated file:",o)}if(a.length===0&&!n.some((o)=>o.endsWith(".log.1")))try{let o=`${r}.1`;await le(o,"")}catch(o){console.error("Error creating backup file:",o)}}catch(o){console.error(`Error during rotation: ${o instanceof Error?o.message:String(o)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),a=r.replace(/\.log$/,`-${n}.log`);if(await k(r).catch(()=>null))await Ze(r,a)}if(this.currentLogFile=i,t.maxFiles){let n=(await Y(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,s)=>s.localeCompare(a));for(let a of n.slice(t.maxFiles))await z(P(this.config.logDirectory,a))}}}async compressLogFile(e,t){let r=_e(e),i=Ft(t),n=Ve();await Dt(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),K(this.currentLogFile))try{let e=We(this.currentLogFile,"r+");Ie(e),oe(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!w()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Y(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await z(P(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?m.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||w())return!1;let e=typeof p.env.NO_COLOR<"u",t=p.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:a,showTimestamp:s=!0}=e,l=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(s)g.push(t);if(a==="warning")g.push("WARN");else if(a==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)g.push(i.replace(/[[\]]/g,""));return g.push(n),g.join(" ")}let o=p.stdout.columns||120,c="";if(a==="warning"||a==="error")c=`${r} ${n}`;else if(a==="info"||a==="success")c=`${r} ${i} ${n}`;else c=`${r} ${i} ${m.cyan(n)}`;if(!s)return c.trim();let f=l(c).trim().length,u=l(t).length,h=Math.max(1,o-2-f-u);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(a,s)=>{let l=Number.parseInt(s,10);return l<t[0].length?String(t[0][l]):a});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(a,s)=>{if(s==="%")return"%";if(i>=t.length)return a;let l=t[i++];switch(s){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return a}});if(i<t.length)n+=` ${t.slice(i).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let a=m.underline(m.blue(i)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(s)}`,o="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${a}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${a}\x1B]8;;\x1B\\`;return a}),t=t.replace(/`([^`]+)`/g,(r,i)=>m.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>m.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>m.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>m.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>m.strikethrough(i)),t}supportsHyperlinks(){if(w())return!1;let e=p.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=p.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Pt(t)||t.startsWith("./")||t.startsWith("../"))t=Rt(t);else return null;return K(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),a=this.formatFileTimestamp(i),s,l;if(t instanceof Error)s=t.message,l=t.stack;else s=this.formatMessage(t,r);let{consoleText:o,fileText:c}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":it[e],h=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:m.gray(o),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:o,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:m.green(o),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:o,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:o,level:e}),console.error(g),l){let b=l.split(`
|
|
3
|
-
`);for(let d of b)if(d.trim()&&!d.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:m.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!w()){if(console.error(`${a} ${this.environment}.${e.toUpperCase()}: ${s}`),l)console.error(l)}let f=`${a} ${this.environment}.${e.toUpperCase()}: ${c}
|
|
4
|
-
`;if(l)f+=`${l}
|
|
5
|
-
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(n,a)=>{},finish:(n)=>{},interrupt:(n,a)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!w()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!w()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,a="info")=>{if(!w()&&p.stdout.isTTY)p.stdout.write(`
|
|
6
|
-
`);if(this[a==="warning"?"warn":a](n),this.activeProgressBar&&this.shouldStyleConsole()&&!w()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":m.blue("\u25D0"),tag:r,message:`${m.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),a=`${e} completed in ${n}ms`,s=new Date,l=this.formatConsoleTimestamp(s),o=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${a}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
|
|
7
|
-
`,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":m.green("\u2713"),tag:c,message:`${a}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!w())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new re(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(w())throw Error("createReadStream is not supported in browser environments");if(!K(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return _e(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=S.isBuffer(e)?e:S.from(e,"base64"),n=i.subarray(0,16),a=i.subarray(i.length-16),s=i.subarray(16,i.length-16),l=Ot("aes-256-gcm",r,n);l.setAuthTag(a);let o=l.update(s),c=l.final(),f=o.length+c.length,u=S.allocUnsafe(f);return o.copy(u,0),c.copy(u,o.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return w()}isServerMode(){return!w()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:a}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=n.split(`
|
|
8
|
-
`),o=Math.max(...l.map((h)=>h.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,f=`\u2514${"\u2500".repeat(o)}\u2518`,u=l.map((h)=>{return this.formatConsoleMessage({timestamp:r,message:m.cyan(h),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:m.cyan(c),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:m.cyan(f),showTimestamp:!1}))}else if(!w())console.error(`${i} ${this.environment}.INFO: [BOX] ${a}`);let s=`${i} ${this.environment}.INFO: [BOX] ${a}
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(w())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${m.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();p.stdin.removeListener("data",r);try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!1)}catch{}p.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!0)}catch{}p.stdin.resume(),p.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,l=0;if(r=e.replace(s,(o,c)=>{if(c==="%")return"%";if(l>=t.length)return o;let f=t[l++];switch(c){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return o}}),l<t.length)r+=` ${t.slice(l).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${m.blue("\u25D0")} `;console.error(`${l}${s} ${m.cyan(i)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
10
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!p.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,a=m.green("\u2501".repeat(i)),s=m.gray("\u2501".repeat(n)),l=`[${a}${s}]`,o=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?m.green("\u2713"):m.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${l} ${o}${c}`,g=p.stdout.columns||80,b=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${b}`,p.stdout.write(e.lastRenderedLine),t)p.stdout.write(`
|
|
11
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||w()||!p.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(w()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Y(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=P(this.config.logDirectory,i);if(e.before)try{if((await k(n)).mtime>=e.before)continue}catch(a){console.error(`Failed to get stats for file ${n}:`,a);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await z(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var ze,ue,I,Jt,v,m,er,He,tr,Ge,rr,ir,he,nr,qe,Xe,ar,ge,sr,or,lr,cr,fr,X,it,ur,hr=F(()=>{ze=Q.env.CLARITY_LOG_DIR||At(Xt(),"logs"),ue={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ze,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},I={...ue},Jt=(async()=>{try{let{loadConfig:e}=await Promise.resolve().then(()=>(yt(),dt)),t=await e({name:"clarity",alias:"logging",defaultConfig:ue,cwd:Q.cwd()});if(t)Object.assign(I,t)}catch{}return I})(),v={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},m=v,er=v.red,He=v.green,tr=v.yellow,Ge=v.blue,rr=v.magenta,ir=v.cyan,he=v.white,nr=v.gray,qe=v.bgRed,Xe=v.bgYellow,ar=v.bgGray,ge=v.bold,sr=v.dim,or=v.italic,lr=v.underline,cr=v.strikethrough,fr=v.reset,X={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},it={debug:"\uD83D\uDD0D",info:Ge("\u2139"),success:He("\u2713"),warning:Xe(he(ge(" WARN "))),error:qe(he(ge(" ERROR ")))},ur=new re("stacks")}),gr="0.15.9",mr=()=>{};async function nt(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:a}=t,s=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(o){if(s=o instanceof Error?o:Error(String(o)),l===r||!n(s))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(a!==void 0)return a;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function at(e){return e instanceof C}function pr(e){return e instanceof J}function dr(e){if(at(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}var C,J,W,ye,we,ee,ve,be,U,Ee,Ce,N,L=F(()=>{C=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},J=class extends C{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((a)=>`"${a}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},W=class extends C{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},ye=class extends C{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},we=class extends C{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},ee=class extends C{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},ve=class extends C{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},be=class extends C{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},U=class extends C{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Ee=class extends C{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},Ce=class extends C{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},N={configNotFound(e,t,r){return new J(e,t,r)},configLoad(e,t,r){return new W(e,t,r)},configValidation(e,t,r){return new ye(e,t,r)},configMerge(e,t,r,i){return new we(e,t,r,i)},envVar(e,t,r,i){return new ee(e,t,r,i)},fileSystem(e,t,r){return new ve(e,t,r)},typeGeneration(e,t,r){return new be(e,t,r)},schemaValidation(e,t,r){return new U(e,t,r)},browserConfig(e,t,r,i){return new Ee(e,t,r,i)},plugin(e,t,r){return new Ce(e,t,r)}}});class ie{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:a=!0,customParsers:s={},verbose:l=!1,trackPerformance:o=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:a,customParsers:s,verbose:l,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(o)return Z.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,a]of Object.entries(e)){let s=[...t,n],l=s.map((f)=>this.formatEnvKey(f,i.useCamelCase)),o=`${r}_${l.join("_")}`,c=i.useBackwardCompatibility?`${r}_${s.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof a==="object"&&a!==null&&!Array.isArray(a))this.processObject(a,s,r,i);else{let f=H.env[o]||(c?H.env[c]:void 0);if(f!==void 0){if(i.verbose){let u=H.env[o]?o:c}try{e[n]=this.parseEnvironmentValue(f,typeof a,o,i.customParsers,i.configName)}catch(u){if(u instanceof ee)throw u;throw N.envVar(o,f,typeof a,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[a,s]of Object.entries(i))try{return s(e)}catch{continue}for(let a of this.defaultParsers)if(a.canParse(e,t))try{return a.parse(e)}catch{throw N.envVar(r,e,`${t} (via ${a.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(H.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,a=i||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],a,s),n){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,a]of Object.entries(e)){let s=[...t,n],l=`${r}_${s.map((o)=>this.formatEnvKey(o,!0)).join("_")}`;if(typeof a==="object"&&a!==null&&!Array.isArray(a))this.extractEnvVarInfo(a,s,r,i);else i.push({key:l,type:Array.isArray(a)?"array":typeof a,description:`Configuration for ${s.join(".")}`,example:this.generateExample(a)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
12
|
-
|
|
13
|
-
`;for(let i of e)r+=`${i.key}
|
|
14
|
-
`,r+=` Type: ${i.type}
|
|
15
|
-
`,r+=` Description: ${i.description}
|
|
16
|
-
`,r+=` Example: ${i.example}
|
|
17
|
-
|
|
18
|
-
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
19
|
-
|
|
20
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
21
|
-
`,r+=`|----------|------|-------------|----------|
|
|
22
|
-
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
23
|
-
`;return r}}var st=F(()=>{V(),L()});function yr(e,t){let r=zt("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function ot(e,t,r={}){return lt(e,t,r,new WeakMap)}function lt(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:a=!1,customMerger:s}=r;if(t===null||t===void 0)return a?e:t;if(s){let l=s(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return ct(e,t,n,i);if(!A(t)||!A(e))return t;return Er(e,t,r,i)}function ct(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return wr(e,t);case"smart":return vr(e,t,i);default:return t}return t}function wr(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>xe(n,i)))r.push(i);return r}function vr(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(A(t[0])&&A(e[0]))return br(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function br(e,t,r){let i=[...t];for(let n of e){if(!A(n)){i.push(n);continue}let a=["id","name","key","path","type"],s=!1;for(let l of a)if(l in n){if(i.find((o)=>A(o)&&(l in o)&&o[l]===n[l])){s=!0;break}}if(!s)i.push(n)}return i}function Er(e,t,r,i){let n=t;if(A(n)&&i.has(n))return i.get(n);let a={...e};if(A(n))i.set(n,a);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let l=n[s],o=a[s];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){a[s]=l;continue}if(A(l)&&A(o))a[s]=lt(o,l,r,i);else if(Array.isArray(l)||Array.isArray(o))a[s]=ct(o,l,r.arrayMergeMode||"smart",i);else a[s]=l}return a}function Ne(e,t,r="replace"){return ot(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function xe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!xe(e[r],t[r]))return!1;return!0}if(A(e)&&A(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!xe(e[n],t[n]))return!1}return!0}return!1}function A(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var ft,je=F(()=>{ft={replace:"replace",concat:"concat",smart:"smart"}});class ne{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:a,trackPerformance:s=!0,verbose:l=!1}=r;if(n){let c=M.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let o=async()=>{if(!G(e))return null;try{let c=`?t=${Date.now()}`,f=await import(e+c),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new W(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new W(e,Error("Configuration must export a valid object"),"unknown");let b={config:Ne(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)M.setWithFileCheck("file",b,e,a);return b}catch(c){throw c instanceof Error?N.configLoad(e,c):N.configLoad(e,Error(String(c)))}};if(s)return Z.track("loadFromPath",o,{path:e});return o()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let a of i)for(let s of this.extensions)n.push(ce(t,`${a}${s}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let a of i){if(!a)continue;if(r.push(a,`.${a}.config`,`${a}.config`,`.${a}`),e)r.push(`${e}.${a}.config`,`.${e}.${a}.config`)}let n=new Set;return r.filter((a)=>{if(!a||n.has(a))return!1;return n.add(a),!0})}checkFileAccess(e){return nt(async()=>{return G(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!G(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let a of n)for(let s of this.extensions){let l=ce(e,`${a}${s}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:n}=await import("fs"),a=n(e);for(let s of a)if(this.looksLikeConfigFile(s)){let l=ce(e,s);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!G(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),a=n(e,"utf8");JSON.parse(a)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}var ut=F(()=>{V(),L(),je()});class ke{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:a=!0,customRules:s=[],trackPerformance:l=!0,verbose:o=!1}=r,c=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:a,customRules:s,trackPerformance:l,verbose:o};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(g){return f.push({path:"",message:`Validation failed: ${g}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(l)return await Z.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!Mt(t))throw new U(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new U(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,a){if(a.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(s)){if(i.push({path:r,message:`Expected type ${l.join(" or ")}, got ${s}`,expected:l.join(" or "),actual:s,rule:"type"}),a.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),a.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let l=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,l,i,n,a),a.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(a.validateRequired&&t.required){for(let l of t.required)if(!(l in s)){if(i.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),a.stopOnFirstError)return}}if(t.properties){for(let[l,o]of Object.entries(t.properties))if(l in s){let c=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(s[l],o,c,i,n,a),a.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let o of Object.keys(s))if(!l.has(o))n.push({path:r?`${r}.${o}`:o,message:`Additional property '${o}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let a of t)try{let s=this.getValueByPath(e,a.path),l=this.validateWithRule(s,a,a.path);if(i.push(...l),r.stopOnFirstError&&i.length>0)break}catch(s){i.push({path:a.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,a,s]=i;t.push({path:n,required:!a,type:this.mapTypeScriptType(s)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ht},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ht,gt=F(()=>{V(),L(),ht=/^https?:\/\//});function Cr(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Pe{fileLoader=new ne;envProcessor=new ie;validator=new ke;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:a,...s}=e;try{if(r?.enabled){let o=this.checkCache(s.name||"",s);if(o)return o}let l;try{l=await this.loadConfigurationStrategies(s,!0,r)}catch(o){let c=s.__strictErrorHandling;if(o instanceof Error&&o.name==="ConfigNotFoundError"){if(c)throw o;l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(o instanceof Error&&o.name==="ConfigLoadError"){let f=o.message.includes("EACCES")||o.message.includes("EPERM")||o.message.includes("permission denied"),u=!f&&(o.message.includes("syntax")||o.message.includes("Expected")||o.message.includes("Unexpected")||o.message.includes("BuildMessage")||o.message.includes("errors building")),h=o.message.includes("Configuration must export a valid object")||o.message.includes("Configuration file is empty and exports nothing");if(c&&(h||f))throw o;if(u&&(!c||!h))l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${o.message}`]};else throw o}else l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${o instanceof Error?o.message:String(o)}`]}}if(n||a)await this.validateConfiguration(l.config,n,a,s.name);if(r?.enabled&&l)this.cacheResult(s.name||"",l,r,s);if(i?.enabled){let o={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(o);if(i.slowThreshold&&o.duration>i.slowThreshold)x.warn(`Slow configuration loading detected: ${o.duration}ms for ${s.name}`);l.metrics=o}return l}catch(l){let o=Date.now()-t;throw x.error(`Configuration loading failed after ${o}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:a,configDir:s,defaultConfig:l,checkEnv:o=!0,arrayStrategy:c="replace",verbose:f=!1}=e,u=a||j.cwd(),h=[],g=await this.loadLocalConfiguration(i,n,u,s,l,c,f,o,r);if(g)return h.push(...this.getLocalSearchPaths(i,n,u,s)),this.finalizeResult(g,h,o,i,f);let b=await this.loadHomeConfiguration(i,n,l,c,f,o);if(b)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(b,h,o,i,f);let d=await this.loadPackageJsonConfiguration(i,n,u,l,c,f,o);if(d)return h.push(E(u,"package.json")),this.finalizeResult(d,h,o,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,s)),t)throw N.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,l,o,f),warnings:[`No configuration file found for "${i}"${Cr(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,a,s,l,o){let c=l?$(e,n,s):n,f=this.getLocalDirectories(r,i);for(let u of f){if(s)x.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:a,verbose:s,cacheTtl:o?.ttl,useCache:!o?.ttl||o.ttl>100});if(g){if(s)x.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,i,n,a){if(!e)return null;let s=a?$(e,r,n):r,l=[E(D(),".config",e),E(D(),".config"),D()];for(let o of l){if(n)x.info(`Checking home directory: ${o}`);let c=this.fileLoader.generateConfigPaths(e,o,t),f=await this.fileLoader.tryLoadFromPaths(c,s,{arrayStrategy:i,verbose:n});if(f){if(n)x.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,a,s){let l=s?$(e,i,a):i;try{let o=E(r,"package.json");if(!de(o))return null;let c={};try{c=JSON.parse($t(o,"utf8"))}catch(h){if(a)x.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=c[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let g of h){if(!g)continue;if(c[g]){f=c[g],u=g;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(a)x.success(`Configuration loaded from package.json: ${u}`);return{config:Ne(l,f,n),source:{type:"package.json",path:o,priority:30,timestamp:new Date}}}}catch(o){if(a)x.warn("Failed to load package.json:",[o instanceof Error?o:Error(String(o))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:$(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let a=r(e);if(a)n.push(...a)}if(t){let a=await this.validator.validateConfiguration(e,t);if(!a.isValid)n.push(...a.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(n.length>0)throw N.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return M.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);M.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,E(e,"config"),E(e,".config"),t?E(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(E(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),a=[];for(let s of n)a.push(...this.fileLoader.generateConfigPaths(e,s,t));return a}getHomeSearchPaths(e,t){if(!e)return[];let r=[E(D(),".config",e),E(D(),".config"),D()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Qe(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function xr(e){return O.loadConfig({...e,__strictErrorHandling:!0})}async function Re(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await O.loadConfig(e);else i=await O.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",a=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||a.includes("config"))&&e.verbose)x.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let s=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await O.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function Ar(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await O.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Qe(r)))return(await O.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await O.loadConfig({...e,cwd:e.cwd||j.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Qe(t)))return(await O.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Sr(e,t,r="replace"){let i=new ne;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function $(e,t,r=!1){let i=new ie,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function a(s,l=[]){let o={...s};for(let[c,f]of Object.entries(s)){let u=[...l,c],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((d)=>d.toUpperCase()).join("")}`,`${n}_${u.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,b;for(let d of h)if(g=j.env[d],g!==void 0){b=d;break}if(g!==void 0&&b)if(typeof f==="boolean")o[c]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let d=Number(g);if(!Number.isNaN(d))o[c]=d}else if(Array.isArray(f))try{o[c]=JSON.parse(g)}catch{o[c]=g.split(",").map((d)=>d.trim())}else o[c]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))o[c]=a(f,u)}return o}return a(t)}function Tr(e){let t=E(j.cwd(),e.configDir),r=E(j.cwd(),e.generatedDir),i=E(r,"config-types.ts");if(!de(Ke(i)))Lt(Ke(i),{recursive:!0,mode:511});let n=de(t)?Bt(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],a=`// Generated by bunfig v${gr}
|
|
24
|
-
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
25
|
-
`;_t(i,a,{mode:438})}function Or(e){let t=null,r=null,i=()=>{if(!r)r=Re(e).then((a)=>{return t=a,a},(a)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)x.warn("Config loading failed, using defaults:",[a instanceof Error?a:Error(String(a))]);return s});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(a,s){if(t)return t[s];let l=n[s];return i(),l},has(a,s){return s in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(a,s){return Object.getOwnPropertyDescriptor(t||n,s)},set(a,s,l){if(!t)t={...n};return t[s]=l,!0}})}var x,O,mt,pt,Fr=F(()=>{hr(),mr(),V(),L(),st(),ut(),gt(),je(),x=new re("bunfig",{showTags:!0}),O=new Pe,mt=E(j.cwd(),"config"),pt=E(j.cwd(),"src/generated")});function Nr(e){let t=Ye(Ut.cwd(),e?.configDir||"./config");function r(){if(!It(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),a=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Wt(t).filter((o)=>n.has(fe(o))).map((o)=>({base:o.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:o})),l=new Map;for(let{base:o,file:c}of s){let f=fe(c).toLowerCase(),u=l.get(o);if(!u){l.set(o,c);continue}let h=fe(u).toLowerCase();if(a.indexOf(f)<a.indexOf(h))l.set(o,c)}return Array.from(l.entries()).map(([o,c])=>({base:o,file:c})).sort((o,c)=>o.base.localeCompare(c.base))}function i(){let n=r(),a=n.map((o)=>o.base),s=a.length?a.map((o)=>`'${o}'`).join(" | "):"string",l=n.length?`{
|
|
26
|
-
${n.map((o)=>{let c=Ye(t,o.file).replace(/\\/g,"/");return` '${o.base}': typeof import('${c}').default`}).join(`,
|
|
27
|
-
`)}
|
|
28
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
29
|
-
export type ConfigByName = ${l}
|
|
30
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
31
|
-
export type ConfigOf = Config
|
|
32
|
-
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(a)=>{return{path:a.path,namespace:"bunfig-virtual"}}),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}var jr=()=>{},dt={};Yt(dt,{withErrorRecovery:()=>nt,tryLoadConfig:()=>Sr,loadConfigWithResult:()=>xr,loadConfig:()=>Re,isRetryableError:()=>dr,isConfigNotFoundError:()=>pr,isBunfigError:()=>at,globalPerformanceMonitor:()=>Z,globalCache:()=>M,getEnvOrDefault:()=>yr,generateConfigTypes:()=>Tr,defaultGeneratedDir:()=>pt,defaultConfigDir:()=>mt,deepMergeWithArrayStrategy:()=>Ne,deepMerge:()=>ot,createLibraryConfig:()=>Or,config:()=>Ar,bunfigPlugin:()=>Nr,applyEnvVarsToConfig:()=>$,TypeGenerationError:()=>be,SchemaValidationError:()=>U,PluginError:()=>Ce,PerformanceMonitor:()=>Fe,FileSystemError:()=>ve,ErrorFactory:()=>N,EnvVarError:()=>ee,EnvProcessor:()=>ie,ConfigValidator:()=>ke,ConfigValidationError:()=>ye,ConfigNotFoundError:()=>J,ConfigMergeError:()=>we,ConfigLoader:()=>Pe,ConfigLoadError:()=>W,ConfigFileLoader:()=>ne,ConfigCache:()=>Oe,CacheUtils:()=>tt,BunfigError:()=>C,BrowserConfigError:()=>Ee,ArrayMergeStrategies:()=>ft});var yt=F(()=>{Fr(),L(),V(),L(),jr(),st(),ut(),gt(),je()});yt();var wt={translationsDir:"locales",defaultLocale:"en",fallbackLocale:void 0,include:void 0,verbose:!1,outDir:"dist/i18n",typesOutFile:"dist/i18n/keys.d.ts",sources:["ts"]},me=null;async function Si(){if(!me)me=await Re({name:"i18n",defaultConfig:wt});return me}var Ti=wt;async function Br(e,t){let r=[];for(let i of e){let n=new Bun.Glob(i);for await(let a of n.scan({dot:t.dot??!1}))r.push(a)}return r}async function $r(e){let t=await(e.startsWith("file://")?import(e):import(Lr(e).href));return t&&(t.default??t.translations??t)}function vt(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}function bt(e,t){let r={...e};for(let i of Object.keys(t)){let n=t[i];if(vt(n)){let a=r[i]&&typeof r[i]==="object"?r[i]:{};r[i]=bt(a,n)}else r[i]=n}return r}function _r(e,t,r){let i=e;for(let n=0;n<t.length-1;n++){let a=t[n];if(!i[a]||typeof i[a]!=="object")i[a]={};i=i[a]}i[t[t.length-1]]=r}function Ir(e){let t=[];if(e.includes("yaml"))t.push("**/*.yml","**/*.yaml");if(e.includes("ts"))t.push("**/*.ts","**/*.js");if(e.includes("json"))t.push("**/*.json");return t}async function Ni(e){if(typeof e.translationsDir!=="string"||e.translationsDir.trim().length===0)throw Error("ts-i18n: translationsDir must be a non-empty string");let t=Je(e.translationsDir),r=(e.include??Ir(e.sources??["ts"])).map((s)=>Rr(t,s)),i=(await Br(r,{dot:!1})).map((s)=>Je(s));if(!i.length){if(e.optional)return{};throw Error(`ts-i18n: No translation files found under ${t}. Looked for ${r.join(", ")}. If this is a fresh scaffold, add a sample file or pass \`optional: true\`.`)}let n=await Promise.all(i.map(async(s)=>{let l=Pr(s).toLowerCase(),o=l===".yml"||l===".yaml",c=l===".ts"||l===".js",f=l===".json",u;if(o)try{let y=await Bun.file(s).text(),B=Bun.YAML.parse(y);u=B==null?{}:B}catch(y){throw Error(`ts-i18n: Failed to parse YAML file ${s}: ${y?.message??y}`)}else if(f)try{let y=await Bun.file(s).text();u=y.trim().length===0?{}:JSON.parse(y)}catch(y){throw Error(`ts-i18n: Failed to parse JSON file ${s}: ${y?.message??y}`)}else if(c)try{let y=await $r(s);u=y.default??y}catch(y){throw Error(`ts-i18n: Failed to import TS translation module ${s}: ${y?.message??y}`)}if(!vt(u))throw Error(`ts-i18n: Translation file must export an object. File: ${s}`);let h=Dr(t,s).split(Mr),g=h[0],b=h.slice(1);if(b.length===0)g=kr(g,l);if(!g)throw Error(`ts-i18n: Could not infer locale from file path: ${s}`);let d=u,ae={};if(b.length===0)ae=d;else{let y=b.join("/").replace(l,"").split("/").filter(Boolean),B=y[y.length-1],De=d;if(d&&typeof d==="object"&&!Array.isArray(d)&&Object.keys(d).length===1&&Object.prototype.hasOwnProperty.call(d,B))De=d[B];let Me={};_r(Me,y,De),ae=Me}return{locale:g,container:ae}})),a={};for(let{locale:s,container:l}of n){if(!a[s])a[s]={};a[s]=bt(a[s],l)}return a}function Et(e){if(e==null||typeof e!=="object")return e;let t=Array.isArray(e)?[]:{};for(let[r,i]of Object.entries(e)){if(typeof i==="function")continue;if(i&&typeof i==="object")t[r]=Et(i);else t[r]=i}return t}async function Pi(e,t){await et(t,{recursive:!0});let r=[];for(let[i,n]of Object.entries(e)){let a=Zr(t,`${i}.json`),s=Et(n),l=JSON.stringify(s,null,2);await et(Ur(a),{recursive:!0}),await Wr(a,l,"utf8"),r.push(a)}return r}function Ae(e){if(typeof e==="string")return JSON.stringify(e);if(typeof e==="number"||typeof e==="boolean")return String(e);if(e==null)return"undefined";if(Array.isArray(e))return`[${e.map((t)=>Ae(t)).join(", ")}]`;if(typeof e==="object")return`{ ${Object.entries(e).map(([t,r])=>`${JSON.stringify(t)}: ${Ae(r)}`).join(", ")} }`;return"undefined"}function pe(e){if(!e)return e;return zr(e)?Hr(Gr.cwd(),e):e}async function Li(e,t=".config/i18n.config.ts"){let r={...e,translationsDir:pe(e.translationsDir),outDir:pe(e.outDir),typesOutFile:pe(e.typesOutFile)},i=`// ts-i18n configuration sample
|
|
33
|
-
// Update values as needed for your project
|
|
34
|
-
|
|
35
|
-
export default ${Ae(r)}
|
|
36
|
-
`;return await Vr(Yr(t),{recursive:!0}),await Kr(t,i,"utf8"),t}function Ct(e,t=""){let r={};for(let[i,n]of Object.entries(e)){let a=t?`${t}.${i}`:i;if(n==null)continue;if(typeof n==="function"||typeof n==="string"||typeof n==="number"||typeof n==="boolean")r[a]=n;else if(n&&typeof n==="object"&&!Array.isArray(n))Object.assign(r,Ct(n,a))}return r}function q(e,t){if(!e.includes(t))e.push(t)}function Bi(e,t){let{defaultLocale:r,fallbackLocale:i}=t,n={};for(let[s,l]of Object.entries(e))n[s]=Ct(l);function a(s,l,o){let c=[];if(l)q(c,l);if(q(c,r),i)if(Array.isArray(i))for(let f of i)q(c,f);else q(c,i);for(let f of c){let u=n[f];if(!u)continue;let h=u[s];if(h==null)continue;if(typeof h==="function")return h(o);if(typeof h==="string"||typeof h==="number"||typeof h==="boolean")return String(h)}return s}return function(s,l,o){let c,f;if(typeof l==="string")c=l,f=o;else f=l;return a(s,c,f)??s}}function xt(e,t=""){let r=[];for(let[i,n]of Object.entries(e)){let a=t?`${t}.${i}`:i;if(n&&typeof n==="object"&&!Array.isArray(n))r.push(...xt(n,a));else r.push(a)}return r}async function Ii(e,t){let r=Object.keys(e);if(r.length===0){await Se(te(t),{recursive:!0}),await Te(t,`export type TranslationKey = string
|
|
37
|
-
`);return}let i=r[0],n=e[i],a=`export type TranslationKey = ${xt(n).sort().map((s)=>JSON.stringify(s)).join(" | ")}
|
|
38
|
-
`;await Se(te(t),{recursive:!0}),await Te(t,a)}async function Wi(e,t,r){let i=Jr(e,t),n=`// Auto-generated by ts-i18n. Do not edit.
|
|
39
|
-
import type { DotPaths, ParamsForKey, TranslatorFor } from 'ts-i18n'
|
|
40
|
-
import * as Mod from ${ei(i)}
|
|
41
|
-
|
|
42
|
-
type Base = (
|
|
43
|
-
Mod extends { default: infer D } ? D :
|
|
44
|
-
Mod extends { translations: infer T } ? T :
|
|
45
|
-
Mod
|
|
46
|
-
) extends infer X ? X : never
|
|
47
|
-
|
|
48
|
-
export type TranslationKey = DotPaths<Base>
|
|
49
|
-
export type ParamsFor<K extends TranslationKey> = ParamsForKey<Base, K>
|
|
50
|
-
export type TypedTranslator = TranslatorFor<Base>
|
|
51
|
-
`;await Se(te(t),{recursive:!0}),await Te(t,n)}function Jr(e,t){if(!qr(e))return e;let r=Xr(te(t),e).split(Qr).join("/");if(!r.startsWith("."))r=`./${r}`;return r}function ei(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}export{Pi as writeOutputs,Ni as loadTranslations,Si as getConfig,Wi as generateTypesFromModule,Ii as generateTypes,Li as generateSampleConfig,wt as defaultConfig,Bi as createTranslator,Ti as config};
|
package/dist/chunk-f69cpnhw.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Au as g,Bu as h,Cu as i,Du as j,Eu as k,uu as a,vu as b,wu as c,xu as d,yu as e,zu as f}from"./chunk-s36z58x2.js";import"./chunk-5n0ckcmc.js";import"./chunk-a3wahyg7.js";export{c as setCachedVideoResult,k as processVideo,b as getCachedVideoResult,f as generateThumbnails,g as generateSpriteSheet,e as generatePoster,h as generateHLSManifest,i as generateDASHManifest,d as clearVideoCache,j as analyzeVideo,a as VideoProcessorCache};
|
package/dist/chunk-fjf53b44.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$m as b,_m as a,an as c,bn as d,cn as e,dn as f,en as g,fn as h,gn as i,hn as j,in as k}from"./chunk-jff6j9y3.js";import"./chunk-jmeb7n8k.js";import"./chunk-a3wahyg7.js";export{c as resetCssCache,d as resetCrosswindCache,g as rebuildCrosswindCSS,e as loadCrosswindConfig,b as loadCrosswind,k as injectCrosswindCSS,a as getCrosswindServeAsset,h as getCachedCSS,j as generateCrosswindCSS,i as extractClassNames,f as buildCrosswindCSS};
|
package/dist/chunk-fjzye4qj.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Aj as a,Bj as b,Cj as c,Dj as d,Ej as e,Fj as f,Gj as g,Hj as h,Ij as i,Jj as j,Kj as k,Lj as l,Mj as m,Nj as n}from"./chunk-tpfgntwj.js";import"./chunk-jff6j9y3.js";import"./chunk-csfrpsp7.js";import"./chunk-0t5vz87j.js";import"./chunk-krkchy8v.js";import"./chunk-brpgjyqg.js";import"./chunk-5mxby3fd.js";import"./chunk-5be9x5cq.js";import"./chunk-jmeb7n8k.js";import"./chunk-kc659vhx.js";import"./chunk-a3wahyg7.js";export{g as usesSignalsInScript,n as unescapeHtml,c as registerFilters,b as registerFilter,k as processExpressions,j as interpolateScriptsInTemplate,h as interpolateScriptExpressions,i as interpolateScriptAttributes,d as getAllFilters,m as evaluateExpression,f as escapeHtml,a as defaultFilters,e as clearCustomFilters,l as applyFilters};
|
package/dist/chunk-gfd23b6t.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$s as H,$t as Ha,As as g,At as ga,Bs as h,Bt as ha,Cs as i,Ct as ia,Ds as j,Dt as ja,Es as k,Et as ka,Fs as l,Ft as la,Gs as m,Gt as ma,Hs as n,Ht as na,Is as o,It as oa,Js as p,Jt as pa,Ks as q,Kt as qa,Ls as r,Lt as ra,Ms as s,Mt as sa,Ns as t,Nt as ta,Os as u,Ot as ua,Ps as v,Pt as va,Qs as w,Qt as wa,Rs as x,Rt as xa,Ss as y,St as ya,Ts as z,Tt as za,Us as A,Ut as Aa,Vs as B,Vt as Ba,Ws as C,Wt as Ca,Xs as D,Xt as Da,Ys as E,Yt as Ea,Zs as F,Zt as Fa,_s as G,_t as Ga,at as I,au as Ia,bt as J,bu as Ja,ct as K,cu as Ka,dt as L,du as La,et as M,eu as Ma,ft as N,fu as Na,gt as O,gu as Oa,ht as P,hu as Pa,it as Q,iu as Qa,jt as R,ju as Ra,kt as S,ku as Sa,lt as T,mt as U,nt as V,ot as W,pt as X,qt as Y,rt as Z,st as _,tt as $,us as a,ut as aa,vs as b,vt as ba,ws as c,wt as ca,xs as d,xt as da,ys as e,yt as ea,zs as f,zt as fa}from"./chunk-jy2jhcpy.js";import"./chunk-a3wahyg7.js";export{A as watchFiles,q as trim,oa as toColorSpace,g as toCodecData,ia as tint,wa as thumbHashToRGBA,Aa as thumbHashToDataURL,xa as thumbHashToAverageRGBA,ya as thumbHashToApproximateAspectRatio,ba as threshold,ma as srgbToLinear,Oa as splatHashToRgba,Ra as splatHashToDataURL,Pa as splatHashToBase64,Qa as splatHashFromBase64,Z as sobelEdgeDetection,X as sharpenConvolution,W as sharpen,d as setPixel,ea as sepia,i as rotate90,k as rotate270,j as rotate180,h as rotate,va as rgbaToThumbHash,Ma as rgbaToSplatHash,za as rgbaToDataURL,ka as rgbToHsl,S as resizeLanczos,R as resizeBilinear,Q as resizeBicubic,T as resize,I as processSvg,ua as processMultiple,H as processImage,ta as process,G as printSummary,E as parseFileSize,J as optimizeSvg,O as optimizeImage,ha as normalize,ca as modulate,na as linearToSrgb,r as jpegExifOrientation,B as isPathMatching,da as invert,K as imageToSvg,Na as imageToSplatHash,la as hslToRgb,aa as grayscale,e as getPixelBilinear,c as getPixel,v as getMetadata,z as getFiles,ja as getDominantColor,Ba as generateThumbHash,Fa as generateSprite,Ia as generateSocialImages,Ja as generateResponsiveImages,x as generateReport,L as generatePlaceholder,Sa as generatePictureSet,Ca as generateMacOSAppIcons,Ka as generateImageSet,Da as generateIOSAppIcons,Ga as generateFavicons,Ea as generateAppIcons,ga as gamma,f as fromCodecData,F as formatBytes,m as flop,l as flip,C as filterPaths,o as extract,p as extend,u as encode,_ as emboss,t as decode,D as debugLog,n as crop,ra as createSolidColor,sa as createLinearGradient,a as createImageData,Y as convolve,M as convertImageFormat,fa as contrast,y as config,qa as compositeMultiple,pa as composite,b as cloneImageData,V as boxBlur,U as blur,N as batchProcessImages,P as applyWatermark,s as applyExifOrientation,w as analyzeImage,Ha as _internals,La as SPLATHASH_TARGET_SIZE,$ as KERNELS};
|
package/dist/chunk-habv0vef.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{If as O,Jf as T}from"./chunk-dxg045wj.js";import{gj as I}from"./chunk-tpfgntwj.js";import{Vm as A}from"./chunk-jff6j9y3.js";import"./chunk-csfrpsp7.js";import"./chunk-0t5vz87j.js";import"./chunk-krkchy8v.js";import"./chunk-brpgjyqg.js";import"./chunk-5mxby3fd.js";import{Mo as L}from"./chunk-5be9x5cq.js";import"./chunk-jmeb7n8k.js";import"./chunk-kc659vhx.js";import"./chunk-a3wahyg7.js";import o from"path";import p from"fs";var X=5,M=1;function Z(n=process.env){return n.STX_DEBUG==="true"||n.STX_DEBUG==="1"}function b(...n){if(Z())console.log("[stx:bundler]",...n)}var R=[];function q(n,i,c){R.push({filePath:n||"<inline>",message:i,details:c})}function oe(){return R.slice()}function ie(){R.length=0}var _;function ce(n){_=n}function G(){if(_)return _;try{let n=I.strict;return typeof n==="object"&&n!==null?n.bundlerFallback??"warn":"warn"}catch{return"warn"}}var k=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function ae(n){let i=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,c;while((c=i.exec(n))!==null){let d=c[1];if(!k.some((s)=>s.test(d)))return b("detected user import:",d),!0}let f=/^[ \t]*import[ \t]+['"]([^'"]+)['"]/gm;while((c=f.exec(n))!==null){let d=c[1];if(/\.css(?:\?.*)?$/.test(d))continue;if(!k.some((s)=>s.test(d)))return b("detected side-effect import:",d),!0}return!1}function Q(n,i,c,f){let d=(s,t)=>{let e=s===c?i:o.dirname(s),r=o.resolve(e,t),u=[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.mjs`,`${r}.jsx`,o.join(r,"index.ts"),o.join(r,"index.tsx"),o.join(r,"index.js"),o.join(r,"index.mjs")];for(let h of u)try{if(p.existsSync(h)&&p.statSync(h,{throwIfNoEntry:!1})?.isFile())return h}catch{}return r};return{name:"stx-client-bundle",setup(s){s.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(t)=>({path:t.path,external:!0})),s.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(t)=>({path:t.path,external:!0})),s.onResolve({filter:/^\//},(t)=>{if(p.existsSync(t.path))return{path:t.path};return{path:t.path,external:!0}}),s.onResolve({filter:/^\.\.?\//},(t)=>{let e=d(t.importer,t.path);return f.add(e),{path:e}}),s.onResolve({filter:/^[@~]\//},(t)=>{let e=o.resolve(n,t.path.slice(2)),r=[e,`${e}.ts`,`${e}.tsx`,`${e}.js`,`${e}.mjs`,`${e}.jsx`,o.join(e,"index.ts"),o.join(e,"index.tsx"),o.join(e,"index.js"),o.join(e,"index.mjs")];for(let u of r)if(p.existsSync(u)&&p.statSync(u,{throwIfNoEntry:!1})?.isFile())return b(`resolved ${t.path[0]}/ import:`,t.path,"\u2192",u),f.add(u),{path:u};return console.warn(`[stx:bundler] could not resolve ${t.path[0]}/ import:`,t.path),{path:e}}),s.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(t)=>{let e=o.extname(t.path).toLowerCase(),r=e===".json"?"json":e===".tsx"?"tsx":e===".jsx"?"jsx":e===".ts"||e===".mts"||e===".cts"?"ts":"js";if(t.path!==c)f.add(t.path);return{contents:p.readFileSync(t.path,"utf8"),loader:r}})}}}var D=new Map,C=Symbol.for("stx.client-bundle-build-queue");function K(n){let i=globalThis,c=(i[C]??Promise.resolve()).then(n,n);return i[C]=c.then(()=>{return},()=>{return}),c}async function le(n,i,c={}){let f=c.projectRoot||process.cwd(),d=c.minify??!1,s=c.cacheDir||A(f,"bundle-cache"),t=new Bun.CryptoHasher("md5");t.update(`${X}\x00${n}\x00${i}`);let e=t.digest("hex").slice(0,12),r=o.join(s,`${e}.js`),u=o.join(s,`${e}.deps.json`),h=Bun.file(r);if(await h.exists()){let x=Bun.file(u),w=!0;if(await x.exists())try{let v=JSON.parse(await x.text());if(v.metadataVersion!==M||!Array.isArray(v.files))w=!1;for(let m of Array.isArray(v.files)?v.files:[])try{if(p.statSync(m.path).mtimeMs!==m.mtimeMs){w=!1;break}}catch{w=!1;break}}catch{w=!1}if(w)return b("cache hit:",e),await h.text();b("cache invalidated by dep change:",e)}let g=D.get(e);if(g)return await g;let B=K(()=>W(n,i,{projectRoot:f,minify:d,cacheDir:s,hash:e,cachePath:r,depsPath:u}));D.set(e,B);try{return await B}finally{D.delete(e)}}async function W(n,i,c){let{projectRoot:f,minify:d,cacheDir:s,hash:t,cachePath:e,depsPath:r}=c,u=A(f,"bundle-tmp"),h=o.join(u,`${t}.ts`),g=o.join(u,"out",t);p.mkdirSync(u,{recursive:!0}),p.mkdirSync(g,{recursive:!0});let B=o.dirname(i),x=[],w=/^(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,v=/^(export\s+)?(?:async\s+)?function\s+(\w+)/gm,m;while((m=w.exec(n))!==null){if(m[1])continue;if(m[2])m[2].split(",").forEach(($)=>{let l=$.split(":")[0].trim();if(l)x.push(l)});else if(m[3])x.push(m[3])}while((m=v.exec(n))!==null){if(m[1])continue;x.push(m[2])}let U=x.length>0?`
|
|
3
|
-
export { ${x.join(", ")} }`:"";await Bun.write(h,n+U),b("bundling:",t,"from:",o.basename(i));let N=new Set;try{let $=await Bun.build({entrypoints:[h],outdir:g,target:"browser",format:"esm",minify:d,plugins:[Q(f,B,h,N)],define:{"process.env.NODE_ENV":d?'"production"':'"development"',...L()},root:f});if(!$.success){let a=$.logs.filter((j)=>j.level==="error").map((j)=>j.message).join(", ");return console.warn("[stx:bundler] build failed:",a),n}let l="";for(let a of $.outputs){l=await a.text();break}let y=[];for(let a of l.matchAll(/^\s*export\s*\{([^}]*)\}\s*;?\s*$/gm))for(let j of a[1].split(",")){let S=j.trim().match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(S){y.push([S[2],S[1]]);continue}let E=j.trim();if(/^[A-Za-z_$][\w$]*$/.test(E))y.push([E,E])}let V=l.match(/^\s*import\s+[^;]+;?\s*$/gm)||[];l=l.replace(/^\s*import\s+[^;]+;?\s*$/gm,"").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"").replace(/^\s*export\s+default\s+.*$/gm,"").trim();let F=`__stxBundle_${t}`,J=y.map(([a,j])=>`${JSON.stringify(a)}: ${j}`).join(", "),z=y.map(([a])=>`var ${a} = undefined;`).join(`
|
|
4
|
-
`),H=y.map(([a])=>`${a} = ${F}[${JSON.stringify(a)}];`).join(`
|
|
5
|
-
`);if(l=`${V.join(`
|
|
6
|
-
`)}
|
|
7
|
-
${z}
|
|
8
|
-
var ${F} = (function() {
|
|
9
|
-
${l}
|
|
10
|
-
return { ${J} };
|
|
11
|
-
})();
|
|
12
|
-
${H}`.trim(),b("bundled:",t,"output:",l.length,"bytes"),x.length>0&&y.length===0)return console.warn(`[stx:bundler] dropped every binding for ${o.basename(i)} (${t}); serving the unbundled source and not caching this result`),n;p.mkdirSync(s,{recursive:!0}),await Bun.write(e,l);let P=Array.from(N).map((a)=>{try{return{path:a,mtimeMs:p.statSync(a).mtimeMs}}catch{return null}}).filter((a)=>a!==null);return await Bun.write(r,JSON.stringify({metadataVersion:M,files:P})),l}catch($){let l=O($,i||void 0),y=T($,i||void 0);if(console.warn(`[stx:bundler] error: ${y}`),q(i||"",y,l),G()==="error")throw $;return n}finally{try{p.rmSync(h,{force:!0}),p.rmSync(g,{recursive:!0,force:!0})}catch{}}}export{Z as shouldLogBundlerDiagnostics,ce as setBundlerFallbackMode,G as resolveBundlerFallback,q as recordBundleFailure,K as queueClientBundleBuild,ae as hasUserImports,oe as getBundleFailures,ie as clearBundleFailures,le as bundleClientScript};
|
package/dist/chunk-hz6fc788.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Fu as x,Ku as d,Lu as R,Mu as k,Nu as D}from"./chunk-5n0ckcmc.js";import{Zu as T}from"./chunk-a3wahyg7.js";import{resolve as H,basename as E,dirname as se,extname as W,join as V}from"path";import{mkdir as A,writeFile as ne}from"fs/promises";var Q={enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500,cacheVariants:!0,cachePlaceholders:!0};class S{config;constructor(e={}){this.config={...Q,...e}}async get(e,i){return R(e,i,"image",this.config)}async set(e,i,r){return k(e,i,r,"image",this.config)}async clear(){return D("image",this.config)}updateConfig(e){this.config={...this.config,...e}}}var b=null;function q(e){if(!b)b=new S(e);else if(e)b.updateConfig(e);return b}async function v(e,i,r){let t=r?{directory:`${r.outputDir}/../.cache`}:{};return q(t).get(e,i)}async function $(e,i,r,t){let a=t?{directory:`${t.outputDir}/../.cache`}:{};return q(a).set(e,i,r)}async function L(){return q().clear()}async function F(){try{return await import("./chunk-gfd23b6t.js")}catch{return null}}function P(e){switch(e){case"quality":return{jpeg:{quality:90,mozjpeg:!0,progressive:!0},png:{compressionLevel:6,palette:!1},webp:{quality:90,effort:6,smartSubsample:!0},avif:{quality:85,effort:6}};case"performance":return{jpeg:{quality:70,mozjpeg:!0,progressive:!0},png:{compressionLevel:9,palette:!0},webp:{quality:70,effort:4,smartSubsample:!0},avif:{quality:60,effort:2}};case"web":default:return{jpeg:{quality:82,mozjpeg:!0,progressive:!0},png:{compressionLevel:8,palette:!1},webp:{quality:82,effort:5,smartSubsample:!0},avif:{quality:75,effort:4}}}}function B(e,i){let r=i?P(i):P("web"),t=e.formatQuality||{};return{jpeg:{...r.jpeg,...t.jpeg},png:{...r.png,...t.png},webp:{...r.webp,...t.webp},avif:{...r.avif,...t.avif}}}async function M(e,i,r){let t=await F();if(!t)return console.warn("[stx-media] ts-images not installed, skipping optimization"),{src:e,processed:!1};let a=await v(e,i,r);if(a)return a;try{let u=H(e);if(!await d(u))return{src:e,processed:!1,errors:[`Source file not found: ${e}`]};let n=B(r,i.preset),m=r.outputDir||"dist/images",I=r.baseUrl||"/images";await A(m,{recursive:!0});let w=await x(u),C=E(e,W(e)),z=i.outputFormat?[i.outputFormat]:r.defaultFormats||["avif","webp","jpeg"],o={src:e,processed:!0,variants:[],hash:w},h=null;if(i.transformations&&i.transformations.length>0)h=await U(u,i.transformations,t);for(let s of z){let p=n[s]||{},l=`${C}-${w}.${s}`,g=V(m,l);try{let c=await t.optimizeImage({input:h||u,output:g,format:s,quality:p.quality,progressive:p.progressive});if(c){if(o.variants.push({path:g,url:`${I}/${l}`,width:c.width||0,height:c.height||0,format:s,size:c.outputSize||0}),!o.originalWidth&&c.width)o.originalWidth=c.width,o.originalHeight=c.height}}catch(c){o.errors=o.errors||[],o.errors.push(`Failed to optimize ${s}: ${c}`)}}if(i.embedThumbhash||i.placeholder==="thumbhash")try{let s=await t.generateThumbHash(u);o.placeholder=s.dataUrl}catch(s){o.errors=o.errors||[],o.errors.push(`Failed to generate thumbhash: ${s}`)}if(i.useDominantColor)try{let s=await t.generatePlaceholder(u,{strategy:"dominant-color"});o.dominantColor=s.dominantColor}catch(s){o.errors=o.errors||[],o.errors.push(`Failed to extract dominant color: ${s}`)}return await $(e,i,o,r),o}catch(u){return{src:e,processed:!1,errors:[`Processing failed: ${u}`]}}}async function O(e,i,r,t){let a=await F();if(!a)return{success:!1,error:"ts-images not installed"};try{return{success:!0,size:(await a.optimizeImage({input:e,output:t,format:i,quality:r}))?.outputSize}}catch(u){return{success:!1,error:String(u)}}}async function U(e,i,r){let t=r||await F();if(!t)return console.warn("[stx-media] ts-images not installed, skipping transformations"),null;try{let a=await t.decode(e);for(let u of i){let n=u.options||{};switch(u.type){case"resize":if(n.width||n.height)a=await t.resize(a,{width:n.width,height:n.height,fit:n.fit});break;case"blur":if(n.sigma!==void 0)a=await t.blur(a,n.sigma);break;case"sharpen":if(n.amount!==void 0)a=await t.sharpen(a,n.amount);break;case"grayscale":a=await t.grayscale(a);break;case"rotate":if(n.angle!==void 0)a=await t.rotate(a,n.angle);break;case"flip":a=await t.flip(a);break;case"flop":a=await t.flop(a);break;case"brightness":if(n.value!==void 0)a=await t.brightness(a,n.value);break;case"contrast":if(n.value!==void 0)a=await t.contrast(a,n.value);break;case"saturation":if(n.value!==void 0)a=await t.saturation(a,n.value);break}}return await t.encode(a,"png")}catch(a){return console.error(`[stx-media] Transformation failed: ${a}`),null}}import{resolve as _,basename as N,extname as G,join as J}from"path";import{mkdir as K}from"fs/promises";async function X(){try{return await import("./chunk-gfd23b6t.js")}catch{return null}}var Y=[320,480,640,768,1024,1280,1536,1920];async function Z(e,i,r){let t=await X();if(!t)return console.warn("[stx-media] ts-images not installed, skipping responsive generation"),null;let a=_(e);if(!await d(a))return console.warn(`[stx-media] Source file not found: ${e}`),null;try{let u=i.responsiveWidths||r.breakpoints||Y,n=i.formats||r.defaultFormats||["avif","webp","jpeg"],m=r.outputDir||"dist/images",I=r.baseUrl||"/images";await K(m,{recursive:!0});let w=await x(a),C=N(e,G(e)),z=r.formatQuality||{jpeg:{quality:82},png:{quality:80},webp:{quality:82},avif:{quality:75}},o={src:e,byFormat:{},srcsets:{}};for(let s of n){o.byFormat[s]=[];let p=[];for(let l of u){let g=`${C}-${l}w-${w}.${s}`,c=J(m,g),y=`${I}/${g}`;try{let j=z[s]?.quality||80;if(await d(c)){o.byFormat[s].push({path:c,url:y,width:l,height:0,format:s,size:0}),p.push(`${y} ${l}w`);continue}let f=await t.processImage({input:a,output:c,format:s,quality:j,resize:{width:l}});if(f)o.byFormat[s].push({path:c,url:y,width:l,height:f.height||Math.round(l*(f.height||1)/(f.width||1)),format:s,size:f.outputSize||0}),p.push(`${y} ${l}w`)}catch(j){console.warn(`[stx-media] Failed to generate ${s} at ${l}w: ${j}`)}}o.srcsets[s]=p.join(", ")}let h=i.placeholder||r.placeholderStrategy||"thumbhash";if(h!=="none")try{if(h==="thumbhash"){let s=await t.generateThumbHash(a);o.placeholder={dataURL:s.dataUrl,width:s.width||32,height:s.height||32,strategy:"thumbhash"}}else{let s=await t.generatePlaceholder(a,{strategy:h,width:20});o.placeholder={dataURL:s.dataURL,width:s.width,height:s.height,strategy:h}}}catch(s){console.warn(`[stx-media] Failed to generate placeholder: ${s}`)}return o.sizes=i.sizes||ee(u),o}catch(u){return console.error(`[stx-media] Responsive generation failed: ${u}`),null}}function ee(e){let i=[...e].sort((t,a)=>t-a),r=[];for(let t=0;t<i.length-1;t++){let a=i[t];r.push(`(max-width: ${a}px) ${a}px`)}return r.push(`${i[i.length-1]}px`),r.join(", ")}function te(e,i="width"){if(!e||e.length===0)return"";if(i==="dpr")return e.filter((r)=>r.dpr).map((r)=>`${r.url} ${r.dpr}x`).join(", ");return e.map((r)=>`${r.url} ${r.width}w`).join(", ")}export{S as lu,v as mu,$ as nu,L as ou,M as pu,O as qu,U as ru,Z as su,te as tu};
|
package/dist/chunk-jff6j9y3.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Zo as te}from"./chunk-jmeb7n8k.js";import{Zu as se}from"./chunk-a3wahyg7.js";import r from"path";function J(s){return typeof s==="object"&&s!==null&&!Array.isArray(s)}function L(s,e){let t={...s};for(let[o,n]of Object.entries(e))t[o]=J(n)&&J(t[o])?L(t[o],n):n;return t}function Y(s={},e={}){let t=s.theme||{},o=e.theme||{},{extend:n,...c}=o,{extend:i,...x}=t,f=L(x,c),S=L(i||{},n||{});if(Object.keys(S).length>0)f.extend=S;let $=[...s.safelist||[],...e.safelist||[]],B={...s.shortcuts||{},...e.shortcuts||{}},j=[...s.preflights||[],...e.preflights||[]];return{config:{...s,...e,theme:f,safelist:$,shortcuts:B,...j.length>0?{preflights:j}:{},content:[],output:""},safelist:$,shortcuts:B,includePreflight:e.preflight!==!1,minify:e.minify===!0}}import D from"path";var A=".stx",ie="STX_DIR",q=null;function he(s){q=s?.trim()||null}function N(){return process.env[ie]?.trim()||q||A}function Z(s=process.cwd(),...e){let t=N();return D.isAbsolute(t)?D.join(t,...e):D.join(s,t,...e)}function me(s){if(!s||D.isAbsolute(s))return s;let e=s.replace(/\\/g,"/");if(e!==A&&!e.startsWith(`${A}/`))return s;let t=e.slice(A.length+1);return t?D.join(N(),t):N()}var a={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgGray:"\x1B[100m"};var p=null,W=!1,w=null,E="",b=!1,ne=256,m=new Map,g=new Map,C=null,P=null;function O(s){return Bun.hash(s).toString(16).padStart(16,"0").slice(0,16)}function F(s,e){if(m.has(s))m.delete(s);else if(m.size>=ne)m.delete(m.keys().next().value);m.set(s,e)}function ce(s){let e=O(s);if(g.has(e))g.delete(e);else if(g.size>=ne)g.delete(g.keys().next().value);return g.set(e,s),e}function ke(s){let e=g.get(s);if(e===void 0)return;return g.delete(s),g.set(s,e),e}async function ae(s){if(!C)return null;try{let e=Bun.file(r.join(C,`cw-${O(s)}.css`));if(!await e.exists())return null;return await e.text()}catch{return null}}async function le(s,e){if(!C)return;try{if(!fs.existsSync(C))fs.mkdirSync(C,{recursive:!0});await Bun.write(r.join(C,`cw-${O(s)}.css`),e)}catch{}}async function ee(s){try{let e=await import(s);if(e&&e.CSSGenerator)return{CSSGenerator:e.CSSGenerator,config:e.config,build:e.build,defaultConfig:e.defaultConfig,extractClasses:e.extractClasses}}catch{}return null}function de(){let s=[],e=process.cwd();while(e!==r.dirname(e))s.push(r.join(e,"node_modules","@cwcss","crosswind","dist","index.js")),s.push(r.join(e,"node_modules","@cwcss","crosswind","src","index.ts")),s.push(r.join(e,"pantry","@cwcss","crosswind","dist","index.js")),s.push(r.join(e,"pantry","@cwcss","crosswind","src","index.ts")),s.push(r.join(e,"node_modules","@stacksjs","crosswind","dist","index.js")),s.push(r.join(e,"pantry","@stacksjs","crosswind","dist","index.js")),e=r.dirname(e);return s}function fe(){let s=[],e=process.env.HOME||process.env.USERPROFILE||"";if(e){let t=[r.join(e,"Code","Tools","crosswind","packages","crosswind","dist","index.js"),r.join(e,"Code","Tools","crosswind","packages","crosswind","src","index.ts"),r.join(e,"repos","stacks-org","crosswind","packages","crosswind","dist","index.js"),r.join(e,"repos","stacks-org","crosswind","packages","crosswind","src","index.ts"),r.join(e,"Code","Tools","stx","packages","stx","node_modules","@cwcss","crosswind","dist","index.js"),r.join(e,"Code","Tools","stx","packages","stx","node_modules","@stacksjs","crosswind","dist","index.js")];s.push(...t)}return s.push(r.join(process.cwd(),"..","crosswind","packages","crosswind","dist","index.js")),s.push(r.join(process.cwd(),"..","crosswind","packages","crosswind","src","index.ts")),s}async function re(){if(W)return p;W=!0;try{let s=async(n)=>{for(let c of n){if(!await Bun.file(c).exists())continue;let i=await ee(c);if(i){if(!process.env.STACKS_DEV_QUIET)console.log(`${a.green}[Crosswind]${a.reset} CSS engine loaded from ${r.dirname(r.dirname(c))}`);return i}}return null};if(process.env.CROSSWIND_SRC){let n=r.resolve(process.env.CROSSWIND_SRC),c=await s([n]);if(!c)throw Error(`CROSSWIND_SRC did not resolve to a Crosswind module: ${n}`);return p=c,p}let e=await s(de());if(e)return p=e,p;let t=["@cwcss/crosswind","@cwcss/crosswind/dist/index.js","@stacksjs/crosswind","@stacksjs/crosswind/dist/index.js"];for(let n of t){let c=await ee(n);if(c){if(p=c,!process.env.STACKS_DEV_QUIET)console.log(`${a.green}[Crosswind]${a.reset} CSS engine loaded`);return p}}let o=await s(fe());if(o)return p=o,p;throw Error("Crosswind CSSGenerator not found in any location")}catch{return console.warn(`${a.yellow}[Crosswind] CSS engine not available, Tailwind styles will not be generated${a.reset}`),console.warn(`${a.yellow}Run 'bun add @stacksjs/crosswind' to enable CSS generation${a.reset}`),null}}function ve(){m.clear(),g.clear()}function Te(){p=null,W=!1,w=null,E="",m.clear(),g.clear(),P=null}async function oe(s){try{if(!te({name:"crosswind",cwd:s}))return null;let{loadConfigWithResult:e}=await import("./chunk-z8szsm21.js"),t=await e({name:"crosswind",cwd:s,defaultConfig:{},checkEnv:!1,verbose:!1});if(!t?.path||!t.config||Object.keys(t.config).length===0)return null;let o=r.relative(s,t.path);if(!process.env.STACKS_DEV_QUIET)console.log(`${a.green}[Crosswind]${a.reset} Loaded config from ${o||t.path}`);return t.config}catch(e){if(e instanceof Error&&e.name==="ConfigNotFoundError")return null;return console.warn(`${a.yellow}[Crosswind]${a.reset} Failed to load crosswind config:`,e instanceof Error?e.message:e),null}}async function ue(s){if(b)return E;b=!0;try{let e=await re();if(!e||!e.build)return b=!1,"";if(!w)w=await oe(s);if(!w)return b=!1,"";let t=e.defaultConfig?.theme||{},o=w.theme||{},n={...e.defaultConfig,...w,theme:{...t,...o,extend:{...t.extend||{},...o.extend||{}}}},c=performance.now(),i=await e.build(n),x=performance.now()-c;if(E=i.css,console.log(`${a.cyan}[Crosswind]${a.reset} Built ${i.classes.size} classes in ${x.toFixed(1)}ms`),n.output){let f=r.isAbsolute(n.output)?n.output:r.join(s,n.output),S=r.dirname(f);if(!fs.existsSync(S))fs.mkdirSync(S,{recursive:!0});await Bun.write(f,i.css)}return b=!1,i.css}catch(e){return console.error(`${a.red}[Crosswind]${a.reset} Build error:`,e),b=!1,E}}async function De(s){w=null,await ue(s)}function Ee(){return E}function ge(s){let e=new Set,t=/class\s*=\s*["']([^"']+)["']/gi,o=t.exec(s);while(o!==null){for(let i of o[1].split(/\s+/))if(i.trim())e.add(i.trim());o=t.exec(s)}let n=/(?:x-class|:class)\s*=\s*"([^"]+)"/gi,c=n.exec(s);while(c!==null){let i=c[1].match(/'([^']+)'/g);if(i){for(let x of i)for(let f of x.slice(1,-1).split(/\s+/))if(f.trim())e.add(f.trim())}c=n.exec(s)}return e}async function we(s,e){try{let t=await re();if(!t)return"";let o=typeof t.extractClasses==="function"?t.extractClasses(s):ge(s);if(o.size===0)return"";let n=e?r.resolve(e):process.cwd();if(!C)C=Z(n,"cache");let c=[...o].sort().join(" "),i=`${P||"default"}::${c}`,x=m.get(i);if(x!==void 0)return F(i,x),x;let f=await ae(i);if(f!==null)return F(i,f),f;if(!w){let d=null;try{let{loadStxConfig:T}=await import("./chunk-cd03rk3x.js"),l=await T(n);if(l.css)if(typeof l.css==="string"){let u=r.isAbsolute(l.css)?l.css:r.resolve(n,l.css);if(await Bun.file(u).exists()){let h=await import(u);d=h.default||h,console.log(`${a.green}[Crosswind]${a.reset} Loaded config from stx.config.ts \u2192 ${l.css}`)}}else{if(d={...l.css,content:l.css.content||[],preflight:l.css.preflight??!0,minify:l.css.minify??!1},l.css.config){let u=r.isAbsolute(l.css.config)?l.css.config:r.resolve(n,l.css.config);if(await Bun.file(u).exists()){let h=await import(u);d={...h.default||h,...d}}}console.log(`${a.green}[Crosswind]${a.reset} Using inline CSS config from stx.config.ts`)}}catch{}w=d||await oe(n);try{P=O(JSON.stringify(w??{}))}catch{P="unhashable"}}let S=t.defaultConfig||t.config,$=w||{},B=Y(S,$),{safelist:j,includePreflight:G,minify:K}=B,z=B.config,k=new t.CSSGenerator(z);for(let d of j)k.generate(d);for(let d of o)k.generate(d);let y=k.toCSS(G,K),U=z.shortcuts||$.shortcuts||{};for(let[d,T]of Object.entries(U)){if(!o.has(d)&&!j.includes(d))continue;let l=T.split(/\s+/).filter(Boolean);for(let u of l)k.generate(u)}y=k.toCSS(G,K);let v=y.split(`
|
|
3
|
-
`);for(let[d,T]of Object.entries(U)){if(!o.has(d)&&!j.includes(d))continue;let l=T.split(/\s+/).filter(Boolean),u=[],h=[];for(let M of l){let V=M.startsWith("dark:"),H=`.${(V?M.slice(5):M).replace(/\//g,"\\/").replace(/:/g,"\\:").replace(/\./g,"\\.").replace(/\[/g,"\\[").replace(/\]/g,"\\]").replace(/%/g,"\\%")}`;for(let _=0;_<v.length;_++){let Q=v[_].trim();if(Q===`${H} {`||Q.startsWith(`${H} {`)){let R=_,X="";while(R<v.length){if(X+=v[R],v[R].includes("}"))break;R++}let I=X.match(/\{([^}]+)\}/);if(I)if(V)h.push(I[1].trim());else u.push(I[1].trim());break}}}if(u.length)y+=`
|
|
4
|
-
.${d} { ${u.join(" ")} }`;if(h.length)y+=`
|
|
5
|
-
@media (prefers-color-scheme: dark) { .dark .${d} { ${h.join(" ")} } }`}return F(i,y),le(i,y),y}catch(t){return console.warn("Failed to generate Crosswind CSS:",t),""}}async function _e(s,e,t=!1){let o=await we(s,e);if(!o)return s;let n=t?`<link data-crosswind="generated" rel="stylesheet" href="/_stx/crosswind.${ce(o)}.css">`:`<style data-crosswind="generated">
|
|
6
|
-
${o}
|
|
7
|
-
</style>`,c=/(?:<style\b[^>]*\bdata-crosswind=(?:"generated"|'generated')[^>]*>[\s\S]*?<\/style>|<link\b[^>]*\bdata-crosswind=(?:"generated"|'generated')[^>]*>)/g;if(c.test(s)){let i=!1;return s.replace(c,()=>{if(i)return"";return i=!0,n})}if(s.includes("</head>"))return s.replace("</head>",`${n}
|
|
8
|
-
</head>`);if(s.includes("<body"))return s.replace(/<body([^>]*)>/,`<body$1>
|
|
9
|
-
${n}`);return n+s}
|
|
10
|
-
export{A as Rm,ie as Sm,he as Tm,N as Um,Z as Vm,me as Wm,L as Xm,Y as Ym,a as Zm,ke as _m,re as $m,ve as an,Te as bn,oe as cn,ue as dn,De as en,Ee as fn,ge as gn,we as hn,_e as in};
|