@donotdev/core 0.2.2 → 0.2.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 (59) hide show
  1. package/functions/index.js +13 -13
  2. package/i18n/locales/eager/dndev_ar.json +4 -0
  3. package/i18n/locales/eager/dndev_da.json +4 -0
  4. package/i18n/locales/eager/dndev_de.json +4 -0
  5. package/i18n/locales/eager/dndev_en.json +4 -0
  6. package/i18n/locales/eager/dndev_es.json +4 -0
  7. package/i18n/locales/eager/dndev_fr.json +4 -0
  8. package/i18n/locales/eager/dndev_it.json +4 -0
  9. package/i18n/locales/eager/dndev_ja.json +4 -0
  10. package/i18n/locales/eager/dndev_ko.json +4 -0
  11. package/i18n/locales/eager/dndev_nl.json +4 -0
  12. package/i18n/locales/eager/dndev_pl.json +636 -0
  13. package/i18n/locales/eager/dndev_pt.json +4 -0
  14. package/i18n/locales/eager/dndev_zh.json +4 -0
  15. package/i18n/locales/lazy/auth_ar.json +5 -2
  16. package/i18n/locales/lazy/auth_da.json +5 -2
  17. package/i18n/locales/lazy/auth_de.json +5 -2
  18. package/i18n/locales/lazy/auth_en.json +5 -2
  19. package/i18n/locales/lazy/auth_es.json +5 -2
  20. package/i18n/locales/lazy/auth_fr.json +5 -2
  21. package/i18n/locales/lazy/auth_it.json +5 -2
  22. package/i18n/locales/lazy/auth_ja.json +5 -2
  23. package/i18n/locales/lazy/auth_ko.json +5 -2
  24. package/i18n/locales/lazy/auth_nl.json +5 -2
  25. package/i18n/locales/lazy/auth_pl.json +195 -0
  26. package/i18n/locales/lazy/auth_pt.json +5 -2
  27. package/i18n/locales/lazy/auth_zh.json +5 -2
  28. package/i18n/locales/lazy/billing_pl.json +93 -0
  29. package/i18n/locales/lazy/blog_pl.json +9 -0
  30. package/i18n/locales/lazy/cookies_pl.json +35 -0
  31. package/i18n/locales/lazy/crud_ar.json +40 -3
  32. package/i18n/locales/lazy/crud_da.json +39 -4
  33. package/i18n/locales/lazy/crud_de.json +40 -3
  34. package/i18n/locales/lazy/crud_en.json +38 -4
  35. package/i18n/locales/lazy/crud_es.json +40 -3
  36. package/i18n/locales/lazy/crud_fr.json +39 -3
  37. package/i18n/locales/lazy/crud_it.json +40 -3
  38. package/i18n/locales/lazy/crud_ja.json +40 -3
  39. package/i18n/locales/lazy/crud_ko.json +40 -3
  40. package/i18n/locales/lazy/crud_nl.json +39 -4
  41. package/i18n/locales/lazy/crud_pl.json +582 -0
  42. package/i18n/locales/lazy/crud_pt.json +39 -4
  43. package/i18n/locales/lazy/crud_zh.json +39 -4
  44. package/i18n/locales/lazy/homeTemplate_pl.json +52 -0
  45. package/i18n/locales/lazy/legalNotice_de.json +55 -0
  46. package/i18n/locales/lazy/legalNotice_pl.json +55 -0
  47. package/i18n/locales/lazy/oauth_pl.json +11 -0
  48. package/i18n/locales/lazy/privacy_pl.json +178 -0
  49. package/i18n/locales/lazy/terms_pl.json +200 -0
  50. package/index.d.ts +881 -60
  51. package/index.js +6 -6
  52. package/next/index.d.ts +129 -4
  53. package/next/index.js +527 -152
  54. package/next/runtime.js +3 -0
  55. package/package.json +5 -3
  56. package/server.d.ts +744 -41
  57. package/server.js +1 -1
  58. package/symbol-index.json +1 -1
  59. package/vite/index.js +68 -68
