@devwareng/vanilla-js
Version: 
Framework-less JavaScript hooks for SPA development.
124 lines (102 loc) • 46.6 kB
JavaScript
var Oe=Object.create;var K=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty;var lt=(s,t)=>()=>(s&&(t=s(s=0)),t);var qt=(s,t)=>{for(var e in t)K(s,e,{get:t[e],enumerable:!0})},Gt=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ne(t))!Ce.call(s,r)&&r!==e&&K(s,r,{get:()=>t[r],enumerable:!(n=Fe(t,r))||n.enumerable});return s};var x=(s,t,e)=>(e=s!=null?Oe(ke(s)):{},Gt(t||!s||!s.__esModule?K(e,"default",{value:s,enumerable:!0}):e,s)),Me=s=>Gt(K({},"__esModule",{value:!0}),s);function he(s,t={}){let e=t.entryType||t.type;if(e==="both"&&(e=L.FILE_DIR_TYPE),e&&(t.type=e),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(e&&!ie.includes(e))throw new Error(`readdirp: Invalid type passed. Use one of ${ie.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=s,new Jt(t)}var k,ce,C,L,Mt,le,Ue,ie,Ye,qe,Ge,Be,oe,ae,Jt,ue=lt(()=>{k=require("fs/promises"),ce=require("stream"),C=require("path"),L={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Mt={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:L.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Mt);le="READDIRP_RECURSIVE_ERROR",Ue=new Set(["ENOENT","EPERM","EACCES","ELOOP",le]),ie=[L.DIR_TYPE,L.EVERYTHING_TYPE,L.FILE_DIR_TYPE,L.FILE_TYPE],Ye=new Set([L.DIR_TYPE,L.EVERYTHING_TYPE,L.FILE_DIR_TYPE]),qe=new Set([L.EVERYTHING_TYPE,L.FILE_DIR_TYPE,L.FILE_TYPE]),Ge=s=>Ue.has(s.code),Be=process.platform==="win32",oe=s=>!0,ae=s=>{if(s===void 0)return oe;if(typeof s=="function")return s;if(typeof s=="string"){let t=s.trim();return e=>e.basename===t}if(Array.isArray(s)){let t=s.map(e=>e.trim());return e=>t.some(n=>e.basename===n)}return oe},Jt=class extends ce.Readable{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let e={...Mt,...t},{root:n,type:r}=e;this._fileFilter=ae(e.fileFilter),this._directoryFilter=ae(e.directoryFilter);let i=e.lstat?k.lstat:k.stat;Be?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=e.depth??Mt.depth,this._wantsDir=r?Ye.has(r):!1,this._wantsFile=r?qe.has(r):!1,this._wantsEverything=r===L.EVERYTHING_TYPE,this._root=(0,C.resolve)(n),this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,n=e&&e.files;if(n&&n.length>0){let{path:r,depth:i}=e,a=n.splice(0,t).map(c=>this._formatEntry(c,r)),o=await Promise.all(a);for(let c of o){if(!c)continue;if(this.destroyed)return;let l=await this._getEntryType(c);l==="directory"&&this._directoryFilter(c)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,i+1)),this._wantsDir&&(this.push(c),t--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),t--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(t,e){let n;try{n=await(0,k.readdir)(t,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:e,path:t}}async _formatEntry(t,e){let n,r=this._isDirent?t.name:t;try{let i=(0,C.resolve)((0,C.join)(e,r));n={path:(0,C.relative)(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?t:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(t){Ge(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let e=t[this._statsProp];if(e.isFile())return"file";if(e.isDirectory())return"directory";if(e&&e.isSymbolicLink()){let n=t.fullPath;try{let r=await(0,k.realpath)(n),i=await(0,k.lstat)(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===C.sep){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=le,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}}});function de(s,t,e,n,r){let i=(a,o)=>{e(s),r(a,o,{watchedPath:s}),o&&s!==o&&st(p.resolve(s,o),j,p.join(s,o))};try{return(0,$.watch)(s,{persistent:t.persistent},i)}catch(a){n(a);return}}var $,F,p,fe,Ve,zt,me,nt,it,Wt,Ke,Qe,Ze,pe,y,O,Xe,ts,j,tt,H,es,ss,rs,$t,q,ns,G,we,et,st,is,jt,os,rt,ye=lt(()=>{$=require("fs"),F=require("fs/promises"),p=x(require("path"),1),fe=require("os"),Ve="data",zt="end",me="close",nt=()=>{},it=process.platform,Wt=it==="win32",Ke=it==="darwin",Qe=it==="linux",Ze=it==="freebsd",pe=(0,fe.type)()==="OS400",y={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},O=y,Xe="watch",ts={lstat:F.lstat,stat:F.stat},j="listeners",tt="errHandlers",H="rawEmitters",es=[j,tt,H],ss=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),rs=s=>ss.has(p.extname(s).slice(1).toLowerCase()),$t=(s,t)=>{s instanceof Set?s.forEach(t):t(s)},q=(s,t,e)=>{let n=s[t];n instanceof Set||(s[t]=n=new Set([n])),n.add(e)},ns=s=>t=>{let e=s[t];e instanceof Set?e.clear():delete s[t]},G=(s,t,e)=>{let n=s[t];n instanceof Set?n.delete(e):n===e&&delete s[t]},we=s=>s instanceof Set?s.size===0:!s,et=new Map;st=(s,t,e,n,r)=>{let i=et.get(s);i&&$t(i[t],a=>{a(e,n,r)})},is=(s,t,e,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=et.get(t),c;if(!e.persistent)return c=de(s,e,r,i,a),c?c.close.bind(c):void 0;if(o)q(o,j,r),q(o,tt,i),q(o,H,a);else{if(c=de(s,e,st.bind(null,t,j),i,st.bind(null,t,H)),!c)return;c.on(O.ERROR,async l=>{let h=st.bind(null,t,tt);if(o&&(o.watcherUnusable=!0),Wt&&l.code==="EPERM")try{await(await(0,F.open)(s,"r")).close(),h(l)}catch{}else h(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},et.set(t,o)}return()=>{G(o,j,r),G(o,tt,i),G(o,H,a),we(o.listeners)&&(o.watcher.close(),et.delete(t),es.forEach(ns(o)),o.watcher=void 0,Object.freeze(o))}},jt=new Map,os=(s,t,e,n)=>{let{listener:r,rawEmitter:i}=n,a=jt.get(t),o=a&&a.options;return o&&(o.persistent<e.persistent||o.interval>e.interval)&&((0,$.unwatchFile)(t),a=void 0),a?(q(a,j,r),q(a,H,i)):(a={listeners:r,rawEmitters:i,options:e,watcher:(0,$.watchFile)(t,e,(c,l)=>{$t(a.rawEmitters,u=>{u(O.CHANGE,t,{curr:c,prev:l})});let h=c.mtimeMs;(c.size!==l.size||h>l.mtimeMs||h===0)&&$t(a.listeners,u=>u(s,c))})},jt.set(t,a)),()=>{G(a,j,r),G(a,H,i),we(a.listeners)&&(jt.delete(t),(0,$.unwatchFile)(t),a.options=a.watcher=void 0,Object.freeze(a))}},rt=class{constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let n=this.fsw.options,r=p.dirname(t),i=p.basename(t);this.fsw._getWatchedDir(r).add(i);let o=p.resolve(t),c={persistent:n.persistent};e||(e=nt);let l;if(n.usePolling){let h=n.interval!==n.binaryInterval;c.interval=h&&rs(i)?n.binaryInterval:n.interval,l=os(t,o,c,{listener:e,rawEmitter:this.fsw._emitRaw})}else l=is(t,o,c,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(t,e,n){if(this.fsw.closed)return;let r=p.dirname(t),i=p.basename(t),a=this.fsw._getWatchedDir(r),o=e;if(a.has(i))return;let c=async(h,u)=>{if(this.fsw._throttle(Xe,t,5)){if(!u||u.mtimeMs===0)try{let d=await(0,F.stat)(t);if(this.fsw.closed)return;let f=d.atimeMs,w=d.mtimeMs;if((!f||f<=w||w!==o.mtimeMs)&&this.fsw._emit(O.CHANGE,t,d),(Ke||Qe||Ze)&&o.ino!==d.ino){this.fsw._closeFile(h),o=d;let R=this._watchWithNodeFs(t,c);R&&this.fsw._addPathCloser(h,R)}else o=d}catch{this.fsw._remove(r,i)}else if(a.has(i)){let d=u.atimeMs,f=u.mtimeMs;(!d||d<=f||f!==o.mtimeMs)&&this.fsw._emit(O.CHANGE,t,u),o=u}}},l=this._watchWithNodeFs(t,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(O.ADD,t,0))return;this.fsw._emit(O.ADD,t,e)}return l}async _handleSymlink(t,e,n,r){if(this.fsw.closed)return;let i=t.fullPath,a=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await(0,F.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==o&&(this.fsw._symlinkPaths.set(i,o),this.fsw._emit(O.CHANGE,n,t.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(O.ADD,n,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(t,e,n,r,i,a,o){if(t=p.join(t,""),o=this.fsw._throttle("readdir",t,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,h=this.fsw._readdirp(t,{fileFilter:u=>n.filterPath(u),directoryFilter:u=>n.filterDir(u)});if(h)return h.on(Ve,async u=>{if(this.fsw.closed){h=void 0;return}let d=u.path,f=p.join(t,d);if(l.add(d),!(u.stats.isSymbolicLink()&&await this._handleSymlink(u,t,f,d))){if(this.fsw.closed){h=void 0;return}(d===r||!r&&!c.has(d))&&(this.fsw._incrReadyCount(),f=p.join(i,p.relative(i,f)),this._addToNodeFs(f,e,n,a+1))}}).on(O.ERROR,this._boundHandleError),new Promise((u,d)=>{if(!h)return d();h.once(zt,()=>{if(this.fsw.closed){h=void 0;return}let f=o?o.clear():!1;u(void 0),c.getChildren().filter(w=>w!==t&&!l.has(w)).forEach(w=>{this.fsw._remove(t,w)}),h=void 0,f&&this._handleRead(t,!1,n,r,i,a,o)})})}async _handleDir(t,e,n,r,i,a,o){let c=this.fsw._getWatchedDir(p.dirname(t)),l=c.has(p.basename(t));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(O.ADD_DIR,t,e),c.add(p.basename(t)),this.fsw._getWatchedDir(t);let h,u,d=this.fsw.options.depth;if((d==null||r<=d)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(t,n,a,i,t,r,h),this.fsw.closed))return;u=this._watchWithNodeFs(t,(f,w)=>{w&&w.mtimeMs===0||this._handleRead(f,!1,a,i,t,r,h)})}return u}async _addToNodeFs(t,e,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(t);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await ts[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,c))return a(),!1;let l=this.fsw.options.followSymlinks,h;if(c.isDirectory()){let u=p.resolve(t),d=l?await(0,F.realpath)(t):t;if(this.fsw.closed||(h=await this._handleDir(o.watchPath,c,e,r,i,o,d),this.fsw.closed))return;u!==d&&d!==void 0&&this.fsw._symlinkPaths.set(u,d)}else if(c.isSymbolicLink()){let u=l?await(0,F.realpath)(t):t;if(this.fsw.closed)return;let d=p.dirname(o.watchPath);if(this.fsw._getWatchedDir(d).add(o.watchPath),this.fsw._emit(O.ADD,o.watchPath,c),h=await this._handleDir(d,c,e,r,t,o,u),this.fsw.closed)return;u!==void 0&&this.fsw._symlinkPaths.set(p.resolve(t),u)}else h=this._handleFile(o.watchPath,c,e);return a(),h&&this.fsw._addPathCloser(t,h),!1}catch(c){if(this.fsw._handleError(c))return a(),t}}}});var xe={};qt(xe,{FSWatcher:()=>B,WatchHelper:()=>at,default:()=>Es,watch:()=>Ae});function ot(s){return Array.isArray(s)?s:[s]}function fs(s){return typeof s=="function"?s:typeof s=="string"?t=>s===t:s instanceof RegExp?t=>s.test(t):typeof s=="object"&&s!==null?t=>{if(s.path===t)return!0;if(s.recursive){let e=m.relative(s.path,t);return e?!e.startsWith("..")&&!m.isAbsolute(e):!1}return!1}:()=>!1}function ms(s){if(typeof s!="string")throw new Error("string expected");s=m.normalize(s),s=s.replace(/\\/g,"/");let t=!1;s.startsWith("//")&&(t=!0);let e=/\/\//;for(;s.match(e);)s=s.replace(e,"/");return t&&(s="/"+s),s}function _e(s,t,e){let n=ms(t);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,e))return!0}return!1}function ps(s,t){if(s==null)throw new TypeError("anymatch: specify first argument");let n=ot(s).map(r=>fs(r));return t==null?(r,i)=>_e(n,r,i):_e(n,t)}function Ae(s,t={}){let e=new B(t);return e.add(s),e}var ve,ct,be,m,Ht,as,De,cs,ls,hs,ge,us,ds,Ut,Ee,Se,Re,Pe,ws,ys,Yt,gs,_s,at,B,Es,Te=lt(()=>{ve=require("fs"),ct=require("fs/promises"),be=require("events"),m=x(require("path"),1);ue();ye();Ht="/",as="//",De=".",cs="..",ls="string",hs=/\\/g,ge=/\/\//,us=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,ds=/^\.[/\\]/;Ut=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);Ee=s=>{let t=ot(s).flat();if(!t.every(e=>typeof e===ls))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(Re)},Se=s=>{let t=s.replace(hs,Ht),e=!1;for(t.startsWith(as)&&(e=!0);t.match(ge);)t=t.replace(ge,Ht);return e&&(t=Ht+t),t},Re=s=>Se(m.normalize(Se(s))),Pe=(s="")=>t=>typeof t=="string"?Re(m.isAbsolute(t)?t:m.join(s,t)):t,ws=(s,t)=>m.isAbsolute(s)?s:m.join(t,s),ys=Object.freeze(new Set),Yt=class{constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&t!==De&&t!==cs&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let n=this.path;try{await(0,ct.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(m.dirname(n),m.basename(n))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=nt,this.items=ys,Object.freeze(this)}},gs="stat",_s="lstat",at=class{constructor(t,e,n){this.fsw=n;let r=t;this.path=t=t.replace(ds,""),this.watchPath=r,this.fullWatchPath=m.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=e,this.statMethod=e?gs:_s}entryPath(t){return m.join(this.watchPath,m.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let n=this.entryPath(t);return this.fsw._isntIgnored(n,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},B=class extends be.EventEmitter{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?ot(t.ignored):ot([]),awaitWriteFinish:e===!0?n:typeof e=="object"?{...n,...e}:!1};pe&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?r.usePolling=!1:c==="true"||c==="1"?r.usePolling=!0:r.usePolling=!!c}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=nt,this._readyEmitted=!0,process.nextTick(()=>this.emit(y.READY)))},this._emitRaw=(...c)=>this.emit(y.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new rt(this),Object.freeze(r)}_addIgnoredPath(t){if(Ut(t)){for(let e of this._ignoredPaths)if(Ut(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let e of this._ignoredPaths)Ut(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Ee(t);return r&&(i=i.map(a=>ws(a,r))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,e);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(m.dirname(o),m.basename(e||o))})}),this}unwatch(t){if(this.closed)return this;let e=Ee(t),{cwd:n}=this.options;return e.forEach(r=>{!m.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=m.join(n,r)),r=m.resolve(r)),this._closePath(r),this._addIgnoredPath(r),this._watched.has(r)&&this._addIgnoredPath({path:r,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(n=>{let r=n();r instanceof Promise&&t.push(r)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,n)=>{let i=(this.options.cwd?m.relative(this.options.cwd,n):n)||De;t[i]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==y.ERROR&&this.emit(y.ALL,t,...e)}async _emit(t,e,n){if(this.closed)return;let r=this.options;Wt&&(e=m.normalize(e)),r.cwd&&(e=m.relative(r.cwd,e));let i=[e];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(e)))return o.lastChange=new Date,this;if(r.atomic){if(t===y.UNLINK)return this._pendingUnlinks.set(e,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(y.ALL,...c),this._pendingUnlinks.delete(l)})},typeof r.atomic=="number"?r.atomic:100),this;t===y.ADD&&this._pendingUnlinks.has(e)&&(t=y.CHANGE,this._pendingUnlinks.delete(e))}if(a&&(t===y.ADD||t===y.CHANGE)&&this._readyEmitted){let c=(l,h)=>{l?(t=y.ERROR,i[0]=l,this.emitWithAll(t,i)):h&&(i.length>1?i[1]=h:i.push(h),this.emitWithAll(t,i))};return this._awaitWriteFinish(e,a.stabilityThreshold,t,c),this}if(t===y.CHANGE&&!this._throttle(y.CHANGE,e,50))return this;if(r.alwaysStat&&n===void 0&&(t===y.ADD||t===y.ADD_DIR||t===y.CHANGE)){let c=r.cwd?m.join(r.cwd,e):e,l;try{l=await(0,ct.stat)(c)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(t,i),this}_handleError(t){let e=t&&t.code;return t&&e!=="ENOENT"&&e!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||e!=="EPERM"&&e!=="EACCES")&&this.emit(y.ERROR,t),t||this.closed}_throttle(t,e,n){this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw new Error("invalid throttle");let i=r.get(e);if(i)return i.count++,!1;let a,o=()=>{let l=r.get(e),h=l?l.count:0;return r.delete(e),clearTimeout(a),l&&clearTimeout(l.timeoutObject),h};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(e,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=t;this.options.cwd&&!m.isAbsolute(t)&&(c=m.join(this.options.cwd,t));let l=new Date,h=this._pendingWrites;function u(d){(0,ve.stat)(c,(f,w)=>{if(f||!h.has(t)){f&&f.code!=="ENOENT"&&r(f);return}let R=Number(new Date);d&&w.size!==d.size&&(h.get(t).lastChange=R);let z=h.get(t);R-z.lastChange>=e?(h.delete(t),r(void 0,w)):o=setTimeout(u,a,w)})}h.has(t)||(h.set(t,{lastChange:l,cancelWait:()=>(h.delete(t),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(t,e){if(this.options.atomic&&us.test(t))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Pe(n)),o=[...[...this._ignoredPaths].map(Pe(n)),...i];this._userIgnored=ps(o,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new at(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=m.resolve(t);return this._watched.has(e)||this._watched.set(e,new Yt(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,e,n){let r=m.join(t,e),i=m.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!n&&this._watched.size===1&&this.add(t,e,!0),this._getWatchedDir(r).getChildren().forEach(d=>this._remove(r,d));let c=this._getWatchedDir(t),l=c.has(e);c.remove(e),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let h=r;if(this.options.cwd&&(h=m.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(h)&&this._pendingWrites.get(h).cancelWait()===y.ADD)return;this._watched.delete(r),this._watched.delete(i);let u=n?y.UNLINK_DIR:y.UNLINK;l&&!this._isIgnored(r)&&this._emit(u,r),this._closePath(r)}_closePath(t){this._closeFile(t);let e=m.dirname(t);this._getWatchedDir(e).remove(m.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(n=>n()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let n=this._closers.get(t);n||(n=[],this._closers.set(t,n)),n.push(e)}_readdirp(t,e){if(this.closed)return;let n={type:y.ALL,alwaysStat:!0,lstat:!0,...e,depth:0},r=he(t,n);return this._streams.add(r),r.once(me,()=>{r=void 0}),r.once(zt,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};Es={watch:Ae,FSWatcher:B}});var Ss={};qt(Ss,{JSFilebasedRouter:()=>Le,JSRouter:()=>X,createEffect:()=>Tt,createSignal:()=>xt,html:()=>Bt,loadPyFiles:()=>It,mapper:()=>Vt,renderChildRoutes:()=>At,useInitialDOM:()=>_t,useJSAnchorSingle:()=>St,useJSAuth:()=>bt,useJSCollection:()=>vt,useJSComponent:()=>Y,useJSElementEach:()=>Z,useJSElements:()=>yt,useJSEvent:()=>dt,useJSEventAll:()=>pt,useJSExtractParams:()=>mt,useJSLazy:()=>Ot,useJSMetaData:()=>Pt,useJSNavigate:()=>Dt,useJSNoReload:()=>kt,useJSOutlet:()=>Rt,useJSParams:()=>U,useJSPurifier:()=>ut,useJSSSRHydration:()=>Ft,useJSSelect:()=>W,useJSloadBrython:()=>Lt});module.exports=Me(Ss);function Je(s){let t=s==null?"":String(s),e=t.toLowerCase();return(e.includes("<script")||e.includes("javascript:"))&&(t=""),t=t.replace(/url\(\s*(['"])?\s*\1?\s*\)/gi,""),t.replace(/<\s*(script|iframe|object|embed|link|style|meta|body)[^>]*>.*?<\s*\/\s*\1\s*>/gi,"").replace(/<\s*(script|iframe|object|embed|link|style|meta)[^>]*>/gi,"").replace(/\s+on\w+\s*=\s*(['"]).*?\1/gi,"").replace(/\s+on\w+\s*=\s*[^\s>]+/gi,"").replace(/\s(href|src)\s*=\s*(['"]?)\s*(javascript:|vbscript:|data:|file:)[^'">\s]*\2/gi,'$1="#"')}function Bt(s,...t){return s.reduce((e,n,r)=>{let i=r<t.length?Je(t[r]):"";return e+n+i},"")}var je=s=>s.replace(/<\/?(script|iframe|object|embed|link|meta|style|form|textarea|svg|math|body)[^>]*>/gi,"").replace(/<(?!\/?(b|i|em|strong|p|br|ul|ol|li|a|div|span|h1|h2|h3|h4|h5|h6|section|article|input|button)\b)[^>]*>/gi,"").replace(/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi,"").replace(/\s*style\s*=\s*("[^"]*"|'[^']*')/gi,"").replace(/<a\b([^>]*)href\s*=\s*(['"]?)(?!https?:|#)[^'"\s>]+(['"]?)([^>]*)>/gi,"<a$1$4>").replace(/\s+(href|src)\s*=\s*(['"]?)\s*(javascript:|data:)[^'"\s>]*/gi,"").replace(/<a\b([^>]*)\bhref\s*=\s*(['"])(\/blog|#blog)\2([^>]*)>/gi,'<a$1 href=$2$3$2 href-line="true"$4>').trim(),Vt=s=>s?.map(t=>je(t)).join("")??"";var ht=x(require("dompurify"),1),ut=(s,t)=>{let n={...{ADD_TAGS:["my-custom-tag"]},...t};return typeof s=="string"?ht.default.sanitize(s,n):ht.default.sanitize(s.innerHTML,n)};var dt=(s,t,e)=>{if(typeof s=="string"){let n=document.getElementById(s);n?n.addEventListener(t,e):console.warn(`Element with id '${s}' not found.`)}else s===document?document.addEventListener(t,e):console.warn("Invalid id parameter provided.")};var Kt=require("zustand/vanilla"),ft=x(require("dompurify"),1);function $e(s,t){let e=[],n=s.replace(/:[^/]+/g,o=>(e.push(o.slice(1)),"([^/]+)")),r=new RegExp(`^${n}$`),i=t.match(r),a={};return i&&e.forEach((o,c)=>{a[o]=ft.default.sanitize(i[c+1]??"")}),a}function ze(s){let t={},e=new URLSearchParams(s);for(let[n,r]of e.entries())t[n]=ft.default.sanitize(r);return t}var U=(0,Kt.createStore)((s,t)=>({params:{},query:{},setFromPattern:e=>{let n=window.location.pathname,r=$e(e,n),i=ze(window.location.search);s({params:r,query:i})},getParam:e=>t().params[e],getQuery:e=>t().query[e]}));function mt(s){let t=U.getState();t.setFromPattern(s);let e=t.params,n=t.query;return{...e,...n}}var pt=(s,t,e)=>{let n=document.querySelectorAll(s);return n.forEach(r=>{r.addEventListener(t,e)}),()=>{n.forEach(r=>{r.removeEventListener(t,e)})}};var wt=x(require("dompurify"),1),yt=(s,t,e={},n)=>{let r={USE_PROFILES:{svg:!0,html:!0},ALLOWED_TAGS:["svg","path","circle","rect","line","polyline","polygon","g","main","div","h1","h2","h3","h4","h5","h6","p","button","span","a","img","input","ul","li","i","label","form"],ALLOWED_ATTR:["class","id","href","src","alt","title","fill","stroke","stroke-width","viewBox","xmlns","d","x","y","cx","cy","r","width","height","type","name","value","placeholder","data-click","data-change","data-select","data-classlist","data-hover","data-submit","data-key","data-event"],FORBID_TAGS:["script","iframe","foreignObject","body","html"],FORBID_ATTR:["style","xlink:href"],ALLOWED_URI_REGEXP:/^(?:(?:https?|mailto|tel|ftp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,...n};wt.default.addHook("uponSanitizeAttribute",(o,c)=>{let l=(c.attrName||"").toLowerCase(),h=(c.attrValue??"").toString().trim();if(l.startsWith("on")){c.keepAttr=!1;return}if(/^data-(click|change|submit|select|hover|classlist|key|event)$/.test(l)){c.keepAttr=!0;return}if(o.nodeName.toLowerCase()==="img"&&l==="src"){/^https?:\/\//i.test(h)||/^\/(?!\/)/.test(h)||/^data:image\/(png|jpeg|jpg|gif|webp);base64,/i.test(h)||(c.keepAttr=!1);return}if(l==="class"){let d=h.split(/\s+/).filter(Boolean).filter(f=>{if(/^[a-zA-Z0-9\-\:\/_\[\]\(\)]*$/.test(f)){if(/^bg-\[url\(.*\)\]$/.test(f)){let w=f.replace(/^bg-\[url\(/,"").replace(/\)\]$/,"").replace(/^['"]|['"]$/g,"");return w===""||/^https?:\/\//i.test(w)||/^\/(?!\/)/.test(w)||/^\.{0,2}\//.test(w)}return/^bg-\[\]$/.test(f),!0}return!1});c.attrValue=d.join(" ");return}});let i=wt.default.sanitize(t,{...r,RETURN_DOM_FRAGMENT:!0});for(;s.firstChild;)s.removeChild(s.firstChild);s.appendChild(i);let a=(o,c)=>{s.querySelectorAll(`[${o}]`).forEach(l=>{let h=l.getAttribute(o);h&&Object.prototype.hasOwnProperty.call(e,h)&&l.addEventListener(c,u=>{c==="submit"&&u.preventDefault(),e[h](u)})})};a("data-click","click"),a("data-change","change"),a("data-select","select"),a("data-submit","submit"),s.querySelectorAll("[data-key]").forEach(o=>{let c=o.dataset.key,l=o.dataset.event??"click";c&&Object.prototype.hasOwnProperty.call(e,c)&&o.addEventListener(l,e[c])}),s.querySelectorAll("[data-hover]").forEach(o=>{let c=o.dataset.hover;c&&Object.prototype.hasOwnProperty.call(e,c)&&(o.addEventListener("mouseenter",e[c]),o.addEventListener("mouseleave",e[c]))}),s.querySelectorAll("[data-classlist]").forEach(o=>{let c=o.dataset.classlist;/^[a-zA-Z0-9\-\s:_]+$/.test(c)&&o.classList.add(...c.split(/\s+/))})};var gt=x(require("dompurify"),1),Q=null,_t=(s,t)=>{if(typeof document>"u")return;let e=document.getElementById(s);if(!e)return;gt.default.addHook("uponSanitizeAttribute",(a,o)=>{let c=(o.attrName||"").toLowerCase(),l=(o.attrValue??"").toString().trim();if(c.startsWith("on")){o.keepAttr=!1;return}if((c==="href"||c==="src")&&/^(javascript:|vbscript:|data:|file:|about:)/i.test(l)){o.keepAttr=!1;return}if(c==="class"){let u=l.split(/\s+/).filter(Boolean).filter(d=>{if(/^[a-zA-Z0-9\-\:\/_\[\]\(\)]+$/.test(d)){if(/^bg-\[url\(.*\)\]$/.test(d)){let f=d.replace(/^bg-\[url\(/,"").replace(/\)\]$/,"").replace(/^['"]|['"]$/g,"");return f===""||/^https?:\/\//i.test(f)||/^\/(?!\/)/.test(f)||/^\.{0,2}\//.test(f)}return!0}return!1});o.attrValue=u.join(" ");return}if(c==="style"){o.keepAttr=!1;return}});let n=e.cloneNode(!0),r=gt.default.sanitize(n.innerHTML,{USE_PROFILES:{html:!0},ALLOWED_TAGS:["div","span","p","h1","h2","h3","h4","h5","h6","ul","ol","li","strong","em","a","img","br","form","button","input","label"],ALLOWED_ATTR:["href","src","alt","title","class","id","type","name","value","placeholder","data-click","data-change","data-submit","data-select","data-hover","data-classlist"],FORBID_TAGS:["script","iframe","object","embed","body","html","svg","math","link","meta"],ALLOW_DATA_ATTR:!0,KEEP_CONTENT:!1,RETURN_DOM_FRAGMENT:!0}),i=Array.from(r.childNodes).map(a=>a.outerHTML||a.textContent||"").join("");if(Q!==null&&i!==Q){let a=document.createElement("div");t(a);let c=new DOMParser().parseFromString(Q,"text/html");for(;e.firstChild;)e.removeChild(e.firstChild);c.body.childNodes.forEach(l=>e.appendChild(l.cloneNode(!0)))}else{for(Q=i;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(r),t(e)}};var Et=x(require("dompurify"),1);typeof window<"u"&&!window.__anchorSinglePopstateHandlerAttached&&(window.addEventListener("popstate",s=>{let t=s.state;t?.scrollPosition!==void 0&&window.scrollTo(0,t.scrollPosition)}),window.__anchorSinglePopstateHandlerAttached=!0);var St=(s,t,e,n="",r=null)=>{if(!s)return;let i=Et.default.sanitize(t,{ALLOWED_URI_REGEXP:/^(https?:|\/)/}),a=Et.default.sanitize(e,{USE_PROFILES:{html:!1}});s.setAttribute("href",i),s.setAttribute("aria-label",a),n&&(s.className=n.trim()),r&&s.replaceChildren(r),typeof window<"u"&&s.addEventListener("click",o=>{o.preventDefault();let l=o.currentTarget.getAttribute("href");if(l){let h=window.scrollY;window.scrollTo(0,0),window.history.pushState({scrollPosition:h},"",l),dispatchEvent(new PopStateEvent("popstate"))}})};var N=x(require("dompurify"),1);var Pt=(s,t)=>{let e={name:N.default.sanitize(s.name||""),title:N.default.sanitize(s.title||""),description:N.default.sanitize(s.description||"Default description"),author:N.default.sanitize(s.author||""),favicon:s.favicon},n=P=>{e.name=N.default.sanitize(P),R("name",e.name)},r=P=>{e.title=N.default.sanitize(P),document.title=e.title},i=P=>{e.description=N.default.sanitize(P),R("description",e.description)},a=P=>{e.author=N.default.sanitize(P),R("author",e.author)},o=P=>{e.favicon=N.default.sanitize(P);let A=document.querySelector('link[rel="icon"]');A||(A=document.createElement("link"),A.rel="icon",document.head.appendChild(A)),A.href=e.favicon},c=()=>e.name,l=()=>e.title,h=()=>e.description,u=()=>e.author,d=()=>e.favicon,f=()=>e,w=(P,A)=>{let I=document.createElement("meta");I.setAttribute("name",P),I.setAttribute("content",A),document.head.appendChild(I)},R=(P,A)=>{let I=document.querySelector(`meta[name="${P}"]`);I?I.setAttribute("content",A):w(P,A)},z=()=>{e.title&&(document.title=e.title),e.name&&R("name",e.name),e.description&&R("description",e.description),e.author&&R("author",e.author),e.favicon&&o(e.favicon)};return t&&useTSCSP(t.scriptSrc,t.styleSrc,t.objectSrc,Array.isArray(t.connectSrc)?t.connectSrc.join(" "):t.connectSrc,t.reportOnly!==void 0?String(t.reportOnly):void 0),z(),{setName:n,setTitle:r,setDescription:i,setAuthor:a,setFavicon:o,getName:c,getTitle:l,getDescription:h,getAuthor:u,getFavicon:d,getAllMetaData:f,appendMetaTagsToHead:z}};var Qt=x(require("dompurify"),1),Y=(s,t,e,n,r)=>{let i=`#${s}`,a=t.querySelectorAll(i);if(a.length===0)throw new Error(`[useTSComponent] No element found with id '${s}' in the given parent.`);if(a.length>1)throw new Error(`[useTSComponent] Duplicate id '${s}' detected. Found ${a.length} elements.`);let o=a[0];o.innerHTML=Qt.default.sanitize(o.innerHTML,{USE_PROFILES:{html:!0}}),e(o,n,r)};var vt=(s,t,e,n=[])=>{let r=new Set;s.forEach((i,a)=>{if(r.has(i)){console.warn(`[useJSCollection] Duplicate ID in collection array: "${i}" \u2014 skipping.`);return}r.add(i);let o=t.querySelectorAll(`#${i}`);if(o.length>1){console.warn(`[useJSCollection] Duplicate ID in DOM: "${i}" (${o.length} elements found) \u2014 skipping component mount.`);return}let c=e[a],l=Array.isArray(n)?n[a]:void 0;typeof c=="function"?Y(i,t,c,l):console.warn(`[useJSCollection] No valid component function found for ID: "${i}"`)})};var W=(s,t)=>{let n=(t??document).querySelectorAll(s);if(n.length===0)return process.env.NODE_ENV!=="production"&&console.warn(`[useJSSelect] No element found for selector: '${s}'`),null;if(s.startsWith("#")&&n.length>1){if(process.env.NODE_ENV!=="production")throw new Error(`[useJSSelect] Duplicate ID detected: '${s}'. Found ${n.length} elements with this ID.`);return n[0]}return n.length>1&&process.env.NODE_ENV!=="production"&&console.warn(`[useJSSelect] Multiple elements found for selector: '${s}'. Returning the first one.`),n[0]};var Zt=require("jwt-decode"),bt=(s,t)=>{let e=localStorage.getItem("token");if(!e)return window.location.href=t,null;try{let n=(0,Zt.jwtDecode)(e),r=Date.now()/1e3;return n.exp&&n.exp<r&&(console.error("Token has expired"),window.localStorage.removeItem("token"),window.location.href=t),null}catch(n){return console.error("Invalid token:",n),window.location.href=t,null}};var Z=(s,t,e)=>{s.forEach(n=>{t.forEach(r=>{n.addEventListener(r,i=>{e(n,i)})})})};var Dt=()=>({back:()=>window.history.back(),forward:()=>window.history.forward()});var Rt=(s,t)=>{let e=document.querySelector(`#${s}`)||document.querySelector(`.${s}`);if(!e)return;let n=window.location.pathname.replace(/\/$/,"");for(let r of t){let i=r.path.replace(/\/$/,"");if(n===i||n.startsWith(`${i}/`)){r.component(e);break}}};function At(s,t){let e=window.location.pathname.replace(/\/$/,"");t.routes.forEach(n=>{n.children?.length&&n.children.forEach(r=>{let i=r.path.replace(/\/$/,"");if(e===i||e.startsWith(`${i}/`)){let a=s.querySelector(`#${r.outlet}`)||s.querySelector(`.${r.outlet}`);a instanceof HTMLElement&&r.element&&r.element(a)}})})}var Xt=require("zustand/vanilla");function xt(s){let t=Xt.createStore<{value:T}>(()=>({value:s})),e=new Set;return{get:()=>t.getState().value,set:n=>{t.setState({value:n}),e.forEach(r=>r(n))},subscribe:n=>(e.add(n),n(t.getState().value),()=>e.delete(n))}}function Tt(s){let t=s();typeof t=="function"&&t()}var Lt=async()=>{let s="https://cdn.jsdelivr.net/npm/brython@3/brython.min.js",t="https://cdn.jsdelivr.net/npm/brython@3/brython_stdlib.js",e=n=>new Promise((r,i)=>{let a=document.createElement("script");a.src=n,a.onload=()=>r(),a.onerror=()=>i(new Error(`Failed to load ${n}`)),document.head.appendChild(a)});await e(s),await e(t),typeof window.brython=="function"?window.brython():console.error("Brython did not load correctly.")},It=s=>new Promise((t,e)=>{let n=document.createElement("script");n.type="text/python",n.src=`/src/python/${s}`,n.onload=()=>t(),n.onerror=()=>e(new Error(`Failed to load ${s}`)),document.body.appendChild(n)});function Ot(s){let t=null;return async(e,n)=>{try{if(!t){let r=await s();t=r.default||r}if(typeof t=="function")return t(e,n);if(t instanceof HTMLElement){let r=t.cloneNode(!0);return e?.appendChild(r),r}if(typeof t=="object"&&t!==null&&"render"in t&&typeof t.render=="function")return t.render(e,n);console.warn("useTSLazy: Unsupported module type",t)}catch(r){console.error("useTSLazy failed:",r)}}}var Ft=s=>typeof window>"u"?{isDOM:null}:{isDOM:s||document.body};var te=require("lodash-es"),Nt=s=>s;typeof window<"u"&&typeof document<"u"&&(Nt=s=>{let t=document.createElement("div");return t.innerText=s,t.innerHTML});var We=s=>{(s?Array.isArray(s)?s:s instanceof HTMLAnchorElement?[s]:Array.from(s):Array.from(document.querySelectorAll("a"))).forEach(e=>{if(!e||e.dataset.anchorEnhanced==="true")return;e.dataset.anchorEnhanced="true";let n=e.getAttribute("class")||"";e.setAttribute("class",Nt(n));let r=e.getAttribute("aria-label");r&&e.setAttribute("aria-label",Nt(r));let i=e.querySelector(":scope > *");i&&(e.innerHTML="",e.appendChild(i));let a=e.getAttribute("href")||"";if(!a.startsWith("#")){try{if(new URL(a,window.location.href).origin!==window.location.origin)return}catch{return}e.addEventListener("click",o=>{o.preventDefault();let c=e.getAttribute("href")||"";try{let l=new URL(c,window.location.href);window.history.pushState({},"",l.pathname+l.search+l.hash),window.dispatchEvent(new PopStateEvent("popstate"))}catch(l){console.error("Invalid URL in anchor:",c,l)}})}})},He=(0,te.debounce)(We,50),ee=s=>{He(s)};var kt=s=>{if(!s)return;let t=W("a",s);ee(t)};var Ct=x(require("dompurify"),1);var re=require("zustand/vanilla"),ne=x(require("dompurify"),1),M=(0,re.createStore)(s=>({params:{},query:{},setParams:t=>s(()=>({params:se(t)})),setQuery:t=>s(()=>({query:se(t)}))}));function se(s){let t={};for(let e in s)t[e]=ne.default.sanitize(s[e]);return t}var X=class{constructor(t,e){this.routes=t||[],this.expectedParams=new Set(e||[]),window.addEventListener("popstate",this.handlePopState.bind(this)),this.handlePopState()}handlePopState(){let t=window.location.pathname,e=window.location.search,n=this.parseQueryParams(e),r=this.findMatchingRoute(t,this.routes);if(r){if(r.routeto){this.navigate(r.routeto);return}let i=this.filterAndSanitizeParams(r.params);M.getState().setParams(i),M.getState().setQuery(n);let a=document.createElement("div");if(r.element&&r.element(a,i,n),r.children){let o=t.slice(r.path.length),c=a.querySelector("#child");c&&this.renderChildren(r.children,o,c,i,n)}}else{let i=this.findMatchingRoute("*",this.routes);if(i){let a=this.filterAndSanitizeParams(i.params);M.getState().setParams(a),M.getState().setQuery(n);let o=document.createElement("div");i.element&&i.element(o,a,n)}}}renderChildren(t,e,n,r,i){if(!t||t.length===0){let o=n.querySelector("#child");o&&o.remove();return}let a=this.findMatchingRoute(e,t);if(a){let o=document.createElement("div");o.id="child";let c={...r,...a.params},l=this.filterAndSanitizeParams(c);if(M.getState().setParams(l),M.getState().setQuery(i),a.element&&a.element(o,l,i),n.appendChild(o),a.children){let h=e.slice(a.path.length);this.renderChildren(a.children,h,o,l,i)}}}parseQueryParams(t){let e={},n=new URLSearchParams(t);for(let[r,i]of n.entries())this.expectedParams.has(r)&&(e[r]=Ct.default.sanitize(i));return e}findMatchingRoute(t,e,n={}){for(let r of e){let i=r.path;if(i==="*")return r;{let o=[],c=i.replace(/:[^\s/]+/g,u=>(o.push(u.substring(1)),"([^\\s/]+)")),l=new RegExp(`^${c}(?:/|$)`),h=t.match(l);if(h){let u={...n};if(o.forEach((d,f)=>{u[d]=h[f+1]??""}),r.children){let d=t.slice(h[0].length),f=this.findMatchingRoute(d,r.children,u);if(f)return f}return{...r,params:u}}}}}filterAndSanitizeParams(t){if(!t)return{};let e={};for(let n in t)this.expectedParams.has(n)&&(e[n]=Ct.default.sanitize(t[n]??""));return e}navigate(t){history.pushState(null,"",t),this.handlePopState()}addRoute(t){this.routes.push(t)}};var Le=()=>({name:"js-filebased-router",async buildStart(){if(typeof process>"u"||!process.versions?.node)return;let s=await import("fs/promises"),t=await import("path"),e=await Promise.resolve().then(()=>(Te(),xe)),n=t.resolve("src/pages"),r=t.resolve("src/gen"),i=t.resolve("src/routes"),a=t.join(r,"jsrouter.gen.js"),o=t.join(i,"__root.js"),c=process.env.NODE_ENV!=="production";async function l(g){try{await s.mkdir(g,{recursive:!0})}catch{}}function h(g,_){let E="/"+t.relative(_,g).replace(/\\/g,"/");return E=E.replace(/\.js$/,"").replace(/\/index$/,"")||"/",E.replace(/\[(.+?)\]/g,":$1")}function u(g){return g.replace(/^\//,"").split("/").map(_=>_.startsWith(":")?_.slice(1):_).filter(Boolean).join("-")||"index"}function d(g,_){let v=t.relative(_,g).replace(/\\/g,"/").split("/").filter(Boolean),b=v[v.length-1].replace(".js",""),D=v.length>1?v[v.length-2]:"";if(b==="index")return D?D.charAt(0).toUpperCase()+D.slice(1):"Index";if(b.startsWith("[")&&b.endsWith("]")){let J=b.slice(1,-1);return D.charAt(0).toUpperCase()+J.charAt(0).toUpperCase()+J.slice(1)}return b.charAt(0).toUpperCase()+b.slice(1)}async function f(g){let _=await s.readdir(g,{withFileTypes:!0}),E=[];for(let v of _){let b=t.join(g,v.name);if(v.isDirectory())E=E.concat(await f(b));else if(v.isFile()&&v.name.endsWith(".js")){let D=h(b,n),J=u(D),S=d(b,n);E.push({file:b,route:D,routeName:J,importName:S})}}return E}function w(){return`import { useInitialDOM } from "@devwareng/vanilla-js";
import App from "./App";
useInitialDOM("app", App)`}function R(){return`import App from './App'
export function render(_url) {
  const html = App()
  return { html }
}`}function z(){return`import { html, useJSComponent, useJSElements, useJSNoReload, useJSSSRHydration } from '@devwareng/vanilla-js'
import { Router } from './routes/__root';
import "tailwindcss/index.css"
export default function App(DOM) {
  const { isDOM } = useJSSSRHydration(DOM)
  if (!isDOM) return
  const ui = useJSElements(
    isDOM,
    html\`
      <div class="min-h-screen text-white bg-black">
        <div id="routes"></div>
      </div>
    \`
  )
  useJSNoReload(isDOM)
  useJSComponent("routes", isDOM, Router)
  return ui
}`}function P(g,_){let E=_.includes(":"),v=E?_.match(/:([^/]+)/)?.[1]:null;return`import { html, useJSElements, useJSMetaData${E?", useJSExtractParams":""} } from '@devwareng/vanilla-js';
export default function ${g}(DOM) {
   ''
  useJSMetaData({ 
      name: '${g.toLowerCase()}', 
      description: '', 
      author: '' 
  });
  ${E?`const params = useJSExtractParams("${_}");
  if (!params.${v}) return;`:""}
  const ui = useJSElements(
    DOM,
    html\`
      <div class="p-4 animate__animated animate__fadeIn duration-300">
        <h1>${g}</h1>
        ${E?"<pre>${JSON.stringify(params, null, 2)}</pre>":""}
      </div>
    \`
  );
  return ui
}`}function A(){return`import { createRouter } from "@/gen/jsrouter.gen";
import { useJSParams } from "@devwareng/vanilla-js";
// This file is auto-generated
export const Router = (DOM) => {
  useJSParams.getState();
  const router = createRouter(DOM);
  router.navigate(window.location.pathname);
  window.addEventListener("popstate", () => {
    router.navigate(window.location.pathname);
  });
};`}async function I(){let g=await f(n),_=g.find(S=>S.route==="/notfound"),E=g.filter(S=>S.route!=="/notfound");for(let S of g)(await s.readFile(S.file,"utf-8")).trim()||await s.writeFile(S.file,P(S.importName,S.route),"utf-8");let v=g.map(S=>{let V="../pages/"+t.relative(n,S.file).replace(/\\/g,"/").replace(/\.js$/,"");return`import ${S.importName} from "${V}";`}).join(`
`),b=E.map(S=>`{ path: "${S.route}", name: "${S.routeName}", component: (DOM) => ${S.importName}(DOM) }`).join(`,
  `),D=_?`export const NotFound = ${_.importName}`:'export function NotFound(DOM) {\n  return useJSElements(DOM, html`<div class="animate__animated animate__fadeIn duration-300 p-4"><h1>404 - Page Not Found</h1></div>`)\n}',J=`// AUTO-GENERATED FILE. DO NOT EDIT MANUALLY.
import { html, useJSElements } from "@devwareng/vanilla-js"
${v}
${D}
export function RootDocument(DOM) {
  return useJSElements(DOM, html\`<div><h1>Root</h1></div>\`)
}
export const routeTree = [
  ${b}
]
export function createRouter(DOM) {
  function matchRoute(path) {
    for (const route of routeTree) {
      const keys = []
      const regex = new RegExp("^" + route.path.replace(/:([^/]+)/g, (_, key) => {
        keys.push(key)
        return "([^/]+)"
      }) + "$")
      const pathname = path.split("?")[0]
      const match = pathname?.match(regex)
      if (match) {
        const params = {}
        keys.forEach((key, i) => (params[key] = match[i + 1] || ""))
        return { ...route, params }
      }
    }
    return null
  }
  function navigate(path) {
    const match = matchRoute(path)
    if (match) { match.component(DOM); history.pushState({}, "", path) }
    else { NotFound(DOM) }
  }
  window.addEventListener("popstate", () => {
    const path = window.location.pathname + window.location.search
    const match = matchRoute(path)
    if (match) { match.component(DOM) }
    else { NotFound(DOM) }
  })
  navigate(window.location.pathname + window.location.search)
  return { navigate, routes: routeTree }
}
`;await l(r),await s.writeFile(a,J,"utf-8"),await s.writeFile(o,A(),"utf-8")}if(await l(r),await l(i),await l(n),await I(),c){e.watch(n).on("all",async(b,D)=>{if(D.endsWith(".js"))if(b==="add"){let S=t.basename(D,".js").replace(/\[|\]/g,"Param").replace(/(^\w|-\w)/g,Ie=>Ie.replace("-","").toUpperCase()),V=h(D,n);(await s.readFile(D,"utf-8")).trim()||await s.writeFile(D,P(S,V),"utf-8"),await I()}else b==="unlink"?(console.log(`\u26A0\uFE0F File removed: ${D}`),await I()):b==="change"&&await I()});let _=t.resolve("src/entry-client.js"),E=t.resolve("src/entry-server.js");try{await s.access(_)}catch{await s.writeFile(_,w(),"utf-8"),console.log("\u{1F7E2} Created default src/entry-client.js")}try{await s.access(E)}catch{await s.writeFile(E,R(),"utf-8"),console.log("\u{1F7E2} Created default src/entry-server.js")}let v=t.resolve("src/App.js");try{await s.access(v)}catch{await s.writeFile(v,z(),"utf-8"),console.log("\u{1F7E2} Created default src/App.js")}e.watch(o).on("unlink",async()=>{console.log("\u26A0\uFE0F Root file removed: regenerating..."),await s.writeFile(o,A(),"utf-8")})}console.log("\u{1F7E2} JS Filebased Router Generated Successfully...")}});0&&(module.exports={JSFilebasedRouter,JSRouter,createEffect,createSignal,html,loadPyFiles,mapper,renderChildRoutes,useInitialDOM,useJSAnchorSingle,useJSAuth,useJSCollection,useJSComponent,useJSElementEach,useJSElements,useJSEvent,useJSEventAll,useJSExtractParams,useJSLazy,useJSMetaData,useJSNavigate,useJSNoReload,useJSOutlet,useJSParams,useJSPurifier,useJSSSRHydration,useJSSelect,useJSloadBrython});
/*! Bundled license information:
chokidar/esm/index.js:
  (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
*/