@donotdev/core 0.3.2 → 0.3.3

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.
Files changed (50) hide show
  1. package/functions/index.js +19 -19
  2. package/i18n/locales/eager/dndev_ar.json +2 -1
  3. package/i18n/locales/eager/dndev_da.json +2 -1
  4. package/i18n/locales/eager/dndev_de.json +2 -1
  5. package/i18n/locales/eager/dndev_en.json +2 -1
  6. package/i18n/locales/eager/dndev_es.json +2 -1
  7. package/i18n/locales/eager/dndev_fr.json +2 -1
  8. package/i18n/locales/eager/dndev_it.json +2 -1
  9. package/i18n/locales/eager/dndev_ja.json +2 -1
  10. package/i18n/locales/eager/dndev_ko.json +2 -1
  11. package/i18n/locales/eager/dndev_nl.json +2 -1
  12. package/i18n/locales/eager/dndev_pl.json +2 -1
  13. package/i18n/locales/eager/dndev_pt.json +2 -1
  14. package/i18n/locales/eager/dndev_zh.json +2 -1
  15. package/i18n/locales/lazy/auth_ar.json +19 -2
  16. package/i18n/locales/lazy/auth_da.json +22 -2
  17. package/i18n/locales/lazy/auth_de.json +19 -2
  18. package/i18n/locales/lazy/auth_en.json +19 -2
  19. package/i18n/locales/lazy/auth_es.json +19 -2
  20. package/i18n/locales/lazy/auth_fr.json +19 -2
  21. package/i18n/locales/lazy/auth_it.json +19 -2
  22. package/i18n/locales/lazy/auth_ja.json +19 -2
  23. package/i18n/locales/lazy/auth_ko.json +19 -2
  24. package/i18n/locales/lazy/auth_nl.json +22 -2
  25. package/i18n/locales/lazy/auth_pl.json +19 -2
  26. package/i18n/locales/lazy/auth_pt.json +19 -2
  27. package/i18n/locales/lazy/auth_zh.json +19 -2
  28. package/i18n/locales/lazy/crud_ar.json +3 -1
  29. package/i18n/locales/lazy/crud_da.json +3 -1
  30. package/i18n/locales/lazy/crud_de.json +3 -1
  31. package/i18n/locales/lazy/crud_en.json +3 -1
  32. package/i18n/locales/lazy/crud_es.json +3 -1
  33. package/i18n/locales/lazy/crud_fr.json +3 -1
  34. package/i18n/locales/lazy/crud_it.json +3 -1
  35. package/i18n/locales/lazy/crud_ja.json +3 -1
  36. package/i18n/locales/lazy/crud_ko.json +3 -1
  37. package/i18n/locales/lazy/crud_nl.json +3 -1
  38. package/i18n/locales/lazy/crud_pl.json +3 -1
  39. package/i18n/locales/lazy/crud_pt.json +3 -1
  40. package/i18n/locales/lazy/crud_zh.json +3 -1
  41. package/index.d.ts +158 -6
  42. package/index.js +3 -3
  43. package/next/index.d.ts +65 -1
  44. package/next/index.js +222 -184
  45. package/package.json +2 -2
  46. package/server.d.ts +158 -4
  47. package/shared.js +1 -1
  48. package/symbol-index.json +1 -1
  49. package/vite/index.d.ts +64 -0
  50. package/vite/index.js +180 -174
package/vite/index.js CHANGED
@@ -1,29 +1,29 @@
1
- var _o=Object.defineProperty;var xt=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var Ao=(n,e)=>{for(var t in e)_o(n,t,{get:e[t],enumerable:!0})};function ir(n,e=null){let t=ce[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(r=>`${e}/${r}`)}:t}function ot(n){return rr[n]||rr.base}var Rt,U,ee,me,He,nt,Pt,Je,Te,ce,we,nr,$t,Ct,or,_t,sr,At,rr,J=xt(()=>{"use strict";Rt={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},U={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},ee={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},me={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.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",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts"},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"}},He="/og-image.png",nt="_shell.html",Pt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},Je={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Te={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",PUBLISHED_FLAGS:"i18n/flags"},ce={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:[`${Te.SOURCE_EAGER}/*_*.json`],lazy:[`${Te.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","icon-*x*.png",He.slice(1)],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/**"]},we={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],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"]},nr=["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"],$t=["@donotdev/core/functions","@donotdev/core/server"],Ct={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)/}},or={Inter:"inter","Space Grotesk":"space-grotesk","Playfair Display":"playfair-display","Press Start 2P":"press-start-2p",Roboto:"roboto"},_t={inter:[300,400,600,700],"playfair-display":[400,500,600,700],roboto:[400,700],"space-grotesk":[300,400,500,600,700],"press-start-2p":[400]},sr={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin","latin-ext"],cs:["latin","latin-ext"],sk:["latin","latin-ext"],hr:["latin","latin-ext"],sl:["latin","latin-ext"],hu:["latin","latin-ext"],ro:["latin","latin-ext"],et:["latin","latin-ext"],lv:["latin","latin-ext"],lt:["latin","latin-ext"],mt:["latin","latin-ext"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin","latin-ext"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","latin-ext","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},At=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],rr={base:{absolute:!0,onlyFiles:!0,ignore:ce.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...ce.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...ce.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:ce.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:ce.globalIgnore}}});import*as I from"node:fs";import"node:fs";import{createRequire as Fo}from"node:module";import{resolve as st,join as Re,dirname as _e,relative as ar,normalize as Mo,sep as lr,extname as Lo}from"node:path";import jo from"fast-glob";function Ie(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="EEXIST"}function cr(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Oe,Y,ur,D,q=xt(()=>{"use strict";J();Oe={getGlobOptionsFor:ot||void 0,SCAN_PATTERNS:ce||void 0,getPatternsFor:ir||void 0,I18N_PATHS:Te||void 0},Y={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};ur={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"},D=class n{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=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 Mo(e).split(lr).join("/")}catch{return String(e).split(lr).join("/")}}getRelativePath(e){let t=this.getAppRoot(),r=ar(t,e);return this.normalizePath(r)}getBasename(e){if(!e)return"";let r=this.normalizePath(e).split("/");return r[r.length-1]||""}getDirname(e){return e?this.normalizePath(_e(e)):""}resolvePackage(e,t=null){try{let r=t||this.getAppRoot(),s=Fo(Re(r,"package.json")).resolve(e);return this.normalizePath(s)}catch{return null}}resolveFrameworkPackage(e,t=null){let r=this.resolvePackage(`${e}/package.json`,t);if(r)return this.getDirname(r);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let i=e.replace("@donotdev/",""),a=this.resolveRepoPath(`packages/${i}`);if(this.pathExists(a))return a;if(["auth","billing","crud","oauth"].includes(i)){let l=this.resolveRepoPath(`packages/features/${i}`);if(this.pathExists(l))return l}if(i==="firebase"){let l=this.resolveRepoPath(`packages/providers/${i}`);if(this.pathExists(l))return l}}let o=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(o))return o;let s=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(s)?s:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),r=st(t,e);return this.normalizePath(r)}resolveRepoPath(e){let t=this.getRepoRoot(),r=this.normalizePath(e),o=st(t,r);return this.normalizePath(o)}resolvePath(e,t){let r=this.normalizePath(t),o=this.normalizePath(e),s=st(r,o);return this.normalizePath(s)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=I.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:Lo(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:r="auto",encoding:o="utf8"}=t,s=this._detectFormat(e,r);try{if(s==="buffer")return await I.promises.readFile(e);let i=await I.promises.readFile(e,o),a=this.stripBom(i);return s==="json"?JSON.parse(a):a}catch(i){return this.options.debug&&Y.warn(`Failed to read file: ${e}`,i),null}}readSync(e,t={}){let{format:r="auto",encoding:o="utf8"}=t,s=this._detectFormat(e,r);try{if(s==="buffer")return I.readFileSync(e);let i=I.readFileSync(e,o),a=this.stripBom(i);return s==="json"?JSON.parse(a):a}catch(i){return this.options.debug&&Y.warn(`Failed to read file: ${e}`,i),null}}async write(e,t,r={}){let{format:o="auto",overwrite:s=!1,dryRun:i=!1,verbose:a=!1}=r,l=this.normalizePath(e),c=this.normalizePath(_e(l)),u=this.pathExists(l);if(u&&!s)return a&&Y.info(`Skipping existing file: ${l}`),!1;if(i)return Y.info(`[DRY RUN] Would write file: ${l}`),!0;try{await I.promises.mkdir(c,{recursive:!0})}catch(f){if(!Ie(f))throw f}let p=this._detectFormat(e,o),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
2
- `:d=String(t);try{return await cr(async()=>(Buffer.isBuffer(d)?await I.promises.writeFile(l,d):await I.promises.writeFile(l,d,"utf8"),a&&Y.info(`${u?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,r={}){let{format:o="auto",overwrite:s=!1,dryRun:i=!1,verbose:a=!1}=r,l=this.normalizePath(e),c=this.normalizePath(_e(l)),u=this.pathExists(l);if(u&&!s)return a&&Y.info(`Skipping existing file: ${l}`),!1;if(i)return Y.info(`[DRY RUN] Would write file: ${l}`),!0;try{I.mkdirSync(c,{recursive:!0})}catch(f){if(!Ie(f))throw f}let p=this._detectFormat(e,o),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
3
- `:d=String(t);try{return Buffer.isBuffer(d)?I.writeFileSync(l,d):I.writeFileSync(l,d,"utf8"),this._writtenPaths?.add(l),a&&Y.info(`${u?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,r={}){let{overwrite:o=!1,dryRun:s=!1,verbose:i=!1}=r,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!o)return i&&Y.info(`Skipping existing file: ${a}`),!1;if(s)return Y.info(`[DRY RUN] Would copy file: ${a}`),!0;let c=this.normalizePath(_e(a));try{await I.promises.mkdir(c,{recursive:!0})}catch(u){if(!Ie(u))throw u}try{return await cr(async()=>(await I.promises.copyFile(e,a),i&&Y.info(`${l?"Updated":"Created"} file: ${a}`),!0),`Failed to copy file from ${e} to ${a}`)}catch{return!1}}copySync(e,t,r={}){let{overwrite:o=!1,dryRun:s=!1,verbose:i=!1}=r,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!o)return i&&Y.info(`Skipping existing file: ${a}`),!1;if(s)return Y.info(`[DRY RUN] Would copy file: ${a}`),!0;let c=this.normalizePath(_e(a));try{I.mkdirSync(c,{recursive:!0})}catch(u){if(!Ie(u))throw u}try{return I.copyFileSync(e,a),this._writtenPaths?.add(a),i&&Y.info(`${l?"Updated":"Created"} file: ${a}`),!0}catch{return!1}}pathExists(e,t=!1){try{return I.existsSync(e)}catch(r){return t||Y.error(`Error checking path existence: ${e}`,r),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return I.readdirSync(e,t)}catch(r){return this.options.debug&&Y.warn(`Failed to read directory: ${e}`,r),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return I.statSync(e)}catch(t){return this.options.debug&&Y.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return I.realpathSync(e)}watch(e,t,r){return I.watch(e,t,r)}lstatSync(e){try{return I.lstatSync(e)}catch(t){return this.options.debug&&Y.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await I.promises.mkdir(e,{recursive:!0})}catch(t){if(!Ie(t))throw t}}ensureDirSync(e){try{I.mkdirSync(e,{recursive:!0})}catch(t){if(!Ie(t))throw t}}async remove(e){await I.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){I.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return I.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}startWriteRecording(){this._writtenPaths=new Set}stopWriteRecording(){if(!this._writtenPaths)throw new Error("stopWriteRecording() called without startWriteRecording()");let e=this._writtenPaths;return this._writtenPaths=null,e}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=Re(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(st(e)),r=this.getAppRoot(),o=ar(r,t),s=this.normalizePath(o);return!s.startsWith("../")&&!s.startsWith("/")}async findFiles(e,t,r={}){let o=this.normalizePath(Re(e,t)),s=this.getAppRoot(),i=this.normalizePath(s),a=o.startsWith(i)?o.slice(i.length+1):o,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:Oe.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([a],{...l,...r})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Oe.I18N_PATHS;if(!t)return null;let r=e.replace(t.SOURCE_ROOT+"/",""),o=this.resolveFrameworkPackage("@donotdev/core");if(!o)return null;let s=this.normalizePath(Re(o,t.PUBLISHED_ROOT,r)),i=s.replace(/\/[^/]*\*.*$/,"");return this.pathExists(i),s}async _globWithNormalization(e,t){return(await jo(e,t)).map(o=>{let s=typeof o=="string"?o:o.path;return this.normalizePath(s)}).sort()}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 r=[...e.framework,...e.consumer];for(let u of r)if(typeof u!="string"||u.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let o=this.getAppRoot(),s=Oe.getGlobOptionsFor?Oe.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},i=this.normalizePath(o),a=e.framework.map(u=>{let p=this.normalizePath(u);return p.startsWith(i)?p.slice(i.length+1):p}),l=e.consumer.map(u=>{let p=this.normalizePath(u);return p.startsWith(i)?p.slice(i.length+1):p}),c={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o};try{let u=a.length>0?await this._globWithNormalization(a,c):[],p=await this._globWithNormalization(l,c);return{frameworkFiles:u,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!Oe.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),r=this.getRepoRoot();if(e==="i18n"&&(!t||t===r))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${r}). Ensure configResolved hook has run before discovery.`);let o=Oe.getPatternsFor(e),s=this.isMonorepo();if(e==="i18n"){let l=o,c={eager:l.eager.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),lazy:l.lazy.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),framework:{eager:s?(l.framework?.eager||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean)),lazy:s?(l.framework?.lazy||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean))},all:[]};return c.all=[...c.eager,...c.lazy,...c.framework.eager,...c.framework.lazy],c}let i=o,a={framework:s?(i.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(i.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return a.all=[...a.consumer,...a.framework],a}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),r=0,o=this.options.maxLevels;for(;r<o;){let s=this.normalizePath(Re(t,ur.TOOLING)),i=this.normalizePath(Re(t,ur.CORE));if(this.pathExists(s)&&this.pathExists(i))return t;let a=Re(t,"apps");if(this.pathExists(a)&&this.statSync(a)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(Re(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(_e(t))===t)return t;let c=this.normalizePath(_e(t));if(c===t)break;t=c,r++}return this.normalizePath(e)}}});var So={};Ao(So,{createDndevPlugin:()=>wa});import{execSync as be,execFileSync as We,spawn as Hi}from"node:child_process";function te(){return D.getInstance()}function ae(){return te().getRepoRoot()}function bo(){return te().resolveRepoPath(".dndev")}function b(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function Se(n,e=Ji){return new Promise((t,r)=>{let o="",s=0;n.on("data",i=>{if(s+=i.length,s>e){n.destroy(),r(new Error("Request body too large"));return}o+=i.toString()}),n.on("end",()=>t(o)),n.on("error",r)})}function qi(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function Ki(){let n=te(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let o=process.platform==="win32"?"where node":"which node",s=be(o,{encoding:"utf8"}).trim().split(`
4
- `)[0];e.push(s)}catch{}let r=[process.env.NVM_DIR,n.resolvePath(".nvm",t)].filter(Boolean);for(let o of r)try{let s=n.resolvePath("versions/node",o),i=n.readdirSync(s).filter(a=>a.startsWith("v")).sort().reverse();for(let a of i)e.push(n.resolvePath(`${a}/bin/node`,s))}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 o=process.env.APPDATA||"";if(o)try{let s=n.resolvePath("nvm",o),i=n.readdirSync(s).filter(a=>a.startsWith("v")).sort().reverse();for(let a of i)e.push(n.resolvePath(`${a}/node.exe`,s))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let o of e)try{let s=n.realpathSync(o);if(s.includes("bun")||!n.pathExists(s))continue;return o}catch{continue}return"node"}function wo(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 Yi(n){return n.includes("..")?!1:n.startsWith(".dndev/")||n.startsWith("docs/")||n.startsWith("guides/")}function Eo(n){let e=te(),t=e.getRepoRoot(),r=e.resolvePath(n,t),o=e.normalizePath(t),s=e.normalizePath(r);return!s.startsWith(o+"/")&&s!==o?null:r}async function Xi(n,e){let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!r)return b(e,{error:"path parameter required"},400);if(!wo(r))return b(e,{error:"Access denied"},403);let o=Eo(r);if(!o)return b(e,{error:"Access denied"},403);let s=te();if(!s.pathExists(o))return b(e,{error:"File not found"},404);let i=qi(o);if(Zi.has(i)){let a=s.readSync(o,{format:"buffer"});return a?(e.writeHead(200,{"Content-Type":xo[i]||"application/octet-stream","Content-Length":a.byteLength}),void e.end(Buffer.from(a))):b(e,{error:"Failed to read file"},500)}if(i===".json")try{let a=await s.read(o);return a===null?b(e,{error:"Failed to read file"},500):b(e,{path:r,content:a})}catch{return b(e,{error:"Invalid JSON"},500)}try{let a=await s.read(o,{format:"text"});if(a===null)return b(e,{error:"Failed to read file"},500);b(e,{path:r,content:a})}catch{b(e,{error:"Failed to read file"},500)}}function Qi(n,e){let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("dir"),o=te(),s=o.getRepoRoot(),i=[],a=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(u,p){try{let d=o.readdirSync(u,{withFileTypes:!0});for(let f of d){let g=p?`${p}/${f.name}`:f.name;f.isDirectory()&&a.has(f.name)||(f.isDirectory()?(i.push({path:g,name:f.name,isDirectory:!0}),l(o.resolvePath(f.name,u),g)):f.name.endsWith(".md")&&i.push({path:g,name:f.name,isDirectory:!1}))}}catch{}}let c=[".dndev","docs","guides"];if(r){if(r.includes("..")||r.includes("\0"))return b(e,{error:"Access denied"},403);if(!c.includes(r)&&!c.some(f=>r.startsWith(f+"/")))return b(e,{error:"Directory not allowed"},403);let u=o.resolvePath(r,s),p=o.normalizePath(s);if(!o.normalizePath(u).startsWith(p+"/"))return b(e,{error:"Access denied"},403);o.pathExists(u)&&(i.push({path:r,name:o.getBasename(r),isDirectory:!0}),l(u,r))}else{for(let u of c){let p=o.resolveRepoPath(u);o.pathExists(p)&&(i.push({path:u,name:u,isDirectory:!0}),l(p,u))}try{let u=o.readdirSync(s,{withFileTypes:!0});for(let p of u)!p.isDirectory()&&p.name.endsWith(".md")&&i.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}b(e,{entries:i})}async function ea(n,e){let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!r)return b(e,{error:"path parameter required"},400);if(!wo(r))return b(e,{error:"Access denied"},403);if(!Yi(r))return b(e,{error:"Write not allowed to this path"},403);let o=Eo(r);if(!o)return b(e,{error:"Access denied"},403);try{let s=await Se(n),{content:i}=JSON.parse(s);if(i===void 0)return b(e,{error:"content field required"},400);let a=typeof i=="string"?i:JSON.stringify(i,null,2);await te().write(o,a,{overwrite:!0}),b(e,{ok:!0})}catch{b(e,{error:"Failed to write file"},500)}}async function ta(n,e){try{let t=await Se(n),{line:r,checked:o}=JSON.parse(t);if(typeof r!="number")return b(e,{error:"line number required"},400);let s=te(),i=s.resolveRepoPath(".dndev/implementation.md");if(!s.pathExists(i))return b(e,{error:"implementation.md not found"},404);let a=await s.read(i,{format:"text"});if(a===null)return b(e,{error:"Failed to read file"},500);let l=a.split(`
5
- `);if(r<0||r>=l.length)return b(e,{error:"Line out of range"},400);let c=l[r];l[r]=o?c.replace("- [ ]","- [x]"):c.replace("- [x]","- [ ]"),await s.write(i,l.join(`
6
- `),{overwrite:!0}),b(e,{ok:!0,line:l[r]})}catch{b(e,{error:"Failed to update progress"},500)}}async function ra(n,e){try{let t=await Se(n),{id:r,data:o}=JSON.parse(t);if(!r||!o)return b(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(r))return b(e,{error:"Invalid screenshot ID"},400);let s=te(),i=s.resolveRepoPath(".dndev/bugs");s.ensureDirSync(i);let a=Buffer.from(o,"base64"),l=s.resolvePath(`${r}.png`,i);await s.write(l,a,{overwrite:!0}),b(e,{ok:!0,path:`.dndev/bugs/${r}.png`})}catch{b(e,{error:"Failed to save screenshot"},500)}}async function na(n,e){try{let t=await Se(n),{action:r,phase:o}=JSON.parse(t);if(!r||typeof o!="number")return b(e,{error:"action and phase required"},400);let s=te(),i=bo();s.ensureDirSync(i);let a=s.resolvePath("protocol.json",i),l={currentPhase:0,phases:{}};if(s.pathExists(a))try{let c=await s.read(a);c&&(l=c)}catch{}r==="start"?(l.currentPhase=o,l.phases[o]||(l.phases[o]={}),l.phases[o].status="active",l.phases[o].startedAt=new Date().toISOString()):r==="complete"&&(l.phases[o]||(l.phases[o]={}),l.phases[o].status="completed",l.phases[o].completedAt=new Date().toISOString()),await s.write(a,l,{overwrite:!0}),b(e,{ok:!0,protocol:l})}catch{b(e,{error:"Failed to update phase"},500)}}function oa(n,e){try{let t=ae(),r=be("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),o=be("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();b(e,{commit:r,branch:o})}catch{b(e,{commit:"unknown",branch:"unknown"})}}async function sa(n,e){try{let t=await Se(n),r=JSON.parse(t);if(!r.id||!r.type||!r.result)return b(e,{error:"id, type, and result required"},400);let o=te(),s=bo();o.ensureDirSync(s);let i=o.resolvePath("health.json",s),a={actions:[]};if(o.pathExists(i))try{let c=await o.read(i);c&&(a=c)}catch{}Array.isArray(a.actions)||(a.actions=[]);let l=a.actions.findIndex(c=>c.id===r.id);l>=0?a.actions[l]={...a.actions[l],...r}:a.actions.unshift(r),await o.write(i,a,{overwrite:!0}),b(e,{ok:!0})}catch{b(e,{error:"Failed to append action"},500)}}function ia(n,e){let t=te(),r=t.resolveRepoPath("apps");try{let s=t.readdirSync(r).filter(i=>{if(i==="dndev")return!1;let a=t.resolvePath(i,r);return t.statSync(a)?.isDirectory()&&t.pathExists(t.resolvePath("package.json",a))}).map(i=>{try{let a=t.resolvePath(`${i}/package.json`,r),l=t.readSync(a);return{name:i,packageName:l?.name||i}}catch{return{name:i,packageName:i}}});b(e,{apps:s})}catch{b(e,{apps:[]})}}function aa(n,e){try{let t=ae(),r=be("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),o=[],s={};for(let i of r.split(`
7
- `))i.startsWith("worktree ")?(s.path&&o.push(s),s={path:i.slice(9)}):i.startsWith("HEAD ")?s.head=i.slice(5):i.startsWith("branch ")?(s.branch=i.slice(7),s.shortBranch=s.branch.replace("refs/heads/","")):i==="detached"&&(s.detached=!0);s.path&&o.push(s),b(e,{worktrees:o})}catch(t){b(e,{error:t.message},500)}}async function la(n,e){try{let t=await Se(n),{branch:r}=JSON.parse(t);if(!r||typeof r!="string")return b(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(r))return b(e,{error:"Invalid branch name"},400);let o=ae(),s=te(),i=s.resolvePath("..",o),a=s.getBasename(o),l=s.resolvePath(`${a}-${r.replace(/\//g,"-")}`,i);We("git",["worktree","add",l,"-b",r],{cwd:o,encoding:"utf-8",timeout:3e4}),b(e,{ok:!0,path:l,branch:r})}catch(t){b(e,{error:t.message},500)}}async function ca(n,e){try{let t=await Se(n),{path:r}=JSON.parse(t);if(!r||typeof r!="string")return b(e,{error:"path required"},400);let o=ae();We("git",["worktree","remove",r,"--force"],{cwd:o,encoding:"utf-8",timeout:1e4}),b(e,{ok:!0})}catch(t){b(e,{error:t.message},500)}}function ua(n,e){try{let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("branch");if(!r)return b(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(r))return b(e,{error:"Invalid branch name"},400);let o=ae(),s=We("git",["diff",`main...${r}`,"--stat"],{cwd:o,encoding:"utf-8",timeout:1e4}).trim(),i=We("git",["diff",`main...${r}`],{cwd:o,encoding:"utf-8",timeout:3e4});b(e,{stat:s,diff:i})}catch(t){b(e,{error:t.message},500)}}async function pa(n,e){try{let t=await Se(n),{branch:r,title:o,bodyText:s}=JSON.parse(t);if(!r)return b(e,{error:"branch required"},400);let i=ae(),a=["pr","create","--head",r];o&&a.push("--title",o),s&&a.push("--body",s);let l=We("gh",a,{cwd:i,encoding:"utf-8",timeout:3e4}).trim();b(e,{ok:!0,url:l})}catch(t){b(e,{error:t.message},500)}}function da(n,e){try{let t=ae(),r=be("git remote get-url origin",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),o=null;r.includes("github.com")?o="github":r.includes("gitlab")&&(o="gitlab"),b(e,{platform:o,remoteUrl:r})}catch{b(e,{platform:null,remoteUrl:null})}}function fa(n,e){try{let t=ae(),r=be("gh pr list --json number,title,state,author,headRefName,url,isDraft,reviewDecision,statusCheckRollup --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});b(e,{prs:JSON.parse(r)})}catch(t){b(e,{prs:[],error:t.message})}}function ga(n,e){try{let t=ae(),r=be("gh issue list --json number,title,state,labels,assignees --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});b(e,{issues:JSON.parse(r)})}catch(t){b(e,{issues:[],error:t.message})}}function ma(n,e){try{let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("number");if(!r||!/^\d+$/.test(r))return b(e,{error:"PR number required"},400);let o=ae(),s=be(`gh pr diff ${r}`,{cwd:o,encoding:"utf-8",timeout:3e4});b(e,{diff:s})}catch(t){b(e,{error:t.message},500)}}function ha(n,e){try{let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("number");if(!r||!/^\d+$/.test(r))return b(e,{error:"PR number required"},400);let o=ae(),s=be(`gh pr checks ${r} --json name,state,status`,{cwd:o,encoding:"utf-8",timeout:15e3});b(e,{checks:JSON.parse(s)})}catch(t){b(e,{checks:[],error:t.message})}}async function va(n,e){try{let t=await Se(n),{number:r,action:o,comment:s}=JSON.parse(t);if(!r||!o)return b(e,{error:"number and action required"},400);let i=["approve","request-changes","comment"];if(!i.includes(o))return b(e,{error:`Invalid action. Use: ${i.join(", ")}`},400);let a=ae(),l=["pr","review",String(r),`--${o}`];s&&l.push("--body",s),We("gh",l,{cwd:a,encoding:"utf-8",timeout:15e3}),b(e,{ok:!0})}catch(t){b(e,{error:t.message},500)}}function ya(n){if(Kt)return;let e=te(),t=e.normalizePath(n.config.root),r=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(r))return;try{let a=be(`fuser ${yo}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();a&&process.kill(Number(a),"SIGKILL")}catch{}Kt=!0;let o=e.getRepoRoot(),s=Ki(),i=Hi(s,[r],{cwd:o,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(yo),TERMINAL_CWD:o}});i.on("message",a=>{a.type}),i.on("exit",a=>{Kt=!1}),process.on("exit",()=>{i.kill()})}function ba(n){let e=te(),t=e.getRepoRoot(),r=[".dndev","docs","guides"];for(let o of r){let s=e.resolveRepoPath(o);if(!e.pathExists(s))continue;let i=e.watch(s,{recursive:!0},(a,l)=>{if(!l||l==="dashboard.json")return;let c=`${o}/${l}`,u=`change:${c}`;Yt.has(u)||(Yt.set(u,!0),setTimeout(()=>Yt.delete(u),300),n.hot.send("dndev:file-changed",{path:c,timestamp:Date.now()}))});n.httpServer?.on("close",()=>i.close())}}function wa(n={}){return{name:"dndev",configureServer(e){let t=ae();n.debug,e.middlewares.use((r,o,s)=>{let i=r.url;if(!i?.startsWith(vo))return s();let l=new URL(i,`http://${r.headers.host}`).pathname.slice(vo.length),c=r.method?.toUpperCase();if(c==="GET")return l==="/file"?void Xi(r,o):l==="/tree"?void Qi(r,o):l==="/git/head"?void oa(r,o):l==="/apps"?void ia(r,o):l==="/worktrees"?void aa(r,o):l==="/worktrees/diff"?void ua(r,o):l==="/git/platform"?void da(r,o):l==="/git/prs"?void fa(r,o):l==="/git/issues"?void ga(r,o):l==="/git/pr/diff"?void ma(r,o):l==="/git/pr/checks"?void ha(r,o):b(o,{error:"Not found"},404);if(c==="POST")return l==="/file"?void ea(r,o):l==="/progress/toggle"?void ta(r,o):l==="/bugs/screenshot"?void ra(r,o):l==="/phase"?void na(r,o):l==="/actions/append"?void sa(r,o):l==="/worktrees/add"?void la(r,o):l==="/worktrees/remove"?void ca(r,o):l==="/worktrees/pr"?void pa(r,o):l==="/git/pr/review"?void va(r,o):b(o,{error:"Not found"},404);b(o,{error:"Method not allowed"},405)}),ya(e),ba(e)}}}var vo,Ji,xo,Zi,yo,Kt,Yt,Ro=xt(()=>{"use strict";q();vo="/api/dndev";Ji=5*1024*1024;xo={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},Zi=new Set(Object.keys(xo));yo=24681,Kt=!1;Yt=new Map});import Bo from"@rollup/plugin-strip";import{visualizer as Uo}from"rollup-plugin-visualizer";var St=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],No={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function Do(n){let e=n.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function Qt(n){let e=n.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function er(n,e=St){return e.some(t=>n.includes(t))}function ko(n){for(let[e,t]of Object.entries(No))if(t.some(r=>n.includes(r)))return e}function To(n){let e=Do(n);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=Qt(n);if(!t)return;if(er(t))return"react-core";let r=ko(t);if(r)return r}function Oo(n=[]){let e=n.filter(r=>!St.includes(r)),t=[...St,...e];return function(r){let o=Qt(r);if(o&&er(o,t))return"react-core"}}var Xt={development:{manualChunks:void 0},production:{manualChunks:To}};function tr(n,e={}){let t=Xt[n]||Xt.production,r=e.reactCore||[];return r.length>0?{manualChunks:Oo(r)}:t}q();import*as ie from"@clack/prompts";var fe={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 zo(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function he(n,e){return zo()?`${e}${n}${fe.reset}`:n}function M(n,e,t,r={}){let{logDir:o=".dndev-logs",fileLogging:s=!1}=r,i=D.getInstance(),a=null;if(s){let u=i.resolveAppPath(o);i.pathExists(u)||i.mkdir(u),a=i.resolveAppPath(`${o}/${n.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${n} Log Started at ${new Date().toISOString()} ===
8
- `;i.writeSync(a,p)}let l=(u,p,d)=>{if(a){let f=new Date().toISOString(),g=d.length>0?" "+d.map(m=>typeof m=="object"?JSON.stringify(m,null,2):String(m)).join(" "):"",w=`${f} [${u}] ${p}${g}
9
- `;i.appendFile(a,w)}},c=(u,p)=>{if(p.length===0)return u;let d=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${u} ${d}`};return{debug:(u,...p)=>{e&&(s?l("DEBUG",u,p):ie.log.message(he(c(u,p),fe.gray)))},verbose:(u,...p)=>{t&&(s?l("VERBOSE",u,p):ie.log.message(c(u,p)))},info:(u,...p)=>{s?l("INFO",u,p):ie.log.info(he(c(u,p),fe.brightCyan))},warn:(u,...p)=>{e&&s?l("WARN",u,p):ie.log.warn(he(c(u,p),fe.brightYellow))},error:(u,...p)=>{e&&s?l("ERROR",u,p):ie.log.error(he(c(u,p),fe.brightRed))},success:(u,...p)=>{e&&s?l("SUCCESS",u,p):ie.log.success(he(c(u,p),fe.brightGreen))},when:(u,p="debug")=>(d,...f)=>{if(u){let g=c(d,f);switch(p){case"verbose":t&&(ie.log.message(g),l("VERBOSE",d,f));break;case"info":ie.log.info(he(g,fe.brightCyan)),l("INFO",d,f);break;case"warn":ie.log.warn(he(g,fe.brightYellow)),l("WARN",d,f);break;case"error":ie.log.error(he(g,fe.brightRed)),l("ERROR",d,f);break;case"success":ie.log.success(he(g,fe.brightGreen)),l("SUCCESS",d,f);break;default:e&&(ie.log.message(he(g,fe.gray)),l("DEBUG",d,f))}}},getLogFilePath:()=>a}}q();function pr(n={}){let{mode:e="development",chunkingOptions:t={},debug:r,verbose:o=!0,isDev:s,isDebug:i,shouldAnalyze:a,build:l={}}=n,c=M("build",r,o),u=tr(e,t);return c.debug("\u{1F41B} DEBUG MODE ENABLED:"),c.debug(" - Minification: DISABLED"),c.debug(" - Sourcemaps: ENABLED"),c.debug(" - Console logs: PRESERVED"),c.debug(" - Debugger statements: PRESERVED"),a&&(c.info("\u{1F4CA} Bundle analysis enabled"),c.info(` Visual treemap will open after build (stats.html)
10
- `)),{outDir:"dist",sourcemap:s||i,cacheDir:"node_modules/.vite",target:"baseline-widely-available",minify:i?!1:"esbuild",reportCompressedSize:!1,chunkSizeWarningLimit:2048,assetsInlineLimit:0,esbuild:{format:"esm",drop:i?[]:["console","debugger"],legalComments:"none"},cssMinify:i?!1:"esbuild",cssCodeSplit:!0,rollupOptions:{external:Go(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...u.manualChunks&&{manualChunks:u.manualChunks},compact:!0},onwarn(d,f){d.code!=="MODULE_LEVEL_DIRECTIVE"&&f(d)},plugins:[...i?[]:[Bo({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...a?[(()=>{let d=D.getInstance(),f=d.getAppRoot(),g="dist",w=d.resolveAppPath(`${g}/stats.html`),m=()=>{try{let R=d.resolveAppPath(g);d.pathExists(R)||d.mkdir(R)}catch{}},h=Uo({filename:w,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:s||i,projectRoot:f});if(h.buildStart){let R=h.buildStart.bind(h);h.buildStart=function(...E){m();let S=R.apply(this,E);return S&&typeof S.then=="function"?S.catch(C=>{}):S}}else h.buildStart=function(){m()};let P=["generateBundle","writeBundle","closeBundle"];for(let R of P)if(h[R]){let E=h[R];h[R]=function(...S){try{m();let C=E.apply(this,S);return C&&typeof C.then=="function"?C.catch(k=>{let y=k?.message||k?.toString()||String(k)||"Unknown error";c.warn(`Bundle visualizer warning in ${R}: ${y}`),R==="closeBundle"&&c.warn(`You can manually open ${w} to view the bundle analysis`)}):C}catch(C){let k=C?.message||C?.toString()||String(C)||"Unknown error";c.warn(`Bundle visualizer warning in ${R}: ${k}`),R==="closeBundle"&&c.warn(` You can manually open ${w} to view the bundle analysis`)}}}return h})()]:[]]}}}function Go(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 Wo(){let n=!1,e=D.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 o=e.readSync("/proc/self/cgroup");o&&(o.includes("docker")||o.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 o=(e.readSync("/proc/version")||"").toLowerCase();t=o.includes("microsoft")||o.includes("wsl")}catch{}if(!t&&process.platform==="linux"&&e.pathExists("/proc/sys/kernel/osrelease"))try{let o=(e.readSync("/proc/sys/kernel/osrelease")||"").toLowerCase()||"";(o.includes("microsoft")||o.includes("wsl"))&&(t=!0)}catch{}if(!t&&process.platform==="win32"){let o=process.cwd();o&&(o.includes("\\wsl$")||o.includes("\\wsl.localhost"))&&(t=!0)}let r=typeof process.versions?.bun=="string";return{isDocker:n,isWSL2:t,isBun:r}}function Vo(n,e){if(n!==void 0)return n;let{isDocker:t,isWSL2:r,isBun:o}=Wo();if(t||r||o){let s=t?"Docker":r?"WSL2":"Bun";return e.info(`Detected ${s} environment - enabling polling mode for file watching`),!0}}function dr(n,e={},t){let r=D.getInstance(),o=r.getRepoRoot(),{watch:s,hmr:i,host:a,...l}=e||{},c=i||{},u=a===!0?"localhost":a||"localhost",p={...c.port&&{port:c.port},...c.clientPort&&{clientPort:c.clientPort},host:c.host??u,...c.protocol&&{protocol:c.protocol},overlay:c.overlay??!0,timeout:c.timeout??5e3},d=a!==void 0?a:!0,f=l.https===!0;return{port:n,host:d,open:e.open!==void 0?e.open:!0,https:f,fs:{allow:[o,r.resolveRepoPath("packages"),r.resolveRepoPath("node_modules")],strict:!1},watch:(()=>{let g=Vo(e?.watch?.usePolling,t);return{usePolling:g,interval:e?.watch?.interval??2e3,...g&&{awaitWriteFinish:{stabilityThreshold:300,pollInterval:100}},...e?.watch||{}}})(),hmr:{...p,...c},headers:{"Cross-Origin-Opener-Policy":"same-origin-allow-popups","Cross-Origin-Embedder-Policy":"unsafe-none"},middlewareMode:!1,...l}}function fr(n={}){let e=n.https===!0;return{...n,https:e}}J();var gr={debug:!1,verbose:process.env.CI!=="true",seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1,aiCrawlers:"recommended",llmsTxt:!0,speculationRules:!0,hreflang:!0,breadcrumbSchema:!0,websiteSchema:!0,organizationSchema:!0},serverShim:{enabled:!0},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},features:{}};var ue={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function Pe(n,e,t,r={}){let{protectedKeys:o=[],onConflict:s}=r;if(e==null)return n;switch(t){case ue.CONCATENATE_DEDUPE:{if(!Array.isArray(n)||!Array.isArray(e))return e;let i=[...n,...e];return[...new Set(i)]}case ue.SHALLOW_MERGE:return typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e)?e:{...n,...e};case ue.DEEP_MERGE:{if(typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e))return e;let i={...n};for(let a in e){if(o.includes(a)){s&&s(a,n[a],e[a]);continue}typeof i[a]=="object"&&typeof e[a]=="object"&&i[a]!==null&&e[a]!==null&&!Array.isArray(i[a])&&!Array.isArray(e[a])?i[a]=Pe(i[a],e[a],ue.DEEP_MERGE,{protectedKeys:o,onConflict:s}):i[a]=e[a]}return i}case ue.REPLACE:default:return e}}function mr(n,e,t=[],r){let o=[...n,...e||[]],s=[...new Set(o)];return[...new Set([...s,...t])]}var Fe={...gr,reactCompiler:!1,base:"/",mode:process.env.NODE_ENV==="production"?"production":"development",logLevel:process.env.NODE_ENV==="production"?"warn":"info",server:{port:3e3,strictPort:!0,host:!0,open:!0,cors:!0,https:!1,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:!1},preview:{port:4173,strictPort:!0,host:!0,open:!1,cors:!0,https:!1},routes:{hmr:!0},themes:{},i18n:{},assets:{},pwa:{enabled:!1},prerender:{routes:"auto"},chunking:{reactCore:[]},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:[...we.mandatoryIncludes],exclude:[...we.buildTools,...Object.values(U)],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 hr(n={},e={}){let{onConflict:t}=e,r={...Fe},o=[],s=(i,a,l,c)=>{o.push({key:i,frameworkValue:a,userValue:l,reason:c}),t&&t(i,a,l,c)};if("prerender"in n){let i=n.prerender;i===!1?n.prerender={routes:[]}:i===!0?n.prerender={routes:"auto"}:Array.isArray(i)&&(n.prerender={routes:i})}return Object.keys(n).forEach(i=>{let a=n[i],l=r[i];if(i==="optimizeDeps"&&typeof a=="object"&&a!==null){let c=l?.include||[],u=l?.exclude||[],p=a.include||[],d=a.exclude||[],f=c.filter(P=>!P.startsWith("@donotdev/")),g=d.filter(P=>f.includes(P));if(g.length>0)for(let P of g)s("optimizeDeps.exclude",P,"excluded",`Framework requires ${P} to be included. It will be included despite your exclusion.`);let w=mr(c,p,f),m=Pe(u,d,ue.CONCATENATE_DEDUPE),h=Pe(l?.esbuildOptions||{},a.esbuildOptions||{},ue.DEEP_MERGE,{protectedKeys:["external"],onConflict:P=>s(`optimizeDeps.esbuildOptions.${P}`,l?.esbuildOptions?.[P],a.esbuildOptions?.[P],`Framework requires ${P} to remain as configured.`)});r[i]={...l,include:w,exclude:m,esbuildOptions:h,...Object.fromEntries(Object.entries(a).filter(([P])=>!["include","exclude","esbuildOptions"].includes(P)))};return}if(i==="css"&&typeof a=="object"&&a!==null){r[i]=Pe(l||{},a,ue.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>s("css.postcss","framework PostCSS config",a.postcss,"Framework PostCSS config is required and cannot be overridden. Your postcss config is ignored.")});return}if(i==="define"&&typeof a=="object"&&a!==null){r[i]=Pe(l||{},a,ue.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:c=>s(`define.${c}`,l?.[c],a[c],`Framework requires ${c} to remain as configured.`)});return}if(Array.isArray(a)){Array.isArray(l)?r[i]=Pe(l,a,ue.CONCATENATE_DEDUPE):r[i]=a;return}if(typeof a=="object"&&a!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){r[i]=Pe(l,a,ue.SHALLOW_MERGE);return}r[i]=a}),r}function vr(n){let{server:e={},preview:t={},mode:r,build:o={},resolve:s={},routes:i={},themes:a={},i18n:l={},assets:c={},features:u={},seo:p={},prerender:d={},pwa:f={},serverShim:g={},chunking:w={},discovery:m={},pluginFactory:h={},debug:P,verbose:R,base:E,define:S={},optimizeDeps:C={},plugins:k=[],css:y={},envDir:T,reactCompiler:$=!1,...v}=n,G=r==="development",A=P||G,L=r==="production"&&(o.analyze??Fe.build.analyze);return{mode:r,debug:P,verbose:R,isDev:G,isDebug:A,shouldAnalyze:L,serverOptions:e,previewOptions:t,buildOverrides:o,resolveOptions:s,routeOptions:i,themeOptions:a,i18nOptions:l,assetOptions:c,featureOptions:u,seoOptions:p,prerenderOptions:d,pwaOptions:f,serverShimOptions:g,chunkingOptions:w,discoveryOptions:m,pluginFactoryOptions:h,base:E,defineOptions:S,optimizeDepsOptions:C,pluginsOptions:k,cssOptions:y,envDir:T,reactCompiler:$,restOptions:v}}q();import Ho from"autoprefixer";import Jo from"postcss-import";import qo from"postcss-nesting";function yr({postcssImport:n,postcssNesting:e,autoprefixer:t,resolve:r}){return{plugins:[r?n({resolve:r}):n,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function br(n={}){if(n.postcss)return n.postcss;let e=D.getInstance();return yr({postcssImport:Jo,postcssNesting:qo,autoprefixer:Ho,resolve:(r,o)=>{let s=e.resolvePackage(r,o);if(s)return s;if(r.startsWith("@donotdev/")){let i=r.split("/")[0]+"/"+r.split("/")[1],a=r.split("/").slice(2).join("/"),l=e.resolveFrameworkPackage(i,o);if(l&&a){let c=e.resolvePath(a,l);if(e.pathExists(c))return c}}return e.resolvePath(r,o)}})}import Ui from"@vitejs/plugin-basic-ssl";import Gi from"@vitejs/plugin-react";import Wi from"vite-tsconfig-paths";var ne=class{static generateVirtualModule(e,t,r=!1,o=void 0,s=void 0){return t.isEmpty(e)?t.generateEmpty(e,r,o,s):t.generateModule(e,r,s)}static generateInspection(e,t,r,o){return t.generateInspection.length>=3?t.generateInspection(e,r,o):t.generateInspection(e,r)}static wrapVirtualModule(e,t){return`// Virtual module: ${e}
1
+ var ss=Object.defineProperty;var _t=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(n){throw t=[n],n}};var as=(o,e)=>{for(var t in e)ss(o,t,{get:e[t],enumerable:!0})};function bn(o,e=null){let t=pe[o];if(!t)throw new Error(`Unknown pattern type: ${o}`);return e&&t.framework?{...t,framework:t.framework.map(n=>`${e}/${n}`)}:t}function st(o){return mn[o]||mn.base}var Nt,V,oe,ve,qe,rt,kt,$e,Fe,pe,Pe,hn,Dt,Tt,vn,yn,Ot,mn,q=_t(()=>{"use strict";Nt={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},V={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},oe={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},ve={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.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",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts",fonts:"src/app/fonts.generated.ts"},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"}},qe="/og-image.png",rt="_shell.html",kt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},$e={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Fe={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",PUBLISHED_FLAGS:"i18n/flags"},pe={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:[`${Fe.SOURCE_EAGER}/*_*.json`],lazy:[`${Fe.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","icon-*x*.png",qe.slice(1)],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/**"]},Pe={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],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"]},hn=["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"],Dt=["@donotdev/core/functions","@donotdev/core/server"],Tt={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)/}},vn=["-apple-system","BlinkMacSystemFont","SF Pro","SF Pro Text","SF Pro Display","SF Mono","Helvetica Neue","Helvetica","Menlo","Monaco","Apple SD Gothic Neo","Hiragino Sans","Hiragino Kaku Gothic ProN","PingFang SC","PingFang TC","Apple Color Emoji","Segoe UI","Segoe UI Emoji","Segoe UI Symbol","Cascadia Code","Cascadia Mono","Consolas","Arial","Georgia","Times New Roman","Times","Courier New","Courier","Verdana","Tahoma","Trebuchet MS","Malgun Gothic","Yu Gothic","Meiryo","Microsoft YaHei","Microsoft JhengHei","Liberation Sans","Liberation Serif","Liberation Mono","DejaVu Sans","DejaVu Serif","DejaVu Sans Mono","Ubuntu","Cantarell","Noto Sans","Noto Serif","Noto Color Emoji","Droid Sans","Droid Sans Mono"],yn={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin","latin-ext"],cs:["latin","latin-ext"],sk:["latin","latin-ext"],hr:["latin","latin-ext"],sl:["latin","latin-ext"],hu:["latin","latin-ext"],ro:["latin","latin-ext"],et:["latin","latin-ext"],lv:["latin","latin-ext"],lt:["latin","latin-ext"],mt:["latin","latin-ext"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin","latin-ext"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","latin-ext","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},Ot=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],mn={base:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...pe.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...pe.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore}}});import*as j from"node:fs";import"node:fs";import{createRequire as fs}from"node:module";import{resolve as at,join as Ae,dirname as De,relative as wn,normalize as gs,sep as En,extname as ms}from"node:path";import hs from"fast-glob";function Le(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EEXIST"}function Sn(o,e){return o().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Me,ee,xn,O,Y=_t(()=>{"use strict";q();Me={getGlobOptionsFor:st||void 0,SCAN_PATTERNS:pe||void 0,getPatternsFor:bn||void 0,I18N_PATHS:Fe||void 0},ee={error:(o,e)=>{},warn:(o,e)=>{},info:o=>{}};xn={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 o{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return o._instance||(o._instance=new o(e)),o._instance}static _reset(){o._instance=null}constructor(e={}){if(o._instance)return o._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,o._instance=this}normalizePath(e){if(!e)return"";try{return gs(e).split(En).join("/")}catch{return String(e).split(En).join("/")}}getRelativePath(e){let t=this.getAppRoot(),n=wn(t,e);return this.normalizePath(n)}getBasename(e){if(!e)return"";let n=this.normalizePath(e).split("/");return n[n.length-1]||""}getDirname(e){return e?this.normalizePath(De(e)):""}resolvePackage(e,t=null){try{let n=t||this.getAppRoot(),s=fs(Ae(n,"package.json")).resolve(e);return this.normalizePath(s)}catch{return null}}resolveFrameworkPackage(e,t=null){let n=this.resolvePackage(`${e}/package.json`,t);if(n)return this.getDirname(n);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 s=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(s)?s:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),n=at(t,e);return this.normalizePath(n)}resolveRepoPath(e){let t=this.getRepoRoot(),n=this.normalizePath(e),r=at(t,n);return this.normalizePath(r)}resolvePath(e,t){let n=this.normalizePath(t),r=this.normalizePath(e),s=at(n,r);return this.normalizePath(s)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=j.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:ms(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:n="auto",encoding:r="utf8"}=t,s=this._detectFormat(e,n);try{if(s==="buffer")return await j.promises.readFile(e);let a=await j.promises.readFile(e,r),i=this.stripBom(a);return s==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&ee.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:n="auto",encoding:r="utf8"}=t,s=this._detectFormat(e,n);try{if(s==="buffer")return j.readFileSync(e);let a=j.readFileSync(e,r),i=this.stripBom(a);return s==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&ee.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,n={}){let{format:r="auto",overwrite:s=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),c=this.normalizePath(De(l)),u=this.pathExists(l);if(u&&!s)return i&&ee.info(`Skipping existing file: ${l}`),!1;if(a)return ee.info(`[DRY RUN] Would write file: ${l}`),!0;try{await j.promises.mkdir(c,{recursive:!0})}catch(f){if(!Le(f))throw f}let p=this._detectFormat(e,r),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
2
+ `:d=String(t);try{return await Sn(async()=>(Buffer.isBuffer(d)?await j.promises.writeFile(l,d):await j.promises.writeFile(l,d,"utf8"),i&&ee.info(`${u?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,n={}){let{format:r="auto",overwrite:s=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),c=this.normalizePath(De(l)),u=this.pathExists(l);if(u&&!s)return i&&ee.info(`Skipping existing file: ${l}`),!1;if(a)return ee.info(`[DRY RUN] Would write file: ${l}`),!0;try{j.mkdirSync(c,{recursive:!0})}catch(f){if(!Le(f))throw f}let p=this._detectFormat(e,r),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
3
+ `:d=String(t);try{return Buffer.isBuffer(d)?j.writeFileSync(l,d):j.writeFileSync(l,d,"utf8"),this._writtenPaths?.add(l),i&&ee.info(`${u?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,n={}){let{overwrite:r=!1,dryRun:s=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&ee.info(`Skipping existing file: ${i}`),!1;if(s)return ee.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(De(i));try{await j.promises.mkdir(c,{recursive:!0})}catch(u){if(!Le(u))throw u}try{return await Sn(async()=>(await j.promises.copyFile(e,i),a&&ee.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,n={}){let{overwrite:r=!1,dryRun:s=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return a&&ee.info(`Skipping existing file: ${i}`),!1;if(s)return ee.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(De(i));try{j.mkdirSync(c,{recursive:!0})}catch(u){if(!Le(u))throw u}try{return j.copyFileSync(e,i),this._writtenPaths?.add(i),a&&ee.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return j.existsSync(e)}catch(n){return t||ee.error(`Error checking path existence: ${e}`,n),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return j.existsSync(t)||j.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return j.readdirSync(e,t)}catch(n){return this.options.debug&&ee.warn(`Failed to read directory: ${e}`,n),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return j.statSync(e)}catch(t){return this.options.debug&&ee.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return j.realpathSync(e)}watch(e,t,n){return j.watch(e,t,n)}lstatSync(e){try{return j.lstatSync(e)}catch(t){return this.options.debug&&ee.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await j.promises.mkdir(e,{recursive:!0})}catch(t){if(!Le(t))throw t}}ensureDirSync(e){try{j.mkdirSync(e,{recursive:!0})}catch(t){if(!Le(t))throw t}}async remove(e){await j.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){j.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return j.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}startWriteRecording(){this._writtenPaths=new Set}stopWriteRecording(){if(!this._writtenPaths)throw new Error("stopWriteRecording() called without startWriteRecording()");let e=this._writtenPaths;return this._writtenPaths=null,e}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=Ae(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(at(e)),n=this.getAppRoot(),r=wn(n,t),s=this.normalizePath(r);return!s.startsWith("../")&&!s.startsWith("/")}async findFiles(e,t,n={}){let r=this.normalizePath(Ae(e,t)),s=this.getAppRoot(),a=this.normalizePath(s),i=r.startsWith(a)?r.slice(a.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:Me.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...n})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Me.I18N_PATHS;if(!t)return null;let n=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let s=this.normalizePath(Ae(r,t.PUBLISHED_ROOT,n)),a=s.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),s}async _globWithNormalization(e,t){return(await hs(e,t)).map(r=>{let s=typeof r=="string"?r:r.path;return this.normalizePath(s)}).sort()}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 n=[...e.framework,...e.consumer];for(let u of n)if(typeof u!="string"||u.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),s=Me.getGlobOptionsFor?Me.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),i=e.framework.map(u=>{let p=this.normalizePath(u);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(u=>{let p=this.normalizePath(u);return p.startsWith(a)?p.slice(a.length+1):p}),c={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let u=i.length>0?await this._globWithNormalization(i,c):[],p=await this._globWithNormalization(l,c);return{frameworkFiles:u,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!Me.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),n=this.getRepoRoot();if(e==="i18n"&&(!t||t===n))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${n}). Ensure configResolved hook has run before discovery.`);let r=Me.getPatternsFor(e),s=this.isMonorepo();if(e==="i18n"){let l=r,c={eager:l.eager.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),lazy:l.lazy.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),framework:{eager:s?(l.framework?.eager||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean)),lazy:s?(l.framework?.lazy||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean))},all:[]};return c.all=[...c.eager,...c.lazy,...c.framework.eager,...c.framework.lazy],c}let a=r,i={framework:s?(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(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),n=0,r=this.options.maxLevels;for(;n<r;){let s=this.normalizePath(Ae(t,xn.TOOLING)),a=this.normalizePath(Ae(t,xn.CORE));if(this.pathExists(s)&&this.pathExists(a))return t;let i=Ae(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(Ae(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(De(t))===t)return t;let c=this.normalizePath(De(t));if(c===t)break;t=c,n++}return this.normalizePath(e)}}});var es={};as(es,{createDndevPlugin:()=>Nl});import{execSync as Se,execFileSync as Ve,spawn as nl}from"node:child_process";function re(){return O.getInstance()}function ce(){return re().getRepoRoot()}function Yr(){return re().resolveRepoPath(".dndev")}function b(o,e,t=200){o.writeHead(t,{"Content-Type":"application/json"}),o.end(JSON.stringify(e))}function _e(o,e=ol){return new Promise((t,n)=>{let r="",s=0;o.on("data",a=>{if(s+=a.length,s>e){o.destroy(),n(new Error("Request body too large"));return}r+=a.toString()}),o.on("end",()=>t(r)),o.on("error",n)})}function rl(o){let e=o.lastIndexOf(".");return e===-1?"":o.slice(e).toLowerCase()}function sl(){let o=re(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let r=process.platform==="win32"?"where node":"which node",s=Se(r,{encoding:"utf8"}).trim().split(`
4
+ `)[0];e.push(s)}catch{}let n=[process.env.NVM_DIR,o.resolvePath(".nvm",t)].filter(Boolean);for(let r of n)try{let s=o.resolvePath("versions/node",r),a=o.readdirSync(s).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(o.resolvePath(`${i}/bin/node`,s))}catch{}if(process.env.NVM_BIN&&e.push(o.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 s=o.resolvePath("nvm",r),a=o.readdirSync(s).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(o.resolvePath(`${i}/node.exe`,s))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let r of e)try{let s=o.realpathSync(r);if(s.includes("bun")||!o.pathExists(s))continue;return r}catch{continue}return"node"}function Zr(o){if(!o||typeof o!="string"||o.includes("\0"))return!1;let e=o.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 al(o){return o.includes("..")?!1:o.startsWith(".dndev/")||o.startsWith("docs/")||o.startsWith("guides/")}function Xr(o){let e=re(),t=e.getRepoRoot(),n=e.resolvePath(o,t),r=e.normalizePath(t),s=e.normalizePath(n);return!s.startsWith(r+"/")&&s!==r?null:n}async function ll(o,e){let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("path");if(!n)return b(e,{error:"path parameter required"},400);if(!Zr(n))return b(e,{error:"Access denied"},403);let r=Xr(n);if(!r)return b(e,{error:"Access denied"},403);let s=re();if(!s.pathExists(r))return b(e,{error:"File not found"},404);let a=rl(r);if(il.has(a)){let i=s.readSync(r,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":Qr[a]||"application/octet-stream","Content-Length":i.byteLength}),void e.end(Buffer.from(i))):b(e,{error:"Failed to read file"},500)}if(a===".json")try{let i=await s.read(r);return i===null?b(e,{error:"Failed to read file"},500):b(e,{path:n,content:i})}catch{return b(e,{error:"Invalid JSON"},500)}try{let i=await s.read(r,{format:"text"});if(i===null)return b(e,{error:"Failed to read file"},500);b(e,{path:n,content:i})}catch{b(e,{error:"Failed to read file"},500)}}function cl(o,e){let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("dir"),r=re(),s=r.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function l(u,p){try{let d=r.readdirSync(u,{withFileTypes:!0});for(let f of d){let g=p?`${p}/${f.name}`:f.name;f.isDirectory()&&i.has(f.name)||(f.isDirectory()?(a.push({path:g,name:f.name,isDirectory:!0}),l(r.resolvePath(f.name,u),g)):f.name.endsWith(".md")&&a.push({path:g,name:f.name,isDirectory:!1}))}}catch{}}let c=[".dndev","docs","guides"];if(n){if(n.includes("..")||n.includes("\0"))return b(e,{error:"Access denied"},403);if(!c.includes(n)&&!c.some(f=>n.startsWith(f+"/")))return b(e,{error:"Directory not allowed"},403);let u=r.resolvePath(n,s),p=r.normalizePath(s);if(!r.normalizePath(u).startsWith(p+"/"))return b(e,{error:"Access denied"},403);r.pathExists(u)&&(a.push({path:n,name:r.getBasename(n),isDirectory:!0}),l(u,n))}else{for(let u of c){let p=r.resolveRepoPath(u);r.pathExists(p)&&(a.push({path:u,name:u,isDirectory:!0}),l(p,u))}try{let u=r.readdirSync(s,{withFileTypes:!0});for(let p of u)!p.isDirectory()&&p.name.endsWith(".md")&&a.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}b(e,{entries:a})}async function ul(o,e){let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("path");if(!n)return b(e,{error:"path parameter required"},400);if(!Zr(n))return b(e,{error:"Access denied"},403);if(!al(n))return b(e,{error:"Write not allowed to this path"},403);let r=Xr(n);if(!r)return b(e,{error:"Access denied"},403);try{let s=await _e(o),{content:a}=JSON.parse(s);if(a===void 0)return b(e,{error:"content field required"},400);let i=typeof a=="string"?a:JSON.stringify(a,null,2);await re().write(r,i,{overwrite:!0}),b(e,{ok:!0})}catch{b(e,{error:"Failed to write file"},500)}}async function pl(o,e){try{let t=await _e(o),{line:n,checked:r}=JSON.parse(t);if(typeof n!="number")return b(e,{error:"line number required"},400);let s=re(),a=s.resolveRepoPath(".dndev/implementation.md");if(!s.pathExists(a))return b(e,{error:"implementation.md not found"},404);let i=await s.read(a,{format:"text"});if(i===null)return b(e,{error:"Failed to read file"},500);let l=i.split(`
5
+ `);if(n<0||n>=l.length)return b(e,{error:"Line out of range"},400);let c=l[n];l[n]=r?c.replace("- [ ]","- [x]"):c.replace("- [x]","- [ ]"),await s.write(a,l.join(`
6
+ `),{overwrite:!0}),b(e,{ok:!0,line:l[n]})}catch{b(e,{error:"Failed to update progress"},500)}}async function dl(o,e){try{let t=await _e(o),{id:n,data:r}=JSON.parse(t);if(!n||!r)return b(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(n))return b(e,{error:"Invalid screenshot ID"},400);let s=re(),a=s.resolveRepoPath(".dndev/bugs");s.ensureDirSync(a);let i=Buffer.from(r,"base64"),l=s.resolvePath(`${n}.png`,a);await s.write(l,i,{overwrite:!0}),b(e,{ok:!0,path:`.dndev/bugs/${n}.png`})}catch{b(e,{error:"Failed to save screenshot"},500)}}async function fl(o,e){try{let t=await _e(o),{action:n,phase:r}=JSON.parse(t);if(!n||typeof r!="number")return b(e,{error:"action and phase required"},400);let s=re(),a=Yr();s.ensureDirSync(a);let i=s.resolvePath("protocol.json",a),l={currentPhase:0,phases:{}};if(s.pathExists(i))try{let c=await s.read(i);c&&(l=c)}catch{}n==="start"?(l.currentPhase=r,l.phases[r]||(l.phases[r]={}),l.phases[r].status="active",l.phases[r].startedAt=new Date().toISOString()):n==="complete"&&(l.phases[r]||(l.phases[r]={}),l.phases[r].status="completed",l.phases[r].completedAt=new Date().toISOString()),await s.write(i,l,{overwrite:!0}),b(e,{ok:!0,protocol:l})}catch{b(e,{error:"Failed to update phase"},500)}}function gl(o,e){try{let t=ce(),n=Se("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=Se("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();b(e,{commit:n,branch:r})}catch{b(e,{commit:"unknown",branch:"unknown"})}}async function ml(o,e){try{let t=await _e(o),n=JSON.parse(t);if(!n.id||!n.type||!n.result)return b(e,{error:"id, type, and result required"},400);let r=re(),s=Yr();r.ensureDirSync(s);let a=r.resolvePath("health.json",s),i={actions:[]};if(r.pathExists(a))try{let c=await r.read(a);c&&(i=c)}catch{}Array.isArray(i.actions)||(i.actions=[]);let l=i.actions.findIndex(c=>c.id===n.id);l>=0?i.actions[l]={...i.actions[l],...n}:i.actions.unshift(n),await r.write(a,i,{overwrite:!0}),b(e,{ok:!0})}catch{b(e,{error:"Failed to append action"},500)}}function hl(o,e){let t=re(),n=t.resolveRepoPath("apps");try{let s=t.readdirSync(n).filter(a=>{if(a==="dndev")return!1;let i=t.resolvePath(a,n);return t.statSync(i)?.isDirectory()&&t.pathExists(t.resolvePath("package.json",i))}).map(a=>{try{let i=t.resolvePath(`${a}/package.json`,n),l=t.readSync(i);return{name:a,packageName:l?.name||a}}catch{return{name:a,packageName:a}}});b(e,{apps:s})}catch{b(e,{apps:[]})}}function vl(o,e){try{let t=ce(),n=Se("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),r=[],s={};for(let a of n.split(`
7
+ `))a.startsWith("worktree ")?(s.path&&r.push(s),s={path:a.slice(9)}):a.startsWith("HEAD ")?s.head=a.slice(5):a.startsWith("branch ")?(s.branch=a.slice(7),s.shortBranch=s.branch.replace("refs/heads/","")):a==="detached"&&(s.detached=!0);s.path&&r.push(s),b(e,{worktrees:r})}catch(t){b(e,{error:t.message},500)}}async function yl(o,e){try{let t=await _e(o),{branch:n}=JSON.parse(t);if(!n||typeof n!="string")return b(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(n))return b(e,{error:"Invalid branch name"},400);let r=ce(),s=re(),a=s.resolvePath("..",r),i=s.getBasename(r),l=s.resolvePath(`${i}-${n.replace(/\//g,"-")}`,a);Ve("git",["worktree","add",l,"-b",n],{cwd:r,encoding:"utf-8",timeout:3e4}),b(e,{ok:!0,path:l,branch:n})}catch(t){b(e,{error:t.message},500)}}async function bl(o,e){try{let t=await _e(o),{path:n}=JSON.parse(t);if(!n||typeof n!="string")return b(e,{error:"path required"},400);let r=ce();Ve("git",["worktree","remove",n,"--force"],{cwd:r,encoding:"utf-8",timeout:1e4}),b(e,{ok:!0})}catch(t){b(e,{error:t.message},500)}}function wl(o,e){try{let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("branch");if(!n)return b(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(n))return b(e,{error:"Invalid branch name"},400);let r=ce(),s=Ve("git",["diff",`main...${n}`,"--stat"],{cwd:r,encoding:"utf-8",timeout:1e4}).trim(),a=Ve("git",["diff",`main...${n}`],{cwd:r,encoding:"utf-8",timeout:3e4});b(e,{stat:s,diff:a})}catch(t){b(e,{error:t.message},500)}}async function El(o,e){try{let t=await _e(o),{branch:n,title:r,bodyText:s}=JSON.parse(t);if(!n)return b(e,{error:"branch required"},400);let a=ce(),i=["pr","create","--head",n];r&&i.push("--title",r),s&&i.push("--body",s);let l=Ve("gh",i,{cwd:a,encoding:"utf-8",timeout:3e4}).trim();b(e,{ok:!0,url:l})}catch(t){b(e,{error:t.message},500)}}function Sl(o,e){try{let t=ce(),n=Se("git remote get-url origin",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),r=null;n.includes("github.com")?r="github":n.includes("gitlab")&&(r="gitlab"),b(e,{platform:r,remoteUrl:n})}catch{b(e,{platform:null,remoteUrl:null})}}function xl(o,e){try{let t=ce(),n=Se("gh pr list --json number,title,state,author,headRefName,url,isDraft,reviewDecision,statusCheckRollup --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});b(e,{prs:JSON.parse(n)})}catch(t){b(e,{prs:[],error:t.message})}}function $l(o,e){try{let t=ce(),n=Se("gh issue list --json number,title,state,labels,assignees --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});b(e,{issues:JSON.parse(n)})}catch(t){b(e,{issues:[],error:t.message})}}function Pl(o,e){try{let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("number");if(!n||!/^\d+$/.test(n))return b(e,{error:"PR number required"},400);let r=ce(),s=Se(`gh pr diff ${n}`,{cwd:r,encoding:"utf-8",timeout:3e4});b(e,{diff:s})}catch(t){b(e,{error:t.message},500)}}function Rl(o,e){try{let n=new URL(o.url,`http://${o.headers.host}`).searchParams.get("number");if(!n||!/^\d+$/.test(n))return b(e,{error:"PR number required"},400);let r=ce(),s=Se(`gh pr checks ${n} --json name,state,status`,{cwd:r,encoding:"utf-8",timeout:15e3});b(e,{checks:JSON.parse(s)})}catch(t){b(e,{checks:[],error:t.message})}}async function Cl(o,e){try{let t=await _e(o),{number:n,action:r,comment:s}=JSON.parse(t);if(!n||!r)return b(e,{error:"number and action required"},400);let a=["approve","request-changes","comment"];if(!a.includes(r))return b(e,{error:`Invalid action. Use: ${a.join(", ")}`},400);let i=ce(),l=["pr","review",String(n),`--${r}`];s&&l.push("--body",s),Ve("gh",l,{cwd:i,encoding:"utf-8",timeout:15e3}),b(e,{ok:!0})}catch(t){b(e,{error:t.message},500)}}function _l(o){if(ln)return;let e=re(),t=e.normalizePath(o.config.root),n=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(n))return;try{let i=Se(`fuser ${Kr}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}ln=!0;let r=e.getRepoRoot(),s=sl(),a=nl(s,[n],{cwd:r,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(Kr),TERMINAL_CWD:r}});a.on("message",i=>{i.type}),a.on("exit",i=>{ln=!1}),process.on("exit",()=>{a.kill()})}function Al(o){let e=re(),t=e.getRepoRoot(),n=[".dndev","docs","guides"];for(let r of n){let s=e.resolveRepoPath(r);if(!e.pathExists(s))continue;let a=e.watch(s,{recursive:!0},(i,l)=>{if(!l||l==="dashboard.json")return;let c=`${r}/${l}`,u=`change:${c}`;cn.has(u)||(cn.set(u,!0),setTimeout(()=>cn.delete(u),300),o.hot.send("dndev:file-changed",{path:c,timestamp:Date.now()}))});o.httpServer?.on("close",()=>a.close())}}function Nl(o={}){return{name:"dndev",configureServer(e){let t=ce();o.debug,e.middlewares.use((n,r,s)=>{let a=n.url;if(!a?.startsWith(qr))return s();let l=new URL(a,`http://${n.headers.host}`).pathname.slice(qr.length),c=n.method?.toUpperCase();if(c==="GET")return l==="/file"?void ll(n,r):l==="/tree"?void cl(n,r):l==="/git/head"?void gl(n,r):l==="/apps"?void hl(n,r):l==="/worktrees"?void vl(n,r):l==="/worktrees/diff"?void wl(n,r):l==="/git/platform"?void Sl(n,r):l==="/git/prs"?void xl(n,r):l==="/git/issues"?void $l(n,r):l==="/git/pr/diff"?void Pl(n,r):l==="/git/pr/checks"?void Rl(n,r):b(r,{error:"Not found"},404);if(c==="POST")return l==="/file"?void ul(n,r):l==="/progress/toggle"?void pl(n,r):l==="/bugs/screenshot"?void dl(n,r):l==="/phase"?void fl(n,r):l==="/actions/append"?void ml(n,r):l==="/worktrees/add"?void yl(n,r):l==="/worktrees/remove"?void bl(n,r):l==="/worktrees/pr"?void El(n,r):l==="/git/pr/review"?void Cl(n,r):b(r,{error:"Not found"},404);b(r,{error:"Method not allowed"},405)}),_l(e),Al(e)}}}var qr,ol,Qr,il,Kr,ln,cn,ts=_t(()=>{"use strict";Y();qr="/api/dndev";ol=5*1024*1024;Qr={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},il=new Set(Object.keys(Qr));Kr=24681,ln=!1;cn=new Map});import ys from"@rollup/plugin-strip";import{visualizer as bs}from"rollup-plugin-visualizer";var At=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],is={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function ls(o){let e=o.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function dn(o){let e=o.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function fn(o,e=At){return e.some(t=>o.includes(t))}function cs(o){for(let[e,t]of Object.entries(is))if(t.some(n=>o.includes(n)))return e}function us(o){let e=ls(o);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=dn(o);if(!t)return;if(fn(t))return"react-core";let n=cs(t);if(n)return n}function ps(o=[]){let e=o.filter(n=>!At.includes(n)),t=[...At,...e];return function(n){let r=dn(n);if(r&&fn(r,t))return"react-core"}}var pn={development:{manualChunks:void 0},production:{manualChunks:us}};function gn(o,e={}){let t=pn[o]||pn.production,n=e.reactCore||[];return n.length>0?{manualChunks:ps(n)}:t}Y();import*as le from"@clack/prompts";var me={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 vs(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function ye(o,e){return vs()?`${e}${o}${me.reset}`:o}function G(o,e,t,n={}){let{logDir:r=".dndev-logs",fileLogging:s=!1}=n,a=O.getInstance(),i=null;if(s){let u=a.resolveAppPath(r);a.pathExists(u)||a.mkdir(u),i=a.resolveAppPath(`${r}/${o.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${o} Log Started at ${new Date().toISOString()} ===
8
+ `;a.writeSync(i,p)}let l=(u,p,d)=>{if(i){let f=new Date().toISOString(),g=d.length>0?" "+d.map(h=>typeof h=="object"?JSON.stringify(h,null,2):String(h)).join(" "):"",v=`${f} [${u}] ${p}${g}
9
+ `;a.appendFile(i,v)}},c=(u,p)=>{if(p.length===0)return u;let d=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${u} ${d}`};return{debug:(u,...p)=>{e&&(s?l("DEBUG",u,p):le.log.message(ye(c(u,p),me.gray)))},verbose:(u,...p)=>{t&&(s?l("VERBOSE",u,p):le.log.message(c(u,p)))},info:(u,...p)=>{s?l("INFO",u,p):le.log.info(ye(c(u,p),me.brightCyan))},warn:(u,...p)=>{e&&s?l("WARN",u,p):le.log.warn(ye(c(u,p),me.brightYellow))},error:(u,...p)=>{e&&s?l("ERROR",u,p):le.log.error(ye(c(u,p),me.brightRed))},success:(u,...p)=>{e&&s?l("SUCCESS",u,p):le.log.success(ye(c(u,p),me.brightGreen))},when:(u,p="debug")=>(d,...f)=>{if(u){let g=c(d,f);switch(p){case"verbose":t&&(le.log.message(g),l("VERBOSE",d,f));break;case"info":le.log.info(ye(g,me.brightCyan)),l("INFO",d,f);break;case"warn":le.log.warn(ye(g,me.brightYellow)),l("WARN",d,f);break;case"error":le.log.error(ye(g,me.brightRed)),l("ERROR",d,f);break;case"success":le.log.success(ye(g,me.brightGreen)),l("SUCCESS",d,f);break;default:e&&(le.log.message(ye(g,me.gray)),l("DEBUG",d,f))}}},getLogFilePath:()=>i}}Y();function $n(o={}){let{mode:e="development",chunkingOptions:t={},debug:n,verbose:r=!0,isDev:s,isDebug:a,shouldAnalyze:i,build:l={}}=o,c=G("build",n,r),u=gn(e,t);return c.debug("\u{1F41B} DEBUG MODE ENABLED:"),c.debug(" - Minification: DISABLED"),c.debug(" - Sourcemaps: ENABLED"),c.debug(" - Console logs: PRESERVED"),c.debug(" - Debugger statements: PRESERVED"),i&&(c.info("\u{1F4CA} Bundle analysis enabled"),c.info(` Visual treemap will open after build (stats.html)
10
+ `)),{outDir:"dist",sourcemap:s||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:ws(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...u.manualChunks&&{manualChunks:u.manualChunks},compact:!0},onwarn(d,f){d.code!=="MODULE_LEVEL_DIRECTIVE"&&f(d)},plugins:[...a?[]:[ys({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let d=O.getInstance(),f=d.getAppRoot(),g="dist",v=d.resolveAppPath(`${g}/stats.html`),h=()=>{try{let $=d.resolveAppPath(g);d.pathExists($)||d.mkdir($)}catch{}},y=bs({filename:v,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:s||a,projectRoot:f});if(y.buildStart){let $=y.buildStart.bind(y);y.buildStart=function(...S){h();let x=$.apply(this,S);return x&&typeof x.then=="function"?x.catch(N=>{}):x}}else y.buildStart=function(){h()};let C=["generateBundle","writeBundle","closeBundle"];for(let $ of C)if(y[$]){let S=y[$];y[$]=function(...x){try{h();let N=S.apply(this,x);return N&&typeof N.then=="function"?N.catch(D=>{let P=D?.message||D?.toString()||String(D)||"Unknown error";c.warn(`Bundle visualizer warning in ${$}: ${P}`),$==="closeBundle"&&c.warn(`You can manually open ${v} to view the bundle analysis`)}):N}catch(N){let D=N?.message||N?.toString()||String(N)||"Unknown error";c.warn(`Bundle visualizer warning in ${$}: ${D}`),$==="closeBundle"&&c.warn(` You can manually open ${v} to view the bundle analysis`)}}}return y})()]:[]]}}}function ws(o){return o?["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 Es(){let o=!1,e=O.getInstance();if((e.pathExists("/.dockerenv")||e.pathExists("/run/.containerenv"))&&(o=!0),!o&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(o=!0),!o&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(o=!0),!o&&process.platform==="linux"&&e.pathExists("/proc/self/cgroup"))try{let r=e.readSync("/proc/self/cgroup");r&&(r.includes("docker")||r.includes("containerd"))&&(o=!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 n=typeof process.versions?.bun=="string";return{isDocker:o,isWSL2:t,isBun:n}}function Ss(o,e){if(o!==void 0)return o;let{isDocker:t,isWSL2:n,isBun:r}=Es();if(t||n||r){let s=t?"Docker":n?"WSL2":"Bun";return e.info(`Detected ${s} environment - enabling polling mode for file watching`),!0}}function Pn(o,e={},t){let n=O.getInstance(),r=n.getRepoRoot(),{watch:s,hmr:a,host:i,...l}=e||{},c=a||{},u=i===!0?"localhost":i||"localhost",p={...c.port&&{port:c.port},...c.clientPort&&{clientPort:c.clientPort},host:c.host??u,...c.protocol&&{protocol:c.protocol},overlay:c.overlay??!0,timeout:c.timeout??5e3},d=i!==void 0?i:!0,f=l.https===!0;return{port:o,host:d,open:e.open!==void 0?e.open:!0,https:f,fs:{allow:[r,n.resolveRepoPath("packages"),n.resolveRepoPath("node_modules")],strict:!1},watch:(()=>{let g=Ss(e?.watch?.usePolling,t);return{usePolling:g,interval:e?.watch?.interval??2e3,...g&&{awaitWriteFinish:{stabilityThreshold:300,pollInterval:100}},...e?.watch||{}}})(),hmr:{...p,...c},headers:{"Cross-Origin-Opener-Policy":"same-origin-allow-popups","Cross-Origin-Embedder-Policy":"unsafe-none"},middlewareMode:!1,...l}}function Rn(o={}){let e=o.https===!0;return{...o,https:e}}q();var Cn={debug:!1,verbose:process.env.CI!=="true",seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1,aiCrawlers:"recommended",llmsTxt:!0,speculationRules:!0,hreflang:!0,breadcrumbSchema:!0,websiteSchema:!0,organizationSchema:!0},serverShim:{enabled:!0},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},features:{}};var de={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function Ne(o,e,t,n={}){let{protectedKeys:r=[],onConflict:s}=n;if(e==null)return o;switch(t){case de.CONCATENATE_DEDUPE:{if(!Array.isArray(o)||!Array.isArray(e))return e;let a=[...o,...e];return[...new Set(a)]}case de.SHALLOW_MERGE:return typeof o!="object"||typeof e!="object"||o===null||e===null||Array.isArray(o)||Array.isArray(e)?e:{...o,...e};case de.DEEP_MERGE:{if(typeof o!="object"||typeof e!="object"||o===null||e===null||Array.isArray(o)||Array.isArray(e))return e;let a={...o};for(let i in e){if(r.includes(i)){s&&s(i,o[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]=Ne(a[i],e[i],de.DEEP_MERGE,{protectedKeys:r,onConflict:s}):a[i]=e[i]}return a}case de.REPLACE:default:return e}}function _n(o,e,t=[],n){let r=[...o,...e||[]],s=[...new Set(r)];return[...new Set([...s,...t])]}var je={...Cn,reactCompiler:!1,base:"/",mode:process.env.NODE_ENV==="production"?"production":"development",logLevel:process.env.NODE_ENV==="production"?"warn":"info",server:{port:3e3,strictPort:!0,host:!0,open:!0,cors:!0,https:!1,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:!1},preview:{port:4173,strictPort:!0,host:!0,open:!1,cors:!0,https:!1},routes:{hmr:!0},themes:{},i18n:{},assets:{},pwa:{enabled:!1},prerender:{routes:"auto"},chunking:{reactCore:[]},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:[...Pe.mandatoryIncludes],exclude:[...Pe.buildTools,...Object.values(V)],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 An(o={},e={}){let{onConflict:t}=e,n={...je},r=[],s=(a,i,l,c)=>{r.push({key:a,frameworkValue:i,userValue:l,reason:c}),t&&t(a,i,l,c)};if("prerender"in o){let a=o.prerender;a===!1?o.prerender={routes:[]}:a===!0?o.prerender={routes:"auto"}:Array.isArray(a)&&(o.prerender={routes:a})}return Object.keys(o).forEach(a=>{let i=o[a],l=n[a];if(a==="optimizeDeps"&&typeof i=="object"&&i!==null){let c=l?.include||[],u=l?.exclude||[],p=i.include||[],d=i.exclude||[],f=c.filter(C=>!C.startsWith("@donotdev/")),g=d.filter(C=>f.includes(C));if(g.length>0)for(let C of g)s("optimizeDeps.exclude",C,"excluded",`Framework requires ${C} to be included. It will be included despite your exclusion.`);let v=_n(c,p,f),h=Ne(u,d,de.CONCATENATE_DEDUPE),y=Ne(l?.esbuildOptions||{},i.esbuildOptions||{},de.DEEP_MERGE,{protectedKeys:["external"],onConflict:C=>s(`optimizeDeps.esbuildOptions.${C}`,l?.esbuildOptions?.[C],i.esbuildOptions?.[C],`Framework requires ${C} to remain as configured.`)});n[a]={...l,include:v,exclude:h,esbuildOptions:y,...Object.fromEntries(Object.entries(i).filter(([C])=>!["include","exclude","esbuildOptions"].includes(C)))};return}if(a==="css"&&typeof i=="object"&&i!==null){n[a]=Ne(l||{},i,de.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>s("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){n[a]=Ne(l||{},i,de.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:c=>s(`define.${c}`,l?.[c],i[c],`Framework requires ${c} to remain as configured.`)});return}if(Array.isArray(i)){Array.isArray(l)?n[a]=Ne(l,i,de.CONCATENATE_DEDUPE):n[a]=i;return}if(typeof i=="object"&&i!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){n[a]=Ne(l,i,de.SHALLOW_MERGE);return}n[a]=i}),n}function Nn(o){let{server:e={},preview:t={},mode:n,build:r={},resolve:s={},routes:a={},themes:i={},i18n:l={},assets:c={},features:u={},seo:p={},prerender:d={},pwa:f={},serverShim:g={},chunking:v={},discovery:h={},pluginFactory:y={},debug:C,verbose:$,base:S,define:x={},optimizeDeps:N={},plugins:D=[],css:P={},envDir:k,reactCompiler:_=!1,...m}=o,A=n==="development",B=C||A,w=n==="production"&&(r.analyze??je.build.analyze);return{mode:n,debug:C,verbose:$,isDev:A,isDebug:B,shouldAnalyze:w,serverOptions:e,previewOptions:t,buildOverrides:r,resolveOptions:s,routeOptions:a,themeOptions:i,i18nOptions:l,assetOptions:c,featureOptions:u,seoOptions:p,prerenderOptions:d,pwaOptions:f,serverShimOptions:g,chunkingOptions:v,discoveryOptions:h,pluginFactoryOptions:y,base:S,defineOptions:x,optimizeDepsOptions:N,pluginsOptions:D,cssOptions:P,envDir:k,reactCompiler:_,restOptions:m}}Y();import xs from"autoprefixer";import $s from"postcss-import";import Ps from"postcss-nesting";function kn({postcssImport:o,postcssNesting:e,autoprefixer:t,resolve:n}){return{plugins:[n?o({resolve:n}):o,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function Dn(o={}){if(o.postcss)return o.postcss;let e=O.getInstance();return kn({postcssImport:$s,postcssNesting:Ps,autoprefixer:xs,resolve:(n,r)=>{let s=e.resolvePackage(n,r);if(s)return s;if(n.startsWith("@donotdev/")){let a=n.split("/")[0]+"/"+n.split("/")[1],i=n.split("/").slice(2).join("/"),l=e.resolveFrameworkPackage(a,r);if(l&&i){let c=e.resolvePath(i,l);if(e.pathExists(c))return c}}return e.resolvePath(n,r)}})}import Xi from"@vitejs/plugin-basic-ssl";import Qi from"@vitejs/plugin-react";import el from"vite-tsconfig-paths";var ae=class{static generateVirtualModule(e,t,n=!1,r=void 0,s=void 0){return t.isEmpty(e)?t.generateEmpty(e,n,r,s):t.generateModule(e,n,s)}static generateInspection(e,t,n,r){return t.generateInspection.length>=3?t.generateInspection(e,n,r):t.generateInspection(e,n)}static wrapVirtualModule(e,t){return`// Virtual module: ${e}
11
11
  // Generated by @donotdev/config discovery
12
12
  // Version: 1.0.0
13
13
 
14
- ${t}`}static generateGlobals(e,t,r=""){let o=typeof t=="string"?t:JSON.stringify(t,null,2);return`
14
+ ${t}`}static generateGlobals(e,t,n=""){let r=typeof t=="string"?t:JSON.stringify(t,null,2);return`
15
15
  if (typeof window !== 'undefined') {
16
- window.${e} = ${o};
17
- ${r?`console.log('${r}');`:""}
18
- }`}static generateInspectionHeader(e,t="",r=""){return`// Auto-generated ${e} inspection file
16
+ window.${e} = ${r};
17
+ ${n?`console.log('${n}');`:""}
18
+ }`}static generateInspectionHeader(e,t="",n=""){return`// Auto-generated ${e} inspection file
19
19
  // Generated by @donotdev/config ${e} discovery at ${new Date().toISOString()}
20
20
  // Version: 1.0.0${t?`
21
- // Source: ${t}`:""}${r?`
22
- // Runtime usage: ${r}`:""}
21
+ // Source: ${t}`:""}${n?`
22
+ // Runtime usage: ${n}`:""}
23
23
 
24
- `}static generateExports(e){return Object.entries(e).map(([t,r])=>typeof r=="function"?`export ${r.toString().replace("function ",`function ${t} `)};`:`export const ${t} = ${JSON.stringify(r,null,2)};`).join(`
24
+ `}static generateExports(e){return Object.entries(e).map(([t,n])=>typeof n=="function"?`export ${n.toString().replace("function ",`function ${t} `)};`:`export const ${t} = ${JSON.stringify(n,null,2)};`).join(`
25
25
 
26
- `)}static generateDefaultExport(e){return`export default ${JSON.stringify(e,null,2)};`}static generateManifest(e,t){let r={generatedAt:new Date().toISOString(),version:"1.0.0",timestamp:Date.now()};return t&&typeof t=="function"?{...r,...t(e)}:r}static generateCSSModule(e){if(e.size===0)return`// No utilities generated
26
+ `)}static generateDefaultExport(e){return`export default ${JSON.stringify(e,null,2)};`}static generateManifest(e,t){let n={generatedAt:new Date().toISOString(),version:"1.0.0",timestamp:Date.now()};return t&&typeof t=="function"?{...n,...t(e)}:n}static generateCSSModule(e){if(e.size===0)return`// No utilities generated
27
27
  export const utilities = {};
28
28
  export default utilities;`;let t=Object.fromEntries(e);return`// Auto-generated utility classes from discovered CSS variables
29
29
  // Generated by @donotdev/config at ${new Date().toISOString()}
@@ -38,21 +38,21 @@ var _o=Object.defineProperty;var xt=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&
38
38
  generatedAt: '${new Date().toISOString()}'
39
39
  };
40
40
 
41
- export default utilities;`}static generateHelperFunctions(e,t){let r=Object.entries(t).map(([o,s])=>typeof s=="function"?s.toString().replace("function ",`function ${o} `):`function ${o}() { ${s} }`).join(`
41
+ export default utilities;`}static generateHelperFunctions(e,t){let n=Object.entries(t).map(([r,s])=>typeof s=="function"?s.toString().replace("function ",`function ${r} `):`function ${r}() { ${s} }`).join(`
42
42
 
43
43
  `);return`// Helper functions for ${e}
44
44
  // Generated by @donotdev/config
45
45
 
46
- ${r}`}static validateTemplates(e){return["isEmpty","generateModule","generateEmpty","generateInspection"].every(r=>e[r]&&typeof e[r]=="function")}static createTemplateConfig(e,t){let{isEmpty:r=()=>!1,generateModule:o=()=>"",generateEmpty:s=()=>"",generateInspection:i=()=>"",generateManifest:a=()=>({}),logConfig:l=()=>{},logStats:c=()=>{},logManifest:u=()=>{}}=t;return{isEmpty:r,generateModule:o,generateEmpty:s,generateInspection:i,generateManifest:a,logConfig:l,logStats:c,logManifest:u,pluginName:e,version:"1.0.0",createdAt:new Date().toISOString()}}static getEmptyResultWithError(e,t){let r=t?.message||t||"Unknown error";if(e&&typeof e._getEmptyResult=="function")try{let o=e._getEmptyResult();return o.errors&&Array.isArray(o.errors)?o.errors.push(r):o.errors===void 0&&(o.errors=[r]),o.source==="empty"&&(o.source="error"),o}catch{return{errors:[r],source:"error"}}return{errors:[r],source:"error"}}};import{existsSync as Zo,readdirSync as Xo}from"node:fs";import{join as Qo}from"node:path";var Ko=/^---\r?\n([\s\S]*?)\r?\n---/,Yo=/^\r?\n/;function wr(n){let e=n.match(Ko);if(!e)return{meta:{},content:n};let t={};for(let r of(e[1]??"").split(`
47
- `)){let o=r.indexOf(":");if(o===-1)continue;let s=r.slice(0,o).trim();if(!s)continue;let i=r.slice(o+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t[s]=i}return{meta:t,content:n.slice(e[0].length).replace(Yo,"")}}q();function Er(n){return n.filter(e=>e.endsWith("_en.md")).sort()}function xr(n){let e=Qo(n,"src","content","blog");try{return Zo(e)?Er(Xo(e)).length>0:!1}catch{return!1}}function it(n,e){let t=D.getInstance(),r=t.resolvePath("src/content/blog",n);try{if(!t.pathExists(r))return[];let o=Er(t.readdirSync(r));if(o.length===0)return[];let s=[];for(let i of o){let a=t.resolvePath(i,r),l=t.readSync(a,{format:"text"}),c=i.replace(/_en\.md$/,""),{meta:u}=wr(l),p=u.date;if(!p)try{p=t.statSync(a).mtime.toISOString().split("T")[0],e.warn(`Blog post "${c}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],e.warn(`Blog post "${c}" has no date and file stat failed, using today`)}s.push({slug:c,title:u.title||c,description:u.description||"",date:p,tags:u.tags?u.tags.split(",").map(d=>d.trim()):[],image:u.image||null})}return s.sort((i,a)=>a.date.localeCompare(i.date)),e.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(o){return e.debug(`Blog content discovery skipped: ${o.message}`),[]}}function H(n,e,t="configuration-error",r={}){let o=`[${n}] ${e}`,s=new Error(o);return s.code=t,s.pluginName=n,s.context=r,s}function ve(n){return n instanceof Error&&typeof n.pluginName=="string"}q();function Sr(n,e,t={}){let{blogPath:r="/blog"}=t;return!n.some(s=>{let i=s.path||s;return typeof i=="string"&&i.startsWith(r+"/")&&i.includes(":")})||e.length===0?[]:[{path:r,auth:!1,meta:{namespace:"blog"}},...e.map(s=>({path:`${r}/${s.slug}`,auth:!1,meta:{namespace:"blog",seo:{title:s.title,description:s.description||null,image:s.image,type:"article"}}}))]}function Rr(){let n=null,e,t=new Promise(r=>{e=r});return{set({routes:r,source:o,blogPosts:s}){if(!Array.isArray(s))throw new Error("[dndev] Route manifest: set() needs the build's blogPosts (readBlogPosts).");n={routes:r,errors:[],source:o,blogPosts:s}},useEntityResolver(r){e(r)},entityResolver:()=>t,get(){if(!n)throw new Error("[dndev] Route manifest unavailable: route discovery did not run or failed (see the error above).");return n}}}function Pr(n){return n.filter(e=>{let t=e.path||e;return!(e.auth&&e.auth.required||typeof t=="string"&&t.includes(":"))}).map(e=>e.path||e)}function ye(n){let{pluginName:e,icon:t,virtualModuleId:r,DiscoveryClass:o,discoveryMethod:s,filePatterns:i,templates:a,manifestFileName:l,createDiscovery:c,discoveryOptions:u={},configKey:p}=n;return function(f={}){let{debug:g,verbose:w,virtualModuleId:m=r,hmrDebounceMs:h,hmrCacheTimeout:P,hmrSmartDetection:R,disableHmr:E,routeManifest:S,discoveryStore:C,...k}=f;if(!ne.validateTemplates(a))throw new Error(`Invalid templates for plugin ${e}`);let y={...Fe.discovery,...u,debug:g,verbose:w,...k},T=p||(()=>{let x=e.match(/dndev-vite-(\w+)-discovery/);return x?x[1]:null})(),$=M(e,g,w,{fileLogging:y.fileLogging,logDir:y.logDir}),v=D.getInstance(),G=()=>{let x=v.getAppRoot(),N=v.getRepoRoot();return x&&x!==N},A=Date.now(),L=c?c(v,y):new o(v,y),j="\0"+m,z="",K=!1,X=null,W=0,se=!1,_=null,O=!1,F=null,B=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(L.clearCache(),_=null,$.info("Discovery cache cleared manually"),"Cache cleared"));function V(x){let Z=ne.generateVirtualModule(x,a,g,y,T).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!E&&K&&(Z+=`
46
+ ${n}`}static validateTemplates(e){return["isEmpty","generateModule","generateEmpty","generateInspection"].every(n=>e[n]&&typeof e[n]=="function")}static createTemplateConfig(e,t){let{isEmpty:n=()=>!1,generateModule:r=()=>"",generateEmpty:s=()=>"",generateInspection:a=()=>"",generateManifest:i=()=>({}),logConfig:l=()=>{},logStats:c=()=>{},logManifest:u=()=>{}}=t;return{isEmpty:n,generateModule:r,generateEmpty:s,generateInspection:a,generateManifest:i,logConfig:l,logStats:c,logManifest:u,pluginName:e,version:"1.0.0",createdAt:new Date().toISOString()}}static getEmptyResultWithError(e,t){let n=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(n):r.errors===void 0&&(r.errors=[n]),r.source==="empty"&&(r.source="error"),r}catch{return{errors:[n],source:"error"}}return{errors:[n],source:"error"}}};import{existsSync as _s,readdirSync as As}from"node:fs";import{join as Ns}from"node:path";var Rs=/^---\r?\n([\s\S]*?)\r?\n---/,Cs=/^\r?\n/;function Tn(o){let e=o.match(Rs);if(!e)return{meta:{},content:o};let t={};for(let n of(e[1]??"").split(`
47
+ `)){let r=n.indexOf(":");if(r===-1)continue;let s=n.slice(0,r).trim();if(!s)continue;let a=n.slice(r+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return{meta:t,content:o.slice(e[0].length).replace(Cs,"")}}Y();function On(o){return o.filter(e=>e.endsWith("_en.md")).sort()}function In(o){let e=Ns(o,"src","content","blog");try{return _s(e)?On(As(e)).length>0:!1}catch{return!1}}function it(o,e){let t=O.getInstance(),n=t.resolvePath("src/content/blog",o);try{if(!t.pathExists(n))return[];let r=On(t.readdirSync(n));if(r.length===0)return[];let s=[];for(let a of r){let i=t.resolvePath(a,n),l=t.readSync(i,{format:"text"}),c=a.replace(/_en\.md$/,""),{meta:u}=Tn(l),p=u.date;if(!p)try{p=t.statSync(i).mtime.toISOString().split("T")[0],e.warn(`Blog post "${c}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],e.warn(`Blog post "${c}" has no date and file stat failed, using today`)}s.push({slug:c,title:u.title||c,description:u.description||"",date:p,tags:u.tags?u.tags.split(",").map(d=>d.trim()):[],image:u.image||null})}return s.sort((a,i)=>i.date.localeCompare(a.date)),e.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(r){return e.debug(`Blog content discovery skipped: ${r.message}`),[]}}function H(o,e,t="configuration-error",n={}){let r=`[${o}] ${e}`,s=new Error(r);return s.code=t,s.pluginName=o,s.context=n,s}function be(o){return o instanceof Error&&typeof o.pluginName=="string"}Y();function Fn(o,e,t={}){let{blogPath:n="/blog"}=t;return!o.some(s=>{let a=s.path||s;return typeof a=="string"&&a.startsWith(n+"/")&&a.includes(":")})||e.length===0?[]:[{path:n,auth:!1,meta:{namespace:"blog"}},...e.map(s=>({path:`${n}/${s.slug}`,auth:!1,meta:{namespace:"blog",seo:{title:s.title,description:s.description||null,image:s.image,type:"article"}}}))]}function Mn(){let o=null,e,t=new Promise(n=>{e=n});return{set({routes:n,source:r,blogPosts:s}){if(!Array.isArray(s))throw new Error("[dndev] Route manifest: set() needs the build's blogPosts (readBlogPosts).");o={routes:n,errors:[],source:r,blogPosts:s}},useEntityResolver(n){e(n)},entityResolver:()=>t,get(){if(!o)throw new Error("[dndev] Route manifest unavailable: route discovery did not run or failed (see the error above).");return o}}}function Ln(o){return o.filter(e=>{let t=e.path||e;return!(e.auth&&e.auth.required||typeof t=="string"&&t.includes(":"))}).map(e=>e.path||e)}function we(o){let{pluginName:e,icon:t,virtualModuleId:n,DiscoveryClass:r,discoveryMethod:s,filePatterns:a,templates:i,manifestFileName:l,createDiscovery:c,discoveryOptions:u={},configKey:p}=o;return function(f={}){let{debug:g,verbose:v,virtualModuleId:h=n,hmrDebounceMs:y,hmrCacheTimeout:C,hmrSmartDetection:$,disableHmr:S,routeManifest:x,discoveryStore:N,...D}=f;if(!ae.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let P={...je.discovery,...u,debug:g,verbose:v,...D},k=p||(()=>{let E=e.match(/dndev-vite-(\w+)-discovery/);return E?E[1]:null})(),_=G(e,g,v,{fileLogging:P.fileLogging,logDir:P.logDir}),m=O.getInstance(),A=()=>{let E=m.getAppRoot(),T=m.getRepoRoot();return E&&E!==T},B=Date.now(),w=c?c(m,P):new r(m,P),M="\0"+h,L="",z=!1,K=null,U=0,Z=!1,R=null,I=!1,F=null,W=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(w.clearCache(),R=null,_.info("Discovery cache cleared manually"),"Cache cleared"));function Q(E){let J=ae.generateVirtualModule(E,i,g,P,k).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!S&&z&&(J+=`
48
48
 
49
49
  // HMR boundary for ${e}
50
50
  if (import.meta.hot) {
51
51
  import.meta.hot.accept();
52
52
  }
53
- `),Z}function de(x){let N=x.replace(/\\/g,"/");if(E||N.includes("/node_modules/")||N.includes("/.git/")||N.includes("/dist/")||N.includes("/build/")||N.includes("/coverage/")||N.includes("/.vite/")||N.includes("/.turbo/")||N.endsWith(".d.ts")||N.endsWith(".tsbuildinfo")||N.endsWith(".map")||N.endsWith(".css.map")||N.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(N))return!1;let Z=v.getRelativePath(N);if(Z.startsWith("packages/"))return!1;let ge=Z.startsWith("src/")&&/\.(ts|tsx)$/.test(Z);return ge?Array.isArray(i)&&i.length>0?i.some(Q=>typeof Q=="function"?Q(N):typeof Q=="string"?Q.startsWith("**/")?N.endsWith(Q.slice(3)):N.endsWith(Q):!1):ge:!1}function Ce(x){if(E)return $.debug("Virtual modules are static - HMR disabled"),[];let N=Date.now();return O?($.debug("HMR already in progress, skipping update"),[]):N-W<h?(se||(se=!0,X=setTimeout(()=>{se=!1,W=Date.now(),ke(x)},h)),[]):(W=N,ke(x))}function ke(x){let N=Date.now();if(F===x.file&&N-W<100)return $.debug(`Same file processed too recently: ${x.file}`),[];if(!de(x.file))return $.debug(`Skipping irrelevant file change: ${x.file}`),[];$.debug(`Relevant file changed: ${x.file}`),O=!0,F=x.file;try{let Z=Date.now()-(_?.timestamp||0);if(Z<P&&_){$.debug(`Using cached discovery data (age: ${Z}ms)`);let Q=x.server.moduleGraph.getModuleById(j);return Q&&x.server.reloadModule(Q),[]}L.clearCache();let ge=x.server.moduleGraph.getModuleById(j);return ge&&x.server.reloadModule(ge),[]}finally{O=!1,setTimeout(()=>{F===x.file&&(F=null)},200)}}return{name:e,enforce:"pre",configResolved(x){z=x.root,K=x.command==="serve",g&&$.debug(`${t} ${e} initialized`),K&&$.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),a.logConfig&&a.logConfig(y)},config(x){return x.optimizeDeps||(x.optimizeDeps={}),x.optimizeDeps.exclude||(x.optimizeDeps.exclude=[]),x.optimizeDeps.exclude.includes(m)||x.optimizeDeps.exclude.push(m),x},resolveId(x){return x===m?($.debug(`Resolving virtual module: ${x}`),{id:j,moduleSideEffects:!0}):null},async load(x){if(x!==j)return null;if($.debug(`Loading virtual module: ${x}`),!G()){$.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let N=0;for(;!G()&&N<100;)await new Promise(Z=>setTimeout(Z,10)),N++;if(!G())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let N;return _?($.debug("Using cached discovery data for virtual module"),N=_):($.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.`),N=await L[s](),_=N,$.debug("Discovery completed for virtual module")),V(N)}catch(N){if(ve(N))throw N;return $.error(`${e} virtual module (${j}) failed to load: ${N.message}`),$.error(`Stack: ${N.stack||"No stack trace available"}`),a.generateEmpty({},g,y,T)}},async buildStart(){if(B=!1,!G()){$.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let x=0;for(;!G()&&x<100;)await new Promise(N=>setTimeout(N,10)),x++;if(!G())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let x=await L[s](!_);if(_=x,p==="routes"&&x?.routes){let N=it(v.getAppRoot(),$),Z=Sr(x.routes,N),ge=[...x.routes.map(Q=>({path:Q.path,auth:Q.auth,meta:Q.meta})),...Z];S?.set({routes:ge,source:x.source||"auto-discovery",blogPosts:N})}a.logStats&&a.logStats(x,t,$)}catch(x){if(ve(x))throw x;$.error(`${e} discovery failed during file scanning: ${x.message}`),$.error(`Stack: ${x.stack||"No stack trace available"}`),_=ne.getEmptyResultWithError(L,x)}finally{B=!0}C?.set(_),p==="routes"&&S?.useEntityResolver(L.getEntityResolver())},configureServer(){B=!0},handleHotUpdate(x){return E?[]:B?Ce(x):($.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!_){$.warn("No cached discovery data for manifest generation - skipping");return}try{let x=ne.generateManifest(_,a.generateManifest);this.emitFile({type:"asset",fileName:l,source:JSON.stringify(x,null,2)}),w&&a.logManifest&&a.logManifest(_,e)}catch(x){$.error(`${e} manifest generation failed: ${x.message}`),$.error(`Stack: ${x.stack||"No stack trace available"}`)}},transform(x,N){return N===j?{code:x,map:null}:null}}}}var ml={generateGlobals:ne.generateGlobals,generateExports:ne.generateExports,generateDefaultExport:ne.generateDefaultExport,wrapVirtualModule:ne.wrapVirtualModule,generateInspectionHeader:ne.generateInspectionHeader,validateTemplates:ne.validateTemplates,createTemplateConfig:ne.createTemplateConfig};J();var pe=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=M(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 r=await this._getPatterns();this.options.verbose&&r&&(typeof r=="object"&&r.pattern?this.logger.verbose(`Pattern: ${r.pattern}`):typeof r=="string"&&this.logger.verbose(`Pattern: ${r}`),r.dirs&&this.logger.verbose(`Search directories: ${r.dirs.slice(0,3).join(", ")}${r.dirs.length>3?` (${r.dirs.length} total)`:""}`));let o=await this._prepareFiles(),s=await this._scanFiles(r),i=await this._processFiles(s,o);this.cache={...i,timestamp:Date.now()};let a=Date.now()-t;return this.logger.debug(`Discovery completed in ${a}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(r){if(ve(r))throw r;return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${r.message}`),this.logger.error(`Stack: ${r.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 _prepareFiles(){return{}}async _processFiles(e,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(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),r=t[t.length-1],o=r.split(".")[0],s=r.split(".").pop();return{fileName:r,baseName:o,extension:s,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let r=this.pathResolver.getFileInfo(e);return r?await t(r):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(r){if(ve(r))throw r;return this.logger.debug(`Error processing file ${e}: ${r.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(o=>this._processSingleFile(o,t)))).filter(o=>o!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};J();var wl={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},$r=[{id:"en",name:"English",nativeName:"English",flagCode:"gb"},{id:"us",name:"English (US)",nativeName:"English (US)",countryCode:"US",dialCode:"+1"},{id:"gb",name:"English (UK)",nativeName:"English (UK)",countryCode:"GB",dialCode:"+44"},{id:"en-ca",name:"English (Canada)",nativeName:"English (Canada)",flagCode:"ca",countryCode:"CA",dialCode:"+1"},{id:"au",name:"English (Australia)",nativeName:"English (Australia)",countryCode:"AU",dialCode:"+61"},{id:"ie",name:"English (Ireland)",nativeName:"English (Ireland)",countryCode:"IE",dialCode:"+353"},{id:"es",name:"Spanish",nativeName:"Espa\xF1ol",countryCode:"ES",dialCode:"+34"},{id:"mx",name:"Spanish (Mexico)",nativeName:"Espa\xF1ol (M\xE9xico)",countryCode:"MX",dialCode:"+52"},{id:"es-ar",name:"Spanish (Argentina)",nativeName:"Espa\xF1ol (Argentina)",flagCode:"ar",countryCode:"AR",dialCode:"+54"},{id:"fr",name:"French",nativeName:"Fran\xE7ais",flagCode:"fr",countryCode:"FR",dialCode:"+33"},{id:"fr-be",name:"French (Belgium)",nativeName:"Fran\xE7ais (Belgique)",flagCode:"be",countryCode:"BE",dialCode:"+32"},{id:"ch",name:"French (Switzerland)",nativeName:"Fran\xE7ais (Suisse)",countryCode:"CH",dialCode:"+41"},{id:"de",name:"German",nativeName:"Deutsch",countryCode:"DE",dialCode:"+49"},{id:"at",name:"German (Austria)",nativeName:"Deutsch (\xD6sterreich)",countryCode:"AT",dialCode:"+43"},{id:"it",name:"Italian",nativeName:"Italiano",countryCode:"IT",dialCode:"+39"},{id:"pt",name:"Portuguese",nativeName:"Portugu\xEAs",countryCode:"PT",dialCode:"+351"},{id:"br",name:"Portuguese (Brazil)",nativeName:"Portugu\xEAs (Brasil)",flagCode:"br",countryCode:"BR",dialCode:"+55"},{id:"ru",name:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",countryCode:"RU",dialCode:"+7"},{id:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",countryCode:"JP",dialCode:"+81"},{id:"ko",name:"Korean",nativeName:"\uD55C\uAD6D\uC5B4",countryCode:"KR",dialCode:"+82"},{id:"zh",name:"Chinese",nativeName:"\u4E2D\u6587",countryCode:"CN",dialCode:"+86"},{id:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flagCode:"sa",countryCode:"SA",dialCode:"+966"},{id:"ar-ma",name:"Arabic (Morocco)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0645\u063A\u0631\u0628)",flagCode:"ma",countryCode:"MA",dialCode:"+212"},{id:"ar-dz",name:"Arabic (Algeria)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u062C\u0632\u0627\u0626\u0631)",flagCode:"dz",countryCode:"DZ",dialCode:"+213"},{id:"ar-tn",name:"Arabic (Tunisia)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u062A\u0648\u0646\u0633)",flagCode:"tn",countryCode:"TN",dialCode:"+216"},{id:"ar-ly",name:"Arabic (Libya)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0644\u064A\u0628\u064A\u0627)",flagCode:"ly",countryCode:"LY",dialCode:"+218"},{id:"ar-mr",name:"Arabic (Mauritania)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627)",flagCode:"mr",countryCode:"MR",dialCode:"+222"},{id:"hi",name:"Hindi",nativeName:"\u0939\u093F\u0928\u094D\u0926\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"nl",name:"Dutch",nativeName:"Nederlands",countryCode:"NL",dialCode:"+31"},{id:"sv",name:"Swedish",nativeName:"Svenska",countryCode:"SE",dialCode:"+46"},{id:"da",name:"Danish",nativeName:"Dansk",countryCode:"DK",dialCode:"+45"},{id:"no",name:"Norwegian",nativeName:"Norsk",countryCode:"NO",dialCode:"+47"},{id:"fi",name:"Finnish",nativeName:"Suomi",countryCode:"FI",dialCode:"+358"},{id:"pl",name:"Polish",nativeName:"Polski",countryCode:"PL",dialCode:"+48"},{id:"tr",name:"Turkish",nativeName:"T\xFCrk\xE7e",countryCode:"TR",dialCode:"+90"},{id:"th",name:"Thai",nativeName:"\u0E44\u0E17\u0E22",countryCode:"TH",dialCode:"+66"},{id:"vi",name:"Vietnamese",nativeName:"Ti\u1EBFng Vi\u1EC7t",countryCode:"VN",dialCode:"+84"},{id:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",countryCode:"ID",dialCode:"+62"},{id:"ms",name:"Malay",nativeName:"Bahasa Melayu",flagCode:"my",countryCode:"MY",dialCode:"+60"},{id:"tl",name:"Filipino",nativeName:"Tagalog",countryCode:"PH",dialCode:"+63"},{id:"bg",name:"Bulgarian",nativeName:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",countryCode:"BG",dialCode:"+359"},{id:"cs",name:"Czech",nativeName:"\u010Ce\u0161tina",countryCode:"CZ",dialCode:"+420"},{id:"el",name:"Greek",nativeName:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",countryCode:"GR",dialCode:"+30"},{id:"he",name:"Hebrew",nativeName:"\u05E2\u05D1\u05E8\u05D9\u05EA",countryCode:"IL",dialCode:"+972"},{id:"hu",name:"Hungarian",nativeName:"Magyar",countryCode:"HU",dialCode:"+36"},{id:"is",name:"Icelandic",nativeName:"\xCDslenska",countryCode:"IS",dialCode:"+354"},{id:"lt",name:"Lithuanian",nativeName:"Lietuvi\u0173",countryCode:"LT",dialCode:"+370"},{id:"lv",name:"Latvian",nativeName:"Latvie\u0161u",countryCode:"LV",dialCode:"+371"},{id:"mt",name:"Maltese",nativeName:"Malti",countryCode:"MT",dialCode:"+356"},{id:"ro",name:"Romanian",nativeName:"Rom\xE2n\u0103",countryCode:"RO",dialCode:"+40"},{id:"sk",name:"Slovak",nativeName:"Sloven\u010Dina",countryCode:"SK",dialCode:"+421"},{id:"sl",name:"Slovenian",nativeName:"Sloven\u0161\u010Dina",flagCode:"si",countryCode:"SI",dialCode:"+386"},{id:"uk",name:"Ukrainian",nativeName:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flagCode:"ua",countryCode:"UA",dialCode:"+380"},{id:"et",name:"Estonian",nativeName:"Eesti",countryCode:"EE",dialCode:"+372"},{id:"ca",name:"Catalan",nativeName:"Catal\xE0",countryCode:"ES",dialCode:"+34"},{id:"eu",name:"Basque",nativeName:"Euskara",countryCode:"ES",dialCode:"+34"},{id:"gl",name:"Galician",nativeName:"Galego",countryCode:"ES",dialCode:"+34"},{id:"cy",name:"Welsh",nativeName:"Cymraeg",countryCode:"GB",dialCode:"+44"},{id:"ga",name:"Irish",nativeName:"Gaeilge",flagCode:"ie",countryCode:"IE",dialCode:"+353"},{id:"gd",name:"Scottish Gaelic",nativeName:"G\xE0idhlig",flagCode:"gb-sct",countryCode:"GB",dialCode:"+44"},{id:"br-fr",name:"Breton",nativeName:"Brezhoneg",flagCode:"bzh",countryCode:"FR",dialCode:"+33"},{id:"co",name:"Corsican",nativeName:"Corsu",flagCode:"fr-cor",countryCode:"FR",dialCode:"+33"},{id:"oc",name:"Occitan",nativeName:"Occitan",countryCode:"FR",dialCode:"+33"},{id:"rm",name:"Romansh",nativeName:"Rumantsch",countryCode:"CH",dialCode:"+41"},{id:"lb",name:"Luxembourgish",nativeName:"L\xEBtzebuergesch",countryCode:"LU",dialCode:"+352"},{id:"af",name:"Afrikaans",nativeName:"Afrikaans",countryCode:"ZA",dialCode:"+27"},{id:"sw",name:"Swahili",nativeName:"Kiswahili",countryCode:"KE",dialCode:"+254"},{id:"am",name:"Amharic",nativeName:"\u12A0\u121B\u122D\u129B",flagCode:"et",countryCode:"ET",dialCode:"+251"},{id:"bn",name:"Bengali",nativeName:"\u09AC\u09BE\u0982\u09B2\u09BE",flagCode:"bd",countryCode:"BD",dialCode:"+880"},{id:"gu",name:"Gujarati",nativeName:"\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"kn",name:"Kannada",nativeName:"\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ml",name:"Malayalam",nativeName:"\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"mr",name:"Marathi",nativeName:"\u092E\u0930\u093E\u0920\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ne",name:"Nepali",nativeName:"\u0928\u0947\u092A\u093E\u0932\u0940",flagCode:"np",countryCode:"NP",dialCode:"+977"},{id:"pa",name:"Punjabi",nativeName:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"si",name:"Sinhala",nativeName:"\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",countryCode:"LK",dialCode:"+94"},{id:"ta",name:"Tamil",nativeName:"\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"te",name:"Telugu",nativeName:"\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ur",name:"Urdu",nativeName:"\u0627\u0631\u062F\u0648",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"fa",name:"Persian",nativeName:"\u0641\u0627\u0631\u0633\u06CC",flagCode:"ir",countryCode:"IR",dialCode:"+98"},{id:"ps",name:"Pashto",nativeName:"\u067E\u069A\u062A\u0648",countryCode:"AF",dialCode:"+93"},{id:"uz",name:"Uzbek",nativeName:"O\u02BBzbek",countryCode:"UZ",dialCode:"+998"},{id:"kk",name:"Kazakh",nativeName:"\u049A\u0430\u0437\u0430\u049B",flagCode:"kz",countryCode:"KZ",dialCode:"+7"},{id:"ky",name:"Kyrgyz",nativeName:"\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430",flagCode:"kg",countryCode:"KG",dialCode:"+996"},{id:"tg",name:"Tajik",nativeName:"\u0422\u043E\u04B7\u0438\u043A\u04E3",flagCode:"tj",countryCode:"TJ",dialCode:"+992"},{id:"mn",name:"Mongolian",nativeName:"\u041C\u043E\u043D\u0433\u043E\u043B",countryCode:"MN",dialCode:"+976"},{id:"my",name:"Burmese",nativeName:"\u1019\u103C\u1014\u103A\u1019\u102C",flagCode:"mm",countryCode:"MM",dialCode:"+95"},{id:"km",name:"Khmer",nativeName:"\u1781\u17D2\u1798\u17C2\u179A",flagCode:"kh",countryCode:"KH",dialCode:"+855"},{id:"lo",name:"Lao",nativeName:"\u0EA5\u0EB2\u0EA7",flagCode:"la",countryCode:"LA",dialCode:"+856"},{id:"ka",name:"Georgian",nativeName:"\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",flagCode:"ge",countryCode:"GE",dialCode:"+995"},{id:"hy",name:"Armenian",nativeName:"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",flagCode:"am",countryCode:"AM",dialCode:"+374"},{id:"az",name:"Azerbaijani",nativeName:"Az\u0259rbaycan",countryCode:"AZ",dialCode:"+994"},{id:"be",name:"Belarusian",nativeName:"\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",flagCode:"by",countryCode:"BY",dialCode:"+375"},{id:"mk",name:"Macedonian",nativeName:"\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",countryCode:"MK",dialCode:"+389"},{id:"sr",name:"Serbian",nativeName:"\u0421\u0440\u043F\u0441\u043A\u0438",countryCode:"RS",dialCode:"+381"},{id:"bs",name:"Bosnian",nativeName:"Bosanski",flagCode:"ba",countryCode:"BA",dialCode:"+387"},{id:"hr",name:"Croatian",nativeName:"Hrvatski",countryCode:"HR",dialCode:"+385"},{id:"sq",name:"Albanian",nativeName:"Shqip",flagCode:"al",countryCode:"AL",dialCode:"+355"},{id:"md",name:"Moldovan",nativeName:"Moldoveneasc\u0103",countryCode:"MD",dialCode:"+373"}],es={US:"United States",GB:"United Kingdom",CA:"Canada",AU:"Australia",IE:"Ireland",FR:"France",BE:"Belgium",CH:"Switzerland",DE:"Germany",AT:"Austria",IT:"Italy",PT:"Portugal",BR:"Brazil",ES:"Spain",MX:"Mexico",AR:"Argentina",RU:"Russia",JP:"Japan",KR:"South Korea",CN:"China",SE:"Sweden",NO:"Norway",DK:"Denmark",FI:"Finland",NL:"Netherlands",PL:"Poland",CZ:"Czech Republic",HU:"Hungary",RO:"Romania",BG:"Bulgaria",GR:"Greece",TR:"Turkey",IL:"Israel",IN:"India",ZA:"South Africa"};function ts(){return $r.filter(n=>n.countryCode!==void 0&&n.dialCode!==void 0).map(n=>({code:n.countryCode,dialCode:n.dialCode,flagCode:n.flagCode||n.id,name:n.countryName||es[n.countryCode]||n.name}))}var rs=ts(),qe="/flags";function at(n){return`${n.toLowerCase()}.svg`}function Nt(n){return $r.find(t=>t.id===n)?.flagCode||n}function lt(){return[...new Set(rs.map(n=>n.flagCode))]}var Ae={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},ns="public/logo.svg is missing: it is the site logo (Organization / publisher logo in the JSON-LD, the default logo) and the source of the favicon, PWA icons and og-image.png. Add public/logo.svg.",Cr="/manifest.json",Ke=class extends pe{constructor(e,t={}){super(e,{assets:ce.assets.fallback,assetPatterns:ce.assets.patterns,frameworkPackage:Pt.package,assetsPath:Pt.assetsPath,modernFormats:ce.assets.modern,...t}),this.hasRunForSession=!1,this.flagCodes=null,this.entityResolver=null}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _prepareFiles(){let e=this.pathResolver.getAppRoot(),t=await this._ensureDefaultAssets(e);if(this.flagCodes){let a=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(a?[...new Set([...this.flagCodes,...lt()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${qe}/: ${l.join(", ")}`)}let r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn(ns);let s=[],i=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(s=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:s}}async _processFiles(e,{copiedAssets:t,generatedAssets:r}){let o=this.pathResolver.getAppRoot(),{consumerFiles:s}=e,i=await this._processAssetFiles(s),a=this._buildAssetManifest(i,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${Cr}`))}),l=await this._readLogoSvgContent("/logo.svg",o);return{assets:i,manifest:{...a,logoSvgContent:l},copiedAssets:t,generatedAssets:r}}_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`}useFlagCodes(e,t){this.flagCodes=e,this.entityResolver=t}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 r=this.getAssets().map(s=>s.path),o=t||this.options.modernFormats;for(let s of o){let i=`/${e}.${s}`;if(r.includes(i))return i}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let r=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${r}`),!r)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let o=this.pathResolver.resolveAppPath(Je.public);this.pathResolver.pathExists(o)||(this.pathResolver.mkdir(o),this.logger.debug(`Created public directory: ${o}`));for(let s of this.options.assets)await this._ensureAsset(s,o,r)&&t.push(s);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(r){this.logger.debug(`Failed to ensure default assets: ${r.message}`)}return t}async _ensureAsset(e,t,r){let o=this.pathResolver.resolveAppPath(`${Je.public}/${e}`);if(this.pathResolver.pathExists(o))return this.logger.debug(`Asset exists: ${e}`),!1;let s=this.pathResolver.normalizePath(`${r}/${e}`);if(this.pathResolver.pathExists(s)){if(await this.pathResolver.copy(s,o))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}_ensureFlags(e){let t=this.pathResolver.resolveFrameworkPackage("@donotdev/core");if(!t)throw new Error("Flag copy: @donotdev/core not found");let r=this.pathResolver.normalizePath(`${t}/${Te.PUBLISHED_FLAGS}`),o=`${Je.public}${qe}`,s=[];for(let i of e){let a=at(i),l=this.pathResolver.resolveAppPath(`${o}/${a}`);if(this.pathResolver.pathExists(l))continue;let c=`${r}/${a}`;if(!this.pathResolver.pathExists(c)){this.logger.warn(`No flag artwork for "${i}": add ${o}/${a} to the app`);continue}if(!this.pathResolver.copySync(c,l))throw new Error(`Flag copy: cannot copy ${c} to ${l}`);s.push(a)}return s}async _processAssetFiles(e){let t=[];for(let r of e)try{let o=this.pathResolver.getFileInfo(r);if(o&&o.isFile){let s=r.split("/").pop()||r.split("\\").pop(),i=this._analyzeAsset(s,o.size);i&&t.push(i)}}catch(o){this.logger.debug(`Error processing asset file ${r}: ${o.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let r=this._determineAssetType(e),o=this._determineAssetFormat(e);return this.options.assetPatterns.some(i=>this._matchesPattern(e,i))?{path:`/${e}`,name:e,type:r,format:o,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(o)}:(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 r=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(r)?"image":["woff2","woff","ttf","otf"].includes(r)?"font":["json"].includes(r)?"json":["ico"].includes(r)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,r=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,o)).toFixed(2))+" "+r[o]}_matchesPattern(e,t){let r=t.split("*").map(o=>o.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${r}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let r=e.map(s=>s.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:t?Cr:null,modernFormats:e.filter(s=>s.isModern).map(s=>s.path),fallbackFormats:e.filter(s=>!s.isModern).map(s=>s.path)}}_getOptimalAsset(e,t,r){for(let o of r){let s=`/${e}.${o}`;if(t.includes(s))return s}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),r=await this._resolvePackage("@donotdev/ui",t);if(!r)return this.logger.debug("@donotdev/ui package not found"),null;let o=this.pathResolver.normalizePath(`${r}/assets`);return this.pathResolver.pathExists(o)?(this.logger.debug(`Using framework assets from: ${o}`),o):(this.logger.debug(`Assets directory not found: ${o}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let r=this.pathResolver.resolveFrameworkPackage(e,t);return r?(this.logger.debug(`Found package: ${r}`),r):(this.logger.debug(`Package ${e} not found`),null)}catch(r){return this.logger.debug(`Error resolving package ${e}: ${r.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 r=e.slice(1),o=this.pathResolver.resolveAppPath(`${Je.public}/${r}`);return this.pathResolver.pathExists(o)&&await this.pathResolver.read(o,{format:"text"})||null}catch(r){return this.logger.debug(`Failed to read logo SVG content: ${r.message}`),null}}async _renderOgImage(e,t){let{width:r,height:o}=await e(t).metadata(),s=Math.min(Ae.logoWidth/r,Ae.logoHeight/o),i=await e(t,{density:Math.ceil(72*s)}).resize(Ae.logoWidth,Ae.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:Ae.width,height:Ae.height,channels:4,background:Ae.background}}).composite([{input:i}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),r=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 o=[{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"}],s=[{name:"favicon.svg",format:"svg"}],i=[],a=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...s,...o].map(u=>u.name),error:"Failed to read logo.svg"};for(let u of s){let p=`${r}/${u.name}`;if(this.pathResolver.pathExists(p)){a.push(u.name);continue}try{await this.pathResolver.write(p,l),i.push(u.name)}catch(d){this.logger.debug(`Failed to copy ${u.name}: ${d.message}`),a.push(u.name)}}let c=await import("sharp").catch(()=>null);if(!c)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),a.push(...o.map(u=>u.name));else{for(let p of o){let d=`${r}/${p.name}`;if(this.pathResolver.pathExists(d)){a.push(p.name);continue}try{let f=c.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;p.format==="ico"?g=await f.toFormat("png").toBuffer():g=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(d,g),i.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),a.push(p.name)}}let u=He.slice(1);if(this.pathResolver.pathExists(`${r}/${u}`))a.push(u);else try{let p=await this._renderOgImage(c.default,t);await this.pathResolver.write(`${r}/${u}`,p),i.push(u)}catch(p){this.logger.debug(`Failed to generate ${u}: ${p.message}`),a.push(u)}}return{generated:i,skipped:a,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:[...s,...o].map(c=>c.name),error:l.message}}}};q();var os={isEmpty:n=>!n.manifest||n.assets?.length===0,generateModule:(n,e,t="assets")=>{let{manifest:r,assets:o,copiedAssets:s}=n,i=r.logoSvgContent||null,a={totalAssets:o.length,copiedAssets:s.length,hasLogo:r.logo.optimal!==null,hasFavicon:r.favicon.optimal!==null,hasManifest:r.manifest!==null,timestamp:new Date().toISOString()};return`// ${U.assets} - Generated asset manifest
54
- const assetManifest = ${JSON.stringify(r,null,2)};
55
- const assetStats = ${JSON.stringify(a,null,2)};
53
+ `),J}function X(E){let T=E.replace(/\\/g,"/");if(S||T.includes("/node_modules/")||T.includes("/.git/")||T.includes("/dist/")||T.includes("/build/")||T.includes("/coverage/")||T.includes("/.vite/")||T.includes("/.turbo/")||T.endsWith(".d.ts")||T.endsWith(".tsbuildinfo")||T.endsWith(".map")||T.endsWith(".css.map")||T.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(T))return!1;let J=m.getRelativePath(T);if(J.startsWith("packages/"))return!1;let he=J.startsWith("src/")&&/\.(ts|tsx)$/.test(J);return he?Array.isArray(a)&&a.length>0?a.some(ne=>typeof ne=="function"?ne(T):typeof ne=="string"?ne.startsWith("**/")?T.endsWith(ne.slice(3)):T.endsWith(ne):!1):he:!1}function te(E){if(S)return _.debug("Virtual modules are static - HMR disabled"),[];let T=Date.now();return I?(_.debug("HMR already in progress, skipping update"),[]):T-U<y?(Z||(Z=!0,K=setTimeout(()=>{Z=!1,U=Date.now(),xe(E)},y)),[]):(U=T,xe(E))}function xe(E){let T=Date.now();if(F===E.file&&T-U<100)return _.debug(`Same file processed too recently: ${E.file}`),[];if(!X(E.file))return _.debug(`Skipping irrelevant file change: ${E.file}`),[];_.debug(`Relevant file changed: ${E.file}`),I=!0,F=E.file;try{let J=Date.now()-(R?.timestamp||0);if(J<C&&R){_.debug(`Using cached discovery data (age: ${J}ms)`);let ne=E.server.moduleGraph.getModuleById(M);return ne&&E.server.reloadModule(ne),[]}w.clearCache();let he=E.server.moduleGraph.getModuleById(M);return he&&E.server.reloadModule(he),[]}finally{I=!1,setTimeout(()=>{F===E.file&&(F=null)},200)}}return{name:e,enforce:"pre",configResolved(E){L=E.root,z=E.command==="serve",g&&_.debug(`${t} ${e} initialized`),z&&_.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),i.logConfig&&i.logConfig(P)},config(E){return E.optimizeDeps||(E.optimizeDeps={}),E.optimizeDeps.exclude||(E.optimizeDeps.exclude=[]),E.optimizeDeps.exclude.includes(h)||E.optimizeDeps.exclude.push(h),E},resolveId(E){return E===h?(_.debug(`Resolving virtual module: ${E}`),{id:M,moduleSideEffects:!0}):null},async load(E){if(E!==M)return null;if(_.debug(`Loading virtual module: ${E}`),!A()){_.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let T=0;for(;!A()&&T<100;)await new Promise(J=>setTimeout(J,10)),T++;if(!A())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let T;return R?(_.debug("Using cached discovery data for virtual module"),T=R):(_.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.`),T=await w[s](),R=T,_.debug("Discovery completed for virtual module")),Q(T)}catch(T){if(be(T))throw T;return _.error(`${e} virtual module (${M}) failed to load: ${T.message}`),_.error(`Stack: ${T.stack||"No stack trace available"}`),i.generateEmpty({},g,P,k)}},async buildStart(){if(W=!1,!A()){_.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let E=0;for(;!A()&&E<100;)await new Promise(T=>setTimeout(T,10)),E++;if(!A())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let E=await w[s](!R);if(R=E,p==="routes"&&E?.routes){let T=it(m.getAppRoot(),_),J=Fn(E.routes,T),he=[...E.routes.map(ne=>({path:ne.path,auth:ne.auth,meta:ne.meta})),...J];x?.set({routes:he,source:E.source||"auto-discovery",blogPosts:T})}i.logStats&&i.logStats(E,t,_)}catch(E){if(be(E))throw E;_.error(`${e} discovery failed during file scanning: ${E.message}`),_.error(`Stack: ${E.stack||"No stack trace available"}`),R=ae.getEmptyResultWithError(w,E)}finally{W=!0}N?.set(R),p==="routes"&&x?.useEntityResolver(w.getEntityResolver())},configureServer(){W=!0},handleHotUpdate(E){return S?[]:W?te(E):(_.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!R){_.warn("No cached discovery data for manifest generation - skipping");return}try{let E=ae.generateManifest(R,i.generateManifest);this.emitFile({type:"asset",fileName:l,source:JSON.stringify(E,null,2)}),v&&i.logManifest&&i.logManifest(R,e)}catch(E){_.error(`${e} manifest generation failed: ${E.message}`),_.error(`Stack: ${E.stack||"No stack trace available"}`)}},transform(E,T){return T===M?{code:E,map:null}:null}}}}var Pc={generateGlobals:ae.generateGlobals,generateExports:ae.generateExports,generateDefaultExport:ae.generateDefaultExport,wrapVirtualModule:ae.wrapVirtualModule,generateInspectionHeader:ae.generateInspectionHeader,validateTemplates:ae.validateTemplates,createTemplateConfig:ae.createTemplateConfig};q();var fe=class o{constructor(e,t={}){if(this.constructor===o)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=G(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 n=await this._getPatterns();this.options.verbose&&n&&(typeof n=="object"&&n.pattern?this.logger.verbose(`Pattern: ${n.pattern}`):typeof n=="string"&&this.logger.verbose(`Pattern: ${n}`),n.dirs&&this.logger.verbose(`Search directories: ${n.dirs.slice(0,3).join(", ")}${n.dirs.length>3?` (${n.dirs.length} total)`:""}`));let r=await this._prepareFiles(),s=await this._scanFiles(n),a=await this._processFiles(s,r);this.cache={...a,timestamp:Date.now()};let i=Date.now()-t;return this.logger.debug(`Discovery completed in ${i}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){if(be(n))throw n;return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${n.message}`),this.logger.error(`Stack: ${n.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 _prepareFiles(){return{}}async _processFiles(e,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(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),n=t[t.length-1],r=n.split(".")[0],s=n.split(".").pop();return{fileName:n,baseName:r,extension:s,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let n=this.pathResolver.getFileInfo(e);return n?await t(n):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(n){if(be(n))throw n;return this.logger.debug(`Error processing file ${e}: ${n.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}};q();var Nc={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},jn=[{id:"en",name:"English",nativeName:"English",flagCode:"gb"},{id:"us",name:"English (US)",nativeName:"English (US)",countryCode:"US",dialCode:"+1"},{id:"gb",name:"English (UK)",nativeName:"English (UK)",countryCode:"GB",dialCode:"+44"},{id:"en-ca",name:"English (Canada)",nativeName:"English (Canada)",flagCode:"ca",countryCode:"CA",dialCode:"+1"},{id:"au",name:"English (Australia)",nativeName:"English (Australia)",countryCode:"AU",dialCode:"+61"},{id:"ie",name:"English (Ireland)",nativeName:"English (Ireland)",countryCode:"IE",dialCode:"+353"},{id:"es",name:"Spanish",nativeName:"Espa\xF1ol",countryCode:"ES",dialCode:"+34"},{id:"mx",name:"Spanish (Mexico)",nativeName:"Espa\xF1ol (M\xE9xico)",countryCode:"MX",dialCode:"+52"},{id:"es-ar",name:"Spanish (Argentina)",nativeName:"Espa\xF1ol (Argentina)",flagCode:"ar",countryCode:"AR",dialCode:"+54"},{id:"fr",name:"French",nativeName:"Fran\xE7ais",flagCode:"fr",countryCode:"FR",dialCode:"+33"},{id:"fr-be",name:"French (Belgium)",nativeName:"Fran\xE7ais (Belgique)",flagCode:"be",countryCode:"BE",dialCode:"+32"},{id:"ch",name:"French (Switzerland)",nativeName:"Fran\xE7ais (Suisse)",countryCode:"CH",dialCode:"+41"},{id:"de",name:"German",nativeName:"Deutsch",countryCode:"DE",dialCode:"+49"},{id:"at",name:"German (Austria)",nativeName:"Deutsch (\xD6sterreich)",countryCode:"AT",dialCode:"+43"},{id:"it",name:"Italian",nativeName:"Italiano",countryCode:"IT",dialCode:"+39"},{id:"pt",name:"Portuguese",nativeName:"Portugu\xEAs",countryCode:"PT",dialCode:"+351"},{id:"br",name:"Portuguese (Brazil)",nativeName:"Portugu\xEAs (Brasil)",flagCode:"br",countryCode:"BR",dialCode:"+55"},{id:"ru",name:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",countryCode:"RU",dialCode:"+7"},{id:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",countryCode:"JP",dialCode:"+81"},{id:"ko",name:"Korean",nativeName:"\uD55C\uAD6D\uC5B4",countryCode:"KR",dialCode:"+82"},{id:"zh",name:"Chinese",nativeName:"\u4E2D\u6587",countryCode:"CN",dialCode:"+86"},{id:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flagCode:"sa",countryCode:"SA",dialCode:"+966"},{id:"ar-ma",name:"Arabic (Morocco)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0645\u063A\u0631\u0628)",flagCode:"ma",countryCode:"MA",dialCode:"+212"},{id:"ar-dz",name:"Arabic (Algeria)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u062C\u0632\u0627\u0626\u0631)",flagCode:"dz",countryCode:"DZ",dialCode:"+213"},{id:"ar-tn",name:"Arabic (Tunisia)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u062A\u0648\u0646\u0633)",flagCode:"tn",countryCode:"TN",dialCode:"+216"},{id:"ar-ly",name:"Arabic (Libya)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0644\u064A\u0628\u064A\u0627)",flagCode:"ly",countryCode:"LY",dialCode:"+218"},{id:"ar-mr",name:"Arabic (Mauritania)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627)",flagCode:"mr",countryCode:"MR",dialCode:"+222"},{id:"hi",name:"Hindi",nativeName:"\u0939\u093F\u0928\u094D\u0926\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"nl",name:"Dutch",nativeName:"Nederlands",countryCode:"NL",dialCode:"+31"},{id:"sv",name:"Swedish",nativeName:"Svenska",countryCode:"SE",dialCode:"+46"},{id:"da",name:"Danish",nativeName:"Dansk",countryCode:"DK",dialCode:"+45"},{id:"no",name:"Norwegian",nativeName:"Norsk",countryCode:"NO",dialCode:"+47"},{id:"fi",name:"Finnish",nativeName:"Suomi",countryCode:"FI",dialCode:"+358"},{id:"pl",name:"Polish",nativeName:"Polski",countryCode:"PL",dialCode:"+48"},{id:"tr",name:"Turkish",nativeName:"T\xFCrk\xE7e",countryCode:"TR",dialCode:"+90"},{id:"th",name:"Thai",nativeName:"\u0E44\u0E17\u0E22",countryCode:"TH",dialCode:"+66"},{id:"vi",name:"Vietnamese",nativeName:"Ti\u1EBFng Vi\u1EC7t",countryCode:"VN",dialCode:"+84"},{id:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",countryCode:"ID",dialCode:"+62"},{id:"ms",name:"Malay",nativeName:"Bahasa Melayu",flagCode:"my",countryCode:"MY",dialCode:"+60"},{id:"tl",name:"Filipino",nativeName:"Tagalog",countryCode:"PH",dialCode:"+63"},{id:"bg",name:"Bulgarian",nativeName:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",countryCode:"BG",dialCode:"+359"},{id:"cs",name:"Czech",nativeName:"\u010Ce\u0161tina",countryCode:"CZ",dialCode:"+420"},{id:"el",name:"Greek",nativeName:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",countryCode:"GR",dialCode:"+30"},{id:"he",name:"Hebrew",nativeName:"\u05E2\u05D1\u05E8\u05D9\u05EA",countryCode:"IL",dialCode:"+972"},{id:"hu",name:"Hungarian",nativeName:"Magyar",countryCode:"HU",dialCode:"+36"},{id:"is",name:"Icelandic",nativeName:"\xCDslenska",countryCode:"IS",dialCode:"+354"},{id:"lt",name:"Lithuanian",nativeName:"Lietuvi\u0173",countryCode:"LT",dialCode:"+370"},{id:"lv",name:"Latvian",nativeName:"Latvie\u0161u",countryCode:"LV",dialCode:"+371"},{id:"mt",name:"Maltese",nativeName:"Malti",countryCode:"MT",dialCode:"+356"},{id:"ro",name:"Romanian",nativeName:"Rom\xE2n\u0103",countryCode:"RO",dialCode:"+40"},{id:"sk",name:"Slovak",nativeName:"Sloven\u010Dina",countryCode:"SK",dialCode:"+421"},{id:"sl",name:"Slovenian",nativeName:"Sloven\u0161\u010Dina",flagCode:"si",countryCode:"SI",dialCode:"+386"},{id:"uk",name:"Ukrainian",nativeName:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flagCode:"ua",countryCode:"UA",dialCode:"+380"},{id:"et",name:"Estonian",nativeName:"Eesti",countryCode:"EE",dialCode:"+372"},{id:"ca",name:"Catalan",nativeName:"Catal\xE0",countryCode:"ES",dialCode:"+34"},{id:"eu",name:"Basque",nativeName:"Euskara",countryCode:"ES",dialCode:"+34"},{id:"gl",name:"Galician",nativeName:"Galego",countryCode:"ES",dialCode:"+34"},{id:"cy",name:"Welsh",nativeName:"Cymraeg",countryCode:"GB",dialCode:"+44"},{id:"ga",name:"Irish",nativeName:"Gaeilge",flagCode:"ie",countryCode:"IE",dialCode:"+353"},{id:"gd",name:"Scottish Gaelic",nativeName:"G\xE0idhlig",flagCode:"gb-sct",countryCode:"GB",dialCode:"+44"},{id:"br-fr",name:"Breton",nativeName:"Brezhoneg",flagCode:"bzh",countryCode:"FR",dialCode:"+33"},{id:"co",name:"Corsican",nativeName:"Corsu",flagCode:"fr-cor",countryCode:"FR",dialCode:"+33"},{id:"oc",name:"Occitan",nativeName:"Occitan",countryCode:"FR",dialCode:"+33"},{id:"rm",name:"Romansh",nativeName:"Rumantsch",countryCode:"CH",dialCode:"+41"},{id:"lb",name:"Luxembourgish",nativeName:"L\xEBtzebuergesch",countryCode:"LU",dialCode:"+352"},{id:"af",name:"Afrikaans",nativeName:"Afrikaans",countryCode:"ZA",dialCode:"+27"},{id:"sw",name:"Swahili",nativeName:"Kiswahili",countryCode:"KE",dialCode:"+254"},{id:"am",name:"Amharic",nativeName:"\u12A0\u121B\u122D\u129B",flagCode:"et",countryCode:"ET",dialCode:"+251"},{id:"bn",name:"Bengali",nativeName:"\u09AC\u09BE\u0982\u09B2\u09BE",flagCode:"bd",countryCode:"BD",dialCode:"+880"},{id:"gu",name:"Gujarati",nativeName:"\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"kn",name:"Kannada",nativeName:"\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ml",name:"Malayalam",nativeName:"\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"mr",name:"Marathi",nativeName:"\u092E\u0930\u093E\u0920\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ne",name:"Nepali",nativeName:"\u0928\u0947\u092A\u093E\u0932\u0940",flagCode:"np",countryCode:"NP",dialCode:"+977"},{id:"pa",name:"Punjabi",nativeName:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"si",name:"Sinhala",nativeName:"\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",countryCode:"LK",dialCode:"+94"},{id:"ta",name:"Tamil",nativeName:"\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"te",name:"Telugu",nativeName:"\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ur",name:"Urdu",nativeName:"\u0627\u0631\u062F\u0648",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"fa",name:"Persian",nativeName:"\u0641\u0627\u0631\u0633\u06CC",flagCode:"ir",countryCode:"IR",dialCode:"+98"},{id:"ps",name:"Pashto",nativeName:"\u067E\u069A\u062A\u0648",countryCode:"AF",dialCode:"+93"},{id:"uz",name:"Uzbek",nativeName:"O\u02BBzbek",countryCode:"UZ",dialCode:"+998"},{id:"kk",name:"Kazakh",nativeName:"\u049A\u0430\u0437\u0430\u049B",flagCode:"kz",countryCode:"KZ",dialCode:"+7"},{id:"ky",name:"Kyrgyz",nativeName:"\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430",flagCode:"kg",countryCode:"KG",dialCode:"+996"},{id:"tg",name:"Tajik",nativeName:"\u0422\u043E\u04B7\u0438\u043A\u04E3",flagCode:"tj",countryCode:"TJ",dialCode:"+992"},{id:"mn",name:"Mongolian",nativeName:"\u041C\u043E\u043D\u0433\u043E\u043B",countryCode:"MN",dialCode:"+976"},{id:"my",name:"Burmese",nativeName:"\u1019\u103C\u1014\u103A\u1019\u102C",flagCode:"mm",countryCode:"MM",dialCode:"+95"},{id:"km",name:"Khmer",nativeName:"\u1781\u17D2\u1798\u17C2\u179A",flagCode:"kh",countryCode:"KH",dialCode:"+855"},{id:"lo",name:"Lao",nativeName:"\u0EA5\u0EB2\u0EA7",flagCode:"la",countryCode:"LA",dialCode:"+856"},{id:"ka",name:"Georgian",nativeName:"\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",flagCode:"ge",countryCode:"GE",dialCode:"+995"},{id:"hy",name:"Armenian",nativeName:"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",flagCode:"am",countryCode:"AM",dialCode:"+374"},{id:"az",name:"Azerbaijani",nativeName:"Az\u0259rbaycan",countryCode:"AZ",dialCode:"+994"},{id:"be",name:"Belarusian",nativeName:"\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",flagCode:"by",countryCode:"BY",dialCode:"+375"},{id:"mk",name:"Macedonian",nativeName:"\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",countryCode:"MK",dialCode:"+389"},{id:"sr",name:"Serbian",nativeName:"\u0421\u0440\u043F\u0441\u043A\u0438",countryCode:"RS",dialCode:"+381"},{id:"bs",name:"Bosnian",nativeName:"Bosanski",flagCode:"ba",countryCode:"BA",dialCode:"+387"},{id:"hr",name:"Croatian",nativeName:"Hrvatski",countryCode:"HR",dialCode:"+385"},{id:"sq",name:"Albanian",nativeName:"Shqip",flagCode:"al",countryCode:"AL",dialCode:"+355"},{id:"md",name:"Moldovan",nativeName:"Moldoveneasc\u0103",countryCode:"MD",dialCode:"+373"}],ks={US:"United States",GB:"United Kingdom",CA:"Canada",AU:"Australia",IE:"Ireland",FR:"France",BE:"Belgium",CH:"Switzerland",DE:"Germany",AT:"Austria",IT:"Italy",PT:"Portugal",BR:"Brazil",ES:"Spain",MX:"Mexico",AR:"Argentina",RU:"Russia",JP:"Japan",KR:"South Korea",CN:"China",SE:"Sweden",NO:"Norway",DK:"Denmark",FI:"Finland",NL:"Netherlands",PL:"Poland",CZ:"Czech Republic",HU:"Hungary",RO:"Romania",BG:"Bulgaria",GR:"Greece",TR:"Turkey",IL:"Israel",IN:"India",ZA:"South Africa"};function Ds(){return jn.filter(o=>o.countryCode!==void 0&&o.dialCode!==void 0).map(o=>({code:o.countryCode,dialCode:o.dialCode,flagCode:o.flagCode||o.id,name:o.countryName||ks[o.countryCode]||o.name}))}var Ts=Ds(),Ke="/flags";function lt(o){return`${o.toLowerCase()}.svg`}function It(o){return jn.find(t=>t.id===o)?.flagCode||o}function ct(){return[...new Set(Ts.map(o=>o.flagCode))]}var Te={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Os="public/logo.svg is missing: it is the site logo (Organization / publisher logo in the JSON-LD, the default logo) and the source of the favicon, PWA icons and og-image.png. Add public/logo.svg.",zn="/manifest.json",Ye=class extends fe{constructor(e,t={}){super(e,{assets:pe.assets.fallback,assetPatterns:pe.assets.patterns,frameworkPackage:kt.package,assetsPath:kt.assetsPath,modernFormats:pe.assets.modern,...t}),this.hasRunForSession=!1,this.flagCodes=null,this.entityResolver=null}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _prepareFiles(){let e=this.pathResolver.getAppRoot(),t=await this._ensureDefaultAssets(e);if(this.flagCodes){let i=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(i?[...new Set([...this.flagCodes,...ct()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${Ke}/: ${l.join(", ")}`)}let n=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(n)||this.logger.warn(Os);let s=[],a=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(s=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:s}}async _processFiles(e,{copiedAssets:t,generatedAssets:n}){let r=this.pathResolver.getAppRoot(),{consumerFiles:s}=e,a=await this._processAssetFiles(s),i=this._buildAssetManifest(a,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${zn}`))}),l=await this._readLogoSvgContent("/logo.svg",r);return{assets:a,manifest:{...i,logoSvgContent:l},copiedAssets:t,generatedAssets:n}}_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`}useFlagCodes(e,t){this.flagCodes=e,this.entityResolver=t}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 n=this.getAssets().map(s=>s.path),r=t||this.options.modernFormats;for(let s of r){let a=`/${e}.${s}`;if(n.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let n=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${n}`),!n)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath($e.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let s of this.options.assets)await this._ensureAsset(s,r,n)&&t.push(s);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(n){this.logger.debug(`Failed to ensure default assets: ${n.message}`)}return t}async _ensureAsset(e,t,n){let r=this.pathResolver.resolveAppPath(`${$e.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let s=this.pathResolver.normalizePath(`${n}/${e}`);if(this.pathResolver.pathExists(s)){if(await this.pathResolver.copy(s,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}_ensureFlags(e){let t=this.pathResolver.resolveFrameworkPackage("@donotdev/core");if(!t)throw new Error("Flag copy: @donotdev/core not found");let n=this.pathResolver.normalizePath(`${t}/${Fe.PUBLISHED_FLAGS}`),r=`${$e.public}${Ke}`,s=[];for(let a of e){let i=lt(a),l=this.pathResolver.resolveAppPath(`${r}/${i}`);if(this.pathResolver.pathExists(l))continue;let c=`${n}/${i}`;if(!this.pathResolver.pathExists(c)){this.logger.warn(`No flag artwork for "${a}": add ${r}/${i} to the app`);continue}if(!this.pathResolver.copySync(c,l))throw new Error(`Flag copy: cannot copy ${c} to ${l}`);s.push(i)}return s}async _processAssetFiles(e){let t=[];for(let n of e)try{let r=this.pathResolver.getFileInfo(n);if(r&&r.isFile){let s=n.split("/").pop()||n.split("\\").pop(),a=this._analyzeAsset(s,r.size);a&&t.push(a)}}catch(r){this.logger.debug(`Error processing asset file ${n}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let n=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:n,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 n=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(n)?"image":["woff2","woff","ttf","otf"].includes(n)?"font":["json"].includes(n)?"json":["ico"].includes(n)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}_matchesPattern(e,t){let n=t.split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let n=e.map(s=>s.path);return{logo:{optimal:this._getOptimalAsset("logo",n,this.options.modernFormats),fallback:this._getOptimalAsset("logo",n,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",n,["svg","ico"]),fallback:this._getOptimalAsset("favicon",n,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",n,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",n,["png"]),512:this._getOptimalAsset("android-chrome-512x512",n,["png"])},manifest:t?zn:null,modernFormats:e.filter(s=>s.isModern).map(s=>s.path),fallbackFormats:e.filter(s=>!s.isModern).map(s=>s.path)}}_getOptimalAsset(e,t,n){for(let r of n){let s=`/${e}.${r}`;if(t.includes(s))return s}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),n=await this._resolvePackage("@donotdev/ui",t);if(!n)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${n}/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 n=this.pathResolver.resolveFrameworkPackage(e,t);return n?(this.logger.debug(`Found package: ${n}`),n):(this.logger.debug(`Package ${e} not found`),null)}catch(n){return this.logger.debug(`Error resolving package ${e}: ${n.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 n=e.slice(1),r=this.pathResolver.resolveAppPath(`${$e.public}/${n}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(n){return this.logger.debug(`Failed to read logo SVG content: ${n.message}`),null}}async _renderOgImage(e,t){let{width:n,height:r}=await e(t).metadata(),s=Math.min(Te.logoWidth/n,Te.logoHeight/r),a=await e(t,{density:Math.ceil(72*s)}).resize(Te.logoWidth,Te.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:Te.width,height:Te.height,channels:4,background:Te.background}}).composite([{input:a}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),n=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"}],s=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...s,...r].map(u=>u.name),error:"Failed to read logo.svg"};for(let u of s){let p=`${n}/${u.name}`;if(this.pathResolver.pathExists(p)){i.push(u.name);continue}try{await this.pathResolver.write(p,l),a.push(u.name)}catch(d){this.logger.debug(`Failed to copy ${u.name}: ${d.message}`),i.push(u.name)}}let c=await import("sharp").catch(()=>null);if(!c)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(u=>u.name));else{for(let p of r){let d=`${n}/${p.name}`;if(this.pathResolver.pathExists(d)){i.push(p.name);continue}try{let f=c.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;p.format==="ico"?g=await f.toFormat("png").toBuffer():g=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(d,g),a.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),i.push(p.name)}}let u=qe.slice(1);if(this.pathResolver.pathExists(`${n}/${u}`))i.push(u);else try{let p=await this._renderOgImage(c.default,t);await this.pathResolver.write(`${n}/${u}`,p),a.push(u)}catch(p){this.logger.debug(`Failed to generate ${u}: ${p.message}`),i.push(u)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:[...s,...r].map(c=>c.name),error:l.message}}}};Y();var Is={isEmpty:o=>!o.manifest||o.assets?.length===0,generateModule:(o,e,t="assets")=>{let{manifest:n,assets:r,copiedAssets:s}=o,a=n.logoSvgContent||null,i={totalAssets:r.length,copiedAssets:s.length,hasLogo:n.logo.optimal!==null,hasFavicon:n.favicon.optimal!==null,hasManifest:n.manifest!==null,timestamp:new Date().toISOString()};return`// ${V.assets} - Generated asset manifest
54
+ const assetManifest = ${JSON.stringify(n,null,2)};
55
+ const assetStats = ${JSON.stringify(i,null,2)};
56
56
 
57
57
  // Populate unified DnDev config for runtime access
58
58
  if (typeof globalThis !== 'undefined') {
@@ -68,11 +68,11 @@ if (typeof globalThis !== 'undefined') {
68
68
  }
69
69
 
70
70
  // Populate assets configuration
71
- globalThis._DNDEV_CONFIG_.${ee[t]} = {
71
+ globalThis._DNDEV_CONFIG_.${oe[t]} = {
72
72
  mapping: assetManifest,
73
- logoSvgContent: ${JSON.stringify(i)},
73
+ logoSvgContent: ${JSON.stringify(a)},
74
74
  manifest: {
75
- totalAssets: ${o.length},
75
+ totalAssets: ${r.length},
76
76
  generatedAt: new Date().toISOString(),
77
77
  },
78
78
  };
@@ -120,7 +120,7 @@ export default {
120
120
  getManifest,
121
121
  getAllAssets
122
122
  };
123
- `},generateEmpty:(n,e,t,r="assets")=>{let o={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${U.assets} - Empty asset manifest
123
+ `},generateEmpty:(o,e,t,n="assets")=>{let r={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${V.assets} - Empty asset manifest
124
124
  const assetManifest = {
125
125
  logo: { optimal: null, fallback: null },
126
126
  favicon: { optimal: null, fallback: null },
@@ -130,7 +130,7 @@ const assetManifest = {
130
130
  modernFormats: [],
131
131
  fallbackFormats: []
132
132
  };
133
- const assetStats = ${JSON.stringify(o,null,2)};
133
+ const assetStats = ${JSON.stringify(r,null,2)};
134
134
 
135
135
  // Populate unified DnDev config for runtime access
136
136
  if (typeof globalThis !== 'undefined') {
@@ -146,7 +146,7 @@ if (typeof globalThis !== 'undefined') {
146
146
  }
147
147
 
148
148
  // Populate empty assets configuration
149
- globalThis._DNDEV_CONFIG_.${ee[r]} = {
149
+ globalThis._DNDEV_CONFIG_.${oe[n]} = {
150
150
  mapping: assetManifest,
151
151
  logoSvgContent: null,
152
152
  manifest: {
@@ -190,7 +190,7 @@ export default {
190
190
  getManifest,
191
191
  getAllAssets
192
192
  };
193
- `},generateInspection:n=>{let{assets:e,manifest:t,copiedAssets:r}=n;return!e||e.length===0?`/**
193
+ `},generateInspection:o=>{let{assets:e,manifest:t,copiedAssets:n}=o;return!e||e.length===0?`/**
194
194
  * Generated Asset Discovery Results
195
195
  * Source: empty
196
196
  * Generated at: ${new Date().toISOString()}
@@ -219,7 +219,7 @@ export default discoveredAssets;
219
219
  `:`/**
220
220
  * Generated Asset Discovery Results
221
221
  * Generated at: ${new Date().toISOString()}
222
- * Import from '${U.assets}'
222
+ * Import from '${V.assets}'
223
223
  */
224
224
 
225
225
  export const discoveredAssets = ${JSON.stringify(e,null,2)};
@@ -228,7 +228,7 @@ export const assetManifest = ${JSON.stringify(t,null,2)};
228
228
 
229
229
  export const assetStats = {
230
230
  totalAssets: ${e.length},
231
- copiedAssets: ${r.length},
231
+ copiedAssets: ${n.length},
232
232
  hasLogo: ${t.logo.optimal!==null},
233
233
  hasFavicon: ${t.favicon.optimal!==null},
234
234
  hasManifest: ${t.manifest!==null},
@@ -236,16 +236,16 @@ export const assetStats = {
236
236
  };
237
237
 
238
238
  export default discoveredAssets;
239
- `},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 r=n.assets?.length||0,o=n.generatedAssets?.length||0;t&&(o>0?t.info(`${e} Assets: ${r} found, ${o} generated`):t.info(`${e} Assets: ${r} found`))}},ss=[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 _r({i18nStore:n,routeManifest:e,...t}={}){if(!n||!e)throw new Error("[dndev] createViteAssetPlugin: options.i18nStore and options.routeManifest are required (createVitePlugins passes the i18n and route plugins' stores).");let r=null,o=ye({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:U.assets,DiscoveryClass:Ke,createDiscovery:(l,c)=>(r=new Ke(l,c),r),discoveryMethod:"discoverAssets",filePatterns:ss,templates:os,manifestFileName:me.manifests.asset,configKey:"assets"})(t),s=o.buildStart,i=o.configureServer,a=null;return o.configureServer=function(l){return a=l,i.call(this,l)},o.buildStart=async function(...l){let[{flagCodes:c},u]=await Promise.all([n.ready(),e.entityResolver()]);r.useFlagCodes(c,u);let p=D.getInstance(),d=[...new Set([...c??[],...lt()])].map(f=>p.resolveAppPath(`public${qe}/${at(f)}`)).filter(f=>!p.pathExists(f));if(await s.apply(this,l),a)for(let f of d)p.pathExists(f)&&a.watcher.emit("add",f)},o}J();var Nr=U.blog,Ar="\0"+Nr;function Dr(){return{name:"dndev-vite-blog",resolveId(n){if(n===Nr)return Ar},load(n){if(n===Ar)return`
239
+ `},generateManifest:o=>({assets:o.assets?.length||0,copied:o.copiedAssets?.length||0,timestamp:Date.now(),hasLogo:o.manifest?.logo?.optimal!==null,hasFavicon:o.manifest?.favicon?.optimal!==null}),logConfig:o=>{},logStats:(o,e,t)=>{let n=o.assets?.length||0,r=o.generatedAssets?.length||0;t&&(r>0?t.info(`${e} Assets: ${n} found, ${r} generated`):t.info(`${e} Assets: ${n} found`))}},Fs=[o=>o.includes("/public/"),o=>o.endsWith(".png")||o.endsWith(".svg")||o.endsWith(".ico"),o=>o.includes("favicon")||o.includes("logo")||o.includes("manifest")];function Bn({i18nStore:o,routeManifest:e,...t}={}){if(!o||!e)throw new Error("[dndev] createViteAssetPlugin: options.i18nStore and options.routeManifest are required (createVitePlugins passes the i18n and route plugins' stores).");let n=null,r=we({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:V.assets,DiscoveryClass:Ye,createDiscovery:(l,c)=>(n=new Ye(l,c),n),discoveryMethod:"discoverAssets",filePatterns:Fs,templates:Is,manifestFileName:ve.manifests.asset,configKey:"assets"})(t),s=r.buildStart,a=r.configureServer,i=null;return r.configureServer=function(l){return i=l,a.call(this,l)},r.buildStart=async function(...l){let[{flagCodes:c},u]=await Promise.all([o.ready(),e.entityResolver()]);n.useFlagCodes(c,u);let p=O.getInstance(),d=[...new Set([...c??[],...ct()])].map(f=>p.resolveAppPath(`public${Ke}/${lt(f)}`)).filter(f=>!p.pathExists(f));if(await s.apply(this,l),i)for(let f of d)p.pathExists(f)&&i.watcher.emit("add",f)},r}q();var Wn=V.blog,Un="\0"+Wn;function Gn(){return{name:"dndev-vite-blog",resolveId(o){if(o===Wn)return Un},load(o){if(o===Un)return`
240
240
  const files = import.meta.glob('/src/content/blog/*.md', {
241
241
  query: '?raw',
242
242
  import: 'default',
243
243
  eager: true,
244
244
  });
245
245
  export default files;
246
- `}}}import{loadEnv as is}from"vite";J();var kr={isEmpty:n=>!n.env||Object.keys(n.env).length===0,generateModule:(n,e,t="env")=>{let{env:r,mode:o}=n;if(!r||Object.keys(r).length===0)return kr.generateEmpty(n,e,void 0,t);let s={totalVars:Object.keys(r).length,mode:o,source:n.source,generatedAt:new Date().toISOString()};return`// ${U.env} - Generated environment variables
246
+ `}}}import{loadEnv as Ms}from"vite";q();var Hn={isEmpty:o=>!o.env||Object.keys(o.env).length===0,generateModule:(o,e,t="env")=>{let{env:n,mode:r}=o;if(!n||Object.keys(n).length===0)return Hn.generateEmpty(o,e,void 0,t);let s={totalVars:Object.keys(n).length,mode:r,source:o.source,generatedAt:new Date().toISOString()};return`// ${V.env} - Generated environment variables
247
247
 
248
- const envData = ${JSON.stringify(r,null,2)};
248
+ const envData = ${JSON.stringify(n,null,2)};
249
249
  const envManifest = ${JSON.stringify(s,null,2)};
250
250
 
251
251
  // Freeze env data to prevent runtime tampering
@@ -258,7 +258,7 @@ if (typeof globalThis !== 'undefined') {
258
258
  if (!globalThis._DNDEV_CONFIG_) {
259
259
  globalThis._DNDEV_CONFIG_ = {
260
260
  platform: 'vite',
261
- mode: '${o}',
261
+ mode: '${r}',
262
262
  context: 'client',
263
263
  timestamp: Date.now(),
264
264
  };
@@ -266,27 +266,27 @@ if (typeof globalThis !== 'undefined') {
266
266
  // Ensure platform is always set to 'vite' (Vite config builder responsibility)
267
267
  globalThis._DNDEV_CONFIG_.platform = 'vite';
268
268
  // Update mode if it exists
269
- if (globalThis._DNDEV_CONFIG_.mode !== '${o}') {
270
- globalThis._DNDEV_CONFIG_.mode = '${o}';
269
+ if (globalThis._DNDEV_CONFIG_.mode !== '${r}') {
270
+ globalThis._DNDEV_CONFIG_.mode = '${r}';
271
271
  }
272
272
  }
273
273
 
274
274
  // Populate env configuration (frozen to prevent tampering)
275
- globalThis._DNDEV_CONFIG_.${ee[t]} = envData;
275
+ globalThis._DNDEV_CONFIG_.${oe[t]} = envData;
276
276
  // Only freeze the env property, not the entire config (other plugins need to add properties)
277
277
  }
278
278
 
279
279
  // Named exports for convenience
280
280
  export const env = envData;
281
281
  export const manifest = envManifest;
282
- export const source = '${n.source}';
282
+ export const source = '${o.source}';
283
283
 
284
284
  // Default export
285
285
  export default envData;
286
- `},generateEmpty:(n,e,t,r="env")=>{let o={totalVars:0,mode:n.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${U.env} - Empty environment data
286
+ `},generateEmpty:(o,e,t,n="env")=>{let r={totalVars:0,mode:o.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${V.env} - Empty environment data
287
287
 
288
288
  const envData = {};
289
- const envManifest = ${JSON.stringify(o,null,2)};
289
+ const envManifest = ${JSON.stringify(r,null,2)};
290
290
 
291
291
  // Freeze env data to prevent runtime tampering
292
292
  Object.freeze(envData);
@@ -298,7 +298,7 @@ if (typeof globalThis !== 'undefined') {
298
298
  if (!globalThis._DNDEV_CONFIG_) {
299
299
  globalThis._DNDEV_CONFIG_ = {
300
300
  platform: 'vite',
301
- mode: '${n.mode||"development"}',
301
+ mode: '${o.mode||"development"}',
302
302
  context: 'client',
303
303
  timestamp: Date.now(),
304
304
  };
@@ -306,13 +306,13 @@ if (typeof globalThis !== 'undefined') {
306
306
  // Ensure platform is always set to 'vite' (Vite config builder responsibility)
307
307
  globalThis._DNDEV_CONFIG_.platform = 'vite';
308
308
  // Update mode if it exists
309
- if (globalThis._DNDEV_CONFIG_.mode !== '${n.mode||"development"}') {
310
- globalThis._DNDEV_CONFIG_.mode = '${n.mode||"development"}';
309
+ if (globalThis._DNDEV_CONFIG_.mode !== '${o.mode||"development"}') {
310
+ globalThis._DNDEV_CONFIG_.mode = '${o.mode||"development"}';
311
311
  }
312
312
  }
313
313
 
314
314
  // Populate empty env configuration (frozen to prevent tampering)
315
- globalThis._DNDEV_CONFIG_.${ee[r]} = envData;
315
+ globalThis._DNDEV_CONFIG_.${oe[n]} = envData;
316
316
  // Only freeze the env property, not the entire config (other plugins need to add properties)
317
317
  }
318
318
 
@@ -321,32 +321,38 @@ export const manifest = envManifest;
321
321
  export const source = 'empty';
322
322
 
323
323
  export default envData;
324
- `},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(`
325
- `)},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 r=Object.keys(n.env).length;t&&t.info(`${e} Env: ${r} VITE_* variables`)}},Dt=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 r={...is(this.mode,e,"VITE_")};return this.mode==="production"&&(delete r.VITE_USE_FIREBASE_EMULATOR,delete r.VITE_FIREBASE_EMULATOR_HOST,delete r.VITE_FIREBASE_AUTH_EMULATOR_HOST,delete r.VITE_FIREBASE_FIRESTORE_EMULATOR_HOST,delete r.VITE_FIREBASE_FUNCTIONS_EMULATOR_PORT),r.MODE=this.mode,r.DEV=this.mode==="development",r.PROD=this.mode==="production",r.SSR=!1,{env:r,mode:this.mode,source:`${e}/.env`,errors:[]}}catch(e){return{env:{},mode:this.mode,source:"error",errors:[e.message]}}}};function Tr(n={}){return ye({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:U.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:kr,manifestFileName:me.manifests.env,configKey:"env",createDiscovery:(e,t)=>new Dt(e,{...t,mode:n.mode||t.mode||"development"})})({...n,disableHmr:!0})}function as(n,e,t,r={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:i}=r;return Array.from({length:t},(a,l)=>{let c=`${e}.${l}`;return n(c)}).filter((a,l)=>{let c=`${e}.${l}`;return!(a===c||s&&a.trim()===""||a.length<o||i&&!i(a,l))})}var Ye=(n,e,t)=>({tag:"meta",attributes:{[n]:e,content:t}});var ls=20,Or={defaultValue:""};function cs(n,e,t){if(n!==null)return n!==void 0?n:t(e,Or)||void 0}function us(n,e){let t=s=>n(s,Or),r=s=>t(`${e}:meta.${s}`)||void 0,o=as(t,`${e}:meta.keywords`,ls);return{fullTitle:r("fullTitle"),image:r("image"),type:r("type"),keywords:o.length>0?o:void 0,author:r("author")}}function Ir(n){let{meta:e,ns:t,defaultNs:r,t:o,siteName:s}=n,i=e.seo;if(!t&&!r)return{title:i?.fullTitle||s};let a=t?cs(i?.title,`${t}:title`,o):i?.title??void 0;return{title:i?.fullTitle||(t?us(o,t).fullTitle:void 0)||(a?`${a} | ${s}`:s),...a&&{pageTitle:a}}}var Fr={enabled:!0,themeColor:"#2563eb",backgroundColor:"#ffffff",includeManifestIcons:!0,includeMSIcons:!1};function Mr(n){let e=t=>n(t)?t:void 0;return{svg:e("/favicon.svg"),ico:e("/favicon.ico"),png16:e("/favicon-16x16.png"),png32:e("/favicon-32x32.png"),apple180:e("/apple-touch-icon.png"),android192:e("/icon-192x192.png"),android512:e("/icon-512x512.png")}}var Me=(n,e,t)=>({tag:"link",attributes:{rel:"icon",type:e,...t&&{sizes:t},href:n}});function Lr(n,e){let{enabled:t,appName:r,themeColor:o,includeManifestIcons:s,includeMSIcons:i}=e;if(t===!1)return[];let a=[];return n.svg&&a.push(Me(n.svg,"image/svg+xml")),n.ico&&a.push(Me(n.ico,"image/x-icon")),n.png16&&a.push(Me(n.png16,"image/png","16x16")),n.png32&&a.push(Me(n.png32,"image/png","32x32")),n.apple180&&(a.push({tag:"link",attributes:{rel:"apple-touch-icon",sizes:"180x180",href:n.apple180}}),r&&a.push(Ye("name","apple-mobile-web-app-title",r))),s&&(n.android192&&a.push(Me(n.android192,"image/png","192x192")),n.android512&&a.push(Me(n.android512,"image/png","512x512"))),i&&n.png32&&(a.push(Ye("name","msapplication-TileImage",n.png32)),o&&a.push(Ye("name","msapplication-TileColor",o))),o&&a.push(Ye("name","theme-color",o)),a.push(Ye("name","color-scheme","light dark")),a}q();function jr({appConfig:n}){let e=n.favicon;return{name:"dndev-favicon",transformIndexHtml(){if(e===!1)return[];let t=D.getInstance();return Lr(Mr(s=>t.pathExists(t.resolveAppPath(`public${s}`))),{...Fr,appName:n.app?.name,...e}).map(({tag:s,attributes:i})=>({tag:s,attrs:i,injectTo:"head"}))}}}J();var ps=["--font-family","--font-headline","--font-mono"],Le=":root",ds=/\/\*[\s\S]*?\*\//g,fs=/([^{}]+)\{([^{}]*)\}/g,gs=/^(?::root|html|:where\(:root\))$/,ms=/^(?::root|html)?\.([a-z][\w-]*)$/i,hs=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/;function Br(n){let e=[],t=0,r="",o=0;for(let s=0;s<n.length;s++){let i=n[s];r?i===r&&(r=""):i==='"'||i==="'"?r=i:i==="("?t++:i===")"?t--:i===","&&t===0&&(e.push(n.slice(o,s)),o=s+1)}return e.push(n.slice(o)),e.map(s=>s.trim())}function vs(n){if(gs.test(n))return Le;let e=ms.exec(n);return e?e[1]:null}function zr(n){let e=new Map,t=n.replace(ds,"");for(let[,r,o]of t.matchAll(fs)){let s=r.split(";").pop(),i=Br(s).map(vs).filter(a=>a!==null);if(i.length!==0)for(let a of o.split(";")){let l=a.indexOf(":");if(l===-1)continue;let c=a.slice(0,l).trim();if(!c.startsWith("--"))continue;let u=a.slice(l+1).replace(/!important\s*$/,"").trim();for(let p of i)e.has(p)||e.set(p,new Map),e.get(p).set(c,u)}}return e}function kt(n,e,t){let r=Br(n)[0];if(!r)return null;let o=hs.exec(r);if(o){let[,s,i]=o;return e.has(s)&&!t.has(s)?kt(e.get(s),e,new Set([...t,s])):i===void 0?null:kt(i,e,t)}return r.replace(/^['"]|['"]$/g,"").trim()}function Ur({frameworkCss:n,appCss:e}){let t=zr(n),r=zr(e.join(`
326
- `)),o=new Set([Le,...t.keys(),...r.keys()]),s=new Set;for(let i of o){let a=new Map([...t.get(Le)??[],...r.get(Le)??[],...i===Le?[]:t.get(i)??[],...i===Le?[]:r.get(i)??[]]);for(let l of ps){if(!a.has(l))continue;let c=kt(a.get(l),a,new Set([l]));c&&s.add(c)}}return[...s]}var ys=new Map(Object.entries(or).map(([n,e])=>[n.toLowerCase(),e]));function Gr({families:n,locales:e=[]}){if(!Array.isArray(n))throw new Error("resolveFontManifest: families is required (ThemeDiscovery fontFamilies)");let t=new Set;for(let s of n){let i=ys.get(s.toLowerCase());i&&t.add(i)}let r=new Set(["latin"]);for(let s of e)for(let i of sr[s]??[])r.add(i);let o=new Set;for(let s of t)for(let i of r)for(let a of _t[s])o.add(`${s}-${i}-${a}-normal`);return{fontStems:t,subsets:r,stems:o}}function Tt(n){let e=n.split(/[/\\]/).pop().toLowerCase();for(let t of Object.keys(_t)){if(!e.startsWith(`${t}-`))continue;let r=new RegExp(`^${t}-[a-z-]+?-\\d+-(?:normal|italic)`).exec(e);if(r)return r[0]}return null}function Wr(n){return n.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}J();J();var je=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:(r,...o)=>{this.options.debug}},this.patterns={selectors:{...Ct.selectors,...this.options.customPatterns?.selectors},themes:{...Ct.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 r=t.split("-").filter(i=>i.length>0);if(r.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let o=r.map((i,a)=>{let l=i.replace(/[^a-zA-Z0-9]/g,"");return l?a===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!o||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(o)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${o}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(o)?`${o}Var`:o}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,r){let o=[],s,i=this.pathResolver.normalizePath(t),a=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(s=l.exec(a))!==null;){let[,c,u,p]=s;if(!c||!p)continue;let d=u.match(this.patterns.themes.themeIcon),f=u.match(this.patterns.themes.themeIsDark),g={name:c,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:d?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${p})`),o.push(g),r.themes.set(c,{name:c,displayName:p,isDark:g.isDark,file:i,variables:new Set,meta:g.meta})}return o.length>0&&this._debug(`Extracted ${o.length} themes from ${i}`),o}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(o=>{let s=o.slice(1);s.startsWith("_")||t.classes.add(s)})}extractVariables(e,t,r){(e.match(this.patterns.selectors.variable)||[]).forEach(s=>{s.startsWith("--")&&s.length>2?r==="framework"?t.variables.framework.add(s):t.variables.consumer.add(s):this._debug(`Skipping invalid CSS variable: ${s}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(o=>{let s=o.replace("@keyframes","").trim();s&&t.keyframes.add(s)})}validateCSS(e){let t=[],r=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return r&&r.forEach(s=>{t.push(`Possible malformed CSS variable: ${s}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(s=>{if(!s.includes("--theme-label")&&s.includes("--")){let i=s.match(/\.([a-z][a-z0-9-]+)/)?.[1];i&&t.push(`Theme class "${i}" missing --theme-label`)}}),t}extractAll(e,t,r="consumer"){let o={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},s=this.extractThemes(e,t,o);this.extractClasses(e,o),this.extractVariables(e,o,r),this.extractKeyframes(e,o);let i=this.validateCSS(e);return{themes:s,classes:Array.from(o.classes),variables:{framework:Array.from(o.variables.framework),consumer:Array.from(o.variables.consumer),all:[...Array.from(o.variables.framework),...Array.from(o.variables.consumer)].sort()},keyframes:Array.from(o.keyframes),warnings:i}}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||"")}};var Vr="@donotdev/components/styles",bs=/@import\s+['"](\.[^'"]+)['"]\s*;/g,Ne=class extends pe{constructor(e,t,r={}){super(t,r),this.cssExtractor=e||new je(t,{debug:r.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:r}=e;this.logger.debug(`Scanning ${t.length} framework + ${r.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",r),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),r.length>0?(this.logger.debug(`Consumer files found: ${r.length}`),this.logger.debug("Consumer files:",r)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t);let o=await this._processConsumerFiles(r),s=this._serializeThemes(),i=Ur({frameworkCss:this._readFrameworkTokenCss(),appCss:o});return this.logger.debug("Theme font families:",i),this.logger.debug(`Discovered ${s.length} themes:`,s.map(a=>a.name)),{themes:s,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(),fontFamilies:i}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return At.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 r=await this.pathResolver.read(t,{format:"text"}),o=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(r,o,this.discovered),this.cssExtractor.extractClasses(r,this.discovered),this.cssExtractor.extractVariables(r,this.discovered,"framework"),this.cssExtractor.extractKeyframes(r,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(o)}`)}catch(r){this.logger.debug(`Error scanning framework file ${t}: ${r.message}`)}}async _processConsumerFiles(e){let t=[];for(let r of e)try{let o=await this.pathResolver.read(r,{format:"text"});t.push(o);let s=this.pathResolver.normalizePath(r);this.cssExtractor.extractThemes(o,s,this.discovered),this.cssExtractor.extractVariables(o,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(s)}`)}catch(o){this.logger.debug(`Error scanning consumer file ${r}: ${o.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(Vr,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw H("dndev-theme",`cannot resolve ${Vr} (framework font defaults), resolved from @donotdev/ui: check that @donotdev/ui and @donotdev/components are installed`,"missing-required-resource");let t=new Set,r=o=>{if(t.has(o))return"";t.add(o);let s=this.pathResolver.readSync(o,{format:"text"});if(typeof s!="string")throw H("dndev-theme",`cannot read ${o} (framework font defaults)`,"missing-required-resource");let i=this.pathResolver.getDirname(o);return s.replace(bs,(a,l)=>r(this.pathResolver.resolvePath(l,i)))};return r(e)}_addEssentialThemes(){At.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}))}};q();var ws=3,Ot="<!-- DNDEV_FONT_PRELOADS -->",Es=/url\(\s*['"]?([^'")]+)['"]?\s*\)/g;function Hr(n={}){let{debug:e=!1,i18nStore:t}=n;if(!t)throw new Error("[dndev] createViteFontPreloadPlugin: options.i18nStore is required (createVitePlugins passes the i18n plugin's, createI18nStore).");let r=M("font-preload",e,!1),o,s={},i=!1,a=null,l=[];return{name:"vite-font-preload-plugin",enforce:"post",configResolved(c){i=c.command==="build",s={root:c.root,base:c.base&&c.base!=="/"?c.base.replace(/\/$/,""):"",outDir:c.build?.outDir??"dist"};try{o=D.getInstance()}catch(u){r.debug(`Font preload: PathResolver not ready: ${u?.message}`)}},async buildStart(){if(!i||!o||!o.getAppRoot())return;let{supportedLanguages:u}=await t.ready(),p=new Ne(null,o,{debug:e}),{fontFamilies:d}=await p.discoverThemes(),f=Gr({families:d,locales:u});a=f.stems,r.debug(`Font filter: ${f.fontStems.size} font(s) [${[...f.fontStems].join(", ")}], ${f.subsets.size} subset(s), ${a.size} allowed stem(s)`)},generateBundle(c,u){if(!a)return;let p=h=>Tt(h)!==null,d=h=>a.has(Tt(h)),f=0,g=0;for(let h of Object.keys(u))u[h].type!=="asset"||!p(h)||(h.endsWith(".woff")?(delete u[h],f++):h.endsWith(".woff2")&&!d(h)&&(delete u[h],g++));r.debug(`Font filter: deleted ${f} .woff + ${g} .woff2 from bundle`);for(let[h,P]of Object.entries(u)){if(P.type!=="asset"||!h.endsWith(".css")||typeof P.source!="string")continue;let R=P.source,E=R.replace(/@font-face\s*\{[\s\S]*?\}/g,S=>{let C=[...S.matchAll(Es)].map(k=>k[1]);return C.some(p)?C.some(d)?Wr(S):"":S});E!==R&&(P.source=E)}let w=s.base||"",m=[];for(let[h,P]of Object.entries(u)){if(P.type!=="asset"||!h.endsWith(".woff2")||!d(h))continue;let R=w?`${w}/${h}`:`/${h}`;m.push(R)}l=m.slice(0,ws)},writeBundle(){if(!i||!l.length)return;let c=o||D.getInstance(),u=s.root||process.cwd(),p=s.outDir||"dist",d=c.resolvePath(`${p}/index.html`,u);try{if(!c.pathExists(d)){r.debug(`Font preload: index.html not found at ${d}`);return}let f=c.readSync(d,{format:"text"}),g=l.map(w=>`<link rel="preload" as="font" href="${w}" type="font/woff2" crossorigin="anonymous" />`).join(`
327
- `);if(f.includes(Ot))f=f.replace(Ot,`${Ot}
328
- ${g}`);else{let w=f.indexOf("<!-- Fonts:"),m=w!==-1?f.indexOf("-->",w)+3:f.indexOf("</head>");m!==-1&&(f=f.slice(0,m)+`
329
- ${g}`+f.slice(m))}c.writeSync(d,f,{overwrite:!0}),r.debug(`Font preload: injected ${l.length} link(s)`)}catch(f){r.debug(`Font preload: write failed: ${f?.message}`)}}}}import{existsSync as Zr,readFileSync as Xr,writeFileSync as xs}from"node:fs";import{join as Qr}from"node:path";var Ss="/(.*)",Ft=Object.freeze(["default-src","script-src","style-src","img-src","font-src","connect-src","media-src","worker-src","manifest-src","frame-src","object-src","base-uri","form-action","frame-ancestors"]),Rs=Object.freeze({"default-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"frame-src":["'none'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"]}),Jr=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),en=Object.freeze({"@donotdev/supabase":{"connect-src":["https://*.supabase.co","wss://*.supabase.co"]},"@donotdev/firebase":{"script-src":["https://accounts.google.com","https://apis.google.com"],"connect-src":["https://identitytoolkit.googleapis.com","https://securetoken.googleapis.com","https://www.googleapis.com","https://*.googleapis.com","https://*.firebaseio.com"],"frame-src":["https://accounts.google.com"]}}),Ps=Object.freeze([{key:"X-Content-Type-Options",value:"nosniff"},{key:"X-Frame-Options",value:"DENY"},{key:"X-XSS-Protection",value:"1; mode=block"},{key:"Referrer-Policy",value:"strict-origin-when-cross-origin"},{key:"Permissions-Policy",value:"geolocation=(), microphone=(), camera=()"}]),$s=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),Cs=31536e3,_s=86400,tn=3600,qr=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(n=>`/assets/:path*.${n}`),"next-export":["/_next/static/:path*"],next:[]}),As=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),Ns=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${tn}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),Kr=Object.freeze(["csp","cache"]);function ct(n,e=!1){return`public, max-age=${n}${e?", immutable":""}`}function It(n,e){return{source:n,headers:[{key:"Cache-Control",value:e}]}}var Yr=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),Ds=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function ks(n,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${n}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!Yr.includes(e)&&!Ds.test(e))throw new Error(`[dndev] appConfig.headers.csp['${n}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${Yr.join(" ")} or a hash like 'sha256-<base64>').`)}function Ts(n){if(n===void 0)return{csp:{},cache:[]};if(!n||typeof n!="object"||Array.isArray(n))throw new Error("[dndev] appConfig.headers must be an object.");for(let r of Object.keys(n))if(!Kr.includes(r))throw new Error(`[dndev] appConfig.headers.${r} is not a header option (allowed: ${Kr.join(", ")}).`);let e=n.csp??{};for(let[r,o]of Object.entries(e)){if(!Ft.includes(r))throw new Error(`[dndev] appConfig.headers.csp['${r}'] is not a CSP directive the framework merges (allowed: ${Ft.join(", ")}).`);if(!Array.isArray(o))throw new Error(`[dndev] appConfig.headers.csp['${r}'] must be an array of sources.`);for(let s of o)ks(r,s)}let t=n.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let r of t){if(typeof r?.source!="string"||!r.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(r?.source)}).`);if(!Number.isInteger(r.maxAge)||r.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${r.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(r.maxAge)}).`)}return{csp:e,cache:t}}function Os({csp:n={},providers:e=[],target:t}){if(!(t in Jr))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...Ft.map(o=>{let s=[...o==="script-src"?Jr[t]:Rs[o]??[],...e.flatMap(l=>en[l]?.[o]??[]),...n[o]??[]],i=[...new Set(s)],a=i.length>1?i.filter(l=>l!=="'none'"):i;return a.length>0?`${o} ${a.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function rn({appConfig:n,target:e,providers:t=[],pwa:r=!1}){if(!(e in qr))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:o,cache:s}=Ts(n?.headers),i=[{key:"Content-Security-Policy",value:Os({csp:o,providers:t,target:e})},...n?.seo===!1?[$s]:[],...Ps].map(a=>({...a}));return[{source:Ss,headers:i},...qr[e].map(a=>It(a,ct(Cs,!0))),...As.map(a=>It(`/:path*.${a}`,ct(_s))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:ct(tn)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...r?Ns.map(a=>({source:a.source,headers:a.headers.map(l=>({...l}))})):[],...s.map(a=>It(a.source,ct(a.maxAge,a.immutable===!0)))]}function nn(n){let e=Qr(n,"package.json");if(!Zr(e))return[];let t=JSON.parse(Xr(e,"utf8")),r={...t.dependencies,...t.devDependencies};return Object.keys(en).filter(o=>!!r[o])}function Is(n){let e=Qr(n,"vercel.json");if(!Zr(e))return null;try{return{path:e,config:JSON.parse(Xr(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function on({appRoot:n,rules:e,ci:t,logger:r}){let o=Is(n);if(!o)return"absent";if(JSON.stringify(o.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${o.path}: "headers" differ from the framework header policy (appConfig.headers, appConfig.seo). The host reads the committed file, so this deploy would serve stale headers. Run the app locally (dev or build) to regenerate vercel.json, then commit it.`);let s=`${JSON.stringify({...o.config,headers:e},null,2)}
330
- `;return xs(o.path,s),r?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function sn({appConfig:n,pwa:e,debug:t,verbose:r}){let o=M("host-headers",t,r);return{name:"dndev-host-headers",configResolved(s){on({appRoot:s.root,rules:rn({appConfig:n,target:"vite",providers:nn(s.root),pwa:e===!0}),ci:!!(process.env.CI||process.env.VERCEL),logger:o})}}}J();J();q();J();function Fs(n){if(!n)return[];let e=D.getInstance(),t=new Set;try{let r=e.resolvePackage("@donotdev/core",n);if(!r)return[];let o=e.getDirname(e.getDirname(r)),s;try{s=e.readdirSync(o)}catch{return[]}for(let i of s)try{let a=e.resolvePath(`${i}/package.json`,o),l=e.readSync(a,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[c,u]of Object.entries(l.peerDependenciesMeta))u?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function Ms(n){if(!n)return[];let e=D.getInstance();try{let t=e.resolvePath("package.json",n),r=e.readSync(t,{format:"json"});if(!r)return[];let o=new Set;if(r.peerDependenciesMeta)for(let[s,i]of Object.entries(r.peerDependenciesMeta))i?.optional&&o.add(s);if(r.optionalDependencies)for(let s of Object.keys(r.optionalDependencies))o.add(s);return Array.from(o)}catch{return[]}}function Ls(n){let e=we.optionalFeatures||[],t=Fs(n),r=Ms(n);return[...new Set([...e,...t,...r])]}function js(n){let e=D.getInstance();try{let t=e.resolvePath("package.json",n),r=e.readSync(t,{format:"json"});return r?new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.devDependencies||{})]):new Set}catch{return new Set}}function zs(n,e,t){if(t.resolvePackage(n,e||void 0))return!0;let r=n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0],o=e;for(let s=0;s<10;s++){let i=t.resolvePath(`node_modules/${r}`,o);if(t.pathExists(i))return!0;let a=t.getDirname(o);if(a===o)break;o=a}return!1}function ut(n){let e=Ls(n),t=[],r=[],o=D.getInstance(),s=js(n);for(let i of e)i.startsWith("@donotdev/")?s.has(i)?r.push(i):t.push(i):s.has(i)&&zs(i,n,o)?r.push(i):t.push(i);return{missing:t,installed:r}}var pt=class extends pe{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[r,o]of Object.entries(e)){for(let s of Object.keys(o))t.includes(s)||delete o[s];Object.keys(o).length===0&&delete e[r]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),r=this.pathResolver.getRepoRoot();if(!t||t===r)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${r})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${r}`);let o=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${o.eager.length}, lazy: ${o.lazy.length}, framework eager: ${o.framework?.eager?.length||0}, framework lazy: ${o.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let s=ot("i18n"),i=o.eager||[],a=o.lazy||[],l=(this.options.additionalPaths||[]).map(_=>{let O=_.endsWith(".json")?_:`${_}/*_*.json`;return this.pathResolver.resolveAppPath(O)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let c=o.framework?.eager||[],u=o.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${i.join(", ")}, lazy: ${a.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${u.join(", ")}`),c.length===0&&u.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),d=this.pathResolver.normalizePath(r),f=(_,O)=>{let F=this.pathResolver.normalizePath(_),B=this.pathResolver.normalizePath(O);return F.startsWith(B)?F.slice(B.length+1):F},g=i.map(_=>f(_,t)),m=[...a,...l].map(_=>f(_,t)),h=c.map(_=>f(_,r)),P=u.map(_=>f(_,r)),R={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},E=await this.pathResolver._globWithNormalization(g,R),S=await this.pathResolver._globWithNormalization(m,R),C={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r,ignore:s.ignore?.filter(_=>_!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${r}, ignore: ${JSON.stringify(C.ignore)}`);let k=await this.pathResolver._globWithNormalization(h,C),y=await this.pathResolver._globWithNormalization(P,C);this.logger.debug(`Found ${E.length} eager, ${S.length} lazy, ${k.length} framework eager, ${y.length} framework lazy files`),k.length>0?this.logger.debug(`Framework eager files (first 3): ${k.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),y.length>0?this.logger.debug(`Framework lazy files (first 3): ${y.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${u.join(", ")}`);let T=[...new Set([...E,...S,...k,...y])],$=new Set([...E,...k]),v={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:G}=ut(t),A=new Set(G.filter(_=>_.startsWith("@donotdev/")).map(_=>_.replace("@donotdev/","")));A.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...A].join(", ")}] (packages not installed)`);let L=new Map,j=[...k,...y];for(let _ of j){let O=this._processTranslationFile(_,k.includes(_),t);if(O){if(A.has(O.namespace))continue;let F=`${O.namespace}_${O.language}`;L.set(F,O),v.allNamespaces.add(O.namespace),v.supportedLanguages.add(O.language),k.includes(_)&&v.eagerNamespaces.add(O.namespace)}}let z=new Set;for(let _ of T){if(j.includes(_))continue;let O=this._processTranslationFile(_,$.has(_),t);if(O){let{namespace:F,language:B,importPath:V,content:de}=O,Ce=`${O.namespace}_${O.language}`;if(L.has(Ce)){let ke=L.get(Ce);O.content=this._mergeTranslations(ke.content,de)}v.allNamespaces.add(F),v.supportedLanguages.add(B),z.add(B),$.has(_)&&v.eagerNamespaces.add(F),v.mapping[F]||(v.mapping[F]={}),v.mapping[F][B]=V,O.content&&(v.content[F]||(v.content[F]={}),v.content[F][B]=O.content),v.files.push({path:_,relativePath:this.pathResolver.getRelativePath(_),namespace:F,language:B,eager:$.has(_),size:O.content?JSON.stringify(O.content).length:0})}}for(let[_,O]of L){let F=_.lastIndexOf("_"),B=_.slice(0,F),V=_.slice(F+1);z.size>0&&!z.has(V)||(!v.mapping[B]||!v.mapping[B][V])&&(v.mapping[B]||(v.mapping[B]={}),v.mapping[B][V]=O.importPath,v.content[B]||(v.content[B]={}),v.content[B][V]=O.content,v.files.push({path:O.absolutePath,relativePath:this.pathResolver.getRelativePath(O.absolutePath),namespace:B,language:V,eager:v.eagerNamespaces.has(B),size:O.content?JSON.stringify(O.content).length:0}))}let K=z.size>0?[...z].sort():[this.options.fallbackLanguage],X=this._getLanguageAllowlist(),W=K;if(X){let _=K.filter(F=>X.includes(F));W=_.length>0?_:[this.options.fallbackLanguage],this._restrictByLanguage(v.mapping,W),this._restrictByLanguage(v.content,W),v.files=v.files.filter(F=>W.includes(F.language));let O=new Set(Object.keys(v.mapping));v.allNamespaces=new Set([...v.allNamespaces].filter(F=>O.has(F))),v.eagerNamespaces=new Set([...v.eagerNamespaces].filter(F=>O.has(F))),this.logger.debug(`I18n restricted by i18n.only [${X.join(", ")}]: languages [${W.join(", ")}], namespaces ${O.size}`)}let se=[...new Set(W.map(Nt))];return{mapping:v.mapping,content:v.content,eagerNamespaces:[...v.eagerNamespaces].sort(),allNamespaces:[...v.allNamespaces].sort(),supportedLanguages:W,fallbackLanguage:this.options.fallbackLanguage,flagCodes:se,files:v.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[Nt(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 r=await this._processFiles([]);this.cache={...r,timestamp:Date.now()};let o=Date.now()-t;return this.logger.debug(`Discovery completed in ${o}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(r){throw this.logger.error(`I18n discovery failed: ${r.message}`),r}}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,r){let o=e.split("/").pop()||e.split("\\").pop()||"",s,i,a=o.match(/^(.+)_([^_.]+)\.json$/);if(!a)return this.logger.debug(`Invalid translation file name format: ${o}`),null;if([,s,i]=a,!s||!i)return this.logger.debug(`Invalid namespace or language in file: ${o}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),u;try{if(u=this.pathResolver.readSync(e,{format:"json"}),!u)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:s,language:i,importPath:c,absolutePath:e,content:u}}_mergeTranslations(e,t){let r={...e};for(let[o,s]of Object.entries(t))typeof s=="object"&&s!==null&&!Array.isArray(s)?r[o]=this._mergeTranslations(r[o]||{},s):r[o]=s;return r}};var an={isEmpty:n=>!n.mapping||Object.keys(n.mapping).length===0,generateModule:(n,e,t="i18n",r=!1)=>{let{mapping:o,eagerNamespaces:s,supportedLanguages:i,fallbackLanguage:a,stats:l,content:c={},files:u=[]}=n,p=r?Object.keys(c):s,d={};for(let h of p)c[h]&&(d[h]=c[h]);let f=[...new Set([...s,...Object.keys(c)])],g={mapping:o,languages:i,eager:r?f:s,fallback:a,content:d,storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:l?.totalFiles||0,totalNamespaces:l?.totalNamespaces||0,totalLanguages:l?.totalLanguages||0,eagerNamespaces:l?.eagerNamespaces||0,generatedAt:new Date().toISOString()},debug:e},w=[];if(!r)for(let[h,P]of Object.entries(o)){if(s.includes(h))continue;let R=[];for(let E of Object.keys(P))R.push(` '${E}': () => import('virtual:i18n-lazy-${h}-${E}')`);R.length>0&&w.push(` '${h}': {
331
- ${R.join(`,
324
+ `},generateInspection:o=>{let{env:e,mode:t}=o;return["/**"," * Generated Environment Variables",` * Mode: ${t}`,` * Generated at: ${new Date().toISOString()}`,` * Total variables: ${Object.keys(e).length}`," */","","```json",JSON.stringify(e,null,2),"```"].join(`
325
+ `)},generateManifest:o=>({totalVars:Object.keys(o?.env||{}).length,mode:o?.mode||"development",variables:Object.keys(o?.env||{}),timestamp:Date.now()}),logStats:(o,e,t)=>{let n=Object.keys(o.env).length;t&&t.info(`${e} Env: ${n} VITE_* variables`)}},Ft=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 n={...Ms(this.mode,e,"VITE_")};return this.mode==="production"&&(delete n.VITE_USE_FIREBASE_EMULATOR,delete n.VITE_FIREBASE_EMULATOR_HOST,delete n.VITE_FIREBASE_AUTH_EMULATOR_HOST,delete n.VITE_FIREBASE_FIRESTORE_EMULATOR_HOST,delete n.VITE_FIREBASE_FUNCTIONS_EMULATOR_PORT),n.MODE=this.mode,n.DEV=this.mode==="development",n.PROD=this.mode==="production",n.SSR=!1,{env:n,mode:this.mode,source:`${e}/.env`,errors:[]}}catch(e){return{env:{},mode:this.mode,source:"error",errors:[e.message]}}}};function Vn(o={}){return we({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:V.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:Hn,manifestFileName:ve.manifests.env,configKey:"env",createDiscovery:(e,t)=>new Ft(e,{...t,mode:o.mode||t.mode||"development"})})({...o,disableHmr:!0})}function Ls(o,e,t,n={}){let{minLength:r=0,excludeEmpty:s=!0,customFilter:a}=n;return Array.from({length:t},(i,l)=>{let c=`${e}.${l}`;return o(c)}).filter((i,l)=>{let c=`${e}.${l}`;return!(i===c||s&&i.trim()===""||i.length<r||a&&!a(i,l))})}var Ze=(o,e,t)=>({tag:"meta",attributes:{[o]:e,content:t}});var js=20,Jn={defaultValue:""};function zs(o,e,t){if(o!==null)return o!==void 0?o:t(e,Jn)||void 0}function Bs(o,e){let t=s=>o(s,Jn),n=s=>t(`${e}:meta.${s}`)||void 0,r=Ls(t,`${e}:meta.keywords`,js);return{fullTitle:n("fullTitle"),image:n("image"),type:n("type"),keywords:r.length>0?r:void 0,author:n("author")}}function qn(o){let{meta:e,ns:t,defaultNs:n,t:r,siteName:s}=o,a=e.seo;if(!t&&!n)return{title:a?.fullTitle||s};let i=t?zs(a?.title,`${t}:title`,r):a?.title??void 0;return{title:a?.fullTitle||(t?Bs(r,t).fullTitle:void 0)||(i?`${i} | ${s}`:s),...i&&{pageTitle:i}}}var Kn={enabled:!0,themeColor:"#2563eb",backgroundColor:"#ffffff",includeManifestIcons:!0,includeMSIcons:!1};function Yn(o){let e=t=>o(t)?t:void 0;return{svg:e("/favicon.svg"),ico:e("/favicon.ico"),png16:e("/favicon-16x16.png"),png32:e("/favicon-32x32.png"),apple180:e("/apple-touch-icon.png"),android192:e("/icon-192x192.png"),android512:e("/icon-512x512.png")}}var ze=(o,e,t)=>({tag:"link",attributes:{rel:"icon",type:e,...t&&{sizes:t},href:o}});function Zn(o,e){let{enabled:t,appName:n,themeColor:r,includeManifestIcons:s,includeMSIcons:a}=e;if(t===!1)return[];let i=[];return o.svg&&i.push(ze(o.svg,"image/svg+xml")),o.ico&&i.push(ze(o.ico,"image/x-icon")),o.png16&&i.push(ze(o.png16,"image/png","16x16")),o.png32&&i.push(ze(o.png32,"image/png","32x32")),o.apple180&&(i.push({tag:"link",attributes:{rel:"apple-touch-icon",sizes:"180x180",href:o.apple180}}),n&&i.push(Ze("name","apple-mobile-web-app-title",n))),s&&(o.android192&&i.push(ze(o.android192,"image/png","192x192")),o.android512&&i.push(ze(o.android512,"image/png","512x512"))),a&&o.png32&&(i.push(Ze("name","msapplication-TileImage",o.png32)),r&&i.push(Ze("name","msapplication-TileColor",r))),r&&i.push(Ze("name","theme-color",r)),i.push(Ze("name","color-scheme","light dark")),i}var ut="dndev-fonts";function Mt(o){return o.map(e=>({tag:"link",attributes:{rel:"preload",as:"font",type:"font/woff2",href:e,crossorigin:"anonymous"}}))}Y();function Xn({appConfig:o}){let e=o.favicon;return{name:"dndev-favicon",transformIndexHtml(){if(e===!1)return[];let t=O.getInstance();return Zn(Yn(s=>t.pathExists(t.resolveAppPath(`public${s}`))),{...Kn,appName:o.app?.name,...e}).map(({tag:s,attributes:a})=>({tag:s,attrs:a,injectTo:"head"}))}}}q();q();var Be=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:(n,...r)=>{this.options.debug}},this.patterns={selectors:{...Tt.selectors,...this.options.customPatterns?.selectors},themes:{...Tt.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 n=t.split("-").filter(a=>a.length>0);if(n.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=n.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,n){let r=[],s,a=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(s=l.exec(i))!==null;){let[,c,u,p]=s;if(!c||!p)continue;let d=u.match(this.patterns.themes.themeIcon),f=u.match(this.patterns.themes.themeIsDark),g={name:c,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:d?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${p})`),r.push(g),n.themes.set(c,{name:c,displayName:p,isDark:g.isDark,file:a,variables:new Set,meta:g.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 s=r.slice(1);s.startsWith("_")||t.classes.add(s)})}extractVariables(e,t,n){(e.match(this.patterns.selectors.variable)||[]).forEach(s=>{s.startsWith("--")&&s.length>2?n==="framework"?t.variables.framework.add(s):t.variables.consumer.add(s):this._debug(`Skipping invalid CSS variable: ${s}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let s=r.replace("@keyframes","").trim();s&&t.keyframes.add(s)})}validateCSS(e){let t=[],n=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return n&&n.forEach(s=>{t.push(`Possible malformed CSS variable: ${s}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(s=>{if(!s.includes("--theme-label")&&s.includes("--")){let a=s.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,n="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},s=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,n),this.extractKeyframes(e,r);let a=this.validateCSS(e);return{themes:s,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||"")}};var Qn="@donotdev/components/styles",Us=/@import\s+['"](\.[^'"]+)['"]\s*;/g,Oe=class extends fe{constructor(e,t,n={}){super(t,n),this.cssExtractor=e||new Be(t,{debug:n.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:n}=e;this.logger.debug(`Scanning ${t.length} framework + ${n.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",n),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),n.length>0?(this.logger.debug(`Consumer files found: ${n.length}`),this.logger.debug("Consumer files:",n)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t);let r=await this._processConsumerFiles(n),s=this._serializeThemes(),a={framework:this._readFrameworkTokenCss(),app:r};return this.logger.debug(`Discovered ${s.length} themes:`,s.map(i=>i.name)),{themes:s,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(),fontCss:a}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return Ot.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 n=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(n,r,this.discovered),this.cssExtractor.extractClasses(n,this.discovered),this.cssExtractor.extractVariables(n,this.discovered,"framework"),this.cssExtractor.extractKeyframes(n,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(n){this.logger.debug(`Error scanning framework file ${t}: ${n.message}`)}}async _processConsumerFiles(e){let t=[];for(let n of e)try{let r=await this.pathResolver.read(n,{format:"text"}),s=this.pathResolver.normalizePath(n);t.push({file:this.pathResolver.getRelativePath(s),css:r}),this.cssExtractor.extractThemes(r,s,this.discovered),this.cssExtractor.extractVariables(r,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(s)}`)}catch(r){this.logger.debug(`Error scanning consumer file ${n}: ${r.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(Qn,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw H("dndev-theme",`cannot resolve ${Qn} (framework font defaults), resolved from @donotdev/ui: check that @donotdev/ui and @donotdev/components are installed`,"missing-required-resource");let t=new Set,n=r=>{if(t.has(r))return"";t.add(r);let s=this.pathResolver.readSync(r,{format:"text"});if(typeof s!="string")throw H("dndev-theme",`cannot read ${r} (framework font defaults)`,"missing-required-resource");let a=this.pathResolver.getDirname(r);return s.replace(Us,(i,l)=>n(this.pathResolver.resolvePath(l,a)))};return n(e)}_addEssentialThemes(){Ot.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}))}};q();import{createHash as Sa}from"node:crypto";var no="src/**/*.{ts,tsx,js,jsx,mjs,cjs}",Lt=/\/\*[\s\S]*?\*\//g,Ws=/(^|\s)\/\/.*$/gm,Gs=/<!--[\s\S]*?-->/g,Hs=/(?:from\s*|import\s*\(\s*|require\s*\(\s*)['"]next\/font(?:\/[^'"]*)?['"]/g,Vs=/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)['"]@fontsource(?:-variable)?\/[^'"]*['"]/g,Js=/@import\s+(?:url\(\s*)?['"]?@fontsource(?:-variable)?\/[^'";)]*/g,eo=/@font-face\b/g,to="Name the family in src/themes.css (e.g. --font-sans: Manrope, 'Manrope Fallback', sans-serif;) and keep @fontsource-variable/<slug> or @fontsource/<slug> in package.json, or declare its woff2 files in appConfig.fonts.",qs={"next-font":{message:`imports next/font: its preload cannot work in a framework app (page files carry the \`.next.\` marker, Next's font manifest is keyed without it) and it is a second font pipeline. The framework ships the theme's fonts (preloaded, inline @font-face, size-matched fallback). ${to}`},fontsource:{message:`imports an @fontsource package: the framework ships the fonts the theme names (preloaded, inline @font-face, hashed /fonts/ files). Remove the import. ${to}`},"font-face":{message:"declares @font-face: the framework writes every @font-face of the app (one place, preloaded, hashed files). Declare the woff2 files in appConfig.fonts (src/config/app.ts: { category, faces: [{ file, weight, unicodeRange? }] }) and name the family in src/themes.css."}};function Ks(o,e){let t=o;for(let n of e)t=t.replace(n,(r,s)=>{let a=typeof s=="string"?s:"";return a+r.slice(a.length).replace(/[^\n]/g," ")});return t}var Ys=(o,e)=>o.slice(0,e).split(`
326
+ `).length;function Zs(o){let e=[];for(let{file:t,content:n}of o){if(/\.generated\.[a-z]+$/.test(t))continue;let r=t.endsWith(".css"),s=t.endsWith(".html"),a=Ks(n,s?[Gs,Lt]:r?[Lt]:[Lt,Ws]),i=r?[["fontsource",Js],["font-face",eo]]:s?[["font-face",eo]]:[["next-font",Hs],["fontsource",Vs]];for(let[l,c]of i)for(let u of a.matchAll(c))e.push({file:t,line:Ys(a,u.index),rule:l})}return e}function oo(o){let e=Zs(o);if(e.length===0)return;let t=e.map(({file:n,line:r,rule:s})=>` ${n}:${r} ${qs[s].message}`);throw H("dndev-fonts",`the app loads fonts itself; the framework font plan is the one way:
327
+ ${t.join(`
328
+ `)}`,"configuration-error")}import{brotliDecompressSync as Xs}from"node:zlib";var ro="aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ",Qs={"sans-serif":{locals:["Arial","Liberation Sans"],azAvgWidth:934.5116279069767,unitsPerEm:2048},serif:{locals:["Times New Roman","Liberation Serif"],azAvgWidth:854.3953488372093,unitsPerEm:2048}},ea={0:"cmap",1:"head",2:"hhea",3:"hmtx"},ta=63,so=48,na=2001684018;function ao(o,e){let t=0;for(let n=0;n<5;n++){let r=o[e+n];if(t=t*128+(r&127),(r&128)===0)return[t,e+n+1]}throw new Error("woff2: invalid UIntBase128")}function oa(o){if(o.length<so||o.readUInt32BE(0)!==na)throw new Error("woff2: bad signature");if(o.readUInt32BE(4)===1953784678)throw new Error("woff2: font collections are not supported");let e=o.readUInt16BE(12),t=o.readUInt32BE(20),n=so,r=[];for(let l=0;l<e;l++){let c=o[n++],u=c&63,p=c>>6,d=ea[u]??`#${u}`;u===ta&&(d=o.toString("latin1",n,n+4),n+=4);let f;[f,n]=ao(o,n);let g=u===10||u===11?p!==3:p!==0,v=f;g&&([v,n]=ao(o,n)),r.push({tag:d,length:v,transformed:g})}let s=Xs(o.subarray(n,n+t)),a=new Map,i=0;for(let{tag:l,length:c,transformed:u}of r)a.set(l,{data:s.subarray(i,i+c),transformed:u}),i+=c;return a}function ra(o){let e=o.readUInt16BE(2),t=[];for(let u=0;u<e;u++){let p=4+u*8,d=o.readUInt16BE(p),f=o.readUInt16BE(p+2),g=o.readUInt32BE(p+4);(d===0||d===3&&(f===1||f===10))&&t.push({offset:g,format:o.readUInt16BE(g)})}let n=t.find(u=>u.format===12)??t.find(u=>u.format===4);if(!n)throw new Error("font: no Unicode cmap (format 4 or 12)");let r=n.offset;if(n.format===12){let u=o.readUInt32BE(r+12);return p=>{for(let d=0;d<u;d++){let f=r+16+d*12,g=o.readUInt32BE(f),v=o.readUInt32BE(f+4);if(p>=g&&p<=v)return o.readUInt32BE(f+8)+(p-g)}return 0}}let s=o.readUInt16BE(r+6)/2,a=r+14,i=a+s*2+2,l=i+s*2,c=l+s*2;return u=>{for(let p=0;p<s;p++){if(u>o.readUInt16BE(a+p*2))continue;let d=o.readUInt16BE(i+p*2);if(u<d)return 0;let f=o.readInt16BE(l+p*2),g=c+p*2,v=o.readUInt16BE(g);if(v===0)return u+f&65535;let h=o.readUInt16BE(g+v+(u-d)*2);return h===0?0:h+f&65535}return 0}}function lo(o){let e=oa(o);for(let c of["head","hhea","hmtx","cmap"])if(!e.has(c))throw new Error(`font: missing ${c} table`);let t=e.get("head").data,n=e.get("hhea").data,r=e.get("hmtx"),s=n.readUInt16BE(34),a=c=>{let u=Math.min(c,s-1);return r.transformed?r.data.readUInt16BE(1+u*2):r.data.readUInt16BE(u*4)},i=ra(e.get("cmap").data),l=0;for(let c of ro){let u=i(c.codePointAt(0));if(u===0)throw new Error(`font: no glyph for '${c}'`);l+=a(u)}return{unitsPerEm:t.readUInt16BE(18),ascent:n.readInt16BE(4),descent:n.readInt16BE(6),lineGap:n.readInt16BE(8),azAvgWidth:l/ro.length}}var io=o=>`${Math.abs(o*100).toFixed(2)}%`;function pt(o){return`${o} Fallback`}function co({family:o,category:e,metrics:t}){let n=Qs[e];if(!n)throw new Error(`font fallback: unknown category '${e}'`);let{unitsPerEm:r,ascent:s,descent:a,lineGap:i,azAvgWidth:l}=t,c=l/r/(n.azAvgWidth/n.unitsPerEm),u=d=>io(d/(r*c)),p=pt(o);return[`/* ${p}: ${n.locals[0]} size-matched to ${o} */`,"@font-face {",` font-family: '${p}';`,` src: ${n.locals.map(d=>`local('${d}')`).join(", ")};`,` ascent-override: ${u(s)};`,` descent-override: ${u(a)};`,` line-gap-override: ${u(i)};`,` size-adjust: ${io(c)};`,"}"].join(`
329
+ `)}var sa=2001684018,dt=400;function gt(o){return o.trim().toLowerCase().replace(/\s+/g,"-")}function aa(o){let[e,t=e]=String(o).trim().split(/\s+/).map(Number);return[e,t]}var ft=([o,e],t)=>t>=o&&t<=e;function uo(o,e){if(e.some(s=>ft(s,o)))return o;let t=[...new Set(e.flat())],n=(s=1/0)=>t.filter(a=>a>o&&a<=s).sort((a,i)=>a-i)[0],r=()=>t.filter(s=>s<o).sort((s,a)=>a-s)[0];return o>=400&&o<=500?n(500)??r()??n():o<400?r()??n():n()??r()}function ge(o){return H("dndev-fonts",o,"configuration-error")}function ia(o){return!!(o&&o.length>=4&&o.readUInt32BE(0)===sa)}var la=o=>o==="serif"?"serif":"sans-serif";function ca({family:o,packageName:e,dir:t,pathResolver:n}){let r=n.readSync(n.resolvePath("metadata.json",t),{format:"json"}),s=n.readSync(n.resolvePath("unicode.json",t),{format:"json"});if(!r||!s)throw ge(`${e}: metadata.json or unicode.json missing in ${t} (not a fontsource package?).`);if(String(r.family).toLowerCase()!==o.toLowerCase())throw ge(`${e} is the family '${r.family}', the font stack names '${o}'. Write the family as the package names it.`);let a=e.startsWith("@fontsource-variable/"),i=r.variable?.wght;if(a&&!i)throw ge(`${e} has no wght axis: use @fontsource/${r.id} (static weights).`);let l=a?[Number(i.min),Number(i.max)]:null,c=["normal","italic"].filter(g=>r.styles.includes(g)),u=(g,v,h)=>n.resolvePath(`files/${r.id}-${g}-${a?"wght":v}-${h}.woff2`,t),p=g=>{if(!n.pathExists(g))throw ge(`${e}: font file missing: ${g}`);return g},d=r.subsets.includes("latin")?"latin":r.defSubset,f=r.weights.reduce((g,v)=>Math.abs(v-dt)<Math.abs(g-dt)?v:g);return{family:o,kind:a?"variable":"static",category:la(r.category),label:e,provides:g=>a?ft(l,g):r.weights.includes(g),matchWeight:g=>uo(g,a?[l]:r.weights.map(v=>[v,v])),faces({weights:g,subsets:v}){let h=v.filter($=>r.subsets.includes($)),y=a?[`${l[0]} ${l[1]}`]:g.map(String),C=[];for(let $ of h)for(let S of y)for(let x of c)C.push({file:p(u($,S,x)),weight:S,style:x,subset:$,unicodeRange:s[$]??null});return C},metricsFile:p(u(d,f,"normal"))}}function ua({family:o,config:e,pathResolver:t}){let n=`appConfig.fonts['${o}']`;if(e?.category!=="sans-serif"&&e?.category!=="serif")throw ge(`${n}.category must be 'sans-serif' or 'serif' (picks the size-matched fallback face's system font).`);if(!Array.isArray(e.faces)||e.faces.length===0)throw ge(`${n}.faces must list the family's woff2 files ({ file, weight, style?, unicodeRange?, subset? }).`);let r=e.faces.map((c,u)=>{let p=`${n}.faces[${u}]`;if(typeof c?.file!="string"||!c.file.endsWith(".woff2"))throw ge(`${p}.file must be a .woff2 path relative to the app root (e.g. 'src/assets/fonts/brand.woff2').`);let[d,f]=aa(c.weight);if(!Number.isFinite(d)||!Number.isFinite(f)||d>f)throw ge(`${p}.weight must be a weight (400) or a variable range ('300 600'). Got ${JSON.stringify(c.weight)}.`);let g=c.style??"normal";if(g!=="normal"&&g!=="italic")throw ge(`${p}.style must be 'normal' or 'italic'.`);let v=t.resolveAppPath(c.file),h=t.pathExists(v)?t.readSync(v,{format:"buffer"}):null;if(!h)throw ge(`${p}.file: ${c.file} does not exist.`);if(!ia(h))throw ge(`${p}.file: ${c.file} is not a woff2 font.`);return{file:v,weight:d===f?String(d):`${d} ${f}`,range:[d,f],style:g,subset:c.subset??null,unicodeRange:c.unicodeRange??null}}),s=r.filter(c=>c.style==="normal"),a=s.filter(c=>c.unicodeRange===null),i=({range:c})=>ft(c,dt)?0:Math.min(...c.map(u=>Math.abs(u-dt))),l=[...a.length>0?a:s].sort((c,u)=>i(c)-i(u))[0];if(!l)throw ge(`${n}.faces has no normal-style face: the size-matched fallback face is measured on one.`);return{family:o,kind:"local",category:e.category,label:n,provides:c=>s.some(u=>ft(u.range,c)),matchWeight:c=>uo(c,s.map(u=>u.range)),faces:()=>r.map(({range:c,...u})=>u),metricsFile:l.file}}function pa(o,e,t){if(!e)return null;let n=t.resolvePackage(`${o}/package.json`,e);return n?t.getDirname(n):null}function po(o,{appFonts:e={},appRoot:t,uiRoot:n,pathResolver:r}){let s=Object.keys(e).find(i=>i.toLowerCase()===o.toLowerCase());if(s)return ua({family:o,config:e[s],pathResolver:r});let a=gt(o);for(let i of[t,n])for(let l of[`@fontsource-variable/${a}`,`@fontsource/${a}`]){let c=pa(l,i,r);if(c)return ca({family:o,packageName:l,dir:c,pathResolver:r})}return null}var Bt=Object.freeze({body:"--font-family",headline:"--font-headline",mono:"--font-mono"}),da="--font-weight-",Ee=":root",fa="@donotdev/components/styles",ga=/\/\*[\s\S]*?\*\//g,ma=/([^{}]+)\{([^{}]*)\}/g,ha=/^(?::root|html|:where\(:root\))$/,va=/^(?::root|html)?\.([a-z][\w-]*)$/i,Ut=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/,fo={normal:400,bold:700};function Wt(o){let e=[],t=0,n="",r=0;for(let s=0;s<o.length;s++){let a=o[s];n?a===n&&(n=""):a==='"'||a==="'"?n=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(o.slice(r,s)),r=s+1)}return e.push(o.slice(r)),e.map(s=>s.trim()).filter(Boolean)}function ya(o){return o.replace(/^['"]|['"]$/g,"").trim()}function ba(o){if(ha.test(o))return Ee;let e=va.exec(o);return e?e[1]:null}function go(o,e=""){let t=new Map,n=o.replace(ga,"");for(let[,r,s]of n.matchAll(ma)){let a=r.split(";").pop(),i=Wt(a).map(ba).filter(l=>l!==null);if(i.length!==0)for(let l of s.split(";")){let c=l.indexOf(":");if(c===-1)continue;let u=l.slice(0,c).trim();if(!u.startsWith("--"))continue;let p=l.slice(c+1).replace(/!important\s*$/,"").replace(/\s+/g," ").trim();for(let d of i)t.has(d)||t.set(d,new Map),t.get(d).set(u,{value:p,source:e,scope:d})}}return t}function wa(o){let e=new Map;for(let t of o)for(let[n,r]of t){e.has(n)||e.set(n,new Map);for(let[s,a]of r)e.get(n).set(s,a)}return e}function mo({source:o,scope:e}){return`${o||"CSS"} (${e===Ee?":root":`.${e}`})`}function jt(o,e,t,n){let r=[];for(let s of Wt(e)){let a=Ut.exec(s);if(!a){r.push(ya(s));continue}let[,i,l]=a;if(t.has(i)&&!n.has(i))r.push(...jt(i,t.get(i).value,t,new Set([...n,i])));else if(l!==void 0)r.push(...jt(o,l,t,n));else throw H("dndev-fonts",`${o}: ${e} uses var(${i}), which no theme CSS defines (src/**/*.css and the framework tokens). Name the font family in the stack itself, e.g. ${o}: Manrope, 'Manrope Fallback', sans-serif; (a next/font or other runtime class variable is not a framework font).`,"configuration-error")}return r}function Ea(o,e){let t=new Set,n=o;for(;e.has(n)&&!t.has(n);){t.add(n);let r=e.get(n),s=Wt(r.value),a=s[0]&&Ut.exec(s[0]);if(!a)return{token:n,declaration:r,entries:s};n=a[1]}return null}function zt(o,e,t=new Set){let{value:n}=e.get(o),r=Ut.exec(n);if(r){let[,a,i]=r;if(e.has(a)&&!t.has(a))return zt(a,e,new Set([...t,o]));if(i!==void 0)return zt(o,new Map([[o,{value:i.trim()}]]),t)}if(n in fo)return fo[n];let s=Number(n);if(Number.isFinite(s)&&s>=1&&s<=1e3)return s;throw H("dndev-fonts",`${o}: ${n} is not a font weight (a number from 1 to 1000, normal or bold): the font plan ships the weights the --font-weight-* tokens name.`,"configuration-error")}function ho({frameworkCss:o,appCss:e}){if(typeof o!="string"||!Array.isArray(e))throw new Error("resolveThemeFonts: frameworkCss (string) and appCss ({ file, css }[]) are required (ThemeDiscovery fontCss)");let t=go(o,fa),n=wa(e.map(({file:s,css:a})=>go(a,s)));return[Ee,...new Set([...t.keys(),...n.keys()])].filter((s,a,i)=>i.indexOf(s)===a).map(s=>{let a=new Map([...t.get(Ee)??[],...n.get(Ee)??[],...s===Ee?[]:t.get(s)??[],...s===Ee?[]:n.get(s)??[]]),i={};for(let[c,u]of Object.entries(Bt))a.has(u)&&(i[c]={stack:jt(u,a.get(u).value,a,new Set([u])),origin:Ea(u,a)});let l=new Map;for(let c of a.keys())c.startsWith(da)&&l.set(c,{weight:zt(c,a),declaration:a.get(c)});return{scope:s,roles:i,weights:l}})}var yo="optional",Ht=$e.fonts,Vt=`/${Ht}`,xa=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),$a=new Set(vn.map(o=>o.toLowerCase())),Pa="--font-weight-normal",Ra="--font-weight-bold",Gt=o=>H("dndev-fonts",o,"configuration-error");function vo(o){let e=yn[o];return e&&e.length>0?[...e]:["latin"]}var bo=o=>`'${o.replace(/'/g,"\\'")}'`;function Ca(o,e){return["@font-face{",`font-family:${bo(o)};`,`font-style:${e.style};`,`font-weight:${e.weight};`,`font-display:${yo};`,`src:url(${e.url}) format('woff2');`,e.unicodeRange?`unicode-range:${e.unicodeRange};`:"","}"].join("")}function _a(o,e){let[t,n=t]=o.split(" ").map(Number);return e>=t&&e<=n}async function wo({fontCss:o,appFonts:e={},languages:t,publicPath:n="",indexHtml:r=null,pathResolver:s}){if(!o||typeof o.framework!="string"||!Array.isArray(o.app))throw new Error("[dndev-fonts] buildFontPlan: fontCss is required (ThemeDiscovery fontCss: theme discovery failed?)");if(!Array.isArray(t)||t.length===0)throw new Error("[dndev-fonts] buildFontPlan: languages is required (i18n discovery supportedLanguages)");let a=s.getAppRoot(),i=await s.findFiles(a,no);oo([...o.app.map(({file:m,css:A})=>({file:m,content:A})),...i.map(m=>({file:s.getRelativePath(m),content:s.readSync(m,{format:"text"})??""})),...r===null?[]:[{file:"index.html",content:r}]]);let l=ho({frameworkCss:o.framework,appCss:o.app}),c=s.resolveFrameworkPackage("@donotdev/ui"),u=new Map,p=m=>{let A=m.toLowerCase();return u.has(A)||u.set(A,po(m,{appFonts:e,appRoot:a,uiRoot:c,pathResolver:s})),u.get(A)},d=new Map,f=new Map,g=new Map,v=new Map,h=new Map;for(let{scope:m,roles:A,weights:B}of l)for(let[w,M]of Object.entries(A)){if(!M)continue;let L=Bt[w];M.stack.forEach((z,K)=>{let U=z.toLowerCase();if(xa.has(U)||$a.has(U))return;let Z=/^(.+) fallback$/i.exec(z)?.[1];if(Z&&p(Z))return;let R=p(z);if(!R){d.has(U)||d.set(U,{family:z,token:L,scope:m});return}v.has(U)||v.set(U,{source:R,weights:new Set,scopes:new Set});let I=v.get(U);I.scopes.add(m);for(let{weight:J}of B.values())I.weights.add(R.matchWeight(J)),!R.provides(J)&&!g.has(`${U}:${J}`)&&g.set(`${U}:${J}`,`${R.family}: weight ${J} not in source, browser-synthesized`);if(K!==0)return;h.set(U,R);let F=M.origin,W=F?F.entries[1]:M.stack[1],Q=pt(z);if(W&&W.replace(/^['"]|['"]$/g,"").trim().toLowerCase()===Q.toLowerCase())return;let X=F?.declaration??{source:"",scope:m},te=F?.token??L,xe=`${X.source}|${te}|${X.value??z}`;if(f.has(xe))return;let E=F?F.entries:[z],T=`${te}: ${[E[0],bo(Q),...E.slice(1)].join(", ")};`;f.set(xe,{location:mo(X),declared:te,family:z,expected:Q,line:T})})}let y=[];for(let{family:m,token:A,scope:B}of d.values())y.push(`${A} (${B===Ee?":root":`.${B}`}) names '${m}', which nothing provides: install @fontsource-variable/${gt(m)} or @fontsource/${gt(m)} in the app, declare its woff2 files in appConfig.fonts['${m}'], or use a system family (SYSTEM_FONT_FAMILIES) or a generic one (sans-serif, serif, monospace, system-ui\u2026).`);for(let{location:m,declared:A,family:B,expected:w,line:M}of f.values())y.push(`${m}: ${A} lacks '${w}' right after '${B}' (the size-matched fallback face: no layout shift, no flicker). Write:
330
+ ${M}`);if(y.length>0)throw Gt(`the theme fonts cannot ship:
331
+ - ${y.join(`
332
+ - `)}`);let C=[...new Set(["latin",...t.flatMap(vo)])],$=new Map,S=m=>{if(!$.has(m)){let A=s.readSync(m,{format:"buffer"}),B=Sa("sha256").update(A).digest("hex").slice(0,8),w=s.getBasename(m).replace(/\.woff2$/,"");$.set(m,`${n}${Vt}/${w}.${B}.woff2`)}return $.get(m)},x=[],N=[];for(let[m,{source:A,weights:B}]of v){let w=A.faces({weights:[...B].sort((M,L)=>M-L),subsets:C}).map(M=>({...M,family:A.family,url:S(M.file)}));N.push(...w),x.push({family:A.family,kind:A.kind,category:A.category,source:A.label,fallback:h.has(m)?pt(A.family):null})}let D=[...h.values()].map(m=>{try{return co({family:m.family,category:m.category,metrics:lo(s.readSync(m.metricsFile,{format:"buffer"}))})}catch(A){throw Gt(`'${m.family}' (${m.label}): cannot measure ${m.metricsFile} for its fallback face (${A.message}). Its core file must be a woff2 with the Latin letters a-z.`)}}),P=l.find(({scope:m})=>m===Ee),k=[["body",Pa],["headline",Ra]].flatMap(([m,A])=>{let B=P.roles[m]?.stack[0];if(!B||!v.has(B.toLowerCase()))return[];let w=P.weights.get(A)?.weight;if(w===void 0)throw Gt(`${A} is not defined: the framework tokens (@donotdev/components/styles) define it.`);let{source:M}=v.get(B.toLowerCase());return[{family:M.family,weight:M.matchWeight(w)}]}),_={};for(let m of t){let A=vo(m),B=[];for(let{family:w,weight:M}of k)for(let L of N){if(L.family!==w||L.style!=="normal"||!_a(L.weight,M))continue;(L.subset===null?L.unicodeRange===null:A.includes(L.subset))&&!B.includes(L.url)&&B.push(L.url)}_[m]=B}return{display:yo,families:x,files:[...$].map(([m,A])=>({source:m,url:A})),css:[...N.map(m=>Ca(m.family,m)),...D].join(`
333
+ `),preloads:_,notices:[...g.values()]}}function Eo(o,{pathResolver:e,publicPath:t=""}){let n=e.resolveAppPath(`public/${Ht}`);e.removeSync(n),e.ensureDirSync(n);let r=`${t}${Vt}/`;for(let{source:s,url:a}of o.files){if(!a.startsWith(r))throw new Error(`[dndev-fonts] writeFontPlan: ${a} is not under ${r}`);e.copySync(s,e.resolvePath(a.slice(r.length),n),{overwrite:!0})}return n}Y();var So=/[ \t]*<link rel="preload" as="font"[^>]*>\n?/g,Aa=o=>o.replace(/&/g,"&amp;").replace(/"/g,"&quot;");function xo(o,e){let t=Mt(e).map(({attributes:s})=>` <link ${Object.entries(s).map(([a,i])=>`${a}="${Aa(i)}"`).join(" ")}>
334
+ `).join(""),n=o.search(So);if(n===-1){if(e.length===0)return o;let s=o.indexOf(`<style id="${ut}"`);if(s===-1)throw new Error(`[dndev-fonts] Prerender: the SPA shell has no font tags (<style id="${ut}">): keep the font plugin (createVitePlugins) before the prerender.`);let a=o.lastIndexOf(`
335
+ `,s)+1;return o.slice(0,a)+t+o.slice(a)}let r=o.replace(So,"");return r.slice(0,n)+t+r.slice(n)}function $o(){let o=null;return{set(e){o=e},get(){if(!o)throw new Error("[dndev-fonts] The font plan is not built yet (the font plugin builds it in buildStart).");return o}}}function Po({appConfig:o,i18nStore:e,fontPlan:t,debug:n=!1}){if(!e||!t)throw new Error("[dndev] createViteFontPlugin: options.i18nStore and options.fontPlan are required (createVitePlugins passes the i18n plugin's createI18nStore and createFontPlanStore).");let r=G("fonts",n,!1),s="",a=null;async function i(){let l=O.getInstance(),{supportedLanguages:c,fallbackLanguage:u}=await e.ready(),{fontCss:p}=await new Oe(null,l,{debug:n}).discoverThemes(!0),d=l.resolveAppPath("index.html"),f=await wo({fontCss:p,appFonts:o?.fonts,languages:c,publicPath:s,indexHtml:l.pathExists(d)?l.readSync(d,{format:"text"}):null,pathResolver:l});Eo(f,{pathResolver:l,publicPath:s}),t.set(f),a=c.includes(u)?u:c[0],r.debug(`Font plan: ${f.families.map(({family:g})=>g).join(", ")||"system fonts only"} (${f.files.length} files)`);for(let g of f.notices)r.info(`\u{1F524} ${g}`)}return{name:"dndev-fonts",configResolved(l){s=l.base&&l.base!=="/"?l.base.replace(/\/$/,""):""},async buildStart(){await i()},configureServer(l){l.watcher.on("change",async c=>{if(!c.endsWith(".css"))return;let u=t.get();try{await i()}catch(d){l.config.logger.error(d.message),l.ws.send({type:"error",err:{message:d.message,stack:""}});return}let p=t.get();(p.css!==u.css||JSON.stringify(p.preloads)!==JSON.stringify(u.preloads))&&l.ws.send({type:"full-reload"})})},transformIndexHtml:{order:"pre",handler(){let l=t.get();return[...Mt(l.preloads[a]).map(({tag:c,attributes:u})=>({tag:c,attrs:u,injectTo:"head"})),...l.css?[{tag:"style",attrs:{id:ut},children:l.css,injectTo:"head"}]:[]]}}}}q();import{existsSync as No,readFileSync as ko,writeFileSync as Na}from"node:fs";import{join as Do}from"node:path";var ka="/(.*)",qt=Object.freeze(["default-src","script-src","style-src","img-src","font-src","connect-src","media-src","worker-src","manifest-src","frame-src","object-src","base-uri","form-action","frame-ancestors"]),Da=Object.freeze({"default-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"frame-src":["'none'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"]}),Ro=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),To=Object.freeze({"@donotdev/supabase":{"connect-src":["https://*.supabase.co","wss://*.supabase.co"]},"@donotdev/firebase":{"script-src":["https://accounts.google.com","https://apis.google.com"],"connect-src":["https://identitytoolkit.googleapis.com","https://securetoken.googleapis.com","https://www.googleapis.com","https://*.googleapis.com","https://*.firebaseio.com"],"frame-src":["https://accounts.google.com"]}}),Ta=Object.freeze([{key:"X-Content-Type-Options",value:"nosniff"},{key:"X-Frame-Options",value:"DENY"},{key:"X-XSS-Protection",value:"1; mode=block"},{key:"Referrer-Policy",value:"strict-origin-when-cross-origin"},{key:"Permissions-Policy",value:"geolocation=(), microphone=(), camera=()"}]),Oa=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),Ia=31536e3,Fa=86400,Oo=3600,Co=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(o=>`/assets/:path*.${o}`),"next-export":["/_next/static/:path*"],next:[]}),Ma=`/${$e.fonts}/:path*`,La=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),ja=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${Oo}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),_o=Object.freeze(["csp","cache"]);function mt(o,e=!1){return`public, max-age=${o}${e?", immutable":""}`}function Jt(o,e){return{source:o,headers:[{key:"Cache-Control",value:e}]}}var Ao=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),za=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function Ba(o,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${o}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!Ao.includes(e)&&!za.test(e))throw new Error(`[dndev] appConfig.headers.csp['${o}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${Ao.join(" ")} or a hash like 'sha256-<base64>').`)}function Ua(o){if(o===void 0)return{csp:{},cache:[]};if(!o||typeof o!="object"||Array.isArray(o))throw new Error("[dndev] appConfig.headers must be an object.");for(let n of Object.keys(o))if(!_o.includes(n))throw new Error(`[dndev] appConfig.headers.${n} is not a header option (allowed: ${_o.join(", ")}).`);let e=o.csp??{};for(let[n,r]of Object.entries(e)){if(!qt.includes(n))throw new Error(`[dndev] appConfig.headers.csp['${n}'] is not a CSP directive the framework merges (allowed: ${qt.join(", ")}).`);if(!Array.isArray(r))throw new Error(`[dndev] appConfig.headers.csp['${n}'] must be an array of sources.`);for(let s of r)Ba(n,s)}let t=o.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let n of t){if(typeof n?.source!="string"||!n.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(n?.source)}).`);if(!Number.isInteger(n.maxAge)||n.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${n.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(n.maxAge)}).`)}return{csp:e,cache:t}}function Wa({csp:o={},providers:e=[],target:t}){if(!(t in Ro))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...qt.map(r=>{let s=[...r==="script-src"?Ro[t]:Da[r]??[],...e.flatMap(l=>To[l]?.[r]??[]),...o[r]??[]],a=[...new Set(s)],i=a.length>1?a.filter(l=>l!=="'none'"):a;return i.length>0?`${r} ${i.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function Io({appConfig:o,target:e,providers:t=[],pwa:n=!1}){if(!(e in Co))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:r,cache:s}=Ua(o?.headers),a=[{key:"Content-Security-Policy",value:Wa({csp:r,providers:t,target:e})},...o?.seo===!1?[Oa]:[],...Ta].map(i=>({...i}));return[{source:ka,headers:a},...[...Co[e],Ma].map(i=>Jt(i,mt(Ia,!0))),...La.map(i=>Jt(`/:path*.${i}`,mt(Fa))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:mt(Oo)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...n?ja.map(i=>({source:i.source,headers:i.headers.map(l=>({...l}))})):[],...s.map(i=>Jt(i.source,mt(i.maxAge,i.immutable===!0)))]}function Fo(o){let e=Do(o,"package.json");if(!No(e))return[];let t=JSON.parse(ko(e,"utf8")),n={...t.dependencies,...t.devDependencies};return Object.keys(To).filter(r=>!!n[r])}function Ga(o){let e=Do(o,"vercel.json");if(!No(e))return null;try{return{path:e,config:JSON.parse(ko(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function Mo({appRoot:o,rules:e,ci:t,logger:n}){let r=Ga(o);if(!r)return"absent";if(JSON.stringify(r.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${r.path}: "headers" differ from the framework header policy (appConfig.headers, appConfig.seo). The host reads the committed file, so this deploy would serve stale headers. Run the app locally (dev or build) to regenerate vercel.json, then commit it.`);let s=`${JSON.stringify({...r.config,headers:e},null,2)}
336
+ `;return Na(r.path,s),n?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function Lo({appConfig:o,pwa:e,debug:t,verbose:n}){let r=G("host-headers",t,n);return{name:"dndev-host-headers",configResolved(s){Mo({appRoot:s.root,rules:Io({appConfig:o,target:"vite",providers:Fo(s.root),pwa:e===!0}),ci:!!(process.env.CI||process.env.VERCEL),logger:r})}}}q();q();Y();q();function Ha(o){if(!o)return[];let e=O.getInstance(),t=new Set;try{let n=e.resolvePackage("@donotdev/core",o);if(!n)return[];let r=e.getDirname(e.getDirname(n)),s;try{s=e.readdirSync(r)}catch{return[]}for(let a of s)try{let i=e.resolvePath(`${a}/package.json`,r),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[c,u]of Object.entries(l.peerDependenciesMeta))u?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function Va(o){if(!o)return[];let e=O.getInstance();try{let t=e.resolvePath("package.json",o),n=e.readSync(t,{format:"json"});if(!n)return[];let r=new Set;if(n.peerDependenciesMeta)for(let[s,a]of Object.entries(n.peerDependenciesMeta))a?.optional&&r.add(s);if(n.optionalDependencies)for(let s of Object.keys(n.optionalDependencies))r.add(s);return Array.from(r)}catch{return[]}}function Ja(o){let e=Pe.optionalFeatures||[],t=Ha(o),n=Va(o);return[...new Set([...e,...t,...n])]}function qa(o){let e=O.getInstance();try{let t=e.resolvePath("package.json",o),n=e.readSync(t,{format:"json"});return n?new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{})]):new Set}catch{return new Set}}function Ka(o,e,t){let n=new Set,r=t.resolvePackage("@donotdev/core",o);if(!r)return n;let s=t.getDirname(t.getDirname(r));for(let a of e){if(!a.startsWith("@donotdev/"))continue;let i=t.resolvePath(`${a.slice(10)}/package.json`,s);if(!t.pathExists(i))continue;let l=t.readSync(i,{format:"json"});for(let c of Object.keys(l?.dependencies||{}))n.add(c)}return n}function Ya(o,e,t){if(t.resolvePackage(o,e||void 0))return!0;let n=o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0],r=e;for(let s=0;s<10;s++){let a=t.resolvePath(`node_modules/${n}`,r);if(t.pathExists(a))return!0;let i=t.getDirname(r);if(i===r)break;r=i}return!1}function ht(o){let e=Ja(o),t=[],n=[],r=O.getInstance(),s=qa(o),a=Ka(o,s,r);for(let i of e)i.startsWith("@donotdev/")?s.has(i)?n.push(i):t.push(i):(s.has(i)||a.has(i))&&Ya(i,o,r)?n.push(i):t.push(i);return{missing:t,installed:n}}var vt=class extends fe{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[n,r]of Object.entries(e)){for(let s of Object.keys(r))t.includes(s)||delete r[s];Object.keys(r).length===0&&delete e[n]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),n=this.pathResolver.getRepoRoot();if(!t||t===n)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${n})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${n}`);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 s=st("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(R=>{let I=R.endsWith(".json")?R:`${R}/*_*.json`;return this.pathResolver.resolveAppPath(I)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let c=r.framework?.eager||[],u=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${u.join(", ")}`),c.length===0&&u.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),d=this.pathResolver.normalizePath(n),f=(R,I)=>{let F=this.pathResolver.normalizePath(R),W=this.pathResolver.normalizePath(I);return F.startsWith(W)?F.slice(W.length+1):F},g=a.map(R=>f(R,t)),h=[...i,...l].map(R=>f(R,t)),y=c.map(R=>f(R,n)),C=u.map(R=>f(R,n)),$={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},S=await this.pathResolver._globWithNormalization(g,$),x=await this.pathResolver._globWithNormalization(h,$),N={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:s.ignore?.filter(R=>R!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${n}, ignore: ${JSON.stringify(N.ignore)}`);let D=await this.pathResolver._globWithNormalization(y,N),P=await this.pathResolver._globWithNormalization(C,N);this.logger.debug(`Found ${S.length} eager, ${x.length} lazy, ${D.length} framework eager, ${P.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: ${c.join(", ")}`),P.length>0?this.logger.debug(`Framework lazy files (first 3): ${P.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${u.join(", ")}`);let k=[...new Set([...S,...x,...D,...P])],_=new Set([...S,...D]),m={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:A}=ht(t),B=new Set(A.filter(R=>R.startsWith("@donotdev/")).map(R=>R.replace("@donotdev/","")));B.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...B].join(", ")}] (packages not installed)`);let w=new Map,M=[...D,...P];for(let R of M){let I=this._processTranslationFile(R,D.includes(R),t);if(I){if(B.has(I.namespace))continue;let F=`${I.namespace}_${I.language}`;w.set(F,I),m.allNamespaces.add(I.namespace),m.supportedLanguages.add(I.language),D.includes(R)&&m.eagerNamespaces.add(I.namespace)}}let L=new Set;for(let R of k){if(M.includes(R))continue;let I=this._processTranslationFile(R,_.has(R),t);if(I){let{namespace:F,language:W,importPath:Q,content:X}=I,te=`${I.namespace}_${I.language}`;if(w.has(te)){let xe=w.get(te);I.content=this._mergeTranslations(xe.content,X)}m.allNamespaces.add(F),m.supportedLanguages.add(W),L.add(W),_.has(R)&&m.eagerNamespaces.add(F),m.mapping[F]||(m.mapping[F]={}),m.mapping[F][W]=Q,I.content&&(m.content[F]||(m.content[F]={}),m.content[F][W]=I.content),m.files.push({path:R,relativePath:this.pathResolver.getRelativePath(R),namespace:F,language:W,eager:_.has(R),size:I.content?JSON.stringify(I.content).length:0})}}for(let[R,I]of w){let F=R.lastIndexOf("_"),W=R.slice(0,F),Q=R.slice(F+1);L.size>0&&!L.has(Q)||(!m.mapping[W]||!m.mapping[W][Q])&&(m.mapping[W]||(m.mapping[W]={}),m.mapping[W][Q]=I.importPath,m.content[W]||(m.content[W]={}),m.content[W][Q]=I.content,m.files.push({path:I.absolutePath,relativePath:this.pathResolver.getRelativePath(I.absolutePath),namespace:W,language:Q,eager:m.eagerNamespaces.has(W),size:I.content?JSON.stringify(I.content).length:0}))}let z=L.size>0?[...L].sort():[this.options.fallbackLanguage],K=this._getLanguageAllowlist(),U=z;if(K){let R=z.filter(F=>K.includes(F));U=R.length>0?R:[this.options.fallbackLanguage],this._restrictByLanguage(m.mapping,U),this._restrictByLanguage(m.content,U),m.files=m.files.filter(F=>U.includes(F.language));let I=new Set(Object.keys(m.mapping));m.allNamespaces=new Set([...m.allNamespaces].filter(F=>I.has(F))),m.eagerNamespaces=new Set([...m.eagerNamespaces].filter(F=>I.has(F))),this.logger.debug(`I18n restricted by i18n.only [${K.join(", ")}]: languages [${U.join(", ")}], namespaces ${I.size}`)}let Z=[...new Set(U.map(It))];return{mapping:m.mapping,content:m.content,eagerNamespaces:[...m.eagerNamespaces].sort(),allNamespaces:[...m.allNamespaces].sort(),supportedLanguages:U,fallbackLanguage:this.options.fallbackLanguage,flagCodes:Z,files:m.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[It(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 n=await this._processFiles([]);this.cache={...n,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){throw this.logger.error(`I18n discovery failed: ${n.message}`),n}}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,n){let r=e.split("/").pop()||e.split("\\").pop()||"",s,a,i=r.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,s,a]=i,!s||!a)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),u;try{if(u=this.pathResolver.readSync(e,{format:"json"}),!u)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:s,language:a,importPath:c,absolutePath:e,content:u}}_mergeTranslations(e,t){let n={...e};for(let[r,s]of Object.entries(t))typeof s=="object"&&s!==null&&!Array.isArray(s)?n[r]=this._mergeTranslations(n[r]||{},s):n[r]=s;return n}};var jo={isEmpty:o=>!o.mapping||Object.keys(o.mapping).length===0,generateModule:(o,e,t="i18n",n=!1)=>{let{mapping:r,eagerNamespaces:s,supportedLanguages:a,fallbackLanguage:i,stats:l,content:c={},files:u=[]}=o,p=n?Object.keys(c):s,d={};for(let y of p)c[y]&&(d[y]=c[y]);let f=[...new Set([...s,...Object.keys(c)])],g={mapping:r,languages:a,eager:n?f:s,fallback:i,content:d,storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:l?.totalFiles||0,totalNamespaces:l?.totalNamespaces||0,totalLanguages:l?.totalLanguages||0,eagerNamespaces:l?.eagerNamespaces||0,generatedAt:new Date().toISOString()},debug:e},v=[];if(!n)for(let[y,C]of Object.entries(r)){if(s.includes(y))continue;let $=[];for(let S of Object.keys(C))$.push(` '${S}': () => import('virtual:i18n-lazy-${y}-${S}')`);$.length>0&&v.push(` '${y}': {
337
+ ${$.join(`,
332
338
  `)}
333
- }`)}let m=w.length>0?`{
334
- ${w.join(`,
339
+ }`)}let h=v.length>0?`{
340
+ ${v.join(`,
335
341
  `)}
336
- }`:"{}";return`// ${U.i18n} - Generated by @donotdev/config
342
+ }`:"{}";return`// ${V.i18n} - Generated by @donotdev/config
337
343
  // Generated at: ${new Date().toISOString()}
338
344
 
339
345
  // ===== STATIC EXPORTS =====
340
346
  export const I18N_CONFIG = ${JSON.stringify(g,null,2)};
341
- export const LANGUAGES = ${JSON.stringify(i,null,2)};
342
- export const FALLBACK_LANGUAGE = '${a}';
347
+ export const LANGUAGES = ${JSON.stringify(a,null,2)};
348
+ export const FALLBACK_LANGUAGE = '${i}';
343
349
  export const EAGER_NAMESPACES = ${JSON.stringify(s,null,2)};
344
350
 
345
351
  const i18nPluginConfig = I18N_CONFIG;
346
352
 
347
353
  // ===== LAZY LOADERS =====
348
354
  // Static import() calls \u2014 Vite bundles each JSON as a separate async chunk
349
- const _lazyLoaders = ${m};
355
+ const _lazyLoaders = ${h};
350
356
 
351
357
  // ============================================================================
352
358
  // INITIALIZE DnDev CONFIG FOUNDATION
@@ -364,7 +370,7 @@ if (typeof globalThis !== 'undefined') {
364
370
  }
365
371
 
366
372
  // Add i18n plugin configuration + lazy loaders (functions, not serializable)
367
- globalThis._DNDEV_CONFIG_.${ee[t]} = {
373
+ globalThis._DNDEV_CONFIG_.${oe[t]} = {
368
374
  ...i18nPluginConfig,
369
375
  loaders: _lazyLoaders,
370
376
  };
@@ -458,7 +464,7 @@ export default {
458
464
  getInlineContent,
459
465
  };
460
466
 
461
- `},generateEmpty:(n,e,t,r="i18n")=>{let o=t.fallbackLanguage||"en",s={mapping:{},languages:[o],eager:[],fallback:o,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`// ${U.i18n} - Empty i18n configuration
467
+ `},generateEmpty:(o,e,t,n="i18n")=>{let r=t.fallbackLanguage||"en",s={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`// ${V.i18n} - Empty i18n configuration
462
468
  // No translation files found - using fallback configuration
463
469
  // Generated at: ${new Date().toISOString()}
464
470
 
@@ -476,7 +482,7 @@ if (typeof globalThis !== 'undefined') {
476
482
  };
477
483
  }
478
484
 
479
- globalThis._DNDEV_CONFIG_.${ee[r]} = i18nPluginConfig;
485
+ globalThis._DNDEV_CONFIG_.${oe[n]} = i18nPluginConfig;
480
486
  }
481
487
 
482
488
  // Placeholder functions
@@ -493,11 +499,11 @@ export function isEagerNamespace() {
493
499
  }
494
500
 
495
501
  export function getSupportedLanguages() {
496
- return ['${o}'];
502
+ return ['${r}'];
497
503
  }
498
504
 
499
505
  export function getFallbackLanguage() {
500
- return '${o}';
506
+ return '${r}';
501
507
  }
502
508
 
503
509
  export function getInlineContent() {
@@ -505,9 +511,9 @@ export function getInlineContent() {
505
511
  }
506
512
 
507
513
  export const mapping = {};
508
- export const languages = ['${o}'];
514
+ export const languages = ['${r}'];
509
515
  export const eager = [];
510
- export const fallback = '${o}';
516
+ export const fallback = '${r}';
511
517
  export const manifest = i18nPluginConfig.manifest;
512
518
  export const config = i18nPluginConfig;
513
519
 
@@ -525,7 +531,7 @@ export default {
525
531
  getFallbackLanguage,
526
532
  getInlineContent,
527
533
  };
528
- `},generateInspection:(n,e,t)=>{let{mapping:r,supportedLanguages:o,eagerNamespaces:s,files:i}=n;return!r||Object.keys(r).length===0?`/**
534
+ `},generateInspection:(o,e,t)=>{let{mapping:n,supportedLanguages:r,eagerNamespaces:s,files:a}=o;return!n||Object.keys(n).length===0?`/**
529
535
  * Generated i18n Discovery Results
530
536
  * Generated at: ${new Date().toISOString()}
531
537
  * Status: No translations found
@@ -556,18 +562,18 @@ export default {
556
562
  * Access via: globalThis._DNDEV_CONFIG_.i18n
557
563
  */
558
564
 
559
- export const discoveredTranslations = ${JSON.stringify(r,null,2)};
565
+ export const discoveredTranslations = ${JSON.stringify(n,null,2)};
560
566
 
561
- export const supportedLanguages = ${JSON.stringify(o,null,2)};
567
+ export const supportedLanguages = ${JSON.stringify(r,null,2)};
562
568
 
563
569
  export const eagerNamespaces = ${JSON.stringify(s,null,2)};
564
570
 
565
- export const translationFiles = ${JSON.stringify(i.map(a=>({namespace:a.namespace,language:a.language,path:a.relativePath,eager:a.eager,size:a.size})),null,2)};
571
+ 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)};
566
572
 
567
573
  export const i18nManifest = {
568
- totalNamespaces: ${n.stats?.totalNamespaces||0},
569
- totalLanguages: ${n.stats?.totalLanguages||0},
570
- eagerNamespaces: ${n.stats?.eagerNamespaces||0},
574
+ totalNamespaces: ${o.stats?.totalNamespaces||0},
575
+ totalLanguages: ${o.stats?.totalLanguages||0},
576
+ eagerNamespaces: ${o.stats?.eagerNamespaces||0},
571
577
  generatedAt: '${new Date().toISOString()}'
572
578
  };
573
579
 
@@ -578,37 +584,37 @@ export default {
578
584
  files: translationFiles,
579
585
  manifest: i18nManifest,
580
586
  };
581
- `},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 r=n.supportedLanguages||[],o=Object.keys(n.mapping||{}).filter(s=>s!=="default").length||0;t&&t.info(`${e} I18n: ${r.length} languages, ${o} namespaces`)}},Bs=[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 ln(){let n=null,e,t=new Promise(r=>{e=r});return{set(r){n=r,e(r)},ready:()=>t,get(){if(!n)throw new Error("[dndev] i18n discovery unavailable: the i18n plugin did not run (see the error above).");return n}}}function Us(n={}){return{...Fe.discovery,fallbackLanguage:n.fallbackLanguage||"en",...n}}function cn({i18nStore:n,...e}={}){if(!n)throw new Error("[dndev] createViteI18nPlugin: options.i18nStore is required (createVitePlugins passes it, createI18nStore).");let t=!1,r=new Map;function o(l){r.clear();let{content:c,eagerNamespaces:u}=l;for(let[p,d]of Object.entries(c||{}))if(!u.includes(p))for(let[f,g]of Object.entries(d))r.set(`virtual:i18n-lazy-${p}-${f}`,g)}let s={...an,generateModule:(l,c,u)=>(t||o(l),an.generateModule(l,c,u,t))};return[ye({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:U.i18n,DiscoveryClass:pt,discoveryMethod:"discoverTranslations",filePatterns:Bs,templates:s,manifestFileName:me.manifests.i18n,configKey:"i18n",discoveryOptions:Us(e)})({...e,discoveryStore:n,hmrSmartDetection:!1}),{name:"dndev-i18n-lazy-loader",enforce:"pre",configResolved(l){t=l.command==="serve"},async buildStart(){if(t)return;let l=await n.ready();o(l)},resolveId(l){if(!t&&l.startsWith("virtual:i18n-lazy-"))return"\0"+l},load(l){if(!t&&l.startsWith("\0virtual:i18n-lazy-")){let c=l.slice(1),u=r.get(c);return`export default ${JSON.stringify(u||{})};`}}}]}q();function un(n,e){return e.some(t=>n===t||n.startsWith(t+"/"))}function pn(n={}){let e=[],t="",r="";return{name:"dndev-optional-dep-resolver",enforce:"pre",config(o){let s={name:"dndev-optional-dep-esbuild",setup(a){a.onResolve({filter:/^[@a-z]/,namespace:"file"},l=>un(l.path,e)?{path:r,external:!1}:null)}};return{optimizeDeps:{esbuildOptions:{plugins:[...o.optimizeDeps?.esbuildOptions?.plugins||[],s]}}}},configResolved(o){let s=D.getInstance(),i=s.getAppRoot();if(e=ut(i).missing,t=s.getEmptyModulePath(),r=s.getEmptyCjsModulePath(),e.length>0){let l=o.optimizeDeps?.exclude||[];o.optimizeDeps.exclude=[...l,...e]}n.debug&&e.length>0},resolveId(o){return un(o,e)?{id:t,syntheticNamedExports:!0}:null}}}function Mt(n){return!n||typeof n!="string"?null:n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0]}function Gs(n){return!n||typeof n!="string"?!1:!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("\\")&&!n.startsWith("\0")}function Ws(n,e){if(!n||!e||!e.getRepoRoot())return!1;let r=n;n.startsWith("@fs/")&&(r=n.slice(4));let o=e.resolveRepoPath("packages"),s=e.normalizePath(r);return o&&s.startsWith(o)}function Vs(n,e){if(!n||!e)return null;let t=Mt(n);if(!t)return null;let r=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(r)?e.resolveAppPath(`node_modules/${n}`):null}function dn(n,e,t){return!Gs(n)||!Ws(e,t)?null:Vs(n,t)}q();function fn(n={}){let{debug:e=!1,verbose:t=!0}=n,r=M("peer-dependency-resolver",e,t);return{name:"dndev-peer-dependency-resolver",enforce:"pre",configResolved(o){let s=D.getInstance(),i=s.getAppRoot();if(!i){r.warn("App root not set, peer dependency resolution may fail");return}this.pathResolver=s,this.appRoot=i},resolveId(o,s){if(!s||!this.appRoot||!this.pathResolver)return null;if(dn(o,s,this.pathResolver)){let a=Mt(o),l=this.pathResolver.resolveAppPath(`node_modules/${o}`),c=this.pathResolver.resolveAppPath(`node_modules/${a}`);return this.pathResolver.pathExists(c)?o===a?((e||t)&&r.debug(`[PeerDeps] Resolving bare import "${o}" from app's node_modules: ${c}`),c):((e||t)&&r.debug(`[PeerDeps] Resolving subpath "${o}" from app's node_modules: ${l}`),l):(e&&r.debug(`[PeerDeps] Package directory not found: ${c}, skipping resolution`),null)}return null}}}q();q();function Hs(n){return n?String(n).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function Js(n){return n?String(n).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function qs(n){return n.replace(/<meta\s+name="description"[^>]*\/?>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="twitter:[^"]*"[^>]*\/?>\s*/gi,"").replace(/<link\s+rel="canonical"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="robots"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="keywords"[^>]*\/?>\s*/gi,"")}var Ks="data-rh";function gn({tag:n,attributes:e,text:t}){if(n==="title")return`<title>${Hs(t)}</title>`;let r=Object.entries(e).map(([s,i])=>`${s}="${Js(i)}"`).join(" "),o=`<${n} ${r} ${Ks}="true"`;return n==="script"?`${o}>${t??""}</script>`:`${o} />`}function mn(n,{tags:e,headScript:t,headElementId:r}){if(!/<title>[^<]*<\/title>/.test(n)||!n.includes("</head>"))throw new Error("[dndev] Prerender: dist/index.html has no <title> or </head>. Keep both in the app's index.html.");let o=e.filter(i=>i.tag==="title").map(gn),s=e.filter(i=>i.tag!=="title").map(i=>` ${gn(i)}`);return s.push(` <script type="application/json" id="${r}">${t}</script>`),qs(n).replace(/<title>[^<]*<\/title>/,()=>o.join("")).replace("</head>",()=>`${s.join(`
587
+ `},generateManifest:o=>({namespaces:o.stats?.totalNamespaces||0,languages:o.stats?.totalLanguages||0,fallbackLanguage:o.fallbackLanguage,eagerNamespaces:o.stats?.eagerNamespaces||0,platform:"vite",timestamp:Date.now()}),logConfig:o=>{},logStats:(o,e,t)=>{let n=o.supportedLanguages||[],r=Object.keys(o.mapping||{}).filter(s=>s!=="default").length||0;t&&t.info(`${e} I18n: ${n.length} languages, ${r} namespaces`)}},Za=[o=>o.endsWith(".json")&&o.includes("locale"),o=>/[a-z]+_[a-z]{2}\.json$/i.test(o),o=>o.includes("/locales/")&&o.endsWith(".json")];function zo(){let o=null,e,t=new Promise(n=>{e=n});return{set(n){o=n,e(n)},ready:()=>t,get(){if(!o)throw new Error("[dndev] i18n discovery unavailable: the i18n plugin did not run (see the error above).");return o}}}function Xa(o={}){return{...je.discovery,fallbackLanguage:o.fallbackLanguage||"en",...o}}function Bo({i18nStore:o,...e}={}){if(!o)throw new Error("[dndev] createViteI18nPlugin: options.i18nStore is required (createVitePlugins passes it, createI18nStore).");let t=!1,n=new Map;function r(l){n.clear();let{content:c,eagerNamespaces:u}=l;for(let[p,d]of Object.entries(c||{}))if(!u.includes(p))for(let[f,g]of Object.entries(d))n.set(`virtual:i18n-lazy-${p}-${f}`,g)}let s={...jo,generateModule:(l,c,u)=>(t||r(l),jo.generateModule(l,c,u,t))};return[we({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:V.i18n,DiscoveryClass:vt,discoveryMethod:"discoverTranslations",filePatterns:Za,templates:s,manifestFileName:ve.manifests.i18n,configKey:"i18n",discoveryOptions:Xa(e)})({...e,discoveryStore:o,hmrSmartDetection:!1}),{name:"dndev-i18n-lazy-loader",enforce:"pre",configResolved(l){t=l.command==="serve"},async buildStart(){if(t)return;let l=await o.ready();r(l)},resolveId(l){if(!t&&l.startsWith("virtual:i18n-lazy-"))return"\0"+l},load(l){if(!t&&l.startsWith("\0virtual:i18n-lazy-")){let c=l.slice(1),u=n.get(c);return`export default ${JSON.stringify(u||{})};`}}}]}Y();function Uo(o,e){return e.some(t=>o===t||o.startsWith(t+"/"))}function Wo(o={}){let e=[],t="",n="";return{name:"dndev-optional-dep-resolver",enforce:"pre",config(r){let s={name:"dndev-optional-dep-esbuild",setup(i){i.onResolve({filter:/^[@a-z]/,namespace:"file"},l=>Uo(l.path,e)?{path:n,external:!1}:null)}};return{optimizeDeps:{esbuildOptions:{plugins:[...r.optimizeDeps?.esbuildOptions?.plugins||[],s]}}}},configResolved(r){let s=O.getInstance(),a=s.getAppRoot();if(e=ht(a).missing,t=s.getEmptyModulePath(),n=s.getEmptyCjsModulePath(),e.length>0){let l=r.optimizeDeps?.exclude||[];r.optimizeDeps.exclude=[...l,...e]}o.debug&&e.length>0},resolveId(r){return Uo(r,e)?{id:t,syntheticNamedExports:!0}:null}}}function Kt(o){return!o||typeof o!="string"?null:o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0]}function Qa(o){return!o||typeof o!="string"?!1:!o.startsWith(".")&&!o.startsWith("/")&&!o.startsWith("\\")&&!o.startsWith("\0")}function ei(o,e){if(!o||!e||!e.getRepoRoot())return!1;let n=o;o.startsWith("@fs/")&&(n=o.slice(4));let r=e.resolveRepoPath("packages"),s=e.normalizePath(n);return r&&s.startsWith(r)}function ti(o,e){if(!o||!e)return null;let t=Kt(o);if(!t)return null;let n=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(n)?e.resolveAppPath(`node_modules/${o}`):null}function Go(o,e,t){return!Qa(o)||!ei(e,t)?null:ti(o,t)}Y();function Ho(o={}){let{debug:e=!1,verbose:t=!0}=o,n=G("peer-dependency-resolver",e,t);return{name:"dndev-peer-dependency-resolver",enforce:"pre",configResolved(r){let s=O.getInstance(),a=s.getAppRoot();if(!a){n.warn("App root not set, peer dependency resolution may fail");return}this.pathResolver=s,this.appRoot=a},resolveId(r,s){if(!s||!this.appRoot||!this.pathResolver)return null;if(Go(r,s,this.pathResolver)){let i=Kt(r),l=this.pathResolver.resolveAppPath(`node_modules/${r}`),c=this.pathResolver.resolveAppPath(`node_modules/${i}`);return this.pathResolver.pathExists(c)?r===i?((e||t)&&n.debug(`[PeerDeps] Resolving bare import "${r}" from app's node_modules: ${c}`),c):((e||t)&&n.debug(`[PeerDeps] Resolving subpath "${r}" from app's node_modules: ${l}`),l):(e&&n.debug(`[PeerDeps] Package directory not found: ${c}, skipping resolution`),null)}return null}}}Y();Y();function ni(o){return o?String(o).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function oi(o){return o?String(o).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}function ri(o){return o.replace(/<meta\s+name="description"[^>]*\/?>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="twitter:[^"]*"[^>]*\/?>\s*/gi,"").replace(/<link\s+rel="canonical"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="robots"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="keywords"[^>]*\/?>\s*/gi,"")}var si="data-rh";function Vo({tag:o,attributes:e,text:t}){if(o==="title")return`<title>${ni(t)}</title>`;let n=Object.entries(e).map(([s,a])=>`${s}="${oi(a)}"`).join(" "),r=`<${o} ${n} ${si}="true"`;return o==="script"?`${r}>${t??""}</script>`:`${r} />`}function Jo(o,{tags:e,headScript:t,headElementId:n}){if(!/<title>[^<]*<\/title>/.test(o)||!o.includes("</head>"))throw new Error("[dndev] Prerender: dist/index.html has no <title> or </head>. Keep both in the app's index.html.");let r=e.filter(a=>a.tag==="title").map(Vo),s=e.filter(a=>a.tag!=="title").map(a=>` ${Vo(a)}`);return s.push(` <script type="application/json" id="${n}">${t}</script>`),ri(o).replace(/<title>[^<]*<\/title>/,()=>r.join("")).replace("</head>",()=>`${s.join(`
582
588
  `)}
583
- </head>`)}function hn(n){if(n==="/")return"/index.html";let e=[];for(let t of n.split("/").slice(1)){let r;try{r=decodeURIComponent(t)}catch{return null}if(!r||r==="."||r===".."||/[/\\\0]/.test(r))return null;e.push(r)}return`/${e.join("/")}.html`}function Ys(n){return!n.includes(":")&&!n.includes("*")}var dt=class{constructor(e){this.routes=e.routes||[],this.outDir=e.outDir,this.debug=e.debug||!1,this.logger=e.logger}expandRoutes(e){let{routes:t,errors:r}=e;if(t.length===0)return r.length>0&&this.logger.warn("Route manifest unavailable. Using explicit routes only."),this.routes.filter(s=>!s.includes("*"));let o=new Set;for(let s of this.routes)if(s.includes("*")){let i=s.replace(/\/?\*.*$/,"");for(let a of t){let l=a.path||a;l.startsWith(i)&&Ys(l)&&!this.isAuthProtected(a)&&o.add(l)}if(this.debug){let a=[...o].filter(l=>l.startsWith(i));this.logger.debug(` Pattern "${s}" matched ${a.length} route(s)`)}}else{let i=t.find(a=>(a.path||a)===s);i&&this.isAuthProtected(i)?this.logger.warn(` Skipping auth-protected route: ${s}`):(o.add(s),!i&&this.debug&&this.logger.debug(` Route "${s}" not in manifest, including anyway`))}return[...o]}isAuthProtected(e){return typeof e=="string"?!1:e.auth?.required===!0}async writeOutputFile(e,t){let r=D.getInstance(),o=r.resolvePath(e.replace(/^\//,""),this.outDir);if(r.ensureDirSync(r.getDirname(o)),!r.writeSync(o,t,{overwrite:!0}))throw new Error(`writeSync returned false for ${o}`)}};J();function $e(n){return n.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function Zs(n,e){let t=e&&Object.hasOwn(e,n.collection)?e[n.collection]:void 0;if(!t)throw new Error(`[dndev] Route "${n.path}" reads "${n.collection}" records but no read schema was given for that collection (entityReadSchemas of the app's entities).`);return t}async function Xs(n,e,t,r){let o=$e(n.path),s=o[0];if(o.length!==1||!n.collection||!s)throw new Error(`[dndev] Cannot list the public URLs of route "${n.path}". Only single-param routes of an entity collection are expanded. Mark the page \`seo: { noindex: true }\` to keep it out of the sitemap and llms.txt.`);if(!e)throw new Error(`[dndev] Route "${n.path}" lists "${n.collection}" records but no server CRUD reader was given.`);let i=Zs(n,r),a;try{a=await e.query(n.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3},i)}catch(c){let u=c?.details?.originalMessage??c?.message??String(c);throw new Error(`[dndev] Route "${n.path}" could not read its public "${n.collection}" records (signed-out visitor: RLS / Security Rules must allow it): ${u}`,{cause:c})}let l=[];for(let c of a.items){let u=c[s];typeof u!="string"&&typeof u!="number"||l.push({param:s,value:String(u),record:c})}return l}async function ze(n,e,t,r){let o=[];for(let s of n){if($e(s.path).length===0){o.push({route:s,path:s.path});continue}for(let{param:i,value:a,record:l}of await Xs(s,e,t,r))o.push({route:s,path:s.path.replace(`:${i}`,encodeURIComponent(a)),record:l})}return o}function vn(n,e){return n.startsWith("/")?`${e}${n}`:n}function Lt(n){return typeof n=="object"&&n!==null&&"collection"in n&&"fields"in n}function yn(n,e,t){for(let r of Object.values(n))if(Lt(r)&&r.collection===e)return r;throw new Error(`[dndev] Entity page "${t}": no entity definition for collection "${e}". Export it from the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`)}function bn(n,e,t){let r=Object.create(null);for(let o of e)!o.collection||Object.hasOwn(r,o.collection)||(r[o.collection]=t(yn(n,o.collection,o.path)).get);return Object.freeze(r)}function wn(n,e){let{route:t,value:r,language:o,baseUrl:s,siteName:i,type:a}=e,l=yn(e.entities,t.collection,t.path),c=e.deriveEntitySeo(l,n,{t:e.translate([l.namespace,"crud"]),locale:o}),u=$e(t.path)[0],p=t.path.replace(`:${u}`,encodeURIComponent(r)),d=h=>e.languageUrl(h,o,s,e.routing,e.trailingSlash),f=d(p),g=c.title?`${c.title} | ${i}`:i,w=vn(c.image||e.defaultImage,s),m=a==="product"?e.buildProductJsonLd({...c,images:[...new Set(c.images.map(h=>vn(h,s)))]},f):null;return{url:f,title:g,...c.description&&{description:c.description},image:w,type:a,jsonLd:m,breadcrumb:c.title?e.buildBreadcrumbJsonLd(p,i,d,c.title):null}}q();function En(n){return(e,t)=>{let r=e.indexOf(":"),o=n[e.slice(0,r)];for(let s of e.slice(r+1).split("."))o=o&&typeof o=="object"&&s in o?o[s]:void 0;return typeof o=="string"?o:t?.defaultValue??e}}var Qs="dndev",ei="crud",ti="entity-";function xn(n,e,t){return e?n?.[e]?.[t]:void 0}function Ee(n){return typeof n=="string"&&n.trim()!==""?n.trim():void 0}function Sn(n){return n?.metaExport||n?.meta||{}}function ri(n,{siteName:e,defaultNamespace:t,t:r}){let o=Sn(n),{title:s,pageTitle:i}=Ir({meta:o,ns:o.namespace||null,defaultNs:t,t:r,siteName:e});return i??s}function ni(n,e,t){let r=Sn(n),o=r.seo||{};if(o.description===null)return;let s=xn(e,r.namespace,t);return Ee(o.description)??Ee(s?.description)}function Rn(n){let{siteName:e,description:t,baseUrl:r,sitemapRoutes:o,routes:s,blogPosts:i=[],blogPath:a="/blog",translations:l,language:c,defaultNamespace:u}=n,p=xn(l,Qs,c)?.seo,d=Ee(p?.llmsPages),f=Ee(p?.llmsBlog);if(!d||!f)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${c}".`);if(!u)throw new Error('[dndev] llms.txt: getLlmsTxtSource needs options.defaultNamespace (appConfig.seo.defaultNamespace, else "home").');let g=new Map(s.map(E=>[E.path,E])),w={siteName:e,defaultNamespace:u,t:En(Object.fromEntries(Object.entries(l||{}).map(([E,S])=>[E,S?.[c]])))},m=new Map(i.map(E=>[`${a}/${E.slug}`,E])),h=o.map(({path:E,collection:S})=>{let C=m.get(E);if(C)return{path:E,title:C.title,...Ee(C.description)&&{description:Ee(C.description)},section:f};if(S)return{path:E,collection:S};let k=g.get(E);if(!k&&E===a)return{path:E,title:f};let y=ni(k,l,c);return{path:E,title:ri(k,w),...y&&{description:y}}}),P={},R={};for(let[E,S]of Object.entries(l||{})){if(E===ei&&S?.[c]&&(R[E]=S[c]),!E.startsWith(ti))continue;S?.[c]&&(R[E]=S[c]);let C=Ee(S?.[c]?.namePlural);C&&(P[E]=C)}return{name:e,...Ee(t)&&{summary:Ee(t)},baseUrl:r,pagesHeading:d,routes:h,entityHeadings:P,language:c,translations:R}}function Pn(n={}){let{siteName:e,baseUrl:t,blogPosts:r=[],blogPath:o="/blog",appRoot:s,logger:i}=n;if(!e||!t)return null;if(r.length===0)return i?.debug?.("llms-full.txt skipped: no blog posts"),null;let a=D.getInstance(),l=s?a.resolvePath("src/content/blog",s):null;if(!l||!a.pathExists(l))return null;let c=[`# ${e}
584
- `];n.description&&c.push(`> ${n.description}
585
- `);for(let u of r){let p=a.resolvePath(`${u.slug}_en.md`,l);try{let d=a.readSync(p,{format:"text"});if(!d)continue;let f=d.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),g=`${t}${o}/${u.slug}`;c.push(`## ${u.title}
589
+ </head>`)}function qo(o){if(o==="/")return"/index.html";let e=[];for(let t of o.split("/").slice(1)){let n;try{n=decodeURIComponent(t)}catch{return null}if(!n||n==="."||n===".."||/[/\\\0]/.test(n))return null;e.push(n)}return`/${e.join("/")}.html`}function ai(o){return!o.includes(":")&&!o.includes("*")}var yt=class{constructor(e){this.routes=e.routes||[],this.outDir=e.outDir,this.debug=e.debug||!1,this.logger=e.logger}expandRoutes(e){let{routes:t,errors:n}=e;if(t.length===0)return n.length>0&&this.logger.warn("Route manifest unavailable. Using explicit routes only."),this.routes.filter(s=>!s.includes("*"));let r=new Set;for(let s of this.routes)if(s.includes("*")){let a=s.replace(/\/?\*.*$/,"");for(let i of t){let l=i.path||i;l.startsWith(a)&&ai(l)&&!this.isAuthProtected(i)&&r.add(l)}if(this.debug){let i=[...r].filter(l=>l.startsWith(a));this.logger.debug(` Pattern "${s}" matched ${i.length} route(s)`)}}else{let a=t.find(i=>(i.path||i)===s);a&&this.isAuthProtected(a)?this.logger.warn(` Skipping auth-protected route: ${s}`):(r.add(s),!a&&this.debug&&this.logger.debug(` Route "${s}" not in manifest, including anyway`))}return[...r]}isAuthProtected(e){return typeof e=="string"?!1:e.auth?.required===!0}async writeOutputFile(e,t){let n=O.getInstance(),r=n.resolvePath(e.replace(/^\//,""),this.outDir);if(n.ensureDirSync(n.getDirname(r)),!n.writeSync(r,t,{overwrite:!0}))throw new Error(`writeSync returned false for ${r}`)}};q();function ke(o){return o.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function ii(o,e){let t=e&&Object.hasOwn(e,o.collection)?e[o.collection]:void 0;if(!t)throw new Error(`[dndev] Route "${o.path}" reads "${o.collection}" records but no read schema was given for that collection (entityReadSchemas of the app's entities).`);return t}async function li(o,e,t,n){let r=ke(o.path),s=r[0];if(r.length!==1||!o.collection||!s)throw new Error(`[dndev] Cannot list the public URLs of route "${o.path}". Only single-param routes of an entity collection are expanded. Mark the page \`seo: { noindex: true }\` to keep it out of the sitemap and llms.txt.`);if(!e)throw new Error(`[dndev] Route "${o.path}" lists "${o.collection}" records but no server CRUD reader was given.`);let a=ii(o,n),i;try{i=await e.query(o.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3},a)}catch(c){let u=c?.details?.originalMessage??c?.message??String(c);throw new Error(`[dndev] Route "${o.path}" could not read its public "${o.collection}" records (signed-out visitor: RLS / Security Rules must allow it): ${u}`,{cause:c})}let l=[];for(let c of i.items){let u=c[s];typeof u!="string"&&typeof u!="number"||l.push({param:s,value:String(u),record:c})}return l}async function Ue(o,e,t,n){let r=[];for(let s of o){if(ke(s.path).length===0){r.push({route:s,path:s.path});continue}for(let{param:a,value:i,record:l}of await li(s,e,t,n))r.push({route:s,path:s.path.replace(`:${a}`,encodeURIComponent(i)),record:l})}return r}function Ko(o,e){return o.startsWith("/")?`${e}${o}`:o}function Yt(o){return typeof o=="object"&&o!==null&&"collection"in o&&"fields"in o}function Yo(o,e,t){for(let n of Object.values(o))if(Yt(n)&&n.collection===e)return n;throw new Error(`[dndev] Entity page "${t}": no entity definition for collection "${e}". Export it from the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`)}function Zo(o,e,t){let n=Object.create(null);for(let r of e)!r.collection||Object.hasOwn(n,r.collection)||(n[r.collection]=t(Yo(o,r.collection,r.path)).get);return Object.freeze(n)}function Xo(o,e){let{route:t,value:n,language:r,baseUrl:s,siteName:a,type:i}=e,l=Yo(e.entities,t.collection,t.path),c=e.deriveEntitySeo(l,o,{t:e.translate([l.namespace,"crud"]),locale:r}),u=ke(t.path)[0],p=t.path.replace(`:${u}`,encodeURIComponent(n)),d=y=>e.languageUrl(y,r,s,e.routing,e.trailingSlash),f=d(p),g=c.title?`${c.title} | ${a}`:a,v=Ko(c.image||e.defaultImage,s),h=i==="product"?e.buildProductJsonLd({...c,images:[...new Set(c.images.map(y=>Ko(y,s)))]},f):null;return{url:f,title:g,...c.description&&{description:c.description},image:v,type:i,jsonLd:h,breadcrumb:c.title?e.buildBreadcrumbJsonLd(p,a,d,c.title):null}}Y();function Qo(o){return(e,t)=>{let n=e.indexOf(":"),r=o[e.slice(0,n)];for(let s of e.slice(n+1).split("."))r=r&&typeof r=="object"&&s in r?r[s]:void 0;return typeof r=="string"?r:t?.defaultValue??e}}var ci="dndev",ui="crud",pi="entity-";function er(o,e,t){return e?o?.[e]?.[t]:void 0}function Re(o){return typeof o=="string"&&o.trim()!==""?o.trim():void 0}function tr(o){return o?.metaExport||o?.meta||{}}function di(o,{siteName:e,defaultNamespace:t,t:n}){let r=tr(o),{title:s,pageTitle:a}=qn({meta:r,ns:r.namespace||null,defaultNs:t,t:n,siteName:e});return a??s}function fi(o,e,t){let n=tr(o),r=n.seo||{};if(r.description===null)return;let s=er(e,n.namespace,t);return Re(r.description)??Re(s?.description)}function nr(o){let{siteName:e,description:t,baseUrl:n,sitemapRoutes:r,routes:s,blogPosts:a=[],blogPath:i="/blog",translations:l,language:c,defaultNamespace:u}=o,p=er(l,ci,c)?.seo,d=Re(p?.llmsPages),f=Re(p?.llmsBlog);if(!d||!f)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${c}".`);if(!u)throw new Error('[dndev] llms.txt: getLlmsTxtSource needs options.defaultNamespace (appConfig.seo.defaultNamespace, else "home").');let g=new Map(s.map(S=>[S.path,S])),v={siteName:e,defaultNamespace:u,t:Qo(Object.fromEntries(Object.entries(l||{}).map(([S,x])=>[S,x?.[c]])))},h=new Map(a.map(S=>[`${i}/${S.slug}`,S])),y=r.map(({path:S,collection:x})=>{let N=h.get(S);if(N)return{path:S,title:N.title,...Re(N.description)&&{description:Re(N.description)},section:f};if(x)return{path:S,collection:x};let D=g.get(S);if(!D&&S===i)return{path:S,title:f};let P=fi(D,l,c);return{path:S,title:di(D,v),...P&&{description:P}}}),C={},$={};for(let[S,x]of Object.entries(l||{})){if(S===ui&&x?.[c]&&($[S]=x[c]),!S.startsWith(pi))continue;x?.[c]&&($[S]=x[c]);let N=Re(x?.[c]?.namePlural);N&&(C[S]=N)}return{name:e,...Re(t)&&{summary:Re(t)},baseUrl:n,pagesHeading:d,routes:y,entityHeadings:C,language:c,translations:$}}function or(o={}){let{siteName:e,baseUrl:t,blogPosts:n=[],blogPath:r="/blog",appRoot:s,logger:a}=o;if(!e||!t)return null;if(n.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=O.getInstance(),l=s?i.resolvePath("src/content/blog",s):null;if(!l||!i.pathExists(l))return null;let c=[`# ${e}
590
+ `];o.description&&c.push(`> ${o.description}
591
+ `);for(let u of n){let p=i.resolvePath(`${u.slug}_en.md`,l);try{let d=i.readSync(p,{format:"text"});if(!d)continue;let f=d.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),g=`${t}${r}/${u.slug}`;c.push(`## ${u.title}
586
592
  `),c.push(`Source: ${g}
587
593
  `),u.date&&c.push(`Date: ${u.date}
588
- `),c.push(f.trim()),c.push("")}catch{i?.debug?.(`llms-full.txt: could not read ${u.slug}`)}}return c.join(`
589
- `)}import oi from"i18next";function Ze(n){return n.replace(/\s+/g," ").trim()}function $n(n){let e=[`# ${Ze(n.name)}`,""];n.summary&&e.push(`> ${Ze(n.summary)}`,"");for(let t of n.sections)if(t.links.length!==0){e.push(`## ${Ze(t.heading)}`,"");for(let r of t.links){let o=`- [${Ze(r.title)}](${r.url})`;e.push(r.description?`${o}: ${Ze(r.description)}`:o)}e.push("")}return e.join(`
590
- `)}function si(n){let e=new Map;for(let t of Object.values(n))Lt(t)&&e.set(t.collection,t);return e}function ii(n,e){let t=oi.createInstance();return t.init({lng:n,resources:{[n]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),r=>t.getFixedT(n,[r,"crud"])}async function Cn(n){let{crud:e,readSchemas:t,deriveEntitySeo:r,hiddenStatuses:o,formatTrailingSlash:s,trailingSlash:i}=n,a=si(n.entities),l,c=new Map,u=p=>{let d=c.get(p);return d||(d={heading:p,links:[]},c.set(p,d)),d};u(n.pagesHeading);for(let{route:p,path:d,record:f}of await ze(n.routes,e,o,t)){let g=`${n.baseUrl}${s(d,i)}`;if(!f){if(!p.title)throw new Error(`[dndev] llms.txt: source route "${p.path}" has no title (getLlmsTxtSource gives every static page one).`);u(p.section??n.pagesHeading).links.push({title:p.title,url:g,...p.description&&{description:p.description}});continue}let w=a.get(p.collection);if(!w)throw new Error(`[dndev] llms.txt: no entity definition for collection "${p.collection}" (route "${p.path}"). Export it from the app's \`entities\` package.`);let m=p.section??(w.namespace?n.entityHeadings[w.namespace]:void 0);if(!m)throw new Error(`[dndev] llms.txt: no heading for route "${p.path}". Add "namePlural" to the ${w.namespace??`entity-${w.name.toLowerCase()}`} translations.`);if(!l){if(!n.language||!n.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");l=ii(n.language,n.translations)}let h=r(w,f,{t:l(w.namespace),locale:n.language});u(m).links.push({title:h.title||n.name,url:g,...h.description&&{description:h.description}})}return $n({name:n.name,...n.summary&&{summary:n.summary},sections:[...c.values()]})}var _n=Object.freeze([{dependency:"@donotdev/supabase",module:"@donotdev/supabase/server",env:["SUPABASE_URL","SUPABASE_PUBLIC_KEY"],create:(n,[e,t])=>new n.SupabasePublicReader(n.createPublicServerClient(e,t))},{dependency:"@donotdev/firebase",module:"@donotdev/firebase/public",env:["FIREBASE_API_KEY","FIREBASE_PROJECT_ID"],create:(n,[e,t])=>new n.FirestorePublicReader(n.createPublicServerFirestore({apiKey:e,projectId:t}))}]);function An(n){return _n.find(({dependency:e})=>n(e))}var Nn=_n.map(({dependency:n})=>n).join(", ");function oe(n){return n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function Dn(n){return n?n.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}function ft(n,e){return(n||e||"").trim().replace(/\/+$/,"")}var On=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function ai(n,e){let t;try{let r=new URL(n);if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Error;t=r.hostname}catch{throw new Error(`[dndev] SEO: base URL "${n}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(On.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: deploy build with base URL "${n}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}var li="DNDEV_DEPLOY";function In(n=process.env){let e=n.CI;return n[li]==="1"||n.VERCEL==="1"||e!==void 0&&e!==""&&e!=="false"&&e!=="0"}var kn=new Set;function Xe(n,e,t,r=process.env){if(In(r)){if(!n)throw new Error(`[dndev] SEO: deploy build without ${e}. The sitemap, robots.txt, llms.txt and canonical URLs need the production URL: set ${e} (or seo.baseUrl) in the build environment.`);return ai(n,e),n}let o=s=>{kn.has(s)||(kn.add(s),t.warn(s))};return!n||!ci(n)?(o(`[dndev] Local build without a usable ${e}${n?` ("${n}")`:""}: no sitemap.xml, llms.txt, robots.txt, rss.xml, canonical URLs or record pages. Set ${e} to build them.`),null):(ui(n)||o(`[dndev] Local build: sitemap.xml, llms.txt, canonical URLs and record pages carry ${n} (${e}). A deploy build (dndev deploy, Vercel, CI) needs the production URL.`),n)}async function gt(n,e,t,r=process.env){try{return await e(),!0}catch(o){if(ve(o))throw o;let s=`${n.join(", ")} not written: ${o.message}`;if(In(r))throw H("dndev-seo",`${s}. A deploy build publishes every SEO file.`,"seo-generation-failed",{files:n});return t.warn(`[dndev] Local build: ${s} (a deploy build fails on it).`),!1}}function ci(n){try{let{protocol:e}=new URL(n);return e==="https:"||e==="http:"}catch{return!1}}function ui(n){let{hostname:e}=new URL(n);return!On.has(e)&&!e.endsWith(".localhost")}var jt=Object.freeze(["/api"]),Tn=new Set(["/404","/not-found","/500","/error"]);function mt(n){return n.auth&&n.auth!==!1||Tn.has(n.path)||Tn.has(n.meta?.route)?!1:n.meta?.seo?.noindex!==!0}function Ut(n){return typeof n.path=="string"&&n.path.split("/").includes("*")}function Fn(n){if(!(typeof n.path!="string"||!n.path.includes(":"))&&mt(n))return n.meta?.entity||void 0}function Mn(n){if(typeof n.path!="string"||n.path.includes("*")||$e(n.path).length!==1)return null;let e=Fn(n);return e?{path:n.path,collection:e}:null}function pi(n=[]){return{totalRoutes:n.length,publicRoutes:n.filter(e=>!e.auth||e.auth===!1).length,protectedRoutes:n.filter(e=>e.auth&&e.auth.required).length}}var Be=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:r=!0,baseUrl:o,siteName:s,crawlDelay:i=1,aiCrawlers:a="recommended",routes:l={},...c}=e;if(!o||!s)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:r,baseUrl:o,siteName:s,crawlDelay:i,aiCrawlers:a,routes:l,blogPath:"/blog",...c},this.appRoot=c.appRoot||null,this.logger=M("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,r){let o={routes:e.routes||[],baseUrl:this.options.baseUrl,siteName:this.options.siteName},s={robotsTxt:null,rss:null,manifest:null};return this.options.generateRobotsTxt&&(s.robotsTxt=await this.generateRobotsTxt(o,t)),r.length>0&&(s.rss=await this.generateRSSFeed(r,t)),s.manifest=await this.generateManifest(o,t),s}async generateRobotsTxt(e,t){let r=this.options.shellPath?[...jt,this.options.shellPath]:jt,o=this.generateRobotsTxtContent({disallowedPaths: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}}getSitemapRoutes(e,t=[]){let{blogPath:r}=this.options,o=[];for(let s of e||[]){if(!mt(s)||typeof s.path!="string"||Ut(s))continue;let i=s.path===r||s.path.startsWith(`${r}/`);if(!(t.length>0&&i))if(s.path.includes(":")){if(i)continue;let a=Fn(s);o.push({path:s.path,...a&&{collection:a}})}else o.push({path:s.path})}if(t.length>0){o.push({path:r,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let s of t)o.push({path:`${r}/${s.slug}`,priority:.6,changeFrequency:"monthly",...s.date&&{lastModified:s.date}})}return o}async generateManifest(e,t){let r={...pi(e.routes),baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()},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:r=jt,sitemap:o,crawlDelay:s}=e,i=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",a=["User-agent: *",...r.map(c=>`Disallow: ${i(c)}`),...t.map(c=>`Allow: ${i(c)}`)];s&&a.push(`Crawl-delay: ${s}`),o&&a.push(`Sitemap: ${o}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(a.push(""),a.push(...di(l))),a.join(`
591
- `)}discoverBlogPosts(){return this.appRoot?it(this.appRoot,this.logger):[]}async generateRSSFeed(e,t){let r=e.map(s=>` <item>
592
- <title><![CDATA[${Dn(s.title)}]]></title>
593
- <link>${oe(this.options.baseUrl)}${oe(this.options.blogPath)}/${oe(s.slug)}</link>
594
- <guid>${oe(this.options.baseUrl)}${oe(this.options.blogPath)}/${oe(s.slug)}</guid>
595
- <description><![CDATA[${Dn(s.description)}]]></description>
594
+ `),c.push(f.trim()),c.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${u.slug}`)}}return c.join(`
595
+ `)}import gi from"i18next";function Xe(o){return o.replace(/\s+/g," ").trim()}function rr(o){let e=[`# ${Xe(o.name)}`,""];o.summary&&e.push(`> ${Xe(o.summary)}`,"");for(let t of o.sections)if(t.links.length!==0){e.push(`## ${Xe(t.heading)}`,"");for(let n of t.links){let r=`- [${Xe(n.title)}](${n.url})`;e.push(n.description?`${r}: ${Xe(n.description)}`:r)}e.push("")}return e.join(`
596
+ `)}function mi(o){let e=new Map;for(let t of Object.values(o))Yt(t)&&e.set(t.collection,t);return e}function hi(o,e){let t=gi.createInstance();return t.init({lng:o,resources:{[o]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),n=>t.getFixedT(o,[n,"crud"])}async function sr(o){let{crud:e,readSchemas:t,deriveEntitySeo:n,hiddenStatuses:r,formatTrailingSlash:s,trailingSlash:a}=o,i=mi(o.entities),l,c=new Map,u=p=>{let d=c.get(p);return d||(d={heading:p,links:[]},c.set(p,d)),d};u(o.pagesHeading);for(let{route:p,path:d,record:f}of await Ue(o.routes,e,r,t)){let g=`${o.baseUrl}${s(d,a)}`;if(!f){if(!p.title)throw new Error(`[dndev] llms.txt: source route "${p.path}" has no title (getLlmsTxtSource gives every static page one).`);u(p.section??o.pagesHeading).links.push({title:p.title,url:g,...p.description&&{description:p.description}});continue}let v=i.get(p.collection);if(!v)throw new Error(`[dndev] llms.txt: no entity definition for collection "${p.collection}" (route "${p.path}"). Export it from the app's \`entities\` package.`);let h=p.section??(v.namespace?o.entityHeadings[v.namespace]:void 0);if(!h)throw new Error(`[dndev] llms.txt: no heading for route "${p.path}". Add "namePlural" to the ${v.namespace??`entity-${v.name.toLowerCase()}`} translations.`);if(!l){if(!o.language||!o.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");l=hi(o.language,o.translations)}let y=n(v,f,{t:l(v.namespace),locale:o.language});u(h).links.push({title:y.title||o.name,url:g,...y.description&&{description:y.description}})}return rr({name:o.name,...o.summary&&{summary:o.summary},sections:[...c.values()]})}var ar=Object.freeze([{dependency:"@donotdev/supabase",module:"@donotdev/supabase/server",env:["SUPABASE_URL","SUPABASE_PUBLIC_KEY"],create:(o,[e,t])=>new o.SupabasePublicReader(o.createPublicServerClient(e,t))},{dependency:"@donotdev/firebase",module:"@donotdev/firebase/public",env:["FIREBASE_API_KEY","FIREBASE_PROJECT_ID"],create:(o,[e,t])=>new o.FirestorePublicReader(o.createPublicServerFirestore({apiKey:e,projectId:t}))}]);function ir(o){return ar.find(({dependency:e})=>o(e))}var lr=ar.map(({dependency:o})=>o).join(", ");function ie(o){return o?o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function cr(o){return o?o.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}function bt(o,e){return(o||e||"").trim().replace(/\/+$/,"")}var dr=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function vi(o,e){let t;try{let n=new URL(o);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error;t=n.hostname}catch{throw new Error(`[dndev] SEO: base URL "${o}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(dr.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: deploy build with base URL "${o}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}var yi="DNDEV_DEPLOY";function fr(o=process.env){let e=o.CI;return o[yi]==="1"||o.VERCEL==="1"||e!==void 0&&e!==""&&e!=="false"&&e!=="0"}var ur=new Set;function Qe(o,e,t,n=process.env){if(fr(n)){if(!o)throw new Error(`[dndev] SEO: deploy build without ${e}. The sitemap, robots.txt, llms.txt and canonical URLs need the production URL: set ${e} (or seo.baseUrl) in the build environment.`);return vi(o,e),o}let r=s=>{ur.has(s)||(ur.add(s),t.warn(s))};return!o||!bi(o)?(r(`[dndev] Local build without a usable ${e}${o?` ("${o}")`:""}: no sitemap.xml, llms.txt, robots.txt, rss.xml, canonical URLs or record pages. Set ${e} to build them.`),null):(wi(o)||r(`[dndev] Local build: sitemap.xml, llms.txt, canonical URLs and record pages carry ${o} (${e}). A deploy build (dndev deploy, Vercel, CI) needs the production URL.`),o)}async function wt(o,e,t,n=process.env){try{return await e(),!0}catch(r){if(be(r))throw r;let s=`${o.join(", ")} not written: ${r.message}`;if(fr(n))throw H("dndev-seo",`${s}. A deploy build publishes every SEO file.`,"seo-generation-failed",{files:o});return t.warn(`[dndev] Local build: ${s} (a deploy build fails on it).`),!1}}function bi(o){try{let{protocol:e}=new URL(o);return e==="https:"||e==="http:"}catch{return!1}}function wi(o){let{hostname:e}=new URL(o);return!dr.has(e)&&!e.endsWith(".localhost")}var Zt=Object.freeze(["/api"]),pr=new Set(["/404","/not-found","/500","/error"]);function Et(o){return o.auth&&o.auth!==!1||pr.has(o.path)||pr.has(o.meta?.route)?!1:o.meta?.seo?.noindex!==!0}function en(o){return typeof o.path=="string"&&o.path.split("/").includes("*")}function gr(o){if(!(typeof o.path!="string"||!o.path.includes(":"))&&Et(o))return o.meta?.entity||void 0}function mr(o){if(typeof o.path!="string"||o.path.includes("*")||ke(o.path).length!==1)return null;let e=gr(o);return e?{path:o.path,collection:e}:null}function Ei(o=[]){return{totalRoutes:o.length,publicRoutes:o.filter(e=>!e.auth||e.auth===!1).length,protectedRoutes:o.filter(e=>e.auth&&e.auth.required).length}}var We=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:n=!0,baseUrl:r,siteName:s,crawlDelay:a=1,aiCrawlers:i="recommended",routes:l={},...c}=e;if(!r||!s)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:n,baseUrl:r,siteName:s,crawlDelay:a,aiCrawlers:i,routes:l,blogPath:"/blog",...c},this.appRoot=c.appRoot||null,this.logger=G("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,n){let r={routes:e.routes||[],baseUrl:this.options.baseUrl,siteName:this.options.siteName},s={robotsTxt:null,rss:null,manifest:null};return this.options.generateRobotsTxt&&(s.robotsTxt=await this.generateRobotsTxt(r,t)),n.length>0&&(s.rss=await this.generateRSSFeed(n,t)),s.manifest=await this.generateManifest(r,t),s}async generateRobotsTxt(e,t){let n=this.options.shellPath?[...Zt,this.options.shellPath]:Zt,r=this.generateRobotsTxtContent({disallowedPaths:n,sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",r),{fileName:"robots.txt",content:r,disallowedPaths:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:n}=this.options,r=[];for(let s of e||[]){if(!Et(s)||typeof s.path!="string"||en(s))continue;let a=s.path===n||s.path.startsWith(`${n}/`);if(!(t.length>0&&a))if(s.path.includes(":")){if(a)continue;let i=gr(s);r.push({path:s.path,...i&&{collection:i}})}else r.push({path:s.path})}if(t.length>0){r.push({path:n,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let s of t)r.push({path:`${n}/${s.slug}`,priority:.6,changeFrequency:"monthly",...s.date&&{lastModified:s.date}})}return r}async generateManifest(e,t){let n={...Ei(e.routes),baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()},r=JSON.stringify(n,null,2);return await t("seo-manifest.json",r),{fileName:"seo-manifest.json",content:r,manifest:n}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:n=Zt,sitemap:r,crawlDelay:s}=e,a=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...n.map(c=>`Disallow: ${a(c)}`),...t.map(c=>`Allow: ${a(c)}`)];s&&i.push(`Crawl-delay: ${s}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Si(l))),i.join(`
597
+ `)}discoverBlogPosts(){return this.appRoot?it(this.appRoot,this.logger):[]}async generateRSSFeed(e,t){let n=e.map(s=>` <item>
598
+ <title><![CDATA[${cr(s.title)}]]></title>
599
+ <link>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}/${ie(s.slug)}</link>
600
+ <guid>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}/${ie(s.slug)}</guid>
601
+ <description><![CDATA[${cr(s.description)}]]></description>
596
602
  <pubDate>${s.date?new Date(s.date).toUTCString():""}</pubDate>${s.tags.length?`
597
- <category>${oe(s.tags.join(", "))}</category>`:""}${s.image?`
598
- <enclosure url="${oe(this.options.baseUrl)}${oe(s.image)}" type="image/png" length="0"/>`:""}
603
+ <category>${ie(s.tags.join(", "))}</category>`:""}${s.image?`
604
+ <enclosure url="${ie(this.options.baseUrl)}${ie(s.image)}" type="image/png" length="0"/>`:""}
599
605
  </item>`).join(`
600
- `),o=`<?xml version="1.0" encoding="UTF-8"?>
606
+ `),r=`<?xml version="1.0" encoding="UTF-8"?>
601
607
  <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
602
608
  <channel>
603
- <title>${oe(this.options.siteName)}</title>
604
- <link>${oe(this.options.baseUrl)}${oe(this.options.blogPath)}</link>
605
- <description>${oe(this.options.siteName)} Blog</description>
609
+ <title>${ie(this.options.siteName)}</title>
610
+ <link>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}</link>
611
+ <description>${ie(this.options.siteName)} Blog</description>
606
612
  <language>en</language>
607
- <atom:link href="${oe(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
608
- ${r}
613
+ <atom:link href="${ie(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
614
+ ${n}
609
615
  </channel>
610
- </rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}},zt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],Bt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function di(n){let e=["# AI Crawler Management"];if(n==="block-all"){for(let t of[...zt,...Bt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(n==="allow-all"){for(let t of[...zt,...Bt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of zt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of Bt)e.push(`User-agent: ${t}`,"Allow: /","");return e}function ht(n){return String(n).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function Ln(n,{baseUrl:e,routing:t,trailingSlash:r,crud:o,readSchemas:s,languageUrls:i,hiddenStatuses:a}){let l=[],c=(u,p)=>{let d=i(u,e,t,r),f=t.languages.length>1?{alternates:{languages:d}}:{};for(let g of t.languages)l.push({url:d[g],...p,...f})};for(let{route:u,path:p,record:d}of await ze(n,o,a,s)){if(!d){c(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??(p==="/"?1:.8),...u.lastModified&&{lastModified:u.lastModified}});continue}let f=d.updatedAt instanceof Date?d.updatedAt.toISOString():d.updatedAt;c(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??.7,...typeof f=="string"&&{lastModified:f}})}return l}function jn(n){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${n.some(r=>r.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let r of n){t.push(" <url>",` <loc>${ht(r.url)}</loc>`);for(let[o,s]of Object.entries(r.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${ht(o)}" href="${ht(s)}" />`);r.lastModified&&t.push(` <lastmod>${ht(r.lastModified)}</lastmod>`),r.changeFrequency&&t.push(` <changefreq>${r.changeFrequency}</changefreq>`),r.priority!==void 0&&t.push(` <priority>${r.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
611
- `)}var Qe=!1,zn=["react-server","module","node","import","default"];function fi(n){let e=[];for(let t of n){let r=Mn(t);r&&e.push({route:r,type:t.meta?.seo?.type??"website"})}return e}function gi(n,e,t){let r={...n?.dependencies,...n?.devDependencies},o=An(a=>!!r[a]);if(!o)throw new Error(`[dndev] ${t.join(", ")} list published records, but the app's backend provider has no public reader (supported: ${Nn}). Mark these pages \`seo: { noindex: true }\`.`);let s=o.env.map(a=>`VITE_${a}`),i=s.map(a=>e[a]);if(i.some(a=>!a))throw new Error(`[dndev] Set ${s.join(" and ")}: the build lists the published records of ${t.join(", ")} (record pages, sitemap.xml, llms.txt).`);return{module:o.module,create:a=>o.create(a,i)}}function mi(n,e,t=process.env){if(!Xe(n||null,"VITE_APP_URL",e,t))return null;if(n.endsWith("/")||n!==n.trim())throw new Error(`[dndev] VITE_APP_URL "${n}" must have no trailing slash or spaces: the browser builds canonical URLs from it as is.`);return n}function hi(n){let e=new Map;return{query(t,r,o){let s=JSON.stringify([t,r]);return e.has(s)||e.set(s,n.query(t,r,o)),e.get(s)}}}async function vi({staticRoutes:n,records:e,crud:t,readSchemas:r,core:o,entities:s,translate:i,routing:a,baseUrl:l,siteName:c,hreflang:u,defaultNamespace:p,defaultImage:d,shellHtml:f}){let g=u&&o.isMultilingual(a.languages),w=[],m=[],h=new Set,P=(R,E)=>{let S=g?o.languageUrls(R,l,a,Qe):null;for(let C of a.languages){let k=o.localizePath(R,C,a),y=hn(k);if(!y||h.has(y)){m.push(k);continue}h.add(y);let T=o.languageUrl(R,C,l,a,Qe),$=E(C,T),v=[...$.tags,...o.siteHeadTags({url:l?T:null,siteName:c,alternates:S,defaultLanguage:a.defaultLanguage})];w.push({file:y,html:mn(f,{tags:v,headScript:o.jsonScriptText({url:T,...$}),headElementId:o.PRERENDERED_HEAD_ELEMENT_ID})})}};for(let R of n){let E=R.meta??{},S=E.namespace||null;P(R.path,(C,k)=>({tags:o.routeHeadTags(o.routeSeo({meta:E,ns:S,defaultNs:p,t:i([S??p],C),siteName:c,baseUrl:l,url:k,defaultImage:d,authOnly:!!R.auth}),{siteName:c,baseUrl:l}),breadcrumb:!1}))}if(e.length>0){let R=new Map(e.map(({route:S,type:C})=>[S.path,C])),E=await ze(e.map(({route:S})=>S),t,o.HIDDEN_STATUSES,r);for(let{route:S,path:C,record:k}of E){let y=String(k[$e(S.path)[0]]);P(C,T=>{let $=wn(k,{route:S,value:y,language:T,routing:a,baseUrl:l,trailingSlash:Qe,siteName:c,defaultImage:d,type:R.get(S.path),entities:s,translate:v=>i(v,T),deriveEntitySeo:o.deriveEntitySeo,buildProductJsonLd:o.buildProductJsonLd,buildBreadcrumbJsonLd:o.buildBreadcrumbJsonLd,languageUrl:o.languageUrl});return{tags:o.recordHeadTags($),breadcrumb:$.breadcrumb!==null}})}}return{pages:w,skipped:m}}async function yi({routes:n,blogPosts:e,generator:t,crud:r,readSchemas:o,core:s,entities:i,routing:a,baseUrl:l,siteName:c,siteDescription:u,translations:p,defaultNamespace:d,sitemap:f,llmsTxt:g}){let w=t.getSitemapRoutes(n,e),m=[];if(f){let h=await Ln(w,{baseUrl:l,routing:a,trailingSlash:Qe,crud:r,readSchemas:o,languageUrls:s.languageUrls,hiddenStatuses:s.HIDDEN_STATUSES});m.push({file:"/sitemap.xml",content:jn(h)})}if(g){let h=Rn({siteName:c,description:u,baseUrl:l,sitemapRoutes:w,routes:n,blogPosts:e,blogPath:t.options.blogPath,translations:p,language:a.defaultLanguage,defaultNamespace:d});m.push({file:"/llms.txt",content:await Cn({...h,trailingSlash:Qe,formatTrailingSlash:s.formatTrailingSlash,entities:i,crud:r,readSchemas:o,deriveEntitySeo:s.deriveEntitySeo,hiddenStatuses:s.HIDDEN_STATUSES})})}return m}async function vt(n,e,t){try{return await n.import(e)}catch(r){throw new Error(`[dndev] Build pages: cannot load "${e}" (${t}): ${r.message}`,{cause:r})}}async function Bn({appRoot:n,mode:e,manifestRoutes:t,blogPosts:r,staticRoutes:o,prerenderRecords:s,shellHtml:i,seo:a,loadI18n:l,pkg:c,write:u,logger:p}){if(!i)throw new Error("[dndev] Build pages: the build output has no index.html (the SPA shell).");if(await u(`/${nt}`,i),a.disabled)return{pages:0,listings:[]};let{createServer:d,loadEnv:f}=await import("vite"),g=f(e,n,"VITE_"),w=a.siteName,m=a.defaultNamespace||"home",h=Xe(ft(a.baseUrl,g.VITE_APP_URL)||null,"VITE_APP_URL",p)??"",R=(a.generateSitemap!==!1||a.llmsTxt!==!1)&&!!(h&&w),E=fi(t),S=s&&E.length>0?mi(g.VITE_APP_URL,p):null,C=S?E:[],k=E.length>0&&(C.length>0||R);if(o.length===0&&C.length===0&&!R)return{pages:0,listings:[]};if(!w)throw new Error("[dndev] Prerendered page titles end with the site name. Set appConfig.app.name (or appConfig.seo.siteName).");let y=null,T=E.map(({route:j})=>j.path);if(k){if(!{...c?.dependencies,...c?.devDependencies}.entities)throw new Error(`[dndev] ${T.join(", ")}: record pages derive their identity from the entity definition, but the app does not depend on an \`entities\` package. Add the entity to the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`);y=gi(c,g,T)}let $=S??g.VITE_APP_URL??"",v=await l(),G={languages:v.supportedLanguages,defaultLanguage:v.fallbackLanguage},A=await d({root:n,configFile:!1,envFile:!1,logLevel:"error",appType:"custom",server:{middlewareMode:!0,hmr:!1,ws:!1,watch:null},optimizeDeps:{noDiscovery:!0,include:[]},resolve:{conditions:zn},ssr:{resolve:{conditions:zn,externalConditions:["react-server"]}}}),L=globalThis._DNDEV_CONFIG_;globalThis._DNDEV_CONFIG_={...L,i18n:{languages:v.supportedLanguages,eager:v.eagerNamespaces,fallback:v.fallbackLanguage,content:v.content}};try{let j=A.environments.ssr.runner,z=await vt(j,"@donotdev/core/server","SEO helpers"),K=await vt(j,"@donotdev/core/rsc","translations"),X={},W,se;if(y){X=await vt(j,"entities","the entity definitions");let V=await vt(j,y.module,"the public reader");W=hi(y.create(V)),se=bn(X,E.map(({route:de})=>de),z.createSchemas)}let _=(V,de)=>K.useTranslation(V,{language:de}).t,{pages:O,skipped:F}=await vi({staticRoutes:o,records:C,crud:W,readSchemas:se,core:z,entities:X,translate:_,routing:G,baseUrl:$,siteName:w,hreflang:a.hreflang!==!1,defaultNamespace:m,defaultImage:a.defaultImage||He,shellHtml:i});for(let V of O)await u(V.file,V.html);F.length>0&&p.warn(`Pages left to the SPA shell (a static page serves the URL, or no file name can hold it): ${F.join(", ")}`);let B=R?await yi({routes:t,blogPosts:r,generator:new Be({baseUrl:h,siteName:w,appRoot:n}),crud:W,readSchemas:se,core:z,entities:X,routing:G,baseUrl:h,siteName:w,siteDescription:a.siteDescription,translations:v.content,defaultNamespace:m,sitemap:a.generateSitemap!==!1,llmsTxt:a.llmsTxt!==!1}):[];for(let{file:V,content:de}of B)await u(V,de);return{pages:O.length,listings:B.map(({file:V})=>V)}}finally{L===void 0?delete globalThis._DNDEV_CONFIG_:globalThis._DNDEV_CONFIG_=L,await A.close()}}function bi(n=!0){if(typeof n=="boolean")return n;throw new Error(`appConfig.prerenderRecords must be true or false. Got ${JSON.stringify(n)}.`)}function Un(n={}){let{routes:e="auto",prerenderRecords:t,seo:r={},i18nStore:o,debug:s,verbose:i,routeManifest:a}=n;if(!a||!o)throw new Error("[dndev] createVitePrerenderPlugin: options.routeManifest and options.i18nStore are required (createVitePlugins passes the route and i18n plugins', createRouteManifestStore / createI18nStore).");let l=e==="auto"&&bi(t),c=M("Prerender",s,i),u=D.getInstance(),p=null,d=!1,f=!1;return{name:"dndev-prerender",enforce:"post",applyToEnvironment(g){return g.name==="client"},configResolved(g){d=g.command==="build",p={outDir:g.build?.outDir||"dist",mode:g.mode}},buildStart(){f=!1},writeBundle(){f=!0},async closeBundle(){if(!f||!p||!d)return;let g=u.getAppRoot(),w=u.resolveAppPath(p.outDir),m=a.get(),h=m.routes,P=new dt({routes:Array.isArray(e)?e:[],debug:s,outDir:w,logger:c}),R=new Map(h.map(y=>[y.path,y])),S=(e==="auto"?[...new Set(Pr(h).filter(y=>!y.includes("*")))]:P.expandRoutes(m)).map(y=>R.get(y)??{path:y}),{pages:C,listings:k}=await Bn({appRoot:g,mode:p.mode,manifestRoutes:h,blogPosts:m.blogPosts,staticRoutes:S,prerenderRecords:l,shellHtml:u.readSync(u.resolvePath("index.html",w)),seo:r,loadI18n:async()=>o.get(),pkg:u.readSync(u.resolveAppPath("package.json"),{format:"json"}),write:(y,T)=>P.writeOutputFile(y,T),logger:c});C>0&&c.info(`Prerendered: ${C} pages`);for(let y of k)c.info(`\u{1F4C4} ${y.slice(1)}`)}}}import{VitePWA as wi}from"vite-plugin-pwa";var yt=class extends pe{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:r}=e,o=[...t,...r];this.logger.debug(`Processing ${o.length} PWA files`);let s=await this._analyzePWAFiles(o),i=[...s.filter(l=>l.type==="manifest"||l.type==="service-worker"),...s.filter(l=>l.type==="icon")],a=this._generatePWAManifest(i);return{assets:i,manifest:a,totalFiles:o.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 r of e){let o=typeof r=="string"?{absolutePath:r,relativePath:this.pathResolver.getRelativePath(r),fileName:r.split("/").pop()||"",extension:(r.split(".").pop()||"").toLowerCase()}:r,s=await this._analyzePWAAsset(o);s&&t.push(s)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let r=e.relativePath,o=e.fileName;return o==="manifest.json"?this._parseManifestFile(t,r):o.includes("service-worker")||o.includes("sw.")?this._parseServiceWorkerFile(t,r):this._isPWAIcon(o)?this._parseIconFile(e,r):null}_parseManifestFile(e,t){try{let r=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:r,size:typeof e=="string"?e.length:JSON.stringify(r).length}}catch(r){return this.logger.debug(`Failed to parse manifest: ${r.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let r=e.fileName,o=this._extractIconSize(r);return{type:"icon",path:t,size:o,format:e.extension,purpose:this._getIconPurpose(r)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(r=>e.includes(r))}_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=this._getDefaultManifest();return t.length>0&&(r.icons=t.map(o=>this.toManifestIcon(o))),r}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},r=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:r==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[r]||`image/${r}`,purpose:e.purpose==="maskable"?"maskable":"any"}}_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 r=this._getWorkboxDefaults(t),o=t.backgroundSync!==!1&&t.backgroundSync,s=t.precacheManifest||[],i=JSON.stringify(s,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
616
+ </rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}},Xt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],Qt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Si(o){let e=["# AI Crawler Management"];if(o==="block-all"){for(let t of[...Xt,...Qt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(o==="allow-all"){for(let t of[...Xt,...Qt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of Xt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of Qt)e.push(`User-agent: ${t}`,"Allow: /","");return e}function St(o){return String(o).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function hr(o,{baseUrl:e,routing:t,trailingSlash:n,crud:r,readSchemas:s,languageUrls:a,hiddenStatuses:i}){let l=[],c=(u,p)=>{let d=a(u,e,t,n),f=t.languages.length>1?{alternates:{languages:d}}:{};for(let g of t.languages)l.push({url:d[g],...p,...f})};for(let{route:u,path:p,record:d}of await Ue(o,r,i,s)){if(!d){c(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??(p==="/"?1:.8),...u.lastModified&&{lastModified:u.lastModified}});continue}let f=d.updatedAt instanceof Date?d.updatedAt.toISOString():d.updatedAt;c(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??.7,...typeof f=="string"&&{lastModified:f}})}return l}function vr(o){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${o.some(n=>n.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let n of o){t.push(" <url>",` <loc>${St(n.url)}</loc>`);for(let[r,s]of Object.entries(n.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${St(r)}" href="${St(s)}" />`);n.lastModified&&t.push(` <lastmod>${St(n.lastModified)}</lastmod>`),n.changeFrequency&&t.push(` <changefreq>${n.changeFrequency}</changefreq>`),n.priority!==void 0&&t.push(` <priority>${n.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
617
+ `)}var et=!1,yr=["react-server","module","node","import","default"];function xi(o){let e=[];for(let t of o){let n=mr(t);n&&e.push({route:n,type:t.meta?.seo?.type??"website"})}return e}function $i(o,e,t){let n={...o?.dependencies,...o?.devDependencies},r=ir(i=>!!n[i]);if(!r)throw new Error(`[dndev] ${t.join(", ")} list published records, but the app's backend provider has no public reader (supported: ${lr}). Mark these pages \`seo: { noindex: true }\`.`);let s=r.env.map(i=>`VITE_${i}`),a=s.map(i=>e[i]);if(a.some(i=>!i))throw new Error(`[dndev] Set ${s.join(" and ")}: the build lists the published records of ${t.join(", ")} (record pages, sitemap.xml, llms.txt).`);return{module:r.module,create:i=>r.create(i,a)}}function Pi(o,e,t=process.env){if(!Qe(o||null,"VITE_APP_URL",e,t))return null;if(o.endsWith("/")||o!==o.trim())throw new Error(`[dndev] VITE_APP_URL "${o}" must have no trailing slash or spaces: the browser builds canonical URLs from it as is.`);return o}function Ri(o){let e=new Map;return{query(t,n,r){let s=JSON.stringify([t,n]);return e.has(s)||e.set(s,o.query(t,n,r)),e.get(s)}}}async function Ci({staticRoutes:o,records:e,crud:t,readSchemas:n,core:r,entities:s,translate:a,routing:i,baseUrl:l,siteName:c,hreflang:u,defaultNamespace:p,defaultImage:d,pageShell:f}){let g=u&&r.isMultilingual(i.languages),v=[],h=[],y=new Set,C=($,S)=>{let x=g?r.languageUrls($,l,i,et):null;for(let N of i.languages){let D=r.localizePath($,N,i),P=qo(D);if(!P||y.has(P)){h.push(D);continue}y.add(P);let k=r.languageUrl($,N,l,i,et),_=S(N,k),m=[..._.tags,...r.siteHeadTags({url:l?k:null,siteName:c,alternates:x,defaultLanguage:i.defaultLanguage})];v.push({file:P,html:Jo(f(N),{tags:m,headScript:r.jsonScriptText({url:k,..._}),headElementId:r.PRERENDERED_HEAD_ELEMENT_ID})})}};for(let $ of o){let S=$.meta??{},x=S.namespace||null;C($.path,(N,D)=>({tags:r.routeHeadTags(r.routeSeo({meta:S,ns:x,defaultNs:p,t:a([x??p],N),siteName:c,baseUrl:l,url:D,defaultImage:d,authOnly:!!$.auth}),{siteName:c,baseUrl:l}),breadcrumb:!1}))}if(e.length>0){let $=new Map(e.map(({route:x,type:N})=>[x.path,N])),S=await Ue(e.map(({route:x})=>x),t,r.HIDDEN_STATUSES,n);for(let{route:x,path:N,record:D}of S){let P=String(D[ke(x.path)[0]]);C(N,k=>{let _=Xo(D,{route:x,value:P,language:k,routing:i,baseUrl:l,trailingSlash:et,siteName:c,defaultImage:d,type:$.get(x.path),entities:s,translate:m=>a(m,k),deriveEntitySeo:r.deriveEntitySeo,buildProductJsonLd:r.buildProductJsonLd,buildBreadcrumbJsonLd:r.buildBreadcrumbJsonLd,languageUrl:r.languageUrl});return{tags:r.recordHeadTags(_),breadcrumb:_.breadcrumb!==null}})}}return{pages:v,skipped:h}}async function _i({routes:o,blogPosts:e,generator:t,crud:n,readSchemas:r,core:s,entities:a,routing:i,baseUrl:l,siteName:c,siteDescription:u,translations:p,defaultNamespace:d,sitemap:f,llmsTxt:g}){let v=t.getSitemapRoutes(o,e),h=[];if(f){let y=await hr(v,{baseUrl:l,routing:i,trailingSlash:et,crud:n,readSchemas:r,languageUrls:s.languageUrls,hiddenStatuses:s.HIDDEN_STATUSES});h.push({file:"/sitemap.xml",content:vr(y)})}if(g){let y=nr({siteName:c,description:u,baseUrl:l,sitemapRoutes:v,routes:o,blogPosts:e,blogPath:t.options.blogPath,translations:p,language:i.defaultLanguage,defaultNamespace:d});h.push({file:"/llms.txt",content:await sr({...y,trailingSlash:et,formatTrailingSlash:s.formatTrailingSlash,entities:a,crud:n,readSchemas:r,deriveEntitySeo:s.deriveEntitySeo,hiddenStatuses:s.HIDDEN_STATUSES})})}return h}async function xt(o,e,t){try{return await o.import(e)}catch(n){throw new Error(`[dndev] Build pages: cannot load "${e}" (${t}): ${n.message}`,{cause:n})}}async function br({appRoot:o,mode:e,manifestRoutes:t,blogPosts:n,staticRoutes:r,prerenderRecords:s,shellHtml:a,pageShell:i,seo:l,loadI18n:c,pkg:u,write:p,logger:d}){if(!a)throw new Error("[dndev] Build pages: the build output has no index.html (the SPA shell).");if(await p(`/${rt}`,a),l.disabled)return{pages:0,listings:[]};let{createServer:f,loadEnv:g}=await import("vite"),v=g(e,o,"VITE_"),h=l.siteName,y=l.defaultNamespace||"home",C=Qe(bt(l.baseUrl,v.VITE_APP_URL)||null,"VITE_APP_URL",d)??"",S=(l.generateSitemap!==!1||l.llmsTxt!==!1)&&!!(C&&h),x=xi(t),N=s&&x.length>0?Pi(v.VITE_APP_URL,d):null,D=N?x:[],P=x.length>0&&(D.length>0||S);if(r.length===0&&D.length===0&&!S)return{pages:0,listings:[]};if(!h)throw new Error("[dndev] Prerendered page titles end with the site name. Set appConfig.app.name (or appConfig.seo.siteName).");let k=null,_=x.map(({route:L})=>L.path);if(P){if(!{...u?.dependencies,...u?.devDependencies}.entities)throw new Error(`[dndev] ${_.join(", ")}: record pages derive their identity from the entity definition, but the app does not depend on an \`entities\` package. Add the entity to the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`);k=$i(u,v,_)}let m=N??v.VITE_APP_URL??"",A=await c(),B={languages:A.supportedLanguages,defaultLanguage:A.fallbackLanguage},w=await f({root:o,configFile:!1,envFile:!1,logLevel:"error",appType:"custom",server:{middlewareMode:!0,hmr:!1,ws:!1,watch:null},optimizeDeps:{noDiscovery:!0,include:[]},resolve:{conditions:yr},ssr:{resolve:{conditions:yr,externalConditions:["react-server"]}}}),M=globalThis._DNDEV_CONFIG_;globalThis._DNDEV_CONFIG_={...M,i18n:{languages:A.supportedLanguages,eager:A.eagerNamespaces,fallback:A.fallbackLanguage,content:A.content}};try{let L=w.environments.ssr.runner,z=await xt(L,"@donotdev/core/server","SEO helpers"),K=await xt(L,"@donotdev/core/rsc","translations"),U={},Z,R;if(k){U=await xt(L,"entities","the entity definitions");let X=await xt(L,k.module,"the public reader");Z=Ri(k.create(X)),R=Zo(U,x.map(({route:te})=>te),z.createSchemas)}let I=(X,te)=>K.useTranslation(X,{language:te}).t,{pages:F,skipped:W}=await Ci({staticRoutes:r,records:D,crud:Z,readSchemas:R,core:z,entities:U,translate:I,routing:B,baseUrl:m,siteName:h,hreflang:l.hreflang!==!1,defaultNamespace:y,defaultImage:l.defaultImage||qe,pageShell:i});for(let X of F)await p(X.file,X.html);W.length>0&&d.warn(`Pages left to the SPA shell (a static page serves the URL, or no file name can hold it): ${W.join(", ")}`);let Q=S?await _i({routes:t,blogPosts:n,generator:new We({baseUrl:C,siteName:h,appRoot:o}),crud:Z,readSchemas:R,core:z,entities:U,routing:B,baseUrl:C,siteName:h,siteDescription:l.siteDescription,translations:A.content,defaultNamespace:y,sitemap:l.generateSitemap!==!1,llmsTxt:l.llmsTxt!==!1}):[];for(let{file:X,content:te}of Q)await p(X,te);return{pages:F.length,listings:Q.map(({file:X})=>X)}}finally{M===void 0?delete globalThis._DNDEV_CONFIG_:globalThis._DNDEV_CONFIG_=M,await w.close()}}function Ai(o=!0){if(typeof o=="boolean")return o;throw new Error(`appConfig.prerenderRecords must be true or false. Got ${JSON.stringify(o)}.`)}function wr(o={}){let{routes:e="auto",prerenderRecords:t,seo:n={},i18nStore:r,fontPlan:s,debug:a,verbose:i,routeManifest:l}=o;if(!l||!r||!s)throw new Error("[dndev] createVitePrerenderPlugin: options.routeManifest, options.i18nStore and options.fontPlan are required (createVitePlugins passes the route, i18n and font plugins', createRouteManifestStore / createI18nStore / createFontPlanStore).");let c=e==="auto"&&Ai(t),u=G("Prerender",a,i),p=O.getInstance(),d=null,f=!1,g=!1;return{name:"dndev-prerender",enforce:"post",applyToEnvironment(v){return v.name==="client"},configResolved(v){f=v.command==="build",d={outDir:v.build?.outDir||"dist",mode:v.mode}},buildStart(){g=!1},writeBundle(){g=!0},async closeBundle(){if(!g||!d||!f)return;let v=p.getAppRoot(),h=p.resolveAppPath(d.outDir),y=l.get(),C=y.routes,$=new yt({routes:Array.isArray(e)?e:[],debug:a,outDir:h,logger:u}),S=new Map(C.map(m=>[m.path,m])),N=(e==="auto"?[...new Set(Ln(C).filter(m=>!m.includes("*")))]:$.expandRoutes(y)).map(m=>S.get(m)??{path:m}),D=p.readSync(p.resolvePath("index.html",h)),{preloads:P}=s.get(),{pages:k,listings:_}=await br({appRoot:v,mode:d.mode,manifestRoutes:C,blogPosts:y.blogPosts,staticRoutes:N,prerenderRecords:c,shellHtml:D,pageShell:m=>xo(D,P[m]),seo:n,loadI18n:async()=>r.get(),pkg:p.readSync(p.resolveAppPath("package.json"),{format:"json"}),write:(m,A)=>$.writeOutputFile(m,A),logger:u});k>0&&u.info(`Prerendered: ${k} pages`);for(let m of _)u.info(`\u{1F4C4} ${m.slice(1)}`)}}}import{VitePWA as Ni}from"vite-plugin-pwa";var $t=class extends fe{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:n}=e,r=[...t,...n];this.logger.debug(`Processing ${r.length} PWA files`);let s=await this._analyzePWAFiles(r),a=[...s.filter(l=>l.type==="manifest"||l.type==="service-worker"),...s.filter(l=>l.type==="icon")],i=this._generatePWAManifest(a);return{assets:a,manifest:i,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 n of e){let r=typeof n=="string"?{absolutePath:n,relativePath:this.pathResolver.getRelativePath(n),fileName:n.split("/").pop()||"",extension:(n.split(".").pop()||"").toLowerCase()}:n,s=await this._analyzePWAAsset(r);s&&t.push(s)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let n=e.relativePath,r=e.fileName;return r==="manifest.json"?this._parseManifestFile(t,n):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,n):this._isPWAIcon(r)?this._parseIconFile(e,n):null}_parseManifestFile(e,t){try{let n=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:n,size:typeof e=="string"?e.length:JSON.stringify(n).length}}catch(n){return this.logger.debug(`Failed to parse manifest: ${n.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let n=e.fileName,r=this._extractIconSize(n);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(n)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(n=>e.includes(n))}_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(r=>r.type==="icon"),n=this._getDefaultManifest();return t.length>0&&(n.icons=t.map(r=>this.toManifestIcon(r))),n}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},n=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:n==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[n]||`image/${n}`,purpose:e.purpose==="maskable"?"maskable":"any"}}_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 n=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,s=t.precacheManifest||[],a=JSON.stringify(s,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
612
618
  // Generated at ${new Date().toISOString()}
613
619
 
614
620
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
@@ -618,19 +624,19 @@ const { registerRoute } = workbox.routing;
618
624
  const { CacheFirst, NetworkFirst, StaleWhileRevalidate } = workbox.strategies;
619
625
  const { ExpirationPlugin } = workbox.expiration;
620
626
  const { CacheableResponsePlugin } = workbox.cacheableResponse;
621
- ${o?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
627
+ ${r?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
622
628
 
623
629
  // Clean up outdated caches
624
630
  cleanupOutdatedPrecaches();
625
631
 
626
632
  // Precache static assets
627
- const precacheManifest = ${i.length>2?i:"self.__WB_MANIFEST || []"};
633
+ const precacheManifest = ${a.length>2?a:"self.__WB_MANIFEST || []"};
628
634
  precacheAndRoute(precacheManifest);
629
635
 
630
636
  // Runtime caching strategies
631
- ${this._generateWorkboxRuntimeCaching(r.runtimeCaching,t)}
637
+ ${this._generateWorkboxRuntimeCaching(n.runtimeCaching,t)}
632
638
 
633
- ${o?this._generateBackgroundSync(t.backgroundSync):""}
639
+ ${r?this._generateBackgroundSync(t.backgroundSync):""}
634
640
 
635
641
  // Skip waiting and claim clients
636
642
  self.addEventListener('message', (event) => {
@@ -642,27 +648,27 @@ self.addEventListener('message', (event) => {
642
648
  self.addEventListener('activate', (event) => {
643
649
  event.waitUntil(self.clients.claim());
644
650
  });
645
- `}_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((r,o)=>{let{urlPattern:s,handler:i,options:a={}}=r,l=i==="CacheFirst"?"CacheFirst":i==="NetworkFirst"?"NetworkFirst":i==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",c;typeof s=="function"?c="({ request }) => request.destination === 'document'":s instanceof RegExp?c=s.toString():c=JSON.stringify(s);let u=[];a.expiration&&u.push(`new ExpirationPlugin({
646
- maxEntries: ${a.expiration.maxEntries||50},
647
- maxAgeSeconds: ${a.expiration.maxAgeSeconds||3600*24},
648
- })`),a.cacheableResponse&&u.push(`new CacheableResponsePlugin({
649
- statuses: ${JSON.stringify(a.cacheableResponse.statuses||[0,200])},
650
- })`),a.backgroundSync&&u.push(`new BackgroundSyncPlugin('${a.backgroundSync.queueName||"background-sync-queue"}', {
651
- maxRetentionTime: ${a.backgroundSync.maxRetentionTime||1440},
652
- })`);let p="";return a.cacheName&&(p+=`
653
- cacheName: '${a.cacheName}',`),u.length>0&&(p+=`
651
+ `}_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((n,r)=>{let{urlPattern:s,handler:a,options:i={}}=n,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",c;typeof s=="function"?c="({ request }) => request.destination === 'document'":s instanceof RegExp?c=s.toString():c=JSON.stringify(s);let u=[];i.expiration&&u.push(`new ExpirationPlugin({
652
+ maxEntries: ${i.expiration.maxEntries||50},
653
+ maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
654
+ })`),i.cacheableResponse&&u.push(`new CacheableResponsePlugin({
655
+ statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
656
+ })`),i.backgroundSync&&u.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
657
+ maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
658
+ })`);let p="";return i.cacheName&&(p+=`
659
+ cacheName: '${i.cacheName}',`),u.length>0&&(p+=`
654
660
  plugins: [
655
661
  ${u.join(`,
656
662
  `)}
657
- ],`),a.networkTimeoutSeconds&&(p+=`
658
- networkTimeoutSeconds: ${a.networkTimeoutSeconds},`),`// Runtime cache ${o+1}: ${a.cacheName||"cache-"+o}
663
+ ],`),i.networkTimeoutSeconds&&(p+=`
664
+ networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${i.cacheName||"cache-"+r}
659
665
  registerRoute(
660
666
  ${c},
661
667
  new ${l}({${p}
662
668
  })
663
669
  );`}).join(`
664
670
 
665
- `)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",r=e.maxRetentionTime||1440,o=e.urlPattern||/\/api\/.*/i,s;return typeof o=="function"||o instanceof RegExp?s=o.toString():s=JSON.stringify(o),`
671
+ `)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",n=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,s;return typeof r=="function"||r instanceof RegExp?s=r.toString():s=JSON.stringify(r),`
666
672
  // Background sync for offline actions
667
673
  const { NetworkOnly } = workbox.strategies;
668
674
  registerRoute(
@@ -670,17 +676,17 @@ registerRoute(
670
676
  new NetworkOnly({
671
677
  plugins: [
672
678
  new BackgroundSyncPlugin('${t}', {
673
- maxRetentionTime: ${r},
679
+ maxRetentionTime: ${n},
674
680
  }),
675
681
  ],
676
682
  }),
677
683
  'POST'
678
684
  );
679
- `}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`),r=this.pathResolver.resolveAppPath(`${e}/static/chunks`),o=this.pathResolver.resolveAppPath(`${e}/static/css`),s=[];try{let i=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${r}/**/*.{js,css}`,`${o}/**/*.css`];for(let a of i){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),a.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let c of l){let u=this.pathResolver.getRelativePath(c);if(u.startsWith(`${e}/static/`)){let p=`/_next/${u.replace(`${e}/static/`,"")}`;s.push({url:p,revision:null})}}}}catch(i){this.logger?.warn(`Failed to discover Next.js build assets: ${i.message}`)}return s}generatePrecacheManifest(e=[],t=null){let r=e;return t&&typeof t=="function"&&(r=t(r)),r}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};q();function Gn(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=M("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 r=D.getInstance(),o=new yt(r,n),s=n.devEnabled===!0,i={registerType:n.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let c=n.app||{},p=(await o.discoverPWAAssets()).assets.filter(d=>d.type==="icon").map(d=>o.toManifestIcon(d));return{name:c.name,short_name:c.shortName,description:c.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:p.length>0?p:[]}},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 u=c.find(p=>p.url==="/index.html"||p.url==="index.html");return u&&!c.find(p=>p.url==="/")&&c.push({url:"/",revision:u.revision}),{manifest:c,warnings:[]}}]},devOptions:{enabled:s,type:"module"}},l={...i,manifest:async()=>{let c=await i.manifest();if(n.manifest){if(typeof n.manifest=="function"){let u=await n.manifest();return{...c,...u}}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 wi(l)}J();J();var Ei=/^[A-Za-z_$][\w$]*$/,xi=/^(?:'[^'\\]*'|"[^"\\]*"|`[^`\\$]*`|-?\d[\w.]*|null|undefined|true|false)$/;function Si(n,e){let t=0;for(let r=e;r<n.length;r++){let o=n[r];if(o==="'"||o==='"'||o==="`"){for(r++;r<n.length&&n[r]!==o;r++)n[r]==="\\"&&r++;continue}if(t===0&&(o===","||o==="/"&&/[/*]/.test(n[r+1]??"")))return r;if("([{".includes(o))t++;else if(")]}".includes(o)){if(t===0)return r;t--}}return n.length}function Ri(n){let e=/(^|[{,\s])entity\s*:\s*/gm,t="",r=0,o;for(;o=e.exec(n);){let s=o.index+o[0].length,i=Si(n,s),a=n.slice(s,i).trimEnd();if(!a)continue;let l=xi.test(a)?a:Ei.test(a)?`{ identifier: '${a}' }`:`{ expression: ${JSON.stringify(a)} }`;t+=n.slice(r,s)+l,r=s+a.length,e.lastIndex=r}return t+n.slice(r)}function Pi(n){let e=n instanceof Error?n.message:String(n),t=/^(\S+) is not defined$/.exec(e)?.[1];return t?`\`${t}\` is not a literal value (an import, a variable or a call)`:`it is not a plain object literal (${e})`}function Wn(n,e="unknown"){let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,r=n.match(t);if(!r)return null;let o=r[1];o=o.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(a,l)=>`icon: '${l}'`),o=Ri(o);let s=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;[...n.matchAll(s)].forEach(a=>{let l=a[1],c=a[2];o=o.replace(new RegExp(`\\b${l}\\b`,"g"),`'${c}'`)});try{return Function(`return ${o}`)()}catch(a){throw H("dndev-routes",`${e}: PageMeta cannot be read at build: ${Pi(a)}. Without it the page would lose its route, auth and seo. The build reads PageMeta statically: write every value as a literal in the object (strings, numbers, booleans, null, arrays and objects of those, icon: <Icon />, a string constant declared in the page file: const NAMESPACE = 'home'), except entity, the defineEntity identifier imported from 'entities'. Example: auth: { required: true, role: 'admin' } instead of auth: ADMIN_ONLY.`,"invalid-configuration")}}function Vn(n){return/^[ \t]*export\s+(?:(?:async\s+)?function\s*\*?\s*generateMetadata\b|(?:const|let)\s+generateMetadata\b|\{[^}]*\bgenerateMetadata\b[^}]*\})/m.test(n)}import{existsSync as Wt,readFileSync as Gt,realpathSync as $i}from"node:fs";import{dirname as Hn,join as et,resolve as Jn}from"node:path";var xe="dndev-routes",bt="entities",Ci="@donotdev/core",qn=[".ts",".tsx",".js",".jsx"],_i=`import { productEntity } from 'entities';
680
- export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,Kn=null;async function Qn(){return Kn??=import("@babel/core").then(n=>n.default??n),Kn}function eo(n,e,t){let r=/\.[jt]sx$/.test(t);try{return n.parseSync(e,{configFile:!1,babelrc:!1,filename:t,sourceType:"module",parserOpts:{plugins:r?["typescript","jsx"]:["typescript"]}}).program}catch(o){throw H(xe,`${t} could not be parsed to resolve entities (PageMeta entity, entity field types): ${o.message}. Fix the syntax error.`,"invalid-configuration")}}function De(n){return n.type==="StringLiteral"?n.value:n.name}function Ue(n){let e=n;for(;e&&["TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","ParenthesizedExpression"].includes(e.type);)e=e.expression;return e}function Ai(n,e){for(let t of n.body)if(!(t.type!=="ImportDeclaration"||t.importKind==="type")){for(let r of t.specifiers)if(r.local.name===e)return t.source.value!==bt||r.type!=="ImportSpecifier"||r.importKind==="type"?null:De(r.imported)}return null}function Vt(n){let e=null,t=new Map;function r(){let u=et(n,"package.json"),p=Wt(u)?JSON.parse(Gt(u,"utf8")):null;return!!(p?.dependencies?.[bt]||p?.devDependencies?.[bt])}function o(u){if(e)return e;let p=r(),d=n,f=null;for(;p;){let m=et(d,"node_modules",bt);if(Wt(et(m,"package.json"))){f=$i(m);break}let h=Hn(d);if(h===d)break;d=h}if(!f)throw H(xe,`${u}, but the app has no \`entities\` package (${p?"not installed: run bun install":"not in the dependencies of its package.json"}). The entity is read from the app's defineEntity definitions. Fix: add \`"entities": "workspace:*"\` to the app's dependencies and export the entity from the entities package.`,"missing-required-resource");let g=JSON.parse(Gt(et(f,"package.json"),"utf8")),w=Xn(Jn(f,g.main??"./index.ts"));if(!w)throw H(xe,`The \`entities\` package (${f}) has no entry module (package.json "main": ${JSON.stringify(g.main??"./index.ts")}). Fix: set "main" to its index file (./index.ts).`,"missing-required-resource");return e=w,e}async function s(u){if(!t.has(u)){let p=await Qn();t.set(u,eo(p,Gt(u,"utf8"),u))}return t.get(u)}function i(u,p){return p.startsWith(".")?Xn(Jn(Hn(u),p)):null}async function a(u,p,d){let f=`${u}#${p}`;if(d.has(f))return null;d.add(f);let g=await s(u),w=[];for(let m of g.body)if(m.type==="ExportNamedDeclaration"&&m.exportKind!=="type"){let h=Zn(m.declaration,p);if(h!==void 0)return{init:h,program:g,file:u};for(let P of m.specifiers??[]){if(P.exportKind==="type"||De(P.exported)!==p)continue;if(P.type!=="ExportSpecifier")return null;let R=De(P.local);if(m.source){let E=i(u,m.source.value);return E?a(E,R,d):null}return l(u,g,R,d)}}else if(m.type==="ExportAllDeclaration"&&m.exportKind!=="type"){let h=i(u,m.source.value);h&&w.push(h)}for(let m of w){let h=await a(m,p,d);if(h)return h}return null}async function l(u,p,d,f){for(let g of p.body){let w=Zn(g,d);if(w!==void 0)return{init:w,program:p,file:u};if(!(g.type!=="ImportDeclaration"||g.importKind==="type"))for(let m of g.specifiers){if(m.local.name!==d||m.type!=="ImportSpecifier")continue;let h=i(u,g.source.value);return h?a(h,De(m.imported),f):null}}return null}async function c(u){let p=[u];for(let d=0;d<p.length;d+=1){let f=await s(p[d]);for(let g of f.body){if(!(g.type==="ImportDeclaration"&&g.importKind!=="type"||g.type==="ExportNamedDeclaration"&&g.source&&g.exportKind!=="type"||g.type==="ExportAllDeclaration"&&g.exportKind!=="type"))continue;let m=i(p[d],g.source.value);m&&!p.includes(m)&&p.push(m)}}return p}return{async usesFieldType(u){if(!r())return!1;for(let p of await c(o("The app's package.json lists `entities` (its entity field types are read)")))if(Ni(await s(p),u))return!0;return!1},async collectionOf(u,p){let d=await a(o(`${p} declares a PageMeta entity`),u,new Set);if(!d)throw H(xe,`${p}: PageMeta entity \`${u}\` is not exported by the \`entities\` package. The page names the entity definition it shows a record of. Fix: export it from the entities package index (export { ${u} } from './\u2026').`,"invalid-configuration");return Di(d,u,p)}}}function to(n){return n.body.filter(e=>e.type==="ImportDeclaration"&&e.source.value===Ci).flatMap(e=>e.specifiers).find(e=>e.type==="ImportSpecifier"&&De(e.imported)==="defineEntity")?.local.name}function Yn(n,e){if(n?.type!=="ObjectExpression")return;let t=n.properties.find(r=>r.type==="ObjectProperty"&&!r.computed&&De(r.key)===e);return Ue(t?.value)}function Ni(n,e){let t=to(n);if(!t)return!1;let r=o=>{if(!o||typeof o.type!="string")return!1;if(o.type==="CallExpression"&&o.callee.type==="Identifier"&&o.callee.name===t){let s=Yn(Ue(o.arguments[0]),"fields");if(s?.type==="ObjectExpression"&&s.properties.some(i=>{let a=Yn(Ue(i.value),"type");return a?.type==="StringLiteral"&&a.value===e}))return!0}for(let s of Object.keys(o)){if(s==="loc"||s==="leadingComments"||s==="trailingComments")continue;let i=o[s];if(Array.isArray(i)?i.some(r):i&&typeof i=="object"&&r(i))return!0}return!1};return r(n)}function Zn(n,e){if(n?.type==="VariableDeclaration"){for(let t of n.declarations)if(t.id.type==="Identifier"&&t.id.name===e)return t.init??null}}function Xn(n){let e=n.replace(/\.[cm]?js$/,""),t=[n,...qn.map(r=>`${e}${r}`),...qn.map(r=>et(n,`index${r}`))];for(let r of t)if(/\.[cm]?[jt]sx?$/.test(r)&&Wt(r))return r;return null}function Di({init:n,program:e,file:t},r,o){let s=Ue(n),i=to(e);if(s?.type!=="CallExpression"||s.callee.type!=="Identifier"||!i||s.callee.name!==i)throw H(xe,`${o}: PageMeta entity \`${r}\` (${t}) is not a defineEntity definition. The build reads the collection from \`defineEntity({ collection: ... })\` in the entities package. Fix: export const ${r} = defineEntity({ name: '...', collection: '...', fields: { ... } }) with defineEntity imported from '@donotdev/core'.`,"invalid-configuration");let a=Ue(s.arguments[0]),l=a?.type==="ObjectExpression"?a.properties.find(p=>p.type==="ObjectProperty"&&!p.computed&&De(p.key)==="collection"):void 0,c=Ue(l?.value),u=c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0].value.cooked:null;if(!u)throw H(xe,`${o}: PageMeta entity \`${r}\` (${t}) has no literal \`collection\` in its defineEntity options. The page's records (sitemap, prerender, server metadata) are read from it. Fix: set collection: 'products' (a string literal) in the defineEntity call.`,"invalid-configuration");return u}async function ro(n,e,t,r){if(!n||n.entity===void 0)return null;let o=n.entity?.identifier,s=n.entity?.expression;if(typeof s=="string"){let l=s.match(/^[A-Za-z_$][\w$]*\s*\??\.\s*([A-Za-z_$][\w$]*)$/)?.[1]??"productEntity";throw H(xe,`${t}: PageMeta entity \`${s}\` is not a bare identifier. The build reads the entity statically: only a defineEntity definition named-imported from 'entities' resolves to its collection (no namespace import, member access or call). Fix: import { ${l} } from 'entities'; then entity: ${l}`,"invalid-configuration")}if(typeof o!="string")throw H(xe,`${t}: PageMeta entity must be the entity definition imported from 'entities' (got ${JSON.stringify(n.entity)}). The build resolves it to the entity's collection. Fix:
681
- ${_i}`,"invalid-configuration");let i=eo(await Qn(),e,t),a=Ai(i,o);if(!a)throw H(xe,`${t}: PageMeta entity \`${o}\` is not imported from 'entities'. The page's entity must be a defineEntity definition of the app's \`entities\` package (one source for its collection). Fix: import { ${o} } from 'entities';`,"invalid-configuration");return r.collectionOf(a,t)}var Ge=null,no=null;function ki(n){let t=(n.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Ti(n){let e=n.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw H("dndev-routes",`${n.file}: PageMeta signedInRedirect must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`,"invalid-configuration");if(e.split(/[?#]/)[0]===n.path)throw H("dndev-routes",`${n.file}: PageMeta signedInRedirect points at the page itself (${e}): signed-in visitors would loop. Use another page.`,"invalid-configuration")}}function Oi(n,{pageGenerateMetadata:e=!1}={}){if(!n.path.split("/").some(r=>r.startsWith(":"))||Ut(n)||!mt(n)||n.meta?.entity||n.metaExport?.namespace==="blog"||e&&n.exportsGenerateMetadata)return;let t=["declare the record entity it shows: import { productEntity } from 'entities'; then entity: productEntity in its PageMeta (title, description and image from the record)",...e?["export Next's generateMetadata from the page module (a server module, no 'use client')"]:[],"keep it out of search engines: seo: { noindex: true } in its PageMeta"];throw H("dndev-routes",`${n.file}: public dynamic route ${n.path} has no per-URL SEO: every URL would get the same title and description (PageMeta + i18n), duplicate pages for search engines. Fix, one of:
682
- `+t.map((r,o)=>` ${o+1}. ${r}`).join(`
683
- `),"invalid-configuration")}var wt=class extends pe{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(),r=process.env.DNDEV_BUILD_ID;if(Ge&&no===r)return this.logger.debug("Using cached route discovery results"),this.routes=Ge.routes,this.errors=Ge.errors,this.source=Ge.source,this.entityResolver=Ge.entityResolver,{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 o=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${o} files in ${t}`);let s=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(s)}`)}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/"),Ge={routes:this.routes,errors:this.errors,source:this.source,entityResolver:this.entityResolver},no=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"}`}getEntityResolver(){return this.entityResolver??=Vt(this.pathResolver.getAppRoot()),this.entityResolver}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:r}=e;this.entityResolver=Vt(t);let o=await this._batchProcessFiles(r,c=>this._analyzePageFile(c,t)),s=await this._scanAdditionalPatterns(t),i=await this._batchProcessFiles(s,c=>this._analyzePageFile(c,t)),a=[...o,...i];this.logger.debug(`Auto-discovering from ${r.length} app + ${s.length} additional files`),this.routes=a.filter(c=>c.path==="home"||c.path==="/home"?(this.logger.debug(`Filtered reserved route: ${c.path} - Use root "/" instead (${c.file})`),!1):!0);let l=new Map;for(let c of this.routes){let u=c.path;if(l.has(u)){let p=l.get(u);throw H("dndev-routes",`${c.file}: route ${u} is also the route of ${p.file}: two pages cannot share a URL. Give one of them another path with a PageMeta route override, e.g. export const meta: PageMeta = { route: '/custom-path' };`,"invalid-configuration")}l.set(u,c),Ti(c),Oi(c,{pageGenerateMetadata:this.options.pageGenerateMetadata===!0})}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${r.length+s.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(r=>this.pathResolver.resolveAppPath(r));if(t.length===0)return[];try{let{consumerFiles:r}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return r}catch(r){return this.logger.debug(`Error scanning additional patterns: ${r.message}`),[]}}async _analyzePageFile(e,t){let r=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!r)return null;let o=e.relativePath,s="/src/"+o.replace(/\\/g,"/");s=s.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let i=this._extractMetaExport(r,o),a=ki(s),c=a===Rt.HOMEPAGE_COMPONENT?Rt.HOMEPAGE_PATH:this._resolveRoutePath(i,o,e.absolutePath),u=this._extractPageMeta(o),p=await ro(i,r,o,this.entityResolver),{entity:d,action:f,...g}=i||{};return{path:c,component:a,importPath:s,auth:i?.auth||!1,meta:{...u,...g,...p&&{entity:p},action:u.action},metaExport:i&&{...i,...p&&{entity:p}},exportsGenerateMetadata:Vn(r),file:o}}_extractMetaExport(e,t){try{let r=Wn(e,t);return r?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(r)}`),r):null}catch(r){if(ve(r))throw r;return this.logger.debug(`Error parsing meta export from ${t}: ${r.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,r){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let o=e.route.trim();return o==="/"?"/":(o=o.replace(/\/+/g,"/"),o.startsWith("/")||(o="/"+o),o)}if(typeof e.route=="object"&&e.route!==null){let o=this._generateRoutePath(t),s=e.route.params;if(Array.isArray(s)&&s.length>0){let i=s.map(a=>`:${a}`).join("/");return`${o}/${i}`}return o}return this.logger.warn(`Invalid route format in ${r}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${r}`),this._generateRoutePath(t)}_extractPageMeta(e){let t=e.split("/").pop()?.replace(".tsx","")||"",r=t.replace(/Page$/,"");r=r.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),s=null;return o.length>1&&(t.includes("List")?s="list":t.includes("Form")||t.includes("Create")||t.includes("Edit")?s="form":(t.includes("Detail")||t.includes("View"))&&(s="detail")),{title:r,action:s,file:e}}};q();var Ii={isEmpty:n=>!n.routes||n.routes.length===0,generateModule:(n,e,t="routes")=>{let r={totalRoutes:n.routes.length,authRequired:n.routes.filter(s=>s.auth&&s.auth.required).length,publicRoutes:n.routes.filter(s=>!s.auth||s.auth===!1).length,source:n.source,generatedAt:new Date().toISOString(),errors:n.errors.length,hasBlogFeed:xr(D.getInstance().getAppRoot())},o=n.routes.map(s=>` {
685
+ `}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`),n=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),s=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${n}/**/*.{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 c of l){let u=this.pathResolver.getRelativePath(c);if(u.startsWith(`${e}/static/`)){let p=`/_next/${u.replace(`${e}/static/`,"")}`;s.push({url:p,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return s}generatePrecacheManifest(e=[],t=null){let n=e;return t&&typeof t=="function"&&(n=t(n)),n}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};Y();function Er(o={}){if(!o.enabled)return null;let e=o.app||{},t=[];if(e.name||t.push("name"),e.shortName||t.push("shortName"),e.description||t.push("description"),t.length>0){let c=G("PWA",o.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 n=O.getInstance(),r=new $t(n,o),s=o.devEnabled===!0,a={registerType:o.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let c=o.app||{},p=(await r.discoverPWAAssets()).assets.filter(d=>d.type==="icon").map(d=>r.toManifestIcon(d));return{name:c.name,short_name:c.shortName,description:c.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:p.length>0?p:[]}},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 u=c.find(p=>p.url==="/index.html"||p.url==="index.html");return u&&!c.find(p=>p.url==="/")&&c.push({url:"/",revision:u.revision}),{manifest:c,warnings:[]}}]},devOptions:{enabled:s,type:"module"}},l={...a,manifest:async()=>{let c=await a.manifest();if(o.manifest){if(typeof o.manifest=="function"){let u=await o.manifest();return{...c,...u}}return{...c,...o.manifest}}return c},workbox:{...a.workbox,...o.workbox||{},runtimeCaching:[...a.workbox.runtimeCaching,...o.workbox?.runtimeCaching||[]],manifestTransforms:[...a.workbox.manifestTransforms||[],...o.workbox?.manifestTransforms||[]]}};return Ni(l)}q();q();var ki=/^[A-Za-z_$][\w$]*$/,Di=/^(?:'[^'\\]*'|"[^"\\]*"|`[^`\\$]*`|-?\d[\w.]*|null|undefined|true|false)$/;function Ti(o,e){let t=0;for(let n=e;n<o.length;n++){let r=o[n];if(r==="'"||r==='"'||r==="`"){for(n++;n<o.length&&o[n]!==r;n++)o[n]==="\\"&&n++;continue}if(t===0&&(r===","||r==="/"&&/[/*]/.test(o[n+1]??"")))return n;if("([{".includes(r))t++;else if(")]}".includes(r)){if(t===0)return n;t--}}return o.length}function Oi(o){let e=/(^|[{,\s])entity\s*:\s*/gm,t="",n=0,r;for(;r=e.exec(o);){let s=r.index+r[0].length,a=Ti(o,s),i=o.slice(s,a).trimEnd();if(!i)continue;let l=Di.test(i)?i:ki.test(i)?`{ identifier: '${i}' }`:`{ expression: ${JSON.stringify(i)} }`;t+=o.slice(n,s)+l,n=s+i.length,e.lastIndex=n}return t+o.slice(n)}function Ii(o){let e=o instanceof Error?o.message:String(o),t=/^(\S+) is not defined$/.exec(e)?.[1];return t?`\`${t}\` is not a literal value (an import, a variable or a call)`:`it is not a plain object literal (${e})`}function Sr(o,e="unknown"){let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,n=o.match(t);if(!n)return null;let r=n[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,l)=>`icon: '${l}'`),r=Oi(r);let s=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;[...o.matchAll(s)].forEach(i=>{let l=i[1],c=i[2];r=r.replace(new RegExp(`\\b${l}\\b`,"g"),`'${c}'`)});try{return Function(`return ${r}`)()}catch(i){throw H("dndev-routes",`${e}: PageMeta cannot be read at build: ${Ii(i)}. Without it the page would lose its route, auth and seo. The build reads PageMeta statically: write every value as a literal in the object (strings, numbers, booleans, null, arrays and objects of those, icon: <Icon />, a string constant declared in the page file: const NAMESPACE = 'home'), except entity, the defineEntity identifier imported from 'entities'. Example: auth: { required: true, role: 'admin' } instead of auth: ADMIN_ONLY.`,"invalid-configuration")}}function xr(o){return/^[ \t]*export\s+(?:(?:async\s+)?function\s*\*?\s*generateMetadata\b|(?:const|let)\s+generateMetadata\b|\{[^}]*\bgenerateMetadata\b[^}]*\})/m.test(o)}import{existsSync as nn,readFileSync as tn,realpathSync as Fi}from"node:fs";import{dirname as $r,join as tt,resolve as Pr}from"node:path";var Ce="dndev-routes",Pt="entities",Mi="@donotdev/core",Rr=[".ts",".tsx",".js",".jsx"],Li=`import { productEntity } from 'entities';
686
+ export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,Cr=null;async function kr(){return Cr??=import("@babel/core").then(o=>o.default??o),Cr}function Dr(o,e,t){let n=/\.[jt]sx$/.test(t);try{return o.parseSync(e,{configFile:!1,babelrc:!1,filename:t,sourceType:"module",parserOpts:{plugins:n?["typescript","jsx"]:["typescript"]}}).program}catch(r){throw H(Ce,`${t} could not be parsed to resolve entities (PageMeta entity, entity field types): ${r.message}. Fix the syntax error.`,"invalid-configuration")}}function Ie(o){return o.type==="StringLiteral"?o.value:o.name}function Ge(o){let e=o;for(;e&&["TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","ParenthesizedExpression"].includes(e.type);)e=e.expression;return e}function ji(o,e){for(let t of o.body)if(!(t.type!=="ImportDeclaration"||t.importKind==="type")){for(let n of t.specifiers)if(n.local.name===e)return t.source.value!==Pt||n.type!=="ImportSpecifier"||n.importKind==="type"?null:Ie(n.imported)}return null}function on(o){let e=null,t=new Map;function n(){let u=tt(o,"package.json"),p=nn(u)?JSON.parse(tn(u,"utf8")):null;return!!(p?.dependencies?.[Pt]||p?.devDependencies?.[Pt])}function r(u){if(e)return e;let p=n(),d=o,f=null;for(;p;){let h=tt(d,"node_modules",Pt);if(nn(tt(h,"package.json"))){f=Fi(h);break}let y=$r(d);if(y===d)break;d=y}if(!f)throw H(Ce,`${u}, but the app has no \`entities\` package (${p?"not installed: run bun install":"not in the dependencies of its package.json"}). The entity is read from the app's defineEntity definitions. Fix: add \`"entities": "workspace:*"\` to the app's dependencies and export the entity from the entities package.`,"missing-required-resource");let g=JSON.parse(tn(tt(f,"package.json"),"utf8")),v=Nr(Pr(f,g.main??"./index.ts"));if(!v)throw H(Ce,`The \`entities\` package (${f}) has no entry module (package.json "main": ${JSON.stringify(g.main??"./index.ts")}). Fix: set "main" to its index file (./index.ts).`,"missing-required-resource");return e=v,e}async function s(u){if(!t.has(u)){let p=await kr();t.set(u,Dr(p,tn(u,"utf8"),u))}return t.get(u)}function a(u,p){return p.startsWith(".")?Nr(Pr($r(u),p)):null}async function i(u,p,d){let f=`${u}#${p}`;if(d.has(f))return null;d.add(f);let g=await s(u),v=[];for(let h of g.body)if(h.type==="ExportNamedDeclaration"&&h.exportKind!=="type"){let y=Ar(h.declaration,p);if(y!==void 0)return{init:y,program:g,file:u};for(let C of h.specifiers??[]){if(C.exportKind==="type"||Ie(C.exported)!==p)continue;if(C.type!=="ExportSpecifier")return null;let $=Ie(C.local);if(h.source){let S=a(u,h.source.value);return S?i(S,$,d):null}return l(u,g,$,d)}}else if(h.type==="ExportAllDeclaration"&&h.exportKind!=="type"){let y=a(u,h.source.value);y&&v.push(y)}for(let h of v){let y=await i(h,p,d);if(y)return y}return null}async function l(u,p,d,f){for(let g of p.body){let v=Ar(g,d);if(v!==void 0)return{init:v,program:p,file:u};if(!(g.type!=="ImportDeclaration"||g.importKind==="type"))for(let h of g.specifiers){if(h.local.name!==d||h.type!=="ImportSpecifier")continue;let y=a(u,g.source.value);return y?i(y,Ie(h.imported),f):null}}return null}async function c(u){let p=[u];for(let d=0;d<p.length;d+=1){let f=await s(p[d]);for(let g of f.body){if(!(g.type==="ImportDeclaration"&&g.importKind!=="type"||g.type==="ExportNamedDeclaration"&&g.source&&g.exportKind!=="type"||g.type==="ExportAllDeclaration"&&g.exportKind!=="type"))continue;let h=a(p[d],g.source.value);h&&!p.includes(h)&&p.push(h)}}return p}return{async usesFieldType(u){if(!n())return!1;for(let p of await c(r("The app's package.json lists `entities` (its entity field types are read)")))if(zi(await s(p),u))return!0;return!1},async collectionOf(u,p){let d=await i(r(`${p} declares a PageMeta entity`),u,new Set);if(!d)throw H(Ce,`${p}: PageMeta entity \`${u}\` is not exported by the \`entities\` package. The page names the entity definition it shows a record of. Fix: export it from the entities package index (export { ${u} } from './\u2026').`,"invalid-configuration");return Bi(d,u,p)}}}function Tr(o){return o.body.filter(e=>e.type==="ImportDeclaration"&&e.source.value===Mi).flatMap(e=>e.specifiers).find(e=>e.type==="ImportSpecifier"&&Ie(e.imported)==="defineEntity")?.local.name}function _r(o,e){if(o?.type!=="ObjectExpression")return;let t=o.properties.find(n=>n.type==="ObjectProperty"&&!n.computed&&Ie(n.key)===e);return Ge(t?.value)}function zi(o,e){let t=Tr(o);if(!t)return!1;let n=r=>{if(!r||typeof r.type!="string")return!1;if(r.type==="CallExpression"&&r.callee.type==="Identifier"&&r.callee.name===t){let s=_r(Ge(r.arguments[0]),"fields");if(s?.type==="ObjectExpression"&&s.properties.some(a=>{let i=_r(Ge(a.value),"type");return i?.type==="StringLiteral"&&i.value===e}))return!0}for(let s of Object.keys(r)){if(s==="loc"||s==="leadingComments"||s==="trailingComments")continue;let a=r[s];if(Array.isArray(a)?a.some(n):a&&typeof a=="object"&&n(a))return!0}return!1};return n(o)}function Ar(o,e){if(o?.type==="VariableDeclaration"){for(let t of o.declarations)if(t.id.type==="Identifier"&&t.id.name===e)return t.init??null}}function Nr(o){let e=o.replace(/\.[cm]?js$/,""),t=[o,...Rr.map(n=>`${e}${n}`),...Rr.map(n=>tt(o,`index${n}`))];for(let n of t)if(/\.[cm]?[jt]sx?$/.test(n)&&nn(n))return n;return null}function Bi({init:o,program:e,file:t},n,r){let s=Ge(o),a=Tr(e);if(s?.type!=="CallExpression"||s.callee.type!=="Identifier"||!a||s.callee.name!==a)throw H(Ce,`${r}: PageMeta entity \`${n}\` (${t}) is not a defineEntity definition. The build reads the collection from \`defineEntity({ collection: ... })\` in the entities package. Fix: export const ${n} = defineEntity({ name: '...', collection: '...', fields: { ... } }) with defineEntity imported from '@donotdev/core'.`,"invalid-configuration");let i=Ge(s.arguments[0]),l=i?.type==="ObjectExpression"?i.properties.find(p=>p.type==="ObjectProperty"&&!p.computed&&Ie(p.key)==="collection"):void 0,c=Ge(l?.value),u=c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0].value.cooked:null;if(!u)throw H(Ce,`${r}: PageMeta entity \`${n}\` (${t}) has no literal \`collection\` in its defineEntity options. The page's records (sitemap, prerender, server metadata) are read from it. Fix: set collection: 'products' (a string literal) in the defineEntity call.`,"invalid-configuration");return u}async function Or(o,e,t,n){if(!o||o.entity===void 0)return null;let r=o.entity?.identifier,s=o.entity?.expression;if(typeof s=="string"){let l=s.match(/^[A-Za-z_$][\w$]*\s*\??\.\s*([A-Za-z_$][\w$]*)$/)?.[1]??"productEntity";throw H(Ce,`${t}: PageMeta entity \`${s}\` is not a bare identifier. The build reads the entity statically: only a defineEntity definition named-imported from 'entities' resolves to its collection (no namespace import, member access or call). Fix: import { ${l} } from 'entities'; then entity: ${l}`,"invalid-configuration")}if(typeof r!="string")throw H(Ce,`${t}: PageMeta entity must be the entity definition imported from 'entities' (got ${JSON.stringify(o.entity)}). The build resolves it to the entity's collection. Fix:
687
+ ${Li}`,"invalid-configuration");let a=Dr(await kr(),e,t),i=ji(a,r);if(!i)throw H(Ce,`${t}: PageMeta entity \`${r}\` is not imported from 'entities'. The page's entity must be a defineEntity definition of the app's \`entities\` package (one source for its collection). Fix: import { ${r} } from 'entities';`,"invalid-configuration");return n.collectionOf(i,t)}var He=null,Ir=null;function Ui(o){let t=(o.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Wi(o){let e=o.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw H("dndev-routes",`${o.file}: PageMeta signedInRedirect must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`,"invalid-configuration");if(e.split(/[?#]/)[0]===o.path)throw H("dndev-routes",`${o.file}: PageMeta signedInRedirect points at the page itself (${e}): signed-in visitors would loop. Use another page.`,"invalid-configuration")}}function Gi(o,{pageGenerateMetadata:e=!1}={}){if(!o.path.split("/").some(n=>n.startsWith(":"))||en(o)||!Et(o)||o.meta?.entity||o.metaExport?.namespace==="blog"||e&&o.exportsGenerateMetadata)return;let t=["declare the record entity it shows: import { productEntity } from 'entities'; then entity: productEntity in its PageMeta (title, description and image from the record)",...e?["export Next's generateMetadata from the page module (a server module, no 'use client')"]:[],"keep it out of search engines: seo: { noindex: true } in its PageMeta"];throw H("dndev-routes",`${o.file}: public dynamic route ${o.path} has no per-URL SEO: every URL would get the same title and description (PageMeta + i18n), duplicate pages for search engines. Fix, one of:
688
+ `+t.map((n,r)=>` ${r+1}. ${n}`).join(`
689
+ `),"invalid-configuration")}var Rt=class extends fe{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(),n=process.env.DNDEV_BUILD_ID;if(He&&Ir===n)return this.logger.debug("Using cached route discovery results"),this.routes=He.routes,this.errors=He.errors,this.source=He.source,this.entityResolver=He.entityResolver,{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 s=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(s)}`)}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/"),He={routes:this.routes,errors:this.errors,source:this.source,entityResolver:this.entityResolver},Ir=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"}`}getEntityResolver(){return this.entityResolver??=on(this.pathResolver.getAppRoot()),this.entityResolver}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:n}=e;this.entityResolver=on(t);let r=await this._batchProcessFiles(n,c=>this._analyzePageFile(c,t)),s=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(s,c=>this._analyzePageFile(c,t)),i=[...r,...a];this.logger.debug(`Auto-discovering from ${n.length} app + ${s.length} additional files`),this.routes=i.filter(c=>c.path==="home"||c.path==="/home"?(this.logger.debug(`Filtered reserved route: ${c.path} - Use root "/" instead (${c.file})`),!1):!0);let l=new Map;for(let c of this.routes){let u=c.path;if(l.has(u)){let p=l.get(u);throw H("dndev-routes",`${c.file}: route ${u} is also the route of ${p.file}: two pages cannot share a URL. Give one of them another path with a PageMeta route override, e.g. export const meta: PageMeta = { route: '/custom-path' };`,"invalid-configuration")}l.set(u,c),Wi(c),Gi(c,{pageGenerateMetadata:this.options.pageGenerateMetadata===!0})}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${n.length+s.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(n=>this.pathResolver.resolveAppPath(n));if(t.length===0)return[];try{let{consumerFiles:n}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return n}catch(n){return this.logger.debug(`Error scanning additional patterns: ${n.message}`),[]}}async _analyzePageFile(e,t){let n=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!n)return null;let r=e.relativePath,s="/src/"+r.replace(/\\/g,"/");s=s.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(n,r),i=Ui(s),c=i===Nt.HOMEPAGE_COMPONENT?Nt.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),u=this._extractPageMeta(r),p=await Or(a,n,r,this.entityResolver),{entity:d,action:f,...g}=a||{};return{path:c,component:i,importPath:s,auth:a?.auth||!1,meta:{...u,...g,...p&&{entity:p},action:u.action},metaExport:a&&{...a,...p&&{entity:p}},exportsGenerateMetadata:xr(n),file:r}}_extractMetaExport(e,t){try{let n=Sr(e,t);return n?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(n)}`),n):null}catch(n){if(be(n))throw n;return this.logger.debug(`Error parsing meta export from ${t}: ${n.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,n){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),s=e.route.params;if(Array.isArray(s)&&s.length>0){let a=s.map(i=>`:${i}`).join("/");return`${r}/${a}`}return r}return this.logger.warn(`Invalid route format in ${n}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${n}`),this._generateRoutePath(t)}_extractPageMeta(e){let t=e.split("/").pop()?.replace(".tsx","")||"",n=t.replace(/Page$/,"");n=n.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),n=n.charAt(0).toUpperCase()+n.slice(1);let r=e.split("/"),s=null;return r.length>1&&(t.includes("List")?s="list":t.includes("Form")||t.includes("Create")||t.includes("Edit")?s="form":(t.includes("Detail")||t.includes("View"))&&(s="detail")),{title:n,action:s,file:e}}};Y();var Hi={isEmpty:o=>!o.routes||o.routes.length===0,generateModule:(o,e,t="routes")=>{let n={totalRoutes:o.routes.length,authRequired:o.routes.filter(s=>s.auth&&s.auth.required).length,publicRoutes:o.routes.filter(s=>!s.auth||s.auth===!1).length,source:o.source,generatedAt:new Date().toISOString(),errors:o.errors.length,hasBlogFeed:In(O.getInstance().getAppRoot())},r=o.routes.map(s=>` {
684
690
  path: '${s.path}',
685
691
  component: () => import('${s.importPath}'),
686
692
  auth: ${JSON.stringify(s.auth,null,2).replace(/\n/g,`
@@ -689,14 +695,14 @@ ${_i}`,"invalid-configuration");let i=eo(await Qn(),e,t),a=Ai(i,o);if(!a)throw H
689
695
  `)}
690
696
  }`).join(`,
691
697
  `);return`
692
- // ${U.routes} - Generated route data
698
+ // ${V.routes} - Generated route data
693
699
  import { lazy } from 'react';
694
700
 
695
701
  const routeData = [
696
- ${o}
702
+ ${r}
697
703
  ];
698
704
 
699
- const routeManifest = ${JSON.stringify(r,null,2)};
705
+ const routeManifest = ${JSON.stringify(n,null,2)};
700
706
 
701
707
  // Populate unified DnDev config for runtime access
702
708
  if (typeof globalThis !== 'undefined') {
@@ -711,13 +717,13 @@ if (typeof globalThis !== 'undefined') {
711
717
  }
712
718
 
713
719
  // Include all routes in mapping (navigation store will filter by hideFromMenu)
714
- globalThis._DNDEV_CONFIG_.${ee[t]} = {
720
+ globalThis._DNDEV_CONFIG_.${oe[t]} = {
715
721
  mapping: routeData,
716
722
  manifest: {
717
- totalRoutes: ${n.routes.length},
718
- authRequired: ${n.routes.filter(s=>s.auth&&s.auth.required).length},
719
- publicRoutes: ${n.routes.filter(s=>!s.auth||s.auth===!1).length},
720
- hasBlogFeed: ${r.hasBlogFeed},
723
+ totalRoutes: ${o.routes.length},
724
+ authRequired: ${o.routes.filter(s=>s.auth&&s.auth.required).length},
725
+ publicRoutes: ${o.routes.filter(s=>!s.auth||s.auth===!1).length},
726
+ hasBlogFeed: ${n.hasBlogFeed},
721
727
  generatedAt: new Date().toISOString(),
722
728
  },
723
729
  };
@@ -726,14 +732,14 @@ if (typeof globalThis !== 'undefined') {
726
732
 
727
733
  export const routes = routeData;
728
734
  export const manifest = routeManifest;
729
- export const source = '${n.source}';
735
+ export const source = '${o.source}';
730
736
 
731
- export default { routes: routeData, manifest: routeManifest, source: '${n.source}' };
732
- `},generateEmpty:(n,e,t,r="routes")=>{let o={totalRoutes:0,authRequired:0,publicRoutes:0,source:"empty",generatedAt:new Date().toISOString()};return`
733
- // ${U.routes} - Empty route data
737
+ export default { routes: routeData, manifest: routeManifest, source: '${o.source}' };
738
+ `},generateEmpty:(o,e,t,n="routes")=>{let r={totalRoutes:0,authRequired:0,publicRoutes:0,source:"empty",generatedAt:new Date().toISOString()};return`
739
+ // ${V.routes} - Empty route data
734
740
 
735
741
  const routeData = [];
736
- const routeManifest = ${JSON.stringify(o,null,2)};
742
+ const routeManifest = ${JSON.stringify(r,null,2)};
737
743
 
738
744
  // Populate unified DnDev config for runtime access
739
745
  if (typeof globalThis !== 'undefined') {
@@ -749,7 +755,7 @@ if (typeof globalThis !== 'undefined') {
749
755
  }
750
756
 
751
757
  // Populate empty routes configuration
752
- globalThis._DNDEV_CONFIG_.${ee[r]} = {
758
+ globalThis._DNDEV_CONFIG_.${oe[n]} = {
753
759
  mapping: [],
754
760
  manifest: {
755
761
  totalRoutes: 0,
@@ -766,7 +772,7 @@ export const manifest = routeManifest;
766
772
  export const source = 'empty';
767
773
 
768
774
  export default { routes: routeData, manifest: routeManifest, source: 'empty' };
769
- `},generateInspection:(n,e)=>{if(!n.routes||n.routes.length===0)return`/**
775
+ `},generateInspection:(o,e)=>{if(!o.routes||o.routes.length===0)return`/**
770
776
  * Generated Route Discovery Results
771
777
  * Source: empty
772
778
  * Generated at: ${new Date().toISOString()}
@@ -782,19 +788,19 @@ export const routeManifest = {
782
788
  };
783
789
 
784
790
  export default discoveredRoutes;
785
- `;let t=n.routes.map(r=>` {
786
- path: '${r.path}',
787
- component: () => import('${r.importPath}'),
788
- auth: ${JSON.stringify(r.auth,null,2).replace(/\n/g,`
791
+ `;let t=o.routes.map(n=>` {
792
+ path: '${n.path}',
793
+ component: () => import('${n.importPath}'),
794
+ auth: ${JSON.stringify(n.auth,null,2).replace(/\n/g,`
789
795
  `)},
790
- meta: ${JSON.stringify(r.meta,null,2).replace(/\n/g,`
796
+ meta: ${JSON.stringify(n.meta,null,2).replace(/\n/g,`
791
797
  `)}
792
798
  }`).join(`,
793
799
  `);return`/**
794
800
  * Generated Route Discovery Results
795
- * Source: ${n.source}
801
+ * Source: ${o.source}
796
802
  * Generated at: ${new Date().toISOString()}
797
- * Import from '${U.routes}'
803
+ * Import from '${V.routes}'
798
804
  */
799
805
 
800
806
  export const discoveredRoutes = [
@@ -802,16 +808,16 @@ ${t}
802
808
  ];
803
809
 
804
810
  export const routeManifest = {
805
- totalRoutes: ${n.routes.length},
806
- source: '${n.source}',
811
+ totalRoutes: ${o.routes.length},
812
+ source: '${o.source}',
807
813
  generatedAt: '${new Date().toISOString()}'
808
814
  };
809
815
 
810
816
  export default discoveredRoutes;
811
- `},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 r=n.routes||[],o=r.filter(i=>i.auth&&i.auth.required).length,s=r.length;t&&t.info(`${e} Routes: ${s} found${o>0?`, ${o} are authguarded`:""}`)}},Fi=[n=>n.endsWith("Page.tsx")];function oo(n={}){return ye({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:U.routes,DiscoveryClass:wt,discoveryMethod:"discoverRoutes",filePatterns:Fi,templates:Ii,manifestFileName:me.manifests.route,configKey:"routes"})({...n,disableHmr:n?.hmr===!1,hmrSmartDetection:!1})}J();import{loadEnv as Mi}from"vite";q();var Li=`/${nt.replace(/\.html$/,"")}`;function so(n={}){let{disabled:e=!1,debug:t,generateRobotsTxt:r,generateSitemap:o,routes:s={},baseUrl:i,siteName:a,siteDescription:l,crawlDelay:c,aiCrawlers:u,llmsTxt:p=!0,redirects:d,isDev:f,routeManifest:g,...w}=n;if(e)return{name:"seo-disabled"};if(!g)throw new Error("[dndev] createViteSEOPlugin: options.routeManifest is required (createVitePlugins passes the route plugin's, createRouteManifestStore).");let m=M("SEO Plugin",t,!0),h=D.getInstance(),P=null,R=null,E=!1;return{name:"vite-seo-plugin",enforce:"pre",applyToEnvironment(S){return S.name==="client"},configResolved(S){let C=h.getAppRoot(),k=S.mode||"production",T=Mi(k,C,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;T&&t&&m.debug(`Using app URL from VITE_APP_URL: ${T}`),P=a||null;let $=ft(i,T)||null;if(R=f?$:Xe($,"VITE_APP_URL",m),!f&&!R){E=!0;return}m.verbose(`Name: ${P||"Not found"}`),m.verbose(`URL: ${R||"Not found"}
812
- `),P&&m.debug(` - Site name from appConfig: "${P}"`);let v=[];if(R||v.push("baseUrl (VITE_APP_URL in .env)"),P||v.push("siteName (APP_NAME in src/config/app.ts)"),v.length>0){E=!0,m.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),v.forEach(G=>m.warn(` - ${G}`)),m.warn(""),m.warn(" To fix:"),R||m.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),P||(m.warn(" 2. Add APP_NAME export to src/config/app.ts:"),m.warn(' export const APP_NAME = "Your App Name";')),m.warn(""),m.warn(" robots.txt and sitemap.xml will NOT be generated."),m.warn("");return}m.debug(`Generate robots.txt: ${r}`),m.debug(`Generate sitemap: ${o}`)},async generateBundle(){if(E)return;let S=new Be({debug:t,generateRobotsTxt:r,shellPath:Li,baseUrl:R,siteName:P,crawlDelay:c,aiCrawlers:u,routes:s,appRoot:h.getAppRoot(),...w}),C=g.get(),{blogPosts:k}=C,y=async(T,$)=>{this.emitFile({type:"asset",fileName:T,source:$})};await gt(["robots.txt","rss.xml","seo-manifest.json"],async()=>{let T=await S.generateSEOFiles(C,y,k);T.robotsTxt&&!T.robotsTxt.skipped&&m.info(`\u{1F916} robots.txt: ${T.robotsTxt.disallowedPaths||0} disallowed paths`),T.rss&&!T.rss.skipped&&m.info(`\u{1F4E1} rss.xml: ${T.rss.postCount||0} blog posts`),T.manifest&&!T.manifest.skipped&&m.info("\u{1F4C4} seo-manifest.json")},m),p&&k.length>0&&await gt(["llms-full.txt"],async()=>{let T=Pn({siteName:P,baseUrl:R,description:l,appRoot:h.getAppRoot(),blogPosts:k,logger:m});T&&(await y("llms-full.txt",T),m.info("\u{1F4C4} llms-full.txt"))},m),d?.length>0&&await gt(["_redirects"],async()=>{let T=new Set,$=[];for(let{from:v,to:G,permanent:A}of d){let L=v.replace(/\/+$/,"")||"/",j=G.replace(/\/+$/,"")||"/";if(L===j){m.warn(`Redirect loop detected: ${v} \u2192 ${G} (skipped)`);continue}if(!v.startsWith("/")){m.warn(`Redirect source must start with /: "${v}" (skipped)`);continue}if(T.has(L)){m.warn(`Duplicate redirect source: "${v}" (skipped)`);continue}T.add(L),$.push(`${v} ${G} ${A===!1?302:301}`)}$.length>0&&(await y("_redirects",$.join(`
817
+ `},generateManifest:o=>({routes:o?.routes?.length||0,source:o?.source||"unknown",timestamp:Date.now(),errors:o?.errors?.length||0}),logConfig:o=>{},logStats:(o,e,t)=>{let n=o.routes||[],r=n.filter(a=>a.auth&&a.auth.required).length,s=n.length;t&&t.info(`${e} Routes: ${s} found${r>0?`, ${r} are authguarded`:""}`)}},Vi=[o=>o.endsWith("Page.tsx")];function Fr(o={}){return we({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:V.routes,DiscoveryClass:Rt,discoveryMethod:"discoverRoutes",filePatterns:Vi,templates:Hi,manifestFileName:ve.manifests.route,configKey:"routes"})({...o,disableHmr:o?.hmr===!1,hmrSmartDetection:!1})}q();import{loadEnv as Ji}from"vite";Y();var qi=`/${rt.replace(/\.html$/,"")}`;function Mr(o={}){let{disabled:e=!1,debug:t,generateRobotsTxt:n,generateSitemap:r,routes:s={},baseUrl:a,siteName:i,siteDescription:l,crawlDelay:c,aiCrawlers:u,llmsTxt:p=!0,redirects:d,isDev:f,routeManifest:g,...v}=o;if(e)return{name:"seo-disabled"};if(!g)throw new Error("[dndev] createViteSEOPlugin: options.routeManifest is required (createVitePlugins passes the route plugin's, createRouteManifestStore).");let h=G("SEO Plugin",t,!0),y=O.getInstance(),C=null,$=null,S=!1;return{name:"vite-seo-plugin",enforce:"pre",applyToEnvironment(x){return x.name==="client"},configResolved(x){let N=y.getAppRoot(),D=x.mode||"production",k=Ji(D,N,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;k&&t&&h.debug(`Using app URL from VITE_APP_URL: ${k}`),C=i||null;let _=bt(a,k)||null;if($=f?_:Qe(_,"VITE_APP_URL",h),!f&&!$){S=!0;return}h.verbose(`Name: ${C||"Not found"}`),h.verbose(`URL: ${$||"Not found"}
818
+ `),C&&h.debug(` - Site name from appConfig: "${C}"`);let m=[];if($||m.push("baseUrl (VITE_APP_URL in .env)"),C||m.push("siteName (APP_NAME in src/config/app.ts)"),m.length>0){S=!0,h.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),m.forEach(A=>h.warn(` - ${A}`)),h.warn(""),h.warn(" To fix:"),$||h.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),C||(h.warn(" 2. Add APP_NAME export to src/config/app.ts:"),h.warn(' export const APP_NAME = "Your App Name";')),h.warn(""),h.warn(" robots.txt and sitemap.xml will NOT be generated."),h.warn("");return}h.debug(`Generate robots.txt: ${n}`),h.debug(`Generate sitemap: ${r}`)},async generateBundle(){if(S)return;let x=new We({debug:t,generateRobotsTxt:n,shellPath:qi,baseUrl:$,siteName:C,crawlDelay:c,aiCrawlers:u,routes:s,appRoot:y.getAppRoot(),...v}),N=g.get(),{blogPosts:D}=N,P=async(k,_)=>{this.emitFile({type:"asset",fileName:k,source:_})};await wt(["robots.txt","rss.xml","seo-manifest.json"],async()=>{let k=await x.generateSEOFiles(N,P,D);k.robotsTxt&&!k.robotsTxt.skipped&&h.info(`\u{1F916} robots.txt: ${k.robotsTxt.disallowedPaths||0} disallowed paths`),k.rss&&!k.rss.skipped&&h.info(`\u{1F4E1} rss.xml: ${k.rss.postCount||0} blog posts`),k.manifest&&!k.manifest.skipped&&h.info("\u{1F4C4} seo-manifest.json")},h),p&&D.length>0&&await wt(["llms-full.txt"],async()=>{let k=or({siteName:C,baseUrl:$,description:l,appRoot:y.getAppRoot(),blogPosts:D,logger:h});k&&(await P("llms-full.txt",k),h.info("\u{1F4C4} llms-full.txt"))},h),d?.length>0&&await wt(["_redirects"],async()=>{let k=new Set,_=[];for(let{from:m,to:A,permanent:B}of d){let w=m.replace(/\/+$/,"")||"/",M=A.replace(/\/+$/,"")||"/";if(w===M){h.warn(`Redirect loop detected: ${m} \u2192 ${A} (skipped)`);continue}if(!m.startsWith("/")){h.warn(`Redirect source must start with /: "${m}" (skipped)`);continue}if(k.has(w)){h.warn(`Duplicate redirect source: "${m}" (skipped)`);continue}k.add(w),_.push(`${m} ${A} ${B===!1?302:301}`)}_.length>0&&(await P("_redirects",_.join(`
813
819
  `)+`
814
- `),m.info(`\u{1F4CE} _redirects: ${$.length} redirect${$.length>1?"s":""}`))},m)}}}J();function io(n={}){let{debug:e}=n;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,r){return t.startsWith("node:")?(M("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${r?` from ${r}`:""}`),"\0virtual:empty-server-module"):$t.includes(t)||$t.some(o=>t.startsWith(`${o}/`))?(M("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${r?` from ${r}`:""}`),"\0virtual:empty-server-module"):nr.includes(t)?(M("server-shim",e,!0).warn(`Blocking server-only import: ${t}${r?` from ${r}`:""}`),"\0virtual:empty-server-module"):null},load(t){return t==="\0virtual:empty-server-module"?`
820
+ `),h.info(`\u{1F4CE} _redirects: ${_.length} redirect${_.length>1?"s":""}`))},h)}}}q();function Lr(o={}){let{debug:e}=o;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,n){return t.startsWith("node:")?(G("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${n?` from ${n}`:""}`),"\0virtual:empty-server-module"):Dt.includes(t)||Dt.some(r=>t.startsWith(`${r}/`))?(G("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${n?` from ${n}`:""}`),"\0virtual:empty-server-module"):hn.includes(t)?(G("server-shim",e,!0).warn(`Blocking server-only import: ${t}${n?` from ${n}`:""}`),"\0virtual:empty-server-module"):null},load(t){return t==="\0virtual:empty-server-module"?`
815
821
  // Node.js built-in modules shims for browser compatibility
816
822
  export const URL = globalThis.URL;
817
823
  export const URLSearchParams = globalThis.URLSearchParams;
@@ -1090,16 +1096,16 @@ export default discoveredRoutes;
1090
1096
  // Google Logging Utils shims
1091
1097
  export const LoggingWinston = class LoggingWinston {};
1092
1098
  export const LoggingBunyan = class LoggingBunyan {};
1093
- `:null}}}J();import{createRequire as ji}from"node:module";var zi=ji(import.meta.url),lo="ThemeIcon_",ao;function Bi(){return ao??=new Set(Object.keys(zi("lucide-react"))),ao}function Ht(n,e){let t=Bi(),r=new Set;for(let o of n){let s=o.meta?.icon;if(!s)continue;let i=String(s).replace(/['"]/g,"").trim();/^[A-Za-z][A-Za-z0-9]*$/.test(i)&&t.has(i)?r.add(i):e.warn(`\u{1F3A8} Theme "${o.name}": --theme-icon '${i}' is not a lucide-react icon name (theme toggle shows the Palette icon)`)}return[...r].sort()}function Jt(n){return n.length===0?"":`import { ${n.map(t=>`${t} as ${lo}${t}`).join(", ")} } from 'lucide-react';
1094
- `}function qt(n){return`{ ${n.map(t=>`${JSON.stringify(t)}: ${lo}${t}`).join(", ")} }`}var co=M("theme-plugin"),uo={isEmpty:n=>!n.themes||n.themes.length===0,generateModule:(n,e,t="themes")=>{let{themes:r}=n;if(!r||r.length===0)return uo.generateEmpty(n,e,void 0,t);let o=r.find(a=>a.essential&&a.name==="light")||r[0],s={totalThemes:r.length,defaultTheme:o?.name||"light",hasCustomThemes:r.some(a=>!a.essential),timestamp:new Date().toISOString()},i=Ht(r,co);return`// Virtual module: ${U.themes}
1099
+ `:null}}}q();import{createRequire as Ki}from"node:module";var Yi=Ki(import.meta.url),zr="ThemeIcon_",jr;function Zi(){return jr??=new Set(Object.keys(Yi("lucide-react"))),jr}function rn(o,e){let t=Zi(),n=new Set;for(let r of o){let s=r.meta?.icon;if(!s)continue;let a=String(s).replace(/['"]/g,"").trim();/^[A-Za-z][A-Za-z0-9]*$/.test(a)&&t.has(a)?n.add(a):e.warn(`\u{1F3A8} Theme "${r.name}": --theme-icon '${a}' is not a lucide-react icon name (theme toggle shows the Palette icon)`)}return[...n].sort()}function sn(o){return o.length===0?"":`import { ${o.map(t=>`${t} as ${zr}${t}`).join(", ")} } from 'lucide-react';
1100
+ `}function an(o){return`{ ${o.map(t=>`${JSON.stringify(t)}: ${zr}${t}`).join(", ")} }`}var Br=G("theme-plugin"),Ur={isEmpty:o=>!o.themes||o.themes.length===0,generateModule:(o,e,t="themes")=>{let{themes:n}=o;if(!n||n.length===0)return Ur.generateEmpty(o,e,void 0,t);let r=n.find(i=>i.essential&&i.name==="light")||n[0],s={totalThemes:n.length,defaultTheme:r?.name||"light",hasCustomThemes:n.some(i=>!i.essential),timestamp:new Date().toISOString()},a=rn(n,Br);return`// Virtual module: ${V.themes}
1095
1101
  // \u{1F680} STATIC INJECTION PATTERN - Zero Runtime Loading
1096
1102
  // Generated by @donotdev/config at ${new Date().toISOString()}
1097
- ${Jt(i)}
1103
+ ${sn(a)}
1098
1104
  // ===== STATIC EXPORTS - IMMEDIATE AVAILABILITY =====
1099
- export const THEMES = ${JSON.stringify(r,null,2)};
1105
+ export const THEMES = ${JSON.stringify(n,null,2)};
1100
1106
  export const THEME_MANIFEST = ${JSON.stringify(s,null,2)};
1101
- export const THEME_COUNT = ${r.length};
1102
- export const DEFAULT_THEME = '${o?.name||"light"}';
1107
+ export const THEME_COUNT = ${n.length};
1108
+ export const DEFAULT_THEME = '${r?.name||"light"}';
1103
1109
 
1104
1110
  const themeData = THEMES;
1105
1111
  const defaultTheme = DEFAULT_THEME;
@@ -1119,17 +1125,17 @@ if (typeof globalThis !== 'undefined') {
1119
1125
  }
1120
1126
 
1121
1127
  // Populate themes configuration
1122
- globalThis._DNDEV_CONFIG_.${ee[t]} = {
1128
+ globalThis._DNDEV_CONFIG_.${oe[t]} = {
1123
1129
  discovered: themeData,
1124
1130
  mapping: themeData.reduce((acc, theme) => {
1125
1131
  acc[theme.name] = theme;
1126
1132
  return acc;
1127
1133
  }, {}),
1128
1134
  // Theme icons (--theme-icon), imported by name: rendered without the lucide namespace
1129
- icons: ${qt(i)},
1135
+ icons: ${an(a)},
1130
1136
  variables: {},
1131
1137
  manifest: {
1132
- totalThemes: ${r.length},
1138
+ totalThemes: ${n.length},
1133
1139
  totalVariables: 0,
1134
1140
  generatedAt: new Date().toISOString(),
1135
1141
  },
@@ -1168,12 +1174,12 @@ export default {
1168
1174
  getAllThemes,
1169
1175
  getThemeNames
1170
1176
  };
1171
- `},generateEmpty:(n,e,t,r="themes")=>{let o=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}],s=o.find(l=>l.essential&&l.name==="light")||o[0],i={totalThemes:o.length,defaultTheme:s?.name||"light",hasCustomThemes:o.some(l=>!l.essential),timestamp:new Date().toISOString()},a=Ht(o,co);return`// ${U.themes} - Using framework essential themes (fallback)
1177
+ `},generateEmpty:(o,e,t,n="themes")=>{let r=o.themes&&o.themes.length>0?o.themes:[{name:"light",displayName:"Light",meta:{icon:"Sun",category:"light"},essential:!0,isDark:!1,source:"built-in",variableCount:0}],s=r.find(l=>l.essential&&l.name==="light")||r[0],a={totalThemes:r.length,defaultTheme:s?.name||"light",hasCustomThemes:r.some(l=>!l.essential),timestamp:new Date().toISOString()},i=rn(r,Br);return`// ${V.themes} - Using framework essential themes (fallback)
1172
1178
  // Generated by @donotdev/config at ${new Date().toISOString()}
1173
- ${Jt(a)}
1174
- export const THEMES = ${JSON.stringify(o,null,2)};
1175
- export const THEME_MANIFEST = ${JSON.stringify(i,null,2)};
1176
- export const THEME_COUNT = ${o.length};
1179
+ ${sn(i)}
1180
+ export const THEMES = ${JSON.stringify(r,null,2)};
1181
+ export const THEME_MANIFEST = ${JSON.stringify(a,null,2)};
1182
+ export const THEME_COUNT = ${r.length};
1177
1183
  export const DEFAULT_THEME = '${s?.name||"light"}';
1178
1184
 
1179
1185
  const themeData = THEMES;
@@ -1192,16 +1198,16 @@ if (typeof globalThis !== 'undefined') {
1192
1198
  };
1193
1199
  }
1194
1200
 
1195
- globalThis._DNDEV_CONFIG_.${ee[r]} = {
1201
+ globalThis._DNDEV_CONFIG_.${oe[n]} = {
1196
1202
  discovered: themeData,
1197
1203
  mapping: themeData.reduce((acc, theme) => {
1198
1204
  acc[theme.name] = theme;
1199
1205
  return acc;
1200
1206
  }, {}),
1201
- icons: ${qt(a)},
1207
+ icons: ${an(i)},
1202
1208
  variables: {},
1203
1209
  manifest: {
1204
- totalThemes: ${o.length},
1210
+ totalThemes: ${r.length},
1205
1211
  generatedAt: new Date().toISOString(),
1206
1212
  },
1207
1213
  };
@@ -1236,7 +1242,7 @@ export default {
1236
1242
  getAllThemes,
1237
1243
  getThemeNames
1238
1244
  };
1239
- `},generateInspection:(n,e)=>{let{themes:t}=n;if(!t||t.length===0)return`/**
1245
+ `},generateInspection:(o,e)=>{let{themes:t}=o;if(!t||t.length===0)return`/**
1240
1246
  * Generated Theme Discovery Results
1241
1247
  * Source: empty
1242
1248
  * Generated at: ${new Date().toISOString()}
@@ -1252,17 +1258,17 @@ export const themeManifest = {
1252
1258
  };
1253
1259
 
1254
1260
  export default discoveredThemes;
1255
- `;let r=t.find(o=>o.essential&&o.name==="light")||t[0];return`/**
1261
+ `;let n=t.find(r=>r.essential&&r.name==="light")||t[0];return`/**
1256
1262
  * Generated Theme Discovery Results
1257
1263
  * Generated at: ${new Date().toISOString()}
1258
- * Import from '${U.themes}'
1264
+ * Import from '${V.themes}'
1259
1265
  */
1260
1266
 
1261
1267
  export const discoveredThemes = ${JSON.stringify(t,null,2)};
1262
1268
 
1263
- export const defaultTheme = '${r?.name||"light"}';
1269
+ export const defaultTheme = '${n?.name||"light"}';
1264
1270
 
1265
- export const themeFiles = ${JSON.stringify(n.files?.map(o=>({name:o.name,path:o.relativePath,size:o.size}))||[],null,2)};
1271
+ export const themeFiles = ${JSON.stringify(o.files?.map(r=>({name:r.name,path:r.relativePath,size:r.size}))||[],null,2)};
1266
1272
 
1267
1273
  export const themeManifest = {
1268
1274
  totalThemes: ${t.length},
@@ -1270,9 +1276,9 @@ export const themeManifest = {
1270
1276
  };
1271
1277
 
1272
1278
  export default discoveredThemes;
1273
- `},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 r=n.themes||[],o=r.filter(i=>!i.essential).length,s=r.length;t&&(s===0?t.warn(`${e} No themes discovered - using framework essential themes fallback`):t.info(`${e} Themes: ${s} discovered${o>0?` (${o} custom)`:""}`))}};function po(n={}){let e=Date.now();return M("theme-plugin",n.debug,n.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),ye({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:U.themes,DiscoveryClass:Ne,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:uo,manifestFileName:me.manifests.theme,configKey:"themes",createDiscovery:(o,s)=>{let i=new je(o,{debug:s.debug,logger:M("css-extractor",s.debug,s.verbose)});return new Ne(i,o,s)}})(n)}J();q();var Et=new Set(["@donotdev/functions"]);function fo(){try{let n=D.getInstance(),e=n.resolveAppPath("package.json"),t=n.readSync(e,{format:"json"});if(!t)return[];let r={...t.dependencies,...t.devDependencies};return Object.keys(r).filter(o=>o.startsWith("@donotdev/")).filter(o=>!we.buildTimePackages.includes(o)).filter(o=>!Et.has(o)).sort()}catch{return[]}}q();function go(n={}){let e=M("vite-plugins",n.debug,n.verbose);try{let{mode:t,debug:r,verbose:o,isDev:s,isPreview:i=!1,server:a={},routes:l={},themes:c={},i18n:u={},assets:p={},seo:d={},prerender:f={},pwa:g={},serverShim:w={},pluginFactory:m={},reactCompiler:h=!1,appConfig:P}=n,R=l.debug??r,E=c.debug??r,S=u.debug??r,C=p.debug??r,k=w.debug??r,y=[];y.push(io({...w,debug:k}));let T;try{T=D.getInstance()}catch(A){throw new Error(`Failed to initialize PathResolver: ${A.message||A}`)}y.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(A){if(r){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let z={root:A.root,mode:A.mode,envDir:A.envDir,base:A.base,build:A.build?{outDir:A.build.outDir,minify:A.build.minify}:void 0,server:A.server?{port:A.server.port,host:A.server.host}:void 0,plugins:A.plugins?{count:A.plugins.length,names:A.plugins.map(K=>K?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(z,null,2))}T.setAppRoot(A.root);let L=T.getAppRoot(),j=fo();if(j.length>0){let z=A.optimizeDeps?.include||[];A.optimizeDeps.include=[...new Set([...z,...j])],e.verbose(`optimizeDeps: added ${j.length} @donotdev packages`)}if(Et.size>0){let z=A.optimizeDeps?.exclude||[],K=[...Et];A.optimizeDeps.exclude=[...new Set([...z,...K])],e.verbose(`optimizeDeps: excluded ${K.length} server-only packages`)}if(s&&A.server?.port){let z=A.server.https?"https":"http";process.env.VITE_APP_URL=`${z}://localhost:${A.server.port}`,(r||o)&&e.debug(`VITE_APP_URL set: ${process.env.VITE_APP_URL}`)}else s&&e.warn("VITE_APP_URL not set in dev mode. Server port not available.");try{let z=T.getRepoRoot();e.verbose(`Repo: ${z}`),e.verbose(`App: ${L}`)}catch(z){e.debug(`Could not log PathResolver values: ${z.message}`)}if(A.server&&!i){let z=X=>{let W=X.replace(/\\/g,"/"),se=L.replace(/\\/g,"/");return!W.startsWith(se)};A.server.watch||(A.server.watch={});let K=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];A.server.watch={...A.server.watch,ignored:[...A.server.watch.ignored||[],...K,z]},e.verbose(`Fixed file watcher to use app root: ${L}`)}}}),y.push(sn({appConfig:P,pwa:g.enabled,debug:r,verbose:o})),y.push(fn({debug:r,verbose:o})),y.push(pn({debug:r})),y.push(Gi({fastRefresh:!0,jsxRuntime:"automatic",...h?{babel:{plugins:[["babel-plugin-react-compiler",{target:"19"}]]}}:{}})),y.push(Wi({ignoreConfigErrors:!0})),a.https===!0&&y.push(Ui());let $=Rr(),v=ln();y.push(oo({...m,...l,debug:R,routeManifest:$})),y.push(po({...m,...c,debug:E})),y.push(...cn({...m,...u,debug:S,i18nStore:v})),y.push(_r({...m,...p,debug:C,i18nStore:v,routeManifest:$})),y.push(jr({appConfig:P})),y.push(Tr({...m,mode:t,debug:r,verbose:o})),y.push(so({...d,routeManifest:$,debug:r,isDev:s})),g.enabled&&y.push(Gn({...g,debug:r})),y.push(Hr({debug:r,i18nStore:v})),y.push(Dr());let G=!1;return y.push({name:"dndev-build-summary",enforce:"post",configResolved(A){G=A.command==="build"},closeBundle(){if(!G)return;let A=T,L=A.resolveAppPath("dist/assets");if(A.pathExists(L))try{let j=A.readdirSync(L),z=j.filter(W=>W.endsWith(".js")),K=j.filter(W=>W.endsWith(".css")),X=j.length-z.length-K.length;e.info(`
1274
- Build output: ${z.length} JS, ${K.length} CSS, ${X} other \u2014 ${j.length} files total`)}catch{}}}),y.push(Un({...f,routeManifest:$,prerenderRecords:P?.prerenderRecords,seo:d,i18nStore:v,debug:r,verbose:o})),y}catch(t){throw M("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}J();function Vi(n){if(!n)return{};let e={};return Array.isArray(n)?n.forEach(({find:t,replacement:r})=>{typeof t=="string"&&(e[t]=r)}):typeof n=="object"&&Object.assign(e,n),e}function mo(n={}){let{alias:e,...t}=n,{conditions:r,...o}=t;return{alias:{"@":"/src",...Vi(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...r||[]],...o}}function ho(n={}){let{include:e=[],exclude:t=[],esbuildOptions:r={},...o}=n,s=[...e,...we.optionalFeatures],i=[...new Set(s)],a=[...new Set(t)];return{include:i,exclude:a,esbuildOptions:r,...o}}function Ea(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 r=e.command,o=e.mode,s=e.isPreview??!1,{appConfig:i,dndev:a,...l}=n;if(!i)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
1275
- Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof i!="object"||i===null)throw new Error(`appConfig must be an object, but got ${typeof i}. Make sure you are exporting appConfig from src/config/app.ts correctly.`);let c=i?.features?{debug:i.features.debug}:void 0,u=i?.seo===!1?{disabled:!0}:i?.seo&&typeof i.seo!="boolean"?{...i.seo,siteName:i.seo.siteName||i.app?.name,siteDescription:i.app?.description}:i?.app?.name?{siteName:i.app.name,siteDescription:i.app.description}:void 0,{features:p,seo:d,...f}=l,g=i?.app?{name:i.app.name,shortName:i.app.shortName,description:i.app.description}:void 0,{pwa:w={},...m}=f,h={...w,app:w.app||g},P={...c?{features:c}:{},...u?{seo:u}:{},...Object.keys(h).length>0?{pwa:h}:{},...m,mode:o},R;try{R=hr(P)}catch(re){throw new Error(`mergeOptions failed: ${re?.message||re||"Unknown error"}`)}let E;try{E=vr(R)}catch(re){throw new Error(`normalizeOptions failed: ${re?.message||re||"Unknown error"}`)}if(!E)throw new Error("normalizeOptions returned undefined");let{mode:S,debug:C,verbose:k,isDev:y,isDebug:T,shouldAnalyze:$,serverOptions:v,previewOptions:G,buildOverrides:A,resolveOptions:L,routeOptions:j,themeOptions:z,i18nOptions:K,assetOptions:X,featureOptions:W,seoOptions:se,prerenderOptions:_,pwaOptions:O,serverShimOptions:F,chunkingOptions:B,pluginFactoryOptions:V,reactCompiler:de,base:Ce,defineOptions:ke,optimizeDepsOptions:x,pluginsOptions:N,cssOptions:Z,envDir:ge,restOptions:Q}=E,tt=M("vite-config",C,k);tt.debug(`Mode: ${S}, Dev: ${y}`);let Zt=process.env.DNDEV_BUILD_ID,Ve;r==="build"?Ve=`Building for ${S}`:s?Ve=`Preview server (serving ${S} build)`:r==="serve"?Ve=`Development server (${S})`:Ve=`Running ${r} (${S})`,tt.info(`
1276
- \u{1F3D7}\uFE0F DnDev Framework - ${Ve}${Zt?` [build:${Zt}]`:""}`),tt.info(` Platform: Vite | Command: ${r} | Mode: ${S}
1277
- `);let rt=go({appConfig:i,mode:S,debug:C,verbose:k,isDev:y,isPreview:s,routes:j,themes:z,i18n:K,assets:X,features:W,seo:se,prerender:_,pwa:O,serverShim:F,chunkingOptions:B,pluginFactory:V,reactCompiler:de});if(!Array.isArray(rt))throw new Error(`createVitePlugins returned ${typeof rt}, expected array. Value: ${rt}`);let Po=pr({mode:S,chunkingOptions:B,debug:C,isDev:y,isDebug:T,shouldAnalyze:$}),$o=s?void 0:dr(v.port||3e3,v,tt),Co=s?fr(G):void 0;if(a)try{let{createDndevPlugin:re}=await Promise.resolve().then(()=>(Ro(),So));N.push(re(typeof a=="object"?a:{}))}catch{}return{...Ce&&{base:Ce},plugins:[...rt,...N],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...S==="production"&&{build:Po},...r==="serve"&&!s&&{server:$o},...s&&{preview:Co},...ge&&{envDir:ge},customLogger:S==="production"&&!C?(()=>{let re={hasWarned:!1,_shouldSuppress(le){return le.includes("dist/")||le.includes("kB")||le.includes("\u2502")||le.includes("gzip:")||le.includes("\u2713 built in")||le.match(/built in \d+\.\d+s/)},info(le){re._shouldSuppress(le)},warn(le){re._shouldSuppress(le)},error(le){},warnOnce(le){re.hasWarned||(re.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return re})():void 0,css:{postcss:br(Z),...Z},optimizeDeps:ho(x),resolve:mo(L),define:{...ke,"process.env.NODE_ENV":JSON.stringify(o),__DEV__:JSON.stringify(y),__PROD__:JSON.stringify(!y)},...Q}}catch(t){let r=t||new Error("Unknown error occurred"),o=r?.message||r?.toString()||String(r)||"Unknown error",s=r?.stack||"",i=new Error(`Failed to create Vite config: ${o}${s?`
1278
- ${s}`:""}`);throw i.stack=s||i.stack,i}}}export{Ea as defineViteConfig};
1279
+ `},generateManifest:o=>({themes:o.themes?.length||0,timestamp:Date.now(),hasCustomThemes:o.themes?.some(e=>!e.essential)||!1}),logConfig:o=>{},logStats:(o,e,t)=>{let n=o.themes||[],r=n.filter(a=>!a.essential).length,s=n.length;t&&(s===0?t.warn(`${e} No themes discovered - using framework essential themes fallback`):t.info(`${e} Themes: ${s} discovered${r>0?` (${r} custom)`:""}`))}};function Wr(o={}){let e=Date.now();return G("theme-plugin",o.debug,o.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),we({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:V.themes,DiscoveryClass:Oe,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:Ur,manifestFileName:ve.manifests.theme,configKey:"themes",createDiscovery:(r,s)=>{let a=new Be(r,{debug:s.debug,logger:G("css-extractor",s.debug,s.verbose)});return new Oe(a,r,s)}})(o)}q();Y();var Ct=new Set(["@donotdev/functions"]);function Gr(){try{let o=O.getInstance(),e=o.resolveAppPath("package.json"),t=o.readSync(e,{format:"json"});if(!t)return[];let n={...t.dependencies,...t.devDependencies};return Object.keys(n).filter(r=>r.startsWith("@donotdev/")).filter(r=>!Pe.buildTimePackages.includes(r)).filter(r=>!Ct.has(r)).sort()}catch{return[]}}Y();function Hr(o={}){let e=G("vite-plugins",o.debug,o.verbose);try{let{mode:t,debug:n,verbose:r,isDev:s,isPreview:a=!1,server:i={},routes:l={},themes:c={},i18n:u={},assets:p={},seo:d={},prerender:f={},pwa:g={},serverShim:v={},pluginFactory:h={},reactCompiler:y=!1,appConfig:C}=o,$=l.debug??n,S=c.debug??n,x=u.debug??n,N=p.debug??n,D=v.debug??n,P=[];P.push(Lr({...v,debug:D}));let k;try{k=O.getInstance()}catch(w){throw new Error(`Failed to initialize PathResolver: ${w.message||w}`)}P.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(w){if(n){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let z={root:w.root,mode:w.mode,envDir:w.envDir,base:w.base,build:w.build?{outDir:w.build.outDir,minify:w.build.minify}:void 0,server:w.server?{port:w.server.port,host:w.server.host}:void 0,plugins:w.plugins?{count:w.plugins.length,names:w.plugins.map(K=>K?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(z,null,2))}k.setAppRoot(w.root);let M=k.getAppRoot(),L=Gr();if(L.length>0){let z=w.optimizeDeps?.include||[];w.optimizeDeps.include=[...new Set([...z,...L])],e.verbose(`optimizeDeps: added ${L.length} @donotdev packages`)}if(Ct.size>0){let z=w.optimizeDeps?.exclude||[],K=[...Ct];w.optimizeDeps.exclude=[...new Set([...z,...K])],e.verbose(`optimizeDeps: excluded ${K.length} server-only packages`)}if(s&&w.server?.port){let z=w.server.https?"https":"http";process.env.VITE_APP_URL=`${z}://localhost:${w.server.port}`,(n||r)&&e.debug(`VITE_APP_URL set: ${process.env.VITE_APP_URL}`)}else s&&e.warn("VITE_APP_URL not set in dev mode. Server port not available.");try{let z=k.getRepoRoot();e.verbose(`Repo: ${z}`),e.verbose(`App: ${M}`)}catch(z){e.debug(`Could not log PathResolver values: ${z.message}`)}if(w.server&&!a){let z=U=>{let Z=U.replace(/\\/g,"/"),R=M.replace(/\\/g,"/");return!Z.startsWith(R)};w.server.watch||(w.server.watch={});let K=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];w.server.watch={...w.server.watch,ignored:[...w.server.watch.ignored||[],...K,z]},e.verbose(`Fixed file watcher to use app root: ${M}`)}}}),P.push(Lo({appConfig:C,pwa:g.enabled,debug:n,verbose:r})),P.push(Ho({debug:n,verbose:r})),P.push(Wo({debug:n})),P.push(Qi({fastRefresh:!0,jsxRuntime:"automatic",...y?{babel:{plugins:[["babel-plugin-react-compiler",{target:"19"}]]}}:{}})),P.push(el({ignoreConfigErrors:!0})),i.https===!0&&P.push(Xi());let _=Mn(),m=zo(),A=$o();P.push(Fr({...h,...l,debug:$,routeManifest:_})),P.push(Wr({...h,...c,debug:S})),P.push(...Bo({...h,...u,debug:x,i18nStore:m})),P.push(Bn({...h,...p,debug:N,i18nStore:m,routeManifest:_})),P.push(Xn({appConfig:C})),P.push(Vn({...h,mode:t,debug:n,verbose:r})),P.push(Mr({...d,routeManifest:_,debug:n,isDev:s})),g.enabled&&P.push(Er({...g,debug:n})),P.push(Po({appConfig:C,debug:n,i18nStore:m,fontPlan:A})),P.push(Gn());let B=!1;return P.push({name:"dndev-build-summary",enforce:"post",configResolved(w){B=w.command==="build"},closeBundle(){if(!B)return;let w=k,M=w.resolveAppPath("dist/assets");if(w.pathExists(M))try{let L=w.readdirSync(M),z=L.filter(Z=>Z.endsWith(".js")),K=L.filter(Z=>Z.endsWith(".css")),U=L.length-z.length-K.length;e.info(`
1280
+ Build output: ${z.length} JS, ${K.length} CSS, ${U} other \u2014 ${L.length} files total`)}catch{}}}),P.push(wr({...f,routeManifest:_,prerenderRecords:C?.prerenderRecords,seo:d,i18nStore:m,fontPlan:A,debug:n,verbose:r})),P}catch(t){throw G("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}q();function tl(o){if(!o)return{};let e={};return Array.isArray(o)?o.forEach(({find:t,replacement:n})=>{typeof t=="string"&&(e[t]=n)}):typeof o=="object"&&Object.assign(e,o),e}function Vr(o={}){let{alias:e,...t}=o,{conditions:n,...r}=t;return{alias:{"@":"/src",...tl(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...n||[]],...r}}function Jr(o={}){let{include:e=[],exclude:t=[],esbuildOptions:n={},...r}=o,s=[...e,...Pe.optionalFeatures],a=[...new Set(s)],i=[...new Set(t)];return{include:a,exclude:i,esbuildOptions:n,...r}}function kl(o={}){return o==null&&(o={}),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 n=e.command,r=e.mode,s=e.isPreview??!1,{appConfig:a,dndev:i,...l}=o;if(!a)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
1281
+ Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof a!="object"||a===null)throw new Error(`appConfig must be an object, but got ${typeof a}. Make sure you are exporting appConfig from src/config/app.ts correctly.`);let c=a?.features?{debug:a.features.debug}:void 0,u=a?.seo===!1?{disabled:!0}:a?.seo&&typeof a.seo!="boolean"?{...a.seo,siteName:a.seo.siteName||a.app?.name,siteDescription:a.app?.description}:a?.app?.name?{siteName:a.app.name,siteDescription:a.app.description}:void 0,{features:p,seo:d,...f}=l,g=a?.app?{name:a.app.name,shortName:a.app.shortName,description:a.app.description}:void 0,{pwa:v={},...h}=f,y={...v,app:v.app||g},C={...c?{features:c}:{},...u?{seo:u}:{},...Object.keys(y).length>0?{pwa:y}:{},...h,mode:r},$;try{$=An(C)}catch(se){throw new Error(`mergeOptions failed: ${se?.message||se||"Unknown error"}`)}let S;try{S=Nn($)}catch(se){throw new Error(`normalizeOptions failed: ${se?.message||se||"Unknown error"}`)}if(!S)throw new Error("normalizeOptions returned undefined");let{mode:x,debug:N,verbose:D,isDev:P,isDebug:k,shouldAnalyze:_,serverOptions:m,previewOptions:A,buildOverrides:B,resolveOptions:w,routeOptions:M,themeOptions:L,i18nOptions:z,assetOptions:K,featureOptions:U,seoOptions:Z,prerenderOptions:R,pwaOptions:I,serverShimOptions:F,chunkingOptions:W,pluginFactoryOptions:Q,reactCompiler:X,base:te,defineOptions:xe,optimizeDepsOptions:E,pluginsOptions:T,cssOptions:J,envDir:he,restOptions:ne}=S,nt=G("vite-config",N,D);nt.debug(`Mode: ${x}, Dev: ${P}`);let un=process.env.DNDEV_BUILD_ID,Je;n==="build"?Je=`Building for ${x}`:s?Je=`Preview server (serving ${x} build)`:n==="serve"?Je=`Development server (${x})`:Je=`Running ${n} (${x})`,nt.info(`
1282
+ \u{1F3D7}\uFE0F DnDev Framework - ${Je}${un?` [build:${un}]`:""}`),nt.info(` Platform: Vite | Command: ${n} | Mode: ${x}
1283
+ `);let ot=Hr({appConfig:a,mode:x,debug:N,verbose:D,isDev:P,isPreview:s,routes:M,themes:L,i18n:z,assets:K,features:U,seo:Z,prerender:R,pwa:I,serverShim:F,chunkingOptions:W,pluginFactory:Q,reactCompiler:X});if(!Array.isArray(ot))throw new Error(`createVitePlugins returned ${typeof ot}, expected array. Value: ${ot}`);let ns=$n({mode:x,chunkingOptions:W,debug:N,isDev:P,isDebug:k,shouldAnalyze:_}),os=s?void 0:Pn(m.port||3e3,m,nt),rs=s?Rn(A):void 0;if(i)try{let{createDndevPlugin:se}=await Promise.resolve().then(()=>(ts(),es));T.push(se(typeof i=="object"?i:{}))}catch{}return{...te&&{base:te},plugins:[...ot,...T],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],...x==="production"&&{build:ns},...n==="serve"&&!s&&{server:os},...s&&{preview:rs},...he&&{envDir:he},customLogger:x==="production"&&!N?(()=>{let se={hasWarned:!1,_shouldSuppress(ue){return ue.includes("dist/")||ue.includes("kB")||ue.includes("\u2502")||ue.includes("gzip:")||ue.includes("\u2713 built in")||ue.match(/built in \d+\.\d+s/)},info(ue){se._shouldSuppress(ue)},warn(ue){se._shouldSuppress(ue)},error(ue){},warnOnce(ue){se.hasWarned||(se.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return se})():void 0,css:{postcss:Dn(J),...J},optimizeDeps:Jr(E),resolve:Vr(w),define:{...xe,"process.env.NODE_ENV":JSON.stringify(r),__DEV__:JSON.stringify(P),__PROD__:JSON.stringify(!P)},...ne}}catch(t){let n=t||new Error("Unknown error occurred"),r=n?.message||n?.toString()||String(n)||"Unknown error",s=n?.stack||"",a=new Error(`Failed to create Vite config: ${r}${s?`
1284
+ ${s}`:""}`);throw a.stack=s||a.stack,a}}}export{kl as defineViteConfig};