@donotdev/core 0.0.31 → 0.0.33
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/functions/index.js +14 -78
- package/next/index.js +87 -108
- package/package.json +1 -1
- package/vite/index.js +159 -180
package/vite/index.js
CHANGED
|
@@ -1,55 +1,54 @@
|
|
|
1
|
-
var po=Object.create;var ar=Object.defineProperty;var go=Object.getOwnPropertyDescriptor;var mo=Object.getOwnPropertyNames;var bo=Object.getPrototypeOf,vo=Object.prototype.hasOwnProperty;var J=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var lr=(e,t)=>()=>(e&&(t=e(e=0)),t);var D=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),yo=(e,t)=>{for(var r in t)ar(e,r,{get:t[r],enumerable:!0})},wo=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of mo(t))!vo.call(e,n)&&n!==r&&ar(e,n,{get:()=>t[n],enumerable:!(s=go(t,n))||s.enumerable});return e};var Eo=(e,t,r)=>(r=e!=null?po(bo(e)):{},wo(t||!e||!e.__esModule?ar(r,"default",{value:e,enumerable:!0}):r,e));function rs(e,t=null){let r=we[e];if(!r)throw new Error(`Unknown pattern type: ${e}`);return t&&r.framework?{...r,framework:r.framework.map(s=>`${t}/${s}`)}:r}function Tt(e){return es[e]||es.base}var ur,H,oe,Z,fr,yt,Dt,we,Ze,ts,hr,dr,wt,pr,es,ee=lr(()=>{"use strict";ur={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},H={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env"},oe={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},Z={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},fr={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},yt={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Dt={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},we={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${Dt.SOURCE_EAGER}/*_*.json`],lazy:[`${Dt.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},Ze={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async","@donotdev/core","@donotdev/components","@donotdev/ui","@donotdev/templates","@donotdev/firebase"],optionalFeatures:["@donotdev/components","@donotdev/auth","@donotdev/billing","@donotdev/crud","@donotdev/oauth","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder"],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},ts=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"],hr=["@donotdev/core/functions","@donotdev/core/server"],dr={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}},wt={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},pr=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],es={base:{absolute:!0,onlyFiles:!0,ignore:we.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...we.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...we.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:we.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:we.globalIgnore}}});import*as T from"node:fs";import"node:fs";import{createRequire as Ao}from"node:module";import{resolve as Ft,join as Le,dirname as qe,relative as ss,normalize as _o,sep as ns,extname as No}from"node:path";import{fileURLToPath as Io}from"node:url";import Do from"fast-glob";function is(e,t){return e().catch(r=>{throw new Error(`${t}: ${r instanceof Error?r.message:String(r)}`)})}var it,te,os,U,ge=lr(()=>{"use strict";ee();it={getGlobOptionsFor:Tt||void 0,SCAN_PATTERNS:we||void 0,getPatternsFor:rs||void 0,I18N_PATHS:Dt||void 0},te={error:(e,t)=>{},warn:(e,t)=>{},info:e=>{}};os={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},U=class e{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(t={}){return e._instance||(e._instance=new e(t)),e._instance}static _reset(){e._instance=null}constructor(t={}){if(e._instance)return e._instance;this.options={maxLevels:t.maxLevels??10,customMarkers:t.customMarkers||[],cache:t.cache??!1,debug:t.debug??!1};try{let r=process.cwd();if(!r)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(r)}catch(r){throw new Error(`PathResolver constructor failed: ${r instanceof Error?r.message:String(r)}. cwd: ${process.cwd()}`)}this._appRoot=null,e._instance=this}normalizePath(t){if(!t)return"";try{return _o(t).split(ns).join("/")}catch{return String(t).split(ns).join("/")}}getRelativePath(t){let r=this.getAppRoot(),s=ss(r,t);return this.normalizePath(s)}getBasename(t){if(!t)return"";let s=this.normalizePath(t).split("/");return s[s.length-1]||""}getDirname(t){return t?this.normalizePath(qe(t)):""}resolvePackage(t,r=null){try{let s=r||this.getAppRoot(),i=Ao(Le(s,"package.json")).resolve(t);return this.normalizePath(i)}catch{return null}}resolveFrameworkPackage(t,r=null){let s=this.resolvePackage(`${t}/package.json`,r);if(s)return this.getDirname(s);if(this.isMonorepo()&&t.startsWith("@donotdev/")){let o=t.replace("@donotdev/",""),a=this.resolveRepoPath(`packages/${o}`);if(this.pathExists(a))return a;if(["auth","billing","crud","oauth"].includes(o)){let l=this.resolveRepoPath(`packages/features/${o}`);if(this.pathExists(l))return l}if(o==="firebase"){let l=this.resolveRepoPath(`packages/providers/${o}`);if(this.pathExists(l))return l}}let n=this.resolveAppPath(`node_modules/${t}`);if(this.pathExists(n))return n;let i=this.resolveRepoPath(`node_modules/${t}`);return this.pathExists(i)?i:null}resolvePackageAsset(t,r=null){return this.resolvePackage(t,r)}resolveAppPath(t){let r=this.getAppRoot(),s=Ft(r,t);return this.normalizePath(s)}resolveRepoPath(t){let r=this.getRepoRoot(),s=this.normalizePath(t),n=Ft(r,s);return this.normalizePath(n)}resolvePath(t,r){let s=this.normalizePath(r),n=this.normalizePath(t),i=Ft(s,n);return this.normalizePath(i)}createImportPath(t){return"./"+this.getRelativePath(t)}getFileInfo(t){try{let r=T.statSync(t);return{absolutePath:this.normalizePath(t),relativePath:this.getRelativePath(t),importPath:this.createImportPath(t),size:r.size,isFile:r.isFile(),isDirectory:r.isDirectory()}}catch{return null}}_detectFormat(t,r){return r&&r!=="auto"?r:No(t).toLowerCase()===".json"?"json":"text"}async read(t,r={}){let{format:s="auto",encoding:n="utf8"}=r,i=this._detectFormat(t,s);try{if(i==="buffer")return await T.promises.readFile(t);let o=await T.promises.readFile(t,n),a=this.stripBom(o);return i==="json"?JSON.parse(a):a}catch(o){return this.options.debug&&te.warn(`Failed to read file: ${t}`,o),null}}readSync(t,r={}){let{format:s="auto",encoding:n="utf8"}=r,i=this._detectFormat(t,s);try{if(i==="buffer")return T.readFileSync(t);let o=T.readFileSync(t,n),a=this.stripBom(o);return i==="json"?JSON.parse(a):a}catch(o){return this.options.debug&&te.warn(`Failed to read file: ${t}`,o),null}}async write(t,r,s={}){let{format:n="auto",overwrite:i=!1,dryRun:o=!1,verbose:a=!1}=s,l=this.normalizePath(t),u=this.normalizePath(qe(l)),f=this.pathExists(l);if(f&&!i)return a&&te.info(`Skipping existing file: ${l}`),!1;if(o)return te.info(`[DRY RUN] Would write file: ${l}`),!0;try{await T.promises.mkdir(u,{recursive:!0})}catch(m){if(m?.code!=="EEXIST")throw m}let d=this._detectFormat(t,n),g;Buffer.isBuffer(r)?g=r:d==="json"&&typeof r=="object"?g=JSON.stringify(r,null,2):g=String(r);try{return await is(async()=>(Buffer.isBuffer(g)?await T.promises.writeFile(l,g):await T.promises.writeFile(l,g,"utf8"),a&&te.info(`${f?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(t,r,s={}){let{format:n="auto",overwrite:i=!1,dryRun:o=!1,verbose:a=!1}=s,l=this.normalizePath(t),u=this.normalizePath(qe(l)),f=this.pathExists(l);if(f&&!i)return a&&te.info(`Skipping existing file: ${l}`),!1;if(o)return te.info(`[DRY RUN] Would write file: ${l}`),!0;try{T.mkdirSync(u,{recursive:!0})}catch(m){if(m?.code!=="EEXIST")throw m}let d=this._detectFormat(t,n),g;Buffer.isBuffer(r)?g=r:d==="json"&&typeof r=="object"?g=JSON.stringify(r,null,2):g=String(r);try{return Buffer.isBuffer(g)?T.writeFileSync(l,g):T.writeFileSync(l,g,"utf8"),a&&te.info(`${f?"Updated":"Created"} file: ${l}`),!0}catch(m){throw new Error(`Failed to write file: ${l}: ${m instanceof Error?m.message:String(m)}`)}}async copy(t,r,s={}){let{overwrite:n=!1,dryRun:i=!1,verbose:o=!1}=s,a=this.normalizePath(r),l=this.pathExists(a);if(l&&!n)return o&&te.info(`Skipping existing file: ${a}`),!1;if(i)return te.info(`[DRY RUN] Would copy file: ${a}`),!0;let u=this.normalizePath(qe(a));try{await T.promises.mkdir(u,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}try{return await is(async()=>(await T.promises.copyFile(t,a),o&&te.info(`${l?"Updated":"Created"} file: ${a}`),!0),`Failed to copy file from ${t} to ${a}`)}catch{return!1}}copySync(t,r,s={}){let{overwrite:n=!1,dryRun:i=!1,verbose:o=!1}=s,a=this.normalizePath(r),l=this.pathExists(a);if(l&&!n)return o&&te.info(`Skipping existing file: ${a}`),!1;if(i)return te.info(`[DRY RUN] Would copy file: ${a}`),!0;let u=this.normalizePath(qe(a));try{T.mkdirSync(u,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}try{return T.copyFileSync(t,a),o&&te.info(`${l?"Updated":"Created"} file: ${a}`),!0}catch{return!1}}pathExists(t,r=!1){try{return T.existsSync(t)}catch(s){return r||te.error(`Error checking path existence: ${t}`,s),!1}}mkdir(t){try{let r=t.startsWith("/")||t.match(/^[A-Z]:/)?this.normalizePath(t):this.resolveAppPath(t);return T.existsSync(r)||T.mkdirSync(r,{recursive:!0}),!0}catch{return!1}}readdirSync(t,r){try{return T.readdirSync(t,r)}catch(s){return this.options.debug&&te.warn(`Failed to read directory: ${t}`,s),r&&typeof r=="object"&&"withFileTypes"in r&&r.withFileTypes?[]:[]}}statSync(t){try{return T.statSync(t)}catch(r){return this.options.debug&&te.warn(`Failed to stat file: ${t}`,r),null}}lstatSync(t){try{return T.lstatSync(t)}catch(r){return this.options.debug&&te.warn(`Failed to lstat file: ${t}`,r),null}}async ensureDir(t){try{await T.promises.mkdir(t,{recursive:!0})}catch(r){if(r?.code!=="EEXIST")throw r}}ensureDirSync(t){try{T.mkdirSync(t,{recursive:!0})}catch(r){if(r?.code!=="EEXIST")throw r}}async remove(t){await T.promises.rm(t,{recursive:!0,force:!0})}removeSync(t){T.rmSync(t,{recursive:!0,force:!0})}async readdir(t,r){return T.promises.readdir(t,r)}stripBom(t){return t.charCodeAt(0)===65279?t.slice(1):t}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(t){if(!t)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(t)}isMonorepo(){let t=Le(this._repoRoot,"packages");return this.pathExists(t)}isWithinApp(t){let r=this.normalizePath(Ft(t)),s=this.getAppRoot(),n=ss(s,r),i=this.normalizePath(n);return!i.startsWith("../")&&!i.startsWith("/")}async findFiles(t,r,s={}){let n=this.normalizePath(Le(t,r)),i=this.getAppRoot(),o=this.normalizePath(i),a=n.startsWith(o)?n.slice(o.length+1):n,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:i,ignore:it.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([a],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(t){let r=it.I18N_PATHS;if(!r)return null;let s=t.replace(r.SOURCE_ROOT+"/",""),n=this.resolveFrameworkPackage("@donotdev/core");if(!n)return null;let i=this.normalizePath(Le(n,r.PUBLISHED_ROOT,s)),o=i.replace(/\/[^/]*\*.*$/,"");return this.pathExists(o),i}async _globWithNormalization(t,r){return(await Do(t,r)).map(n=>{let i=typeof n=="string"?n:n.path;return this.normalizePath(i)})}async resolveFiles(t,r="css"){if(!t||typeof t!="object")return{frameworkFiles:[],consumerFiles:[]};if(r==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(t.framework)||(t.framework=[]),!Array.isArray(t.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...t.framework,...t.consumer];for(let f of s)if(typeof f!="string"||f.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let n=this.getAppRoot(),i=it.getGlobOptionsFor?it.getGlobOptionsFor(r):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},o=this.normalizePath(n),a=t.framework.map(f=>{let d=this.normalizePath(f);return d.startsWith(o)?d.slice(o.length+1):d}),l=t.consumer.map(f=>{let d=this.normalizePath(f);return d.startsWith(o)?d.slice(o.length+1):d}),u={...i,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n};try{let f=a.length>0?await this._globWithNormalization(a,u):[],d=await this._globWithNormalization(l,u);return{frameworkFiles:f,consumerFiles:d}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(t){if(!it.getPatternsFor)return{framework:[],consumer:[],all:[]};let r=this.getAppRoot(),s=this.getRepoRoot();if(t==="i18n"&&(!r||r===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${r}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let n=it.getPatternsFor(t),i=this.isMonorepo();if(t==="i18n"){let l=n,u={eager:l.eager.map(f=>f.startsWith("!")?"!"+this.resolveAppPath(f.slice(1)):this.resolveAppPath(f)),lazy:l.lazy.map(f=>f.startsWith("!")?"!"+this.resolveAppPath(f.slice(1)):this.resolveAppPath(f)),framework:{eager:i?(l.framework?.eager||[]).map(f=>this.resolveRepoPath(f)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(f=>this._resolveFrameworkI18nPattern(f))).then(f=>f.filter(Boolean)),lazy:i?(l.framework?.lazy||[]).map(f=>this.resolveRepoPath(f)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(f=>this._resolveFrameworkI18nPattern(f))).then(f=>f.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let o=n,a={framework:i?(o.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(o.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return a.all=[...a.consumer,...a.framework],a}getEmptyModulePath(t=!1){if(t)return"@donotdev/core/empty";let r=this.resolvePackage("@donotdev/core/empty");if(r)return r;let s=qe(Io(import.meta.url));return this.normalizePath(Le(s,"../empty.js"))}_findRepoRoot(t){let r=this.normalizePath(t),s=0,n=this.options.maxLevels;for(;s<n;){let i=this.normalizePath(Le(r,os.TOOLING)),o=this.normalizePath(Le(r,os.CORE));if(this.pathExists(i)&&this.pathExists(o))return r;let a=Le(r,"apps");if(this.pathExists(a)&&this.statSync(a)?.isDirectory())return this.normalizePath(r);let l=this.normalizePath(Le(r,"package.json"));if(this.pathExists(l)&&this.normalizePath(qe(r))===r)return r;let u=this.normalizePath(qe(r));if(u===r)break;r=u,s++}return this.normalizePath(t)}}});var Ne=D((Lh,ms)=>{var gs=e=>typeof e<"u"&&e!==null,Go=e=>typeof e=="object",qo=e=>Object.prototype.toString.call(e)==="[object Object]",Wo=e=>typeof e=="function",Ho=e=>typeof e=="boolean",Vo=e=>e instanceof Buffer,Jo=e=>{if(gs(e))switch(e.constructor){case Uint8Array:case Uint8ClampedArray:case Int8Array:case Uint16Array:case Int16Array:case Uint32Array:case Int32Array:case Float32Array:case Float64Array:return!0}return!1},Xo=e=>e instanceof ArrayBuffer,Yo=e=>typeof e=="string"&&e.length>0,Ko=e=>typeof e=="number"&&!Number.isNaN(e),Qo=e=>Number.isInteger(e),Zo=(e,t,r)=>e>=t&&e<=r,ea=(e,t)=>t.includes(e),ta=(e,t,r)=>new Error(`Expected ${t} for ${e} but received ${r} of type ${typeof r}`),ra=(e,t)=>(t.message=e.message,t);ms.exports={defined:gs,object:Go,plainObject:qo,fn:Wo,bool:Ho,buffer:Vo,typedArray:Jo,arrayBuffer:Xo,string:Yo,number:Ko,integer:Qo,inRange:Zo,inArray:ea,invalidParameterError:ta,nativeError:ra}});var ys=D((Mh,vs)=>{"use strict";var bs=()=>process.platform==="linux",Ot=null,sa=()=>{if(!Ot)if(bs()&&process.report){let e=process.report.excludeNetwork;process.report.excludeNetwork=!0,Ot=process.report.getReport(),process.report.excludeNetwork=e}else Ot={};return Ot};vs.exports={isLinux:bs,getReport:sa}});var Es=D((zh,ws)=>{"use strict";var ot=J("fs"),na="/usr/bin/ldd",ia="/proc/self/exe",jt=2048,oa=e=>{let t=ot.openSync(e,"r"),r=Buffer.alloc(jt),s=ot.readSync(t,r,0,jt,0);return ot.close(t,()=>{}),r.subarray(0,s)},aa=e=>new Promise((t,r)=>{ot.open(e,"r",(s,n)=>{if(s)r(s);else{let i=Buffer.alloc(jt);ot.read(n,i,0,jt,0,(o,a)=>{t(i.subarray(0,a)),ot.close(n,()=>{})})}})});ws.exports={LDD_PATH:na,SELF_PATH:ia,readFileSync:oa,readFile:aa}});var Ps=D((Bh,xs)=>{"use strict";var la=e=>{if(e.length<64||e.readUInt32BE(0)!==2135247942||e.readUInt8(4)!==2||e.readUInt8(5)!==1)return null;let t=e.readUInt32LE(32),r=e.readUInt16LE(54),s=e.readUInt16LE(56);for(let n=0;n<s;n++){let i=t+n*r;if(e.readUInt32LE(i)===3){let a=e.readUInt32LE(i+8),l=e.readUInt32LE(i+32);return e.subarray(a,a+l).toString().replace(/\0.*$/g,"")}}return null};xs.exports={interpreterPath:la}});var Mt=D((Uh,Bs)=>{"use strict";var Rs=J("child_process"),{isLinux:at,getReport:$s}=ys(),{LDD_PATH:Lt,SELF_PATH:ks,readFile:gr,readFileSync:mr}=Es(),{interpreterPath:As}=Ps(),Ie,De,Te,_s="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",He="",Ns=()=>He||new Promise(e=>{Rs.exec(_s,(t,r)=>{He=t?" ":r,e(He)})}),Is=()=>{if(!He)try{He=Rs.execSync(_s,{encoding:"utf8"})}catch{He=" "}return He},Me="glibc",Ds=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,et="musl",ca=e=>e.includes("libc.musl-")||e.includes("ld-musl-"),Ts=()=>{let e=$s();return e.header&&e.header.glibcVersionRuntime?Me:Array.isArray(e.sharedObjects)&&e.sharedObjects.some(ca)?et:null},Fs=e=>{let[t,r]=e.split(/[\r\n]+/);return t&&t.includes(Me)?Me:r&&r.includes(et)?et:null},Cs=e=>{if(e){if(e.includes("/ld-musl-"))return et;if(e.includes("/ld-linux-"))return Me}return null},Os=e=>(e=e.toString(),e.includes("musl")?et:e.includes("GNU C Library")?Me:null),ua=async()=>{if(De!==void 0)return De;De=null;try{let e=await gr(Lt);De=Os(e)}catch{}return De},fa=()=>{if(De!==void 0)return De;De=null;try{let e=mr(Lt);De=Os(e)}catch{}return De},ha=async()=>{if(Ie!==void 0)return Ie;Ie=null;try{let e=await gr(ks),t=As(e);Ie=Cs(t)}catch{}return Ie},da=()=>{if(Ie!==void 0)return Ie;Ie=null;try{let e=mr(ks),t=As(e);Ie=Cs(t)}catch{}return Ie},js=async()=>{let e=null;if(at()&&(e=await ha(),!e&&(e=await ua(),e||(e=Ts()),!e))){let t=await Ns();e=Fs(t)}return e},Ls=()=>{let e=null;if(at()&&(e=da(),!e&&(e=fa(),e||(e=Ts()),!e))){let t=Is();e=Fs(t)}return e},pa=async()=>at()&&await js()!==Me,ga=()=>at()&&Ls()!==Me,ma=async()=>{if(Te!==void 0)return Te;Te=null;try{let t=(await gr(Lt)).match(Ds);t&&(Te=t[1])}catch{}return Te},ba=()=>{if(Te!==void 0)return Te;Te=null;try{let t=mr(Lt).match(Ds);t&&(Te=t[1])}catch{}return Te},Ms=()=>{let e=$s();return e.header&&e.header.glibcVersionRuntime?e.header.glibcVersionRuntime:null},Ss=e=>e.trim().split(/\s+/)[1],zs=e=>{let[t,r,s]=e.split(/[\r\n]+/);return t&&t.includes(Me)?Ss(t):r&&s&&r.includes(et)?Ss(s):null},va=async()=>{let e=null;if(at()&&(e=await ma(),e||(e=Ms()),!e)){let t=await Ns();e=zs(t)}return e},ya=()=>{let e=null;if(at()&&(e=ba(),e||(e=Ms()),!e)){let t=Is();e=zs(t)}return e};Bs.exports={GLIBC:Me,MUSL:et,family:js,familySync:Ls,isNonGlibcLinux:pa,isNonGlibcLinuxSync:ga,version:va,versionSync:ya}});var Et=D((Gh,Us)=>{"use strict";var wa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>{}:()=>{};Us.exports=wa});var zt=D((qh,Gs)=>{"use strict";var Ea="2.0.0",xa=Number.MAX_SAFE_INTEGER||9007199254740991,Pa=16,Sa=250,Ra=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Gs.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Pa,MAX_SAFE_BUILD_LENGTH:Sa,MAX_SAFE_INTEGER:xa,RELEASE_TYPES:Ra,SEMVER_SPEC_VERSION:Ea,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var xt=D((Fe,qs)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:br,MAX_SAFE_BUILD_LENGTH:$a,MAX_LENGTH:ka}=zt(),Aa=Et();Fe=qs.exports={};var _a=Fe.re=[],Na=Fe.safeRe=[],y=Fe.src=[],Ia=Fe.safeSrc=[],w=Fe.t={},Da=0,vr="[a-zA-Z0-9-]",Ta=[["\\s",1],["\\d",ka],[vr,$a]],Fa=e=>{for(let[t,r]of Ta)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},k=(e,t,r)=>{let s=Fa(t),n=Da++;Aa(e,n,t),w[e]=n,y[n]=t,Ia[n]=s,_a[n]=new RegExp(t,r?"g":void 0),Na[n]=new RegExp(s,r?"g":void 0)};k("NUMERICIDENTIFIER","0|[1-9]\\d*");k("NUMERICIDENTIFIERLOOSE","\\d+");k("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${vr}*`);k("MAINVERSION",`(${y[w.NUMERICIDENTIFIER]})\\.(${y[w.NUMERICIDENTIFIER]})\\.(${y[w.NUMERICIDENTIFIER]})`);k("MAINVERSIONLOOSE",`(${y[w.NUMERICIDENTIFIERLOOSE]})\\.(${y[w.NUMERICIDENTIFIERLOOSE]})\\.(${y[w.NUMERICIDENTIFIERLOOSE]})`);k("PRERELEASEIDENTIFIER",`(?:${y[w.NONNUMERICIDENTIFIER]}|${y[w.NUMERICIDENTIFIER]})`);k("PRERELEASEIDENTIFIERLOOSE",`(?:${y[w.NONNUMERICIDENTIFIER]}|${y[w.NUMERICIDENTIFIERLOOSE]})`);k("PRERELEASE",`(?:-(${y[w.PRERELEASEIDENTIFIER]}(?:\\.${y[w.PRERELEASEIDENTIFIER]})*))`);k("PRERELEASELOOSE",`(?:-?(${y[w.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${y[w.PRERELEASEIDENTIFIERLOOSE]})*))`);k("BUILDIDENTIFIER",`${vr}+`);k("BUILD",`(?:\\+(${y[w.BUILDIDENTIFIER]}(?:\\.${y[w.BUILDIDENTIFIER]})*))`);k("FULLPLAIN",`v?${y[w.MAINVERSION]}${y[w.PRERELEASE]}?${y[w.BUILD]}?`);k("FULL",`^${y[w.FULLPLAIN]}$`);k("LOOSEPLAIN",`[v=\\s]*${y[w.MAINVERSIONLOOSE]}${y[w.PRERELEASELOOSE]}?${y[w.BUILD]}?`);k("LOOSE",`^${y[w.LOOSEPLAIN]}$`);k("GTLT","((?:<|>)?=?)");k("XRANGEIDENTIFIERLOOSE",`${y[w.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);k("XRANGEIDENTIFIER",`${y[w.NUMERICIDENTIFIER]}|x|X|\\*`);k("XRANGEPLAIN",`[v=\\s]*(${y[w.XRANGEIDENTIFIER]})(?:\\.(${y[w.XRANGEIDENTIFIER]})(?:\\.(${y[w.XRANGEIDENTIFIER]})(?:${y[w.PRERELEASE]})?${y[w.BUILD]}?)?)?`);k("XRANGEPLAINLOOSE",`[v=\\s]*(${y[w.XRANGEIDENTIFIERLOOSE]})(?:\\.(${y[w.XRANGEIDENTIFIERLOOSE]})(?:\\.(${y[w.XRANGEIDENTIFIERLOOSE]})(?:${y[w.PRERELEASELOOSE]})?${y[w.BUILD]}?)?)?`);k("XRANGE",`^${y[w.GTLT]}\\s*${y[w.XRANGEPLAIN]}$`);k("XRANGELOOSE",`^${y[w.GTLT]}\\s*${y[w.XRANGEPLAINLOOSE]}$`);k("COERCEPLAIN",`(^|[^\\d])(\\d{1,${br}})(?:\\.(\\d{1,${br}}))?(?:\\.(\\d{1,${br}}))?`);k("COERCE",`${y[w.COERCEPLAIN]}(?:$|[^\\d])`);k("COERCEFULL",y[w.COERCEPLAIN]+`(?:${y[w.PRERELEASE]})?(?:${y[w.BUILD]})?(?:$|[^\\d])`);k("COERCERTL",y[w.COERCE],!0);k("COERCERTLFULL",y[w.COERCEFULL],!0);k("LONETILDE","(?:~>?)");k("TILDETRIM",`(\\s*)${y[w.LONETILDE]}\\s+`,!0);Fe.tildeTrimReplace="$1~";k("TILDE",`^${y[w.LONETILDE]}${y[w.XRANGEPLAIN]}$`);k("TILDELOOSE",`^${y[w.LONETILDE]}${y[w.XRANGEPLAINLOOSE]}$`);k("LONECARET","(?:\\^)");k("CARETTRIM",`(\\s*)${y[w.LONECARET]}\\s+`,!0);Fe.caretTrimReplace="$1^";k("CARET",`^${y[w.LONECARET]}${y[w.XRANGEPLAIN]}$`);k("CARETLOOSE",`^${y[w.LONECARET]}${y[w.XRANGEPLAINLOOSE]}$`);k("COMPARATORLOOSE",`^${y[w.GTLT]}\\s*(${y[w.LOOSEPLAIN]})$|^$`);k("COMPARATOR",`^${y[w.GTLT]}\\s*(${y[w.FULLPLAIN]})$|^$`);k("COMPARATORTRIM",`(\\s*)${y[w.GTLT]}\\s*(${y[w.LOOSEPLAIN]}|${y[w.XRANGEPLAIN]})`,!0);Fe.comparatorTrimReplace="$1$2$3";k("HYPHENRANGE",`^\\s*(${y[w.XRANGEPLAIN]})\\s+-\\s+(${y[w.XRANGEPLAIN]})\\s*$`);k("HYPHENRANGELOOSE",`^\\s*(${y[w.XRANGEPLAINLOOSE]})\\s+-\\s+(${y[w.XRANGEPLAINLOOSE]})\\s*$`);k("STAR","(<|>)?=?\\s*\\*");k("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");k("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Bt=D((Wh,Ws)=>{"use strict";var Ca=Object.freeze({loose:!0}),Oa=Object.freeze({}),ja=e=>e?typeof e!="object"?Ca:e:Oa;Ws.exports=ja});var Xs=D((Hh,Js)=>{"use strict";var Hs=/^[0-9]+$/,Vs=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=Hs.test(e),s=Hs.test(t);return r&&s&&(e=+e,t=+t),e===t?0:r&&!s?-1:s&&!r?1:e<t?-1:1},La=(e,t)=>Vs(t,e);Js.exports={compareIdentifiers:Vs,rcompareIdentifiers:La}});var lt=D((Vh,Ks)=>{"use strict";var Ut=Et(),{MAX_LENGTH:Ys,MAX_SAFE_INTEGER:Gt}=zt(),{safeRe:qt,t:Wt}=xt(),Ma=Bt(),{compareIdentifiers:yr}=Xs(),wr=class e{constructor(t,r){if(r=Ma(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>Ys)throw new TypeError(`version is longer than ${Ys} characters`);Ut("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let s=t.trim().match(r.loose?qt[Wt.LOOSE]:qt[Wt.FULL]);if(!s)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>Gt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Gt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Gt||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let i=+n;if(i>=0&&i<Gt)return i}return n}):this.prerelease=[],this.build=s[5]?s[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(Ut("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let s=this.prerelease[r],n=t.prerelease[r];if(Ut("prerelease compare",r,s,n),s===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(s===void 0)return-1;if(s===n)continue;return yr(s,n)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let s=this.build[r],n=t.build[r];if(Ut("build compare",r,s,n),s===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(s===void 0)return-1;if(s===n)continue;return yr(s,n)}while(++r)}inc(t,r,s){if(t.startsWith("pre")){if(!r&&s===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let n=`-${r}`.match(this.options.loose?qt[Wt.PRERELEASELOOSE]:qt[Wt.PRERELEASE]);if(!n||n[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,s);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,s);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,s),this.inc("pre",r,s);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,s),this.inc("pre",r,s);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(s)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&s===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(r){let i=[r,n];s===!1&&(i=[r]),yr(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Ks.exports=wr});var en=D((Jh,Zs)=>{"use strict";var Qs=lt(),za=(e,t,r=!1)=>{if(e instanceof Qs)return e;try{return new Qs(e,t)}catch(s){if(!r)return null;throw s}};Zs.exports=za});var rn=D((Xh,tn)=>{"use strict";var Ba=lt(),Ua=en(),{safeRe:Ht,t:Vt}=xt(),Ga=(e,t)=>{if(e instanceof Ba)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?Ht[Vt.COERCEFULL]:Ht[Vt.COERCE]);else{let l=t.includePrerelease?Ht[Vt.COERCERTLFULL]:Ht[Vt.COERCERTL],u;for(;(u=l.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let s=r[2],n=r[3]||"0",i=r[4]||"0",o=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Ua(`${s}.${n}.${i}${o}${a}`,t)};tn.exports=Ga});var tt=D((Yh,nn)=>{"use strict";var sn=lt(),qa=(e,t,r)=>new sn(e,r).compare(new sn(t,r));nn.exports=qa});var Er=D((Kh,on)=>{"use strict";var Wa=tt(),Ha=(e,t,r)=>Wa(e,t,r)>=0;on.exports=Ha});var ln=D((Qh,an)=>{"use strict";var xr=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(t,r)}return this}};an.exports=xr});var un=D((Zh,cn)=>{"use strict";var Va=tt(),Ja=(e,t,r)=>Va(e,t,r)===0;cn.exports=Ja});var hn=D((ed,fn)=>{"use strict";var Xa=tt(),Ya=(e,t,r)=>Xa(e,t,r)!==0;fn.exports=Ya});var pn=D((td,dn)=>{"use strict";var Ka=tt(),Qa=(e,t,r)=>Ka(e,t,r)>0;dn.exports=Qa});var mn=D((rd,gn)=>{"use strict";var Za=tt(),el=(e,t,r)=>Za(e,t,r)<0;gn.exports=el});var vn=D((sd,bn)=>{"use strict";var tl=tt(),rl=(e,t,r)=>tl(e,t,r)<=0;bn.exports=rl});var wn=D((nd,yn)=>{"use strict";var sl=un(),nl=hn(),il=pn(),ol=Er(),al=mn(),ll=vn(),cl=(e,t,r,s)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return sl(e,r,s);case"!=":return nl(e,r,s);case">":return il(e,r,s);case">=":return ol(e,r,s);case"<":return al(e,r,s);case"<=":return ll(e,r,s);default:throw new TypeError(`Invalid operator: ${t}`)}};yn.exports=cl});var kn=D((id,$n)=>{"use strict";var Pt=Symbol("SemVer ANY"),Rr=class e{static get ANY(){return Pt}constructor(t,r){if(r=En(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Sr("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Pt?this.value="":this.value=this.operator+this.semver.version,Sr("comp",this)}parse(t){let r=this.options.loose?xn[Pn.COMPARATORLOOSE]:xn[Pn.COMPARATOR],s=t.match(r);if(!s)throw new TypeError(`Invalid comparator: ${t}`);this.operator=s[1]!==void 0?s[1]:"",this.operator==="="&&(this.operator=""),s[2]?this.semver=new Sn(s[2],this.options.loose):this.semver=Pt}toString(){return this.value}test(t){if(Sr("Comparator.test",t,this.options.loose),this.semver===Pt||t===Pt)return!0;if(typeof t=="string")try{t=new Sn(t,this.options)}catch{return!1}return Pr(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Rn(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Rn(this.value,r).test(t.semver):(r=En(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Pr(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Pr(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};$n.exports=Rr;var En=Bt(),{safeRe:xn,t:Pn}=xt(),Pr=wn(),Sr=Et(),Sn=lt(),Rn=$r()});var $r=D((od,In)=>{"use strict";var ul=/\s+/g,kr=class e{constructor(t,r){if(r=hl(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Ar)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(ul," "),this.set=this.raw.split("||").map(s=>this.parseRange(s.trim())).filter(s=>s.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let s=this.set[0];if(this.set=this.set.filter(n=>!_n(n[0])),this.set.length===0)this.set=[s];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&yl(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let s=0;s<r.length;s++)s>0&&(this.formatted+=" "),this.formatted+=r[s].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let s=((this.options.includePrerelease&&bl)|(this.options.loose&&vl))+":"+t,n=An.get(s);if(n)return n;let i=this.options.loose,o=i?le[ie.HYPHENRANGELOOSE]:le[ie.HYPHENRANGE];t=t.replace(o,_l(this.options.includePrerelease)),V("hyphen replace",t),t=t.replace(le[ie.COMPARATORTRIM],pl),V("comparator trim",t),t=t.replace(le[ie.TILDETRIM],gl),V("tilde trim",t),t=t.replace(le[ie.CARETTRIM],ml),V("caret trim",t);let a=t.split(" ").map(d=>wl(d,this.options)).join(" ").split(/\s+/).map(d=>Al(d,this.options));i&&(a=a.filter(d=>(V("loose invalid filter",d,this.options),!!d.match(le[ie.COMPARATORLOOSE])))),V("range list",a);let l=new Map,u=a.map(d=>new Ar(d,this.options));for(let d of u){if(_n(d))return[d];l.set(d.value,d)}l.size>1&&l.has("")&&l.delete("");let f=[...l.values()];return An.set(s,f),f}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(s=>Nn(s,r)&&t.set.some(n=>Nn(n,r)&&s.every(i=>n.every(o=>i.intersects(o,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new dl(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(Nl(this.set[r],t,this.options))return!0;return!1}};In.exports=kr;var fl=ln(),An=new fl,hl=Bt(),Ar=kn(),V=Et(),dl=lt(),{safeRe:le,t:ie,comparatorTrimReplace:pl,tildeTrimReplace:gl,caretTrimReplace:ml}=xt(),{FLAG_INCLUDE_PRERELEASE:bl,FLAG_LOOSE:vl}=zt(),_n=e=>e.value==="<0.0.0-0",yl=e=>e.value==="",Nn=(e,t)=>{let r=!0,s=e.slice(),n=s.pop();for(;r&&s.length;)r=s.every(i=>n.intersects(i,t)),n=s.pop();return r},wl=(e,t)=>(e=e.replace(le[ie.BUILD],""),V("comp",e,t),e=Pl(e,t),V("caret",e),e=El(e,t),V("tildes",e),e=Rl(e,t),V("xrange",e),e=kl(e,t),V("stars",e),e),ce=e=>!e||e.toLowerCase()==="x"||e==="*",El=(e,t)=>e.trim().split(/\s+/).map(r=>xl(r,t)).join(" "),xl=(e,t)=>{let r=t.loose?le[ie.TILDELOOSE]:le[ie.TILDE];return e.replace(r,(s,n,i,o,a)=>{V("tilde",e,s,n,i,o,a);let l;return ce(n)?l="":ce(i)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:ce(o)?l=`>=${n}.${i}.0 <${n}.${+i+1}.0-0`:a?(V("replaceTilde pr",a),l=`>=${n}.${i}.${o}-${a} <${n}.${+i+1}.0-0`):l=`>=${n}.${i}.${o} <${n}.${+i+1}.0-0`,V("tilde return",l),l})},Pl=(e,t)=>e.trim().split(/\s+/).map(r=>Sl(r,t)).join(" "),Sl=(e,t)=>{V("caret",e,t);let r=t.loose?le[ie.CARETLOOSE]:le[ie.CARET],s=t.includePrerelease?"-0":"";return e.replace(r,(n,i,o,a,l)=>{V("caret",e,n,i,o,a,l);let u;return ce(i)?u="":ce(o)?u=`>=${i}.0.0${s} <${+i+1}.0.0-0`:ce(a)?i==="0"?u=`>=${i}.${o}.0${s} <${i}.${+o+1}.0-0`:u=`>=${i}.${o}.0${s} <${+i+1}.0.0-0`:l?(V("replaceCaret pr",l),i==="0"?o==="0"?u=`>=${i}.${o}.${a}-${l} <${i}.${o}.${+a+1}-0`:u=`>=${i}.${o}.${a}-${l} <${i}.${+o+1}.0-0`:u=`>=${i}.${o}.${a}-${l} <${+i+1}.0.0-0`):(V("no pr"),i==="0"?o==="0"?u=`>=${i}.${o}.${a}${s} <${i}.${o}.${+a+1}-0`:u=`>=${i}.${o}.${a}${s} <${i}.${+o+1}.0-0`:u=`>=${i}.${o}.${a} <${+i+1}.0.0-0`),V("caret return",u),u})},Rl=(e,t)=>(V("replaceXRanges",e,t),e.split(/\s+/).map(r=>$l(r,t)).join(" ")),$l=(e,t)=>{e=e.trim();let r=t.loose?le[ie.XRANGELOOSE]:le[ie.XRANGE];return e.replace(r,(s,n,i,o,a,l)=>{V("xRange",e,s,n,i,o,a,l);let u=ce(i),f=u||ce(o),d=f||ce(a),g=d;return n==="="&&g&&(n=""),l=t.includePrerelease?"-0":"",u?n===">"||n==="<"?s="<0.0.0-0":s="*":n&&g?(f&&(o=0),a=0,n===">"?(n=">=",f?(i=+i+1,o=0,a=0):(o=+o+1,a=0)):n==="<="&&(n="<",f?i=+i+1:o=+o+1),n==="<"&&(l="-0"),s=`${n+i}.${o}.${a}${l}`):f?s=`>=${i}.0.0${l} <${+i+1}.0.0-0`:d&&(s=`>=${i}.${o}.0${l} <${i}.${+o+1}.0-0`),V("xRange return",s),s})},kl=(e,t)=>(V("replaceStars",e,t),e.trim().replace(le[ie.STAR],"")),Al=(e,t)=>(V("replaceGTE0",e,t),e.trim().replace(le[t.includePrerelease?ie.GTE0PRE:ie.GTE0],"")),_l=e=>(t,r,s,n,i,o,a,l,u,f,d,g)=>(ce(s)?r="":ce(n)?r=`>=${s}.0.0${e?"-0":""}`:ce(i)?r=`>=${s}.${n}.0${e?"-0":""}`:o?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,ce(u)?l="":ce(f)?l=`<${+u+1}.0.0-0`:ce(d)?l=`<${u}.${+f+1}.0-0`:g?l=`<=${u}.${f}.${d}-${g}`:e?l=`<${u}.${f}.${+d+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),Nl=(e,t,r)=>{for(let s=0;s<e.length;s++)if(!e[s].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let s=0;s<e.length;s++)if(V(e[s].semver),e[s].semver!==Ar.ANY&&e[s].semver.prerelease.length>0){let n=e[s].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}});var Tn=D((ad,Dn)=>{"use strict";var Il=$r(),Dl=(e,t,r)=>{try{t=new Il(t,r)}catch{return!1}return t.test(e)};Dn.exports=Dl});var _r=D((ld,Tl)=>{Tl.exports={name:"sharp",description:"High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images",version:"0.34.5",author:"Lovell Fuller <npm@lovell.info>",homepage:"https://sharp.pixelplumbing.com",contributors:["Pierre Inglebert <pierre.inglebert@gmail.com>","Jonathan Ong <jonathanrichardong@gmail.com>","Chanon Sajjamanochai <chanon.s@gmail.com>","Juliano Julio <julianojulio@gmail.com>","Daniel Gasienica <daniel@gasienica.ch>","Julian Walker <julian@fiftythree.com>","Amit Pitaru <pitaru.amit@gmail.com>","Brandon Aaron <hello.brandon@aaron.sh>","Andreas Lind <andreas@one.com>","Maurus Cuelenaere <mcuelenaere@gmail.com>","Linus Unneb\xE4ck <linus@folkdatorn.se>","Victor Mateevitsi <mvictoras@gmail.com>","Alaric Holloway <alaric.holloway@gmail.com>","Bernhard K. Weisshuhn <bkw@codingforce.com>","Chris Riley <criley@primedia.com>","David Carley <dacarley@gmail.com>","John Tobin <john@limelightmobileinc.com>","Kenton Gray <kentongray@gmail.com>","Felix B\xFCnemann <Felix.Buenemann@gmail.com>","Samy Al Zahrani <samyalzahrany@gmail.com>","Chintan Thakkar <lemnisk8@gmail.com>","F. Orlando Galashan <frulo@gmx.de>","Kleis Auke Wolthuizen <info@kleisauke.nl>","Matt Hirsch <mhirsch@media.mit.edu>","Matthias Thoemmes <thoemmes@gmail.com>","Patrick Paskaris <patrick@paskaris.gr>","J\xE9r\xE9my Lal <kapouer@melix.org>","Rahul Nanwani <r.nanwani@gmail.com>","Alice Monday <alice0meta@gmail.com>","Kristo Jorgenson <kristo.jorgenson@gmail.com>","YvesBos <yves_bos@outlook.com>","Guy Maliar <guy@tailorbrands.com>","Nicolas Coden <nicolas@ncoden.fr>","Matt Parrish <matt.r.parrish@gmail.com>","Marcel Bretschneider <marcel.bretschneider@gmail.com>","Matthew McEachen <matthew+github@mceachen.org>","Jarda Kot\u011B\u0161ovec <jarda.kotesovec@gmail.com>","Kenric D'Souza <kenric.dsouza@gmail.com>","Oleh Aleinyk <oleg.aleynik@gmail.com>","Marcel Bretschneider <marcel.bretschneider@gmail.com>","Andrea Bianco <andrea.bianco@unibas.ch>","Rik Heywood <rik@rik.org>","Thomas Parisot <hi@oncletom.io>","Nathan Graves <nathanrgraves+github@gmail.com>","Tom Lokhorst <tom@lokhorst.eu>","Espen Hovlandsdal <espen@hovlandsdal.com>","Sylvain Dumont <sylvain.dumont35@gmail.com>","Alun Davies <alun.owain.davies@googlemail.com>","Aidan Hoolachan <ajhoolachan21@gmail.com>","Axel Eirola <axel.eirola@iki.fi>","Freezy <freezy@xbmc.org>","Daiz <taneli.vatanen@gmail.com>","Julian Aubourg <j@ubourg.net>","Keith Belovay <keith@picthrive.com>","Michael B. Klein <mbklein@gmail.com>","Jordan Prudhomme <jordan@raboland.fr>","Ilya Ovdin <iovdin@gmail.com>","Andargor <andargor@yahoo.com>","Paul Neave <paul.neave@gmail.com>","Brendan Kennedy <brenwken@gmail.com>","Brychan Bennett-Odlum <git@brychan.io>","Edward Silverton <e.silverton@gmail.com>","Roman Malieiev <aromaleev@gmail.com>","Tomas Szabo <tomas.szabo@deftomat.com>","Robert O'Rourke <robert@o-rourke.org>","Guillermo Alfonso Varela Chouci\xF1o <guillevch@gmail.com>","Christian Flintrup <chr@gigahost.dk>","Manan Jadhav <manan@motionden.com>","Leon Radley <leon@radley.se>","alza54 <alza54@thiocod.in>","Jacob Smith <jacob@frende.me>","Michael Nutt <michael@nutt.im>","Brad Parham <baparham@gmail.com>","Taneli Vatanen <taneli.vatanen@gmail.com>","Joris Dugu\xE9 <zaruike10@gmail.com>","Chris Banks <christopher.bradley.banks@gmail.com>","Ompal Singh <ompal.hitm09@gmail.com>","Brodan <christopher.hranj@gmail.com>","Ankur Parihar <ankur.github@gmail.com>","Brahim Ait elhaj <brahima@gmail.com>","Mart Jansink <m.jansink@gmail.com>","Lachlan Newman <lachnewman007@gmail.com>","Dennis Beatty <dennis@dcbeatty.com>","Ingvar Stepanyan <me@rreverser.com>","Don Denton <don@happycollision.com>"],scripts:{build:"node install/build.js",install:"node install/check.js || npm run build",clean:"rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*",test:"npm run lint && npm run test-unit",lint:"npm run lint-cpp && npm run lint-js && npm run lint-types","lint-cpp":"cpplint --quiet src/*.h src/*.cc","lint-js":"biome lint","lint-types":"tsd --files ./test/types/sharp.test-d.ts","test-leak":"./test/leak/leak.sh","test-unit":"node --experimental-test-coverage test/unit.mjs","package-from-local-build":"node npm/from-local-build.js","package-release-notes":"node npm/release-notes.js","docs-build":"node docs/build.mjs","docs-serve":"cd docs && npm start","docs-publish":"cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp"},type:"commonjs",main:"lib/index.js",types:"lib/index.d.ts",files:["install","lib","src/*.{cc,h,gyp}"],repository:{type:"git",url:"git://github.com/lovell/sharp.git"},keywords:["jpeg","png","webp","avif","tiff","gif","svg","jp2","dzi","image","resize","thumbnail","crop","embed","libvips","vips"],dependencies:{"@img/colour":"^1.0.0","detect-libc":"^2.1.2",semver:"^7.7.3"},optionalDependencies:{"@img/sharp-darwin-arm64":"0.34.5","@img/sharp-darwin-x64":"0.34.5","@img/sharp-libvips-darwin-arm64":"1.2.4","@img/sharp-libvips-darwin-x64":"1.2.4","@img/sharp-libvips-linux-arm":"1.2.4","@img/sharp-libvips-linux-arm64":"1.2.4","@img/sharp-libvips-linux-ppc64":"1.2.4","@img/sharp-libvips-linux-riscv64":"1.2.4","@img/sharp-libvips-linux-s390x":"1.2.4","@img/sharp-libvips-linux-x64":"1.2.4","@img/sharp-libvips-linuxmusl-arm64":"1.2.4","@img/sharp-libvips-linuxmusl-x64":"1.2.4","@img/sharp-linux-arm":"0.34.5","@img/sharp-linux-arm64":"0.34.5","@img/sharp-linux-ppc64":"0.34.5","@img/sharp-linux-riscv64":"0.34.5","@img/sharp-linux-s390x":"0.34.5","@img/sharp-linux-x64":"0.34.5","@img/sharp-linuxmusl-arm64":"0.34.5","@img/sharp-linuxmusl-x64":"0.34.5","@img/sharp-wasm32":"0.34.5","@img/sharp-win32-arm64":"0.34.5","@img/sharp-win32-ia32":"0.34.5","@img/sharp-win32-x64":"0.34.5"},devDependencies:{"@biomejs/biome":"^2.3.4","@cpplint/cli":"^0.1.0","@emnapi/runtime":"^1.7.0","@img/sharp-libvips-dev":"1.2.4","@img/sharp-libvips-dev-wasm32":"1.2.4","@img/sharp-libvips-win32-arm64":"1.2.4","@img/sharp-libvips-win32-ia32":"1.2.4","@img/sharp-libvips-win32-x64":"1.2.4","@types/node":"*",emnapi:"^1.7.0","exif-reader":"^2.0.2","extract-zip":"^2.0.1",icc:"^3.0.0","jsdoc-to-markdown":"^9.1.3","node-addon-api":"^8.5.0","node-gyp":"^11.5.0","tar-fs":"^3.1.1",tsd:"^0.33.0"},license:"Apache-2.0",engines:{node:"^18.17.0 || ^20.3.0 || >=21.0.0"},config:{libvips:">=8.17.3"},funding:{url:"https://opencollective.com/libvips"}}});var Ir=D((cd,Gn)=>{var{spawnSync:Jt}=J("node:child_process"),{createHash:Fl}=J("node:crypto"),jn=rn(),Cl=Er(),Ol=Tn(),Fn=Mt(),{config:jl,engines:Cn,optionalDependencies:Ll}=_r(),Ml=process.env.npm_package_config_libvips||jl.libvips,Ln=jn(Ml).version,zl=["darwin-arm64","darwin-x64","linux-arm","linux-arm64","linux-ppc64","linux-riscv64","linux-s390x","linux-x64","linuxmusl-arm64","linuxmusl-x64","win32-arm64","win32-ia32","win32-x64"],Xt={encoding:"utf8",shell:!0},Bl=e=>{e instanceof Error},Mn=()=>Fn.isNonGlibcLinuxSync()?Fn.familySync():"",Ul=()=>`${process.platform}${Mn()}-${process.arch}`,ct=()=>{if(zn())return"wasm32";let{npm_config_arch:e,npm_config_platform:t,npm_config_libc:r}=process.env,s=typeof r=="string"?r:Mn();return`${t||process.platform}${s}-${e||process.arch}`},Gl=()=>{try{return J(`@img/sharp-libvips-dev-${ct()}/include`)}catch{try{return J("@img/sharp-libvips-dev/include")}catch{}}return""},ql=()=>{try{return J("@img/sharp-libvips-dev/cplusplus")}catch{}return""},Wl=()=>{try{return J(`@img/sharp-libvips-dev-${ct()}/lib`)}catch{try{return J(`@img/sharp-libvips-${ct()}/lib`)}catch{}}return""},Hl=()=>{if(process.release?.name==="node"&&process.versions&&!Ol(process.versions.node,Cn.node))return{found:process.versions.node,expected:Cn.node}},zn=()=>{let{CC:e}=process.env;return!!e?.endsWith("/emcc")},Vl=()=>process.platform==="darwin"&&process.arch==="x64"?(Jt("sysctl sysctl.proc_translated",Xt).stdout||"").trim()==="sysctl.proc_translated: 1":!1,On=e=>Fl("sha512").update(e).digest("hex"),Jl=()=>{try{let e=On(`imgsharp-libvips-${ct()}`),t=jn(Ll[`@img/sharp-libvips-${ct()}`],{includePrerelease:!0}).version;return On(`${e}npm:${t}`).slice(0,10)}catch{}return""},Xl=()=>Jt(`node-gyp rebuild --directory=src ${zn()?"--nodedir=emscripten":""}`,{...Xt,stdio:"inherit"}).status,Bn=()=>process.platform!=="win32"?(Jt("pkg-config --modversion vips-cpp",{...Xt,env:{...process.env,PKG_CONFIG_PATH:Un()}}).stdout||"").trim():"",Un=()=>process.platform!=="win32"?[(Jt('which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2',Xt).stdout||"").trim(),process.env.PKG_CONFIG_PATH,"/usr/local/lib/pkgconfig","/usr/lib/pkgconfig","/usr/local/libdata/pkgconfig","/usr/libdata/pkgconfig"].filter(Boolean).join(":"):"",Nr=(e,t,r)=>(r&&r(`Detected ${t}, skipping search for globally-installed libvips`),e),Yl=e=>{if(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS)return Nr(!1,"SHARP_IGNORE_GLOBAL_LIBVIPS",e);if(process.env.SHARP_FORCE_GLOBAL_LIBVIPS)return Nr(!0,"SHARP_FORCE_GLOBAL_LIBVIPS",e);if(Vl())return Nr(!1,"Rosetta",e);let t=Bn();return!!t&&Cl(t,Ln)};Gn.exports={minimumLibvipsVersion:Ln,prebuiltPlatforms:zl,buildPlatformArch:ct,buildSharpLibvipsIncludeDir:Gl,buildSharpLibvipsCPlusPlusDir:ql,buildSharpLibvipsLibDir:Wl,isUnsupportedNodeRuntime:Hl,runtimePlatformArch:Ul,log:Bl,yarnLocator:Jl,spawnRebuild:Xl,globalLibvipsVersion:Bn,pkgConfigPath:Un,useGlobalLibvips:Yl}});var Rt=D((fd,Wn)=>{var{familySync:Kl,versionSync:Ql}=Mt(),{runtimePlatformArch:Zl,isUnsupportedNodeRuntime:qn,prebuiltPlatforms:ec,minimumLibvipsVersion:tc}=Ir(),rt=Zl(),rc=[`../src/build/Release/sharp-${rt}.node`,"../src/build/Release/sharp-wasm32.node",`@img/sharp-${rt}/sharp.node`,"@img/sharp-wasm32/sharp.node"],Dr,ut,St=[];for(Dr of rc)try{ut=J(Dr);break}catch(e){St.push(e)}if(ut&&Dr.startsWith("@img/sharp-linux-x64")&&!ut._isUsingX64V2()){let e=new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");e.code="Unsupported CPU",St.push(e),ut=null}if(ut)Wn.exports=ut;else{let[e,t,r]=["linux","darwin","win32"].map(i=>rt.startsWith(i)),s=[`Could not load the "sharp" module using the ${rt} runtime`];St.forEach(i=>{i.code!=="MODULE_NOT_FOUND"&&s.push(`${i.code}: ${i.message}`)});let n=St.map(i=>i.message).join(" ");if(s.push("Possible solutions:"),qn()){let{found:i,expected:o}=qn();s.push("- Please upgrade Node.js:",` Found ${i}`,` Requires ${o}`)}else if(ec.includes(rt)){let[i,o]=rt.split("-"),a=i.endsWith("musl")?" --libc=musl":"";s.push("- Ensure optional dependencies can be installed:"," npm install --include=optional sharp","- Ensure your package manager supports multi-platform installation:"," See https://sharp.pixelplumbing.com/install#cross-platform","- Add platform-specific dependencies:",` npm install --os=${i.replace("musl","")}${a} --cpu=${o} sharp`)}else s.push(`- Manually install libvips >= ${tc}`,"- Add experimental WebAssembly-based dependencies:"," npm install --cpu=wasm32 sharp"," npm install @img/sharp-wasm32");if(e&&/(symbol not found|CXXABI_)/i.test(n))try{let{config:i}=J(`@img/sharp-libvips-${rt}/package`),o=`${Kl()} ${Ql()}`,a=`${i.musl?"musl":"glibc"} ${i.musl||i.glibc}`;s.push("- Update your OS:",` Found ${o}`,` Requires ${a}`)}catch{}throw e&&/\/snap\/core[0-9]{2}/.test(n)&&s.push("- Remove the Node.js Snap, which does not support native modules"," snap remove node"),t&&/Incompatible library version/.test(n)&&s.push("- Update Homebrew:"," brew update && brew upgrade vips"),St.some(i=>i.code==="ERR_DLOPEN_DISABLED")&&s.push("- Run Node.js without using the --no-addons flag"),r&&/The specified procedure could not be found/.test(n)&&s.push("- Using the canvas package on Windows?"," See https://sharp.pixelplumbing.com/install#canvas-and-windows","- Check for outdated versions of sharp in the dependency tree:"," npm ls sharp"),s.push("- Consult the installation documentation:"," See https://sharp.pixelplumbing.com/install"),new Error(s.join(`
|
|
2
|
-
`))}});var Vn=D((dd,Hn)=>{var sc=J("node:util"),Tr=J("node:stream"),nc=Ne();Rt();var ic=sc.debuglog("sharp"),oc=e=>{st.queue.emit("change",e)},st=function(e,t){if(arguments.length===1&&!nc.defined(e))throw new Error("Invalid input");return this instanceof st?(Tr.Duplex.call(this),this.options={topOffsetPre:-1,leftOffsetPre:-1,widthPre:-1,heightPre:-1,topOffsetPost:-1,leftOffsetPost:-1,widthPost:-1,heightPost:-1,width:-1,height:-1,canvas:"crop",position:0,resizeBackground:[0,0,0,255],angle:0,rotationAngle:0,rotationBackground:[0,0,0,255],rotateBefore:!1,orientBefore:!1,flip:!1,flop:!1,extendTop:0,extendBottom:0,extendLeft:0,extendRight:0,extendBackground:[0,0,0,255],extendWith:"background",withoutEnlargement:!1,withoutReduction:!1,affineMatrix:[],affineBackground:[0,0,0,255],affineIdx:0,affineIdy:0,affineOdx:0,affineOdy:0,affineInterpolator:this.constructor.interpolators.bilinear,kernel:"lanczos3",fastShrinkOnLoad:!0,tint:[-1,0,0,0],flatten:!1,flattenBackground:[0,0,0],unflatten:!1,negate:!1,negateAlpha:!0,medianSize:0,blurSigma:0,precision:"integer",minAmpl:.2,sharpenSigma:0,sharpenM1:1,sharpenM2:2,sharpenX1:2,sharpenY2:10,sharpenY3:20,threshold:0,thresholdGrayscale:!0,trimBackground:[],trimThreshold:-1,trimLineArt:!1,dilateWidth:0,erodeWidth:0,gamma:0,gammaOut:0,greyscale:!1,normalise:!1,normaliseLower:1,normaliseUpper:99,claheWidth:0,claheHeight:0,claheMaxSlope:3,brightness:1,saturation:1,hue:0,lightness:0,booleanBufferIn:null,booleanFileIn:"",joinChannelIn:[],extractChannel:-1,removeAlpha:!1,ensureAlpha:-1,colourspace:"srgb",colourspacePipeline:"last",composite:[],fileOut:"",formatOut:"input",streamOut:!1,keepMetadata:0,withMetadataOrientation:-1,withMetadataDensity:0,withIccProfile:"",withExif:{},withExifMerge:!0,withXmp:"",resolveWithObject:!1,loop:-1,delay:[],jpegQuality:80,jpegProgressive:!1,jpegChromaSubsampling:"4:2:0",jpegTrellisQuantisation:!1,jpegOvershootDeringing:!1,jpegOptimiseScans:!1,jpegOptimiseCoding:!0,jpegQuantisationTable:0,pngProgressive:!1,pngCompressionLevel:6,pngAdaptiveFiltering:!1,pngPalette:!1,pngQuality:100,pngEffort:7,pngBitdepth:8,pngDither:1,jp2Quality:80,jp2TileHeight:512,jp2TileWidth:512,jp2Lossless:!1,jp2ChromaSubsampling:"4:4:4",webpQuality:80,webpAlphaQuality:100,webpLossless:!1,webpNearLossless:!1,webpSmartSubsample:!1,webpSmartDeblock:!1,webpPreset:"default",webpEffort:4,webpMinSize:!1,webpMixed:!1,gifBitdepth:8,gifEffort:7,gifDither:1,gifInterFrameMaxError:0,gifInterPaletteMaxError:3,gifKeepDuplicateFrames:!1,gifReuse:!0,gifProgressive:!1,tiffQuality:80,tiffCompression:"jpeg",tiffBigtiff:!1,tiffPredictor:"horizontal",tiffPyramid:!1,tiffMiniswhite:!1,tiffBitdepth:8,tiffTile:!1,tiffTileHeight:256,tiffTileWidth:256,tiffXres:1,tiffYres:1,tiffResolutionUnit:"inch",heifQuality:50,heifLossless:!1,heifCompression:"av1",heifEffort:4,heifChromaSubsampling:"4:4:4",heifBitdepth:8,jxlDistance:1,jxlDecodingTier:0,jxlEffort:7,jxlLossless:!1,rawDepth:"uchar",tileSize:256,tileOverlap:0,tileContainer:"fs",tileLayout:"dz",tileFormat:"last",tileDepth:"last",tileAngle:0,tileSkipBlanks:-1,tileBackground:[255,255,255,255],tileCentre:!1,tileId:"https://example.com/iiif",tileBasename:"",timeoutSeconds:0,linearA:[],linearB:[],pdfBackground:[255,255,255,255],debuglog:r=>{this.emit("warning",r),ic(r)},queueListener:oc},this.options.input=this._createInputDescriptor(e,t,{allowStream:!0}),this):new st(e,t)};Object.setPrototypeOf(st.prototype,Tr.Duplex.prototype);Object.setPrototypeOf(st,Tr.Duplex);function ac(){let e=this.constructor.call(),{debuglog:t,queueListener:r,...s}=this.options;return e.options=structuredClone(s),e.options.debuglog=t,e.options.queueListener=r,this._isStreamInput()&&this.on("finish",()=>{this._flattenBufferIn(),e.options.input.buffer=this.options.input.buffer,e.emit("finish")}),e}Object.assign(st.prototype,{clone:ac});Hn.exports=st});var Yn=D((pd,Xn)=>{var h=Ne(),Ve=Rt(),lc={left:"low",top:"low",low:"low",center:"centre",centre:"centre",right:"high",bottom:"high",high:"high"},cc=["failOn","limitInputPixels","unlimited","animated","autoOrient","density","ignoreIcc","page","pages","sequentialRead","jp2","openSlide","pdf","raw","svg","tiff","failOnError","openSlideLevel","pdfBackground","tiffSubifd"];function Jn(e){let t=cc.filter(r=>h.defined(e[r])).map(r=>[r,e[r]]);return t.length?Object.fromEntries(t):void 0}function uc(e,t,r){let s={autoOrient:!1,failOn:"warning",limitInputPixels:268402689,ignoreIcc:!1,unlimited:!1,sequentialRead:!0};if(h.string(e))s.file=e;else if(h.buffer(e)){if(e.length===0)throw Error("Input Buffer is empty");s.buffer=e}else if(h.arrayBuffer(e)){if(e.byteLength===0)throw Error("Input bit Array is empty");s.buffer=Buffer.from(e,0,e.byteLength)}else if(h.typedArray(e)){if(e.length===0)throw Error("Input Bit Array is empty");s.buffer=Buffer.from(e.buffer,e.byteOffset,e.byteLength)}else if(h.plainObject(e)&&!h.defined(t))t=e,Jn(t)&&(s.buffer=[]);else if(!h.defined(e)&&!h.defined(t)&&h.object(r)&&r.allowStream)s.buffer=[];else if(Array.isArray(e))if(e.length>1)if(!this.options.joining)this.options.joining=!0,this.options.join=e.map(n=>this._createInputDescriptor(n));else throw new Error("Recursive join is unsupported");else throw new Error("Expected at least two images to join");else throw new Error(`Unsupported input '${e}' of type ${typeof e}${h.defined(t)?` when also providing options of type ${typeof t}`:""}`);if(h.object(t)){if(h.defined(t.failOnError))if(h.bool(t.failOnError))s.failOn=t.failOnError?"warning":"none";else throw h.invalidParameterError("failOnError","boolean",t.failOnError);if(h.defined(t.failOn))if(h.string(t.failOn)&&h.inArray(t.failOn,["none","truncated","error","warning"]))s.failOn=t.failOn;else throw h.invalidParameterError("failOn","one of: none, truncated, error, warning",t.failOn);if(h.defined(t.autoOrient))if(h.bool(t.autoOrient))s.autoOrient=t.autoOrient;else throw h.invalidParameterError("autoOrient","boolean",t.autoOrient);if(h.defined(t.density))if(h.inRange(t.density,1,1e5))s.density=t.density;else throw h.invalidParameterError("density","number between 1 and 100000",t.density);if(h.defined(t.ignoreIcc))if(h.bool(t.ignoreIcc))s.ignoreIcc=t.ignoreIcc;else throw h.invalidParameterError("ignoreIcc","boolean",t.ignoreIcc);if(h.defined(t.limitInputPixels))if(h.bool(t.limitInputPixels))s.limitInputPixels=t.limitInputPixels?16383**2:0;else if(h.integer(t.limitInputPixels)&&h.inRange(t.limitInputPixels,0,Number.MAX_SAFE_INTEGER))s.limitInputPixels=t.limitInputPixels;else throw h.invalidParameterError("limitInputPixels","positive integer",t.limitInputPixels);if(h.defined(t.unlimited))if(h.bool(t.unlimited))s.unlimited=t.unlimited;else throw h.invalidParameterError("unlimited","boolean",t.unlimited);if(h.defined(t.sequentialRead))if(h.bool(t.sequentialRead))s.sequentialRead=t.sequentialRead;else throw h.invalidParameterError("sequentialRead","boolean",t.sequentialRead);if(h.defined(t.raw)){if(h.object(t.raw)&&h.integer(t.raw.width)&&t.raw.width>0&&h.integer(t.raw.height)&&t.raw.height>0&&h.integer(t.raw.channels)&&h.inRange(t.raw.channels,1,4))switch(s.rawWidth=t.raw.width,s.rawHeight=t.raw.height,s.rawChannels=t.raw.channels,e.constructor){case Uint8Array:case Uint8ClampedArray:s.rawDepth="uchar";break;case Int8Array:s.rawDepth="char";break;case Uint16Array:s.rawDepth="ushort";break;case Int16Array:s.rawDepth="short";break;case Uint32Array:s.rawDepth="uint";break;case Int32Array:s.rawDepth="int";break;case Float32Array:s.rawDepth="float";break;case Float64Array:s.rawDepth="double";break;default:s.rawDepth="uchar";break}else throw new Error("Expected width, height and channels for raw pixel input");if(s.rawPremultiplied=!1,h.defined(t.raw.premultiplied))if(h.bool(t.raw.premultiplied))s.rawPremultiplied=t.raw.premultiplied;else throw h.invalidParameterError("raw.premultiplied","boolean",t.raw.premultiplied);if(s.rawPageHeight=0,h.defined(t.raw.pageHeight))if(h.integer(t.raw.pageHeight)&&t.raw.pageHeight>0&&t.raw.pageHeight<=t.raw.height){if(t.raw.height%t.raw.pageHeight!==0)throw new Error(`Expected raw.height ${t.raw.height} to be a multiple of raw.pageHeight ${t.raw.pageHeight}`);s.rawPageHeight=t.raw.pageHeight}else throw h.invalidParameterError("raw.pageHeight","positive integer",t.raw.pageHeight)}if(h.defined(t.animated))if(h.bool(t.animated))s.pages=t.animated?-1:1;else throw h.invalidParameterError("animated","boolean",t.animated);if(h.defined(t.pages))if(h.integer(t.pages)&&h.inRange(t.pages,-1,1e5))s.pages=t.pages;else throw h.invalidParameterError("pages","integer between -1 and 100000",t.pages);if(h.defined(t.page))if(h.integer(t.page)&&h.inRange(t.page,0,1e5))s.page=t.page;else throw h.invalidParameterError("page","integer between 0 and 100000",t.page);if(h.object(t.openSlide)&&h.defined(t.openSlide.level))if(h.integer(t.openSlide.level)&&h.inRange(t.openSlide.level,0,256))s.openSlideLevel=t.openSlide.level;else throw h.invalidParameterError("openSlide.level","integer between 0 and 256",t.openSlide.level);else if(h.defined(t.level))if(h.integer(t.level)&&h.inRange(t.level,0,256))s.openSlideLevel=t.level;else throw h.invalidParameterError("level","integer between 0 and 256",t.level);if(h.object(t.tiff)&&h.defined(t.tiff.subifd))if(h.integer(t.tiff.subifd)&&h.inRange(t.tiff.subifd,-1,1e5))s.tiffSubifd=t.tiff.subifd;else throw h.invalidParameterError("tiff.subifd","integer between -1 and 100000",t.tiff.subifd);else if(h.defined(t.subifd))if(h.integer(t.subifd)&&h.inRange(t.subifd,-1,1e5))s.tiffSubifd=t.subifd;else throw h.invalidParameterError("subifd","integer between -1 and 100000",t.subifd);if(h.object(t.svg)){if(h.defined(t.svg.stylesheet))if(h.string(t.svg.stylesheet))s.svgStylesheet=t.svg.stylesheet;else throw h.invalidParameterError("svg.stylesheet","string",t.svg.stylesheet);if(h.defined(t.svg.highBitdepth))if(h.bool(t.svg.highBitdepth))s.svgHighBitdepth=t.svg.highBitdepth;else throw h.invalidParameterError("svg.highBitdepth","boolean",t.svg.highBitdepth)}if(h.object(t.pdf)&&h.defined(t.pdf.background)?s.pdfBackground=this._getBackgroundColourOption(t.pdf.background):h.defined(t.pdfBackground)&&(s.pdfBackground=this._getBackgroundColourOption(t.pdfBackground)),h.object(t.jp2)&&h.defined(t.jp2.oneshot))if(h.bool(t.jp2.oneshot))s.jp2Oneshot=t.jp2.oneshot;else throw h.invalidParameterError("jp2.oneshot","boolean",t.jp2.oneshot);if(h.defined(t.create))if(h.object(t.create)&&h.integer(t.create.width)&&t.create.width>0&&h.integer(t.create.height)&&t.create.height>0&&h.integer(t.create.channels)){if(s.createWidth=t.create.width,s.createHeight=t.create.height,s.createChannels=t.create.channels,s.createPageHeight=0,h.defined(t.create.pageHeight))if(h.integer(t.create.pageHeight)&&t.create.pageHeight>0&&t.create.pageHeight<=t.create.height){if(t.create.height%t.create.pageHeight!==0)throw new Error(`Expected create.height ${t.create.height} to be a multiple of create.pageHeight ${t.create.pageHeight}`);s.createPageHeight=t.create.pageHeight}else throw h.invalidParameterError("create.pageHeight","positive integer",t.create.pageHeight);if(h.defined(t.create.noise)){if(!h.object(t.create.noise))throw new Error("Expected noise to be an object");if(t.create.noise.type!=="gaussian")throw new Error("Only gaussian noise is supported at the moment");if(s.createNoiseType=t.create.noise.type,!h.inRange(t.create.channels,1,4))throw h.invalidParameterError("create.channels","number between 1 and 4",t.create.channels);if(s.createNoiseMean=128,h.defined(t.create.noise.mean))if(h.number(t.create.noise.mean)&&h.inRange(t.create.noise.mean,0,1e4))s.createNoiseMean=t.create.noise.mean;else throw h.invalidParameterError("create.noise.mean","number between 0 and 10000",t.create.noise.mean);if(s.createNoiseSigma=30,h.defined(t.create.noise.sigma))if(h.number(t.create.noise.sigma)&&h.inRange(t.create.noise.sigma,0,1e4))s.createNoiseSigma=t.create.noise.sigma;else throw h.invalidParameterError("create.noise.sigma","number between 0 and 10000",t.create.noise.sigma)}else if(h.defined(t.create.background)){if(!h.inRange(t.create.channels,3,4))throw h.invalidParameterError("create.channels","number between 3 and 4",t.create.channels);s.createBackground=this._getBackgroundColourOption(t.create.background)}else throw new Error("Expected valid noise or background to create a new input image");delete s.buffer}else throw new Error("Expected valid width, height and channels to create a new input image");if(h.defined(t.text))if(h.object(t.text)&&h.string(t.text.text)){if(s.textValue=t.text.text,h.defined(t.text.height)&&h.defined(t.text.dpi))throw new Error("Expected only one of dpi or height");if(h.defined(t.text.font))if(h.string(t.text.font))s.textFont=t.text.font;else throw h.invalidParameterError("text.font","string",t.text.font);if(h.defined(t.text.fontfile))if(h.string(t.text.fontfile))s.textFontfile=t.text.fontfile;else throw h.invalidParameterError("text.fontfile","string",t.text.fontfile);if(h.defined(t.text.width))if(h.integer(t.text.width)&&t.text.width>0)s.textWidth=t.text.width;else throw h.invalidParameterError("text.width","positive integer",t.text.width);if(h.defined(t.text.height))if(h.integer(t.text.height)&&t.text.height>0)s.textHeight=t.text.height;else throw h.invalidParameterError("text.height","positive integer",t.text.height);if(h.defined(t.text.align))if(h.string(t.text.align)&&h.string(this.constructor.align[t.text.align]))s.textAlign=this.constructor.align[t.text.align];else throw h.invalidParameterError("text.align","valid alignment",t.text.align);if(h.defined(t.text.justify))if(h.bool(t.text.justify))s.textJustify=t.text.justify;else throw h.invalidParameterError("text.justify","boolean",t.text.justify);if(h.defined(t.text.dpi))if(h.integer(t.text.dpi)&&h.inRange(t.text.dpi,1,1e6))s.textDpi=t.text.dpi;else throw h.invalidParameterError("text.dpi","integer between 1 and 1000000",t.text.dpi);if(h.defined(t.text.rgba))if(h.bool(t.text.rgba))s.textRgba=t.text.rgba;else throw h.invalidParameterError("text.rgba","bool",t.text.rgba);if(h.defined(t.text.spacing))if(h.integer(t.text.spacing)&&h.inRange(t.text.spacing,-1e6,1e6))s.textSpacing=t.text.spacing;else throw h.invalidParameterError("text.spacing","integer between -1000000 and 1000000",t.text.spacing);if(h.defined(t.text.wrap))if(h.string(t.text.wrap)&&h.inArray(t.text.wrap,["word","char","word-char","none"]))s.textWrap=t.text.wrap;else throw h.invalidParameterError("text.wrap","one of: word, char, word-char, none",t.text.wrap);delete s.buffer}else throw new Error("Expected a valid string to create an image with text.");if(h.defined(t.join))if(h.defined(this.options.join)){if(h.defined(t.join.animated))if(h.bool(t.join.animated))s.joinAnimated=t.join.animated;else throw h.invalidParameterError("join.animated","boolean",t.join.animated);if(h.defined(t.join.across))if(h.integer(t.join.across)&&h.inRange(t.join.across,1,1e6))s.joinAcross=t.join.across;else throw h.invalidParameterError("join.across","integer between 1 and 100000",t.join.across);if(h.defined(t.join.shim))if(h.integer(t.join.shim)&&h.inRange(t.join.shim,0,1e6))s.joinShim=t.join.shim;else throw h.invalidParameterError("join.shim","integer between 0 and 100000",t.join.shim);if(h.defined(t.join.background)&&(s.joinBackground=this._getBackgroundColourOption(t.join.background)),h.defined(t.join.halign))if(h.string(t.join.halign)&&h.string(this.constructor.align[t.join.halign]))s.joinHalign=this.constructor.align[t.join.halign];else throw h.invalidParameterError("join.halign","valid alignment",t.join.halign);if(h.defined(t.join.valign))if(h.string(t.join.valign)&&h.string(this.constructor.align[t.join.valign]))s.joinValign=this.constructor.align[t.join.valign];else throw h.invalidParameterError("join.valign","valid alignment",t.join.valign)}else throw new Error("Expected input to be an array of images to join")}else if(h.defined(t))throw new Error(`Invalid input options ${t}`);return s}function fc(e,t,r){Array.isArray(this.options.input.buffer)?h.buffer(e)?(this.options.input.buffer.length===0&&this.on("finish",()=>{this.streamInFinished=!0}),this.options.input.buffer.push(e),r()):r(new Error("Non-Buffer data on Writable Stream")):r(new Error("Unexpected data on Writable Stream"))}function hc(){this._isStreamInput()&&(this.options.input.buffer=Buffer.concat(this.options.input.buffer))}function dc(){return Array.isArray(this.options.input.buffer)}function pc(e){let t=Error();return h.fn(e)?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),Ve.metadata(this.options,(r,s)=>{r?e(h.nativeError(r,t)):e(null,s)})}):Ve.metadata(this.options,(r,s)=>{r?e(h.nativeError(r,t)):e(null,s)}),this):this._isStreamInput()?new Promise((r,s)=>{let n=()=>{this._flattenBufferIn(),Ve.metadata(this.options,(i,o)=>{i?s(h.nativeError(i,t)):r(o)})};this.writableFinished?n():this.once("finish",n)}):new Promise((r,s)=>{Ve.metadata(this.options,(n,i)=>{n?s(h.nativeError(n,t)):r(i)})})}function gc(e){let t=Error();return h.fn(e)?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),Ve.stats(this.options,(r,s)=>{r?e(h.nativeError(r,t)):e(null,s)})}):Ve.stats(this.options,(r,s)=>{r?e(h.nativeError(r,t)):e(null,s)}),this):this._isStreamInput()?new Promise((r,s)=>{this.on("finish",function(){this._flattenBufferIn(),Ve.stats(this.options,(n,i)=>{n?s(h.nativeError(n,t)):r(i)})})}):new Promise((r,s)=>{Ve.stats(this.options,(n,i)=>{n?s(h.nativeError(n,t)):r(i)})})}Xn.exports=e=>{Object.assign(e.prototype,{_inputOptionsFromObject:Jn,_createInputDescriptor:uc,_write:fc,_flattenBufferIn:hc,_isStreamInput:dc,metadata:pc,stats:gc}),e.align=lc}});var ri=D((gd,ti)=>{var x=Ne(),Qn={center:0,centre:0,north:1,east:2,south:3,west:4,northeast:5,southeast:6,southwest:7,northwest:8},Zn={top:1,right:2,bottom:3,left:4,"right top":5,"right bottom":6,"left bottom":7,"left top":8},Kn={background:"background",copy:"copy",repeat:"repeat",mirror:"mirror"},ei={entropy:16,attention:17},Fr={nearest:"nearest",linear:"linear",cubic:"cubic",mitchell:"mitchell",lanczos2:"lanczos2",lanczos3:"lanczos3",mks2013:"mks2013",mks2021:"mks2021"},mc={contain:"contain",cover:"cover",fill:"fill",inside:"inside",outside:"outside"},bc={contain:"embed",cover:"crop",fill:"ignore_aspect",inside:"max",outside:"min"};function Cr(e){return e.angle%360!==0||e.rotationAngle!==0}function Yt(e){return e.width!==-1||e.height!==-1}function vc(e,t,r){if(Yt(this.options)&&this.options.debuglog("ignoring previous resize options"),this.options.widthPost!==-1&&this.options.debuglog("operation order will be: extract, resize, extract"),x.defined(e))if(x.object(e)&&!x.defined(r))r=e;else if(x.integer(e)&&e>0)this.options.width=e;else throw x.invalidParameterError("width","positive integer",e);else this.options.width=-1;if(x.defined(t))if(x.integer(t)&&t>0)this.options.height=t;else throw x.invalidParameterError("height","positive integer",t);else this.options.height=-1;if(x.object(r)){if(x.defined(r.width))if(x.integer(r.width)&&r.width>0)this.options.width=r.width;else throw x.invalidParameterError("width","positive integer",r.width);if(x.defined(r.height))if(x.integer(r.height)&&r.height>0)this.options.height=r.height;else throw x.invalidParameterError("height","positive integer",r.height);if(x.defined(r.fit)){let s=bc[r.fit];if(x.string(s))this.options.canvas=s;else throw x.invalidParameterError("fit","valid fit",r.fit)}if(x.defined(r.position)){let s=x.integer(r.position)?r.position:ei[r.position]||Zn[r.position]||Qn[r.position];if(x.integer(s)&&(x.inRange(s,0,8)||x.inRange(s,16,17)))this.options.position=s;else throw x.invalidParameterError("position","valid position/gravity/strategy",r.position)}if(this._setBackgroundColourOption("resizeBackground",r.background),x.defined(r.kernel))if(x.string(Fr[r.kernel]))this.options.kernel=Fr[r.kernel];else throw x.invalidParameterError("kernel","valid kernel name",r.kernel);x.defined(r.withoutEnlargement)&&this._setBooleanOption("withoutEnlargement",r.withoutEnlargement),x.defined(r.withoutReduction)&&this._setBooleanOption("withoutReduction",r.withoutReduction),x.defined(r.fastShrinkOnLoad)&&this._setBooleanOption("fastShrinkOnLoad",r.fastShrinkOnLoad)}return Cr(this.options)&&Yt(this.options)&&(this.options.rotateBefore=!0),this}function yc(e){if(x.integer(e)&&e>0)this.options.extendTop=e,this.options.extendBottom=e,this.options.extendLeft=e,this.options.extendRight=e;else if(x.object(e)){if(x.defined(e.top))if(x.integer(e.top)&&e.top>=0)this.options.extendTop=e.top;else throw x.invalidParameterError("top","positive integer",e.top);if(x.defined(e.bottom))if(x.integer(e.bottom)&&e.bottom>=0)this.options.extendBottom=e.bottom;else throw x.invalidParameterError("bottom","positive integer",e.bottom);if(x.defined(e.left))if(x.integer(e.left)&&e.left>=0)this.options.extendLeft=e.left;else throw x.invalidParameterError("left","positive integer",e.left);if(x.defined(e.right))if(x.integer(e.right)&&e.right>=0)this.options.extendRight=e.right;else throw x.invalidParameterError("right","positive integer",e.right);if(this._setBackgroundColourOption("extendBackground",e.background),x.defined(e.extendWith))if(x.string(Kn[e.extendWith]))this.options.extendWith=Kn[e.extendWith];else throw x.invalidParameterError("extendWith","one of: background, copy, repeat, mirror",e.extendWith)}else throw x.invalidParameterError("extend","integer or object",e);return this}function wc(e){let t=Yt(this.options)||this.options.widthPre!==-1?"Post":"Pre";return this.options[`width${t}`]!==-1&&this.options.debuglog("ignoring previous extract options"),["left","top","width","height"].forEach(function(r){let s=e[r];if(x.integer(s)&&s>=0)this.options[r+(r==="left"||r==="top"?"Offset":"")+t]=s;else throw x.invalidParameterError(r,"integer",s)},this),Cr(this.options)&&!Yt(this.options)&&(this.options.widthPre===-1||this.options.widthPost===-1)&&(this.options.rotateBefore=!0),this.options.input.autoOrient&&(this.options.orientBefore=!0),this}function Ec(e){if(this.options.trimThreshold=10,x.defined(e))if(x.object(e)){if(x.defined(e.background)&&this._setBackgroundColourOption("trimBackground",e.background),x.defined(e.threshold))if(x.number(e.threshold)&&e.threshold>=0)this.options.trimThreshold=e.threshold;else throw x.invalidParameterError("threshold","positive number",e.threshold);x.defined(e.lineArt)&&this._setBooleanOption("trimLineArt",e.lineArt)}else throw x.invalidParameterError("trim","object",e);return Cr(this.options)&&(this.options.rotateBefore=!0),this}ti.exports=e=>{Object.assign(e.prototype,{resize:vc,extend:yc,extract:wc,trim:Ec}),e.gravity=Qn,e.strategy=ei,e.kernel=Fr,e.fit=mc,e.position=Zn}});var ni=D((md,si)=>{var q=Ne(),Or={clear:"clear",source:"source",over:"over",in:"in",out:"out",atop:"atop",dest:"dest","dest-over":"dest-over","dest-in":"dest-in","dest-out":"dest-out","dest-atop":"dest-atop",xor:"xor",add:"add",saturate:"saturate",multiply:"multiply",screen:"screen",overlay:"overlay",darken:"darken",lighten:"lighten","colour-dodge":"colour-dodge","color-dodge":"colour-dodge","colour-burn":"colour-burn","color-burn":"colour-burn","hard-light":"hard-light","soft-light":"soft-light",difference:"difference",exclusion:"exclusion"};function xc(e){if(!Array.isArray(e))throw q.invalidParameterError("images to composite","array",e);return this.options.composite=e.map(t=>{if(!q.object(t))throw q.invalidParameterError("image to composite","object",t);let r=this._inputOptionsFromObject(t),s={input:this._createInputDescriptor(t.input,r,{allowStream:!1}),blend:"over",tile:!1,left:0,top:0,hasOffset:!1,gravity:0,premultiplied:!1};if(q.defined(t.blend))if(q.string(Or[t.blend]))s.blend=Or[t.blend];else throw q.invalidParameterError("blend","valid blend name",t.blend);if(q.defined(t.tile))if(q.bool(t.tile))s.tile=t.tile;else throw q.invalidParameterError("tile","boolean",t.tile);if(q.defined(t.left))if(q.integer(t.left))s.left=t.left;else throw q.invalidParameterError("left","integer",t.left);if(q.defined(t.top))if(q.integer(t.top))s.top=t.top;else throw q.invalidParameterError("top","integer",t.top);if(q.defined(t.top)!==q.defined(t.left))throw new Error("Expected both left and top to be set");if(s.hasOffset=q.integer(t.top)&&q.integer(t.left),q.defined(t.gravity))if(q.integer(t.gravity)&&q.inRange(t.gravity,0,8))s.gravity=t.gravity;else if(q.string(t.gravity)&&q.integer(this.constructor.gravity[t.gravity]))s.gravity=this.constructor.gravity[t.gravity];else throw q.invalidParameterError("gravity","valid gravity",t.gravity);if(q.defined(t.premultiplied))if(q.bool(t.premultiplied))s.premultiplied=t.premultiplied;else throw q.invalidParameterError("premultiplied","boolean",t.premultiplied);return s}),this}si.exports=e=>{e.prototype.composite=xc,e.blend=Or}});var ci=D((bd,li)=>{var p=Ne(),ii={integer:"integer",float:"float",approximate:"approximate"};function Pc(e,t){if(!p.defined(e))return this.autoOrient();if((this.options.angle||this.options.rotationAngle)&&(this.options.debuglog("ignoring previous rotate options"),this.options.angle=0,this.options.rotationAngle=0),p.integer(e)&&!(e%90))this.options.angle=e;else if(p.number(e))this.options.rotationAngle=e,p.object(t)&&t.background&&this._setBackgroundColourOption("rotationBackground",t.background);else throw p.invalidParameterError("angle","numeric",e);return this}function Sc(){return this.options.input.autoOrient=!0,this}function Rc(e){return this.options.flip=p.bool(e)?e:!0,this}function $c(e){return this.options.flop=p.bool(e)?e:!0,this}function kc(e,t){let r=[].concat(...e);if(r.length===4&&r.every(p.number))this.options.affineMatrix=r;else throw p.invalidParameterError("matrix","1x4 or 2x2 array",e);if(p.defined(t))if(p.object(t)){if(this._setBackgroundColourOption("affineBackground",t.background),p.defined(t.idx))if(p.number(t.idx))this.options.affineIdx=t.idx;else throw p.invalidParameterError("options.idx","number",t.idx);if(p.defined(t.idy))if(p.number(t.idy))this.options.affineIdy=t.idy;else throw p.invalidParameterError("options.idy","number",t.idy);if(p.defined(t.odx))if(p.number(t.odx))this.options.affineOdx=t.odx;else throw p.invalidParameterError("options.odx","number",t.odx);if(p.defined(t.ody))if(p.number(t.ody))this.options.affineOdy=t.ody;else throw p.invalidParameterError("options.ody","number",t.ody);if(p.defined(t.interpolator))if(p.inArray(t.interpolator,Object.values(this.constructor.interpolators)))this.options.affineInterpolator=t.interpolator;else throw p.invalidParameterError("options.interpolator","valid interpolator name",t.interpolator)}else throw p.invalidParameterError("options","object",t);return this}function Ac(e,t,r){if(!p.defined(e))this.options.sharpenSigma=-1;else if(p.bool(e))this.options.sharpenSigma=e?-1:0;else if(p.number(e)&&p.inRange(e,.01,1e4)){if(this.options.sharpenSigma=e,p.defined(t))if(p.number(t)&&p.inRange(t,0,1e4))this.options.sharpenM1=t;else throw p.invalidParameterError("flat","number between 0 and 10000",t);if(p.defined(r))if(p.number(r)&&p.inRange(r,0,1e4))this.options.sharpenM2=r;else throw p.invalidParameterError("jagged","number between 0 and 10000",r)}else if(p.plainObject(e)){if(p.number(e.sigma)&&p.inRange(e.sigma,1e-6,10))this.options.sharpenSigma=e.sigma;else throw p.invalidParameterError("options.sigma","number between 0.000001 and 10",e.sigma);if(p.defined(e.m1))if(p.number(e.m1)&&p.inRange(e.m1,0,1e6))this.options.sharpenM1=e.m1;else throw p.invalidParameterError("options.m1","number between 0 and 1000000",e.m1);if(p.defined(e.m2))if(p.number(e.m2)&&p.inRange(e.m2,0,1e6))this.options.sharpenM2=e.m2;else throw p.invalidParameterError("options.m2","number between 0 and 1000000",e.m2);if(p.defined(e.x1))if(p.number(e.x1)&&p.inRange(e.x1,0,1e6))this.options.sharpenX1=e.x1;else throw p.invalidParameterError("options.x1","number between 0 and 1000000",e.x1);if(p.defined(e.y2))if(p.number(e.y2)&&p.inRange(e.y2,0,1e6))this.options.sharpenY2=e.y2;else throw p.invalidParameterError("options.y2","number between 0 and 1000000",e.y2);if(p.defined(e.y3))if(p.number(e.y3)&&p.inRange(e.y3,0,1e6))this.options.sharpenY3=e.y3;else throw p.invalidParameterError("options.y3","number between 0 and 1000000",e.y3)}else throw p.invalidParameterError("sigma","number between 0.01 and 10000",e);return this}function _c(e){if(!p.defined(e))this.options.medianSize=3;else if(p.integer(e)&&p.inRange(e,1,1e3))this.options.medianSize=e;else throw p.invalidParameterError("size","integer between 1 and 1000",e);return this}function Nc(e){let t;if(p.number(e))t=e;else if(p.plainObject(e)){if(!p.number(e.sigma))throw p.invalidParameterError("options.sigma","number between 0.3 and 1000",t);if(t=e.sigma,"precision"in e)if(p.string(ii[e.precision]))this.options.precision=ii[e.precision];else throw p.invalidParameterError("precision","one of: integer, float, approximate",e.precision);if("minAmplitude"in e)if(p.number(e.minAmplitude)&&p.inRange(e.minAmplitude,.001,1))this.options.minAmpl=e.minAmplitude;else throw p.invalidParameterError("minAmplitude","number between 0.001 and 1",e.minAmplitude)}if(!p.defined(e))this.options.blurSigma=-1;else if(p.bool(e))this.options.blurSigma=e?-1:0;else if(p.number(t)&&p.inRange(t,.3,1e3))this.options.blurSigma=t;else throw p.invalidParameterError("sigma","number between 0.3 and 1000",t);return this}function oi(e){if(!p.defined(e))this.options.dilateWidth=1;else if(p.integer(e)&&e>0)this.options.dilateWidth=e;else throw p.invalidParameterError("dilate","positive integer",oi);return this}function ai(e){if(!p.defined(e))this.options.erodeWidth=1;else if(p.integer(e)&&e>0)this.options.erodeWidth=e;else throw p.invalidParameterError("erode","positive integer",ai);return this}function Ic(e){return this.options.flatten=p.bool(e)?e:!0,p.object(e)&&this._setBackgroundColourOption("flattenBackground",e.background),this}function Dc(){return this.options.unflatten=!0,this}function Tc(e,t){if(!p.defined(e))this.options.gamma=2.2;else if(p.number(e)&&p.inRange(e,1,3))this.options.gamma=e;else throw p.invalidParameterError("gamma","number between 1.0 and 3.0",e);if(!p.defined(t))this.options.gammaOut=this.options.gamma;else if(p.number(t)&&p.inRange(t,1,3))this.options.gammaOut=t;else throw p.invalidParameterError("gammaOut","number between 1.0 and 3.0",t);return this}function Fc(e){if(this.options.negate=p.bool(e)?e:!0,p.plainObject(e)&&"alpha"in e)if(p.bool(e.alpha))this.options.negateAlpha=e.alpha;else throw p.invalidParameterError("alpha","should be boolean value",e.alpha);return this}function Cc(e){if(p.plainObject(e)){if(p.defined(e.lower))if(p.number(e.lower)&&p.inRange(e.lower,0,99))this.options.normaliseLower=e.lower;else throw p.invalidParameterError("lower","number between 0 and 99",e.lower);if(p.defined(e.upper))if(p.number(e.upper)&&p.inRange(e.upper,1,100))this.options.normaliseUpper=e.upper;else throw p.invalidParameterError("upper","number between 1 and 100",e.upper)}if(this.options.normaliseLower>=this.options.normaliseUpper)throw p.invalidParameterError("range","lower to be less than upper",`${this.options.normaliseLower} >= ${this.options.normaliseUpper}`);return this.options.normalise=!0,this}function Oc(e){return this.normalise(e)}function jc(e){if(p.plainObject(e)){if(p.integer(e.width)&&e.width>0)this.options.claheWidth=e.width;else throw p.invalidParameterError("width","integer greater than zero",e.width);if(p.integer(e.height)&&e.height>0)this.options.claheHeight=e.height;else throw p.invalidParameterError("height","integer greater than zero",e.height);if(p.defined(e.maxSlope))if(p.integer(e.maxSlope)&&p.inRange(e.maxSlope,0,100))this.options.claheMaxSlope=e.maxSlope;else throw p.invalidParameterError("maxSlope","integer between 0 and 100",e.maxSlope)}else throw p.invalidParameterError("options","plain object",e);return this}function Lc(e){if(!p.object(e)||!Array.isArray(e.kernel)||!p.integer(e.width)||!p.integer(e.height)||!p.inRange(e.width,3,1001)||!p.inRange(e.height,3,1001)||e.height*e.width!==e.kernel.length)throw new Error("Invalid convolution kernel");return p.integer(e.scale)||(e.scale=e.kernel.reduce((t,r)=>t+r,0)),e.scale<1&&(e.scale=1),p.integer(e.offset)||(e.offset=0),this.options.convKernel=e,this}function Mc(e,t){if(!p.defined(e))this.options.threshold=128;else if(p.bool(e))this.options.threshold=e?128:0;else if(p.integer(e)&&p.inRange(e,0,255))this.options.threshold=e;else throw p.invalidParameterError("threshold","integer between 0 and 255",e);return!p.object(t)||t.greyscale===!0||t.grayscale===!0?this.options.thresholdGrayscale=!0:this.options.thresholdGrayscale=!1,this}function zc(e,t,r){if(this.options.boolean=this._createInputDescriptor(e,r),p.string(t)&&p.inArray(t,["and","or","eor"]))this.options.booleanOp=t;else throw p.invalidParameterError("operator","one of: and, or, eor",t);return this}function Bc(e,t){if(!p.defined(e)&&p.number(t)?e=1:p.number(e)&&!p.defined(t)&&(t=0),!p.defined(e))this.options.linearA=[];else if(p.number(e))this.options.linearA=[e];else if(Array.isArray(e)&&e.length&&e.every(p.number))this.options.linearA=e;else throw p.invalidParameterError("a","number or array of numbers",e);if(!p.defined(t))this.options.linearB=[];else if(p.number(t))this.options.linearB=[t];else if(Array.isArray(t)&&t.length&&t.every(p.number))this.options.linearB=t;else throw p.invalidParameterError("b","number or array of numbers",t);if(this.options.linearA.length!==this.options.linearB.length)throw new Error("Expected a and b to be arrays of the same length");return this}function Uc(e){if(!Array.isArray(e))throw p.invalidParameterError("inputMatrix","array",e);if(e.length!==3&&e.length!==4)throw p.invalidParameterError("inputMatrix","3x3 or 4x4 array",e.length);let t=e.flat().map(Number);if(t.length!==9&&t.length!==16)throw p.invalidParameterError("inputMatrix","cardinality of 9 or 16",t.length);return this.options.recombMatrix=t,this}function Gc(e){if(!p.plainObject(e))throw p.invalidParameterError("options","plain object",e);if("brightness"in e)if(p.number(e.brightness)&&e.brightness>=0)this.options.brightness=e.brightness;else throw p.invalidParameterError("brightness","number above zero",e.brightness);if("saturation"in e)if(p.number(e.saturation)&&e.saturation>=0)this.options.saturation=e.saturation;else throw p.invalidParameterError("saturation","number above zero",e.saturation);if("hue"in e)if(p.integer(e.hue))this.options.hue=e.hue%360;else throw p.invalidParameterError("hue","number",e.hue);if("lightness"in e)if(p.number(e.lightness))this.options.lightness=e.lightness;else throw p.invalidParameterError("lightness","number",e.lightness);return this}li.exports=e=>{Object.assign(e.prototype,{autoOrient:Sc,rotate:Pc,flip:Rc,flop:$c,affine:kc,sharpen:Ac,erode:ai,dilate:oi,median:_c,blur:Nc,flatten:Ic,unflatten:Dc,gamma:Tc,negate:Fc,normalise:Cc,normalize:Oc,clahe:jc,convolve:Lc,threshold:Mc,boolean:zc,linear:Bc,recomb:Uc,modulate:Gc})}});var gi=D((vd,pi)=>{var zr=Object.defineProperty,qc=Object.getOwnPropertyDescriptor,Wc=Object.getOwnPropertyNames,Hc=Object.prototype.hasOwnProperty,Vc=(e,t)=>{for(var r in t)zr(e,r,{get:t[r],enumerable:!0})},Jc=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Wc(t))!Hc.call(e,n)&&n!==r&&zr(e,n,{get:()=>t[n],enumerable:!(s=qc(t,n))||s.enumerable});return e},Xc=e=>Jc(zr({},"__esModule",{value:!0}),e),ui={};Vc(ui,{default:()=>cu});pi.exports=Xc(ui);var Ce={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},fi=Object.create(null);for(let e in Ce)Object.hasOwn(Ce,e)&&(fi[Ce[e]]=e);var de={to:{},get:{}};de.get=function(e){let t=e.slice(0,3).toLowerCase(),r,s;switch(t){case"hsl":{r=de.get.hsl(e),s="hsl";break}case"hwb":{r=de.get.hwb(e),s="hwb";break}default:{r=de.get.rgb(e),s="rgb";break}}return r?{model:s,value:r}:null};de.get.rgb=function(e){if(!e)return null;let t=/^#([a-f\d]{3,4})$/i,r=/^#([a-f\d]{6})([a-f\d]{2})?$/i,s=/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/,n=/^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/,i=/^(\w+)$/,o=[0,0,0,1],a,l,u;if(a=e.match(r)){for(u=a[2],a=a[1],l=0;l<3;l++){let f=l*2;o[l]=Number.parseInt(a.slice(f,f+2),16)}u&&(o[3]=Number.parseInt(u,16)/255)}else if(a=e.match(t)){for(a=a[1],u=a[3],l=0;l<3;l++)o[l]=Number.parseInt(a[l]+a[l],16);u&&(o[3]=Number.parseInt(u+u,16)/255)}else if(a=e.match(s)){for(l=0;l<3;l++)o[l]=Number.parseInt(a[l+1],10);a[4]&&(o[3]=a[5]?Number.parseFloat(a[4])*.01:Number.parseFloat(a[4]))}else if(a=e.match(n)){for(l=0;l<3;l++)o[l]=Math.round(Number.parseFloat(a[l+1])*2.55);a[4]&&(o[3]=a[5]?Number.parseFloat(a[4])*.01:Number.parseFloat(a[4]))}else return(a=e.match(i))?a[1]==="transparent"?[0,0,0,0]:Object.hasOwn(Ce,a[1])?(o=Ce[a[1]],o[3]=1,o):null:null;for(l=0;l<3;l++)o[l]=Je(o[l],0,255);return o[3]=Je(o[3],0,1),o};de.get.hsl=function(e){if(!e)return null;let t=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=e.match(t);if(r){let s=Number.parseFloat(r[4]),n=(Number.parseFloat(r[1])%360+360)%360,i=Je(Number.parseFloat(r[2]),0,100),o=Je(Number.parseFloat(r[3]),0,100),a=Je(Number.isNaN(s)?1:s,0,1);return[n,i,o,a]}return null};de.get.hwb=function(e){if(!e)return null;let t=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=e.match(t);if(r){let s=Number.parseFloat(r[4]),n=(Number.parseFloat(r[1])%360+360)%360,i=Je(Number.parseFloat(r[2]),0,100),o=Je(Number.parseFloat(r[3]),0,100),a=Je(Number.isNaN(s)?1:s,0,1);return[n,i,o,a]}return null};de.to.hex=function(...e){return"#"+Kt(e[0])+Kt(e[1])+Kt(e[2])+(e[3]<1?Kt(Math.round(e[3]*255)):"")};de.to.rgb=function(...e){return e.length<4||e[3]===1?"rgb("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+")":"rgba("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+", "+e[3]+")"};de.to.rgb.percent=function(...e){let t=Math.round(e[0]/255*100),r=Math.round(e[1]/255*100),s=Math.round(e[2]/255*100);return e.length<4||e[3]===1?"rgb("+t+"%, "+r+"%, "+s+"%)":"rgba("+t+"%, "+r+"%, "+s+"%, "+e[3]+")"};de.to.hsl=function(...e){return e.length<4||e[3]===1?"hsl("+e[0]+", "+e[1]+"%, "+e[2]+"%)":"hsla("+e[0]+", "+e[1]+"%, "+e[2]+"%, "+e[3]+")"};de.to.hwb=function(...e){let t="";return e.length>=4&&e[3]!==1&&(t=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+t+")"};de.to.keyword=function(...e){return fi[e.slice(0,3)]};function Je(e,t,r){return Math.min(Math.max(t,e),r)}function Kt(e){let t=Math.round(e).toString(16).toUpperCase();return t.length<2?"0"+t:t}var ft=de,hi={};for(let e of Object.keys(Ce))hi[Ce[e]]=e;var v={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},oklab:{channels:3,labels:["okl","oka","okb"]},lch:{channels:3,labels:"lch"},oklch:{channels:3,labels:["okl","okc","okh"]},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}},nt=v,ze=(6/29)**3;function dt(e){let t=e>.0031308?1.055*e**.4166666666666667-.055:e*12.92;return Math.min(Math.max(0,t),1)}function pt(e){return e>.04045?((e+.055)/1.055)**2.4:e/12.92}for(let e of Object.keys(v)){if(!("channels"in v[e]))throw new Error("missing channels property: "+e);if(!("labels"in v[e]))throw new Error("missing channel labels property: "+e);if(v[e].labels.length!==v[e].channels)throw new Error("channel and label counts mismatch: "+e);let{channels:t,labels:r}=v[e];delete v[e].channels,delete v[e].labels,Object.defineProperty(v[e],"channels",{value:t}),Object.defineProperty(v[e],"labels",{value:r})}v.rgb.hsl=function(e){let t=e[0]/255,r=e[1]/255,s=e[2]/255,n=Math.min(t,r,s),i=Math.max(t,r,s),o=i-n,a,l;switch(i){case n:{a=0;break}case t:{a=(r-s)/o;break}case r:{a=2+(s-t)/o;break}case s:{a=4+(t-r)/o;break}}a=Math.min(a*60,360),a<0&&(a+=360);let u=(n+i)/2;return i===n?l=0:u<=.5?l=o/(i+n):l=o/(2-i-n),[a,l*100,u*100]};v.rgb.hsv=function(e){let t,r,s,n,i,o=e[0]/255,a=e[1]/255,l=e[2]/255,u=Math.max(o,a,l),f=u-Math.min(o,a,l),d=function(g){return(u-g)/6/f+1/2};if(f===0)n=0,i=0;else{switch(i=f/u,t=d(o),r=d(a),s=d(l),u){case o:{n=s-r;break}case a:{n=1/3+t-s;break}case l:{n=2/3+r-t;break}}n<0?n+=1:n>1&&(n-=1)}return[n*360,i*100,u*100]};v.rgb.hwb=function(e){let t=e[0],r=e[1],s=e[2],n=v.rgb.hsl(e)[0],i=1/255*Math.min(t,Math.min(r,s));return s=1-1/255*Math.max(t,Math.max(r,s)),[n,i*100,s*100]};v.rgb.oklab=function(e){let t=pt(e[0]/255),r=pt(e[1]/255),s=pt(e[2]/255),n=Math.cbrt(.4122214708*t+.5363325363*r+.0514459929*s),i=Math.cbrt(.2119034982*t+.6806995451*r+.1073969566*s),o=Math.cbrt(.0883024619*t+.2817188376*r+.6299787005*s),a=.2104542553*n+.793617785*i-.0040720468*o,l=1.9779984951*n-2.428592205*i+.4505937099*o,u=.0259040371*n+.7827717662*i-.808675766*o;return[a*100,l*100,u*100]};v.rgb.cmyk=function(e){let t=e[0]/255,r=e[1]/255,s=e[2]/255,n=Math.min(1-t,1-r,1-s),i=(1-t-n)/(1-n)||0,o=(1-r-n)/(1-n)||0,a=(1-s-n)/(1-n)||0;return[i*100,o*100,a*100,n*100]};function Yc(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}v.rgb.keyword=function(e){let t=hi[e];if(t)return t;let r=Number.POSITIVE_INFINITY,s;for(let n of Object.keys(Ce)){let i=Ce[n],o=Yc(e,i);o<r&&(r=o,s=n)}return s};v.keyword.rgb=function(e){return Ce[e]};v.rgb.xyz=function(e){let t=pt(e[0]/255),r=pt(e[1]/255),s=pt(e[2]/255),n=t*.4124564+r*.3575761+s*.1804375,i=t*.2126729+r*.7151522+s*.072175,o=t*.0193339+r*.119192+s*.9503041;return[n*100,i*100,o*100]};v.rgb.lab=function(e){let t=v.rgb.xyz(e),r=t[0],s=t[1],n=t[2];r/=95.047,s/=100,n/=108.883,r=r>ze?r**(1/3):7.787*r+16/116,s=s>ze?s**(1/3):7.787*s+16/116,n=n>ze?n**(1/3):7.787*n+16/116;let i=116*s-16,o=500*(r-s),a=200*(s-n);return[i,o,a]};v.hsl.rgb=function(e){let t=e[0]/360,r=e[1]/100,s=e[2]/100,n,i;if(r===0)return i=s*255,[i,i,i];let o=s<.5?s*(1+r):s+r-s*r,a=2*s-o,l=[0,0,0];for(let u=0;u<3;u++)n=t+1/3*-(u-1),n<0&&n++,n>1&&n--,6*n<1?i=a+(o-a)*6*n:2*n<1?i=o:3*n<2?i=a+(o-a)*(2/3-n)*6:i=a,l[u]=i*255;return l};v.hsl.hsv=function(e){let t=e[0],r=e[1]/100,s=e[2]/100,n=r,i=Math.max(s,.01);s*=2,r*=s<=1?s:2-s,n*=i<=1?i:2-i;let o=(s+r)/2,a=s===0?2*n/(i+n):2*r/(s+r);return[t,a*100,o*100]};v.hsv.rgb=function(e){let t=e[0]/60,r=e[1]/100,s=e[2]/100,n=Math.floor(t)%6,i=t-Math.floor(t),o=255*s*(1-r),a=255*s*(1-r*i),l=255*s*(1-r*(1-i));switch(s*=255,n){case 0:return[s,l,o];case 1:return[a,s,o];case 2:return[o,s,l];case 3:return[o,a,s];case 4:return[l,o,s];case 5:return[s,o,a]}};v.hsv.hsl=function(e){let t=e[0],r=e[1]/100,s=e[2]/100,n=Math.max(s,.01),i,o;o=(2-r)*s;let a=(2-r)*n;return i=r*n,i/=a<=1?a:2-a,i=i||0,o/=2,[t,i*100,o*100]};v.hwb.rgb=function(e){let t=e[0]/360,r=e[1]/100,s=e[2]/100,n=r+s,i;n>1&&(r/=n,s/=n);let o=Math.floor(6*t),a=1-s;i=6*t-o,(o&1)!==0&&(i=1-i);let l=r+i*(a-r),u,f,d;switch(o){default:case 6:case 0:{u=a,f=l,d=r;break}case 1:{u=l,f=a,d=r;break}case 2:{u=r,f=a,d=l;break}case 3:{u=r,f=l,d=a;break}case 4:{u=l,f=r,d=a;break}case 5:{u=a,f=r,d=l;break}}return[u*255,f*255,d*255]};v.cmyk.rgb=function(e){let t=e[0]/100,r=e[1]/100,s=e[2]/100,n=e[3]/100,i=1-Math.min(1,t*(1-n)+n),o=1-Math.min(1,r*(1-n)+n),a=1-Math.min(1,s*(1-n)+n);return[i*255,o*255,a*255]};v.xyz.rgb=function(e){let t=e[0]/100,r=e[1]/100,s=e[2]/100,n,i,o;return n=t*3.2404542+r*-1.5371385+s*-.4985314,i=t*-.969266+r*1.8760108+s*.041556,o=t*.0556434+r*-.2040259+s*1.0572252,n=dt(n),i=dt(i),o=dt(o),[n*255,i*255,o*255]};v.xyz.lab=function(e){let t=e[0],r=e[1],s=e[2];t/=95.047,r/=100,s/=108.883,t=t>ze?t**(1/3):7.787*t+16/116,r=r>ze?r**(1/3):7.787*r+16/116,s=s>ze?s**(1/3):7.787*s+16/116;let n=116*r-16,i=500*(t-r),o=200*(r-s);return[n,i,o]};v.xyz.oklab=function(e){let t=e[0]/100,r=e[1]/100,s=e[2]/100,n=Math.cbrt(.8189330101*t+.3618667424*r-.1288597137*s),i=Math.cbrt(.0329845436*t+.9293118715*r+.0361456387*s),o=Math.cbrt(.0482003018*t+.2643662691*r+.633851707*s),a=.2104542553*n+.793617785*i-.0040720468*o,l=1.9779984951*n-2.428592205*i+.4505937099*o,u=.0259040371*n+.7827717662*i-.808675766*o;return[a*100,l*100,u*100]};v.oklab.oklch=function(e){return v.lab.lch(e)};v.oklab.xyz=function(e){let t=e[0]/100,r=e[1]/100,s=e[2]/100,n=(.999999998*t+.396337792*r+.215803758*s)**3,i=(1.000000008*t-.105561342*r-.063854175*s)**3,o=(1.000000055*t-.089484182*r-1.291485538*s)**3,a=1.227013851*n-.55779998*i+.281256149*o,l=-.040580178*n+1.11225687*i-.071676679*o,u=-.076381285*n-.421481978*i+1.58616322*o;return[a*100,l*100,u*100]};v.oklab.rgb=function(e){let t=e[0]/100,r=e[1]/100,s=e[2]/100,n=(t+.3963377774*r+.2158037573*s)**3,i=(t-.1055613458*r-.0638541728*s)**3,o=(t-.0894841775*r-1.291485548*s)**3,a=dt(4.0767416621*n-3.3077115913*i+.2309699292*o),l=dt(-1.2684380046*n+2.6097574011*i-.3413193965*o),u=dt(-.0041960863*n-.7034186147*i+1.707614701*o);return[a*255,l*255,u*255]};v.oklch.oklab=function(e){return v.lch.lab(e)};v.lab.xyz=function(e){let t=e[0],r=e[1],s=e[2],n,i,o;i=(t+16)/116,n=r/500+i,o=i-s/200;let a=i**3,l=n**3,u=o**3;return i=a>ze?a:(i-16/116)/7.787,n=l>ze?l:(n-16/116)/7.787,o=u>ze?u:(o-16/116)/7.787,n*=95.047,i*=100,o*=108.883,[n,i,o]};v.lab.lch=function(e){let t=e[0],r=e[1],s=e[2],n;n=Math.atan2(s,r)*360/2/Math.PI,n<0&&(n+=360);let o=Math.sqrt(r*r+s*s);return[t,o,n]};v.lch.lab=function(e){let t=e[0],r=e[1],n=e[2]/360*2*Math.PI,i=r*Math.cos(n),o=r*Math.sin(n);return[t,i,o]};v.rgb.ansi16=function(e,t=null){let[r,s,n]=e,i=t===null?v.rgb.hsv(e)[2]:t;if(i=Math.round(i/50),i===0)return 30;let o=30+(Math.round(n/255)<<2|Math.round(s/255)<<1|Math.round(r/255));return i===2&&(o+=60),o};v.hsv.ansi16=function(e){return v.rgb.ansi16(v.hsv.rgb(e),e[2])};v.rgb.ansi256=function(e){let t=e[0],r=e[1],s=e[2];return t>>4===r>>4&&r>>4===s>>4?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(s/255*5)};v.ansi16.rgb=function(e){e=e[0];let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let r=(Math.trunc(e>50)+1)*.5,s=(t&1)*r*255,n=(t>>1&1)*r*255,i=(t>>2&1)*r*255;return[s,n,i]};v.ansi256.rgb=function(e){if(e=e[0],e>=232){let i=(e-232)*10+8;return[i,i,i]}e-=16;let t,r=Math.floor(e/36)/5*255,s=Math.floor((t=e%36)/6)/5*255,n=t%6/5*255;return[r,s,n]};v.rgb.hex=function(e){let r=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return"000000".slice(r.length)+r};v.hex.rgb=function(e){let t=e.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i);if(!t)return[0,0,0];let r=t[0];t[0].length===3&&(r=[...r].map(a=>a+a).join(""));let s=Number.parseInt(r,16),n=s>>16&255,i=s>>8&255,o=s&255;return[n,i,o]};v.rgb.hcg=function(e){let t=e[0]/255,r=e[1]/255,s=e[2]/255,n=Math.max(Math.max(t,r),s),i=Math.min(Math.min(t,r),s),o=n-i,a,l=o<1?i/(1-o):0;return o<=0?a=0:n===t?a=(r-s)/o%6:n===r?a=2+(s-t)/o:a=4+(t-r)/o,a/=6,a%=1,[a*360,o*100,l*100]};v.hsl.hcg=function(e){let t=e[1]/100,r=e[2]/100,s=r<.5?2*t*r:2*t*(1-r),n=0;return s<1&&(n=(r-.5*s)/(1-s)),[e[0],s*100,n*100]};v.hsv.hcg=function(e){let t=e[1]/100,r=e[2]/100,s=t*r,n=0;return s<1&&(n=(r-s)/(1-s)),[e[0],s*100,n*100]};v.hcg.rgb=function(e){let t=e[0]/360,r=e[1]/100,s=e[2]/100;if(r===0)return[s*255,s*255,s*255];let n=[0,0,0],i=t%1*6,o=i%1,a=1-o,l=0;switch(Math.floor(i)){case 0:{n[0]=1,n[1]=o,n[2]=0;break}case 1:{n[0]=a,n[1]=1,n[2]=0;break}case 2:{n[0]=0,n[1]=1,n[2]=o;break}case 3:{n[0]=0,n[1]=a,n[2]=1;break}case 4:{n[0]=o,n[1]=0,n[2]=1;break}default:n[0]=1,n[1]=0,n[2]=a}return l=(1-r)*s,[(r*n[0]+l)*255,(r*n[1]+l)*255,(r*n[2]+l)*255]};v.hcg.hsv=function(e){let t=e[1]/100,r=e[2]/100,s=t+r*(1-t),n=0;return s>0&&(n=t/s),[e[0],n*100,s*100]};v.hcg.hsl=function(e){let t=e[1]/100,s=e[2]/100*(1-t)+.5*t,n=0;return s>0&&s<.5?n=t/(2*s):s>=.5&&s<1&&(n=t/(2*(1-s))),[e[0],n*100,s*100]};v.hcg.hwb=function(e){let t=e[1]/100,r=e[2]/100,s=t+r*(1-t);return[e[0],(s-t)*100,(1-s)*100]};v.hwb.hcg=function(e){let t=e[1]/100,s=1-e[2]/100,n=s-t,i=0;return n<1&&(i=(s-n)/(1-n)),[e[0],n*100,i*100]};v.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]};v.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]};v.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]};v.gray.hsl=function(e){return[0,0,e[0]]};v.gray.hsv=v.gray.hsl;v.gray.hwb=function(e){return[0,100,e[0]]};v.gray.cmyk=function(e){return[0,0,0,e[0]]};v.gray.lab=function(e){return[e[0],0,0]};v.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,s=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".slice(s.length)+s};v.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]};function Kc(){let e={},t=Object.keys(nt);for(let{length:r}=t,s=0;s<r;s++)e[t[s]]={distance:-1,parent:null};return e}function Qc(e){let t=Kc(),r=[e];for(t[e].distance=0;r.length>0;){let s=r.pop(),n=Object.keys(nt[s]);for(let{length:i}=n,o=0;o<i;o++){let a=n[o],l=t[a];l.distance===-1&&(l.distance=t[s].distance+1,l.parent=s,r.unshift(a))}}return t}function Zc(e,t){return function(r){return t(e(r))}}function eu(e,t){let r=[t[e].parent,e],s=nt[t[e].parent][e],n=t[e].parent;for(;t[n].parent;)r.unshift(t[n].parent),s=Zc(nt[t[n].parent][n],s),n=t[n].parent;return s.conversion=r,s}function tu(e){let t=Qc(e),r={},s=Object.keys(t);for(let{length:n}=s,i=0;i<n;i++){let o=s[i];t[o].parent!==null&&(r[o]=eu(o,t))}return r}var ru=tu,ht={},su=Object.keys(nt);function nu(e){let t=function(...r){let s=r[0];return s==null?s:(s.length>1&&(r=s),e(r))};return"conversion"in e&&(t.conversion=e.conversion),t}function iu(e){let t=function(...r){let s=r[0];if(s==null)return s;s.length>1&&(r=s);let n=e(r);if(typeof n=="object")for(let{length:i}=n,o=0;o<i;o++)n[o]=Math.round(n[o]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}for(let e of su){ht[e]={},Object.defineProperty(ht[e],"channels",{value:nt[e].channels}),Object.defineProperty(ht[e],"labels",{value:nt[e].labels});let t=ru(e),r=Object.keys(t);for(let s of r){let n=t[s];ht[e][s]=iu(n),ht[e][s].raw=nu(n)}}var me=ht,di=["keyword","gray","hex"],jr={};for(let e of Object.keys(me))jr[[...me[e].labels].sort().join("")]=e;var Lr={};function re(e,t){if(!(this instanceof re))return new re(e,t);if(t&&t in di&&(t=null),t&&!(t in me))throw new Error("Unknown model: "+t);let r,s;if(e==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(e instanceof re)this.model=e.model,this.color=[...e.color],this.valpha=e.valpha;else if(typeof e=="string"){let n=ft.get(e);if(n===null)throw new Error("Unable to parse color from string: "+e);this.model=n.model,s=me[this.model].channels,this.color=n.value.slice(0,s),this.valpha=typeof n.value[s]=="number"?n.value[s]:1}else if(e.length>0){this.model=t||"rgb",s=me[this.model].channels;let n=Array.prototype.slice.call(e,0,s);this.color=Mr(n,s),this.valpha=typeof e[s]=="number"?e[s]:1}else if(typeof e=="number")this.model="rgb",this.color=[e>>16&255,e>>8&255,e&255],this.valpha=1;else{this.valpha=1;let n=Object.keys(e);"alpha"in e&&(n.splice(n.indexOf("alpha"),1),this.valpha=typeof e.alpha=="number"?e.alpha:0);let i=n.sort().join("");if(!(i in jr))throw new Error("Unable to parse color from object: "+JSON.stringify(e));this.model=jr[i];let{labels:o}=me[this.model],a=[];for(r=0;r<o.length;r++)a.push(e[o[r]]);this.color=Mr(a)}if(Lr[this.model])for(s=me[this.model].channels,r=0;r<s;r++){let n=Lr[this.model][r];n&&(this.color[r]=n(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}re.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(e){let t=this.model in ft.to?this:this.rgb();t=t.round(typeof e=="number"?e:1);let r=t.valpha===1?t.color:[...t.color,this.valpha];return ft.to[t.model](...r)},percentString(e){let t=this.rgb().round(typeof e=="number"?e:1),r=t.valpha===1?t.color:[...t.color,this.valpha];return ft.to.rgb.percent(...r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){let e={},{channels:t}=me[this.model],{labels:r}=me[this.model];for(let s=0;s<t;s++)e[r[s]]=this.color[s];return this.valpha!==1&&(e.alpha=this.valpha),e},unitArray(){let e=this.rgb().color;return e[0]/=255,e[1]/=255,e[2]/=255,this.valpha!==1&&e.push(this.valpha),e},unitObject(){let e=this.rgb().object();return e.r/=255,e.g/=255,e.b/=255,this.valpha!==1&&(e.alpha=this.valpha),e},round(e){return e=Math.max(e||0,0),new re([...this.color.map(au(e)),this.valpha],this.model)},alpha(e){return e!==void 0?new re([...this.color,Math.max(0,Math.min(1,e))],this.model):this.valpha},red:X("rgb",0,Q(255)),green:X("rgb",1,Q(255)),blue:X("rgb",2,Q(255)),hue:X(["hsl","hsv","hsl","hwb","hcg"],0,e=>(e%360+360)%360),saturationl:X("hsl",1,Q(100)),lightness:X("hsl",2,Q(100)),saturationv:X("hsv",1,Q(100)),value:X("hsv",2,Q(100)),chroma:X("hcg",1,Q(100)),gray:X("hcg",2,Q(100)),white:X("hwb",1,Q(100)),wblack:X("hwb",2,Q(100)),cyan:X("cmyk",0,Q(100)),magenta:X("cmyk",1,Q(100)),yellow:X("cmyk",2,Q(100)),black:X("cmyk",3,Q(100)),x:X("xyz",0,Q(95.047)),y:X("xyz",1,Q(100)),z:X("xyz",2,Q(108.833)),l:X("lab",0,Q(100)),a:X("lab",1),b:X("lab",2),keyword(e){return e!==void 0?new re(e):me[this.model].keyword(this.color)},hex(e){return e!==void 0?new re(e):ft.to.hex(...this.rgb().round().color)},hexa(e){if(e!==void 0)return new re(e);let t=this.rgb().round().color,r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),ft.to.hex(...t)+r},rgbNumber(){let e=this.rgb().color;return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255},luminosity(){let e=this.rgb().color,t=[];for(let[r,s]of e.entries()){let n=s/255;t[r]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return .2126*t[0]+.7152*t[1]+.0722*t[2]},contrast(e){let t=this.luminosity(),r=e.luminosity();return t>r?(t+.05)/(r+.05):(r+.05)/(t+.05)},level(e){let t=this.contrast(e);return t>=7?"AAA":t>=4.5?"AA":""},isDark(){let e=this.rgb().color;return(e[0]*2126+e[1]*7152+e[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){let e=this.rgb();for(let t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten(e){let t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken(e){let t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate(e){let t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate(e){let t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten(e){let t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken(e){let t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale(){let e=this.rgb().color,t=e[0]*.3+e[1]*.59+e[2]*.11;return re.rgb(t,t,t)},fade(e){return this.alpha(this.valpha-this.valpha*e)},opaquer(e){return this.alpha(this.valpha+this.valpha*e)},rotate(e){let t=this.hsl(),r=t.color[0];return r=(r+e)%360,r=r<0?360+r:r,t.color[0]=r,t},mix(e,t){if(!e||!e.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof e);let r=e.rgb(),s=this.rgb(),n=t===void 0?.5:t,i=2*n-1,o=r.alpha()-s.alpha(),a=((i*o===-1?i:(i+o)/(1+i*o))+1)/2,l=1-a;return re.rgb(a*r.red()+l*s.red(),a*r.green()+l*s.green(),a*r.blue()+l*s.blue(),r.alpha()*n+s.alpha()*(1-n))}};for(let e of Object.keys(me)){if(di.includes(e))continue;let{channels:t}=me[e];re.prototype[e]=function(...r){return this.model===e?new re(this):r.length>0?new re(r,e):new re([...lu(me[this.model][e].raw(this.color)),this.valpha],e)},re[e]=function(...r){let s=r[0];return typeof s=="number"&&(s=Mr(r,t)),new re(s,e)}}function ou(e,t){return Number(e.toFixed(t))}function au(e){return function(t){return ou(t,e)}}function X(e,t,r){e=Array.isArray(e)?e:[e];for(let s of e)(Lr[s]||=[])[t]=r;return e=e[0],function(s){let n;return s!==void 0?(r&&(s=r(s)),n=this[e](),n.color[t]=s,n):(n=this[e]().color[t],r&&(n=r(n)),n)}}function Q(e){return function(t){return Math.max(0,Math.min(e,t))}}function lu(e){return Array.isArray(e)?e:[e]}function Mr(e,t){for(let r=0;r<t;r++)typeof e[r]!="number"&&(e[r]=0);return e}var cu=re});var bi=D((yd,mi)=>{mi.exports=gi().default});var Ei=D((wd,wi)=>{var uu=bi(),Be=Ne(),vi={multiband:"multiband","b-w":"b-w",bw:"b-w",cmyk:"cmyk",srgb:"srgb"};function fu(e){return this._setBackgroundColourOption("tint",e),this}function hu(e){return this.options.greyscale=Be.bool(e)?e:!0,this}function du(e){return this.greyscale(e)}function pu(e){if(!Be.string(e))throw Be.invalidParameterError("colourspace","string",e);return this.options.colourspacePipeline=e,this}function gu(e){return this.pipelineColourspace(e)}function mu(e){if(!Be.string(e))throw Be.invalidParameterError("colourspace","string",e);return this.options.colourspace=e,this}function bu(e){return this.toColourspace(e)}function yi(e){if(Be.object(e)||Be.string(e)&&e.length>=3&&e.length<=200){let t=uu(e);return[t.red(),t.green(),t.blue(),Math.round(t.alpha()*255)]}else throw Be.invalidParameterError("background","object or string",e)}function vu(e,t){Be.defined(t)&&(this.options[e]=yi(t))}wi.exports=e=>{Object.assign(e.prototype,{tint:fu,greyscale:hu,grayscale:du,pipelineColourspace:pu,pipelineColorspace:gu,toColourspace:mu,toColorspace:bu,_getBackgroundColourOption:yi,_setBackgroundColourOption:vu}),e.colourspace=vi,e.colorspace=vi}});var Pi=D((Ed,xi)=>{var Oe=Ne(),yu={and:"and",or:"or",eor:"eor"};function wu(){return this.options.removeAlpha=!0,this}function Eu(e){if(Oe.defined(e))if(Oe.number(e)&&Oe.inRange(e,0,1))this.options.ensureAlpha=e;else throw Oe.invalidParameterError("alpha","number between 0 and 1",e);else this.options.ensureAlpha=1;return this}function xu(e){let t={red:0,green:1,blue:2,alpha:3};if(Object.keys(t).includes(e)&&(e=t[e]),Oe.integer(e)&&Oe.inRange(e,0,4))this.options.extractChannel=e;else throw Oe.invalidParameterError("channel","integer or one of: red, green, blue, alpha",e);return this}function Pu(e,t){return Array.isArray(e)?e.forEach(function(r){this.options.joinChannelIn.push(this._createInputDescriptor(r,t))},this):this.options.joinChannelIn.push(this._createInputDescriptor(e,t)),this}function Su(e){if(Oe.string(e)&&Oe.inArray(e,["and","or","eor"]))this.options.bandBoolOp=e;else throw Oe.invalidParameterError("boolOp","one of: and, or, eor",e);return this}xi.exports=e=>{Object.assign(e.prototype,{removeAlpha:wu,ensureAlpha:Eu,extractChannel:xu,joinChannel:Pu,bandbool:Su}),e.bool=yu}});var Ai=D((xd,ki)=>{var Br=J("node:path"),c=Ne(),gt=Rt(),Si=new Map([["heic","heif"],["heif","heif"],["avif","avif"],["jpeg","jpeg"],["jpg","jpeg"],["jpe","jpeg"],["tile","tile"],["dz","tile"],["png","png"],["raw","raw"],["tiff","tiff"],["tif","tiff"],["webp","webp"],["gif","gif"],["jp2","jp2"],["jpx","jp2"],["j2k","jp2"],["j2c","jp2"],["jxl","jxl"]]),Ru=/\.(jp[2x]|j2[kc])$/i,Ri=()=>new Error("JP2 output requires libvips with support for OpenJPEG"),$i=e=>1<<31-Math.clz32(Math.ceil(Math.log2(e)));function $u(e,t){let r;if(c.string(e)?c.string(this.options.input.file)&&Br.resolve(this.options.input.file)===Br.resolve(e)?r=new Error("Cannot use same file for input and output"):Ru.test(Br.extname(e))&&!this.constructor.format.jp2k.output.file&&(r=Ri()):r=new Error("Missing output file path"),r)if(c.fn(t))t(r);else return Promise.reject(r);else{this.options.fileOut=e;let s=Error();return this._pipeline(t,s)}return this}function ku(e,t){c.object(e)?this._setBooleanOption("resolveWithObject",e.resolveWithObject):this.options.resolveWithObject&&(this.options.resolveWithObject=!1),this.options.fileOut="";let r=Error();return this._pipeline(c.fn(e)?e:t,r)}function Au(){return this.options.keepMetadata|=1,this}function _u(e){if(c.object(e))for(let[t,r]of Object.entries(e))if(c.object(r))for(let[s,n]of Object.entries(r))if(c.string(n))this.options.withExif[`exif-${t.toLowerCase()}-${s}`]=n;else throw c.invalidParameterError(`${t}.${s}`,"string",n);else throw c.invalidParameterError(t,"object",r);else throw c.invalidParameterError("exif","object",e);return this.options.withExifMerge=!1,this.keepExif()}function Nu(e){return this.withExif(e),this.options.withExifMerge=!0,this}function Iu(){return this.options.keepMetadata|=8,this}function Du(e,t){if(c.string(e))this.options.withIccProfile=e;else throw c.invalidParameterError("icc","string",e);if(this.keepIccProfile(),c.object(t)&&c.defined(t.attach))if(c.bool(t.attach))t.attach||(this.options.keepMetadata&=-9);else throw c.invalidParameterError("attach","boolean",t.attach);return this}function Tu(){return this.options.keepMetadata|=2,this}function Fu(e){if(c.string(e)&&e.length>0)this.options.withXmp=e,this.options.keepMetadata|=2;else throw c.invalidParameterError("xmp","non-empty string",e);return this}function Cu(){return this.options.keepMetadata=31,this}function Ou(e){if(this.keepMetadata(),this.withIccProfile("srgb"),c.object(e)){if(c.defined(e.orientation))if(c.integer(e.orientation)&&c.inRange(e.orientation,1,8))this.options.withMetadataOrientation=e.orientation;else throw c.invalidParameterError("orientation","integer between 1 and 8",e.orientation);if(c.defined(e.density))if(c.number(e.density)&&e.density>0)this.options.withMetadataDensity=e.density;else throw c.invalidParameterError("density","positive number",e.density);c.defined(e.icc)&&this.withIccProfile(e.icc),c.defined(e.exif)&&this.withExifMerge(e.exif)}return this}function ju(e,t){let r=Si.get((c.object(e)&&c.string(e.id)?e.id:e).toLowerCase());if(!r)throw c.invalidParameterError("format",`one of: ${[...Si.keys()].join(", ")}`,e);return this[r](t)}function Lu(e){if(c.object(e)){if(c.defined(e.quality))if(c.integer(e.quality)&&c.inRange(e.quality,1,100))this.options.jpegQuality=e.quality;else throw c.invalidParameterError("quality","integer between 1 and 100",e.quality);if(c.defined(e.progressive)&&this._setBooleanOption("jpegProgressive",e.progressive),c.defined(e.chromaSubsampling))if(c.string(e.chromaSubsampling)&&c.inArray(e.chromaSubsampling,["4:2:0","4:4:4"]))this.options.jpegChromaSubsampling=e.chromaSubsampling;else throw c.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",e.chromaSubsampling);let t=c.bool(e.optimizeCoding)?e.optimizeCoding:e.optimiseCoding;if(c.defined(t)&&this._setBooleanOption("jpegOptimiseCoding",t),c.defined(e.mozjpeg))if(c.bool(e.mozjpeg))e.mozjpeg&&(this.options.jpegTrellisQuantisation=!0,this.options.jpegOvershootDeringing=!0,this.options.jpegOptimiseScans=!0,this.options.jpegProgressive=!0,this.options.jpegQuantisationTable=3);else throw c.invalidParameterError("mozjpeg","boolean",e.mozjpeg);let r=c.bool(e.trellisQuantization)?e.trellisQuantization:e.trellisQuantisation;c.defined(r)&&this._setBooleanOption("jpegTrellisQuantisation",r),c.defined(e.overshootDeringing)&&this._setBooleanOption("jpegOvershootDeringing",e.overshootDeringing);let s=c.bool(e.optimizeScans)?e.optimizeScans:e.optimiseScans;c.defined(s)&&(this._setBooleanOption("jpegOptimiseScans",s),s&&(this.options.jpegProgressive=!0));let n=c.number(e.quantizationTable)?e.quantizationTable:e.quantisationTable;if(c.defined(n))if(c.integer(n)&&c.inRange(n,0,8))this.options.jpegQuantisationTable=n;else throw c.invalidParameterError("quantisationTable","integer between 0 and 8",n)}return this._updateFormatOut("jpeg",e)}function Mu(e){if(c.object(e)){if(c.defined(e.progressive)&&this._setBooleanOption("pngProgressive",e.progressive),c.defined(e.compressionLevel))if(c.integer(e.compressionLevel)&&c.inRange(e.compressionLevel,0,9))this.options.pngCompressionLevel=e.compressionLevel;else throw c.invalidParameterError("compressionLevel","integer between 0 and 9",e.compressionLevel);c.defined(e.adaptiveFiltering)&&this._setBooleanOption("pngAdaptiveFiltering",e.adaptiveFiltering);let t=e.colours||e.colors;if(c.defined(t))if(c.integer(t)&&c.inRange(t,2,256))this.options.pngBitdepth=$i(t);else throw c.invalidParameterError("colours","integer between 2 and 256",t);if(c.defined(e.palette)?this._setBooleanOption("pngPalette",e.palette):[e.quality,e.effort,e.colours,e.colors,e.dither].some(c.defined)&&this._setBooleanOption("pngPalette",!0),this.options.pngPalette){if(c.defined(e.quality))if(c.integer(e.quality)&&c.inRange(e.quality,0,100))this.options.pngQuality=e.quality;else throw c.invalidParameterError("quality","integer between 0 and 100",e.quality);if(c.defined(e.effort))if(c.integer(e.effort)&&c.inRange(e.effort,1,10))this.options.pngEffort=e.effort;else throw c.invalidParameterError("effort","integer between 1 and 10",e.effort);if(c.defined(e.dither))if(c.number(e.dither)&&c.inRange(e.dither,0,1))this.options.pngDither=e.dither;else throw c.invalidParameterError("dither","number between 0.0 and 1.0",e.dither)}}return this._updateFormatOut("png",e)}function zu(e){if(c.object(e)){if(c.defined(e.quality))if(c.integer(e.quality)&&c.inRange(e.quality,1,100))this.options.webpQuality=e.quality;else throw c.invalidParameterError("quality","integer between 1 and 100",e.quality);if(c.defined(e.alphaQuality))if(c.integer(e.alphaQuality)&&c.inRange(e.alphaQuality,0,100))this.options.webpAlphaQuality=e.alphaQuality;else throw c.invalidParameterError("alphaQuality","integer between 0 and 100",e.alphaQuality);if(c.defined(e.lossless)&&this._setBooleanOption("webpLossless",e.lossless),c.defined(e.nearLossless)&&this._setBooleanOption("webpNearLossless",e.nearLossless),c.defined(e.smartSubsample)&&this._setBooleanOption("webpSmartSubsample",e.smartSubsample),c.defined(e.smartDeblock)&&this._setBooleanOption("webpSmartDeblock",e.smartDeblock),c.defined(e.preset))if(c.string(e.preset)&&c.inArray(e.preset,["default","photo","picture","drawing","icon","text"]))this.options.webpPreset=e.preset;else throw c.invalidParameterError("preset","one of: default, photo, picture, drawing, icon, text",e.preset);if(c.defined(e.effort))if(c.integer(e.effort)&&c.inRange(e.effort,0,6))this.options.webpEffort=e.effort;else throw c.invalidParameterError("effort","integer between 0 and 6",e.effort);c.defined(e.minSize)&&this._setBooleanOption("webpMinSize",e.minSize),c.defined(e.mixed)&&this._setBooleanOption("webpMixed",e.mixed)}return Ur(e,this.options),this._updateFormatOut("webp",e)}function Bu(e){if(c.object(e)){c.defined(e.reuse)&&this._setBooleanOption("gifReuse",e.reuse),c.defined(e.progressive)&&this._setBooleanOption("gifProgressive",e.progressive);let t=e.colours||e.colors;if(c.defined(t))if(c.integer(t)&&c.inRange(t,2,256))this.options.gifBitdepth=$i(t);else throw c.invalidParameterError("colours","integer between 2 and 256",t);if(c.defined(e.effort))if(c.number(e.effort)&&c.inRange(e.effort,1,10))this.options.gifEffort=e.effort;else throw c.invalidParameterError("effort","integer between 1 and 10",e.effort);if(c.defined(e.dither))if(c.number(e.dither)&&c.inRange(e.dither,0,1))this.options.gifDither=e.dither;else throw c.invalidParameterError("dither","number between 0.0 and 1.0",e.dither);if(c.defined(e.interFrameMaxError))if(c.number(e.interFrameMaxError)&&c.inRange(e.interFrameMaxError,0,32))this.options.gifInterFrameMaxError=e.interFrameMaxError;else throw c.invalidParameterError("interFrameMaxError","number between 0.0 and 32.0",e.interFrameMaxError);if(c.defined(e.interPaletteMaxError))if(c.number(e.interPaletteMaxError)&&c.inRange(e.interPaletteMaxError,0,256))this.options.gifInterPaletteMaxError=e.interPaletteMaxError;else throw c.invalidParameterError("interPaletteMaxError","number between 0.0 and 256.0",e.interPaletteMaxError);if(c.defined(e.keepDuplicateFrames))if(c.bool(e.keepDuplicateFrames))this._setBooleanOption("gifKeepDuplicateFrames",e.keepDuplicateFrames);else throw c.invalidParameterError("keepDuplicateFrames","boolean",e.keepDuplicateFrames)}return Ur(e,this.options),this._updateFormatOut("gif",e)}function Uu(e){if(!this.constructor.format.jp2k.output.buffer)throw Ri();if(c.object(e)){if(c.defined(e.quality))if(c.integer(e.quality)&&c.inRange(e.quality,1,100))this.options.jp2Quality=e.quality;else throw c.invalidParameterError("quality","integer between 1 and 100",e.quality);if(c.defined(e.lossless))if(c.bool(e.lossless))this.options.jp2Lossless=e.lossless;else throw c.invalidParameterError("lossless","boolean",e.lossless);if(c.defined(e.tileWidth))if(c.integer(e.tileWidth)&&c.inRange(e.tileWidth,1,32768))this.options.jp2TileWidth=e.tileWidth;else throw c.invalidParameterError("tileWidth","integer between 1 and 32768",e.tileWidth);if(c.defined(e.tileHeight))if(c.integer(e.tileHeight)&&c.inRange(e.tileHeight,1,32768))this.options.jp2TileHeight=e.tileHeight;else throw c.invalidParameterError("tileHeight","integer between 1 and 32768",e.tileHeight);if(c.defined(e.chromaSubsampling))if(c.string(e.chromaSubsampling)&&c.inArray(e.chromaSubsampling,["4:2:0","4:4:4"]))this.options.jp2ChromaSubsampling=e.chromaSubsampling;else throw c.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",e.chromaSubsampling)}return this._updateFormatOut("jp2",e)}function Ur(e,t){if(c.object(e)&&c.defined(e.loop))if(c.integer(e.loop)&&c.inRange(e.loop,0,65535))t.loop=e.loop;else throw c.invalidParameterError("loop","integer between 0 and 65535",e.loop);if(c.object(e)&&c.defined(e.delay))if(c.integer(e.delay)&&c.inRange(e.delay,0,65535))t.delay=[e.delay];else if(Array.isArray(e.delay)&&e.delay.every(c.integer)&&e.delay.every(r=>c.inRange(r,0,65535)))t.delay=e.delay;else throw c.invalidParameterError("delay","integer or an array of integers between 0 and 65535",e.delay)}function Gu(e){if(c.object(e)){if(c.defined(e.quality))if(c.integer(e.quality)&&c.inRange(e.quality,1,100))this.options.tiffQuality=e.quality;else throw c.invalidParameterError("quality","integer between 1 and 100",e.quality);if(c.defined(e.bitdepth))if(c.integer(e.bitdepth)&&c.inArray(e.bitdepth,[1,2,4,8]))this.options.tiffBitdepth=e.bitdepth;else throw c.invalidParameterError("bitdepth","1, 2, 4 or 8",e.bitdepth);if(c.defined(e.tile)&&this._setBooleanOption("tiffTile",e.tile),c.defined(e.tileWidth))if(c.integer(e.tileWidth)&&e.tileWidth>0)this.options.tiffTileWidth=e.tileWidth;else throw c.invalidParameterError("tileWidth","integer greater than zero",e.tileWidth);if(c.defined(e.tileHeight))if(c.integer(e.tileHeight)&&e.tileHeight>0)this.options.tiffTileHeight=e.tileHeight;else throw c.invalidParameterError("tileHeight","integer greater than zero",e.tileHeight);if(c.defined(e.miniswhite)&&this._setBooleanOption("tiffMiniswhite",e.miniswhite),c.defined(e.pyramid)&&this._setBooleanOption("tiffPyramid",e.pyramid),c.defined(e.xres))if(c.number(e.xres)&&e.xres>0)this.options.tiffXres=e.xres;else throw c.invalidParameterError("xres","number greater than zero",e.xres);if(c.defined(e.yres))if(c.number(e.yres)&&e.yres>0)this.options.tiffYres=e.yres;else throw c.invalidParameterError("yres","number greater than zero",e.yres);if(c.defined(e.compression))if(c.string(e.compression)&&c.inArray(e.compression,["none","jpeg","deflate","packbits","ccittfax4","lzw","webp","zstd","jp2k"]))this.options.tiffCompression=e.compression;else throw c.invalidParameterError("compression","one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k",e.compression);if(c.defined(e.bigtiff)&&this._setBooleanOption("tiffBigtiff",e.bigtiff),c.defined(e.predictor))if(c.string(e.predictor)&&c.inArray(e.predictor,["none","horizontal","float"]))this.options.tiffPredictor=e.predictor;else throw c.invalidParameterError("predictor","one of: none, horizontal, float",e.predictor);if(c.defined(e.resolutionUnit))if(c.string(e.resolutionUnit)&&c.inArray(e.resolutionUnit,["inch","cm"]))this.options.tiffResolutionUnit=e.resolutionUnit;else throw c.invalidParameterError("resolutionUnit","one of: inch, cm",e.resolutionUnit)}return this._updateFormatOut("tiff",e)}function qu(e){return this.heif({...e,compression:"av1"})}function Wu(e){if(c.object(e)){if(c.string(e.compression)&&c.inArray(e.compression,["av1","hevc"]))this.options.heifCompression=e.compression;else throw c.invalidParameterError("compression","one of: av1, hevc",e.compression);if(c.defined(e.quality))if(c.integer(e.quality)&&c.inRange(e.quality,1,100))this.options.heifQuality=e.quality;else throw c.invalidParameterError("quality","integer between 1 and 100",e.quality);if(c.defined(e.lossless))if(c.bool(e.lossless))this.options.heifLossless=e.lossless;else throw c.invalidParameterError("lossless","boolean",e.lossless);if(c.defined(e.effort))if(c.integer(e.effort)&&c.inRange(e.effort,0,9))this.options.heifEffort=e.effort;else throw c.invalidParameterError("effort","integer between 0 and 9",e.effort);if(c.defined(e.chromaSubsampling))if(c.string(e.chromaSubsampling)&&c.inArray(e.chromaSubsampling,["4:2:0","4:4:4"]))this.options.heifChromaSubsampling=e.chromaSubsampling;else throw c.invalidParameterError("chromaSubsampling","one of: 4:2:0, 4:4:4",e.chromaSubsampling);if(c.defined(e.bitdepth))if(c.integer(e.bitdepth)&&c.inArray(e.bitdepth,[8,10,12])){if(e.bitdepth!==8&&this.constructor.versions.heif)throw c.invalidParameterError("bitdepth when using prebuilt binaries",8,e.bitdepth);this.options.heifBitdepth=e.bitdepth}else throw c.invalidParameterError("bitdepth","8, 10 or 12",e.bitdepth)}else throw c.invalidParameterError("options","Object",e);return this._updateFormatOut("heif",e)}function Hu(e){if(c.object(e)){if(c.defined(e.quality))if(c.integer(e.quality)&&c.inRange(e.quality,1,100))this.options.jxlDistance=e.quality>=30?.1+(100-e.quality)*.09:53/3e3*e.quality*e.quality-23/20*e.quality+25;else throw c.invalidParameterError("quality","integer between 1 and 100",e.quality);else if(c.defined(e.distance))if(c.number(e.distance)&&c.inRange(e.distance,0,15))this.options.jxlDistance=e.distance;else throw c.invalidParameterError("distance","number between 0.0 and 15.0",e.distance);if(c.defined(e.decodingTier))if(c.integer(e.decodingTier)&&c.inRange(e.decodingTier,0,4))this.options.jxlDecodingTier=e.decodingTier;else throw c.invalidParameterError("decodingTier","integer between 0 and 4",e.decodingTier);if(c.defined(e.lossless))if(c.bool(e.lossless))this.options.jxlLossless=e.lossless;else throw c.invalidParameterError("lossless","boolean",e.lossless);if(c.defined(e.effort))if(c.integer(e.effort)&&c.inRange(e.effort,1,9))this.options.jxlEffort=e.effort;else throw c.invalidParameterError("effort","integer between 1 and 9",e.effort)}return Ur(e,this.options),this._updateFormatOut("jxl",e)}function Vu(e){if(c.object(e)&&c.defined(e.depth))if(c.string(e.depth)&&c.inArray(e.depth,["char","uchar","short","ushort","int","uint","float","complex","double","dpcomplex"]))this.options.rawDepth=e.depth;else throw c.invalidParameterError("depth","one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex",e.depth);return this._updateFormatOut("raw")}function Ju(e){if(c.object(e)){if(c.defined(e.size))if(c.integer(e.size)&&c.inRange(e.size,1,8192))this.options.tileSize=e.size;else throw c.invalidParameterError("size","integer between 1 and 8192",e.size);if(c.defined(e.overlap))if(c.integer(e.overlap)&&c.inRange(e.overlap,0,8192)){if(e.overlap>this.options.tileSize)throw c.invalidParameterError("overlap",`<= size (${this.options.tileSize})`,e.overlap);this.options.tileOverlap=e.overlap}else throw c.invalidParameterError("overlap","integer between 0 and 8192",e.overlap);if(c.defined(e.container))if(c.string(e.container)&&c.inArray(e.container,["fs","zip"]))this.options.tileContainer=e.container;else throw c.invalidParameterError("container","one of: fs, zip",e.container);if(c.defined(e.layout))if(c.string(e.layout)&&c.inArray(e.layout,["dz","google","iiif","iiif3","zoomify"]))this.options.tileLayout=e.layout;else throw c.invalidParameterError("layout","one of: dz, google, iiif, iiif3, zoomify",e.layout);if(c.defined(e.angle))if(c.integer(e.angle)&&!(e.angle%90))this.options.tileAngle=e.angle;else throw c.invalidParameterError("angle","positive/negative multiple of 90",e.angle);if(this._setBackgroundColourOption("tileBackground",e.background),c.defined(e.depth))if(c.string(e.depth)&&c.inArray(e.depth,["onepixel","onetile","one"]))this.options.tileDepth=e.depth;else throw c.invalidParameterError("depth","one of: onepixel, onetile, one",e.depth);if(c.defined(e.skipBlanks))if(c.integer(e.skipBlanks)&&c.inRange(e.skipBlanks,-1,65535))this.options.tileSkipBlanks=e.skipBlanks;else throw c.invalidParameterError("skipBlanks","integer between -1 and 255/65535",e.skipBlanks);else c.defined(e.layout)&&e.layout==="google"&&(this.options.tileSkipBlanks=5);let t=c.bool(e.center)?e.center:e.centre;if(c.defined(t)&&this._setBooleanOption("tileCentre",t),c.defined(e.id))if(c.string(e.id))this.options.tileId=e.id;else throw c.invalidParameterError("id","string",e.id);if(c.defined(e.basename))if(c.string(e.basename))this.options.tileBasename=e.basename;else throw c.invalidParameterError("basename","string",e.basename)}if(c.inArray(this.options.formatOut,["jpeg","png","webp"]))this.options.tileFormat=this.options.formatOut;else if(this.options.formatOut!=="input")throw c.invalidParameterError("format","one of: jpeg, png, webp",this.options.formatOut);return this._updateFormatOut("dz")}function Xu(e){if(!c.plainObject(e))throw c.invalidParameterError("options","object",e);if(c.integer(e.seconds)&&c.inRange(e.seconds,0,3600))this.options.timeoutSeconds=e.seconds;else throw c.invalidParameterError("seconds","integer between 0 and 3600",e.seconds);return this}function Yu(e,t){return c.object(t)&&t.force===!1||(this.options.formatOut=e),this}function Ku(e,t){if(c.bool(t))this.options[e]=t;else throw c.invalidParameterError(e,"boolean",t)}function Qu(){if(!this.options.streamOut){this.options.streamOut=!0;let e=Error();this._pipeline(void 0,e)}}function Zu(e,t){return typeof e=="function"?(this._isStreamInput()?this.on("finish",()=>{this._flattenBufferIn(),gt.pipeline(this.options,(r,s,n)=>{r?e(c.nativeError(r,t)):e(null,s,n)})}):gt.pipeline(this.options,(r,s,n)=>{r?e(c.nativeError(r,t)):e(null,s,n)}),this):this.options.streamOut?(this._isStreamInput()?(this.once("finish",()=>{this._flattenBufferIn(),gt.pipeline(this.options,(r,s,n)=>{r?this.emit("error",c.nativeError(r,t)):(this.emit("info",n),this.push(s)),this.push(null),this.on("end",()=>this.emit("close"))})}),this.streamInFinished&&this.emit("finish")):gt.pipeline(this.options,(r,s,n)=>{r?this.emit("error",c.nativeError(r,t)):(this.emit("info",n),this.push(s)),this.push(null),this.on("end",()=>this.emit("close"))}),this):this._isStreamInput()?new Promise((r,s)=>{this.once("finish",()=>{this._flattenBufferIn(),gt.pipeline(this.options,(n,i,o)=>{n?s(c.nativeError(n,t)):this.options.resolveWithObject?r({data:i,info:o}):r(i)})})}):new Promise((r,s)=>{gt.pipeline(this.options,(n,i,o)=>{n?s(c.nativeError(n,t)):this.options.resolveWithObject?r({data:i,info:o}):r(i)})})}ki.exports=e=>{Object.assign(e.prototype,{toFile:$u,toBuffer:ku,keepExif:Au,withExif:_u,withExifMerge:Nu,keepIccProfile:Iu,withIccProfile:Du,keepXmp:Tu,withXmp:Fu,keepMetadata:Cu,withMetadata:Ou,toFormat:ju,jpeg:Lu,jp2:Uu,png:Mu,webp:zu,tiff:Gu,avif:qu,heif:Wu,jxl:Hu,gif:Bu,raw:Vu,tile:Ju,timeout:Xu,_updateFormatOut:Yu,_setBooleanOption:Ku,_read:Qu,_pipeline:Zu})}});var Di=D((Pd,Ii)=>{var ef=J("node:events"),Qt=Mt(),Pe=Ne(),{runtimePlatformArch:tf}=Ir(),ue=Rt(),_i=tf(),Gr=ue.libvipsVersion(),Xe=ue.format();Xe.heif.output.alias=["avif","heic"];Xe.jpeg.output.alias=["jpe","jpg"];Xe.tiff.output.alias=["tif"];Xe.jp2k.output.alias=["j2c","j2k","jp2","jpx"];var rf={nearest:"nearest",bilinear:"bilinear",bicubic:"bicubic",locallyBoundedBicubic:"lbb",nohalo:"nohalo",vertexSplitQuadraticBasisSpline:"vsqbs"},mt={vips:Gr.semver};if(!Gr.isGlobal)if(Gr.isWasm)try{mt=J("@img/sharp-wasm32/versions")}catch{}else try{mt=J(`@img/sharp-${_i}/versions`)}catch{try{mt=J(`@img/sharp-libvips-${_i}/versions`)}catch{}}mt.sharp=_r().version;mt.heif&&Xe.heif&&(Xe.heif.input.fileSuffix=[".avif"],Xe.heif.output.alias=["avif"]);function Ni(e){return Pe.bool(e)?e?ue.cache(50,20,100):ue.cache(0,0,0):Pe.object(e)?ue.cache(e.memory,e.files,e.items):ue.cache()}Ni(!0);function sf(e){return ue.concurrency(Pe.integer(e)?e:null)}Qt.familySync()===Qt.GLIBC&&!ue._isUsingJemalloc()?ue.concurrency(1):Qt.familySync()===Qt.MUSL&&ue.concurrency()===1024&&ue.concurrency(J("node:os").availableParallelism());var nf=new ef.EventEmitter;function of(){return ue.counters()}function af(e){return ue.simd(Pe.bool(e)?e:null)}function lf(e){if(Pe.object(e))if(Array.isArray(e.operation)&&e.operation.every(Pe.string))ue.block(e.operation,!0);else throw Pe.invalidParameterError("operation","Array<string>",e.operation);else throw Pe.invalidParameterError("options","object",e)}function cf(e){if(Pe.object(e))if(Array.isArray(e.operation)&&e.operation.every(Pe.string))ue.block(e.operation,!1);else throw Pe.invalidParameterError("operation","Array<string>",e.operation);else throw Pe.invalidParameterError("options","object",e)}Ii.exports=e=>{e.cache=Ni,e.concurrency=sf,e.counters=of,e.simd=af,e.format=Xe,e.interpolators=rf,e.versions=mt,e.queue=nf,e.block=lf,e.unblock=cf}});var Fi=D((Rd,Ti)=>{var Ue=Vn();Yn()(Ue);ri()(Ue);ni()(Ue);ci()(Ue);Ei()(Ue);Pi()(Ue);Ai()(Ue);Di()(Ue);Ti.exports=Ue});var co={};yo(co,{createDndevPlugin:()=>Yf});import{realpathSync as If,watch as Df}from"node:fs";import{execSync as nr,spawn as Tf}from"node:child_process";function pe(){return U.getInstance()}function no(){return pe().getRepoRoot()}function io(){return pe().resolveRepoPath(".dndev")}function R(e,t,r=200){e.writeHead(r,{"Content-Type":"application/json"}),e.end(JSON.stringify(t))}function At(e,t=Ff){return new Promise((r,s)=>{let n="",i=0;e.on("data",o=>{if(i+=o.length,i>t){e.destroy(),s(new Error("Request body too large"));return}n+=o.toString()}),e.on("end",()=>r(n)),e.on("error",s)})}function Cf(e){let t=e.lastIndexOf(".");return t===-1?"":e.slice(t).toLowerCase()}function Of(){let e=pe(),t=[],r=process.env.HOME||process.env.USERPROFILE||"";try{let n=process.platform==="win32"?"where node":"which node",i=nr(n,{encoding:"utf8"}).trim().split(`
|
|
3
|
-
`)
|
|
4
|
-
`);if(s
|
|
5
|
-
|
|
6
|
-
`;
|
|
7
|
-
`;o.appendFile(a,G)}},u=(f,d)=>{if(d.length===0)return f;let g=d.map(m=>typeof m=="object"?JSON.stringify(m,null,2):String(m)).join(" ");return`${f} ${g}`};return{debug:(f,...d)=>{t&&(i?l("DEBUG",f,d):he.log.message(Ae(u(f,d),Re.gray)))},verbose:(f,...d)=>{r&&(i?l("VERBOSE",f,d):he.log.message(u(f,d)))},info:(f,...d)=>{i?l("INFO",f,d):he.log.info(Ae(u(f,d),Re.brightCyan))},warn:(f,...d)=>{t&&i?l("WARN",f,d):he.log.warn(Ae(u(f,d),Re.brightYellow))},error:(f,...d)=>{t&&i?l("ERROR",f,d):he.log.error(Ae(u(f,d),Re.brightRed))},success:(f,...d)=>{t&&i?l("SUCCESS",f,d):he.log.success(Ae(u(f,d),Re.brightGreen))},when:(f,d="debug")=>(g,...m)=>{if(f){let P=u(g,m);switch(d){case"verbose":r&&(he.log.message(P),l("VERBOSE",g,m));break;case"info":he.log.info(Ae(P,Re.brightCyan)),l("INFO",g,m);break;case"warn":he.log.warn(Ae(P,Re.brightYellow)),l("WARN",g,m);break;case"error":he.log.error(Ae(P,Re.brightRed)),l("ERROR",g,m);break;case"success":he.log.success(Ae(P,Re.brightGreen)),l("SUCCESS",g,m);break;default:t&&(he.log.message(Ae(P,Re.gray)),l("DEBUG",g,m))}}},getLogFilePath:()=>a}}ge();function as(e={}){let{mode:t="development",chunkingOptions:r={},debug:s,verbose:n=!0,isDev:i,isDebug:o,shouldAnalyze:a,build:l={}}=e,u=B("build",s,n),f=Zr(t,r);return u.debug("\u{1F41B} DEBUG MODE ENABLED:"),u.debug(" - Minification: DISABLED"),u.debug(" - Sourcemaps: ENABLED"),u.debug(" - Console logs: PRESERVED"),u.debug(" - Debugger statements: PRESERVED"),a&&(u.info("\u{1F4CA} Bundle analysis enabled"),u.info(` Visual treemap will open after build (stats.html)
|
|
8
|
-
`)),{outDir:"dist",sourcemap:i||o,cacheDir:"node_modules/.vite",target:"baseline-widely-available",minify:o?!1:"esbuild",reportCompressedSize:!1,chunkSizeWarningLimit:2048,assetsInlineLimit:0,esbuild:{format:"esm",drop:o?[]:["console","debugger"],legalComments:"none"},cssMinify:o?!1:"esbuild",cssCodeSplit:!0,rollupOptions:{external:Oo(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...f.manualChunks&&{manualChunks:f.manualChunks},compact:!0},onwarn(g,m){g.code!=="MODULE_LEVEL_DIRECTIVE"&&m(g)},plugins:[...o?[]:[Fo({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...a?[(()=>{let g=U.getInstance(),m=g.getAppRoot(),P="dist",G=g.resolveAppPath(`${P}/stats.html`),W=()=>{try{let O=g.resolveAppPath(P);g.pathExists(O)||g.mkdir(O)}catch{}},N=Co({filename:G,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:i||o,projectRoot:m});if(N.buildStart){let O=N.buildStart.bind(N);N.buildStart=function(...$){W();let A=O.apply(this,$);return A&&typeof A.then=="function"?A.catch(E=>{}):A}}else N.buildStart=function(){W()};let C=["generateBundle","writeBundle","closeBundle"];for(let O of C)if(N[O]){let $=N[O];N[O]=function(...A){try{W();let E=$.apply(this,A);return E&&typeof E.then=="function"?E.catch(j=>{let M=j?.message||j?.toString()||String(j)||"Unknown error";u.warn(`Bundle visualizer warning in ${O}: ${M}`),O==="closeBundle"&&u.warn(`You can manually open ${G} to view the bundle analysis`)}):E}catch(E){let j=E?.message||E?.toString()||String(E)||"Unknown error";buildLogger.warn(`Bundle visualizer warning in ${O}: ${j}`),O==="closeBundle"&&buildLogger.warn(` You can manually open ${G} to view the bundle analysis`)}}}return N})()]:[]]}}}function Oo(e){return e?["firebase-admin","gcp-metadata","google-logging-utils","@google-cloud/firestore",/\.node$/,"esbuild",/@esbuild\/.*/]:["gcp-metadata","google-logging-utils","payload","file-type","firebase-admin","firebase-admin/app","firebase-admin/auth","firebase-admin/firestore","firebase-admin/functions","firebase-admin/credential","@google-cloud/firestore","google-auth-library","google-gax","googleapis-common"]}function jo(){let e=!1,t=U.getInstance();if((t.pathExists("/.dockerenv")||t.pathExists("/run/.containerenv"))&&(e=!0),!e&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(e=!0),!e&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(e=!0),!e&&process.platform==="linux"&&t.pathExists("/proc/self/cgroup"))try{let n=t.readSync("/proc/self/cgroup");n&&(n.includes("docker")||n.includes("containerd"))&&(e=!0)}catch{}let r=!1;if((process.env.WSL_DISTRO_NAME||process.env.WSLENV)&&(r=!0),!r&&process.platform==="linux"&&t.pathExists("/proc/version"))try{let n=(t.readSync("/proc/version")||"").toLowerCase();r=n.includes("microsoft")||n.includes("wsl")}catch{}if(!r&&process.platform==="linux"&&t.pathExists("/proc/sys/kernel/osrelease"))try{let n=(t.readSync("/proc/sys/kernel/osrelease")||"").toLowerCase()||"";(n.includes("microsoft")||n.includes("wsl"))&&(r=!0)}catch{}if(!r&&process.platform==="win32"){let n=process.cwd();n&&(n.includes("\\wsl$")||n.includes("\\wsl.localhost"))&&(r=!0)}let s=typeof process.versions?.bun=="string";return{isDocker:e,isWSL2:r,isBun:s}}function Lo(e,t){if(e!==void 0)return e;let{isDocker:r,isWSL2:s,isBun:n}=jo();if(r||s||n){let i=r?"Docker":s?"WSL2":"Bun";return t.info(`Detected ${i} environment - enabling polling mode for file watching`),!0}}function ls(e,t={},r){let s=U.getInstance(),n=s.getRepoRoot(),{watch:i,hmr:o,host:a,...l}=t||{},u=o||{},f=a===!0?"localhost":a||"localhost",d={...u.port&&{port:u.port},...u.clientPort&&{clientPort:u.clientPort},host:u.host??f,...u.protocol&&{protocol:u.protocol},overlay:u.overlay??!0,timeout:u.timeout??5e3},g=a!==void 0?a:!0,m=l.https===!0;return{port:e,host:g,open:t.open!==void 0?t.open:!0,https:m,fs:{allow:[n,s.resolveRepoPath("packages"),s.resolveRepoPath("node_modules")],strict:!1},watch:{usePolling:Lo(t?.watch?.usePolling,r),interval:t?.watch?.interval??2e3,...t?.watch||{}},hmr:{...d,...u},headers:{"Cross-Origin-Opener-Policy":"same-origin-allow-popups","Cross-Origin-Embedder-Policy":"unsafe-none"},middlewareMode:!1,...l}}function cs(e={}){let t=e.https===!0;return{...e,https:t}}ee();var Ee={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function We(e,t,r,s={}){let{protectedKeys:n=[],onConflict:i}=s;if(t==null)return e;switch(r){case Ee.CONCATENATE_DEDUPE:{if(!Array.isArray(e)||!Array.isArray(t))return t;let o=[...e,...t];return[...new Set(o)]}case Ee.SHALLOW_MERGE:return typeof e!="object"||typeof t!="object"||e===null||t===null||Array.isArray(e)||Array.isArray(t)?t:{...e,...t};case Ee.DEEP_MERGE:{if(typeof e!="object"||typeof t!="object"||e===null||t===null||Array.isArray(e)||Array.isArray(t))return t;let o={...e};for(let a in t){if(n.includes(a)){i&&i(a,e[a],t[a]);continue}typeof o[a]=="object"&&typeof t[a]=="object"&&o[a]!==null&&t[a]!==null&&!Array.isArray(o[a])&&!Array.isArray(t[a])?o[a]=We(o[a],t[a],Ee.DEEP_MERGE,{protectedKeys:n,onConflict:i}):o[a]=t[a]}return o}case Ee.REPLACE:default:return t}}function us(e,t,r=[],s){let n=[...e,...t||[]],i=[...new Set(n)];return[...new Set([...i,...r])]}var Ct={base:"/",mode:process.env.NODE_ENV==="production"?"production":"development",debug:!1,verbose:process.env.CI!=="true",server:{port:3e3,strictPort:!0,host:!0,open:!0,cors:!0,https:!0,hmr:{overlay:!0,timeout:5e3,usePolling:void 0,interval:2e3},watch:{usePolling:void 0,interval:2e3}},build:{sourcemap:!0,target:"es2020",minify:"esbuild",cssMinify:"esbuild",analyze:!0},preview:{port:4173,strictPort:!0,host:!0,open:!1,cors:!0,https:!0},routes:{hmr:!0},themes:{},i18n:{},assets:{},features:{},pwa:{enabled:!1},seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0},chunking:{reactCore:[]},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},pluginFactory:{verbose:!0,disableHmr:!1,hmrSmartDetection:!0,hmrDebounceMs:500,hmrCacheTimeout:3e4},resolve:{alias:{"@":"/src"},preserveSymlinks:!1},define:{__DEV__:JSON.stringify(process.env.NODE_ENV==="development"),__PROD__:JSON.stringify(process.env.NODE_ENV==="production")},optimizeDeps:{include:[...Ze.mandatoryIncludes],exclude:[...Ze.buildTools,...Object.values(H)],esbuildOptions:{format:"esm",target:"es2020",platform:"browser",define:{"process.env.NODE_ENV":JSON.stringify(process.env.NODE_ENV||"development")},external:["next","next/*"]}},plugins:[],css:{},envDir:void 0};function fs(e={},t={}){let{onConflict:r}=t,s={...Ct},n=[],i=(o,a,l,u)=>{n.push({key:o,frameworkValue:a,userValue:l,reason:u}),r&&r(o,a,l,u)};return Object.keys(e).forEach(o=>{let a=e[o],l=s[o];if(o==="optimizeDeps"&&typeof a=="object"&&a!==null){let u=l?.include||[],f=l?.exclude||[],d=a.include||[],g=a.exclude||[],m=u.filter(C=>!C.startsWith("@donotdev/")),P=g.filter(C=>m.includes(C));if(P.length>0)for(let C of P)i("optimizeDeps.exclude",C,"excluded",`Framework requires ${C} to be included. It will be included despite your exclusion.`);let G=us(u,d,m),W=We(f,g,Ee.CONCATENATE_DEDUPE),N=We(l?.esbuildOptions||{},a.esbuildOptions||{},Ee.DEEP_MERGE,{protectedKeys:["external"],onConflict:C=>i(`optimizeDeps.esbuildOptions.${C}`,l?.esbuildOptions?.[C],a.esbuildOptions?.[C],`Framework requires ${C} to remain as configured.`)});s[o]={...l,include:G,exclude:W,esbuildOptions:N,...Object.fromEntries(Object.entries(a).filter(([C])=>!["include","exclude","esbuildOptions"].includes(C)))};return}if(o==="css"&&typeof a=="object"&&a!==null){s[o]=We(l||{},a,Ee.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>i("css.postcss","framework PostCSS config",a.postcss,"Framework PostCSS config is required and cannot be overridden. Your postcss config is ignored.")});return}if(o==="define"&&typeof a=="object"&&a!==null){s[o]=We(l||{},a,Ee.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:u=>i(`define.${u}`,l?.[u],a[u],`Framework requires ${u} to remain as configured.`)});return}if(Array.isArray(a)){Array.isArray(l)?s[o]=We(l,a,Ee.CONCATENATE_DEDUPE):s[o]=a;return}if(typeof a=="object"&&a!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){s[o]=We(l,a,Ee.SHALLOW_MERGE);return}s[o]=a}),s}function hs(e){let{server:t={},preview:r={},mode:s,build:n={},resolve:i={},routes:o={},themes:a={},i18n:l={},assets:u={},features:f={},seo:d={},pwa:g={},serverShim:m={},chunking:P={},discovery:G={},pluginFactory:W={},debug:N,verbose:C,base:O,define:$={},optimizeDeps:A={},plugins:E=[],css:j={},envDir:M,...be}=e,I=s!=="production",_=N||I,se=s==="production"&&(n.analyze??Ct.build.analyze);return{mode:s,debug:N,verbose:C,isDev:I,isDebug:_,shouldAnalyze:se,serverOptions:t,previewOptions:r,buildOverrides:n,resolveOptions:i,routeOptions:o,themeOptions:a,i18nOptions:l,assetOptions:u,featureOptions:f,seoOptions:d,pwaOptions:g,serverShimOptions:m,chunkingOptions:P,discoveryOptions:G,pluginFactoryOptions:W,base:O,defineOptions:$,optimizeDepsOptions:A,pluginsOptions:E,cssOptions:j,envDir:M,restOptions:be}}ge();import{resolve as Mo}from"node:path";import zo from"autoprefixer";import Bo from"postcss-import";import Uo from"postcss-nesting";function ds({postcssImport:e,postcssNesting:t,autoprefixer:r,resolve:s}){return{plugins:[s?e({resolve:s}):e,t,r({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function ps(e={}){if(e.postcss)return e.postcss;let t=U.getInstance();return ds({postcssImport:Bo,postcssNesting:Uo,autoprefixer:zo,resolve:(s,n)=>{let i=t.resolvePackage(s,n);if(i)return i;if(s.startsWith("@donotdev/")){let o=s.split("/")[0]+"/"+s.split("/")[1],a=s.split("/").slice(2).join("/"),l=t.resolveFrameworkPackage(o,n);if(l&&a){let u=t.resolvePath(a,l);if(t.pathExists(u))return u}}return Mo(n,s)}})}import kf from"@vitejs/plugin-basic-ssl";import Af from"@vitejs/plugin-react";import _f from"vite-tsconfig-paths";var ae=class{static generateVirtualModule(t,r,s=!1,n=void 0,i=void 0){return r.isEmpty(t)?r.generateEmpty(t,s,n,i):r.generateModule(t,s,i)}static generateInspection(t,r,s,n){return r.generateInspection.length>=3?r.generateInspection(t,s,n):r.generateInspection(t,s)}static wrapVirtualModule(t,r){return`// Virtual module: ${t}
|
|
1
|
+
var Kt=Object.defineProperty;var je=(n,e)=>()=>(n&&(e=n(n=0)),e);var Zt=(n,e)=>{for(var t in e)Kt(n,t,{get:e[t],enumerable:!0})};function nt(n,e=null){let t=Q[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function ke(n){return rt[n]||rt.base}var Ge,C,B,z,We,we,De,Q,he,ot,Be,Ve,xe,He,rt,j=je(()=>{"use strict";Ge={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},C={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env"},B={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},z={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},We={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},we={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},De={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},Q={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${De.SOURCE_EAGER}/*_*.json`],lazy:[`${De.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},he={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async","@donotdev/core","@donotdev/components","@donotdev/ui","@donotdev/templates","@donotdev/firebase"],optionalFeatures:["@donotdev/components","@donotdev/auth","@donotdev/billing","@donotdev/crud","@donotdev/oauth","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder"],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},ot=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"],Be=["@donotdev/core/functions","@donotdev/core/server"],Ve={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}},xe={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},He=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],rt={base:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...Q.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...Q.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:Q.globalIgnore}}});import*as P from"node:fs";import"node:fs";import{createRequire as os}from"node:module";import{resolve as Ae,join as ce,dirname as pe,relative as at,normalize as ns,sep as it,extname as as}from"node:path";import{fileURLToPath as is}from"node:url";import ls from"fast-glob";function lt(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var ve,U,ct,O,q=je(()=>{"use strict";j();ve={getGlobOptionsFor:ke||void 0,SCAN_PATTERNS:Q||void 0,getPatternsFor:nt||void 0,I18N_PATHS:De||void 0},U={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};ct={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},O=class n{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,n._instance=this}normalizePath(e){if(!e)return"";try{return ns(e).split(it).join("/")}catch{return String(e).split(it).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=at(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(pe(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=os(ce(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=Ae(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Ae(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=Ae(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=P.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:as(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await P.promises.readFile(e);let a=await P.promises.readFile(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&U.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return P.readFileSync(e);let a=P.readFileSync(e,r),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&U.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(pe(l)),c=this.pathExists(l);if(c&&!o)return i&&U.info(`Skipping existing file: ${l}`),!1;if(a)return U.info(`[DRY RUN] Would write file: ${l}`),!0;try{await P.promises.mkdir(u,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await lt(async()=>(Buffer.isBuffer(g)?await P.promises.writeFile(l,g):await P.promises.writeFile(l,g,"utf8"),i&&U.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),u=this.normalizePath(pe(l)),c=this.pathExists(l);if(c&&!o)return i&&U.info(`Skipping existing file: ${l}`),!1;if(a)return U.info(`[DRY RUN] Would write file: ${l}`),!0;try{P.mkdirSync(u,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let p=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:p==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return Buffer.isBuffer(g)?P.writeFileSync(l,g):P.writeFileSync(l,g,"utf8"),i&&U.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(d){throw new Error(`Failed to write file: ${l}: ${d instanceof Error?d.message:String(d)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&U.info(`Skipping existing file: ${i}`),!1;if(o)return U.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(pe(i));try{await P.promises.mkdir(u,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await lt(async()=>(await P.promises.copyFile(e,i),a&&U.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&U.info(`Skipping existing file: ${i}`),!1;if(o)return U.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(pe(i));try{P.mkdirSync(u,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return P.copyFileSync(e,i),a&&U.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return P.existsSync(e)}catch(s){return t||U.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return P.existsSync(t)||P.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return P.readdirSync(e,t)}catch(s){return this.options.debug&&U.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return P.statSync(e)}catch(t){return this.options.debug&&U.warn(`Failed to stat file: ${e}`,t),null}}lstatSync(e){try{return P.lstatSync(e)}catch(t){return this.options.debug&&U.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await P.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{P.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await P.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){P.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return P.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=ce(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Ae(e)),s=this.getAppRoot(),r=at(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(ce(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=r.startsWith(a)?r.slice(a.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:ve.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ve.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(ce(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await ls(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=ve.getGlobOptionsFor?ve.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),i=e.framework.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),u={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=i.length>0?await this._globWithNormalization(i,u):[],p=await this._globWithNormalization(l,u);return{frameworkFiles:c,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ve.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=ve.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=r,u={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let a=r,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(e=!1){if(e)return"@donotdev/core/empty";let t=this.resolvePackage("@donotdev/core/empty");if(t)return t;let s=pe(is(import.meta.url));return this.normalizePath(ce(s,"../empty.js"))}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(ce(t,ct.TOOLING)),a=this.normalizePath(ce(t,ct.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=ce(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(ce(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(pe(t))===t)return t;let u=this.normalizePath(pe(t));if(u===t)break;t=u,s++}return this.normalizePath(e)}}});var Ht={};Zt(Ht,{createDndevPlugin:()=>nr});import{realpathSync as js,watch as Us}from"node:fs";import{execSync as Me,spawn as Gs}from"node:child_process";function J(){return O.getInstance()}function Ut(){return J().getRepoRoot()}function Gt(){return J().resolveRepoPath(".dndev")}function y(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function Pe(n,e=Ws){return new Promise((t,s)=>{let r="",o=0;n.on("data",a=>{if(o+=a.length,o>e){n.destroy(),s(new Error("Request body too large"));return}r+=a.toString()}),n.on("end",()=>t(r)),n.on("error",s)})}function Bs(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function Vs(){let n=J(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",o=Me(r,{encoding:"utf8"}).trim().split(`
|
|
2
|
+
`)[0];e.push(o)}catch{}let s=[process.env.NVM_DIR,n.resolvePath(".nvm",t)].filter(Boolean);for(let r of s)try{let o=n.resolvePath("versions/node",r),a=n.readdirSync(o).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/bin/node`,o))}catch{}if(process.env.NVM_BIN&&e.push(n.resolvePath("node",process.env.NVM_BIN)),process.platform==="win32"){e.push("C:\\Program Files\\nodejs\\node.exe");let r=process.env.APPDATA||"";if(r)try{let o=n.resolvePath("nvm",r),a=n.readdirSync(o).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/node.exe`,o))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let r of e)try{let o=js(r);if(o.includes("bun")||!n.pathExists(o))continue;return r}catch{continue}return"node"}function Wt(n){if(!n||typeof n!="string"||n.includes("\0"))return!1;let e=n.split(/[/\\]/).filter(Boolean);for(let t of e)if(t==="."||t===".."||t==="node_modules"||t===".git"||t.startsWith(".")&&t!==".dndev")return!1;return!0}function Hs(n){return n.includes("..")?!1:n.startsWith(".dndev/")||n.startsWith("docs/")||n.startsWith("guides/")}function Bt(n){let e=J(),t=e.getRepoRoot(),s=e.resolvePath(n,t),r=e.normalizePath(t),o=e.normalizePath(s);return!o.startsWith(r+"/")&&o!==r?null:s}async function qs(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!s)return y(e,{error:"path parameter required"},400);if(!Wt(s))return y(e,{error:"Access denied"},403);let r=Bt(s);if(!r)return y(e,{error:"Access denied"},403);let o=J();if(!o.pathExists(r))return y(e,{error:"File not found"},404);let a=Bs(r);if(Js.has(a)){let i=o.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":Vt[a]||"application/octet-stream","Content-Length":i.byteLength}),void e.end(Buffer.from(i))):y(e,{error:"Failed to read file"},500)}if(a===".json")try{let i=await o.read(r);return i===null?y(e,{error:"Failed to read file"},500):y(e,{path:s,content:i})}catch{return y(e,{error:"Invalid JSON"},500)}try{let i=await o.read(r,{format:"text"});if(i===null)return y(e,{error:"Failed to read file"},500);y(e,{path:s,content:i})}catch{y(e,{error:"Failed to read file"},500)}}function Ys(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("dir"),r=J(),o=r.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(c,p){try{let g=r.readdirSync(c,{withFileTypes:!0});for(let d of g){let h=p?`${p}/${d.name}`:d.name;d.isDirectory()&&i.has(d.name)||(d.isDirectory()?(a.push({path:h,name:d.name,isDirectory:!0}),l(r.resolvePath(d.name,c),h)):d.name.endsWith(".md")&&a.push({path:h,name:d.name,isDirectory:!1}))}}catch{}}let u=[".dndev","docs","guides"];if(s){if(s.includes("..")||s.includes("\0"))return y(e,{error:"Access denied"},403);if(!u.includes(s)&&!u.some(d=>s.startsWith(d+"/")))return y(e,{error:"Directory not allowed"},403);let c=r.resolvePath(s,o),p=r.normalizePath(o);if(!r.normalizePath(c).startsWith(p+"/"))return y(e,{error:"Access denied"},403);r.pathExists(c)&&(a.push({path:s,name:r.getBasename(s),isDirectory:!0}),l(c,s))}else{for(let c of u){let p=r.resolveRepoPath(c);r.pathExists(p)&&(a.push({path:c,name:c,isDirectory:!0}),l(p,c))}try{let c=r.readdirSync(o,{withFileTypes:!0});for(let p of c)!p.isDirectory()&&p.name.endsWith(".md")&&a.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}y(e,{entries:a})}async function Ks(n,e){let s=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!s)return y(e,{error:"path parameter required"},400);if(!Wt(s))return y(e,{error:"Access denied"},403);if(!Hs(s))return y(e,{error:"Write not allowed to this path"},403);let r=Bt(s);if(!r)return y(e,{error:"Access denied"},403);try{let o=await Pe(n),{content:a}=JSON.parse(o);if(a===void 0)return y(e,{error:"content field required"},400);let i=typeof a=="string"?a:JSON.stringify(a,null,2);await J().write(r,i,{overwrite:!0}),y(e,{ok:!0})}catch{y(e,{error:"Failed to write file"},500)}}async function Zs(n,e){try{let t=await Pe(n),{line:s,checked:r}=JSON.parse(t);if(typeof s!="number")return y(e,{error:"line number required"},400);let o=J(),a=o.resolveRepoPath(".dndev/implementation.md");if(!o.pathExists(a))return y(e,{error:"implementation.md not found"},404);let i=await o.read(a,{format:"text"});if(i===null)return y(e,{error:"Failed to read file"},500);let l=i.split(`
|
|
3
|
+
`);if(s<0||s>=l.length)return y(e,{error:"Line out of range"},400);let u=l[s];l[s]=r?u.replace("- [ ]","- [x]"):u.replace("- [x]","- [ ]"),await o.write(a,l.join(`
|
|
4
|
+
`),{overwrite:!0}),y(e,{ok:!0,line:l[s]})}catch{y(e,{error:"Failed to update progress"},500)}}async function Xs(n,e){try{let t=await Pe(n),{id:s,data:r}=JSON.parse(t);if(!s||!r)return y(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(s))return y(e,{error:"Invalid screenshot ID"},400);let o=J(),a=o.resolveRepoPath(".dndev/bugs");o.ensureDirSync(a);let i=Buffer.from(r,"base64"),l=o.resolvePath(`${s}.png`,a);await o.write(l,i,{overwrite:!0}),y(e,{ok:!0,path:`.dndev/bugs/${s}.png`})}catch{y(e,{error:"Failed to save screenshot"},500)}}async function Qs(n,e){try{let t=await Pe(n),{action:s,phase:r}=JSON.parse(t);if(!s||typeof r!="number")return y(e,{error:"action and phase required"},400);let o=J(),a=Gt();o.ensureDirSync(a);let i=o.resolvePath("protocol.json",a),l={currentPhase:0,phases:{}};if(o.pathExists(i))try{let u=await o.read(i);u&&(l=u)}catch{}s==="start"?(l.currentPhase=r,l.phases[r]||(l.phases[r]={}),l.phases[r].status="active",l.phases[r].startedAt=new Date().toISOString()):s==="complete"&&(l.phases[r]||(l.phases[r]={}),l.phases[r].status="completed",l.phases[r].completedAt=new Date().toISOString()),await o.write(i,l,{overwrite:!0}),y(e,{ok:!0,protocol:l})}catch{y(e,{error:"Failed to update phase"},500)}}function er(n,e){try{let t=Ut(),s=Me("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=Me("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();y(e,{commit:s,branch:r})}catch{y(e,{commit:"unknown",branch:"unknown"})}}async function tr(n,e){try{let t=await Pe(n),s=JSON.parse(t);if(!s.id||!s.type||!s.result)return y(e,{error:"id, type, and result required"},400);let r=J(),o=Gt();r.ensureDirSync(o);let a=r.resolvePath("health.json",o),i={actions:[]};if(r.pathExists(a))try{let u=await r.read(a);u&&(i=u)}catch{}Array.isArray(i.actions)||(i.actions=[]);let l=i.actions.findIndex(u=>u.id===s.id);l>=0?i.actions[l]={...i.actions[l],...s}:i.actions.unshift(s),await r.write(a,i,{overwrite:!0}),y(e,{ok:!0})}catch{y(e,{error:"Failed to append action"},500)}}function sr(n,e){let t=J(),s=t.resolveRepoPath("apps");try{let o=t.readdirSync(s).filter(a=>{if(a==="dndev")return!1;let i=t.resolvePath(a,s);return t.statSync(i)?.isDirectory()&&t.pathExists(t.resolvePath("package.json",i))}).map(a=>{try{let i=t.resolvePath(`${a}/package.json`,s),l=t.readSync(i);return{name:a,packageName:l?.name||a}}catch{return{name:a,packageName:a}}});y(e,{apps:o})}catch{y(e,{apps:[]})}}function rr(n){if(Ze)return;let e=J(),t=e.normalizePath(n.config.root),s=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(s))return;try{let i=Me(`fuser ${jt}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}Ze=!0;let r=e.getRepoRoot(),o=Vs(),a=Gs(o,[s],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(jt),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{Ze=!1}),process.on("exit",()=>{a.kill()})}function or(n){let e=J(),t=e.getRepoRoot(),s=[".dndev","docs","guides"];for(let r of s){let o=e.resolveRepoPath(r);if(!e.pathExists(o))continue;let a=Us(o,{recursive:!0},(i,l)=>{if(!l||l==="dashboard.json")return;let u=`${r}/${l}`,c=`change:${u}`;Xe.has(c)||(Xe.set(c,!0),setTimeout(()=>Xe.delete(c),300),n.hot.send("dndev:file-changed",{path:u,timestamp:Date.now()}))});n.httpServer?.on("close",()=>a.close())}}function nr(n={}){return{name:"dndev",configureServer(e){let t=Ut();n.debug,e.middlewares.use((s,r,o)=>{let a=s.url;if(!a?.startsWith(zt))return o();let l=new URL(a,`http://${s.headers.host}`).pathname.slice(zt.length),u=s.method?.toUpperCase();if(u==="GET")return l==="/file"?void qs(s,r):l==="/tree"?void Ys(s,r):l==="/git/head"?void er(s,r):l==="/apps"?void sr(s,r):y(r,{error:"Not found"},404);if(u==="POST")return l==="/file"?void Ks(s,r):l==="/progress/toggle"?void Zs(s,r):l==="/bugs/screenshot"?void Xs(s,r):l==="/phase"?void Qs(s,r):l==="/actions/append"?void tr(s,r):y(r,{error:"Not found"},404);y(r,{error:"Method not allowed"},405)}),rr(e),or(e)}}}var zt,Ws,Vt,Js,jt,Ze,Xe,Jt=je(()=>{"use strict";q();zt="/api/dndev";Ws=5*1024*1024;Vt={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},Js=new Set(Object.keys(Vt));jt=24681,Ze=!1;Xe=new Map});import us from"@rollup/plugin-strip";import{visualizer as ps}from"rollup-plugin-visualizer";var Ue=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-day-picker/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],Xt={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/i18next-http-backend/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function Qt(n){let e=n.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function et(n){let e=n.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function tt(n,e=Ue){return e.some(t=>n.includes(t))}function es(n){for(let[e,t]of Object.entries(Xt))if(t.some(s=>n.includes(s)))return e}function ts(n){let e=Qt(n);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":"virtual-modules";let t=et(n);if(!t)return;if(tt(t))return"react-core";let s=es(t);if(s)return s}function ss(n=[]){let e=n.filter(s=>!Ue.includes(s)),t=[...Ue,...e];return function(s){let r=et(s);if(r&&tt(r,t))return"react-core"}}var Qe={development:{manualChunks:void 0},production:{manualChunks:ts}};function st(n,e={}){let t=Qe[n]||Qe.production,s=e.reactCore||[];return s.length>0?{manualChunks:ss(s)}:t}q();import*as Y from"@clack/prompts";var re={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function cs(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function ae(n,e){return cs()?`${e}${n}${re.reset}`:n}function T(n,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,a=O.getInstance(),i=null;if(o){let c=a.resolveAppPath(r);a.pathExists(c)||a.mkdir(c),i=a.resolveAppPath(`${r}/${n.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${n} Log Started at ${new Date().toISOString()} ===
|
|
5
|
+
`;a.writeSync(i,p)}let l=(c,p,g)=>{if(i){let d=new Date().toISOString(),h=g.length>0?" "+g.map(I=>typeof I=="object"?JSON.stringify(I,null,2):String(I)).join(" "):"",F=`${d} [${c}] ${p}${h}
|
|
6
|
+
`;a.appendFile(i,F)}},u=(c,p)=>{if(p.length===0)return c;let g=p.map(d=>typeof d=="object"?JSON.stringify(d,null,2):String(d)).join(" ");return`${c} ${g}`};return{debug:(c,...p)=>{e&&(o?l("DEBUG",c,p):Y.log.message(ae(u(c,p),re.gray)))},verbose:(c,...p)=>{t&&(o?l("VERBOSE",c,p):Y.log.message(u(c,p)))},info:(c,...p)=>{o?l("INFO",c,p):Y.log.info(ae(u(c,p),re.brightCyan))},warn:(c,...p)=>{e&&o?l("WARN",c,p):Y.log.warn(ae(u(c,p),re.brightYellow))},error:(c,...p)=>{e&&o?l("ERROR",c,p):Y.log.error(ae(u(c,p),re.brightRed))},success:(c,...p)=>{e&&o?l("SUCCESS",c,p):Y.log.success(ae(u(c,p),re.brightGreen))},when:(c,p="debug")=>(g,...d)=>{if(c){let h=u(g,d);switch(p){case"verbose":t&&(Y.log.message(h),l("VERBOSE",g,d));break;case"info":Y.log.info(ae(h,re.brightCyan)),l("INFO",g,d);break;case"warn":Y.log.warn(ae(h,re.brightYellow)),l("WARN",g,d);break;case"error":Y.log.error(ae(h,re.brightRed)),l("ERROR",g,d);break;case"success":Y.log.success(ae(h,re.brightGreen)),l("SUCCESS",g,d);break;default:e&&(Y.log.message(ae(h,re.gray)),l("DEBUG",g,d))}}},getLogFilePath:()=>i}}q();function ut(n={}){let{mode:e="development",chunkingOptions:t={},debug:s,verbose:r=!0,isDev:o,isDebug:a,shouldAnalyze:i,build:l={}}=n,u=T("build",s,r),c=st(e,t);return u.debug("\u{1F41B} DEBUG MODE ENABLED:"),u.debug(" - Minification: DISABLED"),u.debug(" - Sourcemaps: ENABLED"),u.debug(" - Console logs: PRESERVED"),u.debug(" - Debugger statements: PRESERVED"),i&&(u.info("\u{1F4CA} Bundle analysis enabled"),u.info(` Visual treemap will open after build (stats.html)
|
|
7
|
+
`)),{outDir:"dist",sourcemap:o||a,cacheDir:"node_modules/.vite",target:"baseline-widely-available",minify:a?!1:"esbuild",reportCompressedSize:!1,chunkSizeWarningLimit:2048,assetsInlineLimit:0,esbuild:{format:"esm",drop:a?[]:["console","debugger"],legalComments:"none"},cssMinify:a?!1:"esbuild",cssCodeSplit:!0,rollupOptions:{external:gs(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...c.manualChunks&&{manualChunks:c.manualChunks},compact:!0},onwarn(g,d){g.code!=="MODULE_LEVEL_DIRECTIVE"&&d(g)},plugins:[...a?[]:[us({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let g=O.getInstance(),d=g.getAppRoot(),h="dist",F=g.resolveAppPath(`${h}/stats.html`),I=()=>{try{let $=g.resolveAppPath(h);g.pathExists($)||g.mkdir($)}catch{}},S=ps({filename:F,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:o||a,projectRoot:d});if(S.buildStart){let $=S.buildStart.bind(S);S.buildStart=function(...b){I();let w=$.apply(this,b);return w&&typeof w.then=="function"?w.catch(m=>{}):w}}else S.buildStart=function(){I()};let _=["generateBundle","writeBundle","closeBundle"];for(let $ of _)if(S[$]){let b=S[$];S[$]=function(...w){try{I();let m=b.apply(this,w);return m&&typeof m.then=="function"?m.catch(D=>{let A=D?.message||D?.toString()||String(D)||"Unknown error";u.warn(`Bundle visualizer warning in ${$}: ${A}`),$==="closeBundle"&&u.warn(`You can manually open ${F} to view the bundle analysis`)}):m}catch(m){let D=m?.message||m?.toString()||String(m)||"Unknown error";buildLogger.warn(`Bundle visualizer warning in ${$}: ${D}`),$==="closeBundle"&&buildLogger.warn(` You can manually open ${F} to view the bundle analysis`)}}}return S})()]:[]]}}}function gs(n){return n?["firebase-admin","gcp-metadata","google-logging-utils","@google-cloud/firestore",/\.node$/,"esbuild",/@esbuild\/.*/]:["gcp-metadata","google-logging-utils","payload","file-type","firebase-admin","firebase-admin/app","firebase-admin/auth","firebase-admin/firestore","firebase-admin/functions","firebase-admin/credential","@google-cloud/firestore","google-auth-library","google-gax","googleapis-common"]}function ds(){let n=!1,e=O.getInstance();if((e.pathExists("/.dockerenv")||e.pathExists("/run/.containerenv"))&&(n=!0),!n&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(n=!0),!n&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(n=!0),!n&&process.platform==="linux"&&e.pathExists("/proc/self/cgroup"))try{let r=e.readSync("/proc/self/cgroup");r&&(r.includes("docker")||r.includes("containerd"))&&(n=!0)}catch{}let t=!1;if((process.env.WSL_DISTRO_NAME||process.env.WSLENV)&&(t=!0),!t&&process.platform==="linux"&&e.pathExists("/proc/version"))try{let r=(e.readSync("/proc/version")||"").toLowerCase();t=r.includes("microsoft")||r.includes("wsl")}catch{}if(!t&&process.platform==="linux"&&e.pathExists("/proc/sys/kernel/osrelease"))try{let r=(e.readSync("/proc/sys/kernel/osrelease")||"").toLowerCase()||"";(r.includes("microsoft")||r.includes("wsl"))&&(t=!0)}catch{}if(!t&&process.platform==="win32"){let r=process.cwd();r&&(r.includes("\\wsl$")||r.includes("\\wsl.localhost"))&&(t=!0)}let s=typeof process.versions?.bun=="string";return{isDocker:n,isWSL2:t,isBun:s}}function fs(n,e){if(n!==void 0)return n;let{isDocker:t,isWSL2:s,isBun:r}=ds();if(t||s||r){let o=t?"Docker":s?"WSL2":"Bun";return e.info(`Detected ${o} environment - enabling polling mode for file watching`),!0}}function pt(n,e={},t){let s=O.getInstance(),r=s.getRepoRoot(),{watch:o,hmr:a,host:i,...l}=e||{},u=a||{},c=i===!0?"localhost":i||"localhost",p={...u.port&&{port:u.port},...u.clientPort&&{clientPort:u.clientPort},host:u.host??c,...u.protocol&&{protocol:u.protocol},overlay:u.overlay??!0,timeout:u.timeout??5e3},g=i!==void 0?i:!0,d=l.https===!0;return{port:n,host:g,open:e.open!==void 0?e.open:!0,https:d,fs:{allow:[r,s.resolveRepoPath("packages"),s.resolveRepoPath("node_modules")],strict:!1},watch:{usePolling:fs(e?.watch?.usePolling,t),interval:e?.watch?.interval??2e3,...e?.watch||{}},hmr:{...p,...u},headers:{"Cross-Origin-Opener-Policy":"same-origin-allow-popups","Cross-Origin-Embedder-Policy":"unsafe-none"},middlewareMode:!1,...l}}function gt(n={}){let e=n.https===!0;return{...n,https:e}}j();var ee={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function ge(n,e,t,s={}){let{protectedKeys:r=[],onConflict:o}=s;if(e==null)return n;switch(t){case ee.CONCATENATE_DEDUPE:{if(!Array.isArray(n)||!Array.isArray(e))return e;let a=[...n,...e];return[...new Set(a)]}case ee.SHALLOW_MERGE:return typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e)?e:{...n,...e};case ee.DEEP_MERGE:{if(typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e))return e;let a={...n};for(let i in e){if(r.includes(i)){o&&o(i,n[i],e[i]);continue}typeof a[i]=="object"&&typeof e[i]=="object"&&a[i]!==null&&e[i]!==null&&!Array.isArray(a[i])&&!Array.isArray(e[i])?a[i]=ge(a[i],e[i],ee.DEEP_MERGE,{protectedKeys:r,onConflict:o}):a[i]=e[i]}return a}case ee.REPLACE:default:return e}}function dt(n,e,t=[],s){let r=[...n,...e||[]],o=[...new Set(r)];return[...new Set([...o,...t])]}var Ne={base:"/",mode:process.env.NODE_ENV==="production"?"production":"development",debug:!1,verbose:process.env.CI!=="true",server:{port:3e3,strictPort:!0,host:!0,open:!0,cors:!0,https:!0,hmr:{overlay:!0,timeout:5e3,usePolling:void 0,interval:2e3},watch:{usePolling:void 0,interval:2e3}},build:{sourcemap:!0,target:"es2020",minify:"esbuild",cssMinify:"esbuild",analyze:!0},preview:{port:4173,strictPort:!0,host:!0,open:!1,cors:!0,https:!0},routes:{hmr:!0},themes:{},i18n:{},assets:{},features:{},pwa:{enabled:!1},seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0},chunking:{reactCore:[]},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},pluginFactory:{verbose:!0,disableHmr:!1,hmrSmartDetection:!0,hmrDebounceMs:500,hmrCacheTimeout:3e4},resolve:{alias:{"@":"/src"},preserveSymlinks:!1},define:{__DEV__:JSON.stringify(process.env.NODE_ENV==="development"),__PROD__:JSON.stringify(process.env.NODE_ENV==="production")},optimizeDeps:{include:[...he.mandatoryIncludes],exclude:[...he.buildTools,...Object.values(C)],esbuildOptions:{format:"esm",target:"es2020",platform:"browser",define:{"process.env.NODE_ENV":JSON.stringify(process.env.NODE_ENV||"development")},external:["next","next/*"]}},plugins:[],css:{},envDir:void 0};function ft(n={},e={}){let{onConflict:t}=e,s={...Ne},r=[],o=(a,i,l,u)=>{r.push({key:a,frameworkValue:i,userValue:l,reason:u}),t&&t(a,i,l,u)};return Object.keys(n).forEach(a=>{let i=n[a],l=s[a];if(a==="optimizeDeps"&&typeof i=="object"&&i!==null){let u=l?.include||[],c=l?.exclude||[],p=i.include||[],g=i.exclude||[],d=u.filter(_=>!_.startsWith("@donotdev/")),h=g.filter(_=>d.includes(_));if(h.length>0)for(let _ of h)o("optimizeDeps.exclude",_,"excluded",`Framework requires ${_} to be included. It will be included despite your exclusion.`);let F=dt(u,p,d),I=ge(c,g,ee.CONCATENATE_DEDUPE),S=ge(l?.esbuildOptions||{},i.esbuildOptions||{},ee.DEEP_MERGE,{protectedKeys:["external"],onConflict:_=>o(`optimizeDeps.esbuildOptions.${_}`,l?.esbuildOptions?.[_],i.esbuildOptions?.[_],`Framework requires ${_} to remain as configured.`)});s[a]={...l,include:F,exclude:I,esbuildOptions:S,...Object.fromEntries(Object.entries(i).filter(([_])=>!["include","exclude","esbuildOptions"].includes(_)))};return}if(a==="css"&&typeof i=="object"&&i!==null){s[a]=ge(l||{},i,ee.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>o("css.postcss","framework PostCSS config",i.postcss,"Framework PostCSS config is required and cannot be overridden. Your postcss config is ignored.")});return}if(a==="define"&&typeof i=="object"&&i!==null){s[a]=ge(l||{},i,ee.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:u=>o(`define.${u}`,l?.[u],i[u],`Framework requires ${u} to remain as configured.`)});return}if(Array.isArray(i)){Array.isArray(l)?s[a]=ge(l,i,ee.CONCATENATE_DEDUPE):s[a]=i;return}if(typeof i=="object"&&i!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){s[a]=ge(l,i,ee.SHALLOW_MERGE);return}s[a]=i}),s}function mt(n){let{server:e={},preview:t={},mode:s,build:r={},resolve:o={},routes:a={},themes:i={},i18n:l={},assets:u={},features:c={},seo:p={},pwa:g={},serverShim:d={},chunking:h={},discovery:F={},pluginFactory:I={},debug:S,verbose:_,base:$,define:b={},optimizeDeps:w={},plugins:m=[],css:D={},envDir:A,...K}=n,E=s!=="production",x=S||E,G=s==="production"&&(r.analyze??Ne.build.analyze);return{mode:s,debug:S,verbose:_,isDev:E,isDebug:x,shouldAnalyze:G,serverOptions:e,previewOptions:t,buildOverrides:r,resolveOptions:o,routeOptions:a,themeOptions:i,i18nOptions:l,assetOptions:u,featureOptions:c,seoOptions:p,pwaOptions:g,serverShimOptions:d,chunkingOptions:h,discoveryOptions:F,pluginFactoryOptions:I,base:$,defineOptions:b,optimizeDepsOptions:w,pluginsOptions:m,cssOptions:D,envDir:A,restOptions:K}}q();import{resolve as ms}from"node:path";import hs from"autoprefixer";import vs from"postcss-import";import ys from"postcss-nesting";function ht({postcssImport:n,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?n({resolve:s}):n,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function vt(n={}){if(n.postcss)return n.postcss;let e=O.getInstance();return ht({postcssImport:vs,postcssNesting:ys,autoprefixer:hs,resolve:(s,r)=>{let o=e.resolvePackage(s,r);if(o)return o;if(s.startsWith("@donotdev/")){let a=s.split("/")[0]+"/"+s.split("/")[1],i=s.split("/").slice(2).join("/"),l=e.resolveFrameworkPackage(a,r);if(l&&i){let u=e.resolvePath(i,l);if(e.pathExists(u))return u}}return ms(r,s)}})}import Cs from"@vitejs/plugin-basic-ssl";import Ms from"@vitejs/plugin-react";import Ls from"vite-tsconfig-paths";var V=class{static generateVirtualModule(e,t,s=!1,r=void 0,o=void 0){return t.isEmpty(e)?t.generateEmpty(e,s,r,o):t.generateModule(e,s,o)}static generateInspection(e,t,s,r){return t.generateInspection.length>=3?t.generateInspection(e,s,r):t.generateInspection(e,s)}static wrapVirtualModule(e,t){return`// Virtual module: ${e}
|
|
9
8
|
// Generated by @donotdev/config discovery
|
|
10
9
|
// Version: 1.0.0
|
|
11
10
|
|
|
12
|
-
${
|
|
11
|
+
${t}`}static generateGlobals(e,t,s=""){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return`
|
|
13
12
|
if (typeof window !== 'undefined') {
|
|
14
|
-
window.${
|
|
13
|
+
window.${e} = ${r};
|
|
15
14
|
${s?`console.log('${s}');`:""}
|
|
16
|
-
}`}static generateInspectionHeader(t
|
|
17
|
-
// Generated by @donotdev/config ${
|
|
18
|
-
// Version: 1.0.0${
|
|
19
|
-
// Source: ${
|
|
15
|
+
}`}static generateInspectionHeader(e,t="",s=""){return`// Auto-generated ${e} inspection file
|
|
16
|
+
// Generated by @donotdev/config ${e} discovery at ${new Date().toISOString()}
|
|
17
|
+
// Version: 1.0.0${t?`
|
|
18
|
+
// Source: ${t}`:""}${s?`
|
|
20
19
|
// Runtime usage: ${s}`:""}
|
|
21
20
|
|
|
22
|
-
`}static generateExports(
|
|
21
|
+
`}static generateExports(e){return Object.entries(e).map(([t,s])=>typeof s=="function"?`export ${s.toString().replace("function ",`function ${t} `)};`:`export const ${t} = ${JSON.stringify(s,null,2)};`).join(`
|
|
23
22
|
|
|
24
|
-
`)}static generateDefaultExport(
|
|
23
|
+
`)}static generateDefaultExport(e){return`export default ${JSON.stringify(e,null,2)};`}static generateManifest(e,t){let s={generatedAt:new Date().toISOString(),version:"1.0.0",timestamp:Date.now()};return t&&typeof t=="function"?{...s,...t(e)}:s}static generateCSSModule(e){if(e.size===0)return`// No utilities generated
|
|
25
24
|
export const utilities = {};
|
|
26
|
-
export default utilities;`;let
|
|
25
|
+
export default utilities;`;let t=Object.fromEntries(e);return`// Auto-generated utility classes from discovered CSS variables
|
|
27
26
|
// Generated by @donotdev/config at ${new Date().toISOString()}
|
|
28
27
|
// Version: 1.0.0
|
|
29
28
|
|
|
30
|
-
export const utilities = ${JSON.stringify(
|
|
29
|
+
export const utilities = ${JSON.stringify(t,null,2)};
|
|
31
30
|
|
|
32
|
-
export const utilityNames = ${JSON.stringify(Array.from(
|
|
31
|
+
export const utilityNames = ${JSON.stringify(Array.from(e.keys()),null,2)};
|
|
33
32
|
|
|
34
33
|
export const stats = {
|
|
35
|
-
totalUtilities: ${
|
|
34
|
+
totalUtilities: ${e.size},
|
|
36
35
|
generatedAt: '${new Date().toISOString()}'
|
|
37
36
|
};
|
|
38
37
|
|
|
39
|
-
export default utilities;`}static generateHelperFunctions(t
|
|
38
|
+
export default utilities;`}static generateHelperFunctions(e,t){let s=Object.entries(t).map(([r,o])=>typeof o=="function"?o.toString().replace("function ",`function ${r} `):`function ${r}() { ${o} }`).join(`
|
|
40
39
|
|
|
41
|
-
`);return`// Helper functions for ${
|
|
40
|
+
`);return`// Helper functions for ${e}
|
|
42
41
|
// Generated by @donotdev/config
|
|
43
42
|
|
|
44
|
-
${s}`}static validateTemplates(
|
|
43
|
+
${s}`}static validateTemplates(e){return["isEmpty","generateModule","generateEmpty","generateInspection"].every(s=>e[s]&&typeof e[s]=="function")}static createTemplateConfig(e,t){let{isEmpty:s=()=>!1,generateModule:r=()=>"",generateEmpty:o=()=>"",generateInspection:a=()=>"",generateManifest:i=()=>({}),logConfig:l=()=>{},logStats:u=()=>{},logManifest:c=()=>{}}=t;return{isEmpty:s,generateModule:r,generateEmpty:o,generateInspection:a,generateManifest:i,logConfig:l,logStats:u,logManifest:c,pluginName:e,version:"1.0.0",createdAt:new Date().toISOString()}}static getEmptyResultWithError(e,t){let s=t?.message||t||"Unknown error";if(e&&typeof e._getEmptyResult=="function")try{let r=e._getEmptyResult();return r.errors&&Array.isArray(r.errors)?r.errors.push(s):r.errors===void 0&&(r.errors=[s]),r.source==="empty"&&(r.source="error"),r}catch{return{errors:[s],source:"error"}}return{errors:[s],source:"error"}}};q();function ie(n){let{pluginName:e,icon:t,virtualModuleId:s,DiscoveryClass:r,discoveryMethod:o,filePatterns:a,templates:i,defaultInspectionPath:l,manifestFileName:u,createDiscovery:c,discoveryOptions:p={},configKey:g}=n;return function(h={}){let{debug:F,verbose:I,virtualModuleId:S=s,inspectionFilePath:_=l,hmrDebounceMs:$,hmrCacheTimeout:b,hmrSmartDetection:w,disableHmr:m,...D}=h;if(!V.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let A={...Ne.discovery,...p,debug:F,verbose:I,...D},K=g||(()=>{let f=e.match(/dndev-vite-(\w+)-discovery/);return f?f[1]:null})(),E=T(e,F,I,{fileLogging:A.fileLogging,logDir:A.logDir}),x=O.getInstance(),G=()=>{let f=x.getAppRoot(),v=x.getRepoRoot();return f&&f!==v},ye=Date.now(),Z=c?c(x,A):new r(x,A),oe="\0"+S,R="",N=!1,k=null,L=0,fe=!1,W=null,le=!1,ue=null,me=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(Z.clearCache(),W=null,E.info("Discovery cache cleared manually"),"Cache cleared"));function Le(f){let M=V.generateVirtualModule(f,i,F,A,K).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!m&&N&&(M+=`
|
|
45
44
|
|
|
46
|
-
// HMR boundary for ${
|
|
45
|
+
// HMR boundary for ${e}
|
|
47
46
|
if (import.meta.hot) {
|
|
48
47
|
import.meta.hot.accept();
|
|
49
48
|
}
|
|
50
|
-
`),Y}function or(b){return ae.generateInspection(b,a,F,M)}async function vt(){if(F)try{let b=await ve[i](),S=or(b),Y=_.resolveAppPath(C);await _.write(Y,S),I.debug(`Generated inspection file: ${_.getRelativePath(Y)}`)}catch(b){I.error(`${t} failed to write inspection file (${C}): ${b.message}`),I.error(`Stack: ${b.stack||"No stack trace available"}`)}}function _t(b){let S=b.replace(/\\/g,"/");if(E||S.includes("/node_modules/")||S.includes("/.git/")||S.includes("/dist/")||S.includes("/build/")||S.includes("/coverage/")||S.includes("/.vite/")||S.includes("/.turbo/")||S.endsWith(".d.ts")||S.endsWith(".tsbuildinfo")||S.endsWith(".map")||S.endsWith(".css.map")||S.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(S))return!1;let Y=_.getRelativePath(S);if(Y.startsWith("packages/"))return!1;let ke=Y.startsWith("src/")&&/\.(ts|tsx)$/.test(Y);return ke?Array.isArray(o)&&o.length>0?o.some(Se=>typeof Se=="function"?Se(S):typeof Se=="string"?Se.startsWith("**/")?S.endsWith(Se.slice(3)):S.endsWith(Se):!1):ke:!1}function Nt(b){if(E)return I.debug("Virtual modules are static - HMR disabled"),[];let S=Date.now();return je?(I.debug("HMR already in progress, skipping update"),[]):S-K<O?(Ke||(Ke=!0,L=setTimeout(()=>{Ke=!1,K=Date.now(),It(b)},O)),[]):(K=S,It(b))}function It(b){let S=Date.now();if(Ge===b.file&&S-K<100)return I.debug(`Same file processed too recently: ${b.file}`),[];if(!_t(b.file))return I.debug(`Skipping irrelevant file change: ${b.file}`),[];I.debug(`Relevant file changed: ${b.file}`),je=!0,Ge=b.file;try{let Y=Date.now()-(ne?.timestamp||0);if(Y<$&&ne){I.debug(`Using cached discovery data (age: ${Y}ms)`);let Se=b.server.moduleGraph.getModuleById($e);return Se&&b.server.reloadModule(Se),[]}ve.clearCache();let ke=b.server.moduleGraph.getModuleById($e);return ke&&b.server.reloadModule(ke),L&&clearTimeout(L),L=setTimeout(()=>{vt()},500),[]}finally{je=!1,setTimeout(()=>{Ge===b.file&&(Ge=null)},200)}}return{name:t,enforce:"pre",configResolved(b){F=b.root,z=b.command==="serve",G&&I.debug(`${r} ${t} initialized`),z&&I.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),a.logConfig&&a.logConfig(M)},config(b){return b.optimizeDeps||(b.optimizeDeps={}),b.optimizeDeps.exclude||(b.optimizeDeps.exclude=[]),b.optimizeDeps.exclude.includes(N)||b.optimizeDeps.exclude.push(N),b},resolveId(b){return b===N?(I.debug(`Resolving virtual module: ${b}`),{id:$e,moduleSideEffects:!0}):null},async load(b){if(b!==$e)return null;if(I.debug(`Loading virtual module: ${b}`),!se()){I.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let S=0;for(;!se()&&S<100;)await new Promise(Y=>setTimeout(Y,10)),S++;if(!se())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let S;return ne?(I.debug("Using cached discovery data for virtual module"),S=ne):(I.warn(`\u26A0\uFE0F No cached discovery data found for ${t} - running discovery in load() hook. This may indicate buildStart() hook did not run or failed. Performance may be impacted.`),S=await ve[i](),ne=S,I.debug("Discovery completed for virtual module")),ir(S)}catch(S){return I.error(`${t} virtual module (${$e}) failed to load: ${S.message}`),I.error(`Stack: ${S.stack||"No stack trace available"}`),a.generateEmpty({},G,M,be)}},async buildStart(){if(Qe=!1,!se()){I.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let b=0;for(;!se()&&b<100;)await new Promise(S=>setTimeout(S,10)),b++;if(!se())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let b=await ve[i](!ne);ne=b,await vt(),a.logStats&&a.logStats(b,r,I)}catch(b){I.error(`${t} discovery failed during file scanning: ${b.message}`),I.error(`Stack: ${b.stack||"No stack trace available"}`),ne=ae.getEmptyResultWithError(ve,b)}finally{Qe=!0}},configureServer(){Qe=!0},handleHotUpdate(b){return E?[]:Qe?Nt(b):(I.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!ne){I.warn("No cached discovery data for manifest generation - skipping");return}try{let b=ae.generateManifest(ne,a.generateManifest);this.emitFile({type:"asset",fileName:u,source:JSON.stringify(b,null,2)}),W&&a.logManifest&&a.logManifest(ne,t)}catch(b){I.error(`${t} manifest generation failed: ${b.message}`),I.error(`Stack: ${b.stack||"No stack trace available"}`)}},transform(b,S){return S===$e?{code:b,map:null}:null}}}}var Fh={generateGlobals:ae.generateGlobals,generateExports:ae.generateExports,generateDefaultExport:ae.generateDefaultExport,wrapVirtualModule:ae.wrapVirtualModule,generateInspectionHeader:ae.generateInspectionHeader,validateTemplates:ae.validateTemplates,createTemplateConfig:ae.createTemplateConfig};ee();var xe=class e{constructor(t,r={}){if(this.constructor===e)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=t,this.options={...r},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=B(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(t=!1){if(!t&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let r=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let n=await this._scanFiles(s),i=await this._processFiles(n);this.cache={...i,timestamp:Date.now()};let o=Date.now()-r;return this.logger.debug(`Discovery completed in ${o}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(t){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(t){let r=this._getPatternType();return await this.pathResolver.resolveFiles(t,r)}_extractFileNameInfo(t){let r=t.split("/"),s=r[r.length-1],n=s.split(".")[0],i=s.split(".").pop();return{fileName:s,baseName:n,extension:i,directory:r.slice(0,-1).join("/")}}async _processSingleFile(t,r){try{let s=this.pathResolver.getFileInfo(t);return s?await r(s):(this.logger.debug(`Could not get file info: ${t}`),null)}catch(s){return this.logger.debug(`Error processing file ${t}: ${s.message}`),null}}async _batchProcessFiles(t,r){return(await Promise.all(t.map(n=>this._processSingleFile(n,r)))).filter(n=>n!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};ee();var Zt=class extends xe{constructor(t,r={}){super(t,{assets:we.assets.fallback,assetPatterns:we.assets.patterns,frameworkPackage:fr.package,assetsPath:fr.assetsPath,modernFormats:we.assets.modern,...r}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(t){let r=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(r),n=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(n)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let o=[],a=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(o=(await this._generateMissingAssets(r))?.generated||[]);let{consumerFiles:l}=t,u=await this._processAssetFiles(l),f=this._buildAssetManifest(u),d=await this._readLogoSvgContent("/logo.svg",r);return{assets:u,manifest:{...f,logoSvgContent:d},copiedAssets:s,generatedAssets:o,pwaIcons:this._extractPWAIcons(u)}}_extractPWAIcons(t){let r=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return t.filter(s=>{let n=s.path.split("/").pop()||"";return r.some(i=>i.test(n))}).map(s=>{let n=s.path.split("/").pop()||"",i=n.match(/(\d+)x(\d+)/),o=i?{width:parseInt(i[1]),height:parseInt(i[2])}:this._getDefaultIconSize(n);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:o,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(n)}})}_getDefaultIconSize(t){return t.includes("apple-touch-icon")?{width:180,height:180}:t.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(t){return t.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(t){return t.includes("maskable")||t.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let t=this.cache?.assets?.length||0,r=this.cache?.copiedAssets?.length||0;return`${t} assets, ${r} copied`}async discoverAssets(t=!1){return await this.discover(t)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(t,r){let s=this.getAssets().map(i=>i.path),n=r||this.options.modernFormats;for(let i of n){let o=`/${t}.${i}`;if(s.includes(o))return o}return null}async _ensureDefaultAssets(t){this.logger.debug("Ensuring default assets with modern format support...");let r=[];try{let s=await this._resolveFrameworkAssetsDir(t);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),r;let n=this.pathResolver.resolveAppPath(yt.public);this.pathResolver.pathExists(n)||(this.pathResolver.mkdir(n),this.logger.debug(`Created public directory: ${n}`));for(let i of this.options.assets)await this._ensureAsset(i,n,s)&&r.push(i);r.length>0&&this.logger.debug(`Added ${r.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return r}async _ensureAsset(t,r,s){let n=this.pathResolver.resolveAppPath(`${yt.public}/${t}`);if(this.pathResolver.pathExists(n))return this.logger.debug(`Asset exists: ${t}`),!1;let i=this.pathResolver.normalizePath(`${s}/${t}`);if(this.pathResolver.pathExists(i)){if(await this.pathResolver.copy(i,n))return this.logger.debug(`Copied framework asset: ${t}`),!0;this.logger.debug(`Failed to copy framework asset: ${t}`)}return!1}async _processAssetFiles(t){let r=[];for(let s of t)try{let n=this.pathResolver.getFileInfo(s);if(n&&n.isFile){let i=s.split("/").pop()||s.split("\\").pop(),o=this._analyzeAsset(i,n.size);o&&r.push(o)}}catch(n){this.logger.debug(`Error processing asset file ${s}: ${n.message}`)}return this.logger.debug(`Processed ${r.length} assets from ${t.length} files`),r}_analyzeAsset(t,r){let s=this._determineAssetType(t),n=this._determineAssetFormat(t);return this.options.assetPatterns.some(o=>this._matchesPattern(t,o))?{path:`/${t}`,name:t,type:s,format:n,size:r,sizeFormatted:this._formatBytes(r),isModern:this.options.modernFormats.includes(n)}:(this.logger.debug(`Asset ${t} does not match any pattern, skipping`),null)}_determineAssetType(t){let r=t.toLowerCase();if(r.includes("favicon"))return"favicon";if(r.includes("logo"))return"logo";if(r.includes("icon"))return"icon";if(r.includes("apple-touch"))return"apple-touch-icon";if(r.includes("android-chrome"))return"android-icon";if(r.includes("manifest"))return"manifest";let s=t.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(t){return t.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(t){if(t===0)return"0 Bytes";let r=1024,s=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(t)/Math.log(r));return parseFloat((t/Math.pow(r,n)).toFixed(2))+" "+s[n]}_matchesPattern(t,r){let s=t.toLowerCase(),n=r.toLowerCase();return s.includes(n.replace("*",""))}_buildAssetManifest(t){let r=t.map(n=>n.path);return{logo:{optimal:this._getOptimalAsset("logo",r,this.options.modernFormats),fallback:this._getOptimalAsset("logo",r,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",r,["svg","ico"]),fallback:this._getOptimalAsset("favicon",r,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",r,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",r,["png"]),512:this._getOptimalAsset("android-chrome-512x512",r,["png"])},manifest:r.find(n=>n.includes("manifest.json"))||null,modernFormats:t.filter(n=>n.isModern).map(n=>n.path),fallbackFormats:t.filter(n=>!n.isModern).map(n=>n.path)}}_getOptimalAsset(t,r,s){for(let n of s){let i=`/${t}.${n}`;if(r.includes(i))return i}return null}async _resolveFrameworkAssetsDir(t){try{let r=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",r);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let n=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(n)?(this.logger.debug(`Using framework assets from: ${n}`),n):(this.logger.debug(`Assets directory not found: ${n}`),null)}catch(r){return this.logger.debug(`Error resolving framework assets directory: ${r.message}`),null}}async _resolvePackage(t,r){try{let s=this.pathResolver.resolveFrameworkPackage(t,r);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${t} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${t}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(t,r){if(!t||!t.endsWith(".svg"))return null;try{let s=t.slice(1),n=this.pathResolver.resolveAppPath(`${yt.public}/${s}`);return this.pathResolver.pathExists(n)&&await this.pathResolver.read(n,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(t){try{let r=await this._resolveFrameworkAssetsDir(t);if(!r)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${r}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let n=this.pathResolver.resolveAppPath(yt.public);this.pathResolver.pathExists(n)||this.pathResolver.mkdir(n);let i=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,i)}catch(r){return this.logger.debug(`Failed to copy framework logo: ${r.message}`),!1}}async _generateMissingAssets(t){let r=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(r))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let n=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],i=[{name:"favicon.svg",format:"svg"}],o=[],a=[];try{let l=await this.pathResolver.read(r,{format:"text"});if(!l)return{generated:[],skipped:[...i,...n].map(f=>f.name),error:"Failed to read logo.svg"};for(let f of i){let d=`${s}/${f.name}`;if(this.pathResolver.pathExists(d)){a.push(f.name);continue}try{await this.pathResolver.write(`public/${f.name}`,l),o.push(f.name)}catch(g){this.logger.debug(`Failed to copy ${f.name}: ${g.message}`),a.push(f.name)}}let u=await Promise.resolve().then(()=>Eo(Fi(),1)).catch(()=>null);if(!u)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),a.push(...n.map(f=>f.name));else for(let f of n){let d=`${s}/${f.name}`;if(this.pathResolver.pathExists(d)){a.push(f.name);continue}try{let g=u.default(r).resize(f.size,f.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),m;f.format==="ico"?m=await g.toFormat("png").toBuffer():m=await g.toFormat(f.format).toBuffer(),await this.pathResolver.write(`public/${f.name}`,m),o.push(f.name)}catch(g){this.logger.debug(`Failed to generate ${f.name}: ${g.message}`),a.push(f.name)}}return{generated:o,skipped:a,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(u=>u.name),error:l.message}}}};ge();var qr={data:null},uf={isEmpty:e=>!e.manifest||e.assets?.length===0,generateModule:(e,t,r="assets")=>{let{manifest:s,assets:n,copiedAssets:i}=e,o=s.logoSvgContent||null,a={totalAssets:n.length,copiedAssets:i.length,hasLogo:s.logo.optimal!==null,hasFavicon:s.favicon.optimal!==null,hasManifest:s.manifest!==null,timestamp:new Date().toISOString()};return`// ${H.assets} - Generated asset manifest
|
|
49
|
+
`),M}function ze(f){return V.generateInspection(f,i,R,A)}async function be(){if(R)try{let f=await Z[o](),v=ze(f),M=x.resolveAppPath(_);await x.write(M,v),E.debug(`Generated inspection file: ${x.getRelativePath(M)}`)}catch(f){E.error(`${e} failed to write inspection file (${_}): ${f.message}`),E.error(`Stack: ${f.stack||"No stack trace available"}`)}}function Re(f){let v=f.replace(/\\/g,"/");if(m||v.includes("/node_modules/")||v.includes("/.git/")||v.includes("/dist/")||v.includes("/build/")||v.includes("/coverage/")||v.includes("/.vite/")||v.includes("/.turbo/")||v.endsWith(".d.ts")||v.endsWith(".tsbuildinfo")||v.endsWith(".map")||v.endsWith(".css.map")||v.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(v))return!1;let M=x.getRelativePath(v);if(M.startsWith("packages/"))return!1;let ne=M.startsWith("src/")&&/\.(ts|tsx)$/.test(M);return ne?Array.isArray(a)&&a.length>0?a.some(se=>typeof se=="function"?se(v):typeof se=="string"?se.startsWith("**/")?v.endsWith(se.slice(3)):v.endsWith(se):!1):ne:!1}function _e(f){if(m)return E.debug("Virtual modules are static - HMR disabled"),[];let v=Date.now();return le?(E.debug("HMR already in progress, skipping update"),[]):v-L<$?(fe||(fe=!0,k=setTimeout(()=>{fe=!1,L=Date.now(),$e(f)},$)),[]):(L=v,$e(f))}function $e(f){let v=Date.now();if(ue===f.file&&v-L<100)return E.debug(`Same file processed too recently: ${f.file}`),[];if(!Re(f.file))return E.debug(`Skipping irrelevant file change: ${f.file}`),[];E.debug(`Relevant file changed: ${f.file}`),le=!0,ue=f.file;try{let M=Date.now()-(W?.timestamp||0);if(M<b&&W){E.debug(`Using cached discovery data (age: ${M}ms)`);let se=f.server.moduleGraph.getModuleById(oe);return se&&f.server.reloadModule(se),[]}Z.clearCache();let ne=f.server.moduleGraph.getModuleById(oe);return ne&&f.server.reloadModule(ne),k&&clearTimeout(k),k=setTimeout(()=>{be()},500),[]}finally{le=!1,setTimeout(()=>{ue===f.file&&(ue=null)},200)}}return{name:e,enforce:"pre",configResolved(f){R=f.root,N=f.command==="serve",F&&E.debug(`${t} ${e} initialized`),N&&E.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),i.logConfig&&i.logConfig(A)},config(f){return f.optimizeDeps||(f.optimizeDeps={}),f.optimizeDeps.exclude||(f.optimizeDeps.exclude=[]),f.optimizeDeps.exclude.includes(S)||f.optimizeDeps.exclude.push(S),f},resolveId(f){return f===S?(E.debug(`Resolving virtual module: ${f}`),{id:oe,moduleSideEffects:!0}):null},async load(f){if(f!==oe)return null;if(E.debug(`Loading virtual module: ${f}`),!G()){E.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let v=0;for(;!G()&&v<100;)await new Promise(M=>setTimeout(M,10)),v++;if(!G())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let v;return W?(E.debug("Using cached discovery data for virtual module"),v=W):(E.warn(`\u26A0\uFE0F No cached discovery data found for ${e} - running discovery in load() hook. This may indicate buildStart() hook did not run or failed. Performance may be impacted.`),v=await Z[o](),W=v,E.debug("Discovery completed for virtual module")),Le(v)}catch(v){return E.error(`${e} virtual module (${oe}) failed to load: ${v.message}`),E.error(`Stack: ${v.stack||"No stack trace available"}`),i.generateEmpty({},F,A,K)}},async buildStart(){if(me=!1,!G()){E.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let f=0;for(;!G()&&f<100;)await new Promise(v=>setTimeout(v,10)),f++;if(!G())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let f=await Z[o](!W);W=f,await be(),i.logStats&&i.logStats(f,t,E)}catch(f){E.error(`${e} discovery failed during file scanning: ${f.message}`),E.error(`Stack: ${f.stack||"No stack trace available"}`),W=V.getEmptyResultWithError(Z,f)}finally{me=!0}},configureServer(){me=!0},handleHotUpdate(f){return m?[]:me?_e(f):(E.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!W){E.warn("No cached discovery data for manifest generation - skipping");return}try{let f=V.generateManifest(W,i.generateManifest);this.emitFile({type:"asset",fileName:u,source:JSON.stringify(f,null,2)}),I&&i.logManifest&&i.logManifest(W,e)}catch(f){E.error(`${e} manifest generation failed: ${f.message}`),E.error(`Stack: ${f.stack||"No stack trace available"}`)}},transform(f,v){return v===oe?{code:f,map:null}:null}}}}var Wr={generateGlobals:V.generateGlobals,generateExports:V.generateExports,generateDefaultExport:V.generateDefaultExport,wrapVirtualModule:V.wrapVirtualModule,generateInspectionHeader:V.generateInspectionHeader,validateTemplates:V.validateTemplates,createTemplateConfig:V.createTemplateConfig};j();var te=class n{constructor(e,t={}){if(this.constructor===n)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=T(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let a=Date.now()-t;return this.logger.debug(`Discovery completed in ${a}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};j();var Te=class extends te{constructor(e,t={}){super(e,{assets:Q.assets.fallback,assetPatterns:Q.assets.patterns,frameworkPackage:We.package,assetsPath:We.assetsPath,modernFormats:Q.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let a=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(a=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,u=await this._processAssetFiles(l),c=this._buildAssetManifest(u),p=await this._readLogoSvgContent("/logo.svg",t);return{assets:u,manifest:{...c,logoSvgContent:p},copiedAssets:s,generatedAssets:a,pwaIcons:this._extractPWAIcons(u)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(o=>o.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",o=r.match(/(\d+)x(\d+)/),a=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:a,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let a=`/${e}.${o}`;if(s.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(we.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let o of this.options.assets)await this._ensureAsset(o,r,s)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${we.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let o=s.split("/").pop()||s.split("\\").pop(),a=this._analyzeAsset(o,r.size);a&&t.push(a)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let o=`/${e}.${r}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${we.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(we.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let p=`${s}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,l),a.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),i.push(c.name)}}let u=await import("sharp").catch(()=>null);if(!u)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(c=>c.name));else for(let c of r){let p=`${s}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{let g=u.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),d;c.format==="ico"?d=await g.toFormat("png").toBuffer():d=await g.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,d),a.push(c.name)}catch(g){this.logger.debug(`Failed to generate ${c.name}: ${g.message}`),i.push(c.name)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(u=>u.name),error:l.message}}}};q();var Je={data:null},bs={isEmpty:n=>!n.manifest||n.assets?.length===0,generateModule:(n,e,t="assets")=>{let{manifest:s,assets:r,copiedAssets:o}=n,a=s.logoSvgContent||null,i={totalAssets:r.length,copiedAssets:o.length,hasLogo:s.logo.optimal!==null,hasFavicon:s.favicon.optimal!==null,hasManifest:s.manifest!==null,timestamp:new Date().toISOString()};return`// ${C.assets} - Generated asset manifest
|
|
51
50
|
const assetManifest = ${JSON.stringify(s,null,2)};
|
|
52
|
-
const assetStats = ${JSON.stringify(
|
|
51
|
+
const assetStats = ${JSON.stringify(i,null,2)};
|
|
53
52
|
|
|
54
53
|
// Populate unified DnDev config for runtime access
|
|
55
54
|
if (typeof globalThis !== 'undefined') {
|
|
@@ -65,11 +64,11 @@ if (typeof globalThis !== 'undefined') {
|
|
|
65
64
|
}
|
|
66
65
|
|
|
67
66
|
// Populate assets configuration
|
|
68
|
-
globalThis._DNDEV_CONFIG_.${
|
|
67
|
+
globalThis._DNDEV_CONFIG_.${B[t]} = {
|
|
69
68
|
mapping: assetManifest,
|
|
70
|
-
logoSvgContent: ${JSON.stringify(
|
|
69
|
+
logoSvgContent: ${JSON.stringify(a)},
|
|
71
70
|
manifest: {
|
|
72
|
-
totalAssets: ${
|
|
71
|
+
totalAssets: ${r.length},
|
|
73
72
|
generatedAt: new Date().toISOString(),
|
|
74
73
|
},
|
|
75
74
|
};
|
|
@@ -117,7 +116,7 @@ export default {
|
|
|
117
116
|
getManifest,
|
|
118
117
|
getAllAssets
|
|
119
118
|
};
|
|
120
|
-
`},generateEmpty:(e,t,
|
|
119
|
+
`},generateEmpty:(n,e,t,s="assets")=>{let r={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${C.assets} - Empty asset manifest
|
|
121
120
|
const assetManifest = {
|
|
122
121
|
logo: { optimal: null, fallback: null },
|
|
123
122
|
favicon: { optimal: null, fallback: null },
|
|
@@ -127,7 +126,7 @@ const assetManifest = {
|
|
|
127
126
|
modernFormats: [],
|
|
128
127
|
fallbackFormats: []
|
|
129
128
|
};
|
|
130
|
-
const assetStats = ${JSON.stringify(
|
|
129
|
+
const assetStats = ${JSON.stringify(r,null,2)};
|
|
131
130
|
|
|
132
131
|
// Populate unified DnDev config for runtime access
|
|
133
132
|
if (typeof globalThis !== 'undefined') {
|
|
@@ -143,7 +142,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
143
142
|
}
|
|
144
143
|
|
|
145
144
|
// Populate empty assets configuration
|
|
146
|
-
globalThis._DNDEV_CONFIG_.${
|
|
145
|
+
globalThis._DNDEV_CONFIG_.${B[s]} = {
|
|
147
146
|
mapping: assetManifest,
|
|
148
147
|
logoSvgContent: null,
|
|
149
148
|
manifest: {
|
|
@@ -187,7 +186,7 @@ export default {
|
|
|
187
186
|
getManifest,
|
|
188
187
|
getAllAssets
|
|
189
188
|
};
|
|
190
|
-
`},generateInspection:
|
|
189
|
+
`},generateInspection:n=>{let{assets:e,manifest:t,copiedAssets:s}=n;return!e||e.length===0?`/**
|
|
191
190
|
* Generated Asset Discovery Results
|
|
192
191
|
* Source: empty
|
|
193
192
|
* Generated at: ${new Date().toISOString()}
|
|
@@ -216,27 +215,27 @@ export default discoveredAssets;
|
|
|
216
215
|
`:`/**
|
|
217
216
|
* Generated Asset Discovery Results
|
|
218
217
|
* Generated at: ${new Date().toISOString()}
|
|
219
|
-
* Import from '${
|
|
218
|
+
* Import from '${C.assets}'
|
|
220
219
|
*/
|
|
221
220
|
|
|
222
|
-
export const discoveredAssets = ${JSON.stringify(
|
|
221
|
+
export const discoveredAssets = ${JSON.stringify(e,null,2)};
|
|
223
222
|
|
|
224
|
-
export const assetManifest = ${JSON.stringify(
|
|
223
|
+
export const assetManifest = ${JSON.stringify(t,null,2)};
|
|
225
224
|
|
|
226
225
|
export const assetStats = {
|
|
227
|
-
totalAssets: ${
|
|
226
|
+
totalAssets: ${e.length},
|
|
228
227
|
copiedAssets: ${s.length},
|
|
229
|
-
hasLogo: ${
|
|
230
|
-
hasFavicon: ${
|
|
231
|
-
hasManifest: ${
|
|
228
|
+
hasLogo: ${t.logo.optimal!==null},
|
|
229
|
+
hasFavicon: ${t.favicon.optimal!==null},
|
|
230
|
+
hasManifest: ${t.manifest!==null},
|
|
232
231
|
generatedAt: '${new Date().toISOString()}'
|
|
233
232
|
};
|
|
234
233
|
|
|
235
234
|
export default discoveredAssets;
|
|
236
|
-
`},generateManifest:
|
|
235
|
+
`},generateManifest:n=>({assets:n.assets?.length||0,copied:n.copiedAssets?.length||0,timestamp:Date.now(),hasLogo:n.manifest?.logo?.optimal!==null,hasFavicon:n.manifest?.favicon?.optimal!==null}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.assets?.length||0,r=n.generatedAssets?.length||0;t&&(r>0?t.info(`${e} Assets: ${s} found, ${r} generated`):t.info(`${e} Assets: ${s} found`))}},ws=[n=>n.includes("/public/"),n=>n.endsWith(".png")||n.endsWith(".svg")||n.endsWith(".ico"),n=>n.includes("favicon")||n.includes("logo")||n.includes("manifest")];function yt(n={}){let e=ie({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:C.assets,DiscoveryClass:Te,discoveryMethod:"discoverAssets",filePatterns:ws,templates:bs,defaultInspectionPath:z.vite.assetInspection,manifestFileName:z.manifests.asset,configKey:"assets"})(n),t=O.getInstance(),s=T("asset-plugin",n.debug,n.verbose),r=e.buildStart;return e.buildStart=async function(...o){r&&await r.apply(this,o);let a=null;try{let i=t.resolveAppPath(z.vite.assetInspection);if(t.pathExists(i)){let l=t.readSync(i,{format:"json"});l&&(a=l,Je.data=a)}}catch(i){s.debug(`Could not cache asset data: ${i.message}`)}},e}import{loadEnv as xs}from"vite";j();var bt={isEmpty:n=>!n.env||Object.keys(n.env).length===0,generateModule:(n,e,t="env")=>{let{env:s,mode:r}=n;if(!s||Object.keys(s).length===0)return bt.generateEmpty(n,e,void 0,t);let o={totalVars:Object.keys(s).length,mode:r,source:n.source,generatedAt:new Date().toISOString()};return`// ${C.env} - Generated environment variables
|
|
237
236
|
|
|
238
237
|
const envData = ${JSON.stringify(s,null,2)};
|
|
239
|
-
const envManifest = ${JSON.stringify(
|
|
238
|
+
const envManifest = ${JSON.stringify(o,null,2)};
|
|
240
239
|
|
|
241
240
|
// Freeze env data to prevent runtime tampering
|
|
242
241
|
Object.freeze(envData);
|
|
@@ -248,7 +247,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
248
247
|
if (!globalThis._DNDEV_CONFIG_) {
|
|
249
248
|
globalThis._DNDEV_CONFIG_ = {
|
|
250
249
|
platform: 'vite',
|
|
251
|
-
mode: '${
|
|
250
|
+
mode: '${r}',
|
|
252
251
|
context: 'client',
|
|
253
252
|
timestamp: Date.now(),
|
|
254
253
|
};
|
|
@@ -256,27 +255,27 @@ if (typeof globalThis !== 'undefined') {
|
|
|
256
255
|
// Ensure platform is always set to 'vite' (Vite config builder responsibility)
|
|
257
256
|
globalThis._DNDEV_CONFIG_.platform = 'vite';
|
|
258
257
|
// Update mode if it exists
|
|
259
|
-
if (globalThis._DNDEV_CONFIG_.mode !== '${
|
|
260
|
-
globalThis._DNDEV_CONFIG_.mode = '${
|
|
258
|
+
if (globalThis._DNDEV_CONFIG_.mode !== '${r}') {
|
|
259
|
+
globalThis._DNDEV_CONFIG_.mode = '${r}';
|
|
261
260
|
}
|
|
262
261
|
}
|
|
263
262
|
|
|
264
263
|
// Populate env configuration (frozen to prevent tampering)
|
|
265
|
-
globalThis._DNDEV_CONFIG_.${
|
|
264
|
+
globalThis._DNDEV_CONFIG_.${B[t]} = envData;
|
|
266
265
|
// Only freeze the env property, not the entire config (other plugins need to add properties)
|
|
267
266
|
}
|
|
268
267
|
|
|
269
268
|
// Named exports for convenience
|
|
270
269
|
export const env = envData;
|
|
271
270
|
export const manifest = envManifest;
|
|
272
|
-
export const source = '${
|
|
271
|
+
export const source = '${n.source}';
|
|
273
272
|
|
|
274
273
|
// Default export
|
|
275
274
|
export default envData;
|
|
276
|
-
`},generateEmpty:(e,t,
|
|
275
|
+
`},generateEmpty:(n,e,t,s="env")=>{let r={totalVars:0,mode:n.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${C.env} - Empty environment data
|
|
277
276
|
|
|
278
277
|
const envData = {};
|
|
279
|
-
const envManifest = ${JSON.stringify(
|
|
278
|
+
const envManifest = ${JSON.stringify(r,null,2)};
|
|
280
279
|
|
|
281
280
|
// Freeze env data to prevent runtime tampering
|
|
282
281
|
Object.freeze(envData);
|
|
@@ -288,7 +287,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
288
287
|
if (!globalThis._DNDEV_CONFIG_) {
|
|
289
288
|
globalThis._DNDEV_CONFIG_ = {
|
|
290
289
|
platform: 'vite',
|
|
291
|
-
mode: '${
|
|
290
|
+
mode: '${n.mode||"development"}',
|
|
292
291
|
context: 'client',
|
|
293
292
|
timestamp: Date.now(),
|
|
294
293
|
};
|
|
@@ -296,13 +295,13 @@ if (typeof globalThis !== 'undefined') {
|
|
|
296
295
|
// Ensure platform is always set to 'vite' (Vite config builder responsibility)
|
|
297
296
|
globalThis._DNDEV_CONFIG_.platform = 'vite';
|
|
298
297
|
// Update mode if it exists
|
|
299
|
-
if (globalThis._DNDEV_CONFIG_.mode !== '${
|
|
300
|
-
globalThis._DNDEV_CONFIG_.mode = '${
|
|
298
|
+
if (globalThis._DNDEV_CONFIG_.mode !== '${n.mode||"development"}') {
|
|
299
|
+
globalThis._DNDEV_CONFIG_.mode = '${n.mode||"development"}';
|
|
301
300
|
}
|
|
302
301
|
}
|
|
303
302
|
|
|
304
303
|
// Populate empty env configuration (frozen to prevent tampering)
|
|
305
|
-
globalThis._DNDEV_CONFIG_.${
|
|
304
|
+
globalThis._DNDEV_CONFIG_.${B[s]} = envData;
|
|
306
305
|
// Only freeze the env property, not the entire config (other plugins need to add properties)
|
|
307
306
|
}
|
|
308
307
|
|
|
@@ -311,19 +310,19 @@ export const manifest = envManifest;
|
|
|
311
310
|
export const source = 'empty';
|
|
312
311
|
|
|
313
312
|
export default envData;
|
|
314
|
-
`},generateInspection:
|
|
315
|
-
`)},generateManifest:
|
|
316
|
-
`);if(
|
|
317
|
-
${g}`);else{let
|
|
318
|
-
${g}`+
|
|
313
|
+
`},generateInspection:n=>{let{env:e,mode:t}=n;return["/**"," * Generated Environment Variables",` * Mode: ${t}`,` * Generated at: ${new Date().toISOString()}`,` * Total variables: ${Object.keys(e).length}`," */","","```json",JSON.stringify(e,null,2),"```"].join(`
|
|
314
|
+
`)},generateManifest:n=>({totalVars:Object.keys(n?.env||{}).length,mode:n?.mode||"development",variables:Object.keys(n?.env||{}),timestamp:Date.now()}),logStats:(n,e,t)=>{let s=Object.keys(n.env).length;t&&t.info(`${e} Env: ${s} VITE_* variables`)}},qe=class{constructor(e,t={}){this.pathResolver=e,this.options=t,this.mode=t.mode||"development",this.appRoot=null}async discoverEnv(){try{let e=this.pathResolver.getAppRoot();if(!e)throw new Error("App root not available in EnvDiscovery");let s={...xs(this.mode,e,"VITE_")};return this.mode==="production"&&(delete s.VITE_USE_FIREBASE_EMULATOR,delete s.VITE_FIREBASE_EMULATOR_HOST,delete s.VITE_FIREBASE_AUTH_EMULATOR_HOST,delete s.VITE_FIREBASE_FIRESTORE_EMULATOR_HOST,delete s.VITE_FIREBASE_FUNCTIONS_EMULATOR_PORT),s.MODE=this.mode,s.DEV=this.mode==="development",s.PROD=this.mode==="production",s.SSR=!1,{env:s,mode:this.mode,source:`${e}/.env`,errors:[]}}catch(e){return{env:{},mode:this.mode,source:"error",errors:[e.message]}}}};function wt(n={}){return ie({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:C.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:bt,defaultInspectionPath:z.vite.envInspection,manifestFileName:z.manifests.env,configKey:"env",createDiscovery:(e,t)=>new qe(e,{...t,mode:n.mode||t.mode||"development"})})({...n,disableHmr:!0})}q();j();var xt=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,de=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{...Ve.selectors,...this.options.customPatterns?.selectors},themes:{...Ve.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(a=>a.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((a,i)=>{let l=a.replace(/[^a-zA-Z0-9]/g,"");return l?i===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,a=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(i))!==null;){let[,u,c,p]=o;if(!u||!p)continue;let g=c.match(this.patterns.themes.themeIcon),d=c.match(this.patterns.themes.themeIsDark),h={name:u,displayName:p,isDark:d?d[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${u} (${p})`),r.push(h),s.themes.set(u,{name:u,displayName:p,isDark:h.isDark,file:a,variables:new Set,meta:h.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${a}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(xt.lastIndex=0;(r=xt.exec(t))!==null;){let o=r[1];o&&o.trim()&&s.add(o.trim())}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let a=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let a=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:a}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};j();var Ss=3,Ye="<!-- DNDEV_FONT_PRELOADS -->";function St(n={}){let{debug:e=!1}=n,t=T("font-preload",e,!1),s,r={},o=[],a=[];return{name:"vite-font-preload-plugin",enforce:"post",configResolved(i){r={root:i.root,base:i.base&&i.base!=="/"?i.base.replace(/\/$/,""):"",outDir:i.build?.outDir??"dist"};try{s=O.getInstance()}catch(l){t.debug(`Font preload: PathResolver not ready: ${l?.message}`)}},async buildStart(){if(!(!s||!s.getAppRoot()))try{let l=await s.resolvePatterns("css"),{consumerFiles:u}=await s.resolveFiles(l,"css");if(!u?.length){o=[xe.Inter],t.debug("Font preload: no consumer CSS, using default Inter");return}let c=new de(s,{debug:e,logger:t}),p=new Set;for(let d of u)try{let h=await s.read(d,{format:"text"});h&&c.extractFontFamilies(h).forEach(I=>p.add(I))}catch(h){t.debug(`Font preload: skip read ${d}: ${h?.message}`)}if(p.size===0){o=[xe.Inter],t.debug("Font preload: no font families in CSS, using default Inter");return}let g=new Set;for(let d of p){let h=xe[d];h&&g.add(h)}o=Array.from(g),t.debug(`Font preload: stems ${o.join(", ")} from CSS`)}catch(l){t.debug(`Font preload: discovery failed, use Inter: ${l?.message}`),o=[xe.Inter]}},generateBundle(i,l){if(!o.length)return;let u=r.base||"",c=[];for(let[p,g]of Object.entries(l)){if(g.type!=="asset"||!p.endsWith(".woff2")&&!p.endsWith(".woff"))continue;let d=p.toLowerCase();if(o.some(F=>d.includes(F))){let F=u?`${u}/${p}`:`/${p}`;c.push(F)}}a=c.slice(0,Ss)},writeBundle(){if(!a.length)return;let i=s||O.getInstance(),l=r.root||process.cwd(),u=r.outDir||"dist",c=i.resolvePath(`${u}/index.html`,l);try{if(!i.pathExists(c)){t.debug(`Font preload: index.html not found at ${c}`);return}let p=i.readSync(c,{format:"text"}),g=a.map(d=>`<link rel="preload" as="font" href="${d}" type="font/woff2" crossorigin="anonymous" />`).join(`
|
|
315
|
+
`);if(p.includes(Ye))p=p.replace(Ye,`${Ye}
|
|
316
|
+
${g}`);else{let d=p.indexOf("<!-- Fonts:"),h=d!==-1?p.indexOf("-->",d)+3:p.indexOf("</head>");h!==-1&&(p=p.slice(0,h)+`
|
|
317
|
+
${g}`+p.slice(h))}i.writeSync(c,p,{overwrite:!0}),t.debug(`Font preload: injected ${a.length} link(s)`)}catch(p){t.debug(`Font preload: write failed: ${p?.message}`)}}}}j();j();var Oe=class extends te{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],...t})}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=ke("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(R=>{let N=R.endsWith(".json")?R:`${R}/*_*.json`;return this.pathResolver.resolveAppPath(N)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let u=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${u.join(", ")}, framework lazy: ${c.join(", ")}`),u.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),d=(R,N)=>{let k=this.pathResolver.normalizePath(R),L=this.pathResolver.normalizePath(N);return k.startsWith(L)?k.slice(L.length+1):k},h=a.map(R=>d(R,t)),I=[...i,...l].map(R=>d(R,t)),S=u.map(R=>d(R,s)),_=c.map(R=>d(R,s)),$={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},b=await this.pathResolver._globWithNormalization(h,$),w=await this.pathResolver._globWithNormalization(I,$),m={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(R=>R!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(m.ignore)}`);let D=await this.pathResolver._globWithNormalization(S,m),A=await this.pathResolver._globWithNormalization(_,m);this.logger.debug(`Found ${b.length} eager, ${w.length} lazy, ${D.length} framework eager, ${A.length} framework lazy files`),D.length>0?this.logger.debug(`Framework eager files (first 3): ${D.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${u.join(", ")}`),A.length>0?this.logger.debug(`Framework lazy files (first 3): ${A.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let K=[...new Set([...b,...w,...D,...A])],E=new Set([...b,...D]),x={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},G=new Map,ye=[...D,...A];for(let R of ye){let N=this._processTranslationFile(R,D.includes(R),t);if(N){let k=`${N.namespace}_${N.language}`;G.set(k,N),x.allNamespaces.add(N.namespace),x.supportedLanguages.add(N.language),D.includes(R)&&x.eagerNamespaces.add(N.namespace)}}let Z=new Set;for(let R of K){if(ye.includes(R))continue;let N=this._processTranslationFile(R,E.has(R),t);if(N){let{namespace:k,language:L,importPath:fe,content:W}=N,le=`${N.namespace}_${N.language}`;if(G.has(le)){let ue=G.get(le);N.content=this._mergeTranslations(ue.content,W)}x.allNamespaces.add(k),x.supportedLanguages.add(L),Z.add(L),E.has(R)&&x.eagerNamespaces.add(k),x.mapping[k]||(x.mapping[k]={}),x.mapping[k][L]=fe,N.content&&(x.content[k]||(x.content[k]={}),x.content[k][L]=N.content),x.files.push({path:R,relativePath:this.pathResolver.getRelativePath(R),namespace:k,language:L,eager:E.has(R),size:N.content?JSON.stringify(N.content).length:0})}}for(let[R,N]of G){let[k,L]=R.split("_");(!x.mapping[k]||!x.mapping[k][L])&&(x.mapping[k]||(x.mapping[k]={}),x.mapping[k][L]=N.importPath,x.content[k]||(x.content[k]={}),x.content[k][L]=N.content)}let oe=Z.size>0?[...Z].sort():[this.options.fallbackLanguage];return{mapping:x.mapping,content:x.content,eagerNamespaces:[...x.eagerNamespaces].sort(),allNamespaces:[...x.allNamespaces].sort(),supportedLanguages:oe,fallbackLanguage:this.options.fallbackLanguage,files:x.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,a,i=r.match(/^([^_]+)_([^.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,a]=i,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let u="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(p){return this.logger.debug(`Error parsing JSON from ${e}: ${p.message}`),null}return{namespace:o,language:a,importPath:u,content:c}}_mergeTranslations(e,t){let s={...e};for(let[r,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?s[r]=this._mergeTranslations(s[r]||{},o):s[r]=o;return s}};var Es={isEmpty:n=>!n.mapping||Object.keys(n.mapping).length===0,generateModule:(n,e,t="i18n")=>{let{mapping:s,eagerNamespaces:r,supportedLanguages:o,fallbackLanguage:a,stats:i,content:l={}}=n,u={mapping:s,languages:o,eager:r,fallback:a,content:l,storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:i?.totalFiles||0,totalNamespaces:i?.totalNamespaces||0,totalLanguages:i?.totalLanguages||0,eagerNamespaces:i?.eagerNamespaces||0,generatedAt:new Date().toISOString()},debug:e};return`// ${C.i18n} - Generated by @donotdev/config
|
|
319
318
|
// \u{1F680} STATIC INJECTION PATTERN - Zero Runtime Loading
|
|
320
319
|
// Generated at: ${new Date().toISOString()}
|
|
321
320
|
|
|
322
321
|
// ===== STATIC EXPORTS - IMMEDIATE AVAILABILITY =====
|
|
323
322
|
export const I18N_CONFIG = ${JSON.stringify(u,null,2)};
|
|
324
|
-
export const LANGUAGES = ${JSON.stringify(
|
|
325
|
-
export const FALLBACK_LANGUAGE = '${
|
|
326
|
-
export const EAGER_NAMESPACES = ${JSON.stringify(
|
|
323
|
+
export const LANGUAGES = ${JSON.stringify(o,null,2)};
|
|
324
|
+
export const FALLBACK_LANGUAGE = '${a}';
|
|
325
|
+
export const EAGER_NAMESPACES = ${JSON.stringify(r,null,2)};
|
|
327
326
|
export const TRANSLATION_CONTENT = ${JSON.stringify(l,null,2)};
|
|
328
327
|
|
|
329
328
|
const i18nPluginConfig = I18N_CONFIG;
|
|
@@ -348,7 +347,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
348
347
|
}
|
|
349
348
|
|
|
350
349
|
// Add i18n plugin configuration
|
|
351
|
-
globalThis._DNDEV_CONFIG_.${
|
|
350
|
+
globalThis._DNDEV_CONFIG_.${B[t]} = i18nPluginConfig;
|
|
352
351
|
}
|
|
353
352
|
|
|
354
353
|
// ============================================================================
|
|
@@ -453,11 +452,11 @@ export default {
|
|
|
453
452
|
getInlineContent,
|
|
454
453
|
};
|
|
455
454
|
|
|
456
|
-
`},generateEmpty:(e,t,
|
|
455
|
+
`},generateEmpty:(n,e,t,s="i18n")=>{let r=t.fallbackLanguage||"en",o={mapping:{},languages:[r],eager:[],fallback:r,content:{},storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:0,totalNamespaces:0,totalLanguages:1,eagerNamespaces:0,generatedAt:new Date().toISOString()},debug:e};return`// ${C.i18n} - Empty i18n configuration
|
|
457
456
|
// No translation files found - using fallback configuration
|
|
458
457
|
// Generated at: ${new Date().toISOString()}
|
|
459
458
|
|
|
460
|
-
const i18nPluginConfig = ${JSON.stringify(
|
|
459
|
+
const i18nPluginConfig = ${JSON.stringify(o,null,2)};
|
|
461
460
|
|
|
462
461
|
// Initialize base config if needed (universal CSR/SSR)
|
|
463
462
|
if (typeof globalThis !== 'undefined') {
|
|
@@ -471,7 +470,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
471
470
|
};
|
|
472
471
|
}
|
|
473
472
|
|
|
474
|
-
globalThis._DNDEV_CONFIG_.${
|
|
473
|
+
globalThis._DNDEV_CONFIG_.${B[s]} = i18nPluginConfig;
|
|
475
474
|
}
|
|
476
475
|
|
|
477
476
|
// Placeholder functions
|
|
@@ -488,11 +487,11 @@ export function isEagerNamespace() {
|
|
|
488
487
|
}
|
|
489
488
|
|
|
490
489
|
export function getSupportedLanguages() {
|
|
491
|
-
return ['${
|
|
490
|
+
return ['${r}'];
|
|
492
491
|
}
|
|
493
492
|
|
|
494
493
|
export function getFallbackLanguage() {
|
|
495
|
-
return '${
|
|
494
|
+
return '${r}';
|
|
496
495
|
}
|
|
497
496
|
|
|
498
497
|
export function getInlineContent() {
|
|
@@ -500,9 +499,9 @@ export function getInlineContent() {
|
|
|
500
499
|
}
|
|
501
500
|
|
|
502
501
|
export const mapping = {};
|
|
503
|
-
export const languages = ['${
|
|
502
|
+
export const languages = ['${r}'];
|
|
504
503
|
export const eager = [];
|
|
505
|
-
export const fallback = '${
|
|
504
|
+
export const fallback = '${r}';
|
|
506
505
|
export const manifest = i18nPluginConfig.manifest;
|
|
507
506
|
export const config = i18nPluginConfig;
|
|
508
507
|
|
|
@@ -520,14 +519,14 @@ export default {
|
|
|
520
519
|
getFallbackLanguage,
|
|
521
520
|
getInlineContent,
|
|
522
521
|
};
|
|
523
|
-
`},generateInspection:(e,t
|
|
522
|
+
`},generateInspection:(n,e,t)=>{let{mapping:s,supportedLanguages:r,eagerNamespaces:o,files:a}=n;return!s||Object.keys(s).length===0?`/**
|
|
524
523
|
* Generated i18n Discovery Results
|
|
525
524
|
* Generated at: ${new Date().toISOString()}
|
|
526
525
|
* Status: No translations found
|
|
527
526
|
*/
|
|
528
527
|
|
|
529
528
|
export const discoveredTranslations = {};
|
|
530
|
-
export const supportedLanguages = ['${
|
|
529
|
+
export const supportedLanguages = ['${t?.fallbackLanguage||"en"}'];
|
|
531
530
|
export const eagerNamespaces = [];
|
|
532
531
|
export const translationFiles = [];
|
|
533
532
|
|
|
@@ -553,16 +552,16 @@ export default {
|
|
|
553
552
|
|
|
554
553
|
export const discoveredTranslations = ${JSON.stringify(s,null,2)};
|
|
555
554
|
|
|
556
|
-
export const supportedLanguages = ${JSON.stringify(
|
|
555
|
+
export const supportedLanguages = ${JSON.stringify(r,null,2)};
|
|
557
556
|
|
|
558
|
-
export const eagerNamespaces = ${JSON.stringify(
|
|
557
|
+
export const eagerNamespaces = ${JSON.stringify(o,null,2)};
|
|
559
558
|
|
|
560
|
-
export const translationFiles = ${JSON.stringify(
|
|
559
|
+
export const translationFiles = ${JSON.stringify(a.map(i=>({namespace:i.namespace,language:i.language,path:i.relativePath,eager:i.eager,size:i.size})),null,2)};
|
|
561
560
|
|
|
562
561
|
export const i18nManifest = {
|
|
563
|
-
totalNamespaces: ${
|
|
564
|
-
totalLanguages: ${
|
|
565
|
-
eagerNamespaces: ${
|
|
562
|
+
totalNamespaces: ${n.stats?.totalNamespaces||0},
|
|
563
|
+
totalLanguages: ${n.stats?.totalLanguages||0},
|
|
564
|
+
eagerNamespaces: ${n.stats?.eagerNamespaces||0},
|
|
566
565
|
generatedAt: '${new Date().toISOString()}'
|
|
567
566
|
};
|
|
568
567
|
|
|
@@ -573,7 +572,7 @@ export default {
|
|
|
573
572
|
files: translationFiles,
|
|
574
573
|
manifest: i18nManifest,
|
|
575
574
|
};
|
|
576
|
-
`},generateManifest:
|
|
575
|
+
`},generateManifest:n=>({namespaces:n.stats?.totalNamespaces||0,languages:n.stats?.totalLanguages||0,fallbackLanguage:n.fallbackLanguage,eagerNamespaces:n.stats?.eagerNamespaces||0,platform:"vite",timestamp:Date.now()}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.supportedLanguages||[],r=Object.keys(n.mapping||{}).filter(o=>o!=="default").length||0;t&&t.info(`${e} I18n: ${s.length} languages, ${r} namespaces`)}},Ps=[n=>n.endsWith(".json")&&n.includes("locale"),n=>/[a-z]+_[a-z]{2}\.json$/i.test(n),n=>n.includes("/locales/")&&n.endsWith(".json")];function Et(n={}){return ie({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:C.i18n,DiscoveryClass:Oe,discoveryMethod:"discoverTranslations",filePatterns:Ps,templates:Es,defaultInspectionPath:z.vite.i18nInspection,manifestFileName:z.manifests.i18n,configKey:"i18n",discoveryOptions:{fallbackLanguage:n.fallbackLanguage||"en",...n}})({...n,hmrSmartDetection:!1})}j();q();function Pt(n={}){let e=[],t="";return{name:"dndev-optional-dep-resolver",enforce:"pre",configResolved(){let s=O.getInstance(),r=s.getAppRoot(),o=he.optionalFeatures||[];for(let a of o)s.resolvePackage(a,r)||e.push(a);t=s.getEmptyModulePath(),n.debug&&e.length>0},resolveId(s){return e.includes(s)?t:null}}}function Ke(n){return!n||typeof n!="string"?null:n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0]}function Rs(n){return!n||typeof n!="string"?!1:!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("\\")&&!n.startsWith("\0")}function _s(n,e){if(!n||!e||!e.getRepoRoot())return!1;let s=n;n.startsWith("@fs/")&&(s=n.slice(4));let r=e.resolveRepoPath("packages"),o=e.normalizePath(s);return r&&o.startsWith(r)}function $s(n,e){if(!n||!e)return null;let t=Ke(n);if(!t)return null;let s=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(s)?e.resolveAppPath(`node_modules/${n}`):null}function Rt(n,e,t){return!Rs(n)||!_s(e,t)?null:$s(n,t)}q();function _t(n={}){let{debug:e=!1,verbose:t=!0}=n,s=T("peer-dependency-resolver",e,t);return{name:"dndev-peer-dependency-resolver",enforce:"pre",configResolved(r){let o=O.getInstance(),a=o.getAppRoot();if(!a){s.warn("App root not set, peer dependency resolution may fail");return}this.pathResolver=o,this.appRoot=a},resolveId(r,o){if(!o||!this.appRoot||!this.pathResolver)return null;if(Rt(r,o,this.pathResolver)){let i=Ke(r),l=this.pathResolver.resolveAppPath(`node_modules/${r}`),u=this.pathResolver.resolveAppPath(`node_modules/${i}`);return this.pathResolver.pathExists(u)?r===i?((e||t)&&s.debug(`[PeerDeps] Resolving bare import "${r}" from app's node_modules: ${u}`),u):((e||t)&&s.debug(`[PeerDeps] Resolving subpath "${r}" from app's node_modules: ${l}`),l):(e&&s.debug(`[PeerDeps] Package directory not found: ${u}, skipping resolution`),null)}return null}}}import{VitePWA as Ds}from"vite-plugin-pwa";j();var Fe=class extends te{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:s}=e,r=[...t,...s];this.logger.debug(`Processing ${r.length} PWA files`);let o=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),o=[...this.options.assetData.pwaIcons]);let a=await this._analyzePWAFiles(r),i=a.filter(g=>g.type==="manifest"||g.type==="service-worker");o.push(...i);let l=a.filter(g=>g.type==="icon"),u=new Set(o.filter(g=>g.type==="icon").map(g=>g.path)),c=l.filter(g=>!u.has(g.path));o.push(...c);let p=this._generatePWAManifest(o);return{assets:o,manifest:p,totalFiles:r.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let s of e){let r=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,o=await this._analyzePWAAsset(r);o&&t.push(o)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let s=e.relativePath,r=e.fileName;return r.includes("manifest.json")?this._parseManifestFile(t,s):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,s):this._isPWAIcon(r)?this._parseIconFile(e,s):null}_parseManifestFile(e,t){try{let s=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:s,size:typeof e=="string"?e.length:JSON.stringify(s).length}}catch(s){return this.logger.debug(`Failed to parse manifest: ${s.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let s=e.fileName,r=this._extractIconSize(s);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(s)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(s=>e.includes(s))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(o=>o.type==="icon"),r=e.find(o=>o.type==="manifest")?.content||this._getDefaultManifest();return t.length>0&&(r.icons=t.map(o=>({src:`/${o.path}`,sizes:`${o.size.width}x${o.size.height}`,type:`image/${o.format}`,purpose:o.purpose}))),r}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let t=e.manifest||this._getDefaultManifest();return JSON.stringify(t,null,2)}generateServiceWorkerContent(e,t={}){let s=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,o=t.precacheManifest||[],a=JSON.stringify(o,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
577
576
|
// Generated at ${new Date().toISOString()}
|
|
578
577
|
|
|
579
578
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -583,19 +582,19 @@ const { registerRoute } = workbox.routing;
|
|
|
583
582
|
const { CacheFirst, NetworkFirst, StaleWhileRevalidate } = workbox.strategies;
|
|
584
583
|
const { ExpirationPlugin } = workbox.expiration;
|
|
585
584
|
const { CacheableResponsePlugin } = workbox.cacheableResponse;
|
|
586
|
-
${
|
|
585
|
+
${r?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
|
|
587
586
|
|
|
588
587
|
// Clean up outdated caches
|
|
589
588
|
cleanupOutdatedPrecaches();
|
|
590
589
|
|
|
591
590
|
// Precache static assets
|
|
592
|
-
const precacheManifest = ${
|
|
591
|
+
const precacheManifest = ${a.length>2?a:"self.__WB_MANIFEST || []"};
|
|
593
592
|
precacheAndRoute(precacheManifest);
|
|
594
593
|
|
|
595
594
|
// Runtime caching strategies
|
|
596
|
-
${this._generateWorkboxRuntimeCaching(s.runtimeCaching,
|
|
595
|
+
${this._generateWorkboxRuntimeCaching(s.runtimeCaching,t)}
|
|
597
596
|
|
|
598
|
-
${
|
|
597
|
+
${r?this._generateBackgroundSync(t.backgroundSync):""}
|
|
599
598
|
|
|
600
599
|
// Skip waiting and claim clients
|
|
601
600
|
self.addEventListener('message', (event) => {
|
|
@@ -607,54 +606,54 @@ self.addEventListener('message', (event) => {
|
|
|
607
606
|
self.addEventListener('activate', (event) => {
|
|
608
607
|
event.waitUntil(self.clients.claim());
|
|
609
608
|
});
|
|
610
|
-
`}_getWorkboxDefaults(
|
|
611
|
-
maxEntries: ${
|
|
612
|
-
maxAgeSeconds: ${
|
|
613
|
-
})`),
|
|
614
|
-
statuses: ${JSON.stringify(
|
|
615
|
-
})`),
|
|
616
|
-
maxRetentionTime: ${
|
|
617
|
-
})`);let
|
|
618
|
-
cacheName: '${
|
|
609
|
+
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:o,handler:a,options:i={}}=s,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",u;typeof o=="function"?u="({ request }) => request.destination === 'document'":o instanceof RegExp?u=o.toString():u=JSON.stringify(o);let c=[];i.expiration&&c.push(`new ExpirationPlugin({
|
|
610
|
+
maxEntries: ${i.expiration.maxEntries||50},
|
|
611
|
+
maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
|
|
612
|
+
})`),i.cacheableResponse&&c.push(`new CacheableResponsePlugin({
|
|
613
|
+
statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
|
|
614
|
+
})`),i.backgroundSync&&c.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
|
|
615
|
+
maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
|
|
616
|
+
})`);let p="";return i.cacheName&&(p+=`
|
|
617
|
+
cacheName: '${i.cacheName}',`),c.length>0&&(p+=`
|
|
619
618
|
plugins: [
|
|
620
|
-
${
|
|
619
|
+
${c.join(`,
|
|
621
620
|
`)}
|
|
622
|
-
],`),
|
|
623
|
-
networkTimeoutSeconds: ${
|
|
621
|
+
],`),i.networkTimeoutSeconds&&(p+=`
|
|
622
|
+
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${i.cacheName||"cache-"+r}
|
|
624
623
|
registerRoute(
|
|
625
624
|
${u},
|
|
626
|
-
new ${l}({${
|
|
625
|
+
new ${l}({${p}
|
|
627
626
|
})
|
|
628
627
|
);`}).join(`
|
|
629
628
|
|
|
630
|
-
`)}_generateBackgroundSync(
|
|
629
|
+
`)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",s=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,o;return typeof r=="function"||r instanceof RegExp?o=r.toString():o=JSON.stringify(r),`
|
|
631
630
|
// Background sync for offline actions
|
|
632
631
|
const { NetworkOnly } = workbox.strategies;
|
|
633
632
|
registerRoute(
|
|
634
|
-
${
|
|
633
|
+
${o},
|
|
635
634
|
new NetworkOnly({
|
|
636
635
|
plugins: [
|
|
637
|
-
new BackgroundSyncPlugin('${
|
|
636
|
+
new BackgroundSyncPlugin('${t}', {
|
|
638
637
|
maxRetentionTime: ${s},
|
|
639
638
|
}),
|
|
640
639
|
],
|
|
641
640
|
}),
|
|
642
641
|
'POST'
|
|
643
642
|
);
|
|
644
|
-
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(t=".next"){let r=this.pathResolver.resolveAppPath(`${t}/static`),s=this.pathResolver.resolveAppPath(`${t}/static/chunks`),n=this.pathResolver.resolveAppPath(`${t}/static/css`),i=[];try{let o=[`${r}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${n}/**/*.css`];for(let a of o){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),a.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let u of l){let f=this.pathResolver.getRelativePath(u);if(f.startsWith(`${t}/static/`)){let d=`/_next/${f.replace(`${t}/static/`,"")}`;i.push({url:d,revision:null})}}}}catch(o){this.logger?.warn(`Failed to discover Next.js build assets: ${o.message}`)}return i}generatePrecacheManifest(t=[],r=null){let s=t;return r&&typeof r=="function"&&(s=r(s)),s}async discoverPWAAssets(t=!1){return await this.discover(t)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};ge();function qi(e={}){if(!e.enabled)return null;let t=e.app||{},r=[];if(t.name||r.push("name"),t.shortName||r.push("shortName"),t.description||r.push("description"),r.length>0){let f=B("PWA",e.debug,!0);f.warn(`\u26A0\uFE0F PWA is enabled but appConfig.app is missing required fields: ${r.join(", ")}`),f.warn(" Add these to your src/config/app.ts:"),f.warn(" export const appConfig: AppConfig = {"),f.warn(" app: {"),t.name||f.warn(' name: "Your App Name",'),t.shortName||f.warn(' shortName: "App",'),t.description||f.warn(' description: "Your app description",'),f.warn(" },"),f.warn(" // ... rest of config"),f.warn(" };"),f.warn("")}let s=U.getInstance(),n=qr.data;if(!n)try{let f=s.resolveAppPath(Z.vite.assetInspection);s.pathExists(f)}catch{}let i=new tr(s,{...e,assetData:n}),o=e.devEnabled===!0,a={registerType:e.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let f=e.app||{},g=(await i.discoverPWAAssets()).assets.filter(m=>m.type==="icon").map(m=>({src:`/${m.path}`,sizes:`${m.size.width}x${m.size.height}`,type:`image/${m.format}`,purpose:m.purpose}));return{name:f.name,short_name:f.shortName,description:f.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:g.length>0?g:[]}},workbox:{globPatterns:["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:f})=>f.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:!0,skipWaiting:!0,clientsClaim:!0,maximumFileSizeToCacheInBytes:5*1024*1024,navigateFallback:"/index.html",navigateFallbackDenylist:[/^\/api\/.*/],manifestTransforms:[f=>{let d=f.find(g=>g.url==="/index.html"||g.url==="index.html");return d&&!f.find(g=>g.url==="/")&&f.push({url:"/",revision:d.revision}),{manifest:f,warnings:[]}}]},devOptions:{enabled:o,type:"module"}},u={...a,manifest:async()=>{let f=await a.manifest();if(e.manifest){if(typeof e.manifest=="function"){let d=await e.manifest();return{...f,...d}}return{...f,...e.manifest}}return f},workbox:{...a.workbox,...e.workbox||{},runtimeCaching:[...a.workbox.runtimeCaching,...e.workbox?.runtimeCaching||[]],manifestTransforms:[...a.workbox.manifestTransforms||[],...e.workbox?.manifestTransforms||[]]}};return yf(u)}ee();ee();function Wi(e,t="unknown"){try{let r=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=e.match(r);if(!s)return null;let n=s[1];n=n.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,u)=>`icon: '${u}'`);let i=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...e.matchAll(i)].forEach(l=>{let u=l[1],f=l[2];n=n.replace(new RegExp(`\\b${u}\\b`,"g"),`'${f}'`)}),Function(`return ${n}`)()}catch{return null}}var $t=null,Hi=null;function wf(e){let r=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return r.charAt(0).toUpperCase()+r.slice(1)}var rr=class extends xe{constructor(t,r={}){super(t,{additionalPatterns:[],...r}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(t){let r=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if($t&&Hi===s)return this.logger.debug("Using cached route discovery results"),this.routes=$t.routes,this.errors=$t.errors,this.source=$t.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${r}`),this.options.debug){let n=t?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${n} files in ${r}`);let i=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(i)}`)}return await this._performAutoDiscovery(t,r),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),$t={routes:this.routes,errors:this.errors,source:this.source},Hi=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(t=!1){return await this.discover(t)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(t,r){let{consumerFiles:s}=t,n=await this._batchProcessFiles(s,u=>this._analyzePageFile(u,r)),i=await this._scanAdditionalPatterns(r),o=await this._batchProcessFiles(i,u=>this._analyzePageFile(u,r)),a=[...n,...o];this.logger.debug(`Auto-discovering from ${s.length} app + ${i.length} additional files`),this.routes=a.filter(u=>u.path==="home"||u.path==="/home"?(this.logger.debug(`Filtered reserved route: ${u.path} - Use root "/" instead (${u.file})`),!1):!0);let l=new Map;for(let u of this.routes){let f=u.path;if(l.has(f)){let d=l.get(f);throw new Error(`Route conflict: Multiple routes found for path '${f}'. Routes: ${d.file} and ${u.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}l.set(f,u)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+i.length} files`)}async _scanAdditionalPatterns(t){let r=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(r.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:r,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(t,r){let s=await this.pathResolver.read(t.absolutePath,{format:"text"});if(!s)return null;let n=t.relativePath,i="/src/"+n.replace(/\\/g,"/");i=i.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let o=this._extractMetaExport(s,t.absolutePath),a=wf(i),u=a===ur.HOMEPAGE_COMPONENT?ur.HOMEPAGE_PATH:this._resolveRoutePath(o,n,t.absolutePath),f=this._extractPageMeta(n,s),{entity:d,action:g,...m}=o||{};return{path:u,component:a,importPath:i,auth:o?.auth||!1,meta:{...f,...m,entity:f.entity,action:f.action},metaExport:o,file:n}}_extractMetaExport(t,r){try{let s=Wi(t,r);return s?(this.logger.debug(`Extracted meta export from ${r}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${r}: ${s.message}`),null}}_generateRoutePath(t){let r=t.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(r.endsWith("/index")||r==="index")&&(r=r.replace(/\/index$/,"")||"/"),r==="/"?"/":"/"+r.replace(/\/+/g,"/")}_resolveRoutePath(t,r,s){if(!t?.route)return this._generateRoutePath(r);if(typeof t.route=="string"){let n=t.route.trim();return n==="/"?"/":(n=n.replace(/\/+/g,"/"),n.startsWith("/")||(n="/"+n),n)}if(typeof t.route=="object"&&t.route!==null){let n=this._generateRoutePath(r),i=t.route.params;if(Array.isArray(i)&&i.length>0){let o=i.map(a=>`:${a}`).join("/");return`${n}/${o}`}return n}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(r)}_extractPageMeta(t,r){let s=t.split("/").pop()?.replace(".tsx","")||"",n=s.replace(/Page$/,"");n=n.replace(/([A-Z])/g," $1").trim(),n=n.charAt(0).toUpperCase()+n.slice(1);let i=t.split("/"),o=null,a=null;return i.length>1&&(o=i[i.length-2],s.includes("List")?a="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?a="form":(s.includes("Detail")||s.includes("View"))&&(a="detail")),{title:n,entity:o,action:a,file:t}}};var Ef={isEmpty:e=>!e.routes||e.routes.length===0,generateModule:(e,t,r="routes")=>{let s={totalRoutes:e.routes.length,authRequired:e.routes.filter(i=>i.auth&&i.auth.required).length,publicRoutes:e.routes.filter(i=>!i.auth||i.auth===!1).length,source:e.source,generatedAt:new Date().toISOString(),errors:e.errors.length},n=e.routes.map(i=>` {
|
|
645
|
-
path: '${
|
|
646
|
-
component: () => import('${
|
|
647
|
-
auth: ${JSON.stringify(
|
|
643
|
+
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let i of a){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let u of l){let c=this.pathResolver.getRelativePath(u);if(c.startsWith(`${e}/static/`)){let p=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:p,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};q();function $t(n={}){if(!n.enabled)return null;let e=n.app||{},t=[];if(e.name||t.push("name"),e.shortName||t.push("shortName"),e.description||t.push("description"),t.length>0){let c=T("PWA",n.debug,!0);c.warn(`\u26A0\uFE0F PWA is enabled but appConfig.app is missing required fields: ${t.join(", ")}`),c.warn(" Add these to your src/config/app.ts:"),c.warn(" export const appConfig: AppConfig = {"),c.warn(" app: {"),e.name||c.warn(' name: "Your App Name",'),e.shortName||c.warn(' shortName: "App",'),e.description||c.warn(' description: "Your app description",'),c.warn(" },"),c.warn(" // ... rest of config"),c.warn(" };"),c.warn("")}let s=O.getInstance(),r=Je.data;if(!r)try{let c=s.resolveAppPath(z.vite.assetInspection);s.pathExists(c)}catch{}let o=new Fe(s,{...n,assetData:r}),a=n.devEnabled===!0,i={registerType:n.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let c=n.app||{},g=(await o.discoverPWAAssets()).assets.filter(d=>d.type==="icon").map(d=>({src:`/${d.path}`,sizes:`${d.size.width}x${d.size.height}`,type:`image/${d.format}`,purpose:d.purpose}));return{name:c.name,short_name:c.shortName,description:c.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:g.length>0?g:[]}},workbox:{globPatterns:["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:c})=>c.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:!0,skipWaiting:!0,clientsClaim:!0,maximumFileSizeToCacheInBytes:5*1024*1024,navigateFallback:"/index.html",navigateFallbackDenylist:[/^\/api\/.*/],manifestTransforms:[c=>{let p=c.find(g=>g.url==="/index.html"||g.url==="index.html");return p&&!c.find(g=>g.url==="/")&&c.push({url:"/",revision:p.revision}),{manifest:c,warnings:[]}}]},devOptions:{enabled:a,type:"module"}},u={...i,manifest:async()=>{let c=await i.manifest();if(n.manifest){if(typeof n.manifest=="function"){let p=await n.manifest();return{...c,...p}}return{...c,...n.manifest}}return c},workbox:{...i.workbox,...n.workbox||{},runtimeCaching:[...i.workbox.runtimeCaching,...n.workbox?.runtimeCaching||[]],manifestTransforms:[...i.workbox.manifestTransforms||[],...n.workbox?.manifestTransforms||[]]}};return Ds(u)}j();j();function Dt(n,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=n.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,u)=>`icon: '${u}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...n.matchAll(o)].forEach(l=>{let u=l[1],c=l[2];r=r.replace(new RegExp(`\\b${u}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var Se=null,kt=null;function ks(n){let t=(n.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var Ie=class extends te{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(Se&&kt===s)return this.logger.debug("Using cached route discovery results"),this.routes=Se.routes,this.errors=Se.errors,this.source=Se.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let o=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(o)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),Se={routes:this.routes,errors:this.errors,source:this.source},kt=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,u=>this._analyzePageFile(u,t)),o=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(o,u=>this._analyzePageFile(u,t)),i=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=i.filter(u=>u.path==="home"||u.path==="/home"?(this.logger.debug(`Filtered reserved route: ${u.path} - Use root "/" instead (${u.file})`),!1):!0);let l=new Map;for(let u of this.routes){let c=u.path;if(l.has(c)){let p=l.get(c);throw new Error(`Route conflict: Multiple routes found for path '${c}'. Routes: ${p.file} and ${u.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}l.set(c,u)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,o="/src/"+r.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(s,e.absolutePath),i=ks(o),u=i===Ge.HOMEPAGE_COMPONENT?Ge.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:p,action:g,...d}=a||{};return{path:u,component:i,importPath:o,auth:a?.auth||!1,meta:{...c,...d,entity:c.entity,action:c.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=Dt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let a=o.map(i=>`:${i}`).join("/");return`${r}/${a}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z])/g," $1").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),a=null,i=null;return o.length>1&&(a=o[o.length-2],s.includes("List")?i="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?i="form":(s.includes("Detail")||s.includes("View"))&&(i="detail")),{title:r,entity:a,action:i,file:e}}};var As={isEmpty:n=>!n.routes||n.routes.length===0,generateModule:(n,e,t="routes")=>{let s={totalRoutes:n.routes.length,authRequired:n.routes.filter(o=>o.auth&&o.auth.required).length,publicRoutes:n.routes.filter(o=>!o.auth||o.auth===!1).length,source:n.source,generatedAt:new Date().toISOString(),errors:n.errors.length},r=n.routes.map(o=>` {
|
|
644
|
+
path: '${o.path}',
|
|
645
|
+
component: () => import('${o.importPath}'),
|
|
646
|
+
auth: ${JSON.stringify(o.auth,null,2).replace(/\n/g,`
|
|
648
647
|
`)},
|
|
649
|
-
meta: ${JSON.stringify(
|
|
648
|
+
meta: ${JSON.stringify(o.meta,null,2).replace(/\n/g,`
|
|
650
649
|
`)}
|
|
651
650
|
}`).join(`,
|
|
652
651
|
`);return`
|
|
653
|
-
// ${
|
|
652
|
+
// ${C.routes} - Generated route data
|
|
654
653
|
import { lazy } from 'react';
|
|
655
654
|
|
|
656
655
|
const routeData = [
|
|
657
|
-
${
|
|
656
|
+
${r}
|
|
658
657
|
];
|
|
659
658
|
|
|
660
659
|
const routeManifest = ${JSON.stringify(s,null,2)};
|
|
@@ -672,12 +671,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
672
671
|
}
|
|
673
672
|
|
|
674
673
|
// Include all routes in mapping (navigation store will filter by hideFromMenu)
|
|
675
|
-
globalThis._DNDEV_CONFIG_.${
|
|
674
|
+
globalThis._DNDEV_CONFIG_.${B[t]} = {
|
|
676
675
|
mapping: routeData,
|
|
677
676
|
manifest: {
|
|
678
|
-
totalRoutes: ${
|
|
679
|
-
authRequired: ${
|
|
680
|
-
publicRoutes: ${
|
|
677
|
+
totalRoutes: ${n.routes.length},
|
|
678
|
+
authRequired: ${n.routes.filter(o=>o.auth&&o.auth.required).length},
|
|
679
|
+
publicRoutes: ${n.routes.filter(o=>!o.auth||o.auth===!1).length},
|
|
681
680
|
generatedAt: new Date().toISOString(),
|
|
682
681
|
},
|
|
683
682
|
};
|
|
@@ -686,14 +685,14 @@ if (typeof globalThis !== 'undefined') {
|
|
|
686
685
|
|
|
687
686
|
export const routes = routeData;
|
|
688
687
|
export const manifest = routeManifest;
|
|
689
|
-
export const source = '${
|
|
688
|
+
export const source = '${n.source}';
|
|
690
689
|
|
|
691
|
-
export default { routes: routeData, manifest: routeManifest, source: '${
|
|
692
|
-
`},generateEmpty:(e,t,
|
|
693
|
-
// ${
|
|
690
|
+
export default { routes: routeData, manifest: routeManifest, source: '${n.source}' };
|
|
691
|
+
`},generateEmpty:(n,e,t,s="routes")=>{let r={totalRoutes:0,authRequired:0,publicRoutes:0,source:"empty",generatedAt:new Date().toISOString()};return`
|
|
692
|
+
// ${C.routes} - Empty route data
|
|
694
693
|
|
|
695
694
|
const routeData = [];
|
|
696
|
-
const routeManifest = ${JSON.stringify(
|
|
695
|
+
const routeManifest = ${JSON.stringify(r,null,2)};
|
|
697
696
|
|
|
698
697
|
// Populate unified DnDev config for runtime access
|
|
699
698
|
if (typeof globalThis !== 'undefined') {
|
|
@@ -709,7 +708,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
709
708
|
}
|
|
710
709
|
|
|
711
710
|
// Populate empty routes configuration
|
|
712
|
-
globalThis._DNDEV_CONFIG_.${
|
|
711
|
+
globalThis._DNDEV_CONFIG_.${B[s]} = {
|
|
713
712
|
mapping: [],
|
|
714
713
|
manifest: {
|
|
715
714
|
totalRoutes: 0,
|
|
@@ -726,7 +725,7 @@ export const manifest = routeManifest;
|
|
|
726
725
|
export const source = 'empty';
|
|
727
726
|
|
|
728
727
|
export default { routes: routeData, manifest: routeManifest, source: 'empty' };
|
|
729
|
-
`},generateInspection:(e
|
|
728
|
+
`},generateInspection:(n,e)=>{if(!n.routes||n.routes.length===0)return`/**
|
|
730
729
|
* Generated Route Discovery Results
|
|
731
730
|
* Source: empty
|
|
732
731
|
* Generated at: ${new Date().toISOString()}
|
|
@@ -742,7 +741,7 @@ export const routeManifest = {
|
|
|
742
741
|
};
|
|
743
742
|
|
|
744
743
|
export default discoveredRoutes;
|
|
745
|
-
`;let
|
|
744
|
+
`;let t=n.routes.map(s=>` {
|
|
746
745
|
path: '${s.path}',
|
|
747
746
|
component: () => import('${s.importPath}'),
|
|
748
747
|
auth: ${JSON.stringify(s.auth,null,2).replace(/\n/g,`
|
|
@@ -752,41 +751,41 @@ export default discoveredRoutes;
|
|
|
752
751
|
}`).join(`,
|
|
753
752
|
`);return`/**
|
|
754
753
|
* Generated Route Discovery Results
|
|
755
|
-
* Source: ${
|
|
754
|
+
* Source: ${n.source}
|
|
756
755
|
* Generated at: ${new Date().toISOString()}
|
|
757
|
-
* Import from '${
|
|
756
|
+
* Import from '${C.routes}'
|
|
758
757
|
*/
|
|
759
758
|
|
|
760
759
|
export const discoveredRoutes = [
|
|
761
|
-
${
|
|
760
|
+
${t}
|
|
762
761
|
];
|
|
763
762
|
|
|
764
763
|
export const routeManifest = {
|
|
765
|
-
totalRoutes: ${
|
|
766
|
-
source: '${
|
|
764
|
+
totalRoutes: ${n.routes.length},
|
|
765
|
+
source: '${n.source}',
|
|
767
766
|
generatedAt: '${new Date().toISOString()}'
|
|
768
767
|
};
|
|
769
768
|
|
|
770
769
|
export default discoveredRoutes;
|
|
771
|
-
`},generateManifest:
|
|
772
|
-
`)}generateSitemapContent(
|
|
770
|
+
`},generateManifest:n=>({routes:n?.routes?.length||0,source:n?.source||"unknown",timestamp:Date.now(),errors:n?.errors?.length||0}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.routes||[],r=s.filter(a=>a.auth&&a.auth.required).length,o=s.length;t&&t.info(`${e} Routes: ${o} found${r>0?`, ${r} are authguarded`:""}`)}},Ns=[n=>n.endsWith("Page.tsx")];function At(n={}){return ie({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:C.routes,DiscoveryClass:Ie,discoveryMethod:"discoverRoutes",filePatterns:Ns,templates:As,defaultInspectionPath:z.vite.routeInspection,manifestFileName:z.manifests.route,configKey:"routes"})({...n,disableHmr:n?.hmr===!1,hmrSmartDetection:!1})}import{loadEnv as Is}from"vite";q();import{readFileSync as Ts,readdirSync as Os,existsSync as Fs}from"fs";import{join as Nt}from"path";var Ce=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:a,crawlDelay:i=1,routes:l={},...u}=e;if(!o||!a)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:o,siteName:a,crawlDelay:i,routes:l,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...u},this.appRoot=u.appRoot||null,this.logger=T("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,s=null){try{let r=this.generateRouteMetaTags(e.routes||[]),o={routes:e.routes||[],routeMetaTags:r,baseUrl:this.options.baseUrl,siteName:this.options.siteName},a=this.discoverBlogPosts(),i={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:o.routes.length,publicRoutes:o.routes.filter(l=>!l.auth||l.auth===!1).length,protectedRoutes:o.routes.filter(l=>l.auth&&l.auth.required).length,blogPosts:a.length};return this.options.generateRobotsTxt&&(i.robotsTxt=await this.generateRobotsTxt(o,t,s)),this.options.generateSitemap&&(i.sitemap=await this.generateSitemap(o,t,s,a)),a.length>0&&(i.rss=await this.generateRSSFeed(a,t,s)),i.manifest=await this.generateManifest(o,t,s),i}catch(r){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`),r}}async generateRobotsTxt(e,t,s=null){if(s&&await s("robots.txt"))return this.logger.info("\u2705 robots.txt already exists, skipping generation"),{fileName:"robots.txt",skipped:!0};let r=[];(e.routes||[]).forEach(a=>{if(a.auth&&a.auth.required){let i=a.path.startsWith("/")?a.path:`/${a.path}`;r.push(i)}}),r.push("/admin","/api","/_next","/static");let o=this.generateRobotsTxtContent({disallowedPaths:[...new Set(r)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",o),{fileName:"robots.txt",content:o,disallowedPaths:r.length}}async generateSitemap(e,t,s=null,r=[]){if(s&&await s("sitemap.xml"))return this.logger.info("\u2705 sitemap.xml already exists, skipping generation"),{fileName:"sitemap.xml",skipped:!0};let a=(e.routes||[]).filter(l=>!l.auth||l.auth===!1).map(l=>({url:l.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:l.path==="/"?"1.0":"0.8"}));if(r.length>0){a.push({url:"/blog",lastmod:r[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let l of r)a.push({url:`/blog/${l.slug}`,lastmod:l.date,changefreq:"monthly",priority:"0.6"})}let i=this.generateSitemapContent(a);return await t("sitemap.xml",i),{fileName:"sitemap.xml",content:i,publicRoutes:a.length}}async generateManifest(e,t,s=null){if(s&&await s("seo-manifest.json"))return this.logger.info("\u2705 seo-manifest.json already exists, skipping generation"),{fileName:"seo-manifest.json",skipped:!0};let r={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(a=>!a.auth||a.auth===!1).length||0,protectedRoutes:e.routes?.filter(a=>a.auth&&a.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},o=JSON.stringify(r,null,2);return await t("seo-manifest.json",o),{fileName:"seo-manifest.json",content:o,manifest:r}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:o}=e,a=l=>l?l==="*"?"*":l.startsWith("/")?l:`/${l}`:"/",i=["User-agent: *",...s.map(l=>`Disallow: ${a(l)}`),...t.map(l=>`Allow: ${a(l)}`)];return o&&i.push(`Crawl-delay: ${o}`),r&&i.push(`Sitemap: ${r}`),i.join(`
|
|
771
|
+
`)}generateSitemapContent(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
773
772
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
774
|
-
${
|
|
775
|
-
${
|
|
773
|
+
${e.map(({url:s,lastmod:r,changefreq:o,priority:a})=>{let i=[` <loc>${this.options.baseUrl}${s}</loc>`];return r&&i.push(` <lastmod>${r}</lastmod>`),o&&i.push(` <changefreq>${o}</changefreq>`),a&&i.push(` <priority>${a}</priority>`),` <url>
|
|
774
|
+
${i.join(`
|
|
776
775
|
`)}
|
|
777
776
|
</url>`}).join(`
|
|
778
777
|
`)}
|
|
779
|
-
</urlset>`}generateRouteMetaTags(
|
|
780
|
-
`)){let
|
|
781
|
-
<title><![CDATA[${
|
|
782
|
-
<link>${this.options.baseUrl}/blog/${
|
|
783
|
-
<guid>${this.options.baseUrl}/blog/${
|
|
784
|
-
<description><![CDATA[${
|
|
785
|
-
<pubDate>${
|
|
786
|
-
<category>${
|
|
787
|
-
<enclosure url="${this.options.baseUrl}${
|
|
778
|
+
</urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(r=`Explore ${o[o.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=Nt(this.appRoot,"src","content","blog");try{if(!Fs(e))return[];let t=Os(e).filter(r=>r.endsWith("_en.md"));if(t.length===0)return[];let s=[];for(let r of t){let o=Ts(Nt(e,r),"utf-8"),a=r.replace(/_en\.md$/,""),i=o.match(/^---\r?\n([\s\S]*?)\r?\n---/),l={};if(i)for(let u of i[1].split(`
|
|
779
|
+
`)){let c=u.indexOf(":");c!==-1&&(l[u.slice(0,c).trim()]=u.slice(c+1).trim())}s.push({slug:a,title:l.title||a,description:l.description||"",date:l.date||new Date().toISOString().split("T")[0],tags:l.tags?l.tags.split(",").map(u=>u.trim()):[],image:l.image||null})}return s.sort((r,o)=>o.date.localeCompare(r.date)),this.logger.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(t){return this.logger.debug(`Blog content discovery skipped: ${t.message}`),[]}}async generateRSSFeed(e,t,s=null){if(s&&await s("rss.xml"))return this.logger.info("\u2705 rss.xml already exists, skipping generation"),{fileName:"rss.xml",skipped:!0};let r=e.map(a=>` <item>
|
|
780
|
+
<title><![CDATA[${a.title}]]></title>
|
|
781
|
+
<link>${this.options.baseUrl}/blog/${a.slug}</link>
|
|
782
|
+
<guid>${this.options.baseUrl}/blog/${a.slug}</guid>
|
|
783
|
+
<description><![CDATA[${a.description}]]></description>
|
|
784
|
+
<pubDate>${a.date?new Date(a.date).toUTCString():""}</pubDate>${a.tags.length?`
|
|
785
|
+
<category>${a.tags.join(", ")}</category>`:""}${a.image?`
|
|
786
|
+
<enclosure url="${this.options.baseUrl}${a.image}" type="image/png" length="0"/>`:""}
|
|
788
787
|
</item>`).join(`
|
|
789
|
-
`),
|
|
788
|
+
`),o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
790
789
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
791
790
|
<channel>
|
|
792
791
|
<title>${this.options.siteName}</title>
|
|
@@ -794,9 +793,9 @@ ${a.join(`
|
|
|
794
793
|
<description>${this.options.siteName} Blog</description>
|
|
795
794
|
<language>en</language>
|
|
796
795
|
<atom:link href="${this.options.baseUrl}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
797
|
-
${
|
|
796
|
+
${r}
|
|
798
797
|
</channel>
|
|
799
|
-
</rss>`;return await
|
|
798
|
+
</rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}};function Tt(n={}){let{disabled:e=!1,debug:t,generateRobotsTxt:s,generateSitemap:r,routes:o={},baseUrl:a,siteName:i,crawlDelay:l,isDev:u,...c}=n;if(e)return{name:"seo-disabled"};let p=T("SEO Plugin",t,!0),g=O.getInstance(),d=null,h=null,F=!1;async function I(){try{let S=g.resolveAppPath("src/routes.generated.log"),_=g.readSync(S,{format:"text"});if(!_)return p.error(`SEO plugin: routes discovery file not found at ${S}`),p.error("This indicates route discovery failed or did not run. SEO files will be generated with empty routes."),{routes:[],errors:[`Routes file missing: ${S}`],source:"fallback"};let $=_.match(/export const discoveredRoutes = (\[[\s\S]*?\]);/);if(!$)return p.error(`SEO plugin: failed to parse routes from ${S}`),p.error("Expected format: export const discoveredRoutes = [...];"),p.error("This indicates route discovery generated invalid output. SEO files will be generated with empty routes."),{routes:[],errors:[`Invalid routes file format: ${S}`],source:"fallback"};let b=$[1].replace(/component:\s*\(\)\s*=>\s*Promise\.resolve\(\{[^}]*\}\),?/g,"").replace(/component:\s*\(\)\s*=>\s*import\([^)]*\),?/g,"").replace(/component:\s*[^,}\n]+,?/g,"").replace(/,\s*,/g,",").replace(/,\s*}/g,"}").replace(/,\s*]/g,"]"),w=Function(`"use strict"; return ${b}`)();return{routes:w,errors:[],source:"generated",totalFiles:w.length}}catch(S){return p.warn(`Error parsing generated routes: ${S.message}, falling back to empty routes`),{routes:[],errors:[],source:"fallback"}}}return{name:"vite-seo-plugin",enforce:"pre",configResolved(S){let _=g.getAppRoot(),$=S.mode||"production",w=Is($,_,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;w&&t&&p.debug(`Using app URL from VITE_APP_URL: ${w}`),d=i||null,h=a||w||null,p.verbose(`Name: ${d||"Not found"}`),p.verbose(`URL: ${h||"Not found"}`),d&&p.debug(` - Site name from appConfig: "${d}"`);let m=[];if(h||m.push("baseUrl (VITE_APP_URL in .env)"),d||m.push("siteName (APP_NAME in src/config/app.ts)"),m.length>0){F=!0,p.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),m.forEach(D=>p.warn(` - ${D}`)),p.warn(""),p.warn(" To fix:"),h||p.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),d||(p.warn(" 2. Add APP_NAME export to src/config/app.ts:"),p.warn(' export const APP_NAME = "Your App Name";')),p.warn(""),p.warn(" robots.txt and sitemap.xml will NOT be generated."),p.warn("");return}p.debug(`Generate robots.txt: ${s}`),p.debug(`Generate sitemap: ${r}`)},async generateBundle(){if(!F)try{let S=new Ce({debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:h,siteName:d,crawlDelay:l,routes:o,appRoot:g.getAppRoot(),...c}),_=await I(),$=async(m,D)=>{this.emitFile({type:"asset",fileName:m,source:D})},b=async m=>!1,w=await S.generateSEOFiles(_,$,b);w.robotsTxt&&!w.robotsTxt.skipped&&p.info(`\u{1F916} robots.txt: ${w.robotsTxt.disallowedPaths||0} disallowed paths`),w.sitemap&&!w.sitemap.skipped&&p.info(`\u{1F5FA}\uFE0F sitemap.xml: ${w.sitemap.publicRoutes||0} routes`),w.rss&&!w.rss.skipped&&p.info(`\u{1F4E1} rss.xml: ${w.rss.postCount||0} blog posts`),w.manifest&&!w.manifest.skipped&&p.info("\u{1F4C4} seo-manifest.json")}catch(S){p.error(`SEO plugin failed to generate files (robots.txt/sitemap.xml): ${S.message}`),p.error(`Stack: ${S.stack||"No stack trace available"}`)}}}}j();function Ot(n={}){let{debug:e}=n;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,s){return t.startsWith("node:")?(T("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):Be.includes(t)||Be.some(r=>t.startsWith(`${r}/`))?(T("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):ot.includes(t)?(T("server-shim",e,!0).warn(`Blocking server-only import: ${t}${s?` from ${s}`:""}`),"\0virtual:empty-server-module"):null},load(t){return t==="\0virtual:empty-server-module"?`
|
|
800
799
|
// Node.js built-in modules shims for browser compatibility
|
|
801
800
|
export const URL = globalThis.URL;
|
|
802
801
|
export const URLSearchParams = globalThis.URLSearchParams;
|
|
@@ -1075,15 +1074,15 @@ ${n}
|
|
|
1075
1074
|
// Google Logging Utils shims
|
|
1076
1075
|
export const LoggingWinston = class LoggingWinston {};
|
|
1077
1076
|
export const LoggingBunyan = class LoggingBunyan {};
|
|
1078
|
-
`:null}}}
|
|
1077
|
+
`:null}}}j();j();var Ee=class extends te{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new de(t,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:s}=e;this.logger.debug(`Scanning ${t.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",s),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t),await this._processConsumerFiles(s);let r=this._serializeThemes();return this.logger.debug(`Discovered ${r.length} themes:`,r.map(o=>o.name)),{themes:r,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return He.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning framework file ${t}: ${s.message}`)}}async _processConsumerFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${t}: ${s.message}`)}}_addEssentialThemes(){He.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var Ft={isEmpty:n=>!n.themes||n.themes.length===0,generateModule:(n,e,t="themes")=>{let{themes:s}=n;if(!s||s.length===0)return Ft.generateEmpty(n,e,void 0,t);let r=s.find(a=>a.essential&&a.name==="light")||s[0],o={totalThemes:s.length,defaultTheme:r?.name||"light",hasCustomThemes:s.some(a=>!a.essential),timestamp:new Date().toISOString()};return`// Virtual module: ${C.themes}
|
|
1079
1078
|
// \u{1F680} STATIC INJECTION PATTERN - Zero Runtime Loading
|
|
1080
1079
|
// Generated by @donotdev/config at ${new Date().toISOString()}
|
|
1081
1080
|
|
|
1082
1081
|
// ===== STATIC EXPORTS - IMMEDIATE AVAILABILITY =====
|
|
1083
1082
|
export const THEMES = ${JSON.stringify(s,null,2)};
|
|
1084
|
-
export const THEME_MANIFEST = ${JSON.stringify(
|
|
1083
|
+
export const THEME_MANIFEST = ${JSON.stringify(o,null,2)};
|
|
1085
1084
|
export const THEME_COUNT = ${s.length};
|
|
1086
|
-
export const DEFAULT_THEME = '${
|
|
1085
|
+
export const DEFAULT_THEME = '${r?.name||"light"}';
|
|
1087
1086
|
|
|
1088
1087
|
const themeData = THEMES;
|
|
1089
1088
|
const defaultTheme = DEFAULT_THEME;
|
|
@@ -1103,7 +1102,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1103
1102
|
}
|
|
1104
1103
|
|
|
1105
1104
|
// Populate themes configuration
|
|
1106
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1105
|
+
globalThis._DNDEV_CONFIG_.${B[t]} = {
|
|
1107
1106
|
discovered: themeData,
|
|
1108
1107
|
mapping: themeData.reduce((acc, theme) => {
|
|
1109
1108
|
acc[theme.name] = theme;
|
|
@@ -1150,13 +1149,13 @@ export default {
|
|
|
1150
1149
|
getAllThemes,
|
|
1151
1150
|
getThemeNames
|
|
1152
1151
|
};
|
|
1153
|
-
`},generateEmpty:(e,t,
|
|
1152
|
+
`},generateEmpty:(n,e,t,s="themes")=>{let r=n.themes&&n.themes.length>0?n.themes:[{name:"light",displayName:"Light",meta:{icon:"Sun",category:"light"},essential:!0,isDark:!1,source:"built-in",variableCount:0}],o=r.find(i=>i.essential&&i.name==="light")||r[0],a={totalThemes:r.length,defaultTheme:o?.name||"light",hasCustomThemes:r.some(i=>!i.essential),timestamp:new Date().toISOString()};return`// ${C.themes} - Using framework essential themes (fallback)
|
|
1154
1153
|
// Generated by @donotdev/config at ${new Date().toISOString()}
|
|
1155
1154
|
|
|
1156
|
-
export const THEMES = ${JSON.stringify(
|
|
1157
|
-
export const THEME_MANIFEST = ${JSON.stringify(
|
|
1158
|
-
export const THEME_COUNT = ${
|
|
1159
|
-
export const DEFAULT_THEME = '${
|
|
1155
|
+
export const THEMES = ${JSON.stringify(r,null,2)};
|
|
1156
|
+
export const THEME_MANIFEST = ${JSON.stringify(a,null,2)};
|
|
1157
|
+
export const THEME_COUNT = ${r.length};
|
|
1158
|
+
export const DEFAULT_THEME = '${o?.name||"light"}';
|
|
1160
1159
|
|
|
1161
1160
|
const themeData = THEMES;
|
|
1162
1161
|
const defaultTheme = DEFAULT_THEME;
|
|
@@ -1174,7 +1173,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1174
1173
|
};
|
|
1175
1174
|
}
|
|
1176
1175
|
|
|
1177
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1176
|
+
globalThis._DNDEV_CONFIG_.${B[s]} = {
|
|
1178
1177
|
discovered: themeData,
|
|
1179
1178
|
mapping: themeData.reduce((acc, theme) => {
|
|
1180
1179
|
acc[theme.name] = theme;
|
|
@@ -1182,7 +1181,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1182
1181
|
}, {}),
|
|
1183
1182
|
variables: {},
|
|
1184
1183
|
manifest: {
|
|
1185
|
-
totalThemes: ${
|
|
1184
|
+
totalThemes: ${r.length},
|
|
1186
1185
|
generatedAt: new Date().toISOString(),
|
|
1187
1186
|
},
|
|
1188
1187
|
};
|
|
@@ -1217,7 +1216,7 @@ export default {
|
|
|
1217
1216
|
getAllThemes,
|
|
1218
1217
|
getThemeNames
|
|
1219
1218
|
};
|
|
1220
|
-
`},generateInspection:(e
|
|
1219
|
+
`},generateInspection:(n,e)=>{let{themes:t}=n;if(!t||t.length===0)return`/**
|
|
1221
1220
|
* Generated Theme Discovery Results
|
|
1222
1221
|
* Source: empty
|
|
1223
1222
|
* Generated at: ${new Date().toISOString()}
|
|
@@ -1233,46 +1232,26 @@ export const themeManifest = {
|
|
|
1233
1232
|
};
|
|
1234
1233
|
|
|
1235
1234
|
export default discoveredThemes;
|
|
1236
|
-
`;let s=
|
|
1235
|
+
`;let s=t.find(r=>r.essential&&r.name==="light")||t[0];return`/**
|
|
1237
1236
|
* Generated Theme Discovery Results
|
|
1238
1237
|
* Generated at: ${new Date().toISOString()}
|
|
1239
|
-
* Import from '${
|
|
1238
|
+
* Import from '${C.themes}'
|
|
1240
1239
|
*/
|
|
1241
1240
|
|
|
1242
|
-
export const discoveredThemes = ${JSON.stringify(
|
|
1241
|
+
export const discoveredThemes = ${JSON.stringify(t,null,2)};
|
|
1243
1242
|
|
|
1244
1243
|
export const defaultTheme = '${s?.name||"light"}';
|
|
1245
1244
|
|
|
1246
|
-
export const themeFiles = ${JSON.stringify(
|
|
1245
|
+
export const themeFiles = ${JSON.stringify(n.files?.map(r=>({name:r.name,path:r.relativePath,size:r.size}))||[],null,2)};
|
|
1247
1246
|
|
|
1248
1247
|
export const themeManifest = {
|
|
1249
|
-
totalThemes: ${
|
|
1248
|
+
totalThemes: ${t.length},
|
|
1250
1249
|
generatedAt: '${new Date().toISOString()}'
|
|
1251
1250
|
};
|
|
1252
1251
|
|
|
1253
1252
|
export default discoveredThemes;
|
|
1254
|
-
`},generateManifest:
|
|
1255
|
-
Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof
|
|
1256
|
-
\u{1F3D7}\uFE0F DnDev Framework - ${
|
|
1257
|
-
`);let
|
|
1258
|
-
${
|
|
1259
|
-
/*! Bundled license information:
|
|
1260
|
-
|
|
1261
|
-
sharp/lib/is.js:
|
|
1262
|
-
sharp/lib/libvips.js:
|
|
1263
|
-
sharp/lib/sharp.js:
|
|
1264
|
-
sharp/lib/constructor.js:
|
|
1265
|
-
sharp/lib/input.js:
|
|
1266
|
-
sharp/lib/resize.js:
|
|
1267
|
-
sharp/lib/composite.js:
|
|
1268
|
-
sharp/lib/operation.js:
|
|
1269
|
-
sharp/lib/colour.js:
|
|
1270
|
-
sharp/lib/channel.js:
|
|
1271
|
-
sharp/lib/output.js:
|
|
1272
|
-
sharp/lib/utility.js:
|
|
1273
|
-
sharp/lib/index.js:
|
|
1274
|
-
(*!
|
|
1275
|
-
Copyright 2013 Lovell Fuller and others.
|
|
1276
|
-
SPDX-License-Identifier: Apache-2.0
|
|
1277
|
-
*)
|
|
1278
|
-
*/
|
|
1253
|
+
`},generateManifest:n=>({themes:n.themes?.length||0,timestamp:Date.now(),hasCustomThemes:n.themes?.some(e=>!e.essential)||!1}),logConfig:n=>{},logStats:(n,e,t)=>{let s=n.themes||[],r=s.filter(a=>!a.essential).length,o=s.length;t&&(o===0?t.warn(`${e} No themes discovered - using framework essential themes fallback`):t.info(`${e} Themes: ${o} discovered${r>0?` (${r} custom)`:""}`))}};function It(n={}){let e=Date.now();return T("theme-plugin",n.debug,n.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),ie({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:C.themes,DiscoveryClass:Ee,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:Ft,defaultInspectionPath:z.vite.themeInspection,manifestFileName:z.manifests.theme,configKey:"themes",createDiscovery:(r,o)=>{let a=new de(r,{debug:o.debug,logger:T("css-extractor",o.debug,o.verbose)});return new Ee(a,r,o)}})(n)}q();function Ct(n={}){let e=T("vite-plugins",n.debug,n.verbose);try{let{mode:t,debug:s,verbose:r,isDev:o,server:a={},routes:i={},themes:l={},i18n:u={},assets:c={},seo:p={},pwa:g={},serverShim:d={},pluginFactory:h={}}=n,F=i.debug??s,I=l.debug??s,S=u.debug??s,_=c.debug??s,$=d.debug??s,b=[];b.push(Ot({...d,debug:$}));let w;try{w=O.getInstance()}catch(m){throw new Error(`Failed to initialize PathResolver: ${m.message||m}`)}return b.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(m){if(s){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let A={root:m.root,mode:m.mode,envDir:m.envDir,base:m.base,build:m.build?{outDir:m.build.outDir,minify:m.build.minify}:void 0,server:m.server?{port:m.server.port,host:m.server.host}:void 0,plugins:m.plugins?{count:m.plugins.length,names:m.plugins.map(K=>K?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(A,null,2))}w.setAppRoot(m.root);let D=w.getAppRoot();if(o&&m.server?.port){let A=m.server.https?"https":"http";process.env.VITE_APP_URL=`${A}://localhost:${m.server.port}`,(s||r)&&e.debug(`VITE_APP_URL set: ${process.env.VITE_APP_URL}`)}else o&&e.warn("VITE_APP_URL not set in dev mode. Server port not available.");try{let A=w.getRepoRoot();e.verbose(`Repo: ${A}`),e.verbose(`App: ${D}`)}catch(A){e.debug(`Could not log PathResolver values: ${A.message}`)}if(m.server){let A=E=>{let x=E.replace(/\\/g,"/"),G=D.replace(/\\/g,"/");return!x.startsWith(G)};m.server.watch||(m.server.watch={});let K=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];m.server.watch={...m.server.watch,ignored:[...m.server.watch.ignored||[],...K,A]},e.verbose(`Fixed file watcher to use app root: ${D}`)}}}),b.push(_t({debug:s,verbose:r})),b.push(Pt({debug:s})),b.push(Ms({fastRefresh:!0,jsxRuntime:"automatic"})),b.push(Ls({ignoreConfigErrors:!0})),a.https!==!1&&b.push(Cs()),b.push(At({...h,...i,debug:F})),b.push(It({...h,...l,debug:I})),b.push(Et({...h,...u,debug:S})),b.push(yt({...h,...c,debug:_})),b.push(wt({...h,mode:t,debug:s,verbose:r})),b.push(Tt({...p,debug:s,isDev:o})),g.enabled&&b.push($t({...g,debug:s})),b.push(St({debug:s})),b}catch(t){throw T("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}j();function zs(n){if(!n)return{};let e={};return Array.isArray(n)?n.forEach(({find:t,replacement:s})=>{typeof t=="string"&&(e[t]=s)}):typeof n=="object"&&Object.assign(e,n),e}function Mt(n={}){let{alias:e,...t}=n,{conditions:s,...r}=t;return{alias:{"@":"/src",...zs(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...s||[]],...r}}function Lt(n={}){let{include:e=[],exclude:t=[],esbuildOptions:s={},...r}=n,o=[...e,...he.optionalFeatures],a=[...new Set(o)],i=[...new Set(t)];return{include:a,exclude:i,esbuildOptions:s,...r}}function ar(n={}){return n==null&&(n={}),async(e={})=>{e==null&&(e={});try{let t=process.env.CI==="true";process.env.DNDEV_BUILD_ID||(process.env.DNDEV_BUILD_ID=t?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9));let s=e.command,r=e.mode,{appConfig:o,dndev:a,...i}=n;if(!o)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
|
|
1254
|
+
Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof o!="object"||o===null)throw new Error(`appConfig must be an object, but got ${typeof o}. Make sure you are exporting appConfig from src/config/app.ts correctly.`);let l=o?.features?{debug:o.features.debug}:void 0,u=o?.seo&&typeof o.seo!="boolean"?{...o.seo,siteName:o.seo.siteName||o.app?.name}:o?.app?.name?{siteName:o.app.name}:void 0,{features:c,seo:p,...g}=i,d=o?.app?{name:o.app.name,shortName:o.app.shortName,description:o.app.description}:void 0,{pwa:h={},...F}=g,I={...h,app:h.app||d},S={...l?{features:l}:{},...u?{seo:u}:{},...Object.keys(I).length>0?{pwa:I}:{},...F,mode:r},_;try{_=ft(S)}catch(H){throw new Error(`mergeOptions failed: ${H?.message||H||"Unknown error"}`)}let $;try{$=mt(_)}catch(H){throw new Error(`normalizeOptions failed: ${H?.message||H||"Unknown error"}`)}if(!$)throw new Error("normalizeOptions returned undefined");let{mode:b,debug:w,verbose:m,isDev:D,isDebug:A,shouldAnalyze:K,serverOptions:E,previewOptions:x,buildOverrides:G,resolveOptions:ye,routeOptions:Z,themeOptions:oe,i18nOptions:R,assetOptions:N,featureOptions:k,seoOptions:L,pwaOptions:fe,serverShimOptions:W,chunkingOptions:le,pluginFactoryOptions:ue,base:me,defineOptions:Le,optimizeDepsOptions:ze,pluginsOptions:be,cssOptions:Re,envDir:_e,restOptions:$e}=$,f=T("vite-config",w,m);f.debug(`Mode: ${b}, Dev: ${D}`);let v=process.env.DNDEV_BUILD_ID,M;s==="build"?M=`Building for ${b}`:s==="serve"?M=`Development server (${b})`:s==="preview"?M=`Preview server (serving ${b} build)`:M=`Running ${s} (${b})`,f.info(`
|
|
1255
|
+
\u{1F3D7}\uFE0F DnDev Framework - ${M}${v?` [build:${v}]`:""}`),f.info(` Platform: Vite | Command: ${s} | Mode: ${b}
|
|
1256
|
+
`);let ne=Ct({mode:b,debug:w,verbose:m,isDev:D,routes:Z,themes:oe,i18n:R,assets:N,features:k,seo:L,pwa:fe,serverShim:W,chunkingOptions:le,pluginFactory:ue});if(!Array.isArray(ne))throw new Error(`createVitePlugins returned ${typeof ne}, expected array. Value: ${ne}`);let se=ut({mode:b,chunkingOptions:le,debug:w,isDev:D,isDebug:A,shouldAnalyze:K}),qt=pt(E.port||3e3,E,f),Yt=gt(x);if(a)try{let{createDndevPlugin:H}=await Promise.resolve().then(()=>(Jt(),Ht));be.push(H(typeof a=="object"?a:{}))}catch{}return{...me&&{base:me},plugins:[...ne,...be],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...b==="production"&&{build:se},...s==="serve"&&{server:qt},...s==="preview"&&{preview:Yt},..._e&&{envDir:_e},customLogger:b==="production"&&!w?(()=>{let H={hasWarned:!1,_shouldSuppress(X){return X.includes("dist/")||X.includes("kB")||X.includes("\u2502")||X.includes("gzip:")||X.includes("\u2713 built in")||X.match(/built in \d+\.\d+s/)},info(X){H._shouldSuppress(X)},warn(X){H._shouldSuppress(X)},error(X){},warnOnce(X){H.hasWarned||(H.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return H})():void 0,css:{postcss:vt(Re),...Re},optimizeDeps:Lt(ze),resolve:Mt(ye),define:{...Le,"process.env.NODE_ENV":JSON.stringify(r),__DEV__:JSON.stringify(D),__PROD__:JSON.stringify(!D)},...$e}}catch(t){let s=t||new Error("Unknown error occurred"),r=s?.message||s?.toString()||String(s)||"Unknown error",o=s?.stack||"",a=new Error(`Failed to create Vite config: ${r}${o?`
|
|
1257
|
+
${o}`:""}`);throw a.stack=o||a.stack,a}}}export{ar as defineViteConfig};
|