package/next/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import*as w from"node:fs";import"node:fs";import{createRequire as xs}from"node:module";import{resolve as me,join as Z,dirname as Q,relative as ct,normalize as ks,sep as pt,extname as _s}from"node:path";import{fileURLToPath as As}from"node:url";import Es from"fast-glob";var he={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var De={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},U={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},D={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",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"}},oe="/og-image.png",Oe={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},de={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Pe={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"},z={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:[`${Pe.SOURCE_EAGER}/*_*.json`],lazy:[`${Pe.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},$e={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"]},it=["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"];var Te={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)/}};var le={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]},Se={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin"],cs:["latin"],sk:["latin"],hr:["latin"],sl:["latin"],hu:["latin"],ro:["latin"],et:["latin"],lv:["latin"],lt:["latin"],mt:["latin"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},Ie=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],at={base:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...z.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...z.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore}};function lt(a,e=null){let t=z[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Re(a){return at[a]||at.base}var ce={getGlobOptionsFor:Re||void 0,SCAN_PATTERNS:z||void 0,getPatternsFor:lt||void 0,I18N_PATHS:Pe||void 0},E={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function ut(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var gt={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"},$=class a{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._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,a._instance=this}normalizePath(e){if(!e)return"";try{return ks(e).split(pt).join("/")}catch{return String(e).split(pt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=ct(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(Q(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=xs(Z(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let n=e.replace("@donotdev/",""),l=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(l))return l;if(["auth","billing","crud","oauth"].includes(n)){let i=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(i))return i}if(n==="firebase"){let i=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(i))return i}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=me(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=me(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=me(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=w.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:_s(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await w.promises.readFile(e);let n=await w.promises.readFile(e,r),l=this.stripBom(n);return o==="json"?JSON.parse(l):l}catch(n){return this.options.debug&&E.warn(`Failed to read file: ${e}`,n),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return w.readFileSync(e);let n=w.readFileSync(e,r),l=this.stripBom(n);return o==="json"?JSON.parse(l):l}catch(n){return this.options.debug&&E.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:l=!1}=s,i=this.normalizePath(e),p=this.normalizePath(Q(i)),c=this.pathExists(i);if(c&&!o)return l&&E.info(`Skipping existing file: ${i}`),!1;if(n)return E.info(`[DRY RUN] Would write file: ${i}`),!0;try{await w.promises.mkdir(p,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
2
- `:g=String(t);try{return await ut(async()=>(Buffer.isBuffer(g)?await w.promises.writeFile(i,g):await w.promises.writeFile(i,g,"utf8"),l&&E.info(`${c?"Updated":"Created"} file: ${i}`),!0),`Failed to write file: ${i}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:l=!1}=s,i=this.normalizePath(e),p=this.normalizePath(Q(i)),c=this.pathExists(i);if(c&&!o)return l&&E.info(`Skipping existing file: ${i}`),!1;if(n)return E.info(`[DRY RUN] Would write file: ${i}`),!0;try{w.mkdirSync(p,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
3
- `:g=String(t);try{return Buffer.isBuffer(g)?w.writeFileSync(i,g):w.writeFileSync(i,g,"utf8"),this._writtenPaths?.add(i),l&&E.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch(f){throw new Error(`Failed to write file: ${i}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,l=this.normalizePath(t),i=this.pathExists(l);if(i&&!r)return n&&E.info(`Skipping existing file: ${l}`),!1;if(o)return E.info(`[DRY RUN] Would copy file: ${l}`),!0;let p=this.normalizePath(Q(l));try{await w.promises.mkdir(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await ut(async()=>(await w.promises.copyFile(e,l),n&&E.info(`${i?"Updated":"Created"} file: ${l}`),!0),`Failed to copy file from ${e} to ${l}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,l=this.normalizePath(t),i=this.pathExists(l);if(i&&!r)return n&&E.info(`Skipping existing file: ${l}`),!1;if(o)return E.info(`[DRY RUN] Would copy file: ${l}`),!0;let p=this.normalizePath(Q(l));try{w.mkdirSync(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return w.copyFileSync(e,l),this._writtenPaths?.add(l),n&&E.info(`${i?"Updated":"Created"} file: ${l}`),!0}catch{return!1}}pathExists(e,t=!1){try{return w.existsSync(e)}catch(s){return t||E.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return w.existsSync(t)||w.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return w.readdirSync(e,t)}catch(s){return this.options.debug&&E.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return w.statSync(e)}catch(t){return this.options.debug&&E.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return w.realpathSync(e)}watch(e,t,s){return w.watch(e,t,s)}lstatSync(e){try{return w.lstatSync(e)}catch(t){return this.options.debug&&E.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await w.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{w.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await w.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){w.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return w.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=Z(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(me(e)),s=this.getAppRoot(),r=ct(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(Z(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),l=r.startsWith(n)?r.slice(n.length+1):r,i={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:ce.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([l],{...i,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ce.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(Z(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await Es(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=ce.getGlobOptionsFor?ce.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),l=e.framework.map(c=>{let u=this.normalizePath(c);return u.startsWith(n)?u.slice(n.length+1):u}),i=e.consumer.map(c=>{let u=this.normalizePath(c);return u.startsWith(n)?u.slice(n.length+1):u}),p={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=l.length>0?await this._globWithNormalization(l,p):[],u=await this._globWithNormalization(i,p);return{frameworkFiles:c,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ce.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=ce.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let i=r,p={eager:i.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:i.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(i.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((i.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(i.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((i.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return p.all=[...p.eager,...p.lazy,...p.framework.eager,...p.framework.lazy],p}let n=r,l={framework:o?(n.framework||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):[],consumer:(n.consumer||[]).map(i=>this.resolveAppPath(i)),all:[]};return l.all=[...l.consumer,...l.framework],l}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyFlagModulePath(){let e=Q(As(import.meta.url));return this.normalizePath(me(e,"emptyFlag.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),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(Z(t,gt.TOOLING)),n=this.normalizePath(Z(t,gt.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let l=Z(t,"apps");if(this.pathExists(l)&&this.statSync(l)?.isDirectory())return this.normalizePath(t);let i=this.normalizePath(Z(t,"package.json"));if(this.pathExists(i)&&this.normalizePath(Q(t))===t)return t;let p=this.normalizePath(Q(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function ft({logger:a,debug:e=!1}={}){let t=$.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):a&&a.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&a&&a.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let n=t.resolveRepoPath("apps");if(t.pathExists(n))try{let l=process.cwd(),i=t.normalizePath(l);if(i.includes("/apps/")){let p=i.indexOf("/apps/"),u=i.substring(p+6).split("/")[0];if(u){let g=t.resolveRepoPath(`apps/${u}`),f=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(f)&&(r=g,t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}import Pt from"node:fs";function ht(a){let e=new Set(Object.keys(le)),t=new Set(["latin"]);for(let o of a||[]){let n=Se[o];if(n)for(let l of n)t.add(l)}let s=[],r=new Set;for(let o of e){let n=le[o];for(let l of t)for(let i of n){let p=`@fontsource/${o}/${l}-${i}.css`,c=`${o}-${l}-${i}-normal`;s.push(p),r.add(c)}}return{imports:s,stems:r,subsets:t,fontStems:e}}function Me(a){return a.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}import*as I from"@clack/prompts";var W={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function Cs(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function V(a,e){return Cs()?`${e}${a}${W.reset}`:a}function N(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=$.getInstance(),l=null;if(o){let c=n.resolveAppPath(r);n.pathExists(c)||n.mkdir(c),l=n.resolveAppPath(`${r}/${a.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${a} Log Started at ${new Date().toISOString()} ===
4
- `;n.writeSync(l,u)}let i=(c,u,g)=>{if(l){let f=new Date().toISOString(),h=g.length>0?" "+g.map(d=>typeof d=="object"?JSON.stringify(d,null,2):String(d)).join(" "):"",b=`${f} [${c}] ${u}${h}
5
- `;n.appendFile(l,b)}},p=(c,u)=>{if(u.length===0)return c;let g=u.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${c} ${g}`};return{debug:(c,...u)=>{e&&(o?i("DEBUG",c,u):I.log.message(V(p(c,u),W.gray)))},verbose:(c,...u)=>{t&&(o?i("VERBOSE",c,u):I.log.message(p(c,u)))},info:(c,...u)=>{o?i("INFO",c,u):I.log.info(V(p(c,u),W.brightCyan))},warn:(c,...u)=>{e&&o?i("WARN",c,u):I.log.warn(V(p(c,u),W.brightYellow))},error:(c,...u)=>{e&&o?i("ERROR",c,u):I.log.error(V(p(c,u),W.brightRed))},success:(c,...u)=>{e&&o?i("SUCCESS",c,u):I.log.success(V(p(c,u),W.brightGreen))},when:(c,u="debug")=>(g,...f)=>{if(c){let h=p(g,f);switch(u){case"verbose":t&&(I.log.message(h),i("VERBOSE",g,f));break;case"info":I.log.info(V(h,W.brightCyan)),i("INFO",g,f);break;case"warn":I.log.warn(V(h,W.brightYellow)),i("WARN",g,f);break;case"error":I.log.error(V(h,W.brightRed)),i("ERROR",g,f);break;case"success":I.log.success(V(h,W.brightGreen)),i("SUCCESS",g,f);break;default:e&&(I.log.message(V(h,W.gray)),i("DEBUG",g,f))}}},getLogFilePath:()=>l}}var G=class a{constructor(e,t={}){if(this.constructor===a)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=N(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let n=Date.now()-t;return this.logger.debug(`Discovery completed in ${n}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};function Ns(a){if(!a)return[];let e=$.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",a);if(!s)return[];let r=e.getDirname(e.getDirname(s)),o;try{o=e.readdirSync(r)}catch{return[]}for(let n of o)try{let l=e.resolvePath(`${n}/package.json`,r),i=e.readSync(l,{format:"json"});if(!i?.peerDependenciesMeta)continue;for(let[p,c]of Object.entries(i.peerDependenciesMeta))c?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function Fs(a){if(!a)return[];let e=$.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[o,n]of Object.entries(s.peerDependenciesMeta))n?.optional&&r.add(o);if(s.optionalDependencies)for(let o of Object.keys(s.optionalDependencies))r.add(o);return Array.from(r)}catch{return[]}}function Ds(a){let e=$e.optionalFeatures||[],t=Ns(a),s=Fs(a);return[...new Set([...e,...t,...s])]}function Os(a){let e=$.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function Ts(a,e,t){if(t.resolvePackage(a,e||void 0))return!0;let s=a.startsWith("@")?a.split("/").slice(0,2).join("/"):a.split("/")[0],r=e;for(let o=0;o<10;o++){let n=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(n))return!0;let l=t.getDirname(r);if(l===r)break;r=l}return!1}function xe(a){let e=Ds(a),t=[],s=[],r=$.getInstance(),o=Os(a);for(let n of e)n.startsWith("@donotdev/")?o.has(n)?s.push(n):t.push(n):o.has(n)&&Ts(n,a,r)?s.push(n):t.push(n);return{missing:t,installed:s}}var pe=class a extends G{static LANGUAGE_FLAG_OVERRIDES={en:"gb","en-ca":"ca","es-ar":"ar","fr-be":"be",ar:"sa","ar-ma":"ma","ar-dz":"dz","ar-tn":"tn","ar-ly":"ly","ar-mr":"mr",hi:"in",sl:"si",uk:"ua",ga:"ie",gd:"gb-sct",br:"bzh",co:"fr-cor",am:"et",bn:"bd",gu:"in",kn:"in",ml:"in",mr:"in",ne:"np",pa:"pk",ta:"in",te:"in",ur:"pk",fa:"ir",kk:"kz",ky:"kg",tg:"tj",my:"mm",km:"kh",lo:"la",ka:"ge",hy:"am",be:"by",bs:"ba",sq:"al",ms:"my"};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[s,r]of Object.entries(e)){for(let o of Object.keys(r))t.includes(o)||delete r[o];Object.keys(r).length===0&&delete e[s]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Re("i18n"),n=r.eager||[],l=r.lazy||[],i=(this.options.additionalPaths||[]).map(y=>{let P=y.endsWith(".json")?y:`${y}/*_*.json`;return this.pathResolver.resolveAppPath(P)});i.length>0&&this.logger.debug(`Additional i18n paths configured: ${i.join(", ")}`);let p=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${l.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${c.join(", ")}`),p.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),f=(y,P)=>{let R=this.pathResolver.normalizePath(y),k=this.pathResolver.normalizePath(P);return R.startsWith(k)?R.slice(k.length+1):R},h=n.map(y=>f(y,t)),d=[...l,...i].map(y=>f(y,t)),m=p.map(y=>f(y,s)),S=c.map(y=>f(y,s)),O={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},T=await this.pathResolver._globWithNormalization(h,O),M=await this.pathResolver._globWithNormalization(d,O),A={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(y=>y!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(A.ignore)}`);let L=await this.pathResolver._globWithNormalization(m,A),J=await this.pathResolver._globWithNormalization(S,A);this.logger.debug(`Found ${T.length} eager, ${M.length} lazy, ${L.length} framework eager, ${J.length} framework lazy files`),L.length>0?this.logger.debug(`Framework eager files (first 3): ${L.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),J.length>0?this.logger.debug(`Framework lazy files (first 3): ${J.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let ae=[...new Set([...T,...M,...L,...J])],ee=new Set([...T,...L]),v={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:ie}=xe(t),x=new Set(ie.filter(y=>y.startsWith("@donotdev/")).map(y=>y.replace("@donotdev/","")));x.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...x].join(", ")}] (packages not installed)`);let K=new Map,H=[...L,...J];for(let y of H){let P=this._processTranslationFile(y,L.includes(y),t);if(P){if(x.has(P.namespace))continue;let R=`${P.namespace}_${P.language}`;K.set(R,P),v.allNamespaces.add(P.namespace),v.supportedLanguages.add(P.language),L.includes(y)&&v.eagerNamespaces.add(P.namespace)}}let B=new Set;for(let y of ae){if(H.includes(y))continue;let P=this._processTranslationFile(y,ee.has(y),t);if(P){let{namespace:R,language:k,importPath:j,content:se}=P,we=`${P.namespace}_${P.language}`;if(K.has(we)){let Fe=K.get(we);P.content=this._mergeTranslations(Fe.content,se)}v.allNamespaces.add(R),v.supportedLanguages.add(k),B.add(k),ee.has(y)&&v.eagerNamespaces.add(R),v.mapping[R]||(v.mapping[R]={}),v.mapping[R][k]=j,P.content&&(v.content[R]||(v.content[R]={}),v.content[R][k]=P.content),v.files.push({path:y,relativePath:this.pathResolver.getRelativePath(y),namespace:R,language:k,eager:ee.has(y),size:P.content?JSON.stringify(P.content).length:0})}}for(let[y,P]of K){let R=y.lastIndexOf("_"),k=y.slice(0,R),j=y.slice(R+1);B.size>0&&!B.has(j)||(!v.mapping[k]||!v.mapping[k][j])&&(v.mapping[k]||(v.mapping[k]={}),v.mapping[k][j]=P.importPath,v.content[k]||(v.content[k]={}),v.content[k][j]=P.content,v.files.push({path:P.absolutePath,relativePath:this.pathResolver.getRelativePath(P.absolutePath),namespace:k,language:j,eager:v.eagerNamespaces.has(k),size:P.content?JSON.stringify(P.content).length:0}))}let te=B.size>0?[...B].sort():[this.options.fallbackLanguage],X=this._getLanguageAllowlist(),_=te;if(X){let y=te.filter(R=>X.includes(R));_=y.length>0?y:[this.options.fallbackLanguage],this._restrictByLanguage(v.mapping,_),this._restrictByLanguage(v.content,_),v.files=v.files.filter(R=>_.includes(R.language));let P=new Set(Object.keys(v.mapping));v.allNamespaces=new Set([...v.allNamespaces].filter(R=>P.has(R))),v.eagerNamespaces=new Set([...v.eagerNamespaces].filter(R=>P.has(R))),this.logger.debug(`I18n restricted by i18n.only [${X.join(", ")}]: languages [${_.join(", ")}], namespaces ${P.size}`)}let q=[...new Set(_.map(y=>a.LANGUAGE_FLAG_OVERRIDES[y]||y))];return{mapping:v.mapping,content:v.content,eagerNamespaces:[...v.eagerNamespaces].sort(),allNamespaces:[...v.allNamespaces].sort(),supportedLanguages:_,fallbackLanguage:this.options.fallbackLanguage,flagCodes:q,files:v.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[a.LANGUAGE_FLAG_OVERRIDES[this.options.fallbackLanguage]||this.options.fallbackLanguage],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,n,l=r.match(/^(.+)_([^_.]+)\.json$/);if(!l)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,n]=l,!o||!n)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let p="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:o,language:n,importPath:p,absolutePath:e,content:c}}_mergeTranslations(e,t){let s={...e};for(let[r,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?s[r]=this._mergeTranslations(s[r]||{},o):s[r]=o;return s}};var Is=3,dt="dndev-font-preloads.json";function mt({pathResolver:a,debug:e=!1,languages:t=[]}){let s=N("font-preload-next",e,!1);return{apply(r){r.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(o,n)=>{if(o.compiler.isChild()||o.compiler.name?.includes("server"))return n();try{if(!a.getAppRoot())return n();let p=t.length?t:["en"];if(!t.length)try{let m=await new pe(a,{fallbackLanguage:"en"}).discoverTranslations();m?.supportedLanguages?.length&&(p=m.supportedLanguages)}catch{}let u=ht(p).stems,g=o.outputOptions.publicPath&&String(o.outputOptions.publicPath)!=="auto"?o.outputOptions.publicPath.replace(/\/$/,""):"",f=[];for(let[d]of Object.entries(o.assets)){if(!d.endsWith(".woff2"))continue;let m=d.toLowerCase();if(Array.from(u).some(S=>m.includes(S))){let S=g?`${g}/${d}`:`/${d}`;if(f.push({href:S,type:"font/woff2"}),f.length>=Is)break}}let h=a.resolveAppPath("public");if(!a.pathExists(h))try{a.ensureDirSync(h)}catch(d){return s.debug(`Font preload: could not create public dir: ${d?.message}`),n()}let b=a.resolvePath(dt,h);a.writeSync(b,JSON.stringify(f,null,0),{overwrite:!0}),s.debug(`Font preload: wrote ${f.length} entries to ${dt}`)}catch(i){s.debug(`Font preload manifest: ${i?.message}`)}n()})}}}import{createRequire as Ms}from"node:module";var vt=Ms(import.meta.url),Le;function Ls(){return Le===void 0&&(Le=[[vt.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],vt.resolve("@babel/plugin-transform-parameters")]),Le}function bt({logger:a=N("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:o}=s,{RawSource:n}=o;t.hooks.thisCompilation.tap("DndevLowerDestructuring",l=>{l.compiler.isChild()||l.compiler.name?.includes("server")||l.options.mode==="production"&&l.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async i=>{let p,c;try{p=(await import("@babel/core")).default,c=Ls()}catch(g){a.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${g?.message}`);return}let u=0;for(let g of Object.keys(i)){if(!g.endsWith(".js"))continue;let f=l.getAsset(g).source.source(),h=typeof f=="string"?f:f.toString("utf8"),b;try{b=p.transformSync(h,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:c})}catch(d){throw new Error(`[lower-destructuring] failed to transform ${g}: ${d.message}`)}b?.code&&b.code!==h&&(l.updateAsset(g,new n(b.code)),u++)}e&&a.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function yt({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?a({resolve:s}):a,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var wt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function js(a){return(e,t)=>{wt[e]&&(e=wt[e]);let s=a.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),n=a.resolveFrameworkPackage(r,t);if(n){if(o){let i=a.resolvePath(o,n);if(a.pathExists(i))return i;let p=i+".css";if(a.pathExists(p))return p}let l=a.resolvePath("index.css",n);if(a.pathExists(l))return l}}return a.resolvePath(e,t)}}async function zs(){let[a,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=$.getInstance();return yt({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:js(s)})}function Y(a){return a&&typeof a=="object"&&!Array.isArray(a)}var $t={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function St({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],languages:o=[],logger:n,debug:l}){return(i,p)=>{let{dev:c,isServer:u,webpack:g}=p;c&&!u&&(i.infrastructureLogging={level:"error"},i.stats={...i.stats,logging:"error",loggingTrace:!1},i.ignoreWarnings=[...i.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let f=i.module?.rules?.find(h=>h.test?.test?.(".svg"));f&&(f.exclude=/\.svg$/i),i.module=i.module||{},i.module.rules=i.module.rules||[],i.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),i.module.rules.push({test:/\.md$/,type:"asset/source"}),i.resolve=i.resolve||{},i.resolve.alias=i.resolve.alias||{};try{let h=$.getInstance(),b=h.resolveAppPath(D.next.blogContent);i.resolve.alias[De.blog]=Pt.existsSync(b)?b:h.getEmptyCjsModulePath()}catch(h){n.debug(`Blog content alias fallback to empty stub: ${h?.message}`)}i.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...$t},g?.IgnorePlugin&&i.plugins.push(new g.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=$.getInstance();i.plugins.push(mt({pathResolver:h,debug:l,languages:o}))}catch(h){n.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(!u)try{i.plugins.push(bt({logger:n,debug:l}))}catch(h){n.debug(`Lower-destructuring webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(n.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),n.info(`\u2705 Including features: ${t.join(", ")}`),i.externals=i.externals||[],Array.isArray(i.externals))i.externals.push(...e);else{let h=i.externals;i.externals=(b,d,m)=>e.includes(d)?m(null,"commonjs "+d):typeof h=="function"?h(b,d,m):m()}if(s.length>0&&g?.NormalModuleReplacementPlugin){let b=$.getInstance().getEmptyCjsModulePath(),d=s.map(S=>S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),m=new RegExp(`^(${d.join("|")})(\\/|$)`);i.plugins.push(new g.NormalModuleReplacementPlugin(m,b)),l&&n.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&g?.NormalModuleReplacementPlugin){let b=$.getInstance().getEmptyFlagModulePath(),d=new Set(r.map(m=>m.toUpperCase()));i.plugins.push(new g.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,m=>{let S=m.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);S&&S[1].toUpperCase()!=="BASE"&&!d.has(S[1].toUpperCase())&&(m.request=b)})),l&&n.debug(`Flag filter: allowing ${d.size} flags, aliasing rest to empty component`)}return a?a(i,p):i}}function Rt({originalRewrites:a,handlers:e,logger:t}){return async function(){try{let s=a?await a():[],o=e.filter(l=>l?.getAPIRewrites).map(l=>l.getAPIRewrites()).reduce((l,i)=>(i?.beforeFiles&&l.beforeFiles.push(...i.beforeFiles),i?.afterFiles&&l.afterFiles.push(...i.afterFiles),i?.fallback&&l.fallback.push(...i.fallback),l),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...o.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function Us(a){let e=a||[],t=new Set(e.map(o=>o?.path).filter(Boolean)),s=[],r=new Set;for(let o of e){let n=String(o?.file||o?.importPath||"").replace(/\\/g,"/");if(n=n.replace(/^\/?(?:src\/)?/,""),!n.startsWith("pages/")||(n=n.slice(6).replace(/\.[jt]sx?$/,""),!n||n.split("/").some(p=>p.startsWith("_")))||n==="api"||n.startsWith("api/"))continue;n=n.replace(/(?:^|\/)index$/,"");let l=n?"/"+n:"/",i=o?.path;!i||l===i||/[[\]]/.test(l)||/[:[]/.test(i)||t.has(l)||r.has(l)||(r.add(l),s.push({from:l,to:i,permanent:!0}))}return s}function xt({originalRedirects:a,seoRedirects:e,routes:t,logger:s}){return async function(){try{let r=a?await a():[],o=Us(t),l=[...e||[],...o].map(({from:u,to:g,permanent:f})=>({source:u,destination:g,permanent:f!==!1})),i=[],p=new Set;for(let u of l){let g=u.source.replace(/\/+$/,"")||"/",f=u.destination.replace(/\/+$/,"")||"/";if(g===f){s.warn(`Redirect loop detected: ${u.source} \u2192 ${u.destination} (skipped)`);continue}if(!u.source.startsWith("/")){s.warn(`Redirect source must start with /: "${u.source}" (skipped)`);continue}if(p.has(g)){s.warn(`Duplicate redirect source: "${u.source}" (skipped)`);continue}p.add(g),i.push(u)}let c=[...Array.isArray(r)?r:[],...i];return c.length===0?[]:(s.info(` \u{1F4CE} ${c.length} redirect${c.length>1?"s":""} configured`),c)}catch(r){return s.error(`Failed to merge redirects: ${r.message}`),[]}}}function kt({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:l,discoveredPackages:i,reactCompiler:p=!1,webpackConfig:c,rewritesConfig:u,redirectsConfig:g,missingOptionalDeps:f,flagCodes:h=[],pathResolver:b,env:d,logger:m}){let S=l?.output==="export",T=l?.distDir||".next";return{transpilePackages:[...i,...f||[]],...p?{reactCompiler:p}:{},...Y(l)?l:(m.warn("restNextConfig is not a plain object:",l),{}),serverExternalPackages:(l?.serverExternalPackages||l?.serverComponentsExternalPackages||[]).filter(A=>!A.startsWith("@donotdev/")&&!f?.includes(A)),turbopack:{...l?.turbopack||{},root:l?.turbopack?.root||b.getRepoRoot(),resolveAlias:{...l?.turbopack?.resolveAlias||{},...$t,[De.blog]:(()=>{try{let A=b.resolveAppPath(D.next.blogContent);if(Pt.existsSync(A))return"./"+D.next.blogContent}catch{}return"@donotdev/core/empty"})(),...f?.length>0?Object.fromEntries(f.flatMap(A=>[[A,"@donotdev/core/empty"],[`${A}/*`,"@donotdev/core/empty"]])):{}}},distDir:T,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...Y(a)?a:(m.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...Y(e)?e:(m.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...Y(t)?t:(m.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...Y(s)?s:(m.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...Y(r)?r:(m.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...Y(o)?o:(m.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...Y(n)?n:(m.warn("serverShimConfig returned non-object:",n),{}),webpack:c,...S?{}:{rewrites:u,...g?{redirects:g}:{}},env:d,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var ke="fonts",je="dndev-fonts.css",Gs=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,At=/url\(\.\/files\/([^)]+)\)/g;function Bs(a){let e=new Set(["latin"]);for(let t of a){let s=Se[t];if(s)for(let r of s)e.add(r)}return e}function Ws(a,e){let t=a.resolvePath("src/dndev.css",e),s=a.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=Gs.exec(s))!==null;)r.push([o[1],o[2]]);return r}function Hs(a,e,t,s,r){let o=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
6
- `],n=new Set,l=r&&r.size>0;for(let[i,p]of e){let c=a.resolveFrameworkPackage(`@fontsource/${i}`);if(!c){s.debug(`@fontsource/${i} not found`);continue}let u=!!le[i];if(l&&u)for(let g of r){let f=a.resolvePath(`${g}-${p}.css`,c),h=a.readSync(f,{format:"text"});if(!h)continue;let b=_t(Me(h),a,c,t,n,s,!0);o.push(b)}else{let g=a.resolvePath(`${p}.css`,c),f=a.readSync(g,{format:"text"});if(!f){s.debug(`Missing: @fontsource/${i}/${p}.css`);continue}let h=_t(f,a,c,t,n,s,!1);o.push(h)}}return{cssChunks:o,copiedFiles:n}}function _t(a,e,t,s,r,o,n){return a.replace(At,(l,i)=>{if(n&&i.endsWith(".woff"))return"url(data:,)";let p=e.resolvePath(`files/${i}`,t);if(!e.pathExists(p))return o.warn(`Font file missing: ${p} \u2014 dropping from CSS`),"url(data:,)";if(!r.has(i)){let u=e.resolvePath(i,s);e.copySync(p,u,{overwrite:!0}),r.add(i)}return`url(/${ke}/${i})`})}var Vs=/@font-face\s*\{[^}]*\}/g;function Js(a,e,t,s,r){let o=a.resolvePath("dist/dndev.css",e),n=a.readSync(o,{format:"text"});if(!n)return s.debug("dist/dndev.css not found in @donotdev/ui"),{cssChunks:[],copiedFiles:new Set};let l=n.match(Vs);if(!l||l.length===0)return s.debug("No @font-face blocks found in dist/dndev.css"),{cssChunks:[],copiedFiles:new Set};let i=r&&r.size>0,p=new Set(Object.keys(le));i&&(l=l.filter(h=>{if(!Array.from(p).some(d=>h.includes(`${d}-`)))return!0;for(let d of r)if(h.includes(`-${d}-`))return!0;return!1}));let c=a.resolvePath("dist/files",e),u=new Set;return{cssChunks:[`/* Auto-generated by @donotdev/core \u2014 do not edit */
7
- `,...l.map(h=>{let b=i&&Array.from(p).some(m=>h.includes(`${m}-`));return(b?Me(h):h).replace(At,(m,S)=>{if(b&&S.endsWith(".woff"))return"url(data:,)";let O=a.resolvePath(S,c);if(!a.pathExists(O))return s.warn(`Font file missing: ${O} \u2014 dropping from CSS`),"url(data:,)";if(!u.has(S)){let M=a.resolvePath(S,t);a.copySync(O,M,{overwrite:!0}),u.add(S)}return`url(/${ke}/${S})`})})],copiedFiles:u}}function Et({debug:a=!1,force:e=!1,languages:t}={}){let s=N("font-copy",a,!1),r=$.getInstance(),o=r.resolveAppPath(`public/${je}`);if(!e&&r.pathExists(o)){s.debug("dndev-fonts.css already exists, skipping font copy");return}let n=r.resolveFrameworkPackage("@donotdev/ui");if(!n){s.debug("@donotdev/ui not found, skipping font copy");return}let l=r.resolveAppPath(`public/${ke}`);r.ensureDirSync(l);let i=t?.length?Bs(t):null;i&&s.debug(`Font copy: locale-aware filtering \u2014 locales=[${t.join(",")}] subsets=[${[...i].join(",")}]`);let p=Ws(r,n),c,u;if(p.length>0?(s.debug(`Monorepo mode: ${p.length} @fontsource imports found`),{cssChunks:c,copiedFiles:u}=Hs(r,p,l,s,i)):(s.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:c,copiedFiles:u}=Js(r,n,l,s,i)),u.size===0){s.debug("No font files found to copy");return}r.writeSync(o,c.join(`
8
- `)),s.debug(`Font copy: wrote ${je} (${u.size} font files copied)`)}function Ct(){let a=$.getInstance(),e=a.resolveAppPath(`public/${je}`),t=a.resolveAppPath(`public/${ke}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var qs=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json","public/dndev-fonts.css","public/robots.txt","public/sitemap.xml","public/rss.xml","public/llms.txt","public/llms-full.txt"],Ys="dndev-config-",Nt=".dndev-build";function ze(a){if(!a)return!1;let e=$.getInstance(),t=e.resolveAppPath(Nt),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function Ks(a){if(!a)return;let e=$.getInstance(),t=e.resolveAppPath(Nt),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s,{overwrite:!0})}catch{}}function Xs(a,e,t){if(!a)return;let s=$.getInstance(),r=(n,l)=>{let i=s.normalizePath(n);if(!(t.has(i)||!s.pathExists(i)))try{s.removeSync(n),e.debug(`Removed stale: ${l}`)}catch{}};for(let n of qs)r(s.resolveAppPath(n),n);let o=s.resolveAppPath("src/config");for(let n of s.readdirSync(o))n.startsWith(Ys)&&n.endsWith(".js")&&r(s.resolvePath(n,o),`src/config/${n}`)}async function Ft({routeHandler:a,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:o,blogContentHandler:n},l){let i=a?.pathResolver;if(!i)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let p=i.getAppRoot(),c=i.getRepoRoot();if(!p||p===c){l.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(b=>setTimeout(b,0));let h=i.getAppRoot();if(!h||h===c)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(ze(p)){l.debug("Discoveries already completed this build, skipping");return}Ks(p);let u=Date.now();i.startWriteRecording();let g;try{if(Ct(),a)try{l.info("\u{1F50D} Starting route discovery...");let m=(await a.generateFiles())?.routes?.length||0;l.info(`\u2705 Routes generated: ${m} routes found`),m===0&&l.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(d){throw l.error(`\u274C Route generation failed: ${d.message}`),d.stack&&l.error(`Stack: ${d.stack}`),d}else l.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let h=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:o},{name:"BlogContent",handler:n}],b;for(let{name:d,handler:m}of h)try{let S=await m.generateFiles();d==="I18n"&&S?.supportedLanguages?.length&&(b=S.supportedLanguages)}catch(S){l.debug(`${d} generation failed: ${S.message}`)}try{Zs(i,l)}catch(d){l.debug(`Env config generation failed (non-critical): ${d.message}`)}try{Et({languages:b})}catch(d){l.debug(`Font copy failed (non-critical): ${d.message}`)}}finally{g=i.stopWriteRecording()}Xs(p,l,g);let f=Date.now()-u;l.verbose?.(`\u2705 All discoveries completed in ${f}ms - Next.js can now compile`)}function Zs(a,e){let t={};for(let[n,l]of Object.entries(process.env))n.startsWith("NEXT_PUBLIC_")&&l!==void 0&&(t[n]=l);let s=`// Auto-generated DnDev env config by @donotdev/config
1
+ import*as $ from"node:fs";import"node:fs";import{createRequire as zs}from"node:module";import{resolve as Se,join as oe,dirname as ae,relative as bt,normalize as Bs,sep as wt,extname as Ws}from"node:path";import{fileURLToPath as Hs}from"node:url";import qs from"fast-glob";var be={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var Ge={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},X={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},B={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},T={next:{proxy:"src/proxy.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"}},pe="/og-image.png",ze={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},we={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Ae={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"},J={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:[`${Ae.SOURCE_EAGER}/*_*.json`],lazy:[`${Ae.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},_e={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"]},vt=["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"];var Be={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)/}};var ge={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]},ke={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin"],cs:["latin"],sk:["latin"],hr:["latin"],sl:["latin"],hu:["latin"],ro:["latin"],et:["latin"],lv:["latin"],lt:["latin"],mt:["latin"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},We=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],mt={base:{absolute:!0,onlyFiles:!0,ignore:J.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...J.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...J.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:J.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:J.globalIgnore}};function yt(o,e=null){let t=J[o];if(!t)throw new Error(`Unknown pattern type: ${o}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Ne(o){return mt[o]||mt.base}var he={getGlobOptionsFor:Ne||void 0,SCAN_PATTERNS:J||void 0,getPatternsFor:yt||void 0,I18N_PATHS:Ae||void 0},I={error:(o,e)=>{},warn:(o,e)=>{},info:o=>{}};function de(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EEXIST"}function St(o,e){return o().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var $t={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"},R=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 Bs(e).split(wt).join("/")}catch{return String(e).split(wt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=bt(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(ae(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),n=zs(oe(s,"package.json")).resolve(e);return this.normalizePath(n)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),l=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(l))return l;if(["auth","billing","crud","oauth"].includes(a)){let i=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(i))return i}if(a==="firebase"){let i=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(i))return i}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let n=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(n)?n:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=Se(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Se(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),n=Se(s,r);return this.normalizePath(n)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=$.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:Ws(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return await $.promises.readFile(e);let a=await $.promises.readFile(e,r),l=this.stripBom(a);return n==="json"?JSON.parse(l):l}catch(a){return this.options.debug&&I.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return $.readFileSync(e);let a=$.readFileSync(e,r),l=this.stripBom(a);return n==="json"?JSON.parse(l):l}catch(a){return this.options.debug&&I.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:a=!1,verbose:l=!1}=s,i=this.normalizePath(e),c=this.normalizePath(ae(i)),p=this.pathExists(i);if(p&&!n)return l&&I.info(`Skipping existing file: ${i}`),!1;if(a)return I.info(`[DRY RUN] Would write file: ${i}`),!0;try{await $.promises.mkdir(c,{recursive:!0})}catch(d){if(!de(d))throw d}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
2
+ `:g=String(t);try{return await St(async()=>(Buffer.isBuffer(g)?await $.promises.writeFile(i,g):await $.promises.writeFile(i,g,"utf8"),l&&I.info(`${p?"Updated":"Created"} file: ${i}`),!0),`Failed to write file: ${i}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:a=!1,verbose:l=!1}=s,i=this.normalizePath(e),c=this.normalizePath(ae(i)),p=this.pathExists(i);if(p&&!n)return l&&I.info(`Skipping existing file: ${i}`),!1;if(a)return I.info(`[DRY RUN] Would write file: ${i}`),!0;try{$.mkdirSync(c,{recursive:!0})}catch(d){if(!de(d))throw d}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
3
+ `:g=String(t);try{return Buffer.isBuffer(g)?$.writeFileSync(i,g):$.writeFileSync(i,g,"utf8"),this._writtenPaths?.add(i),l&&I.info(`${p?"Updated":"Created"} file: ${i}`),!0}catch(d){throw new Error(`Failed to write file: ${i}: ${d instanceof Error?d.message:String(d)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:n=!1,verbose:a=!1}=s,l=this.normalizePath(t),i=this.pathExists(l);if(i&&!r)return a&&I.info(`Skipping existing file: ${l}`),!1;if(n)return I.info(`[DRY RUN] Would copy file: ${l}`),!0;let c=this.normalizePath(ae(l));try{await $.promises.mkdir(c,{recursive:!0})}catch(p){if(!de(p))throw p}try{return await St(async()=>(await $.promises.copyFile(e,l),a&&I.info(`${i?"Updated":"Created"} file: ${l}`),!0),`Failed to copy file from ${e} to ${l}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:n=!1,verbose:a=!1}=s,l=this.normalizePath(t),i=this.pathExists(l);if(i&&!r)return a&&I.info(`Skipping existing file: ${l}`),!1;if(n)return I.info(`[DRY RUN] Would copy file: ${l}`),!0;let c=this.normalizePath(ae(l));try{$.mkdirSync(c,{recursive:!0})}catch(p){if(!de(p))throw p}try{return $.copyFileSync(e,l),this._writtenPaths?.add(l),a&&I.info(`${i?"Updated":"Created"} file: ${l}`),!0}catch{return!1}}pathExists(e,t=!1){try{return $.existsSync(e)}catch(s){return t||I.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return $.existsSync(t)||$.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return $.readdirSync(e,t)}catch(s){return this.options.debug&&I.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return $.statSync(e)}catch(t){return this.options.debug&&I.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return $.realpathSync(e)}watch(e,t,s){return $.watch(e,t,s)}lstatSync(e){try{return $.lstatSync(e)}catch(t){return this.options.debug&&I.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await $.promises.mkdir(e,{recursive:!0})}catch(t){if(!de(t))throw t}}ensureDirSync(e){try{$.mkdirSync(e,{recursive:!0})}catch(t){if(!de(t))throw t}}async remove(e){await $.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){$.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return $.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=oe(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Se(e)),s=this.getAppRoot(),r=bt(s,t),n=this.normalizePath(r);return!n.startsWith("../")&&!n.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(oe(e,t)),n=this.getAppRoot(),a=this.normalizePath(n),l=r.startsWith(a)?r.slice(a.length+1):r,i={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:he.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([l],{...i,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=he.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let n=this.normalizePath(oe(r,t.PUBLISHED_ROOT,s)),a=n.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),n}async _globWithNormalization(e,t){return(await qs(e,t)).map(r=>{let n=typeof r=="string"?r:r.path;return this.normalizePath(n)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let p of s)if(typeof p!="string"||p.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),n=he.getGlobOptionsFor?he.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),l=e.framework.map(p=>{let u=this.normalizePath(p);return u.startsWith(a)?u.slice(a.length+1):u}),i=e.consumer.map(p=>{let u=this.normalizePath(p);return u.startsWith(a)?u.slice(a.length+1):u}),c={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let p=l.length>0?await this._globWithNormalization(l,c):[],u=await this._globWithNormalization(i,c);return{frameworkFiles:p,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!he.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=he.getPatternsFor(e),n=this.isMonorepo();if(e==="i18n"){let i=r,c={eager:i.eager.map(p=>p.startsWith("!")?"!"+this.resolveAppPath(p.slice(1)):this.resolveAppPath(p)),lazy:i.lazy.map(p=>p.startsWith("!")?"!"+this.resolveAppPath(p.slice(1)):this.resolveAppPath(p)),framework:{eager:n?(i.framework?.eager||[]).map(p=>this.resolveRepoPath(p)).filter(Boolean):await Promise.all((i.framework?.eager||[]).map(p=>this._resolveFrameworkI18nPattern(p))).then(p=>p.filter(Boolean)),lazy:n?(i.framework?.lazy||[]).map(p=>this.resolveRepoPath(p)).filter(Boolean):await Promise.all((i.framework?.lazy||[]).map(p=>this._resolveFrameworkI18nPattern(p))).then(p=>p.filter(Boolean))},all:[]};return c.all=[...c.eager,...c.lazy,...c.framework.eager,...c.framework.lazy],c}let a=r,l={framework:n?(a.framework||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):[],consumer:(a.consumer||[]).map(i=>this.resolveAppPath(i)),all:[]};return l.all=[...l.consumer,...l.framework],l}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyFlagModulePath(){let e=ae(Hs(import.meta.url));return this.normalizePath(Se(e,"emptyFlag.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),s=0,r=this.options.maxLevels;for(;s<r;){let n=this.normalizePath(oe(t,$t.TOOLING)),a=this.normalizePath(oe(t,$t.CORE));if(this.pathExists(n)&&this.pathExists(a))return t;let l=oe(t,"apps");if(this.pathExists(l)&&this.statSync(l)?.isDirectory())return this.normalizePath(t);let i=this.normalizePath(oe(t,"package.json"));if(this.pathExists(i)&&this.normalizePath(ae(t))===t)return t;let c=this.normalizePath(ae(t));if(c===t)break;t=c,s++}return this.normalizePath(e)}};function Pt({logger:o,debug:e=!1}={}){let t=R.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&o&&o.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):o&&o.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&o&&o.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let a=t.resolveRepoPath("apps");if(t.pathExists(a))try{let l=process.cwd(),i=t.normalizePath(l);if(i.includes("/apps/")){let c=i.indexOf("/apps/"),u=i.substring(c+6).split("/")[0];if(u){let g=t.resolveRepoPath(`apps/${u}`),d=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(d)&&(r=g,t.setAppRoot(r),s=!0,e&&o&&o.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&o&&o.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}import Tt from"node:fs";function Rt(o){let e=new Set(Object.keys(ge)),t=new Set(["latin"]);for(let n of o||[]){let a=ke[n];if(a)for(let l of a)t.add(l)}let s=[],r=new Set;for(let n of e){let a=ge[n];for(let l of t)for(let i of a){let c=`@fontsource/${n}/${l}-${i}.css`,p=`${n}-${l}-${i}-normal`;s.push(c),r.add(p)}}return{imports:s,stems:r,subsets:t,fontStems:e}}function He(o){return o.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}import*as W from"@clack/prompts";var Z={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 Q(o,e){return Vs()?`${e}${o}${Z.reset}`:o}function M(o,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:n=!1}=s,a=R.getInstance(),l=null;if(n){let p=a.resolveAppPath(r);a.pathExists(p)||a.mkdir(p),l=a.resolveAppPath(`${r}/${o.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${o} Log Started at ${new Date().toISOString()} ===
4
+ `;a.writeSync(l,u)}let i=(p,u,g)=>{if(l){let d=new Date().toISOString(),h=g.length>0?" "+g.map(m=>typeof m=="object"?JSON.stringify(m,null,2):String(m)).join(" "):"",w=`${d} [${p}] ${u}${h}
5
+ `;a.appendFile(l,w)}},c=(p,u)=>{if(u.length===0)return p;let g=u.map(d=>typeof d=="object"?JSON.stringify(d,null,2):String(d)).join(" ");return`${p} ${g}`};return{debug:(p,...u)=>{e&&(n?i("DEBUG",p,u):W.log.message(Q(c(p,u),Z.gray)))},verbose:(p,...u)=>{t&&(n?i("VERBOSE",p,u):W.log.message(c(p,u)))},info:(p,...u)=>{n?i("INFO",p,u):W.log.info(Q(c(p,u),Z.brightCyan))},warn:(p,...u)=>{e&&n?i("WARN",p,u):W.log.warn(Q(c(p,u),Z.brightYellow))},error:(p,...u)=>{e&&n?i("ERROR",p,u):W.log.error(Q(c(p,u),Z.brightRed))},success:(p,...u)=>{e&&n?i("SUCCESS",p,u):W.log.success(Q(c(p,u),Z.brightGreen))},when:(p,u="debug")=>(g,...d)=>{if(p){let h=c(g,d);switch(u){case"verbose":t&&(W.log.message(h),i("VERBOSE",g,d));break;case"info":W.log.info(Q(h,Z.brightCyan)),i("INFO",g,d);break;case"warn":W.log.warn(Q(h,Z.brightYellow)),i("WARN",g,d);break;case"error":W.log.error(Q(h,Z.brightRed)),i("ERROR",g,d);break;case"success":W.log.success(Q(h,Z.brightGreen)),i("SUCCESS",g,d);break;default:e&&(W.log.message(Q(h,Z.gray)),i("DEBUG",g,d))}}},getLogFilePath:()=>l}}var K=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=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 s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),n=await this._processFiles(r);this.cache={...n,timestamp:Date.now()};let a=Date.now()-t;return this.logger.debug(`Discovery completed in ${a}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],n=s.split(".").pop();return{fileName:s,baseName:r,extension:n,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};function Js(o){if(!o)return[];let e=R.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",o);if(!s)return[];let r=e.getDirname(e.getDirname(s)),n;try{n=e.readdirSync(r)}catch{return[]}for(let a of n)try{let l=e.resolvePath(`${a}/package.json`,r),i=e.readSync(l,{format:"json"});if(!i?.peerDependenciesMeta)continue;for(let[c,p]of Object.entries(i.peerDependenciesMeta))p?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function Xs(o){if(!o)return[];let e=R.getInstance();try{let t=e.resolvePath("package.json",o),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[n,a]of Object.entries(s.peerDependenciesMeta))a?.optional&&r.add(n);if(s.optionalDependencies)for(let n of Object.keys(s.optionalDependencies))r.add(n);return Array.from(r)}catch{return[]}}function Ks(o){let e=_e.optionalFeatures||[],t=Js(o),s=Xs(o);return[...new Set([...e,...t,...s])]}function Ys(o){let e=R.getInstance();try{let t=e.resolvePath("package.json",o),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function Zs(o,e,t){if(t.resolvePackage(o,e||void 0))return!0;let s=o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0],r=e;for(let n=0;n<10;n++){let a=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(a))return!0;let l=t.getDirname(r);if(l===r)break;r=l}return!1}function Ce(o){let e=Ks(o),t=[],s=[],r=R.getInstance(),n=Ys(o);for(let a of e)a.startsWith("@donotdev/")?n.has(a)?s.push(a):t.push(a):n.has(a)&&Zs(a,o,r)?s.push(a):t.push(a);return{missing:t,installed:s}}var fe=class o extends K{static LANGUAGE_FLAG_OVERRIDES={en:"gb","en-ca":"ca","es-ar":"ar","fr-be":"be",ar:"sa","ar-ma":"ma","ar-dz":"dz","ar-tn":"tn","ar-ly":"ly","ar-mr":"mr",hi:"in",sl:"si",uk:"ua",ga:"ie",gd:"gb-sct",br:"bzh",co:"fr-cor",am:"et",bn:"bd",gu:"in",kn:"in",ml:"in",mr:"in",ne:"np",pa:"pk",ta:"in",te:"in",ur:"pk",fa:"ir",kk:"kz",ky:"kg",tg:"tj",my:"mm",km:"kh",lo:"la",ka:"ge",hy:"am",be:"by",bs:"ba",sq:"al",ms:"my"};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[s,r]of Object.entries(e)){for(let n of Object.keys(r))t.includes(n)||delete r[n];Object.keys(r).length===0&&delete e[s]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let n=Ne("i18n"),a=r.eager||[],l=r.lazy||[],i=(this.options.additionalPaths||[]).map(S=>{let P=S.endsWith(".json")?S:`${S}/*_*.json`;return this.pathResolver.resolveAppPath(P)});i.length>0&&this.logger.debug(`Additional i18n paths configured: ${i.join(", ")}`);let c=r.framework?.eager||[],p=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${l.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${p.join(", ")}`),c.length===0&&p.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),d=(S,P)=>{let A=this.pathResolver.normalizePath(S),C=this.pathResolver.normalizePath(P);return A.startsWith(C)?A.slice(C.length+1):A},h=a.map(S=>d(S,t)),m=[...l,...i].map(S=>d(S,t)),b=c.map(S=>d(S,s)),f=p.map(S=>d(S,s)),y={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},x=await this.pathResolver._globWithNormalization(h,y),D=await this.pathResolver._globWithNormalization(m,y),O={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:n.ignore?.filter(S=>S!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(O.ignore)}`);let _=await this.pathResolver._globWithNormalization(b,O),G=await this.pathResolver._globWithNormalization(f,O);this.logger.debug(`Found ${x.length} eager, ${D.length} lazy, ${_.length} framework eager, ${G.length} framework lazy files`),_.length>0?this.logger.debug(`Framework eager files (first 3): ${_.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),G.length>0?this.logger.debug(`Framework lazy files (first 3): ${G.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${p.join(", ")}`);let re=[...new Set([...x,...D,..._,...G])],ee=new Set([...x,..._]),v={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:ne}=Ce(t),E=new Set(ne.filter(S=>S.startsWith("@donotdev/")).map(S=>S.replace("@donotdev/","")));E.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...E].join(", ")}] (packages not installed)`);let Y=new Map,z=[..._,...G];for(let S of z){let P=this._processTranslationFile(S,_.includes(S),t);if(P){if(E.has(P.namespace))continue;let A=`${P.namespace}_${P.language}`;Y.set(A,P),v.allNamespaces.add(P.namespace),v.supportedLanguages.add(P.language),_.includes(S)&&v.eagerNamespaces.add(P.namespace)}}let U=new Set;for(let S of re){if(z.includes(S))continue;let P=this._processTranslationFile(S,ee.has(S),t);if(P){let{namespace:A,language:C,importPath:V,content:le}=P,Ee=`${P.namespace}_${P.language}`;if(Y.has(Ee)){let je=Y.get(Ee);P.content=this._mergeTranslations(je.content,le)}v.allNamespaces.add(A),v.supportedLanguages.add(C),U.add(C),ee.has(S)&&v.eagerNamespaces.add(A),v.mapping[A]||(v.mapping[A]={}),v.mapping[A][C]=V,P.content&&(v.content[A]||(v.content[A]={}),v.content[A][C]=P.content),v.files.push({path:S,relativePath:this.pathResolver.getRelativePath(S),namespace:A,language:C,eager:ee.has(S),size:P.content?JSON.stringify(P.content).length:0})}}for(let[S,P]of Y){let A=S.lastIndexOf("_"),C=S.slice(0,A),V=S.slice(A+1);U.size>0&&!U.has(V)||(!v.mapping[C]||!v.mapping[C][V])&&(v.mapping[C]||(v.mapping[C]={}),v.mapping[C][V]=P.importPath,v.content[C]||(v.content[C]={}),v.content[C][V]=P.content,v.files.push({path:P.absolutePath,relativePath:this.pathResolver.getRelativePath(P.absolutePath),namespace:C,language:V,eager:v.eagerNamespaces.has(C),size:P.content?JSON.stringify(P.content).length:0}))}let q=U.size>0?[...U].sort():[this.options.fallbackLanguage],k=this._getLanguageAllowlist(),N=q;if(k){let S=q.filter(A=>k.includes(A));N=S.length>0?S:[this.options.fallbackLanguage],this._restrictByLanguage(v.mapping,N),this._restrictByLanguage(v.content,N),v.files=v.files.filter(A=>N.includes(A.language));let P=new Set(Object.keys(v.mapping));v.allNamespaces=new Set([...v.allNamespaces].filter(A=>P.has(A))),v.eagerNamespaces=new Set([...v.eagerNamespaces].filter(A=>P.has(A))),this.logger.debug(`I18n restricted by i18n.only [${k.join(", ")}]: languages [${N.join(", ")}], namespaces ${P.size}`)}let te=[...new Set(N.map(S=>o.LANGUAGE_FLAG_OVERRIDES[S]||S))];return{mapping:v.mapping,content:v.content,eagerNamespaces:[...v.eagerNamespaces].sort(),allNamespaces:[...v.allNamespaces].sort(),supportedLanguages:N,fallbackLanguage:this.options.fallbackLanguage,flagCodes:te,files:v.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[o.LANGUAGE_FLAG_OVERRIDES[this.options.fallbackLanguage]||this.options.fallbackLanguage],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",n,a,l=r.match(/^(.+)_([^_.]+)\.json$/);if(!l)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,n,a]=l,!n||!a)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),p;try{if(p=this.pathResolver.readSync(e,{format:"json"}),!p)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:n,language:a,importPath:c,absolutePath:e,content:p}}_mergeTranslations(e,t){let s={...e};for(let[r,n]of Object.entries(t))typeof n=="object"&&n!==null&&!Array.isArray(n)?s[r]=this._mergeTranslations(s[r]||{},n):s[r]=n;return s}};var Qs=3,xt="dndev-font-preloads.json";function Et({pathResolver:o,debug:e=!1,languages:t=[]}){let s=M("font-preload-next",e,!1);return{apply(r){r.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(n,a)=>{if(n.compiler.isChild()||n.compiler.name?.includes("server"))return a();try{if(!o.getAppRoot())return a();let c=t.length?t:["en"];if(!t.length)try{let b=await new fe(o,{fallbackLanguage:"en"}).discoverTranslations();b?.supportedLanguages?.length&&(c=b.supportedLanguages)}catch{}let u=Rt(c).stems,g=n.outputOptions.publicPath&&String(n.outputOptions.publicPath)!=="auto"?n.outputOptions.publicPath.replace(/\/$/,""):"",d=[];for(let[m]of Object.entries(n.assets)){if(!m.endsWith(".woff2"))continue;let b=m.toLowerCase();if(Array.from(u).some(f=>b.includes(f))){let f=g?`${g}/${m}`:`/${m}`;if(d.push({href:f,type:"font/woff2"}),d.length>=Qs)break}}let h=o.resolveAppPath("public");if(!o.pathExists(h))try{o.ensureDirSync(h)}catch(m){return s.debug(`Font preload: could not create public dir: ${m?.message}`),a()}let w=o.resolvePath(xt,h);o.writeSync(w,JSON.stringify(d,null,0),{overwrite:!0}),s.debug(`Font preload: wrote ${d.length} entries to ${xt}`)}catch(i){s.debug(`Font preload manifest: ${i?.message}`)}a()})}}}import{createRequire as er}from"node:module";var At=er(import.meta.url),qe;function tr(){return qe===void 0&&(qe=[[At.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],At.resolve("@babel/plugin-transform-parameters")]),qe}function _t({logger:o=M("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:n}=s,{RawSource:a}=n;t.hooks.thisCompilation.tap("DndevLowerDestructuring",l=>{l.compiler.isChild()||l.compiler.name?.includes("server")||l.options.mode==="production"&&l.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async i=>{let c,p;try{c=(await import("@babel/core")).default,p=tr()}catch(g){o.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${g?.message}`);return}let u=0;for(let g of Object.keys(i)){if(!g.endsWith(".js"))continue;let d=l.getAsset(g).source.source(),h=typeof d=="string"?d:d.toString("utf8"),w;try{w=c.transformSync(h,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:p})}catch(m){throw new Error(`[lower-destructuring] failed to transform ${g}: ${m.message}`)}w?.code&&w.code!==h&&(l.updateAsset(g,new a(w.code)),u++)}e&&o.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function kt({postcssImport:o,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?o({resolve:s}):o,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var Nt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function sr(o){return(e,t)=>{Nt[e]&&(e=Nt[e]);let s=o.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],n=e.split("/").slice(2).join("/"),a=o.resolveFrameworkPackage(r,t);if(a){if(n){let i=o.resolvePath(n,a);if(o.pathExists(i))return i;let c=i+".css";if(o.pathExists(c))return c}let l=o.resolvePath("index.css",a);if(o.pathExists(l))return l}}return o.resolvePath(e,t)}}async function rr(){let[o,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=R.getInstance();return kt({postcssImport:o,postcssNesting:e,autoprefixer:t,resolve:sr(s)})}import{renameSync as nr}from"node:fs";import{basename as Ct,dirname as or,join as Je,relative as ar}from"node:path";var ie="next",ir=["tsx","ts","jsx","js"],Dt=ir.map(o=>`${ie}.${o}`);function F(o,e){return`${o}.${ie}.${e}`}var lr=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],cr=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],pr=["proxy","middleware","instrumentation"],ur="// Generated by @donotdev/config";function Ve(o,e){let t=o.match(new RegExp(`^(.+?)(\\.${ie})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,s,r,n]=t;return e.includes(s)?{name:s,extension:n,marked:!!r}:null}function gr(o){let e=[],t=o.resolveAppPath("src/app"),s=r=>{for(let n of o.readdirSync(r,{withFileTypes:!0})){let a=Je(r,n.name);if(n.isDirectory()){s(a);continue}if(!n.isFile())continue;let l=Ve(n.name,lr);l&&e.push({file:a,...l,metadata:!1});let i=Ve(n.name,cr);i&&e.push({file:a,...i,metadata:!0})}};o.pathExists(t)&&s(t);for(let r of[o.resolveAppPath("src"),o.getAppRoot()])if(o.pathExists(r))for(let n of o.readdirSync(r,{withFileTypes:!0})){let a=n.isFile()&&Ve(n.name,pr);a&&e.push({file:Je(r,n.name),...a,metadata:!1})}return e}function Ft({pathResolver:o,logger:e,isCI:t}){let s=o.getAppRoot(),r=c=>ar(s,c),n=[],a=[],l=[],i=[];for(let c of gr(o)){let p=o.readSync(c.file,{format:"text"})||"";if(!c.marked&&p.startsWith(ur)){o.removeSync(c.file),a.push(r(c.file));continue}c.metadata?i.push(r(c.file)):c.marked||l.push(c)}if(i.length>0)throw new Error(`[dndev] Next ignores code metadata files with the framework's file marker: ${i.join(", ")}. Serve each as a route handler (e.g. src/app/robots.txt/${F("route","ts")}) or a static file (icon.png, opengraph-image.png). The sitemap and llms.txt are generated by the framework.`);if(t&&l.length>0)throw new Error(`[dndev] Next files must carry the .${ie}. marker (src/pages is never a Next route). Rename: `+l.map(({file:c,name:p,extension:u})=>`${r(c)} \u2192 ${F(p,u)}`).join(", ")+". Running the app once in development renames them.");for(let{file:c,name:p,extension:u}of l){let g=Je(or(c),F(p,u));if(o.pathExists(g))throw new Error(`[dndev] Both ${r(c)} and ${r(g)} exist. Next only reads *.${ie}.* files: merge ${Ct(c)} into ${Ct(g)} and delete it.`);nr(c,g),n.push(r(c))}return n.length>0&&e.warn(`Next files renamed to *.${ie}.* (src/pages is never a Next route): ${n.join(", ")}. Commit the renames.`),a.length>0&&e.debug(`Removed generated Next files without marker: ${a.join(", ")}`),{renamed:n,removed:a}}function se(o){return o&&typeof o=="object"&&!Array.isArray(o)}var Ot={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function It({originalWebpack:o,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],languages:n=[],logger:a,debug:l}){return(i,c)=>{let{dev:p,isServer:u,webpack:g}=c;p&&!u&&(i.infrastructureLogging={level:"error"},i.stats={...i.stats,logging:"error",loggingTrace:!1},i.ignoreWarnings=[...i.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let d=i.module?.rules?.find(h=>h.test?.test?.(".svg"));d&&(d.exclude=/\.svg$/i),i.module=i.module||{},i.module.rules=i.module.rules||[],i.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),i.module.rules.push({test:/\.md$/,type:"asset/source"}),i.resolve=i.resolve||{},i.resolve.alias=i.resolve.alias||{};try{let h=R.getInstance(),w=h.resolveAppPath(T.next.blogContent);i.resolve.alias[Ge.blog]=Tt.existsSync(w)?w:h.getEmptyCjsModulePath()}catch(h){a.debug(`Blog content alias fallback to empty stub: ${h?.message}`)}i.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...Ot},g?.IgnorePlugin&&i.plugins.push(new g.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=R.getInstance();i.plugins.push(Et({pathResolver:h,debug:l,languages:n}))}catch(h){a.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(!u)try{i.plugins.push(_t({logger:a,debug:l}))}catch(h){a.debug(`Lower-destructuring webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(a.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),a.info(`\u2705 Including features: ${t.join(", ")}`),i.externals=i.externals||[],Array.isArray(i.externals))i.externals.push(...e);else{let h=i.externals;i.externals=(w,m,b)=>e.includes(m)?b(null,"commonjs "+m):typeof h=="function"?h(w,m,b):b()}if(s.length>0&&g?.NormalModuleReplacementPlugin){let w=R.getInstance().getEmptyCjsModulePath(),m=s.map(f=>f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),b=new RegExp(`^(${m.join("|")})(\\/|$)`);i.plugins.push(new g.NormalModuleReplacementPlugin(b,w)),l&&a.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&g?.NormalModuleReplacementPlugin){let w=R.getInstance().getEmptyFlagModulePath(),m=new Set(r.map(b=>b.toUpperCase()));i.plugins.push(new g.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,b=>{let f=b.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);f&&f[1].toUpperCase()!=="BASE"&&!m.has(f[1].toUpperCase())&&(b.request=w)})),l&&a.debug(`Flag filter: allowing ${m.size} flags, aliasing rest to empty component`)}return o?o(i,c):i}}function Lt({originalRewrites:o,handlers:e,logger:t}){return async function(){try{let s=o?await o():[],n=e.filter(l=>l?.getAPIRewrites).map(l=>l.getAPIRewrites()).reduce((l,i)=>(i?.beforeFiles&&l.beforeFiles.push(...i.beforeFiles),i?.afterFiles&&l.afterFiles.push(...i.afterFiles),i?.fallback&&l.fallback.push(...i.fallback),l),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...n.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...n.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...n.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function Ut({originalRedirects:o,seoRedirects:e,logger:t}){return async function(){try{let s=o?await o():[],r=(e||[]).map(({from:i,to:c,permanent:p})=>({source:i,destination:c,permanent:p!==!1})),n=[],a=new Set;for(let i of r){let c=i.source.replace(/\/+$/,"")||"/",p=i.destination.replace(/\/+$/,"")||"/";if(c===p){t.warn(`Redirect loop detected: ${i.source} \u2192 ${i.destination} (skipped)`);continue}if(!i.source.startsWith("/")){t.warn(`Redirect source must start with /: "${i.source}" (skipped)`);continue}if(a.has(c)){t.warn(`Duplicate redirect source: "${i.source}" (skipped)`);continue}a.add(c),n.push(i)}let l=[...Array.isArray(s)?s:[],...n];return l.length===0?[]:(t.info(` \u{1F4CE} ${l.length} redirect${l.length>1?"s":""} configured`),l)}catch(s){return t.error(`Failed to merge redirects: ${s.message}`),[]}}}function Mt({routeResult:o,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:n,serverShimResult:a,restNextConfig:l,discoveredPackages:i,reactCompiler:c=!1,routingMode:p,webpackConfig:u,rewritesConfig:g,redirectsConfig:d,missingOptionalDeps:h,flagCodes:w=[],pathResolver:m,env:b,logger:f}){let y=l?.output==="export";if(p==="app"&&l?.pageExtensions)throw new Error("[dndev] pageExtensions is set by the framework (Next files carry the .next. marker so src/pages is never a route). Remove it from next.config.");let D=l?.distDir||".next";return{transpilePackages:[...i,...h||[]],...c?{reactCompiler:c}:{},...se(l)?l:(f.warn("restNextConfig is not a plain object:",l),{}),...p==="app"&&{pageExtensions:Dt},...p==="app"&&{experimental:{...l?.experimental,globalNotFound:!0}},serverExternalPackages:(l?.serverExternalPackages||l?.serverComponentsExternalPackages||[]).filter(_=>!_.startsWith("@donotdev/")&&!h?.includes(_)),turbopack:{...l?.turbopack||{},root:l?.turbopack?.root||m.getRepoRoot(),resolveAlias:{...l?.turbopack?.resolveAlias||{},...Ot,[Ge.blog]:(()=>{try{let _=m.resolveAppPath(T.next.blogContent);if(Tt.existsSync(_))return"./"+T.next.blogContent}catch{}return"@donotdev/core/empty"})(),...h?.length>0?Object.fromEntries(h.flatMap(_=>[[_,"@donotdev/core/empty"],[`${_}/*`,"@donotdev/core/empty"]])):{}}},distDir:D,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...se(o)?o:(f.error(`Route handler config invalid (got ${typeof o}):`,o),{}),...se(e)?e:(f.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...se(t)?t:(f.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...se(s)?s:(f.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...se(r)?r:(f.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...se(n)?n:(f.error(`PWA handler config invalid (got ${typeof n}):`,n),{}),...se(a)?a:(f.warn("serverShimConfig returned non-object:",a),{}),webpack:u,...y?{}:{rewrites:g,...d?{redirects:d}:{}},env:b,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var De="fonts",Xe="dndev-fonts.css",hr=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,Gt=/url\(\.\/files\/([^)]+)\)/g;function dr(o){let e=new Set(["latin"]);for(let t of o){let s=ke[t];if(s)for(let r of s)e.add(r)}return e}function fr(o,e){let t=o.resolvePath("src/dndev.css",e),s=o.readSync(t,{format:"text"});if(!s)return[];let r=[],n;for(;(n=hr.exec(s))!==null;)r.push([n[1],n[2]]);return r}function mr(o,e,t,s,r){let n=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
6
+ `],a=new Set,l=r&&r.size>0;for(let[i,c]of e){let p=o.resolveFrameworkPackage(`@fontsource/${i}`);if(!p){s.debug(`@fontsource/${i} not found`);continue}let u=!!ge[i];if(l&&u)for(let g of r){let d=o.resolvePath(`${g}-${c}.css`,p),h=o.readSync(d,{format:"text"});if(!h)continue;let w=jt(He(h),o,p,t,a,s,!0);n.push(w)}else{let g=o.resolvePath(`${c}.css`,p),d=o.readSync(g,{format:"text"});if(!d){s.debug(`Missing: @fontsource/${i}/${c}.css`);continue}let h=jt(d,o,p,t,a,s,!1);n.push(h)}}return{cssChunks:n,copiedFiles:a}}function jt(o,e,t,s,r,n,a){return o.replace(Gt,(l,i)=>{if(a&&i.endsWith(".woff"))return"url(data:,)";let c=e.resolvePath(`files/${i}`,t);if(!e.pathExists(c))return n.warn(`Font file missing: ${c} \u2014 dropping from CSS`),"url(data:,)";if(!r.has(i)){let u=e.resolvePath(i,s);e.copySync(c,u,{overwrite:!0}),r.add(i)}return`url(/${De}/${i})`})}var vr=/@font-face\s*\{[^}]*\}/g;function yr(o,e,t,s,r){let n=o.resolvePath("dist/dndev.css",e),a=o.readSync(n,{format:"text"});if(!a)return s.debug("dist/dndev.css not found in @donotdev/ui"),{cssChunks:[],copiedFiles:new Set};let l=a.match(vr);if(!l||l.length===0)return s.debug("No @font-face blocks found in dist/dndev.css"),{cssChunks:[],copiedFiles:new Set};let i=r&&r.size>0,c=new Set(Object.keys(ge));i&&(l=l.filter(h=>{if(!Array.from(c).some(m=>h.includes(`${m}-`)))return!0;for(let m of r)if(h.includes(`-${m}-`))return!0;return!1}));let p=o.resolvePath("dist/files",e),u=new Set;return{cssChunks:[`/* Auto-generated by @donotdev/core \u2014 do not edit */
7
+ `,...l.map(h=>{let w=i&&Array.from(c).some(b=>h.includes(`${b}-`));return(w?He(h):h).replace(Gt,(b,f)=>{if(w&&f.endsWith(".woff"))return"url(data:,)";let y=o.resolvePath(f,p);if(!o.pathExists(y))return s.warn(`Font file missing: ${y} \u2014 dropping from CSS`),"url(data:,)";if(!u.has(f)){let D=o.resolvePath(f,t);o.copySync(y,D,{overwrite:!0}),u.add(f)}return`url(/${De}/${f})`})})],copiedFiles:u}}function zt({debug:o=!1,force:e=!1,languages:t}={}){let s=M("font-copy",o,!1),r=R.getInstance(),n=r.resolveAppPath(`public/${Xe}`);if(!e&&r.pathExists(n)){s.debug("dndev-fonts.css already exists, skipping font copy");return}let a=r.resolveFrameworkPackage("@donotdev/ui");if(!a){s.debug("@donotdev/ui not found, skipping font copy");return}let l=r.resolveAppPath(`public/${De}`);r.ensureDirSync(l);let i=t?.length?dr(t):null;i&&s.debug(`Font copy: locale-aware filtering \u2014 locales=[${t.join(",")}] subsets=[${[...i].join(",")}]`);let c=fr(r,a),p,u;if(c.length>0?(s.debug(`Monorepo mode: ${c.length} @fontsource imports found`),{cssChunks:p,copiedFiles:u}=mr(r,c,l,s,i)):(s.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:p,copiedFiles:u}=yr(r,a,l,s,i)),u.size===0){s.debug("No font files found to copy");return}r.writeSync(n,p.join(`
8
+ `)),s.debug(`Font copy: wrote ${Xe} (${u.size} font files copied)`)}function Bt(){let o=R.getInstance(),e=o.resolveAppPath(`public/${Xe}`),t=o.resolveAppPath(`public/${De}`);if(o.pathExists(e))try{o.removeSync(e)}catch{}if(o.pathExists(t))try{o.removeSync(t)}catch{}}var br=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json","public/dndev-fonts.css","public/robots.txt","public/sitemap.xml","public/rss.xml","public/llms.txt","public/llms-full.txt"],wr="dndev-config-",Wt=".dndev-build";function Ke(o){if(!o)return!1;let e=R.getInstance(),t=e.resolveAppPath(Wt),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function Sr(o){if(!o)return;let e=R.getInstance(),t=e.resolveAppPath(Wt),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s,{overwrite:!0})}catch{}}function $r(o,e,t){if(!o)return;let s=R.getInstance(),r=(a,l)=>{let i=s.normalizePath(a);if(!(t.has(i)||!s.pathExists(i)))try{s.removeSync(a),e.debug(`Removed stale: ${l}`)}catch{}};for(let a of br)r(s.resolveAppPath(a),a);let n=s.resolveAppPath("src/config");for(let a of s.readdirSync(n))a.startsWith(wr)&&a.endsWith(".js")&&r(s.resolvePath(a,n),`src/config/${a}`)}async function Ht({routeHandler:o,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:n,blogContentHandler:a},l){let i=o?.pathResolver;if(!i)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let c=i.getAppRoot(),p=i.getRepoRoot();if(!c||c===p){l.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(w=>setTimeout(w,0));let h=i.getAppRoot();if(!h||h===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Ke(c)){l.debug("Discoveries already completed this build, skipping");return}Sr(c);let u=Date.now();i.startWriteRecording();let g;try{Bt();let h=await t.getDiscoveryData(),w={languages:h.supportedLanguages,defaultLanguage:h.fallbackLanguage};if(r.useLanguages(w),r.useTranslations(h.content),o)try{o.useLanguages(w),l.info("\u{1F50D} Starting route discovery...");let y=(await o.generateFiles())?.routes?.length||0;l.info(`\u2705 Routes generated: ${y} routes found`),y===0&&l.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(f){throw l.error(`\u274C Route generation failed: ${f.message}`),f.stack&&l.error(`Stack: ${f.stack}`),f}else l.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let m=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:n},{name:"BlogContent",handler:a}],b;for(let{name:f,handler:y}of m)try{let x=await y.generateFiles();f==="I18n"&&x?.supportedLanguages?.length&&(b=x.supportedLanguages)}catch(x){l.debug(`${f} generation failed: ${x.message}`)}try{Pr(i,l)}catch(f){l.debug(`Env config generation failed (non-critical): ${f.message}`)}try{zt({languages:b})}catch(f){l.debug(`Font copy failed (non-critical): ${f.message}`)}}finally{g=i.stopWriteRecording()}$r(c,l,g);let d=Date.now()-u;l.verbose?.(`\u2705 All discoveries completed in ${d}ms - Next.js can now compile`)}function Pr(o,e){let t={};for(let[a,l]of Object.entries(process.env))a.startsWith("NEXT_PUBLIC_")&&l!==void 0&&(t[a]=l);let s=`// Auto-generated DnDev env config by @donotdev/config
9
9
  // Generated at: ${new Date().toISOString()}
10
10
  // Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
11
11
 
@@ -22,12 +22,12 @@ if (typeof globalThis !== 'undefined') {
22
22
  timestamp: Date.now(),
23
23
  };
24
24
  }
25
- globalThis._DNDEV_CONFIG_.${U.env} = envConfig;
25
+ globalThis._DNDEV_CONFIG_.${X.env} = envConfig;
26
26
  }
27
27
 
28
28
  // Export for compatibility
29
29
  export default envConfig;
30
- `,r=a.resolveAppPath(D.next.configEnv);a.writeSync(r,s,{overwrite:!0});let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}async function Dt(a,e,t){if(t)return!1;try{let s=await a.getDiscoveryData();return s?.copiedAssets?.length>0&&e.info(`\u{1F4E6} Copied ${s.copiedAssets.length} assets from framework`),!0}catch(s){return e.debug(`Asset discovery failed (non-critical): ${s.message}`),!1}}var Ot={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 ve={...Ot,generateManifest:!0,reactCompiler:!1,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function Tt(a,e){let t={...a};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=Tt(a[s]||{},e[s]):t[s]=e[s]}),t}function It(a={}){return Tt(ve,a)}function Mt(a){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:n={},seo:l={},serverShim:i={},discovery:p={},generateManifest:c,debug:u,verbose:g,...f}=a,h=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:u,verbose:g,mode:h,isDev:h==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:n,seoOptions:l,serverShimOptions:i,discoveryOptions:p,nextConfigOptions:f}}var F=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=N(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=$.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...ve.discovery,...this.options};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}createNextConfig(){return(e={})=>(this.options.debug&&this.logger.debug(`${this.getHandlerName()} handler initialized`),{...e,webpack:(t,s)=>{let{dev:r,isServer:o,webpack:n}=s;return this.applyViteIgnorePlugin(t,n),this._generateFiles(),e.webpack?e.webpack(t,s):t},rewrites:async function(){try{let t=e.rewrites?await e.rewrites():[],s=this.getAPIRewrites();return this.mergeRewrites(t,s)}catch(t){return this.logger.error(`${this.getHandlerName()} handler failed to merge rewrites: ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`),[]}}.bind(this)})}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let t=this.getHandlerName().toLowerCase(),s=D.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!s)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let r=this.generateConfigContent(e);this.writeGeneratedFile(s,r,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),s=U[t]||t;return`// Auto-generated DnDev config by @donotdev/config
30
+ `,r=o.resolveAppPath(T.next.configEnv);o.writeSync(r,s,{overwrite:!0});let n=Object.keys(t).length;e.debug(`Generated env config: ${n} NEXT_PUBLIC_* vars`)}async function qt(o,e,t){if(t)return!1;try{let s=await o.getDiscoveryData();return s?.copiedAssets?.length>0&&e.info(`\u{1F4E6} Copied ${s.copiedAssets.length} assets from framework`),!0}catch(s){return e.debug(`Asset discovery failed (non-critical): ${s.message}`),!1}}var Vt={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 $e={...Vt,generateManifest:!0,reactCompiler:!1,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function Jt(o,e){let t={...o};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=Jt(o[s]||{},e[s]):t[s]=e[s]}),t}function Xt(o={}){return Jt($e,o)}function Kt(o){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:n={},pwa:a={},seo:l={},serverShim:i={},discovery:c={},generateManifest:p,debug:u,verbose:g,...d}=o,h=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:p,debug:u,verbose:g,mode:h,isDev:h==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:n,featureOptions:e,pwaOptions:a,seoOptions:l,serverShimOptions:i,discoveryOptions:c,nextConfigOptions:d}}var j=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=M(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=R.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...$e.discovery,...this.options};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}createNextConfig(){return(e={})=>(this.options.debug&&this.logger.debug(`${this.getHandlerName()} handler initialized`),{...e,webpack:(t,s)=>{let{dev:r,isServer:n,webpack:a}=s;return this.applyViteIgnorePlugin(t,a),this._generateFiles(),e.webpack?e.webpack(t,s):t},rewrites:async function(){try{let t=e.rewrites?await e.rewrites():[],s=this.getAPIRewrites();return this.mergeRewrites(t,s)}catch(t){return this.logger.error(`${this.getHandlerName()} handler failed to merge rewrites: ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`),[]}}.bind(this)})}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let t=this.getHandlerName().toLowerCase(),s=T.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!s)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let r=this.generateConfigContent(e);this.writeGeneratedFile(s,r,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),s=X[t]||t;return`// Auto-generated DnDev config by @donotdev/config
31
31
  // Generated at: ${new Date().toISOString()}
32
32
  // Populates _DNDEV_CONFIG_ with discovery results
33
33
 
@@ -49,7 +49,7 @@ if (typeof globalThis !== 'undefined') {
49
49
 
50
50
  // Export for compatibility
51
51
  export default ${t}Config;
52
- `}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t,{overwrite:!0}),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var ne={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},_e=class extends G{constructor(e,t={}){super(e,{assets:z.assets.fallback,assetPatterns:z.assets.patterns,frameworkPackage:Oe.package,assetsPath:Oe.assetsPath,modernFormats:z.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let n=[],l=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(l)&&this.options.generateAssets!==!1&&(n=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:i}=e,p=await this._processAssetFiles(i),c=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...c,logoSvgContent:u},copiedAssets:s,generatedAssets:n,pwaIcons:this._extractPWAIcons(p)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(o=>o.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",o=r.match(/(\d+)x(\d+)/),n=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:n,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let n=`/${e}.${o}`;if(s.includes(n))return n}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(de.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let o of this.options.assets)await this._ensureAsset(o,r,s)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${de.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let o=s.split("/").pop()||s.split("\\").pop(),n=this._analyzeAsset(o,r.size);n&&t.push(n)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(n=>this._matchesPattern(e,n))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let o=`/${e}.${r}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${de.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(de.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _renderOgImage(e,t){let{width:s,height:r}=await e(t).metadata(),o=Math.min(ne.logoWidth/s,ne.logoHeight/r),n=await e(t,{density:Math.ceil(72*o)}).resize(ne.logoWidth,ne.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:ne.width,height:ne.height,channels:4,background:ne.background}}).composite([{input:n}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],n=[],l=[];try{let i=await this.pathResolver.read(t,{format:"text"});if(!i)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){l.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,i),n.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),l.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),l.push(...r.map(c=>c.name));else{for(let u of r){let g=`${s}/${u.name}`;if(this.pathResolver.pathExists(g)){l.push(u.name);continue}try{let f=p.default(t).resize(u.size,u.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;u.format==="ico"?h=await f.toFormat("png").toBuffer():h=await f.toFormat(u.format).toBuffer(),await this.pathResolver.write(`public/${u.name}`,h),n.push(u.name)}catch(f){this.logger.debug(`Failed to generate ${u.name}: ${f.message}`),l.push(u.name)}}let c=oe.slice(1);if(this.pathResolver.pathExists(`${s}/${c}`))l.push(c);else try{let u=await this._renderOgImage(p.default,t);await this.pathResolver.write(`public/${c}`,u),n.push(c)}catch(u){this.logger.debug(`Failed to generate ${c}: ${u.message}`),l.push(c)}}return{generated:n,skipped:l,error:null}}catch(i){return this.logger.debug(`Asset generation failed: ${i.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:i.message}}}};var Ge={data:null},Ue=class extends F{constructor(e={}){super(_e,e)}getHandlerDefaults(){return{manifestPath:D.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
52
+ `}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t,{overwrite:!0}),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var ue={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Fe=class extends K{constructor(e,t={}){super(e,{assets:J.assets.fallback,assetPatterns:J.assets.patterns,frameworkPackage:ze.package,assetsPath:ze.assetsPath,modernFormats:J.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let a=[],l=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(l)&&this.options.generateAssets!==!1&&(a=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:i}=e,c=await this._processAssetFiles(i),p=this._buildAssetManifest(c),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:c,manifest:{...p,logoSvgContent:u},copiedAssets:s,generatedAssets:a,pwaIcons:this._extractPWAIcons(c)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(n=>n.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",n=r.match(/(\d+)x(\d+)/),a=n?{width:parseInt(n[1]),height:parseInt(n[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:a,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(n=>n.path),r=t||this.options.modernFormats;for(let n of r){let a=`/${e}.${n}`;if(s.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(we.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let n of this.options.assets)await this._ensureAsset(n,r,s)&&t.push(n);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${we.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let n=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(n)){if(await this.pathResolver.copy(n,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let n=s.split("/").pop()||s.split("\\").pop(),a=this._analyzeAsset(n,r.size);a&&t.push(a)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let n=`/${e}.${r}`;if(t.includes(n))return n}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${we.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(we.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let n=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,n)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _renderOgImage(e,t){let{width:s,height:r}=await e(t).metadata(),n=Math.min(ue.logoWidth/s,ue.logoHeight/r),a=await e(t,{density:Math.ceil(72*n)}).resize(ue.logoWidth,ue.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:ue.width,height:ue.height,channels:4,background:ue.background}}).composite([{input:a}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],n=[{name:"favicon.svg",format:"svg"}],a=[],l=[];try{let i=await this.pathResolver.read(t,{format:"text"});if(!i)return{generated:[],skipped:[...n,...r].map(p=>p.name),error:"Failed to read logo.svg"};for(let p of n){let u=`${s}/${p.name}`;if(this.pathResolver.pathExists(u)){l.push(p.name);continue}try{await this.pathResolver.write(`public/${p.name}`,i),a.push(p.name)}catch(g){this.logger.debug(`Failed to copy ${p.name}: ${g.message}`),l.push(p.name)}}let c=await import("sharp").catch(()=>null);if(!c)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),l.push(...r.map(p=>p.name));else{for(let u of r){let g=`${s}/${u.name}`;if(this.pathResolver.pathExists(g)){l.push(u.name);continue}try{let d=c.default(t).resize(u.size,u.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;u.format==="ico"?h=await d.toFormat("png").toBuffer():h=await d.toFormat(u.format).toBuffer(),await this.pathResolver.write(`public/${u.name}`,h),a.push(u.name)}catch(d){this.logger.debug(`Failed to generate ${u.name}: ${d.message}`),l.push(u.name)}}let p=pe.slice(1);if(this.pathResolver.pathExists(`${s}/${p}`))l.push(p);else try{let u=await this._renderOgImage(c.default,t);await this.pathResolver.write(`public/${p}`,u),a.push(p)}catch(u){this.logger.debug(`Failed to generate ${p}: ${u.message}`),l.push(p)}}return{generated:a,skipped:l,error:null}}catch(i){return this.logger.debug(`Asset generation failed: ${i.message}`),{generated:[],skipped:requiredAssets.map(c=>c.name),error:i.message}}}};var Ze={data:null},Ye=class extends j{constructor(e={}){super(Fe,e)}getHandlerDefaults(){return{manifestPath:T.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
53
53
  // Generated at: ${new Date().toISOString()}
54
54
  // Populates _DNDEV_CONFIG_ with discovery results
55
55
 
@@ -66,7 +66,7 @@ if (typeof globalThis !== 'undefined') {
66
66
  timestamp: Date.now(),
67
67
  };
68
68
  }
69
- globalThis._DNDEV_CONFIG_.${U.assets} = {
69
+ globalThis._DNDEV_CONFIG_.${X.assets} = {
70
70
  mapping: assetConfig.manifest,
71
71
  logoSvgContent: ${JSON.stringify(t)},
72
72
  manifest: {
@@ -78,14 +78,14 @@ if (typeof globalThis !== 'undefined') {
78
78
 
79
79
  // Export for compatibility
80
80
  export default assetConfig;
81
- `}logDiscoveryResults(e){let t=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(Ge.data={pwaIcons:e.pwaIcons}),e}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({path:t.path,type:t.type,format:t.format,size:t.size,optimized:t.optimized})),manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} assets, ${e.copiedAssets.length} copied from framework`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateAssetManifest(e),this.options.optimizeImages&&await this.generateImageOptimization(e),await this.generateAPIHandler(e)}async generateAssetManifest(e){let t=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",t,"asset manifest")}generateAssetManifestContent(e){let t=e.assets.map(o=>` {
82
- path: '${o.path}',
83
- type: '${o.type}',
84
- format: '${o.format}',
85
- size: ${o.size},
86
- optimized: ${o.optimized||!1}
81
+ `}logDiscoveryResults(e){let t=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(Ze.data={pwaIcons:e.pwaIcons}),e}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({path:t.path,type:t.type,format:t.format,size:t.size,optimized:t.optimized})),manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} assets, ${e.copiedAssets.length} copied from framework`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateAssetManifest(e),this.options.optimizeImages&&await this.generateImageOptimization(e),await this.generateAPIHandler(e)}async generateAssetManifest(e){let t=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",t,"asset manifest")}generateAssetManifestContent(e){let t=e.assets.map(n=>` {
82
+ path: '${n.path}',
83
+ type: '${n.type}',
84
+ format: '${n.format}',
85
+ size: ${n.size},
86
+ optimized: ${n.optimized||!1}
87
87
  }`).join(`,
88
- `),s=Object.entries(e.manifest).map(([o,n])=>` ${o}: ${JSON.stringify(n)}`).join(`,
88
+ `),s=Object.entries(e.manifest).map(([n,a])=>` ${n}: ${JSON.stringify(a)}`).join(`,
89
89
  `),r=e.manifest.logoSvgContent||null;return`// Auto-generated asset manifest by @donotdev/config
90
90
  // Generated at ${new Date().toISOString()}
91
91
  // Populates _DNDEV_CONFIG_ with discovery results
@@ -125,16 +125,16 @@ ${t}
125
125
  export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
126
126
 
127
127
  export default imageConfigs;
128
- `}};function Lt(a={}){return new Ue(a)}import Be from"node:fs";import Qs from"node:path";var We=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!Be.existsSync(e))return{blogDir:e,files:[]};let t;try{t=Be.readdirSync(e)}catch{return{blogDir:e,files:[]}}let s=t.filter(r=>r.endsWith(".md")&&!r.startsWith(".")).sort();return{blogDir:e,files:s}}},He=class extends F{constructor(e={}){super(We,e)}getHandlerDefaults(){return{outputPath:D.next.blogContent}}getHandlerName(){return"BlogContent"}createDiscovery(e){return new e(this.pathResolver)}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateSpecificFiles(e),this.logger.debug(`Generated BlogContent: ${this.getGenerationSummary(e)}`),e}catch(e){return this.logger.debug(`BlogContent generation failed (non-critical): ${e.message}`),{blogDir:"",files:[]}}}async getDiscoveryData(){return this.discovery.discoverBlogFiles()}logDiscoveryResults(e){this.logger.info(`\u{1F4DD} Blog: ${e.files.length} .md file(s) found`)}getGenerationSummary(e){return`${e.files.length} blog file(s)`}async generateSpecificFiles(e){let{blogDir:t,files:s}=e;if(s.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let r=this._buildGeneratedContent(t,s);this.writeGeneratedFile(this.options.outputPath,r,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
128
+ `}};function Yt(o={}){return new Ye(o)}import Qe from"node:fs";import Rr from"node:path";var et=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!Qe.existsSync(e))return{blogDir:e,files:[]};let t;try{t=Qe.readdirSync(e)}catch{return{blogDir:e,files:[]}}let s=t.filter(r=>r.endsWith(".md")&&!r.startsWith(".")).sort();return{blogDir:e,files:s}}},tt=class extends j{constructor(e={}){super(et,e)}getHandlerDefaults(){return{outputPath:T.next.blogContent}}getHandlerName(){return"BlogContent"}createDiscovery(e){return new e(this.pathResolver)}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateSpecificFiles(e),this.logger.debug(`Generated BlogContent: ${this.getGenerationSummary(e)}`),e}catch(e){return this.logger.debug(`BlogContent generation failed (non-critical): ${e.message}`),{blogDir:"",files:[]}}}async getDiscoveryData(){return this.discovery.discoverBlogFiles()}logDiscoveryResults(e){this.logger.info(`\u{1F4DD} Blog: ${e.files.length} .md file(s) found`)}getGenerationSummary(e){return`${e.files.length} blog file(s)`}async generateSpecificFiles(e){let{blogDir:t,files:s}=e;if(s.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let r=this._buildGeneratedContent(t,s);this.writeGeneratedFile(this.options.outputPath,r,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
129
129
  // Regenerated when src/content/blog/*.md files change
130
130
 
131
131
  const blogContent: Record<string, string> = {
132
- ${t.map(r=>{let o=Be.readFileSync(Qs.join(e,r),"utf8");return` './${r}': ${JSON.stringify(o)},`}).join(`
132
+ ${t.map(r=>{let n=Qe.readFileSync(Rr.join(e,r),"utf8");return` './${r}': ${JSON.stringify(n)},`}).join(`
133
133
  `)}
134
134
  };
135
135
 
136
136
  export default blogContent;
137
- `}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function jt(a={}){return new He(a)}var Ve=class extends F{constructor(e={}){super(pe,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...ve.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:o,content:n}=e;return`// Auto-generated DnDev config by @donotdev/config
137
+ `}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function Zt(o={}){return new tt(o)}var st=class extends j{constructor(e={}){super(fe,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...$e.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:n,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
138
138
  // Generated at: ${new Date().toISOString()}
139
139
  // Populates _DNDEV_CONFIG_ with discovery results
140
140
 
@@ -142,8 +142,8 @@ const i18nConfig = {
142
142
  mapping: ${JSON.stringify(t,null,2)},
143
143
  languages: ${JSON.stringify(s,null,2)},
144
144
  eager: ${JSON.stringify(r,null,2)},
145
- fallback: '${o}',
146
- content: ${JSON.stringify(n||{},null,2)},
145
+ fallback: '${n}',
146
+ content: ${JSON.stringify(a||{},null,2)},
147
147
  storage: {
148
148
  type: 'localStorage',
149
149
  prefix: 'dndev_i18n_',
@@ -176,12 +176,12 @@ if (typeof globalThis !== 'undefined') {
176
176
  timestamp: Date.now(),
177
177
  };
178
178
  }
179
- globalThis._DNDEV_CONFIG_.${U.i18n} = i18nConfig;
179
+ globalThis._DNDEV_CONFIG_.${X.i18n} = i18nConfig;
180
180
  }
181
181
 
182
182
  // Export for compatibility
183
183
  export default i18nConfig;
184
- `}};function zt(a={}){return new Ve(a)}var Ae=class extends G{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:s}=e,r=[...t,...s];this.logger.debug(`Processing ${r.length} PWA files`);let o=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),o=[...this.options.assetData.pwaIcons]);let n=await this._analyzePWAFiles(r),l=n.filter(g=>g.type==="manifest"||g.type==="service-worker");o.push(...l);let i=n.filter(g=>g.type==="icon"),p=new Set(o.filter(g=>g.type==="icon").map(g=>g.path)),c=i.filter(g=>!p.has(g.path));o.push(...c);let u=this._generatePWAManifest(o);return{assets:o,manifest:u,totalFiles:r.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let s of e){let r=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,o=await this._analyzePWAAsset(r);o&&t.push(o)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let s=e.relativePath,r=e.fileName;return r.includes("manifest.json")?this._parseManifestFile(t,s):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,s):this._isPWAIcon(r)?this._parseIconFile(e,s):null}_parseManifestFile(e,t){try{let s=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:s,size:typeof e=="string"?e.length:JSON.stringify(s).length}}catch(s){return this.logger.debug(`Failed to parse manifest: ${s.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let s=e.fileName,r=this._extractIconSize(s);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(s)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(s=>e.includes(s))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(o=>o.type==="icon"),r=e.find(o=>o.type==="manifest")?.content||this._getDefaultManifest();return t.length>0&&(r.icons=t.map(o=>({src:`/${o.path}`,sizes:`${o.size.width}x${o.size.height}`,type:`image/${o.format}`,purpose:o.purpose}))),r}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let t=e.manifest||this._getDefaultManifest();return JSON.stringify(t,null,2)}generateServiceWorkerContent(e,t={}){let s=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,o=t.precacheManifest||[],n=JSON.stringify(o,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
184
+ `}};function Qt(o={}){return new st(o)}var Te=class extends K{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:s}=e,r=[...t,...s];this.logger.debug(`Processing ${r.length} PWA files`);let n=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),n=[...this.options.assetData.pwaIcons]);let a=await this._analyzePWAFiles(r),l=a.filter(g=>g.type==="manifest"||g.type==="service-worker");n.push(...l);let i=a.filter(g=>g.type==="icon"),c=new Set(n.filter(g=>g.type==="icon").map(g=>g.path)),p=i.filter(g=>!c.has(g.path));n.push(...p);let u=this._generatePWAManifest(n);return{assets:n,manifest:u,totalFiles:r.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let s of e){let r=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,n=await this._analyzePWAAsset(r);n&&t.push(n)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let s=e.relativePath,r=e.fileName;return r==="manifest.json"?this._parseManifestFile(t,s):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,s):this._isPWAIcon(r)?this._parseIconFile(e,s):null}_parseManifestFile(e,t){try{let s=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:s,size:typeof e=="string"?e.length:JSON.stringify(s).length}}catch(s){return this.logger.debug(`Failed to parse manifest: ${s.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let s=e.fileName,r=this._extractIconSize(s);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(s)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(s=>e.includes(s))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(r=>r.type==="icon"),s=this._getDefaultManifest();return t.length>0&&(s.icons=t.map(r=>this.toManifestIcon(r))),s}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},s=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:s==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[s]||`image/${s}`,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 s=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,n=t.precacheManifest||[],a=JSON.stringify(n,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
185
185
  // Generated at ${new Date().toISOString()}
186
186
 
187
187
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
@@ -197,7 +197,7 @@ ${r?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
197
197
  cleanupOutdatedPrecaches();
198
198
 
199
199
  // Precache static assets
200
- const precacheManifest = ${n.length>2?n:"self.__WB_MANIFEST || []"};
200
+ const precacheManifest = ${a.length>2?a:"self.__WB_MANIFEST || []"};
201
201
  precacheAndRoute(precacheManifest);
202
202
 
203
203
  // Runtime caching strategies
@@ -215,31 +215,31 @@ self.addEventListener('message', (event) => {
215
215
  self.addEventListener('activate', (event) => {
216
216
  event.waitUntil(self.clients.claim());
217
217
  });
218
- `}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:o,handler:n,options:l={}}=s,i=n==="CacheFirst"?"CacheFirst":n==="NetworkFirst"?"NetworkFirst":n==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",p;typeof o=="function"?p="({ request }) => request.destination === 'document'":o instanceof RegExp?p=o.toString():p=JSON.stringify(o);let c=[];l.expiration&&c.push(`new ExpirationPlugin({
218
+ `}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:n,handler:a,options:l={}}=s,i=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",c;typeof n=="function"?c="({ request }) => request.destination === 'document'":n instanceof RegExp?c=n.toString():c=JSON.stringify(n);let p=[];l.expiration&&p.push(`new ExpirationPlugin({
219
219
  maxEntries: ${l.expiration.maxEntries||50},
220
220
  maxAgeSeconds: ${l.expiration.maxAgeSeconds||3600*24},
221
- })`),l.cacheableResponse&&c.push(`new CacheableResponsePlugin({
221
+ })`),l.cacheableResponse&&p.push(`new CacheableResponsePlugin({
222
222
  statuses: ${JSON.stringify(l.cacheableResponse.statuses||[0,200])},
223
- })`),l.backgroundSync&&c.push(`new BackgroundSyncPlugin('${l.backgroundSync.queueName||"background-sync-queue"}', {
223
+ })`),l.backgroundSync&&p.push(`new BackgroundSyncPlugin('${l.backgroundSync.queueName||"background-sync-queue"}', {
224
224
  maxRetentionTime: ${l.backgroundSync.maxRetentionTime||1440},
225
225
  })`);let u="";return l.cacheName&&(u+=`
226
- cacheName: '${l.cacheName}',`),c.length>0&&(u+=`
226
+ cacheName: '${l.cacheName}',`),p.length>0&&(u+=`
227
227
  plugins: [
228
- ${c.join(`,
228
+ ${p.join(`,
229
229
  `)}
230
230
  ],`),l.networkTimeoutSeconds&&(u+=`
231
231
  networkTimeoutSeconds: ${l.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${l.cacheName||"cache-"+r}
232
232
  registerRoute(
233
- ${p},
233
+ ${c},
234
234
  new ${i}({${u}
235
235
  })
236
236
  );`}).join(`
237
237
 
238
- `)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",s=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,o;return typeof r=="function"||r instanceof RegExp?o=r.toString():o=JSON.stringify(r),`
238
+ `)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",s=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,n;return typeof r=="function"||r instanceof RegExp?n=r.toString():n=JSON.stringify(r),`
239
239
  // Background sync for offline actions
240
240
  const { NetworkOnly } = workbox.strategies;
241
241
  registerRoute(
242
- ${o},
242
+ ${n},
243
243
  new NetworkOnly({
244
244
  plugins: [
245
245
  new BackgroundSyncPlugin('${t}', {
@@ -249,7 +249,7 @@ registerRoute(
249
249
  }),
250
250
  'POST'
251
251
  );
252
- `}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let n=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let l of n){let i=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),l.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of i){let c=this.pathResolver.getRelativePath(p);if(c.startsWith(`${e}/static/`)){let u=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:u,revision:null})}}}}catch(n){this.logger?.warn(`Failed to discover Next.js build assets: ${n.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Je=class extends F{constructor(e={}){super(Ae,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Ge.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.enabled){this.logger.debug("PWA disabled, skipping generation");return}this.options.generateManifest&&await this.generatePWAManifest(e),this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,t,"PWA manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:o,webpack:n}=s;return this.applyViteIgnorePlugin(t,n),!r&&!o&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function Ut(a={}){return new Je(a)}import{createRequire as sr}from"node:module";function Gt(a,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=a.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(o)].forEach(i=>{let p=i[1],c=i[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var be=null,Bt=null;function er(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var ue=class extends G{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(be&&Bt===s)return this.logger.debug("Using cached route discovery results"),this.routes=be.routes,this.errors=be.errors,this.source=be.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let o=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(o)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),be={routes:this.routes,errors:this.errors,source:this.source},Bt=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),o=await this._scanAdditionalPatterns(t),n=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),l=[...r,...n];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=l.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let i=new Map;for(let p of this.routes){let c=p.path;if(i.has(c)){let u=i.get(c);throw new Error(`Route conflict: Multiple routes found for path '${c}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}i.set(c,p)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,o="/src/"+r.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let n=this._extractMetaExport(s,e.absolutePath),l=er(o),p=l===he.HOMEPAGE_COMPONENT?he.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:g,...f}=n||{};return{path:p,component:l,importPath:o,auth:n?.auth||!1,meta:{...c,...f,entity:c.entity,action:c.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=Gt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let n=o.map(l=>`:${l}`).join("/");return`${r}/${n}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z]+)([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("/"),n=null,l=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?l="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?l="form":(s.includes("Detail")||s.includes("View"))&&(l="detail")),{title:r,entity:n,action:l,file:e}}};function tr(a,e,t="configuration-error",s={}){let r=`[${a}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=a,o.context=s,o}function Wt(a,e,t,s={}){return tr(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function qe(a,e,t,s){try{if(t?.content?.[a]?.[e])return t.content[a][e];let r=t?.mapping?.[a]?.[e];if(!r)return null;let o=s.resolveAppPath(r),n=s.readSync(o,{format:"text"});return n?JSON.parse(n):null}catch{return null}}function Ee(a,e){if(!a||!e)return;let t=e.split("."),s=a;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function Ye(a){return a?.languages||a?.supportedLanguages||["en"]}function Ke(a){return a?.fallback||a?.fallbackLanguage||"en"}var Xe=class extends F{constructor(e={}){super(ue,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:D.next.middleware,manifestPath:D.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(o=>o.auth&&o.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
252
+ `}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),n=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let l of a){let i=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),l.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let c of i){let p=this.pathResolver.getRelativePath(c);if(p.startsWith(`${e}/static/`)){let u=`/_next/${p.replace(`${e}/static/`,"")}`;n.push({url:u,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return n}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var rt=class extends j{constructor(e={}){super(Te,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/pwa-manifest.json",webManifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Ze.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(this.options.generateManifest&&await this.generatePWAManifest(e),!this.options.enabled){this.logger.debug("PWA disabled, skipping service worker generation");return}this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.webManifestPath,t,"web app manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let n=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(n,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:n,webpack:a}=s;return this.applyViteIgnorePlugin(t,a),!r&&!n&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function es(o={}){return new rt(o)}import{createRequire as _r}from"node:module";function ts(o,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=o.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,c)=>`icon: '${c}'`);let n=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...o.matchAll(n)].forEach(i=>{let c=i[1],p=i[2];r=r.replace(new RegExp(`\\b${c}\\b`,"g"),`'${p}'`)}),Function(`return ${r}`)()}catch{return null}}var Pe=null,ss=null;function xr(o){let t=(o.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Er(o){let e=o.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw new Error(`PageMeta signedInRedirect in ${o.file} must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`);if(e.split(/[?#]/)[0]===o.path)throw new Error(`PageMeta signedInRedirect in ${o.file} points at the page itself (${e}): signed-in visitors would loop. Use another page.`)}}var me=class extends K{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(Pe&&ss===s)return this.logger.debug("Using cached route discovery results"),this.routes=Pe.routes,this.errors=Pe.errors,this.source=Pe.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let n=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(n)}`)}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/"),Pe={routes:this.routes,errors:this.errors,source:this.source},ss=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,c=>this._analyzePageFile(c,t)),n=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(n,c=>this._analyzePageFile(c,t)),l=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${n.length} additional files`),this.routes=l.filter(c=>c.path==="home"||c.path==="/home"?(this.logger.debug(`Filtered reserved route: ${c.path} - Use root "/" instead (${c.file})`),!1):!0);let i=new Map;for(let c of this.routes){let p=c.path;if(i.has(p)){let u=i.get(p);throw new Error(`Route conflict: Multiple routes found for path '${p}'. Routes: ${u.file} and ${c.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}i.set(p,c),Er(c)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+n.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,n="/src/"+r.replace(/\\/g,"/");n=n.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(s,e.absolutePath),l=xr(n),c=l===be.HOMEPAGE_COMPONENT?be.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),p=this._extractPageMeta(r,s),{entity:u,action:g,...d}=a||{};return{path:c,component:l,importPath:n,auth:a?.auth||!1,meta:{...p,...d,entity:p.entity,action:p.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=ts(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),n=e.route.params;if(Array.isArray(n)&&n.length>0){let a=n.map(l=>`:${l}`).join("/");return`${r}/${a}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z]+)([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 n=e.split("/"),a=null,l=null;return n.length>1&&(a=n[n.length-2],s.includes("List")?l="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?l="form":(s.includes("Detail")||s.includes("View"))&&(l="detail")),{title:r,entity:a,action:l,file:e}}};function Ar(o,e,t="configuration-error",s={}){let r=`[${o}] ${e}`,n=new Error(r);return n.code=t,n.pluginName=o,n.context=s,n}function rs(o,e,t,s={}){return Ar(o,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function nt(o,e,t,s){try{if(t?.content?.[o]?.[e])return t.content[o][e];let r=t?.mapping?.[o]?.[e];if(!r)return null;let n=s.resolveAppPath(r),a=s.readSync(n,{format:"text"});return a?JSON.parse(a):null}catch{return null}}function Oe(o,e){if(!o||!e)return;let t=e.split("."),s=o;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function ot(o){return o?.languages||o?.supportedLanguages||["en"]}function at(o){return o?.fallback||o?.fallbackLanguage||"en"}var it=class extends j{constructor(e={}){super(me,e),this.rendersSessionTree=!1,this.appRouteSegments=[]}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,proxyPath:T.next.proxy,manifestPath:T.next.routeManifest,languages:[],defaultLanguage:null}}useLanguages({languages:e,defaultLanguage:t}){if(e.length>1&&!e.includes(t))throw new Error(`i18n fallbackLanguage "${t}" has no translations among [${e.join(", ")}]: it is the language served at the root URL. Add its locale files or set i18n.fallbackLanguage to one of them.`);this.options.languages=e,this.options.defaultLanguage=t}isMultilingual(){return this.options.languages.length>1}rootDir(){return this.isMultilingual()?"/[lang]":""}treeDir(e="site"){return`${this.rootDir()}/${e==="session"?B.sessionSegment:B.siteGroup}`}appDirFor(e,t="site"){return`${this.treeDir(t)}${this.convertRouteToAppPath(e)}`}appImport(e,t){let s=e.split("/").filter(Boolean).length;return s===0?`./${t}`:`${"../".repeat(s)}${t}`}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(n=>n.auth&&n.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
253
253
  // Generated at: ${new Date().toISOString()}
254
254
  // Populates _DNDEV_CONFIG_.routes with discovery results
255
255
 
@@ -268,7 +268,7 @@ if (typeof globalThis !== 'undefined') {
268
268
  timestamp: Date.now(),
269
269
  };
270
270
  }
271
- globalThis._DNDEV_CONFIG_.${U.routes} = {
271
+ globalThis._DNDEV_CONFIG_.${X.routes} = {
272
272
  mapping: routeMapping,
273
273
  manifest: routeManifest,
274
274
  };
@@ -278,35 +278,185 @@ if (typeof globalThis !== 'undefined') {
278
278
  export const routes = routeMapping;
279
279
  export const manifest = routeManifest;
280
280
  export default { routes: routeMapping, manifest: routeManifest };
281
- `}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=Ye(t),r=Ke(t),o=process.env.NEXT_PUBLIC_SITE_NAME||"";if(!o)try{let i=this.pathResolver.resolveAppPath("public/seo-manifest.json");this.pathResolver.pathExists(i)&&(o=this.pathResolver.readSync(i,{format:"json"})?.siteName||"")}catch{}let n={};for(let i of e.routes){let p=i.metaExport?.namespace,c=i.metaExport?.seo||{},u={};for(let g of s){let f=p&&t&&qe(p,g,t,this.pathResolver)||qe(p,r,t,this.pathResolver),h=Ee(f,"meta")||{},b=Ee(f,"title"),d=Ee(f,"description"),m;h.fullTitle?m=h.fullTitle:c.fullTitle?m=c.fullTitle:b?m=o?`${b} | ${o}`:b:c.title?m=o?`${c.title} | ${o}`:c.title:c.title===null?m=o:m=o||"";let S;c.description===null?S=void 0:c.description?S=c.description:d&&(S=d);let O=c.image||h.image||oe,T=c.type||h.type||"website",M=c.keywords||h.keywords,A=c.noindex||!1;u[g]={title:m,...S&&{description:S},image:O,type:T,...M&&{keywords:M},...A&&{noindex:A}}}n[i.path]={locales:u,defaultLocale:r}}let l=JSON.stringify(n,null,2);this.writeGeneratedFile("public/metadata-manifest.json",l,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(n).length} routes`)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles();let t=0;for(let s of e.routes)await this.generateSingleAppPage(s)&&t++;this.logger.debug(`Successfully generated ${t}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=["src/app/**/page.tsx","src/app/**/*PageClient.tsx","src/app/[...slug]/page.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let o of s)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),r++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(n){this.logger.debug(`Could not clean file ${o}: ${n.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e){try{let t=this.convertRouteToAppPath(e.path),s=`src/app${t}/page.tsx`,r=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(r)&&!await this.hasGenerationMarker(r))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let o={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},n=this.generatePageFileContent(o);this.writeGeneratedFile(s,n,`app page: ${t}`);let l=this.extractComponentName(o.filePath),i=this.calculateRelativeImportPath(o.relativePath,o.path);return o.metaExport?.namespace==="blog"&&this.hasDynamicSegment(o.path)?this.writeGeneratedFile(`src/app${t}/BlogPostClient.tsx`,this.generateBlogPostClientContent(l,i),`app blog client: ${t}`):this.isClientComponent(o.filePath)&&this.writeGeneratedFile(`src/app${t}/${l}Client.tsx`,this.generateMountedClientContent(l,i),`app client wrapper: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===he.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(s=>s.startsWith(":")?`[${s.slice(1)}]`:s==="*"?"[...slug]":s).join("/")}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=sr(t),r=s.resolve(e);delete s.cache[r];let o=s(r);return o.default||o.i18nConfig||o}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e){let t=this.extractComponentName(e.filePath),s=e.relativePath||e.file,r=this.calculateRelativeImportPath(s,e.path);return e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path)?this.generateBlogPostRSCContent(e,t,r):this.isClientComponent(e.filePath)?`// Generated by @donotdev/config - DO NOT EDIT
281
+ `}async generateSpecificFiles(e){await this.assertAppDocument(),this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=ot(t),r=at(t),n=process.env.NEXT_PUBLIC_SITE_NAME||"";if(!n)try{let i=this.pathResolver.resolveAppPath("public/seo-manifest.json");this.pathResolver.pathExists(i)&&(n=this.pathResolver.readSync(i,{format:"json"})?.siteName||"")}catch{}let a={};for(let i of e.routes){let c=i.metaExport?.namespace,p=i.metaExport?.seo||{},u={};for(let g of s){let d=c&&t&&nt(c,g,t,this.pathResolver)||nt(c,r,t,this.pathResolver),h=Oe(d,"meta")||{},w=Oe(d,"title"),m=Oe(d,"description"),b;h.fullTitle?b=h.fullTitle:p.fullTitle?b=p.fullTitle:w?b=n?`${w} | ${n}`:w:p.title?b=n?`${p.title} | ${n}`:p.title:p.title===null?b=n:b=n||"";let f;p.description===null?f=void 0:p.description?f=p.description:m&&(f=m);let y=p.image||h.image||pe,x=p.type||h.type||"website",D=p.keywords||h.keywords,O=p.noindex||!1;u[g]={title:b,...f&&{description:f},image:y,type:x,...D&&{keywords:D},...O&&{noindex:O}}}a[i.path]={locales:u,defaultLocale:r}}let l=JSON.stringify(a,null,2);this.writeGeneratedFile("public/metadata-manifest.json",l,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(a).length} routes`)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles(),this.generateRootLayout(),this.generateNotFoundPages();let t=this.rendersSessionTree?["site","session"]:["site"];for(let r of t)await this.generateTreeLayout(r);let s=0;for(let r of e.routes){let n=await this.generateSingleAppPage(r);n&&s++,n&&this.rendersSessionTree&&this.generateSessionPage(r)}this.logger.debug(`Successfully generated ${s}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}requestDocumentParts(e){return[[/<ClientLayout\b/,"renders <ClientLayout>"],[/from\s+['"]next\/headers['"]/,"imports next/headers"],[/export\s+const\s+dynamic\b/,"exports `dynamic`"]].filter(([t])=>t.test(e)).map(([,t])=>t)}async assertAppDocument(){let e=T.next.appDocument,t=`${e} exports \`metadata\` (site-level: metadataBase) and \`AppDocument({ lang, children })\`, which renders <html lang={lang}>, the <head> links (favicon, <FontPreloadLinks />), imports the global CSS and puts {children} in <body> (see the @donotdev/cli app-next template)`,s=[];for(let a of this.frameworkRootFiles()){let l=this.pathResolver.resolveAppPath(a);this.pathResolver.pathExists(l)&&!await this.hasGenerationMarker(l)&&s.push(a)}if(s.length>0)throw new Error(`[dndev] ${s.join(", ")}: the framework generates the root layout and the 404 pages, so every page's HTML carries its language (<html lang>). Move the HTML shell into ${e}: ${t}. Then delete ${s.join(", ")}.`);let r=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(r))throw new Error(`[dndev] ${e} is missing: ${t}.`);let n=this.requestDocumentParts(await this.pathResolver.read(r,{format:"text"}));if(n.length!==0)throw new Error(`[dndev] ${e} ${n.join(", ")}. It must be the HTML shell: render {children} in <body>, drop the ClientLayout / headers() wrapper and \`export const dynamic\`. The generated layouts render ClientLayout: cached pages for guests, per-request pages for visitors with an auth cookie.`)}frameworkRootFiles(){let e=F("layout","tsx"),t=F("not-found","tsx");return[T.next.appLayout,`src/app/[lang]/${e}`,`src/app/${t}`,`src/app/[lang]/${t}`,`src/app/${F("global-not-found","tsx")}`]}async generateTreeLayout(e){let t=`src/app${this.treeDir(e)}/${F("layout","tsx")}`,s=this.pathResolver.resolveAppPath(t);if(this.pathResolver.pathExists(s)&&!await this.hasGenerationMarker(s)){this.logger.debug(`Skipping ${t} - user-created file detected`);return}this.writeGeneratedFile(t,e==="session"?this.generateSessionLayoutContent():this.generateSiteLayoutContent(),`${e} layout`)}generateSiteLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
282
+ // Cached pages: rendered without request data (no cookies, no headers), served from the
283
+ // cache and re-rendered at most every ${B.revalidateSeconds}s. One entry per URL (page and language).
284
+
285
+ import { Suspense } from 'react';
286
+ import type { ReactNode } from 'react';
287
+
288
+ import { ClientLayout } from '${this.appImport(this.treeDir("site"),"ClientLayout")}';
289
+
290
+ export const revalidate = ${B.revalidateSeconds};
291
+
292
+ export default function SiteLayout({ children }: { children: ReactNode }) {
293
+ return (
294
+ <ClientLayout serverCookies="" acceptLanguage={null}>
295
+ <Suspense fallback={null}>{children}</Suspense>
296
+ </ClientLayout>
297
+ );
298
+ }
299
+ `}generateSessionLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
300
+ // Per-request pages for visitors with an auth cookie (the proxy rewrites them here; a
301
+ // direct hit is a 404): the providers read the request cookies, so the server render
302
+ // shows the visitor's signed-in state and data. Never cached.
303
+
304
+ import { headers } from 'next/headers';
305
+ import type { ReactNode } from 'react';
306
+
307
+ import { ClientLayout } from '${this.appImport(this.treeDir("session"),"ClientLayout")}';
308
+
309
+ export default async function SessionLayout({ children }: { children: ReactNode }) {
310
+ const requestHeaders = await headers();
311
+ return (
312
+ <ClientLayout
313
+ serverCookies={requestHeaders.get('cookie') ?? ''}
314
+ acceptLanguage={requestHeaders.get('accept-language')}
315
+ >
316
+ {children}
317
+ </ClientLayout>
318
+ );
319
+ }
320
+ `}generateRootLayout(){this.writeGeneratedFile(`src/app${this.rootDir()}/${F("layout","tsx")}`,this.generateRootLayoutContent(),"root layout")}generateRootLayoutContent(){let e=this.appImport(this.rootDir(),"AppDocument");return this.isMultilingual()?`// Generated by @donotdev/config - DO NOT EDIT
321
+ // Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the URL's language.
322
+ // One URL per language: the default language (${this.options.defaultLanguage}) at the root, served here by
323
+ // the proxy's rewrite; the others under their prefix. Any other first segment is a 404.
324
+
325
+ import { notFound } from 'next/navigation';
326
+ import type { ReactNode } from 'react';
327
+
328
+ import { AppDocument } from '${e}';
329
+
330
+ export { metadata } from '${e}';
331
+
332
+ const LANGUAGES: readonly string[] = ${JSON.stringify(this.options.languages)};
333
+
334
+ export function generateStaticParams() {
335
+ return LANGUAGES.map((lang) => ({ lang }));
336
+ }
337
+
338
+ export default async function RootLayout({
339
+ children,
340
+ params,
341
+ }: {
342
+ children: ReactNode;
343
+ params: Promise<{ lang: string }>;
344
+ }) {
345
+ const { lang } = await params;
346
+ if (!LANGUAGES.includes(lang)) notFound();
347
+ return <AppDocument lang={lang}>{children}</AppDocument>;
348
+ }
349
+ `:`// Generated by @donotdev/config - DO NOT EDIT
350
+ // Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the app's language.
351
+
352
+ import type { ReactNode } from 'react';
353
+
354
+ import { AppDocument } from '${e}';
355
+
356
+ export { metadata } from '${e}';
357
+
358
+ export default function RootLayout({ children }: { children: ReactNode }) {
359
+ return <AppDocument lang=${JSON.stringify(this.options.defaultLanguage)}>{children}</AppDocument>;
360
+ }
361
+ `}generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${F("not-found","tsx")}`,this.generateNotFoundContent(),"404 page"),this.writeGeneratedFile(`src/app/${F("global-not-found","tsx")}`,this.generateGlobalNotFoundContent(),"global 404 page")}generateNotFoundContent(){return`// Generated by @donotdev/config - DO NOT EDIT
362
+ // 404 page: the app's providers without request data (static, like every cached page).
363
+ // The Suspense boundary keeps a query-string read (useSearchParams) to the 404 content.
364
+
365
+ import { Suspense } from 'react';
366
+
367
+ import { NotFoundPage } from '@donotdev/ui';
368
+
369
+ import { ClientLayout } from '${this.appImport(this.rootDir(),"ClientLayout")}';
370
+
371
+ export default function NotFound() {
372
+ return (
373
+ <ClientLayout serverCookies="" acceptLanguage={null}>
374
+ <Suspense fallback={null}>
375
+ <NotFoundPage />
376
+ </Suspense>
377
+ </ClientLayout>
378
+ );
379
+ }
380
+ `}generateGlobalNotFoundContent(){let e=`
381
+ <AppDocument lang={lang}>
382
+ <ClientLayout serverCookies="" acceptLanguage={null}>
383
+ <Suspense fallback={null}>
384
+ <NotFoundPage />
385
+ </Suspense>
386
+ </ClientLayout>
387
+ </AppDocument>`;return this.isMultilingual()?`// Generated by @donotdev/config - DO NOT EDIT
388
+ // 404 of an unknown URL (no root layout above [lang]): the app's AppDocument in the URL's
389
+ // language, which the proxy sets on the request (${B.languageHeader}); a request the proxy
390
+ // does not see (API route, file) gets the default language (${this.options.defaultLanguage}).
391
+
392
+ import { headers } from 'next/headers';
393
+ import { Suspense } from 'react';
394
+
395
+ import { NotFoundPage } from '@donotdev/ui';
396
+
397
+ import { AppDocument } from './AppDocument';
398
+ import { ClientLayout } from './ClientLayout';
399
+
400
+ export { metadata } from './AppDocument';
401
+
402
+ const LANGUAGES: readonly string[] = ${JSON.stringify(this.options.languages)};
403
+
404
+ export default async function GlobalNotFound() {
405
+ const requested = (await headers()).get(${JSON.stringify(B.languageHeader)});
406
+ const lang =
407
+ requested && LANGUAGES.includes(requested) ? requested : ${JSON.stringify(this.options.defaultLanguage)};
408
+ return (${e}
409
+ );
410
+ }
411
+ `:`// Generated by @donotdev/config - DO NOT EDIT
412
+ // 404 of an unknown URL: the app's AppDocument in the app's language (static).
413
+
414
+ import { Suspense } from 'react';
415
+
416
+ import { NotFoundPage } from '@donotdev/ui';
417
+
418
+ import { AppDocument } from './AppDocument';
419
+ import { ClientLayout } from './ClientLayout';
420
+
421
+ export { metadata } from './AppDocument';
422
+
423
+ const lang = ${JSON.stringify(this.options.defaultLanguage)};
424
+
425
+ export default function GlobalNotFound() {
426
+ return (${e}
427
+ );
428
+ }
429
+ `}generateSessionPage(e){let t=this.appDirFor(e.path,"session"),r=`${"../".repeat(t.split("/").filter(Boolean).length)}${this.appDirFor(e.path).slice(1)}/${F("page","tsx").replace(/\.tsx$/,"")}`,n=["default"];e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path)&&n.push("generateMetadata"),this.writeGeneratedFile(`src/app${t}/${F("page","tsx")}`,`// Generated by @donotdev/config - DO NOT EDIT
430
+ // Per-request render of ${e.path} (visitors with an auth cookie): same page as the cached one.
431
+
432
+ export { ${n.join(", ")} } from '${r}';
433
+ `,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${F("page","tsx")}`,`src/app/**/${F("layout","tsx")}`,`src/app/**/${F("not-found","tsx")}`,`src/app/${F("global-not-found","tsx")}`,"src/app/**/*PageClient.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let n of s)if(await this.hasGenerationMarker(n))try{await this.pathResolver.remove(n),r++,this.logger.debug(`Cleaned generated file: ${n}`)}catch(a){this.logger.debug(`Could not clean file ${n}: ${a.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e){try{let t=this.appDirFor(e.path),s=`src/app${t}/${F("page","tsx")}`,r=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(r)&&!await this.hasGenerationMarker(r))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let n={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},a=this.generatePageFileContent(n);this.writeGeneratedFile(s,a,`app page: ${t}`);let l=this.extractComponentName(n.filePath),i=this.calculateRelativeImportPath(n.relativePath,n.path);return n.metaExport?.namespace==="blog"&&this.hasDynamicSegment(n.path)?this.writeGeneratedFile(`src/app${t}/BlogPostClient.tsx`,this.generateBlogPostClientContent(l,i),`app blog client: ${t}`):this.isClientComponent(n.filePath)&&this.writeGeneratedFile(`src/app${t}/${l}Client.tsx`,this.generateMountedClientContent(l,i),`app client wrapper: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===be.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(s=>s.startsWith(":")?`[${s.slice(1)}]`:s==="*"?"[...slug]":s).join("/")}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=_r(t),r=s.resolve(e);delete s.cache[r];let n=s(r);return n.default||n.i18nConfig||n}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e){let t=this.extractComponentName(e.filePath),s=e.relativePath||e.file,r=this.calculateRelativeImportPath(s,e.path);if(e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path))return this.generateBlogPostRSCContent(e,t,r);let n=this.isClientComponent(e.filePath),a=this.normalizeAuth(e.auth)?e.auth:null,l=e.meta?.signedInRedirect??null,i=[...a?["AuthGuard"]:[],...l?["SignedInRedirect"]:[]],c=i.length?`import { ${i.join(", ")} } from '@donotdev/ui';
434
+ `:"",p=u=>{let g=l?`<SignedInRedirect to={${JSON.stringify(l)}}>${u}</SignedInRedirect>`:u;return a?`<AuthGuard auth={${JSON.stringify(a===!0?{required:!0}:a)}}>${g}</AuthGuard>`:g};return n?`// Generated by @donotdev/config - DO NOT EDIT
282
435
  // This file will be regenerated when src/pages changes
283
436
  // To customize: edit ${e.filePath} or create manual app/** files
284
437
 
285
- import ${t}Client from './${t}Client';
286
- ${this.ssrDynamicExport()}
438
+ ${c}import ${t}Client from './${t}Client';
439
+ ${this.onDemandParamsExport(e)}
287
440
  export default function ${t}Route() {
288
- return <${t}Client />;
441
+ return ${p(`<${t}Client />`)};
289
442
  }
290
- `:`// Generated by @donotdev/config - DO NOT EDIT
443
+ `:i.length?`// Generated by @donotdev/config - DO NOT EDIT
291
444
  // This file will be regenerated when src/pages changes
292
445
  // To customize: edit ${e.filePath} or create manual app/** files
293
446
 
294
- import type { Metadata } from 'next';
295
-
296
- import { getMetadataForPath } from '@donotdev/core/next';
297
-
298
- import ${t} from '${r}';
299
- ${this.ssrDynamicExport()}
300
- export async function generateMetadata(): Promise<Metadata> {
301
- return getMetadataForPath('${e.path}');
447
+ ${c}import ${t} from '${r}';
448
+ ${this.onDemandParamsExport(e)}
449
+ export default function ${t}Route(props: Record<string, unknown>) {
450
+ return ${p(`<${t} {...props} />`)};
302
451
  }
452
+ `:`// Generated by @donotdev/config - DO NOT EDIT
453
+ // This file will be regenerated when src/pages changes
454
+ // To customize: edit ${e.filePath} or create manual app/** files
303
455
 
456
+ import ${t} from '${r}';
457
+ ${this.onDemandParamsExport(e)}
304
458
  export default ${t};
305
- `}ssrDynamicExport(){return this.options.ssr?`
306
- // SSR (appConfig.ssr): render at request time \u2014 the provider tree is store-driven
307
- // and therefore dynamic. Content is fully server-rendered.
308
- export const dynamic = 'force-dynamic';
309
- `:""}generateMetadataFunction(e,t,s){let r=Ye(s),o=Ke(s),n="`",l=r.map(i=>` '${i}': { href: ${n}\${baseUrl}\${currentPath}${n} }`).join(`,
459
+ `}generateMetadataFunction(e,t,s){let r=ot(s),n=at(s),a="`",l=r.map(i=>` '${i}': { href: ${a}\${baseUrl}\${currentPath}${a} }`).join(`,
310
460
  `);return`
311
461
  import type { Metadata } from 'next';
312
462
  import { readFileSync } from 'node:fs';
@@ -345,7 +495,7 @@ function getTranslationValue(translation, keyPath) {
345
495
  // I18n config (inlined from build-time config)
346
496
  const i18nConfig = ${JSON.stringify(s,null,2)};
347
497
  const supportedLocales = ${JSON.stringify(r)};
348
- const fallbackLocale = '${o}';
498
+ const fallbackLocale = '${n}';
349
499
 
350
500
  export async function generateMetadata({ params }): Promise<Metadata> {
351
501
  // Detect locale from params or use fallback
@@ -356,7 +506,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
356
506
  // Get base URL from environment or construct from request
357
507
  const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
358
508
  (typeof process !== 'undefined' && process.env.VERCEL_URL
359
- ? ${n}https://\${process.env.VERCEL_URL}${n}
509
+ ? ${a}https://\${process.env.VERCEL_URL}${a}
360
510
  : '');
361
511
  const currentPath = '${e.path}';
362
512
 
@@ -381,9 +531,9 @@ export async function generateMetadata({ params }): Promise<Metadata> {
381
531
  }
382
532
  }
383
533
 
384
- const pageTitle = title ? ${n}\${title} | \${siteName}${n} : siteName;
534
+ const pageTitle = title ? ${a}\${title} | \${siteName}${a} : siteName;
385
535
  const pageDescription = description || '';
386
- const pageImage = metaObject?.image || '${oe}';
536
+ const pageImage = metaObject?.image || '${pe}';
387
537
  const pageType = metaObject?.type || 'website';
388
538
  const pageKeywords = metaObject?.keywords;
389
539
  const pageAuthor = metaObject?.author;
@@ -400,7 +550,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
400
550
  title: pageTitle,
401
551
  ...(pageDescription && { description: pageDescription }),
402
552
  type: pageType,
403
- url: ${n}\${baseUrl}\${currentPath}${n},
553
+ url: ${a}\${baseUrl}\${currentPath}${a},
404
554
  ...(pageImage && { images: [pageImage] }),
405
555
  siteName: siteName,
406
556
  },
@@ -419,75 +569,234 @@ ${l}
419
569
 
420
570
  return metadata;
421
571
  }
422
- `}generateMetadataObject(e){let t={};return e.title&&(t.title=e.title),e.description&&(t.description=e.description),(e.title||e.description)&&(t.openGraph={},e.title&&(t.openGraph.title=e.title),e.description&&(t.openGraph.description=e.description),t.openGraph.type="website"),(e.title||e.description)&&(t.twitter={card:"summary_large_image"},e.title&&(t.twitter.title=e.title),e.description&&(t.twitter.description=e.description)),Object.keys(e).forEach(s=>{["title","description"].includes(s)||(t[s]=e[s])}),JSON.stringify(t,null,2)}extractComponentName(e){let s=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return s.charAt(0).toUpperCase()+s.slice(1)}async hasGenerationMarker(e){try{let t=await this.pathResolver.read(e,{format:"text"});return t&&t.includes("// Generated by @donotdev/config")}catch{return!1}}async generateMiddleware(e){let t=e.routes.filter(r=>r.auth&&r.auth!==!1&&r.auth.required);if(t.length===0){this.logger.debug("No protected routes found, skipping middleware generation");return}let s=this.generateMiddlewareContent(t);this.writeGeneratedFile(this.options.middlewarePath,s,"middleware")}generateMiddlewareContent(e){let t=e.map(s=>` '${s.path.replace(/\[([^\]]+)\]/g,":$1").replace(/\.\.\./g,"*")}'`).join(`,
423
- `);return`// Auto-generated middleware by @donotdev/config
424
- // Generated at ${new Date().toISOString()}
572
+ `}generateMetadataObject(e){let t={};return e.title&&(t.title=e.title),e.description&&(t.description=e.description),(e.title||e.description)&&(t.openGraph={},e.title&&(t.openGraph.title=e.title),e.description&&(t.openGraph.description=e.description),t.openGraph.type="website"),(e.title||e.description)&&(t.twitter={card:"summary_large_image"},e.title&&(t.twitter.title=e.title),e.description&&(t.twitter.description=e.description)),Object.keys(e).forEach(s=>{["title","description"].includes(s)||(t[s]=e[s])}),JSON.stringify(t,null,2)}extractComponentName(e){let s=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return s.charAt(0).toUpperCase()+s.slice(1)}async hasGenerationMarker(e){try{let t=await this.pathResolver.read(e,{format:"text"});return t&&t.includes("// Generated by @donotdev/config")}catch{return!1}}async generateMiddleware(e){this.removeLegacyMiddleware(),this.rendersSessionTree=!1;let t=e.routes.filter(c=>!!this.normalizeAuth(c.auth)),s=e.routes.filter(c=>c.meta?.signedInRedirect),r=this.usesCookieSession();(t.length>0||s.length>0)&&!r&&this.logger.debug("Auth session not in cookies (no Supabase createBrowserClient): pages use the client AuthGuard / SignedInRedirect only, no proxy auth redirects");let n=r?t:[],a=r?s:[],l=this.pathResolver.resolveAppPath(this.options.proxyPath),i=this.pathResolver.pathExists(l)&&!await this.hasGenerationMarker(l);if(!this.isMultilingual()&&!r){this.logger.debug("One language and no cookie session: no proxy.next.ts"),this.pathResolver.pathExists(l)&&!i&&await this.pathResolver.remove(l);return}if(i){this.logger.warn(`${this.options.proxyPath} is hand-written: not generating language routing / session refresh / auth redirects / per-request pages (add them to your proxy; every visitor gets the cached pages)`);return}this.isMultilingual()&&(this.appRouteSegments=await this.findAppRouteSegments()),this.writeGeneratedFile(this.options.proxyPath,this.generateMiddlewareContent(n,e.routes,a,r),"proxy"),this.rendersSessionTree=r}async findAppRouteSegments(){let e=this.pathResolver.getAppRoot(),t=this.pathResolver.resolveAppPath(T.next.appPages),s=await this.pathResolver._globWithNormalization([`${T.next.appPages}/**/{route,page}.${ie}.{ts,tsx,js,jsx}`],{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0}),r=new Set;for(let n of s){if(await this.hasGenerationMarker(n))continue;let[a]=n.slice(t.length+1).split("/").slice(0,-1).filter(l=>!/^\(.*\)$/.test(l));a&&a!=="[lang]"&&r.add(a)}return[...r].sort()}routePattern(e){return"^"+e.split("/").map(t=>t==="*"?".*":t.startsWith(":")?"[^/]+":t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("/")+"$"}generateMiddlewareContent(e,t=[],s=[],r=!1){let n=this.isMultilingual(),a=e.length>0,l=s.length>0,i=a||l,c=r||i,p=this.options.auth??{},u=e.map(k=>{let{role:N}=this.normalizeAuth(k.auth);return` { pattern: new RegExp(${JSON.stringify(this.routePattern(k.path))})${N?`, role: ${JSON.stringify(N)}`:""} },`}).join(`
573
+ `),g=s.map(k=>` { pattern: new RegExp(${JSON.stringify(this.routePattern(k.path))}), to: ${JSON.stringify(k.meta.signedInRedirect)} },`).join(`
574
+ `),d=[...new Set(t.map(k=>k.path))].map(k=>` new RegExp(${JSON.stringify(this.routePattern(k))}),`).join(`
575
+ `),h=` ${JSON.stringify("/((?!api|_next|.*\\..*).*)")},`,w=[...a?["hasRoleAccess"]:[],...n?["LANGUAGE_COOKIE",...i?["localizePath"]:[],"parseAcceptLanguage","readCookieValue","resolveLanguageRoute","splitLanguagePath"]:[]],m=["hasSupabaseSessionCookie","refreshSupabaseSession",...i?["type SupabaseProxySession"]:[]],b=i?`,
576
+ session: SupabaseProxySession['session']`:"",f=n?`,
577
+ language: string`:"",y=c?"{ request }":"",x=`/${B.sessionSegment}`,D=`// Generated by @donotdev/config - DO NOT EDIT
578
+ // Request gate (Next 16 proxy)${n?`: one URL per language, the default language (${this.options.defaultLanguage}) at the
579
+ // root, the others under their prefix (resolveLanguageRoute in @donotdev/core)`:""}.${c?`
580
+ // Session: the Supabase cookie (createBrowserClient). No auth cookie: signed out, the
581
+ // page comes from the cache (src/app${this.treeDir("site")}, static). With one: verified and refreshed
582
+ // when expired (refreshSupabaseSession), then rendered per request with the refreshed
583
+ // cookies (src/app${this.rootDir()}${x}, an internal path: a direct hit is a 404); the browser
584
+ // gets the refreshed cookies on the response.`:""}${a?`
585
+ // Auth redirects for pages whose PageMeta sets \`auth\`, on the verified session.
586
+ // Redirect gate only: data access stays enforced by RLS, and the page's AuthGuard still
587
+ // runs on the client.`:""}${l?"\n// Signed-in redirects for pages whose PageMeta sets `signedInRedirect` (verified\n// session); the page's SignedInRedirect still runs on the client.":""}
425
588
 
426
589
  import { NextResponse } from 'next/server';
427
590
  import type { NextRequest } from 'next/server';
428
591
 
429
- // Protected route patterns
430
- const protectedRoutes = [
431
- ${t}
592
+ ${w.length?`import { ${w.join(", ")} } from '@donotdev/core/server';
593
+ `:""}${c?`import { ${m.join(", ")} } from '@donotdev/supabase/server';
594
+ `:""}`,O=c?`
595
+ /** Supabase project of the cookie session (same env as src/config/providers.ts) */
596
+ const SUPABASE = supabaseProject(
597
+ process.env.NEXT_PUBLIC_SUPABASE_URL,
598
+ process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY
599
+ );
600
+
601
+ function supabaseProject(url: string | undefined, publicKey: string | undefined) {
602
+ if (!url || !publicKey) {
603
+ throw new Error(
604
+ '[dndev] Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLIC_KEY: the proxy refreshes the auth session on every page request.'
605
+ );
606
+ }
607
+ return { url, publicKey };
608
+ }
609
+ ${n?`
610
+ /** Internal tree of the per-request pages (src/app/[lang]${x}), after the language: never a public URL */
611
+ const SESSION_SEGMENT = ${JSON.stringify(B.sessionSegment)};
612
+
613
+ /** Internal URL path of a page rendered per request: \`/fr/compte\` \u2192 \`/fr${x}/compte\` */
614
+ function sessionPath(path: string): string {
615
+ const [, language, ...rest] = path.split('/');
616
+ return ['', language, SESSION_SEGMENT, ...rest].join('/');
617
+ }
618
+
619
+ /** A direct request for the internal tree (\`/fr${x}/\u2026\`) */
620
+ function isSessionTreePath(pathname: string): boolean {
621
+ return pathname.split('/').slice(1, 3).includes(SESSION_SEGMENT);
622
+ }
623
+ `:`
624
+ /** Internal tree of the per-request pages (src/app${x}): never a public URL */
625
+ const SESSION_TREE = ${JSON.stringify(x)};
626
+
627
+ /** Internal URL path of a page rendered per request */
628
+ function sessionPath(path: string): string {
629
+ return path === '/' ? SESSION_TREE : SESSION_TREE + path;
630
+ }
631
+
632
+ /** A direct request for the internal tree */
633
+ function isSessionTreePath(pathname: string): boolean {
634
+ return pathname === SESSION_TREE || pathname.startsWith(\`\${SESSION_TREE}/\`);
635
+ }
636
+ `}${i?`
637
+ /** Session of a request without an auth cookie: signed out, nothing to verify */
638
+ const SIGNED_OUT: SupabaseProxySession['session'] = { user: null };
639
+ `:""}`:"",_=a?`
640
+ /** appConfig.auth.authRoute: where a signed-out visitor goes (null: page fallback) */
641
+ const AUTH_ROUTE: string | null = ${JSON.stringify(p.authRoute??null)};
642
+ /** appConfig.auth.roleRoute: where a visitor without the role goes (null: page fallback) */
643
+ const ROLE_ROUTE: string | null = ${JSON.stringify(p.roleRoute??null)};
644
+
645
+ const protectedRoutes: Array<{ pattern: RegExp; role?: string }> = [
646
+ ${u}
432
647
  ];
433
648
 
434
- // Auth check function (customize as needed)
435
- function isAuthenticated(request: NextRequest): boolean {
436
- // TODO: Implement your authentication logic
437
- // Example: check for auth cookie, JWT token, etc.
438
- const authToken = request.cookies.get('auth-token')?.value;
439
- return Boolean(authToken);
440
- }
441
-
442
- // Route matching function
443
- function matchesProtectedRoute(pathname: string): boolean {
444
- return protectedRoutes.some(pattern => {
445
- if (pattern.includes(':')) {
446
- // Dynamic route matching
447
- const regex = new RegExp('^' + pattern.replace(/:[^/]+/g, '[^/]+') + '$');
448
- return regex.test(pathname);
449
- }
450
- if (pattern.includes('*')) {
451
- // Wildcard matching
452
- const regex = new RegExp('^' + pattern.replace(/*/g, '.*') + '$');
453
- return regex.test(pathname);
454
- }
455
- // Exact match
456
- return pathname === pattern;
457
- });
649
+ /** Redirect of a protected route, or null to let the page render. */
650
+ function authRedirect(
651
+ request: NextRequest${b},
652
+ routePath: string${f}
653
+ ): NextResponse | null {
654
+ const route = protectedRoutes.find((r) => r.pattern.test(routePath));
655
+ if (!route) return null;
656
+ // Cannot tell (Supabase unreachable, several projects' cookies): the page's AuthGuard decides
657
+ if (session === null) return null;
658
+
659
+ if (!session.user) {
660
+ if (!AUTH_ROUTE) return null;
661
+ const url = new URL(${n?"localizePath(AUTH_ROUTE, language, LANGUAGE_ROUTING)":"AUTH_ROUTE"}, request.url);
662
+ url.searchParams.set('returnTo', request.nextUrl.pathname + request.nextUrl.search);
663
+ return NextResponse.redirect(url);
664
+ }
665
+ if (route.role && !hasRoleAccess(session.user.role, route.role)) {
666
+ if (!ROLE_ROUTE) return null;
667
+ return NextResponse.redirect(new URL(${n?"localizePath(ROLE_ROUTE, language, LANGUAGE_ROUTING)":"ROLE_ROUTE"}, request.url));
668
+ }
669
+ return null;
670
+ }
671
+ `:"",G=l?`
672
+ /** PageMeta \`signedInRedirect\`: where a signed-in visitor of the page goes */
673
+ const signedInRoutes: Array<{ pattern: RegExp; to: string }> = [
674
+ ${g}
675
+ ];
676
+
677
+ /** Redirect of a signed-in visitor, or null to let the page render. */
678
+ function signedInRedirect(
679
+ request: NextRequest${b},
680
+ routePath: string${f}
681
+ ): NextResponse | null {
682
+ const route = signedInRoutes.find((r) => r.pattern.test(routePath));
683
+ if (!route) return null;
684
+ // A pending return-to wins: the page's AuthReturnTo takes the visitor there
685
+ if (request.nextUrl.searchParams.has('returnTo')) return null;
686
+ // Signed out, or cannot tell: the page renders (its SignedInRedirect decides on the client)
687
+ if (!session?.user) return null;
688
+ return NextResponse.redirect(new URL(${n?"localizePath(route.to, language, LANGUAGE_ROUTING)":"route.to"}, request.url));
458
689
  }
690
+ `:"",re=n?`
691
+ const LANGUAGE_ROUTING = {
692
+ languages: ${JSON.stringify(this.options.languages)},
693
+ defaultLanguage: ${JSON.stringify(this.options.defaultLanguage)},
694
+ };
459
695
 
460
- export function middleware(request: NextRequest) {
461
- const { pathname } = request.nextUrl;
696
+ /** Request header of the URL's language, read by the 404 page (src/app/global-not-found) */
697
+ const LANGUAGE_HEADER = ${JSON.stringify(B.languageHeader)};
462
698
 
463
- // Check if the current route is protected
464
- if (matchesProtectedRoute(pathname)) {
465
- if (!isAuthenticated(request)) {
466
- // Redirect to login page
467
- const loginUrl = new URL('/login', request.url);
468
- loginUrl.searchParams.set('from', pathname);
469
- return NextResponse.redirect(loginUrl);
699
+ /** First URL segments of the app's hand-written routes outside src/app/[lang] (route handlers) */
700
+ const APP_ROUTE_SEGMENTS: readonly string[] = ${JSON.stringify(this.appRouteSegments)};
701
+ `:"",ee=n||c?`
702
+ /** App pages (src/pages): API routes, files and hand-written app routes pass untouched */
703
+ const pageRoutes: RegExp[] = [
704
+ ${d}
705
+ ];
706
+ `:"",v=i?"session, ":"",ne=" // Verified session, refreshed when expired: the redirects and the server render\n // (refreshed cookies forwarded with `request`) see the same signed-in state\n const auth = await refreshSupabaseSession(request, SUPABASE.url, SUPABASE.publicKey);",E=`
707
+ request: NextRequest${b}${c?`,
708
+ personal: boolean`:""}
709
+ `,Y=(k,N)=>`${a?`
710
+ const redirect = authRedirect(request, ${v}${k}${N});
711
+ if (redirect) return redirect;
712
+ `:""}${l?`
713
+ const signedIn = signedInRedirect(request, ${v}${k}${N});
714
+ if (signedIn) return signedIn;
715
+ `:""}`,z=k=>c?`
716
+ // Auth cookie: rendered per request with the visitor's cookies
717
+ if (personal) {${k==="pathname"?"":`
718
+ const page = ${k};`}
719
+ return NextResponse.rewrite(new URL(sessionPath(${k==="pathname"?"pathname":"page"}) + search, request.url), { request });
720
+ }`:"",U;n?U=`
721
+ /** Language routing, redirects and render tree of a page request. */
722
+ function route(${E}): NextResponse {
723
+ const { pathname, search } = request.nextUrl;
724
+ const decision = resolveLanguageRoute(
725
+ pathname,
726
+ {
727
+ stored: readCookieValue(request.headers.get('cookie'), LANGUAGE_COOKIE),
728
+ preferred: parseAcceptLanguage(request.headers.get('accept-language')),
729
+ },
730
+ LANGUAGE_ROUTING
731
+ );
732
+ if (!pageRoutes.some((pattern) => pattern.test(decision.path))) {
733
+ // Not a page (API route, hand-written route, unknown URL): an unknown URL's 404
734
+ // renders in the URL's language
735
+ const url = splitLanguagePath(pathname, LANGUAGE_ROUTING);
736
+ request.headers.set(LANGUAGE_HEADER, url.language);
737
+ // Unprefixed and not a hand-written route: the app/[lang] route would read its first
738
+ // segment as a language. Served as an unknown URL of the default language instead.
739
+ if (!url.prefixed && !APP_ROUTE_SEGMENTS.includes(pathname.split('/')[1] ?? '')) {
740
+ return NextResponse.rewrite(
741
+ new URL('/' + LANGUAGE_ROUTING.defaultLanguage + pathname + search, request.url),
742
+ { request }
743
+ );
470
744
  }
745
+ return NextResponse.next({ request });
471
746
  }
472
747
 
473
- return NextResponse.next();
748
+ // Language redirects set no language cookie (the browser language store does)
749
+ if (decision.type === 'redirect') {
750
+ return NextResponse.redirect(
751
+ new URL(decision.location + search, request.url),
752
+ decision.permanent ? 308 : 307
753
+ );
754
+ }
755
+ ${Y("decision.path",", decision.language")}${z("decision.type === 'rewrite' ? decision.destination : pathname")}
756
+ if (decision.type === 'rewrite') {
757
+ return NextResponse.rewrite(new URL(decision.destination + search, request.url)${c?", { request }":""});
758
+ }
759
+ return NextResponse.next(${y});
760
+ }
761
+ `:U=`
762
+ /** Redirects and render tree of a page request. */
763
+ function route(${E}): NextResponse {
764
+ const { ${c?"pathname, search":"pathname"} } = request.nextUrl;
765
+ if (!pageRoutes.some((pattern) => pattern.test(pathname))) {
766
+ return NextResponse.next({ request });
767
+ }
768
+ ${Y("pathname","")}${z("pathname")}
769
+ return NextResponse.next({ request });
474
770
  }
771
+ `;let q;return c?q=`
772
+ export async function proxy(request: NextRequest) {
773
+ if (isSessionTreePath(request.nextUrl.pathname)) {
774
+ return new NextResponse(null, { status: 404 });
775
+ }
776
+ // No auth cookie: signed out. Nothing to verify or refresh, no cookie written: the
777
+ // page is served from the cache.
778
+ if (!hasSupabaseSessionCookie(request)) {
779
+ return route(request${i?", SIGNED_OUT":""}, false);
780
+ }
475
781
 
782
+ ${ne}
783
+ // Signed in, or cannot tell (Supabase unreachable): per-request render. Signed out
784
+ // (refresh failed, session revoked): the cached page, with the cleared cookies.
785
+ return auth.apply(route(request, ${i?"auth.session, ":""}auth.session?.user !== null));
786
+ }
787
+ ${U}`:q=`
788
+ export function proxy(request: NextRequest) {
789
+ return route(request);
790
+ }
791
+ ${U}`,`${D}${O}${re}${ee}${_}${G}${q}
476
792
  export const config = {
477
793
  matcher: [
478
- /*
479
- * Match all request paths except for the ones starting with:
480
- * - api (API routes)
481
- * - _next/static (static files)
482
- * - _next/image (image optimization files)
483
- * - favicon.ico (favicon file)
484
- */
485
- '/((?!api|_next/static|_next/image|favicon.ico).*)',
794
+ ${h}
486
795
  ],
487
796
  };
488
- `}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),o=s.relativePath||s.file;if(!o)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let n=o.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
797
+ `}normalizeAuth(e){return e===!0?{}:!e||typeof e!="object"||!e.required&&!e.role&&!e.tier?null:{role:e.role,tier:e.tier}}usesCookieSession(){try{let e=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"));if(!{...e.dependencies,...e.devDependencies}["@donotdev/supabase"])return!1;let s=this.pathResolver.resolveAppPath("src/config/providers.ts");return this.pathResolver.pathExists(s)?this.pathResolver.readSync(s).includes("createBrowserClient("):!1}catch(e){return this.logger.debug(`Cookie session detection failed: ${e.message}`),!1}}removeLegacyMiddleware(){for(let e of["middleware.ts","src/middleware.ts"]){let t=this.pathResolver.resolveAppPath(e);try{this.pathResolver.pathExists(t)&&this.pathResolver.readSync(t).startsWith("// Auto-generated middleware by @donotdev/config")&&(this.pathResolver.removeSync(t),this.logger.debug(`Removed legacy generated ${e}`))}catch(s){this.logger.debug(`Could not remove legacy ${e}: ${s.message}`)}}}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),n=s.relativePath||s.file;if(!n)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let a=n.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
489
798
  path: '${s.path}',
490
- component: lazy(() => import('${n}')),
799
+ component: lazy(() => import('${a}')),
491
800
  auth: ${JSON.stringify(s.auth)},
492
801
  meta: ${JSON.stringify(s.meta)}
493
802
  }`}).filter(s=>s!==null).join(`,
@@ -526,7 +835,12 @@ export const routeManifest = {
526
835
  };
527
836
 
528
837
  export default pageRoutes;
529
- `}pathToComponentName(e){return e.split("/").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")+"Page"}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let r=e.replace(/\.tsx$/,"").replace(/^src\//,""),o=t==="/"?0:t.split("/").filter(Boolean).length;return`${"../".repeat(o+1)}${r}`}hasDynamicSegment(e){return e.includes(":")||e.includes("[")}extractDynamicParam(e){let t=e.match(/:([a-zA-Z0-9_]+)/);if(t)return t[1];let s=e.match(/\[([^\]]+)\]/);return s?s[1]:"slug"}generateMountedClientContent(e,t){return this.options.ssr?`// Generated by @donotdev/config - DO NOT EDIT
838
+ `}pathToComponentName(e){return e.split("/").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")+"Page"}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let r=e.replace(/\.tsx$/,"").replace(/^src\//,""),n=this.appDirFor(t).split("/").filter(Boolean).length;return`${"../".repeat(n+1)}${r}`}onDemandParamsExport(e){return this.convertRouteToAppPath(e.path).includes("[")?`
839
+ // Each URL renders on its first request, then is cached like the static pages (ISR)
840
+ export function generateStaticParams() {
841
+ return [];
842
+ }
843
+ `:""}hasDynamicSegment(e){return e.includes(":")||e.includes("[")}extractDynamicParam(e){let t=e.match(/:([a-zA-Z0-9_]+)/);if(t)return t[1];let s=e.match(/\[([^\]]+)\]/);return s?s[1]:"slug"}generateMountedClientContent(e,t){return this.options.ssr?`// Generated by @donotdev/config - DO NOT EDIT
530
844
  // This file will be regenerated when src/pages changes
531
845
  'use client';
532
846
 
@@ -575,7 +889,7 @@ export default function BlogPostClient() {
575
889
  if (!mounted) return null;
576
890
  return <${e} />;
577
891
  }
578
- `}calculateBlogContentImportPath(e){let s=this.convertRouteToAppPath(e).split("/").filter(Boolean);return`${"../".repeat(s.length+1)}content/blog/blog-content.generated`}generateBlogPostRSCContent(e,t,s){let r=this.extractDynamicParam(e.path);return`// Generated by @donotdev/config - DO NOT EDIT
892
+ `}calculateBlogContentImportPath(e){let s=this.appDirFor(e).split("/").filter(Boolean);return`${"../".repeat(s.length+1)}content/blog/blog-content.generated`}generateBlogPostRSCContent(e,t,s){let r=this.extractDynamicParam(e.path);return`// Generated by @donotdev/config - DO NOT EDIT
579
893
  // This file will be regenerated when src/pages changes
580
894
  // To customize: edit ${e.filePath} or create manual app/** files
581
895
 
@@ -716,45 +1030,116 @@ export default async function BlogPostRoute({ params }: { params: Params }) {
716
1030
  );
717
1031
  }
718
1032
  `}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let s=this.pathResolver.readSync(t);return s?s.split(`
719
- `).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function Ht(a={}){return new Xe(a)}function C(a){return a?a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function Vt(a){return a?a.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Ce=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:n,crawlDelay:l=1,aiCrawlers:i="recommended",routes:p={},...c}=e;if(!o||!n)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:o,siteName:n,crawlDelay:l,aiCrawlers:i,routes:p,defaultImage:oe,twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...c},this.appRoot=c.appRoot||null,this.logger=N("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t){try{let s=this.generateRouteMetaTags(e.routes||[]),r={routes:e.routes||[],routeMetaTags:s,baseUrl:this.options.baseUrl,siteName:this.options.siteName},o=this.discoverBlogPosts(),n={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:r.routes.length,publicRoutes:r.routes.filter(l=>!l.auth||l.auth===!1).length,protectedRoutes:r.routes.filter(l=>l.auth&&l.auth.required).length,blogPosts:o.length};return this.options.generateRobotsTxt&&(n.robotsTxt=await this.generateRobotsTxt(r,t)),this.options.generateSitemap&&(n.sitemap=await this.generateSitemap(r,t,o)),o.length>0&&(n.rss=await this.generateRSSFeed(o,t)),n.manifest=await this.generateManifest(r,t),n}catch(s){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),s}}async generateRobotsTxt(e,t){let s=[];(e.routes||[]).forEach(o=>{if(o.auth&&o.auth.required){let n=o.path.startsWith("/")?o.path:`/${o.path}`;s.push(n)}}),s.push("/admin","/api","/_next","/static");let r=this.generateRobotsTxtContent({disallowedPaths:[...new Set(s)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",r),{fileName:"robots.txt",content:r,disallowedPaths:s.length}}async generateSitemap(e,t,s=[]){let o=(e.routes||[]).filter(l=>!(l.auth&&l.auth!==!1||typeof l.path=="string"&&l.path.includes(":")||s.length>0&&l.path===this.options.blogPath)).map(l=>({url:l.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:l.path==="/"?"1.0":"0.8"}));if(s.length>0){o.push({url:this.options.blogPath,lastmod:s[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let l of s)o.push({url:`${this.options.blogPath}/${l.slug}`,lastmod:l.date,changefreq:"monthly",priority:"0.6",image:l.image||null})}let n=this.generateSitemapContent(o);return await t("sitemap.xml",n),{fileName:"sitemap.xml",content:n,publicRoutes:o.length}}async generateManifest(e,t){let s={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,protectedRoutes:e.routes?.filter(o=>o.auth&&o.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},r=JSON.stringify(s,null,2);return await t("seo-manifest.json",r),{fileName:"seo-manifest.json",content:r,manifest:s}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:o}=e,n=p=>p?p==="*"?"*":p.startsWith("/")?p:`/${p}`:"/",l=["User-agent: *",...s.map(p=>`Disallow: ${n(p)}`),...t.map(p=>`Allow: ${n(p)}`)];o&&l.push(`Crawl-delay: ${o}`),r&&l.push(`Sitemap: ${r}`);let i=this.options.aiCrawlers;return i&&i!==!1&&(l.push(""),l.push(...rr(i))),l.join(`
720
- `)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:o,changefreq:n,priority:l,image:i})=>{let p=[` <loc>${C(this.options.baseUrl)}${C(r)}</loc>`];return o&&p.push(` <lastmod>${o}</lastmod>`),n&&p.push(` <changefreq>${n}</changefreq>`),l&&p.push(` <priority>${l}</priority>`),i&&p.push(` <image:image>
721
- <image:loc>${C(this.options.baseUrl)}${C(i)}</image:loc>
1033
+ `).slice(0,50).some(n=>n.trim()==="'use client';"||n.trim()==='"use client";'):!1}catch{return!1}}};function ns(o={}){return new it(o)}function L(o){return o?o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function os(o){return o?o.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var kr=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function is(o,e){let t;try{let s=new URL(o);if(s.protocol!=="https:"&&s.protocol!=="http:")throw new Error;t=s.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(kr.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: production 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.`)}function as(o){return o.auth&&o.auth!==!1?!1:o.meta?.seo?.noindex!==!0}var Ie=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:n,siteName:a,crawlDelay:l=1,aiCrawlers:i="recommended",routes:c={},...p}=e;if(!n||!a)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:n,siteName:a,crawlDelay:l,aiCrawlers:i,routes:c,defaultImage:pe,twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=M("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t){try{let s=this.generateRouteMetaTags(e.routes||[]),r={routes:e.routes||[],routeMetaTags:s,baseUrl:this.options.baseUrl,siteName:this.options.siteName},n=this.discoverBlogPosts(),a={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:r.routes.length,publicRoutes:r.routes.filter(l=>!l.auth||l.auth===!1).length,protectedRoutes:r.routes.filter(l=>l.auth&&l.auth.required).length,blogPosts:n.length};return this.options.generateRobotsTxt&&(a.robotsTxt=await this.generateRobotsTxt(r,t)),this.options.generateSitemap&&(a.sitemap=await this.generateSitemap(r,t,n)),n.length>0&&(a.rss=await this.generateRSSFeed(n,t)),a.manifest=await this.generateManifest(r,t),a}catch(s){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),s}}async generateRobotsTxt(e,t){let s=[];(e.routes||[]).forEach(n=>{if(n.auth&&n.auth.required){let a=n.path.startsWith("/")?n.path:`/${n.path}`;s.push(a)}}),s.push("/admin","/api");let r=this.generateRobotsTxtContent({disallowedPaths:[...new Set(s)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",r),{fileName:"robots.txt",content:r,disallowedPaths:s.length}}async generateSitemap(e,t,s=[]){let n=(e.routes||[]).filter(l=>!(!as(l)||typeof l.path=="string"&&l.path.includes(":")||s.length>0&&l.path===this.options.blogPath)).map(l=>({url:l.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:l.path==="/"?"1.0":"0.8"}));if(s.length>0){n.push({url:this.options.blogPath,lastmod:s[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let l of s)n.push({url:`${this.options.blogPath}/${l.slug}`,lastmod:l.date,changefreq:"monthly",priority:"0.6",image:l.image||null})}let a=this.generateSitemapContent(n);return await t("sitemap.xml",a),{fileName:"sitemap.xml",content:a,publicRoutes:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:s}=this.options,r=[];for(let n of e||[]){if(!as(n)||typeof n.path!="string")continue;let a=n.path===s||n.path.startsWith(`${s}/`);if(!(t.length>0&&a))if(n.path.includes(":")){if(a)continue;r.push({path:n.path,...n.meta?.entity&&{collection:n.meta.entity}})}else r.push({path:n.path})}if(t.length>0){r.push({path:s,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let n of t)r.push({path:`${s}/${n.slug}`,priority:.6,changeFrequency:"monthly",...n.date&&{lastModified:n.date}})}return r}async generateManifest(e,t){let s={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,protectedRoutes:e.routes?.filter(n=>n.auth&&n.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},r=JSON.stringify(s,null,2);return await t("seo-manifest.json",r),{fileName:"seo-manifest.json",content:r,manifest:s}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:n}=e,a=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",l=["User-agent: *",...s.map(c=>`Disallow: ${a(c)}`),...t.map(c=>`Allow: ${a(c)}`)];n&&l.push(`Crawl-delay: ${n}`),r&&l.push(`Sitemap: ${r}`);let i=this.options.aiCrawlers;return i&&i!==!1&&(l.push(""),l.push(...Nr(i))),l.join(`
1034
+ `)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:n,changefreq:a,priority:l,image:i})=>{let c=[` <loc>${L(this.options.baseUrl)}${L(r)}</loc>`];return n&&c.push(` <lastmod>${n}</lastmod>`),a&&c.push(` <changefreq>${a}</changefreq>`),l&&c.push(` <priority>${l}</priority>`),i&&c.push(` <image:image>
1035
+ <image:loc>${L(this.options.baseUrl)}${L(i)}</image:loc>
722
1036
  </image:image>`),` <url>
723
- ${p.join(`
1037
+ ${c.join(`
724
1038
  `)}
725
1039
  </url>`}).join(`
726
1040
  `);return`<?xml version="1.0" encoding="UTF-8"?>
727
1041
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
728
1042
  xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
729
1043
  ${s}
730
- </urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(r=`Explore ${o[o.length-1].split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=$.getInstance(),t=e.resolvePath("src/content/blog",this.appRoot);try{if(!e.pathExists(t))return[];let s=e.readdirSync(t).filter(o=>o.endsWith("_en.md"));if(s.length===0)return[];let r=[];for(let o of s){let n=e.resolvePath(o,t),l=e.readSync(n,{format:"text"}),i=o.replace(/_en\.md$/,""),p=l.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(p)for(let g of p[1].split(`
731
- `)){let f=g.indexOf(":");f!==-1&&(c[g.slice(0,f).trim()]=g.slice(f+1).trim())}let u=c.date;if(!u)try{u=e.statSync(n).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${i}" has no frontmatter date, using file mtime (${u})`)}catch{u=new Date().toISOString().split("T")[0],this.logger.warn(`Blog post "${i}" has no date and file stat failed, using today`)}r.push({slug:i,title:c.title||i,description:c.description||"",date:u,tags:c.tags?c.tags.split(",").map(g=>g.trim()):[],image:c.image||null})}return r.sort((o,n)=>n.date.localeCompare(o.date)),this.logger.info(`\u{1F4DD} Discovered ${r.length} blog post(s) in src/content/blog/`),r}catch(s){return this.logger.debug(`Blog content discovery skipped: ${s.message}`),[]}}async generateRSSFeed(e,t){let s=e.map(o=>` <item>
732
- <title><![CDATA[${Vt(o.title)}]]></title>
733
- <link>${C(this.options.baseUrl)}${C(this.options.blogPath)}/${C(o.slug)}</link>
734
- <guid>${C(this.options.baseUrl)}${C(this.options.blogPath)}/${C(o.slug)}</guid>
735
- <description><![CDATA[${Vt(o.description)}]]></description>
736
- <pubDate>${o.date?new Date(o.date).toUTCString():""}</pubDate>${o.tags.length?`
737
- <category>${C(o.tags.join(", "))}</category>`:""}${o.image?`
738
- <enclosure url="${C(this.options.baseUrl)}${C(o.image)}" type="image/png" length="0"/>`:""}
1044
+ </urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let n=t.path.split("/").filter(Boolean);n.length>0&&(s=`${n[n.length-1].split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let n=t.path.split("/").filter(Boolean);n.length>0&&(r=`Explore ${n[n.length-1].split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=R.getInstance(),t=e.resolvePath("src/content/blog",this.appRoot);try{if(!e.pathExists(t))return[];let s=e.readdirSync(t).filter(n=>n.endsWith("_en.md"));if(s.length===0)return[];let r=[];for(let n of s){let a=e.resolvePath(n,t),l=e.readSync(a,{format:"text"}),i=n.replace(/_en\.md$/,""),c=l.match(/^---\r?\n([\s\S]*?)\r?\n---/),p={};if(c)for(let g of c[1].split(`
1045
+ `)){let d=g.indexOf(":");d!==-1&&(p[g.slice(0,d).trim()]=g.slice(d+1).trim())}let u=p.date;if(!u)try{u=e.statSync(a).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${i}" has no frontmatter date, using file mtime (${u})`)}catch{u=new Date().toISOString().split("T")[0],this.logger.warn(`Blog post "${i}" has no date and file stat failed, using today`)}r.push({slug:i,title:p.title||i,description:p.description||"",date:u,tags:p.tags?p.tags.split(",").map(g=>g.trim()):[],image:p.image||null})}return r.sort((n,a)=>a.date.localeCompare(n.date)),this.logger.info(`\u{1F4DD} Discovered ${r.length} blog post(s) in src/content/blog/`),r}catch(s){return this.logger.debug(`Blog content discovery skipped: ${s.message}`),[]}}async generateRSSFeed(e,t){let s=e.map(n=>` <item>
1046
+ <title><![CDATA[${os(n.title)}]]></title>
1047
+ <link>${L(this.options.baseUrl)}${L(this.options.blogPath)}/${L(n.slug)}</link>
1048
+ <guid>${L(this.options.baseUrl)}${L(this.options.blogPath)}/${L(n.slug)}</guid>
1049
+ <description><![CDATA[${os(n.description)}]]></description>
1050
+ <pubDate>${n.date?new Date(n.date).toUTCString():""}</pubDate>${n.tags.length?`
1051
+ <category>${L(n.tags.join(", "))}</category>`:""}${n.image?`
1052
+ <enclosure url="${L(this.options.baseUrl)}${L(n.image)}" type="image/png" length="0"/>`:""}
739
1053
  </item>`).join(`
740
1054
  `),r=`<?xml version="1.0" encoding="UTF-8"?>
741
1055
  <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
742
1056
  <channel>
743
- <title>${C(this.options.siteName)}</title>
744
- <link>${C(this.options.baseUrl)}${C(this.options.blogPath)}</link>
745
- <description>${C(this.options.siteName)} Blog</description>
1057
+ <title>${L(this.options.siteName)}</title>
1058
+ <link>${L(this.options.baseUrl)}${L(this.options.blogPath)}</link>
1059
+ <description>${L(this.options.siteName)} Blog</description>
746
1060
  <language>en</language>
747
- <atom:link href="${C(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
1061
+ <atom:link href="${L(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
748
1062
  ${s}
749
1063
  </channel>
750
- </rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}},Ze=["GPTBot","Google-Extended","CCBot","ClaudeBot"],Qe=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function rr(a){let e=["# AI Crawler Management"];if(a==="block-all"){for(let t of[...Ze,...Qe])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(a==="allow-all"){for(let t of[...Ze,...Qe])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of Ze)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of Qe)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Jt(a={}){let{logger:e}=a,t=$.getInstance(),s=a.appRoot||t.getAppRoot();try{let r=t.resolvePath("public/route-manifest.json",s),o=t.readSync(r,{format:"json"});if(!o)return e?.error?.(`Route manifest not found at ${r}. Routes will be empty.`),{routes:[],errors:[`Route manifest missing: ${r}`],source:"fallback"};let n=o.routes||[];return{routes:n,errors:[],source:o.source||"generated",totalFiles:n.length}}catch(r){return e?.warn?.(`Error parsing route manifest: ${r.message}, falling back to empty routes`),{routes:[],errors:[r.message],source:"fallback"}}}function qt(a={}){let{siteName:e,baseUrl:t,description:s,blogPosts:r=[],blogPath:o="/blog",logger:n}=a;if(!e||!t)return n?.warn?.("llms.txt generation skipped: missing siteName or baseUrl"),null;let i=Jt({appRoot:a.appRoot,logger:n}).routes||[],p=[];p.push(`# ${e}`),p.push(""),s&&(p.push(`> ${s}`),p.push(""));let c=i.filter(u=>!u.auth||u.auth===!1);if(c.length>0){p.push("## Pages"),p.push("");for(let u of c){let g=u.path||"/",f=u.meta?.title||or(g),h=u.meta?.description||"",b=`${t}${g}`;h?p.push(`- [${f}](${b}): ${h}`):p.push(`- [${f}](${b})`)}p.push("")}if(r.length>0){p.push("## Blog"),p.push("");for(let u of r){let g=`${t}${o}/${u.slug}`;u.description?p.push(`- [${u.title}](${g}): ${u.description}`):p.push(`- [${u.title}](${g})`)}p.push("")}return p.join(`
751
- `)}function Yt(a={}){let{siteName:e,baseUrl:t,blogPosts:s=[],blogPath:r="/blog",appRoot:o,logger:n}=a;if(!e||!t)return null;if(s.length===0)return n?.debug?.("llms-full.txt skipped: no blog posts"),null;let l=$.getInstance(),i=o?l.resolvePath("src/content/blog",o):null;if(!i||!l.pathExists(i))return null;let p=[`# ${e}
752
- `];a.description&&p.push(`> ${a.description}
753
- `);for(let c of s){let u=l.resolvePath(`${c.slug}_en.md`,i);try{let g=l.readSync(u,{format:"text"});if(!g)continue;let f=g.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),h=`${t}${r}/${c.slug}`;p.push(`## ${c.title}
754
- `),p.push(`Source: ${h}
755
- `),c.date&&p.push(`Date: ${c.date}
756
- `),p.push(f.trim()),p.push("")}catch{n?.debug?.(`llms-full.txt: could not read ${c.slug}`)}}return p.join(`
757
- `)}function or(a){return a==="/"||a===""?"Home":(a.split("/").filter(Boolean).pop()||"Home").split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}var et=class extends F{constructor(e={}){super(ue,e);let t=$.getInstance(),s=N("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let o=e.seo?.baseUrl;if(!o&&r){let i=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(i)?i:`https://${i}`}o?s.debug(`Found app URL: ${o}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let n=e.siteName||e.seo?.siteName||null;if(s.verbose(`Name: ${n||"Not found"}`),s.verbose(`URL: ${o||"Not found"}`),n&&s.debug(` - Site name from appConfig: "${n}"`),e.seo?.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let l=[];if(o||l.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),n||l.push("siteName (APP_NAME in src/config/app.ts)"),l.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),l.forEach(i=>s.warn(` - ${i}`)),s.warn(""),s.warn(" To fix:"),o||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),n||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this._baseUrl=o,this._siteName=n,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this.seoGenerator=new Ce({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:o,siteName:n,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(r,o)=>{if(!r){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${r}`,o,r)},s=await this.seoGenerator.generateSEOFiles(e,t);if(s.robotsTxt&&!s.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${s.robotsTxt.disallowedPaths||0} disallowed paths`),s.sitemap&&!s.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${s.sitemap.publicRoutes||0} routes`),s.rss&&!s.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${s.rss.postCount||0} blog posts`),s.manifest&&!s.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json"),this._llmsTxtEnabled){let r=this.seoGenerator.discoverBlogPosts(),o=this.pathResolver.getAppRoot(),n=qt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});if(n&&(this.writeGeneratedFile("public/llms.txt",n,"llms.txt"),this.logger.info("\u{1F4C4} llms.txt")),r.length>0){let l=Yt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});l&&(this.writeGeneratedFile("public/llms-full.txt",l,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))}}}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function Kt(a={}){return new et(a)}function Xt(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),it.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var Zt=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,Qt=/['"]([^'"]+)['"]/g,ge=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{...Te.selectors,...this.options.customPatterns?.selectors},themes:{...Te.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(n=>n.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((n,l)=>{let i=n.replace(/[^a-zA-Z0-9]/g,"");return i?l===0?i.toLowerCase():i.charAt(0).toUpperCase()+i.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,n=this.pathResolver.normalizePath(t),l=this._stripComments(e),i=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=i.exec(l))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let g=c.match(this.patterns.themes.themeIcon),f=c.match(this.patterns.themes.themeIsDark),h={name:p,displayName:u,isDark:f?f[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(h),s.themes.set(p,{name:p,displayName:u,isDark:h.isDark,file:n,variables:new Set,meta:h.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${n}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Zt.lastIndex=0;(r=Zt.exec(t))!==null;){let o=r[1],n;for(Qt.lastIndex=0;(n=Qt.exec(o))!==null;){let l=n[1].trim();l&&s.add(l)}}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let n=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];n&&t.push(`Theme class "${n}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let n=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:n}}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 Ne=class extends G{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new ge(t,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:s}=e;this.logger.debug(`Scanning ${t.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",s),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t),await this._processConsumerFiles(s);let r=this._serializeThemes();return this.logger.debug(`Discovered ${r.length} themes:`,r.map(o=>o.name)),{themes:r,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return Ie.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning framework file ${t}: ${s.message}`)}}async _processConsumerFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${t}: ${s.message}`)}}_addEssentialThemes(){Ie.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var tt=class extends F{constructor(e={}){super(Ne,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new ge(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(o=>!o.essential).length,r=t.length;if(r===0)throw Wt("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
1064
+ </rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,r=e.routes?.filter(n=>n.auth&&n.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}},lt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],ct=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Nr(o){let e=["# AI Crawler Management"];if(o==="block-all"){for(let t of[...lt,...ct])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(o==="allow-all"){for(let t of[...lt,...ct])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of lt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of ct)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Re(o){return o.replace(/\s+/g," ").trim()}function ls(o){let e=[`# ${Re(o.name)}`,""];o.summary&&e.push(`> ${Re(o.summary)}`,"");for(let t of o.sections)if(t.links.length!==0){e.push(`## ${Re(t.heading)}`,"");for(let s of t.links){let r=`- [${Re(s.title)}](${s.url})`;e.push(s.description?`${r}: ${Re(s.description)}`:r)}e.push("")}return e.join(`
1065
+ `)}var Cr="dndev",Dr="crud",Fr="entity-";function cs(o,e,t){return e?o?.[e]?.[t]:void 0}function H(o){return typeof o=="string"&&o.trim()!==""?o.trim():void 0}function Tr(o,e,t){let s=o.metaExport||o.meta||{},r=s.seo||{},n=cs(e,s.namespace,t),a=H(n?.title)??H(r.title)??H(n?.meta?.fullTitle)??H(r.fullTitle),l=r.description===null?void 0:H(r.description)??H(n?.description);return{...a&&{title:a},...l&&{description:l}}}function ps(o){let{siteName:e,description:t,baseUrl:s,sitemapRoutes:r,routes:n,blogPosts:a=[],blogPath:l="/blog",translations:i,language:c}=o,p=cs(i,Cr,c)?.seo,u=H(p?.llmsPages),g=H(p?.llmsBlog);if(!u||!g)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${c}".`);let d=new Map(n.map(y=>[y.path,y])),h=new Map(a.map(y=>[`${l}/${y.slug}`,y])),w=r.map(({path:y,collection:x})=>{let D=h.get(y);if(D)return{path:y,title:D.title,...H(D.description)&&{description:H(D.description)},section:g};if(x)return{path:y,collection:x};let O=m(y);if(y===l&&!O.title)return{path:y,...O,title:g};if(!O.title){let _=d.get(y),G=(_?.metaExport||_?.meta)?.namespace;throw new Error(`[dndev] llms.txt: page "${y}" has no title in "${c}". Add "title" to `+(G?`${G}_${c}.json`:"its translations")+" or `seo: { title }` to its PageMeta.")}return{path:y,...O}});function m(y){let x=d.get(y);return x?Tr(x,i,c):{}}let b={},f={};for(let[y,x]of Object.entries(i||{})){if(y===Dr&&x?.[c]&&(f[y]=x[c]),!y.startsWith(Fr))continue;x?.[c]&&(f[y]=x[c]);let D=H(x?.[c]?.namePlural);D&&(b[y]=D)}return{name:e,...H(t)&&{summary:H(t)},baseUrl:s,pagesHeading:u,routes:w,entityHeadings:b,language:c,translations:f}}function us(o={}){let{siteName:e,baseUrl:t,blogPosts:s=[],blogPath:r="/blog",appRoot:n,logger:a}=o;if(!e||!t)return null;if(s.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let l=R.getInstance(),i=n?l.resolvePath("src/content/blog",n):null;if(!i||!l.pathExists(i))return null;let c=[`# ${e}
1066
+ `];o.description&&c.push(`> ${o.description}
1067
+ `);for(let p of s){let u=l.resolvePath(`${p.slug}_en.md`,i);try{let g=l.readSync(u,{format:"text"});if(!g)continue;let d=g.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),h=`${t}${r}/${p.slug}`;c.push(`## ${p.title}
1068
+ `),c.push(`Source: ${h}
1069
+ `),p.date&&c.push(`Date: ${p.date}
1070
+ `),c.push(d.trim()),c.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${p.slug}`)}}return c.join(`
1071
+ `)}var gs=`src/app/sitemap.xml/${F("route","ts")}`,hs=`src/app/llms.txt/${F("route","ts")}`,pt=class extends j{constructor(e={}){super(me,e);let t=R.getInstance(),s=M("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let n=e.baseUrl;if(!n&&r){let i=r.trim().replace(/\/+$/,"");n=/^https?:\/\//i.test(i)?i:`https://${i}`}n?s.debug(`Found app URL: ${n}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let a=e.siteName||null;if(s.verbose(`Name: ${a||"Not found"}`),s.verbose(`URL: ${n||"Not found"}`),a&&s.debug(` - Site name from appConfig: "${a}"`),e.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let l=[];if(n||l.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),a||l.push("siteName (APP_NAME in src/config/app.ts)"),l.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),l.forEach(i=>s.warn(` - ${i}`)),s.warn(""),s.warn(" To fix:"),n||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),a||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this.options.isDev||is(n,"NEXT_PUBLIC_APP_URL"),this._baseUrl=n,this._siteName=a,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this._sitemapEnabled=this.options.generateSitemap!==!1,this.seoGenerator=new Ie({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,baseUrl:n,siteName:a,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e,generateSitemap:!1})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(r,n)=>{if(!r){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${r}`,n,r)},s=await this.seoGenerator.generateSEOFiles(e,t);if(this._sitemapEnabled&&await this.generateSitemapRoute(e.routes||[]),s.robotsTxt&&!s.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${s.robotsTxt.disallowedPaths||0} disallowed paths`),s.sitemap&&!s.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${s.sitemap.publicRoutes||0} routes`),s.rss&&!s.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${s.rss.postCount||0} blog posts`),s.manifest&&!s.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json"),this._llmsTxtEnabled){let r=this.seoGenerator.discoverBlogPosts(),n=this.pathResolver.getAppRoot();if(await this.generateLlmsTxtRoute(e.routes||[],r),r.length>0){let a=us({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:n,blogPosts:r,logger:this.logger});a&&(this.writeGeneratedFile("public/llms-full.txt",a,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))}}}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}useLanguages(e){this._languageRouting=e}async generateSitemapRoute(e){if(!this._languageRouting)throw new Error("SEO handler: languages not set before sitemap generation (runDiscoveries calls useLanguages)");let t=this.seoGenerator.getSitemapRoutes(e,this.seoGenerator.discoverBlogPosts()),s=this.serverCrudReader(t),r=`// Generated by @donotdev/config - DO NOT EDIT
1072
+ // Regenerated on every build from src/pages (PageMeta) and appConfig.
1073
+ // Public routes + one URL per published record of each dynamic route's entity
1074
+ // (read with the public role). Keep a page out with \`seo: { noindex: true }\`.
1075
+
1076
+ import { HIDDEN_STATUSES, languageUrls } from '@donotdev/core/server';
1077
+ import type { LanguageRouting } from '@donotdev/core/server';
1078
+ import { buildSitemap, formatSitemapXml } from '@donotdev/core/next';
1079
+ import type { SitemapRoute } from '@donotdev/core/next';
1080
+ ${s.imports}
1081
+ // Re-read published records at most once per cache lifetime (same as the pages).
1082
+ export const revalidate = ${B.revalidateSeconds};
1083
+
1084
+ const BASE_URL = ${JSON.stringify(this._baseUrl)};
1085
+
1086
+ const LANGUAGE_ROUTING: LanguageRouting = ${JSON.stringify(this._languageRouting)};
1087
+
1088
+ const ROUTES: SitemapRoute[] = ${JSON.stringify(t,null,2)};
1089
+ ${s.setup}
1090
+ export async function GET(): Promise<Response> {
1091
+ const entries = await buildSitemap(ROUTES, {
1092
+ baseUrl: BASE_URL,
1093
+ routing: LANGUAGE_ROUTING,
1094
+ languageUrls,
1095
+ hiddenStatuses: HIDDEN_STATUSES,${s.expr?`
1096
+ crud: ${s.expr},`:""}
1097
+ });
1098
+ return new Response(formatSitemapXml(entries), {
1099
+ headers: { 'Content-Type': 'application/xml; charset=utf-8' },
1100
+ });
1101
+ }
1102
+ `;this.writeGeneratedFile(gs,r,"sitemap route");let n=this.pathResolver.resolveAppPath("public/sitemap.xml");this.pathResolver.pathExists(n)&&await this.pathResolver.remove(n),this.logger.info(`\u{1F5FA}\uFE0F sitemap: ${t.length} routes (${gs})`)}useTranslations(e){this._translations=e}async generateLlmsTxtRoute(e,t){if(!this._languageRouting||!this._translations)throw new Error("SEO handler: languages/translations not set before llms.txt generation (runDiscoveries calls useLanguages and useTranslations)");let s=ps({siteName:this._siteName,description:this._siteDescription,baseUrl:this._baseUrl,sitemapRoutes:this.seoGenerator.getSitemapRoutes(e,t),routes:e,blogPosts:t,blogPath:this.seoGenerator.options.blogPath,translations:this._translations,language:this._languageRouting.defaultLanguage}),r=this.serverCrudReader(s.routes),n=this.appDependsOn("entities"),a=`// Generated by @donotdev/config - DO NOT EDIT
1103
+ // Regenerated on every build from src/pages (PageMeta), translations and appConfig.
1104
+ // Same URLs as app/sitemap.xml: public pages + one link per published record of each
1105
+ // dynamic route's entity. Keep a page out with \`seo: { noindex: true }\`.
1106
+
1107
+ import { HIDDEN_STATUSES, deriveEntitySeo } from '@donotdev/core/server';
1108
+ import { buildLlmsTxt } from '@donotdev/core/next';
1109
+ import type { LlmsTxtSource } from '@donotdev/core/next';
1110
+ ${n?`import * as entities from 'entities';
1111
+ `:""}${r.imports}
1112
+ // Re-read published records at most once an hour (same as the sitemap).
1113
+ export const revalidate = ${B.revalidateSeconds};
1114
+
1115
+ const SOURCE: LlmsTxtSource = ${JSON.stringify(s,null,2)};
1116
+ ${r.setup}
1117
+ export async function GET(): Promise<Response> {
1118
+ const body = await buildLlmsTxt({
1119
+ ...SOURCE,
1120
+ entities: ${n?"entities":"{}"},
1121
+ deriveEntitySeo,
1122
+ hiddenStatuses: HIDDEN_STATUSES,${r.expr?`
1123
+ crud: ${r.expr},`:""}
1124
+ });
1125
+ return new Response(body, {
1126
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
1127
+ });
1128
+ }
1129
+ `;this.writeGeneratedFile(hs,a,"llms.txt route"),this.logger.info(`\u{1F4C4} llms.txt: ${s.routes.length} routes (${hs})`)}appDependsOn(e){let t=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"),{format:"json"});return!!(t?.dependencies?.[e]||t?.devDependencies?.[e])}serverCrudReader(e){let t=e.filter(s=>s.collection);if(t.length===0)return{imports:"",setup:"",expr:null};if(this.appDependsOn("@donotdev/supabase"))return{imports:`import { createPublicServerClient, SupabaseCrudAdapter } from '@donotdev/supabase/server';
1130
+ `,setup:`
1131
+ // Public (anonymous) reader: RLS returns what a signed-out visitor can read.
1132
+ const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
1133
+ const SUPABASE_PUBLIC_KEY = process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY;
1134
+ if (!SUPABASE_URL || !SUPABASE_PUBLIC_KEY) {
1135
+ throw new Error(
1136
+ '[dndev] Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLIC_KEY: the sitemap and llms.txt list published records.'
1137
+ );
1138
+ }
1139
+ const CRUD = new SupabaseCrudAdapter(
1140
+ createPublicServerClient(SUPABASE_URL, SUPABASE_PUBLIC_KEY)
1141
+ );
1142
+ `,expr:"CRUD"};throw new Error(`[dndev] SEO: ${t.map(s=>s.path).join(", ")} list published records, but the app's backend provider has no server reader (supported: @donotdev/supabase). Mark these pages \`seo: { noindex: true }\`.`)}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function ds(o={}){return new pt(o)}function fs(o={}){let{debug:e}=o;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:n}=r;return n||(s.externals||(s.externals={}),vt.forEach(a=>{s.externals[a]=`commonjs ${a}`})),t.webpack?t.webpack(s,r):s}})}var ms=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,vs=/['"]([^'"]+)['"]/g,ve=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{...Be.selectors,...this.options.customPatterns?.selectors},themes:{...Be.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(a=>a.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((a,l)=>{let i=a.replace(/[^a-zA-Z0-9]/g,"");return i?l===0?i.toLowerCase():i.charAt(0).toUpperCase()+i.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],n,a=this.pathResolver.normalizePath(t),l=this._stripComments(e),i=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(n=i.exec(l))!==null;){let[,c,p,u]=n;if(!c||!u)continue;let g=p.match(this.patterns.themes.themeIcon),d=p.match(this.patterns.themes.themeIsDark),h={name:c,displayName:u,isDark:d?d[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${u})`),r.push(h),s.themes.set(c,{name:c,displayName:u,isDark:h.isDark,file:a,variables:new Set,meta:h.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${a}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let n=r.slice(1);n.startsWith("_")||t.classes.add(n)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(n=>{n.startsWith("--")&&n.length>2?s==="framework"?t.variables.framework.add(n):t.variables.consumer.add(n):this._debug(`Skipping invalid CSS variable: ${n}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(ms.lastIndex=0;(r=ms.exec(t))!==null;){let n=r[1],a;for(vs.lastIndex=0;(a=vs.exec(n))!==null;){let l=a[1].trim();l&&s.add(l)}}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let n=r.replace("@keyframes","").trim();n&&t.keyframes.add(n)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(n=>{t.push(`Possible malformed CSS variable: ${n}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(n=>{if(!n.includes("--theme-label")&&n.includes("--")){let a=n.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},n=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let a=this.validateCSS(e);return{themes:n,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 Le=class extends K{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new ve(t,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:s}=e;this.logger.debug(`Scanning ${t.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",s),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t),await this._processConsumerFiles(s);let r=this._serializeThemes();return this.logger.debug(`Discovered ${r.length} themes:`,r.map(n=>n.name)),{themes:r,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return We.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning framework file ${t}: ${s.message}`)}}async _processConsumerFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${t}: ${s.message}`)}}_addEssentialThemes(){We.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var ut=class extends j{constructor(e={}){super(Le,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new ve(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(n=>!n.essential).length,r=t.length;if(r===0)throw rs("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
758
1143
  // Generated at: ${new Date().toISOString()}
759
1144
  // Populates _DNDEV_CONFIG_ with discovery results
760
1145
 
@@ -786,22 +1171,12 @@ if (typeof globalThis !== 'undefined') {
786
1171
  timestamp: Date.now(),
787
1172
  };
788
1173
  }
789
- globalThis._DNDEV_CONFIG_.${U.themes} = themeConfig;
1174
+ globalThis._DNDEV_CONFIG_.${X.themes} = themeConfig;
790
1175
  }
791
1176
 
792
1177
  // Export for compatibility
793
1178
  export default themeConfig;
794
- `}getThemeHook(){return`
795
- // Auto-generated theme hook by @donotdev/config
796
- // Generated at ${new Date().toISOString()}
797
-
798
- import { useThemeStore } from '@donotdev/stores';
799
-
800
- export function useTheme() {
801
- return useThemeStore();
802
- }
803
-
804
- export default useTheme;
805
- `}};function es(a={}){return new tt(a)}function ts({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:l,pwaOptions:i,serverShimOptions:p,appUrl:c,isDev:u,logger:g}){let f=s.debug??a,h=r.debug??a,b=o.debug??a,d=n.debug??a,m=l.debug??a,S=i.debug??a,O=p.debug??a,T=s.verbose??e,M=r.verbose??e,A=o.verbose??e,L=n.verbose??e,J=l.verbose??e,ae=i.verbose??e,ee=p.verbose??e,v={debug:a,verbose:e,generateManifest:t},ie=s.disabled?null:Ht({...v,...s,debug:f,verbose:T});a&&g.debug(`Route handler created: ${ie?"enabled":"disabled"} (debug: ${f})`);let x=es({...v,...r,debug:h,verbose:M}),K=zt({...v,...o,debug:b,verbose:A}),H=Lt({...v,...n,debug:d,verbose:L}),B=Kt({...v,...l,debug:m,verbose:J,appUrl:c,isDev:u}),te=Ut({...v,...i,debug:S,verbose:ae}),X=Xt({...v,...p,debug:O,verbose:ee}),_=jt({debug:a,verbose:e});return{routeHandler:ie,themeHandler:x,i18nHandler:K,assetHandler:H,seoHandler:B,pwaHandler:te,serverShimHandler:X,blogContentHandler:_}}function ss(a,e){let t={};if(a.routeHandler)try{t.routeConfig=a.routeHandler.createNextConfig()}catch(r){e.error(`Route handler failed during config creation: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.routeConfig=()=>({})}else t.routeConfig=()=>({});let s=[{name:"theme",handler:a.themeHandler},{name:"i18n",handler:a.i18nHandler},{name:"asset",handler:a.assetHandler},{name:"seo",handler:a.seoHandler},{name:"pwa",handler:a.pwaHandler}];for(let{name:r,handler:o}of s)try{t[`${r}Config`]=o.createNextConfig()}catch(n){e.error(`${r.charAt(0).toUpperCase()+r.slice(1)} handler failed: ${n.message}`),e.error(`Stack: ${n.stack||"No stack trace available"}`),t[`${r}Config`]=()=>({})}try{t.serverShimConfig=a.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}var nr=new Set(["@donotdev/functions"]);function rs(){try{let a=$.getInstance(),e=a.resolveAppPath("package.json"),t=a.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(r=>r.startsWith("@donotdev/")).filter(r=>!$e.buildTimePackages.includes(r)).filter(r=>!nr.has(r)).sort()}catch{return[]}}var st=new Map;function ar(a={}){let{port:e,...t}=a;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let P=process.env.CI==="true";process.env.DNDEV_BUILD_ID=P?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let s=process.env.DNDEV_BUILD_ID;if(s&&st.has(s))return st.get(s).configFn;let{appConfig:r,...o}=t;if(!r)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let n=r?.features?{debug:r.features.debug}:void 0,l=r?.seo&&typeof r.seo!="boolean"?{...r.seo,siteName:r.seo.siteName||r.app?.name}:r?.app?.name?{siteName:r.app.name}:void 0,i=r?.app?{name:r.app.name,shortName:r.app.shortName,description:r.app.description}:void 0,{features:p,seo:c,...u}=o,g={...n?{features:n}:{},...l?{seo:l}:{},...u},f=It(g),h=Mt(f);if(!h)throw new Error("normalizeOptions returned undefined");let{generateManifest:b,debug:d,verbose:m,mode:S,isDev:O,routeOptions:T,themeOptions:M,i18nOptions:A,assetOptions:L,pwaOptions:J,seoOptions:ae,serverShimOptions:ee,nextConfigOptions:v,reactCompiler:ie}=h,x=N("next-config",d,m),{appRoot:K,appRootSet:H}=ft({logger:x,debug:d}),B=!1,te=T?.routingMode||"app",X=H&&ze(K);if(X||(x.info(`
806
- \u{1F3D7}\uFE0F DnDev Framework - Building for ${S}${s?` [build:${s}]`:""}`),x.info(` Platform: Next.js | Routing: ${te}
807
- `)),O){let P=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${P}`,d&&(x.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&x.debug(`Port configured: ${P} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||x.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let _=ts({debug:d,verbose:m,generateManifest:b,routeOptions:{...T,ssr:r?.ssr!==!1},themeOptions:M,i18nOptions:A,assetOptions:L,seoOptions:ae,pwaOptions:J,serverShimOptions:ee,isDev:O,logger:x}),q=ss(_,x),y=async function(R={}){let k=$.getInstance(),j=H?rs():[];d&&j.length>0&&x.debug(`Discovered ${j.length} packages: ${j.join(", ")}`);let{missing:se,installed:we}=xe(k.getAppRoot()),Fe=se.filter(fe=>fe.startsWith("@donotdev/")),ns=we.filter(fe=>fe.startsWith("@donotdev/"));d&&se.length>0&&x.debug(`Missing optional deps (will alias to empty): ${se.join(", ")}`),H&&await Ft(_,x);let re=typeof R=="object"&&R!==null?R:{},{webpack:as,rewrites:is,redirects:ls,...cs}=re;H&&!B&&(B=await Dt(_.assetHandler,x,B));let ps=q.routeConfig(re),us=q.themeConfig(re),gs=q.i18nConfig(re),fs=q.assetConfig(re),hs=q.seoConfig(re),ds=q.pwaConfig(re),ms=q.serverShimConfig(),ot=await _.i18nHandler?.getDiscoveryData?.(),nt=ot?.flagCodes||[],vs=ot?.supportedLanguages||[],bs=te==="app"?await _.routeHandler?.getDiscoveryData?.():null,ys=St({originalWebpack:as,unusedFeaturePackages:Fe,usedFeaturePackages:ns,missingOptionalDeps:se,flagCodes:nt,languages:vs,logger:x,debug:d}),ws=Rt({originalRewrites:is,handlers:[_.routeHandler,_.themeHandler,_.i18nHandler,_.assetHandler,_.pwaHandler],logger:x}),Ps=xt({originalRedirects:ls,seoRedirects:ae?.redirects||[],routes:bs?.routes||[],logger:x}),$s={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Ss=kt({routeResult:ps,themeResult:us,i18nResult:gs,assetResult:fs,seoResult:hs,pwaResult:ds,serverShimResult:ms,restNextConfig:cs,discoveredPackages:j,reactCompiler:ie,webpackConfig:ys,rewritesConfig:ws,redirectsConfig:Ps,missingOptionalDeps:se,flagCodes:nt,pathResolver:k,env:$s,logger:x});if(x.debug("Next.js config generated"),H&&!X){let fe=i?.name||"app";x.info(`Name: ${fe}`),x.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),x.info(`App root (final): ${k.getAppRoot()}`)}return Ss};return s&&st.set(s,{configFn:y}),y}var os=ar;import{readFileSync as ir,existsSync as lr}from"node:fs";import{join as cr}from"node:path";var ye=null,rt=0,pr=6e4;function ur(){let a=Date.now();if(ye&&a-rt<pr)return ye;try{let e=cr(process.cwd(),"public","metadata-manifest.json");if(!lr(e))return null;let t=ir(e,"utf-8");return ye=JSON.parse(t),rt=a,ye}catch{return null}}function gr(a,e,t){let s=ur(),r={title:t?.siteName||"Site"};if(!s)return r;let o=a.startsWith("/")?a:`/${a}`,n=s[o];if(!n)return r;let l=e||n.defaultLocale||"en",i=n.locales[l]||n.locales[n.defaultLocale]||Object.values(n.locales)[0];if(!i)return r;let p=process.env.NEXT_PUBLIC_APP_URL,c={title:i.title,...p&&{metadataBase:new URL(p)}};return i.description&&(c.description=i.description),i.keywords&&(c.keywords=i.keywords),c.openGraph={title:i.title,type:i.type||"website",...i.description&&{description:i.description},...i.image&&{images:[i.image]},...t?.siteName&&{siteName:t.siteName}},c.twitter={card:"summary_large_image",title:i.title,...i.description&&{description:i.description},...i.image&&{images:[i.image]}},i.noindex&&(c.robots={index:!1,follow:!1}),c}function fr(){ye=null,rt=0}export{fr as clearMetadataCache,os as default,os as defineNextConfig,zs as definePostCSSConfig,gr as getMetadataForPath};
1179
+ `}};function ys(o={}){return new ut(o)}function bs({debug:o,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:n,assetOptions:a,seoOptions:l,pwaOptions:i,serverShimOptions:c,appUrl:p,isDev:u,logger:g}){let d=s.debug??o,h=r.debug??o,w=n.debug??o,m=a.debug??o,b=l.debug??o,f=i.debug??o,y=c.debug??o,x=s.verbose??e,D=r.verbose??e,O=n.verbose??e,_=a.verbose??e,G=l.verbose??e,re=i.verbose??e,ee=c.verbose??e,v={debug:o,verbose:e,generateManifest:t},ne=s.disabled?null:ns({...v,...s,debug:d,verbose:x});o&&g.debug(`Route handler created: ${ne?"enabled":"disabled"} (debug: ${d})`);let E=ys({...v,...r,debug:h,verbose:D}),Y=Qt({...v,...n,debug:w,verbose:O}),z=Yt({...v,...a,debug:m,verbose:_}),U=ds({...v,...l,debug:b,verbose:G,appUrl:p,isDev:u}),q=es({...v,...i,debug:f,verbose:re}),k=fs({...v,...c,debug:y,verbose:ee}),N=Zt({debug:o,verbose:e});return{routeHandler:ne,themeHandler:E,i18nHandler:Y,assetHandler:z,seoHandler:U,pwaHandler:q,serverShimHandler:k,blogContentHandler:N}}function ws(o,e){let t={};if(o.routeHandler)try{t.routeConfig=o.routeHandler.createNextConfig()}catch(r){e.error(`Route handler failed during config creation: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.routeConfig=()=>({})}else t.routeConfig=()=>({});let s=[{name:"theme",handler:o.themeHandler},{name:"i18n",handler:o.i18nHandler},{name:"asset",handler:o.assetHandler},{name:"seo",handler:o.seoHandler},{name:"pwa",handler:o.pwaHandler}];for(let{name:r,handler:n}of s)try{t[`${r}Config`]=n.createNextConfig()}catch(a){e.error(`${r.charAt(0).toUpperCase()+r.slice(1)} handler failed: ${a.message}`),e.error(`Stack: ${a.stack||"No stack trace available"}`),t[`${r}Config`]=()=>({})}try{t.serverShimConfig=o.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}var Or=new Set(["@donotdev/functions"]);function Ss(){try{let o=R.getInstance(),e=o.resolveAppPath("package.json"),t=o.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(r=>r.startsWith("@donotdev/")).filter(r=>!_e.buildTimePackages.includes(r)).filter(r=>!Or.has(r)).sort()}catch{return[]}}var gt=new Map;function Ir(o={}){let{port:e,...t}=o;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let P=process.env.CI==="true";process.env.DNDEV_BUILD_ID=P?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let s=process.env.DNDEV_BUILD_ID;if(s&&gt.has(s))return gt.get(s).configFn;let{appConfig:r,...n}=t;if(!r)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let a=r?.features?{debug:r.features.debug}:void 0,l=r?.seo===!1?{disabled:!0}:r?.seo&&typeof r.seo!="boolean"?{...r.seo,siteName:r.seo.siteName||r.app?.name,siteDescription:r.app?.description}:r?.app?.name?{siteName:r.app.name,siteDescription:r.app.description}:void 0,i=r?.app?{name:r.app.name,shortName:r.app.shortName,description:r.app.description}:void 0,{features:c,seo:p,...u}=n,g={...a?{features:a}:{},...l?{seo:l}:{},...u},d=Xt(g),h=Kt(d);if(!h)throw new Error("normalizeOptions returned undefined");let{generateManifest:w,debug:m,verbose:b,mode:f,isDev:y,routeOptions:x,themeOptions:D,i18nOptions:O,assetOptions:_,pwaOptions:G,seoOptions:re,serverShimOptions:ee,nextConfigOptions:v,reactCompiler:ne}=h,E=M("next-config",m,b),{appRoot:Y,appRootSet:z}=Pt({logger:E,debug:m}),U=!1,q=x?.routingMode||"app",k=z&&Ke(Y);if(k||(E.info(`
1180
+ \u{1F3D7}\uFE0F DnDev Framework - Building for ${f}${s?` [build:${s}]`:""}`),E.info(` Platform: Next.js | Routing: ${q}
1181
+ `)),y){let P=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${P}`,m&&(E.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&E.debug(`Port configured: ${P} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||E.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let N=bs({debug:m,verbose:b,generateManifest:w,routeOptions:{...x,ssr:r?.ssr!==!1,auth:r?.auth},themeOptions:D,i18nOptions:O,assetOptions:_,seoOptions:re,pwaOptions:{...G,app:i},serverShimOptions:ee,isDev:y,logger:E}),te=ws(N,E),S=async function(A={}){let C=R.getInstance(),V=z?Ss():[];m&&V.length>0&&E.debug(`Discovered ${V.length} packages: ${V.join(", ")}`);let{missing:le,installed:Ee}=Ce(C.getAppRoot()),je=le.filter(ye=>ye.startsWith("@donotdev/")),Ps=Ee.filter(ye=>ye.startsWith("@donotdev/"));m&&le.length>0&&E.debug(`Missing optional deps (will alias to empty): ${le.join(", ")}`),z&&(q==="app"&&Ft({pathResolver:C,logger:E,isCI:!!(process.env.CI||process.env.VERCEL)}),await Ht(N,E));let ce=typeof A=="object"&&A!==null?A:{},{webpack:Rs,rewrites:xs,redirects:Es,...As}=ce;z&&!U&&(U=await qt(N.assetHandler,E,U));let _s=te.routeConfig(ce),ks=te.themeConfig(ce),Ns=te.i18nConfig(ce),Cs=te.assetConfig(ce),Ds=te.seoConfig(ce),Fs=te.pwaConfig(ce),Ts=te.serverShimConfig(),dt=await N.i18nHandler?.getDiscoveryData?.(),ft=dt?.flagCodes||[],Os=dt?.supportedLanguages||[],Is=It({originalWebpack:Rs,unusedFeaturePackages:je,usedFeaturePackages:Ps,missingOptionalDeps:le,flagCodes:ft,languages:Os,logger:E,debug:m}),Ls=Lt({originalRewrites:xs,handlers:[N.routeHandler,N.themeHandler,N.i18nHandler,N.assetHandler,N.pwaHandler],logger:E}),Us=Ut({originalRedirects:Es,seoRedirects:re?.redirects||[],logger:E}),Ms={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},js=Mt({routeResult:_s,themeResult:ks,i18nResult:Ns,assetResult:Cs,seoResult:Ds,pwaResult:Fs,serverShimResult:Ts,restNextConfig:As,discoveredPackages:V,reactCompiler:ne,routingMode:q,webpackConfig:Is,rewritesConfig:Ls,redirectsConfig:Us,missingOptionalDeps:le,flagCodes:ft,pathResolver:C,env:Ms,logger:E});if(E.debug("Next.js config generated"),z&&!k){let ye=i?.name||"app";E.info(`Name: ${ye}`),E.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),E.info(`App root (final): ${C.getAppRoot()}`)}return js};return s&&gt.set(s,{configFn:S}),S}var $s=Ir;import{readFileSync as Lr,existsSync as Ur}from"node:fs";import{join as Mr}from"node:path";var xe=null,ht=0,jr=6e4;function Gr(){let o=Date.now();if(xe&&o-ht<jr)return xe;try{let e=Mr(process.cwd(),"public","metadata-manifest.json");if(!Ur(e))return null;let t=Lr(e,"utf-8");return xe=JSON.parse(t),ht=o,xe}catch{return null}}function zr(o,e,t){let s=Gr(),r={title:t?.siteName||"Site"};if(!s)return r;let n=o.startsWith("/")?o:`/${o}`,a=s[n];if(!a)return r;let l=e||a.defaultLocale||"en",i=a.locales[l]||a.locales[a.defaultLocale]||Object.values(a.locales)[0];if(!i)return r;let c=process.env.NEXT_PUBLIC_APP_URL,p={title:i.title,...c&&{metadataBase:new URL(c)}};return i.description&&(p.description=i.description),i.keywords&&(p.keywords=i.keywords),p.openGraph={title:i.title,type:i.type||"website",...i.description&&{description:i.description},...i.image&&{images:[i.image]},...t?.siteName&&{siteName:t.siteName}},p.twitter={card:"summary_large_image",title:i.title,...i.description&&{description:i.description},...i.image&&{images:[i.image]}},i.noindex&&(p.robots={index:!1,follow:!1}),p}function Br(){xe=null,ht=0}function Wr(o){return o.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}async function Ue(o,e,t){let s=[];for(let r of o){let n=Wr(r.path);if(n.length===0){s.push({route:r,path:r.path});continue}let a=n[0];if(n.length>1||!r.collection||!a)throw new Error(`[dndev] Cannot list the public URLs of route "${r.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 "${r.path}" lists "${r.collection}" records but no server CRUD reader was given.`);let l=await e.query(r.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3});for(let i of l.items){let c=i[a];typeof c!="string"&&typeof c!="number"||s.push({route:r,path:r.path.replace(`:${a}`,encodeURIComponent(String(c))),record:i})}}return s}function Me(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,crud:s,languageUrls:r,hiddenStatuses:n}){let a=[],l=(i,c)=>{let p=r(i,e,t),u=t.languages.length>1?{alternates:{languages:p}}:{};for(let g of t.languages)a.push({url:p[g],...c,...u})};for(let{route:i,path:c,record:p}of await Ue(o,s,n)){if(!p){l(c,{changeFrequency:i.changeFrequency??"weekly",priority:i.priority??(c==="/"?1:.8),...i.lastModified&&{lastModified:i.lastModified}});continue}let u=p.updatedAt instanceof Date?p.updatedAt.toISOString():p.updatedAt;l(c,{changeFrequency:i.changeFrequency??"weekly",priority:i.priority??.7,...typeof u=="string"&&{lastModified:u}})}return a}function qr(o){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${o.some(s=>s.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let s of o){t.push(" <url>",` <loc>${Me(s.url)}</loc>`);for(let[r,n]of Object.entries(s.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${Me(r)}" href="${Me(n)}" />`);s.lastModified&&t.push(` <lastmod>${Me(s.lastModified)}</lastmod>`),s.changeFrequency&&t.push(` <changefreq>${s.changeFrequency}</changefreq>`),s.priority!==void 0&&t.push(` <priority>${s.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
1182
+ `)}import Vr from"i18next";function Jr(o){let e=new Map;for(let t of Object.values(o))typeof t=="object"&&t!==null&&"collection"in t&&"fields"in t&&e.set(t.collection,t);return e}function Xr(o,e){let t=Vr.createInstance();return t.init({lng:o,resources:{[o]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),s=>t.getFixedT(o,[s,"crud"])}async function Kr(o){let{crud:e,deriveEntitySeo:t,hiddenStatuses:s}=o,r=Jr(o.entities),n,a=new Map,l=i=>{let c=a.get(i);return c||(c={heading:i,links:[]},a.set(i,c)),c};l(o.pagesHeading);for(let{route:i,path:c,record:p}of await Ue(o.routes,e,s)){let u=`${o.baseUrl}${c}`;if(!p){if(!i.title)throw new Error(`[dndev] llms.txt: page "${i.path}" has no label in the app language.`);l(i.section??o.pagesHeading).links.push({title:i.title,url:u,...i.description&&{description:i.description}});continue}let g=r.get(i.collection);if(!g)throw new Error(`[dndev] llms.txt: no entity definition for collection "${i.collection}" (route "${i.path}"). Export it from the app's \`entities\` package.`);let d=i.section??(g.namespace?o.entityHeadings[g.namespace]:void 0);if(!d)throw new Error(`[dndev] llms.txt: no heading for route "${i.path}". Add "namePlural" to the ${g.namespace??`entity-${g.name.toLowerCase()}`} translations.`);if(!n){if(!o.language||!o.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");n=Xr(o.language,o.translations)}let h=t(g,p,{t:n(g.namespace),locale:o.language});if(!h.title)throw new Error(`[dndev] llms.txt: published "${i.collection}" record at "${c}" has no title (listCardFields title fields, or first text field, are empty).`);l(d).links.push({title:h.title,url:u,...h.description&&{description:h.description}})}return ls({name:o.name,...o.summary&&{summary:o.summary},sections:[...a.values()]})}export{Kr as buildLlmsTxt,Hr as buildSitemap,Br as clearMetadataCache,$s as default,$s as defineNextConfig,rr as definePostCSSConfig,qr as formatSitemapXml,zr as getMetadataForPath};