@donotdev/core 0.0.46 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE.md +3 -3
  2. package/functions/index.d.ts +11 -166
  3. package/functions/index.js +7 -7
  4. package/i18n/locales/eager/dndev_ar.json +158 -0
  5. package/i18n/locales/eager/dndev_da.json +153 -0
  6. package/i18n/locales/eager/dndev_de.json +158 -0
  7. package/i18n/locales/eager/dndev_en.json +3 -0
  8. package/i18n/locales/eager/dndev_es.json +159 -1
  9. package/i18n/locales/eager/dndev_fr.json +158 -0
  10. package/i18n/locales/eager/dndev_it.json +158 -0
  11. package/i18n/locales/eager/dndev_ja.json +158 -0
  12. package/i18n/locales/eager/dndev_ko.json +158 -0
  13. package/i18n/locales/eager/dndev_nl.json +153 -0
  14. package/i18n/locales/eager/dndev_pt.json +581 -0
  15. package/i18n/locales/eager/dndev_zh.json +581 -0
  16. package/i18n/locales/lazy/ai_en.json +25 -0
  17. package/i18n/locales/lazy/ai_pt.json +25 -0
  18. package/i18n/locales/lazy/ai_zh.json +25 -0
  19. package/i18n/locales/lazy/auth_ar.json +44 -0
  20. package/i18n/locales/lazy/auth_da.json +45 -1
  21. package/i18n/locales/lazy/auth_de.json +44 -0
  22. package/i18n/locales/lazy/auth_en.json +44 -0
  23. package/i18n/locales/lazy/auth_es.json +44 -0
  24. package/i18n/locales/lazy/auth_fr.json +44 -0
  25. package/i18n/locales/lazy/auth_it.json +44 -0
  26. package/i18n/locales/lazy/auth_ja.json +44 -0
  27. package/i18n/locales/lazy/auth_ko.json +44 -0
  28. package/i18n/locales/lazy/auth_nl.json +45 -1
  29. package/i18n/locales/lazy/auth_pt.json +192 -0
  30. package/i18n/locales/lazy/auth_zh.json +192 -0
  31. package/i18n/locales/lazy/billing_en.json +11 -0
  32. package/i18n/locales/lazy/billing_pt.json +93 -0
  33. package/i18n/locales/lazy/billing_zh.json +93 -0
  34. package/i18n/locales/lazy/blog_pt.json +9 -0
  35. package/i18n/locales/lazy/blog_zh.json +9 -0
  36. package/i18n/locales/lazy/cookies_pt.json +32 -0
  37. package/i18n/locales/lazy/cookies_zh.json +32 -0
  38. package/i18n/locales/lazy/crud_ar.json +3 -0
  39. package/i18n/locales/lazy/crud_da.json +3 -0
  40. package/i18n/locales/lazy/crud_de.json +3 -0
  41. package/i18n/locales/lazy/crud_en.json +3 -0
  42. package/i18n/locales/lazy/crud_es.json +3 -0
  43. package/i18n/locales/lazy/crud_fr.json +3 -0
  44. package/i18n/locales/lazy/crud_it.json +3 -0
  45. package/i18n/locales/lazy/crud_ja.json +3 -0
  46. package/i18n/locales/lazy/crud_ko.json +3 -0
  47. package/i18n/locales/lazy/crud_nl.json +3 -0
  48. package/i18n/locales/lazy/crud_pt.json +534 -0
  49. package/i18n/locales/lazy/crud_zh.json +534 -0
  50. package/i18n/locales/lazy/homeTemplate_pt.json +52 -0
  51. package/i18n/locales/lazy/homeTemplate_zh.json +52 -0
  52. package/i18n/locales/lazy/legalNotice_pt.json +55 -0
  53. package/i18n/locales/lazy/legalNotice_zh.json +55 -0
  54. package/i18n/locales/lazy/oauth_pt.json +11 -0
  55. package/i18n/locales/lazy/oauth_zh.json +11 -0
  56. package/i18n/locales/lazy/privacy_pt.json +178 -0
  57. package/i18n/locales/lazy/privacy_zh.json +178 -0
  58. package/i18n/locales/lazy/terms_pt.json +200 -0
  59. package/i18n/locales/lazy/terms_zh.json +200 -0
  60. package/index.d.ts +2834 -4778
  61. package/index.js +44 -516
  62. package/next/index.d.ts +349 -176
  63. package/next/index.js +84 -61
  64. package/package.json +10 -6
  65. package/server.d.ts +1994 -2847
  66. package/server.js +1 -372
  67. package/vite/index.d.ts +298 -181
  68. package/vite/index.js +91 -76
package/next/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import*as b from"node:fs";import"node:fs";import{createRequire as Zt}from"node:module";import{resolve as ge,join as q,dirname as Y,relative as Be,normalize as Qt,sep as He,extname as es}from"node:path";import{fileURLToPath as ts}from"node:url";import ss from"fast-glob";var pe={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var I={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},W={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"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},_e={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ue={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},de={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},O={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${de.SOURCE_EAGER}/*_*.json`],lazy:[`${de.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},me={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async"],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"]},Ge=["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 Ae={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 se={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]},ve={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:[]},Ee=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ue={base:{absolute:!0,onlyFiles:!0,ignore:O.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...O.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...O.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:O.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:O.globalIgnore}};function We(i,e=null){let t=O[i];if(!t)throw new Error(`Unknown pattern type: ${i}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function be(i){return Ue[i]||Ue.base}var re={getGlobOptionsFor:be||void 0,SCAN_PATTERNS:O||void 0,getPatternsFor:We||void 0,I18N_PATHS:de||void 0},R={error:(i,e)=>{},warn:(i,e)=>{},info:i=>{}};function Ve(i,e){return i().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Je={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"},P=class i{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return i._instance||(i._instance=new i(e)),i._instance}static _reset(){i._instance=null}constructor(e={}){if(i._instance)return i._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,i._instance=this}normalizePath(e){if(!e)return"";try{return Qt(e).split(He).join("/")}catch{return String(e).split(He).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Be(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(Y(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Zt(q(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/",""),a=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(a))return a;if(["auth","billing","crud","oauth"].includes(n)){let l=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(l))return l}if(n==="firebase"){let l=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(l))return l}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=ge(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=ge(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=ge(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=b.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:es(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 b.promises.readFile(e);let n=await b.promises.readFile(e,r),a=this.stripBom(n);return o==="json"?JSON.parse(a):a}catch(n){return this.options.debug&&R.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 b.readFileSync(e);let n=b.readFileSync(e,r),a=this.stripBom(n);return o==="json"?JSON.parse(a):a}catch(n){return this.options.debug&&R.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:a=!1}=s,l=this.normalizePath(e),p=this.normalizePath(Y(l)),c=this.pathExists(l);if(c&&!o)return a&&R.info(`Skipping existing file: ${l}`),!1;if(n)return R.info(`[DRY RUN] Would write file: ${l}`),!0;try{await b.promises.mkdir(p,{recursive:!0})}catch(h){if(h?.code!=="EEXIST")throw h}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await Ve(async()=>(Buffer.isBuffer(g)?await b.promises.writeFile(l,g):await b.promises.writeFile(l,g,"utf8"),a&&R.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:a=!1}=s,l=this.normalizePath(e),p=this.normalizePath(Y(l)),c=this.pathExists(l);if(c&&!o)return a&&R.info(`Skipping existing file: ${l}`),!1;if(n)return R.info(`[DRY RUN] Would write file: ${l}`),!0;try{b.mkdirSync(p,{recursive:!0})}catch(h){if(h?.code!=="EEXIST")throw h}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return Buffer.isBuffer(g)?b.writeFileSync(l,g):b.writeFileSync(l,g,"utf8"),a&&R.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(h){throw new Error(`Failed to write file: ${l}: ${h instanceof Error?h.message:String(h)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!r)return n&&R.info(`Skipping existing file: ${a}`),!1;if(o)return R.info(`[DRY RUN] Would copy file: ${a}`),!0;let p=this.normalizePath(Y(a));try{await b.promises.mkdir(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await Ve(async()=>(await b.promises.copyFile(e,a),n&&R.info(`${l?"Updated":"Created"} file: ${a}`),!0),`Failed to copy file from ${e} to ${a}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!r)return n&&R.info(`Skipping existing file: ${a}`),!1;if(o)return R.info(`[DRY RUN] Would copy file: ${a}`),!0;let p=this.normalizePath(Y(a));try{b.mkdirSync(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return b.copyFileSync(e,a),n&&R.info(`${l?"Updated":"Created"} file: ${a}`),!0}catch{return!1}}pathExists(e,t=!1){try{return b.existsSync(e)}catch(s){return t||R.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 b.existsSync(t)||b.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return b.readdirSync(e,t)}catch(s){return this.options.debug&&R.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return b.statSync(e)}catch(t){return this.options.debug&&R.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return b.realpathSync(e)}watch(e,t,s){return b.watch(e,t,s)}lstatSync(e){try{return b.lstatSync(e)}catch(t){return this.options.debug&&R.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await b.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{b.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await b.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){b.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return b.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=q(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(ge(e)),s=this.getAppRoot(),r=Be(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(q(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),a=r.startsWith(n)?r.slice(n.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:re.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([a],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=re.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(q(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await ss(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=re.getGlobOptionsFor?re.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),a=e.framework.map(c=>{let u=this.normalizePath(c);return u.startsWith(n)?u.slice(n.length+1):u}),l=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=a.length>0?await this._globWithNormalization(a,p):[],u=await this._globWithNormalization(l,p);return{frameworkFiles:c,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!re.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=re.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=r,p={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return p.all=[...p.eager,...p.lazy,...p.framework.eager,...p.framework.lazy],p}let n=r,a={framework:o?(n.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(n.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return a.all=[...a.consumer,...a.framework],a}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyFlagModulePath(){let e=Y(ts(import.meta.url));return this.normalizePath(ge(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(q(t,Je.TOOLING)),n=this.normalizePath(q(t,Je.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let a=q(t,"apps");if(this.pathExists(a)&&this.statSync(a)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(q(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(Y(t))===t)return t;let p=this.normalizePath(Y(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function qe({logger:i,debug:e=!1}={}){let t=P.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&&i&&i.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):i&&i.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&i&&i.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let n=t.resolveRepoPath("apps");if(t.pathExists(n))try{let a=process.cwd(),l=t.normalizePath(a);if(l.includes("/apps/")){let p=l.indexOf("/apps/"),u=l.substring(p+6).split("/")[0];if(u){let g=t.resolveRepoPath(`apps/${u}`),h=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(h)&&(r=g,t.setAppRoot(r),s=!0,e&&i&&i.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&i&&i.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}function Ye(i){let e=new Set(Object.keys(se)),t=new Set(["latin"]);for(let o of i||[]){let n=ve[o];if(n)for(let a of n)t.add(a)}let s=[],r=new Set;for(let o of e){let n=se[o];for(let a of t)for(let l of n){let p=`@fontsource/${o}/${a}-${l}.css`,c=`${o}-${a}-${l}-normal`;s.push(p),r.add(c)}}return{imports:s,stems:r,subsets:t,fontStems:e}}function Ne(i){return i.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}import*as F from"@clack/prompts";var j={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 rs(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function L(i,e){return rs()?`${e}${i}${j.reset}`:i}function E(i,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=P.getInstance(),a=null;if(o){let c=n.resolveAppPath(r);n.pathExists(c)||n.mkdir(c),a=n.resolveAppPath(`${r}/${i.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${i} Log Started at ${new Date().toISOString()} ===
2
- `;n.writeSync(a,u)}let l=(c,u,g)=>{if(a){let h=new Date().toISOString(),f=g.length>0?" "+g.map(y=>typeof y=="object"?JSON.stringify(y,null,2):String(y)).join(" "):"",m=`${h} [${c}] ${u}${f}
3
- `;n.appendFile(a,m)}},p=(c,u)=>{if(u.length===0)return c;let g=u.map(h=>typeof h=="object"?JSON.stringify(h,null,2):String(h)).join(" ");return`${c} ${g}`};return{debug:(c,...u)=>{e&&(o?l("DEBUG",c,u):F.log.message(L(p(c,u),j.gray)))},verbose:(c,...u)=>{t&&(o?l("VERBOSE",c,u):F.log.message(p(c,u)))},info:(c,...u)=>{o?l("INFO",c,u):F.log.info(L(p(c,u),j.brightCyan))},warn:(c,...u)=>{e&&o?l("WARN",c,u):F.log.warn(L(p(c,u),j.brightYellow))},error:(c,...u)=>{e&&o?l("ERROR",c,u):F.log.error(L(p(c,u),j.brightRed))},success:(c,...u)=>{e&&o?l("SUCCESS",c,u):F.log.success(L(p(c,u),j.brightGreen))},when:(c,u="debug")=>(g,...h)=>{if(c){let f=p(g,h);switch(u){case"verbose":t&&(F.log.message(f),l("VERBOSE",g,h));break;case"info":F.log.info(L(f,j.brightCyan)),l("INFO",g,h);break;case"warn":F.log.warn(L(f,j.brightYellow)),l("WARN",g,h);break;case"error":F.log.error(L(f,j.brightRed)),l("ERROR",g,h);break;case"success":F.log.success(L(f,j.brightGreen)),l("SUCCESS",g,h);break;default:e&&(F.log.message(L(f,j.gray)),l("DEBUG",g,h))}}},getLogFilePath:()=>a}}var T=class i{constructor(e,t={}){if(this.constructor===i)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=E(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 os(i){if(!i)return[];let e=P.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",i);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 a=e.resolvePath(`${n}/package.json`,r),l=e.readSync(a,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[p,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function ns(i){if(!i)return[];let e=P.getInstance();try{let t=e.resolvePath("package.json",i),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 as(i){let e=me.optionalFeatures||[],t=os(i),s=ns(i);return[...new Set([...e,...t,...s])]}function is(i){let e=P.getInstance();try{let t=e.resolvePath("package.json",i),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 ls(i,e,t){if(t.resolvePackage(i,e||void 0))return!0;let s=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.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 a=t.getDirname(r);if(a===r)break;r=a}return!1}function ye(i){let e=as(i),t=[],s=[],r=P.getInstance(),o=is(i);for(let n of e)n.startsWith("@donotdev/")?o.has(n)?s.push(n):t.push(n):o.has(n)&&ls(n,i,r)?s.push(n):t.push(n);return{missing:t,installed:s}}var oe=class i extends T{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:[],...t})}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=be("i18n"),n=r.eager||[],a=r.lazy||[],l=(this.options.additionalPaths||[]).map(v=>{let w=v.endsWith(".json")?v:`${v}/*_*.json`;return this.pathResolver.resolveAppPath(w)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let p=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${a.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),h=(v,w)=>{let S=this.pathResolver.normalizePath(v),$=this.pathResolver.normalizePath(w);return S.startsWith($)?S.slice($.length+1):S},f=n.map(v=>h(v,t)),y=[...a,...l].map(v=>h(v,t)),k=p.map(v=>h(v,s)),x=c.map(v=>h(v,s)),C={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},_=await this.pathResolver._globWithNormalization(f,C),H=await this.pathResolver._globWithNormalization(y,C),K={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(v=>v!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(K.ignore)}`);let D=await this.pathResolver._globWithNormalization(k,K),U=await this.pathResolver._globWithNormalization(x,K);this.logger.debug(`Found ${_.length} eager, ${H.length} lazy, ${D.length} framework eager, ${U.length} framework lazy files`),D.length>0?this.logger.debug(`Framework eager files (first 3): ${D.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),U.length>0?this.logger.debug(`Framework lazy files (first 3): ${U.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let ie=[...new Set([..._,...H,...D,...U])],ee=new Set([..._,...D]),d={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:le}=ye(t),M=new Set(le.filter(v=>v.startsWith("@donotdev/")).map(v=>v.replace("@donotdev/","")));M.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...M].join(", ")}] (packages not installed)`);let G=new Map,V=[...D,...U];for(let v of V){let w=this._processTranslationFile(v,D.includes(v),t);if(w){if(M.has(w.namespace))continue;let S=`${w.namespace}_${w.language}`;G.set(S,w),d.allNamespaces.add(w.namespace),d.supportedLanguages.add(w.language),D.includes(v)&&d.eagerNamespaces.add(w.namespace)}}let z=new Set;for(let v of ie){if(V.includes(v))continue;let w=this._processTranslationFile(v,ee.has(v),t);if(w){let{namespace:S,language:$,importPath:A,content:te}=w,J=`${w.namespace}_${w.language}`;if(G.has(J)){let Re=G.get(J);w.content=this._mergeTranslations(Re.content,te)}d.allNamespaces.add(S),d.supportedLanguages.add($),z.add($),ee.has(v)&&d.eagerNamespaces.add(S),d.mapping[S]||(d.mapping[S]={}),d.mapping[S][$]=A,w.content&&(d.content[S]||(d.content[S]={}),d.content[S][$]=w.content),d.files.push({path:v,relativePath:this.pathResolver.getRelativePath(v),namespace:S,language:$,eager:ee.has(v),size:w.content?JSON.stringify(w.content).length:0})}}for(let[v,w]of G){let S=v.lastIndexOf("_"),$=v.slice(0,S),A=v.slice(S+1);z.size>0&&!z.has(A)||(!d.mapping[$]||!d.mapping[$][A])&&(d.mapping[$]||(d.mapping[$]={}),d.mapping[$][A]=w.importPath,d.content[$]||(d.content[$]={}),d.content[$][A]=w.content,d.files.push({path:w.absolutePath,relativePath:this.pathResolver.getRelativePath(w.absolutePath),namespace:$,language:A,eager:d.eagerNamespaces.has($),size:w.content?JSON.stringify(w.content).length:0}))}let X=z.size>0?[...z].sort():[this.options.fallbackLanguage],ce=[...new Set(X.map(v=>i.LANGUAGE_FLAG_OVERRIDES[v]||v))];return{mapping:d.mapping,content:d.content,eagerNamespaces:[...d.eagerNamespaces].sort(),allNamespaces:[...d.allNamespaces].sort(),supportedLanguages:X,fallbackLanguage:this.options.fallbackLanguage,flagCodes:ce,files:d.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[i.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,a=r.match(/^(.+)_([^_.]+)\.json$/);if(!a)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,n]=a,!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 cs=3,Ke="dndev-font-preloads.json";function Xe({pathResolver:i,debug:e=!1}){let t=E("font-preload-next",e,!1);return{apply(s){s.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(r,o)=>{if(r.compiler.isChild()||r.compiler.name?.includes("server"))return o();try{if(!i.getAppRoot())return o();let l=["en"];try{let y=await new oe(i,{fallbackLanguage:"en"}).discoverTranslations();y?.supportedLanguages?.length&&(l=y.supportedLanguages)}catch{}let c=Ye(l).stems,u=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",g=[];for(let[m]of Object.entries(r.assets)){if(!m.endsWith(".woff2"))continue;let y=m.toLowerCase();if(Array.from(c).some(k=>y.includes(k))){let k=u?`${u}/${m}`:`/${m}`;if(g.push({href:k,type:"font/woff2"}),g.length>=cs)break}}let h=i.resolveAppPath("public");if(!i.pathExists(h))try{i.ensureDirSync(h)}catch(m){return t.debug(`Font preload: could not create public dir: ${m?.message}`),o()}let f=i.resolvePath(Ke,h);i.writeSync(f,JSON.stringify(g,null,0),{overwrite:!0}),t.debug(`Font preload: wrote ${g.length} entries to ${Ke}`)}catch(a){t.debug(`Font preload manifest: ${a?.message}`)}o()})}}}function Ze({postcssImport:i,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?i({resolve:s}):i,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var Qe={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function ps(i){return(e,t)=>{Qe[e]&&(e=Qe[e]);let s=i.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=i.resolveFrameworkPackage(r,t);if(n){if(o){let l=i.resolvePath(o,n);if(i.pathExists(l))return l;let p=l+".css";if(i.pathExists(p))return p}let a=i.resolvePath("index.css",n);if(i.pathExists(a))return a}}return i.resolvePath(e,t)}}async function us(){let[i,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=P.getInstance();return Ze({postcssImport:i,postcssNesting:e,autoprefixer:t,resolve:ps(s)})}function et(){try{let i=P.getInstance(),e=i.resolveAppPath("package.json"),t=i.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(o=>o.startsWith("@donotdev/")).filter(o=>!me.buildTimePackages.includes(o)).sort()}catch{return[]}}function B(i){return i&&typeof i=="object"&&!Array.isArray(i)}var tt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function st({originalWebpack:i,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],logger:o,debug:n}){return(a,l)=>{let{dev:p,isServer:c,webpack:u}=l;p&&!c&&(a.infrastructureLogging={level:"error"},a.stats={...a.stats,logging:"error",loggingTrace:!1},a.ignoreWarnings=[...a.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let g=a.module?.rules?.find(h=>h.test?.test?.(".svg"));g&&(g.exclude=/\.svg$/i),a.module=a.module||{},a.module.rules=a.module.rules||[],a.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),a.resolve=a.resolve||{},a.resolve.alias={...a.resolve.alias,...tt},u?.IgnorePlugin&&a.plugins.push(new u.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=P.getInstance();a.plugins.push(Xe({pathResolver:h,debug:n}))}catch(h){o.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(o.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),o.info(`\u2705 Including features: ${t.join(", ")}`),a.externals=a.externals||[],Array.isArray(a.externals))a.externals.push(...e);else{let h=a.externals;a.externals=(f,m,y)=>e.includes(m)?y(null,"commonjs "+m):typeof h=="function"?h(f,m,y):y()}if(s.length>0&&u?.NormalModuleReplacementPlugin){let f=P.getInstance().getEmptyCjsModulePath(),m=s.map(k=>k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),y=new RegExp(`^(${m.join("|")})(\\/|$)`);a.plugins.push(new u.NormalModuleReplacementPlugin(y,f)),n&&o.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&u?.NormalModuleReplacementPlugin){let f=P.getInstance().getEmptyFlagModulePath(),m=new Set(r.map(y=>y.toUpperCase()));a.plugins.push(new u.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,y=>{let k=y.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);k&&k[1].toUpperCase()!=="BASE"&&!m.has(k[1].toUpperCase())&&(y.request=f)})),n&&o.debug(`Flag filter: allowing ${m.size} flags, aliasing rest to empty component`)}return i?i(a,l):a}}function rt({originalRewrites:i,handlers:e,logger:t}){return async function(){try{let s=i?await i():[],o=e.filter(a=>a?.getAPIRewrites).map(a=>a.getAPIRewrites()).reduce((a,l)=>(l?.beforeFiles&&a.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&a.afterFiles.push(...l.afterFiles),l?.fallback&&a.fallback.push(...l.fallback),a),{beforeFiles:[],afterFiles:[],fallback:[]}),n={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]};return n.beforeFiles.length===0&&n.afterFiles.length===0&&n.fallback.length===0?null:n}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),null}}}function ot({routeResult:i,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:a,discoveredPackages:l,webpackConfig:p,rewritesConfig:c,missingOptionalDeps:u,flagCodes:g=[],pathResolver:h,env:f,logger:m}){let y=a?.output==="export",x=a?.distDir||".next";return{transpilePackages:[...l,...u||[]],...B(a)?a:(m.warn("restNextConfig is not a plain object:",a),{}),serverExternalPackages:(a?.serverExternalPackages||a?.serverComponentsExternalPackages||[]).filter(_=>!_.startsWith("@donotdev/")&&!u?.includes(_)),turbopack:{...a?.turbopack||{},root:a?.turbopack?.root||h.getRepoRoot(),resolveAlias:{...a?.turbopack?.resolveAlias||{},...tt,...u?.length>0?Object.fromEntries(u.flatMap(_=>[[_,"@donotdev/core/empty"],[`${_}/*`,"@donotdev/core/empty"]])):{}}},distDir:x,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...B(i)?i:(m.error(`Route handler config invalid (got ${typeof i}):`,i),{}),...B(e)?e:(m.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...B(t)?t:(m.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...B(s)?s:(m.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...B(r)?r:(m.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...B(o)?o:(m.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...B(n)?n:(m.warn("serverShimConfig returned non-object:",n),{}),webpack:p,...y?{}:{rewrites:async()=>await c()||void 0},env:f,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var we="fonts",Fe="dndev-fonts.css",gs=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,at=/url\(\.\/files\/([^)]+)\)/g;function hs(i){let e=new Set(["latin"]);for(let t of i){let s=ve[t];if(s)for(let r of s)e.add(r)}return e}function fs(i,e){let t=i.resolvePath("src/dndev.css",e),s=i.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 ds(i,e,t,s,r){let o=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
4
- `],n=new Set,a=r&&r.size>0;for(let[l,p]of e){let c=i.resolveFrameworkPackage(`@fontsource/${l}`);if(!c){s.debug(`@fontsource/${l} not found`);continue}let u=!!se[l];if(a&&u)for(let g of r){let h=i.resolvePath(`${g}-${p}.css`,c),f=i.readSync(h,{format:"text"});if(!f)continue;let m=nt(Ne(f),i,c,t,n,s,!0);o.push(m)}else{let g=i.resolvePath(`${p}.css`,c),h=i.readSync(g,{format:"text"});if(!h){s.debug(`Missing: @fontsource/${l}/${p}.css`);continue}let f=nt(h,i,c,t,n,s,!1);o.push(f)}}return{cssChunks:o,copiedFiles:n}}function nt(i,e,t,s,r,o,n){return i.replace(at,(a,l)=>{if(n&&l.endsWith(".woff"))return"url(data:,)";let p=e.resolvePath(`files/${l}`,t);if(!e.pathExists(p))return o.warn(`Font file missing: ${p} \u2014 dropping from CSS`),"url(data:,)";if(!r.has(l)){let u=e.resolvePath(l,s);e.copySync(p,u,{overwrite:!0}),r.add(l)}return`url(/${we}/${l})`})}var ms=/@font-face\s*\{[^}]*\}/g;function vs(i,e,t,s,r){let o=i.resolvePath("dist/dndev.css",e),n=i.readSync(o,{format:"text"});if(!n)return s.debug("dist/dndev.css not found in @donotdev/ui"),{cssChunks:[],copiedFiles:new Set};let a=n.match(ms);if(!a||a.length===0)return s.debug("No @font-face blocks found in dist/dndev.css"),{cssChunks:[],copiedFiles:new Set};let l=r&&r.size>0,p=new Set(Object.keys(se));l&&(a=a.filter(f=>{if(!Array.from(p).some(y=>f.includes(`${y}-`)))return!0;for(let y of r)if(f.includes(`-${y}-`))return!0;return!1}));let c=i.resolvePath("dist/files",e),u=new Set;return{cssChunks:[`/* Auto-generated by @donotdev/core \u2014 do not edit */
5
- `,...a.map(f=>{let m=l&&Array.from(p).some(k=>f.includes(`${k}-`));return(m?Ne(f):f).replace(at,(k,x)=>{if(m&&x.endsWith(".woff"))return"url(data:,)";let C=i.resolvePath(x,c);if(!i.pathExists(C))return s.warn(`Font file missing: ${C} \u2014 dropping from CSS`),"url(data:,)";if(!u.has(x)){let H=i.resolvePath(x,t);i.copySync(C,H,{overwrite:!0}),u.add(x)}return`url(/${we}/${x})`})})],copiedFiles:u}}function it({debug:i=!1,force:e=!1,languages:t}={}){let s=E("font-copy",i,!1),r=P.getInstance(),o=r.resolveAppPath(`public/${Fe}`);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 a=r.resolveAppPath(`public/${we}`);r.ensureDir(a);let l=t?.length?hs(t):null;l&&s.debug(`Font copy: locale-aware filtering \u2014 locales=[${t.join(",")}] subsets=[${[...l].join(",")}]`);let p=fs(r,n),c,u;if(p.length>0?(s.debug(`Monorepo mode: ${p.length} @fontsource imports found`),{cssChunks:c,copiedFiles:u}=ds(r,p,a,s,l)):(s.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:c,copiedFiles:u}=vs(r,n,a,s,l)),u.size===0){s.debug("No font files found to copy");return}r.writeSync(o,c.join(`
6
- `)),s.debug(`Font copy: wrote ${Fe} (${u.size} font files copied)`)}function lt(){let i=P.getInstance(),e=i.resolveAppPath(`public/${Fe}`),t=i.resolveAppPath(`public/${we}`);if(i.pathExists(e))try{i.removeSync(e)}catch{}if(i.pathExists(t))try{i.removeSync(t)}catch{}}var bs=["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"],ys="dndev-config-",ct=".dndev-build";function ws(i){if(!i)return!1;let e=P.getInstance(),t=e.resolveAppPath(ct),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function Ps(i){if(!i)return;let e=P.getInstance(),t=e.resolveAppPath(ct),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s)}catch{}}function pt(i,e){if(!i)return;let t=P.getInstance();for(let r of bs){let o=t.resolveAppPath(r);if(t.pathExists(o))try{t.removeSync(o),e.debug(`Cleaned: ${r}`)}catch{}}lt();let s=t.resolveAppPath("src/config");if(t.pathExists(s))try{let r=t.readdirSync(s);for(let o of r)if(o.startsWith(ys)&&o.endsWith(".js"))try{let n=t.resolvePath(o,s);t.removeSync(n),e.debug(`Cleaned: src/config/${o}`)}catch{}}catch{}}async function ut({routeHandler:i,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:o},n){let a=i?.pathResolver;if(!a)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let l=a.getAppRoot(),p=a.getRepoRoot();if(!l||l===p){n.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(m=>setTimeout(m,0));let f=a.getAppRoot();if(!f||f===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(ws(l)){n.debug("Discoveries already completed this build, skipping");return}let c=Date.now();if(i)try{n.info("\u{1F50D} Starting route discovery...");let m=(await i.generateFiles())?.routes?.length||0;n.info(`\u2705 Routes generated: ${m} routes found`),m===0&&n.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(f){throw n.error(`\u274C Route generation failed: ${f.message}`),f.stack&&n.error(`Stack: ${f.stack}`),f}else n.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let u=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:o}],g;for(let{name:f,handler:m}of u)try{let y=await m.generateFiles();f==="I18n"&&y?.supportedLanguages?.length&&(g=y.supportedLanguages)}catch(y){n.debug(`${f} generation failed: ${y.message}`)}try{Ss(a,n)}catch(f){n.debug(`Env config generation failed (non-critical): ${f.message}`)}try{it({languages:g})}catch(f){n.debug(`Font copy failed (non-critical): ${f.message}`)}let h=Date.now()-c;n.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`),Ps(l)}function Ss(i,e){let t={};for(let[n,a]of Object.entries(process.env))n.startsWith("NEXT_PUBLIC_")&&a!==void 0&&(t[n]=a);let s=`// Auto-generated DnDev env config by @donotdev/config
1
+ import*as b from"node:fs";import"node:fs";import{createRequire as cs}from"node:module";import{resolve as ge,join as X,dirname as Z,relative as Qe,normalize as ps,sep as et,extname as us}from"node:path";import{fileURLToPath as gs}from"node:url";import hs from"fast-glob";var pe={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var L={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},q={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"},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"}},Ee={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ue={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},ve={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:[`${ve.SOURCE_EAGER}/*_*.json`],lazy:[`${ve.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/**"]},be={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","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"]},Xe=["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 Ne={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 oe={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]},ye={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:[]},Fe=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ke={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 Ze(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 we(a){return Ke[a]||Ke.base}var ne={getGlobOptionsFor:we||void 0,SCAN_PATTERNS:z||void 0,getPatternsFor:Ze||void 0,I18N_PATHS:ve||void 0},_={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function tt(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var st={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"},y=class a{static _instance=null;options;_repoRoot;_appRoot=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 ps(e).split(et).join("/")}catch{return String(e).split(et).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Qe(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(Z(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=cs(X(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/",""),i=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(n)){let l=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(l))return l}if(n==="firebase"){let l=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(l))return l}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=ge(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=ge(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=ge(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=b.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:us(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 b.promises.readFile(e);let n=await b.promises.readFile(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&_.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 b.readFileSync(e);let n=b.readFileSync(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&_.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:i=!1}=s,l=this.normalizePath(e),p=this.normalizePath(Z(l)),c=this.pathExists(l);if(c&&!o)return i&&_.info(`Skipping existing file: ${l}`),!1;if(n)return _.info(`[DRY RUN] Would write file: ${l}`),!0;try{await b.promises.mkdir(p,{recursive:!0})}catch(h){if(h?.code!=="EEXIST")throw h}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await tt(async()=>(Buffer.isBuffer(g)?await b.promises.writeFile(l,g):await b.promises.writeFile(l,g,"utf8"),i&&_.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:i=!1}=s,l=this.normalizePath(e),p=this.normalizePath(Z(l)),c=this.pathExists(l);if(c&&!o)return i&&_.info(`Skipping existing file: ${l}`),!1;if(n)return _.info(`[DRY RUN] Would write file: ${l}`),!0;try{b.mkdirSync(p,{recursive:!0})}catch(h){if(h?.code!=="EEXIST")throw h}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return Buffer.isBuffer(g)?b.writeFileSync(l,g):b.writeFileSync(l,g,"utf8"),i&&_.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(h){throw new Error(`Failed to write file: ${l}: ${h instanceof Error?h.message:String(h)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return n&&_.info(`Skipping existing file: ${i}`),!1;if(o)return _.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{await b.promises.mkdir(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await tt(async()=>(await b.promises.copyFile(e,i),n&&_.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return n&&_.info(`Skipping existing file: ${i}`),!1;if(o)return _.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{b.mkdirSync(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return b.copyFileSync(e,i),n&&_.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return b.existsSync(e)}catch(s){return t||_.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 b.existsSync(t)||b.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return b.readdirSync(e,t)}catch(s){return this.options.debug&&_.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return b.statSync(e)}catch(t){return this.options.debug&&_.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return b.realpathSync(e)}watch(e,t,s){return b.watch(e,t,s)}lstatSync(e){try{return b.lstatSync(e)}catch(t){return this.options.debug&&_.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await b.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{b.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await b.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){b.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return b.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=X(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(ge(e)),s=this.getAppRoot(),r=Qe(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(X(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),i=r.startsWith(n)?r.slice(n.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:ne.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ne.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(X(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await hs(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=ne.getGlobOptionsFor?ne.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),i=e.framework.map(c=>{let u=this.normalizePath(c);return u.startsWith(n)?u.slice(n.length+1):u}),l=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=i.length>0?await this._globWithNormalization(i,p):[],u=await this._globWithNormalization(l,p);return{frameworkFiles:c,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ne.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=ne.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=r,p={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return p.all=[...p.eager,...p.lazy,...p.framework.eager,...p.framework.lazy],p}let n=r,i={framework:o?(n.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(n.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyFlagModulePath(){let e=Z(gs(import.meta.url));return this.normalizePath(ge(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(X(t,st.TOOLING)),n=this.normalizePath(X(t,st.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let i=X(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(X(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(Z(t))===t)return t;let p=this.normalizePath(Z(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function rt({logger:a,debug:e=!1}={}){let t=y.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 i=process.cwd(),l=t.normalizePath(i);if(l.includes("/apps/")){let p=l.indexOf("/apps/"),u=l.substring(p+6).split("/")[0];if(u){let g=t.resolveRepoPath(`apps/${u}`),h=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(h)&&(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}}function ot(a){let e=new Set(Object.keys(oe)),t=new Set(["latin"]);for(let o of a||[]){let n=ye[o];if(n)for(let i of n)t.add(i)}let s=[],r=new Set;for(let o of e){let n=oe[o];for(let i of t)for(let l of n){let p=`@fontsource/${o}/${i}-${l}.css`,c=`${o}-${i}-${l}-normal`;s.push(p),r.add(c)}}return{imports:s,stems:r,subsets:t,fontStems:e}}function Ce(a){return a.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}import*as O from"@clack/prompts";var B={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 fs(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function V(a,e){return fs()?`${e}${a}${B.reset}`:a}function C(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=y.getInstance(),i=null;if(o){let c=n.resolveAppPath(r);n.pathExists(c)||n.mkdir(c),i=n.resolveAppPath(`${r}/${a.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${a} Log Started at ${new Date().toISOString()} ===
2
+ `;n.writeSync(i,u)}let l=(c,u,g)=>{if(i){let h=new Date().toISOString(),f=g.length>0?" "+g.map(d=>typeof d=="object"?JSON.stringify(d,null,2):String(d)).join(" "):"",m=`${h} [${c}] ${u}${f}
3
+ `;n.appendFile(i,m)}},p=(c,u)=>{if(u.length===0)return c;let g=u.map(h=>typeof h=="object"?JSON.stringify(h,null,2):String(h)).join(" ");return`${c} ${g}`};return{debug:(c,...u)=>{e&&(o?l("DEBUG",c,u):O.log.message(V(p(c,u),B.gray)))},verbose:(c,...u)=>{t&&(o?l("VERBOSE",c,u):O.log.message(p(c,u)))},info:(c,...u)=>{o?l("INFO",c,u):O.log.info(V(p(c,u),B.brightCyan))},warn:(c,...u)=>{e&&o?l("WARN",c,u):O.log.warn(V(p(c,u),B.brightYellow))},error:(c,...u)=>{e&&o?l("ERROR",c,u):O.log.error(V(p(c,u),B.brightRed))},success:(c,...u)=>{e&&o?l("SUCCESS",c,u):O.log.success(V(p(c,u),B.brightGreen))},when:(c,u="debug")=>(g,...h)=>{if(c){let f=p(g,h);switch(u){case"verbose":t&&(O.log.message(f),l("VERBOSE",g,h));break;case"info":O.log.info(V(f,B.brightCyan)),l("INFO",g,h);break;case"warn":O.log.warn(V(f,B.brightYellow)),l("WARN",g,h);break;case"error":O.log.error(V(f,B.brightRed)),l("ERROR",g,h);break;case"success":O.log.success(V(f,B.brightGreen)),l("SUCCESS",g,h);break;default:e&&(O.log.message(V(f,B.gray)),l("DEBUG",g,h))}}},getLogFilePath:()=>i}}var U=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=C(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 ds(a){if(!a)return[];let e=y.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 i=e.resolvePath(`${n}/package.json`,r),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[p,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function ms(a){if(!a)return[];let e=y.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 vs(a){let e=be.optionalFeatures||[],t=ds(a),s=ms(a);return[...new Set([...e,...t,...s])]}function bs(a){let e=y.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 ys(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 i=t.getDirname(r);if(i===r)break;r=i}return!1}function Pe(a){let e=vs(a),t=[],s=[],r=y.getInstance(),o=bs(a);for(let n of e)n.startsWith("@donotdev/")?o.has(n)?s.push(n):t.push(n):o.has(n)&&ys(n,a,r)?s.push(n):t.push(n);return{missing:t,installed:s}}var ae=class a extends U{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:[],...t})}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=we("i18n"),n=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(v=>{let P=v.endsWith(".json")?v:`${v}/*_*.json`;return this.pathResolver.resolveAppPath(P)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let p=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${i.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),h=(v,P)=>{let x=this.pathResolver.normalizePath(v),R=this.pathResolver.normalizePath(P);return x.startsWith(R)?x.slice(R.length+1):x},f=n.map(v=>h(v,t)),d=[...i,...l].map(v=>h(v,t)),$=p.map(v=>h(v,s)),k=c.map(v=>h(v,s)),N={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},T=await this.pathResolver._globWithNormalization(f,N),E=await this.pathResolver._globWithNormalization(d,N),W={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(v=>v!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(W.ignore)}`);let I=await this.pathResolver._globWithNormalization($,W),J=await this.pathResolver._globWithNormalization(k,W);this.logger.debug(`Found ${T.length} eager, ${E.length} lazy, ${I.length} framework eager, ${J.length} framework lazy files`),I.length>0?this.logger.debug(`Framework eager files (first 3): ${I.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 re=[...new Set([...T,...E,...I,...J])],Q=new Set([...T,...I]),w={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:S}=Pe(t),ee=new Set(S.filter(v=>v.startsWith("@donotdev/")).map(v=>v.replace("@donotdev/","")));ee.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...ee].join(", ")}] (packages not installed)`);let M=new Map,K=[...I,...J];for(let v of K){let P=this._processTranslationFile(v,I.includes(v),t);if(P){if(ee.has(P.namespace))continue;let x=`${P.namespace}_${P.language}`;M.set(x,P),w.allNamespaces.add(P.namespace),w.supportedLanguages.add(P.language),I.includes(v)&&w.eagerNamespaces.add(P.namespace)}}let H=new Set;for(let v of re){if(K.includes(v))continue;let P=this._processTranslationFile(v,Q.has(v),t);if(P){let{namespace:x,language:R,importPath:j,content:te}=P,me=`${P.namespace}_${P.language}`;if(M.has(me)){let Ae=M.get(me);P.content=this._mergeTranslations(Ae.content,te)}w.allNamespaces.add(x),w.supportedLanguages.add(R),H.add(R),Q.has(v)&&w.eagerNamespaces.add(x),w.mapping[x]||(w.mapping[x]={}),w.mapping[x][R]=j,P.content&&(w.content[x]||(w.content[x]={}),w.content[x][R]=P.content),w.files.push({path:v,relativePath:this.pathResolver.getRelativePath(v),namespace:x,language:R,eager:Q.has(v),size:P.content?JSON.stringify(P.content).length:0})}}for(let[v,P]of M){let x=v.lastIndexOf("_"),R=v.slice(0,x),j=v.slice(x+1);H.size>0&&!H.has(j)||(!w.mapping[R]||!w.mapping[R][j])&&(w.mapping[R]||(w.mapping[R]={}),w.mapping[R][j]=P.importPath,w.content[R]||(w.content[R]={}),w.content[R][j]=P.content,w.files.push({path:P.absolutePath,relativePath:this.pathResolver.getRelativePath(P.absolutePath),namespace:R,language:j,eager:w.eagerNamespaces.has(R),size:P.content?JSON.stringify(P.content).length:0}))}let F=H.size>0?[...H].sort():[this.options.fallbackLanguage],G=[...new Set(F.map(v=>a.LANGUAGE_FLAG_OVERRIDES[v]||v))];return{mapping:w.mapping,content:w.content,eagerNamespaces:[...w.eagerNamespaces].sort(),allNamespaces:[...w.allNamespaces].sort(),supportedLanguages:F,fallbackLanguage:this.options.fallbackLanguage,flagCodes:G,files:w.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,i=r.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,n]=i,!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 ws=3,nt="dndev-font-preloads.json";function at({pathResolver:a,debug:e=!1}){let t=C("font-preload-next",e,!1);return{apply(s){s.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(r,o)=>{if(r.compiler.isChild()||r.compiler.name?.includes("server"))return o();try{if(!a.getAppRoot())return o();let l=["en"];try{let d=await new ae(a,{fallbackLanguage:"en"}).discoverTranslations();d?.supportedLanguages?.length&&(l=d.supportedLanguages)}catch{}let c=ot(l).stems,u=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",g=[];for(let[m]of Object.entries(r.assets)){if(!m.endsWith(".woff2"))continue;let d=m.toLowerCase();if(Array.from(c).some($=>d.includes($))){let $=u?`${u}/${m}`:`/${m}`;if(g.push({href:$,type:"font/woff2"}),g.length>=ws)break}}let h=a.resolveAppPath("public");if(!a.pathExists(h))try{a.ensureDirSync(h)}catch(m){return t.debug(`Font preload: could not create public dir: ${m?.message}`),o()}let f=a.resolvePath(nt,h);a.writeSync(f,JSON.stringify(g,null,0),{overwrite:!0}),t.debug(`Font preload: wrote ${g.length} entries to ${nt}`)}catch(i){t.debug(`Font preload manifest: ${i?.message}`)}o()})}}}function it({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 lt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Ps(a){return(e,t)=>{lt[e]&&(e=lt[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 l=a.resolvePath(o,n);if(a.pathExists(l))return l;let p=l+".css";if(a.pathExists(p))return p}let i=a.resolvePath("index.css",n);if(a.pathExists(i))return i}}return a.resolvePath(e,t)}}async function $s(){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=y.getInstance();return it({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:Ps(s)})}function Y(a){return a&&typeof a=="object"&&!Array.isArray(a)}var ct={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function pt({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],logger:o,debug:n}){return(i,l)=>{let{dev:p,isServer:c,webpack:u}=l;p&&!c&&(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 g=i.module?.rules?.find(h=>h.test?.test?.(".svg"));g&&(g.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.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...ct},u?.IgnorePlugin&&i.plugins.push(new u.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=y.getInstance();i.plugins.push(at({pathResolver:h,debug:n}))}catch(h){o.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(o.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),o.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=(f,m,d)=>e.includes(m)?d(null,"commonjs "+m):typeof h=="function"?h(f,m,d):d()}if(s.length>0&&u?.NormalModuleReplacementPlugin){let f=y.getInstance().getEmptyCjsModulePath(),m=s.map($=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),d=new RegExp(`^(${m.join("|")})(\\/|$)`);i.plugins.push(new u.NormalModuleReplacementPlugin(d,f)),n&&o.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&u?.NormalModuleReplacementPlugin){let f=y.getInstance().getEmptyFlagModulePath(),m=new Set(r.map(d=>d.toUpperCase()));i.plugins.push(new u.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,d=>{let $=d.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);$&&$[1].toUpperCase()!=="BASE"&&!m.has($[1].toUpperCase())&&(d.request=f)})),n&&o.debug(`Flag filter: allowing ${m.size} flags, aliasing rest to empty component`)}return a?a(i,l):i}}function ut({originalRewrites:a,handlers:e,logger:t}){return async function(){try{let s=a?await a():[],o=e.filter(i=>i?.getAPIRewrites).map(i=>i.getAPIRewrites()).reduce((i,l)=>(l?.beforeFiles&&i.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&i.afterFiles.push(...l.afterFiles),l?.fallback&&i.fallback.push(...l.fallback),i),{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 gt({originalRedirects:a,seoRedirects:e,logger:t}){return async function(){try{let s=a?await a():[],r=(e||[]).map(({from:l,to:p,permanent:c})=>({source:l,destination:p,permanent:c!==!1})),o=[],n=new Set;for(let l of r){let p=l.source.replace(/\/+$/,"")||"/",c=l.destination.replace(/\/+$/,"")||"/";if(p===c){t.warn(`Redirect loop detected: ${l.source} \u2192 ${l.destination} (skipped)`);continue}if(!l.source.startsWith("/")){t.warn(`Redirect source must start with /: "${l.source}" (skipped)`);continue}if(n.has(p)){t.warn(`Duplicate redirect source: "${l.source}" (skipped)`);continue}n.add(p),o.push(l)}let i=[...Array.isArray(s)?s:[],...o];return i.length===0?[]:(t.info(` \u{1F4CE} ${i.length} redirect${i.length>1?"s":""} configured`),i)}catch(s){return t.error(`Failed to merge redirects: ${s.message}`),[]}}}function ht({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:i,discoveredPackages:l,webpackConfig:p,rewritesConfig:c,redirectsConfig:u,missingOptionalDeps:g,flagCodes:h=[],pathResolver:f,env:m,logger:d}){let $=i?.output==="export",N=i?.distDir||".next";return{transpilePackages:[...l,...g||[]],...Y(i)?i:(d.warn("restNextConfig is not a plain object:",i),{}),serverExternalPackages:(i?.serverExternalPackages||i?.serverComponentsExternalPackages||[]).filter(E=>!E.startsWith("@donotdev/")&&!g?.includes(E)),turbopack:{...i?.turbopack||{},root:i?.turbopack?.root||f.getRepoRoot(),resolveAlias:{...i?.turbopack?.resolveAlias||{},...ct,...g?.length>0?Object.fromEntries(g.flatMap(E=>[[E,"@donotdev/core/empty"],[`${E}/*`,"@donotdev/core/empty"]])):{}}},distDir:N,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...Y(a)?a:(d.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...Y(e)?e:(d.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...Y(t)?t:(d.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...Y(s)?s:(d.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...Y(r)?r:(d.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...Y(o)?o:(d.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...Y(n)?n:(d.warn("serverShimConfig returned non-object:",n),{}),webpack:p,...$?{}:{rewrites:c,...u?{redirects:u}:{}},env:m,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var $e="fonts",De="dndev-fonts.css",Ss=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,dt=/url\(\.\/files\/([^)]+)\)/g;function Rs(a){let e=new Set(["latin"]);for(let t of a){let s=ye[t];if(s)for(let r of s)e.add(r)}return e}function xs(a,e){let t=a.resolvePath("src/dndev.css",e),s=a.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=Ss.exec(s))!==null;)r.push([o[1],o[2]]);return r}function ks(a,e,t,s,r){let o=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
4
+ `],n=new Set,i=r&&r.size>0;for(let[l,p]of e){let c=a.resolveFrameworkPackage(`@fontsource/${l}`);if(!c){s.debug(`@fontsource/${l} not found`);continue}let u=!!oe[l];if(i&&u)for(let g of r){let h=a.resolvePath(`${g}-${p}.css`,c),f=a.readSync(h,{format:"text"});if(!f)continue;let m=ft(Ce(f),a,c,t,n,s,!0);o.push(m)}else{let g=a.resolvePath(`${p}.css`,c),h=a.readSync(g,{format:"text"});if(!h){s.debug(`Missing: @fontsource/${l}/${p}.css`);continue}let f=ft(h,a,c,t,n,s,!1);o.push(f)}}return{cssChunks:o,copiedFiles:n}}function ft(a,e,t,s,r,o,n){return a.replace(dt,(i,l)=>{if(n&&l.endsWith(".woff"))return"url(data:,)";let p=e.resolvePath(`files/${l}`,t);if(!e.pathExists(p))return o.warn(`Font file missing: ${p} \u2014 dropping from CSS`),"url(data:,)";if(!r.has(l)){let u=e.resolvePath(l,s);e.copySync(p,u,{overwrite:!0}),r.add(l)}return`url(/${$e}/${l})`})}var _s=/@font-face\s*\{[^}]*\}/g;function As(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 i=n.match(_s);if(!i||i.length===0)return s.debug("No @font-face blocks found in dist/dndev.css"),{cssChunks:[],copiedFiles:new Set};let l=r&&r.size>0,p=new Set(Object.keys(oe));l&&(i=i.filter(f=>{if(!Array.from(p).some(d=>f.includes(`${d}-`)))return!0;for(let d of r)if(f.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 */
5
+ `,...i.map(f=>{let m=l&&Array.from(p).some($=>f.includes(`${$}-`));return(m?Ce(f):f).replace(dt,($,k)=>{if(m&&k.endsWith(".woff"))return"url(data:,)";let N=a.resolvePath(k,c);if(!a.pathExists(N))return s.warn(`Font file missing: ${N} \u2014 dropping from CSS`),"url(data:,)";if(!u.has(k)){let E=a.resolvePath(k,t);a.copySync(N,E,{overwrite:!0}),u.add(k)}return`url(/${$e}/${k})`})})],copiedFiles:u}}function mt({debug:a=!1,force:e=!1,languages:t}={}){let s=C("font-copy",a,!1),r=y.getInstance(),o=r.resolveAppPath(`public/${De}`);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 i=r.resolveAppPath(`public/${$e}`);r.ensureDir(i);let l=t?.length?Rs(t):null;l&&s.debug(`Font copy: locale-aware filtering \u2014 locales=[${t.join(",")}] subsets=[${[...l].join(",")}]`);let p=xs(r,n),c,u;if(p.length>0?(s.debug(`Monorepo mode: ${p.length} @fontsource imports found`),{cssChunks:c,copiedFiles:u}=ks(r,p,i,s,l)):(s.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:c,copiedFiles:u}=As(r,n,i,s,l)),u.size===0){s.debug("No font files found to copy");return}r.writeSync(o,c.join(`
6
+ `)),s.debug(`Font copy: wrote ${De} (${u.size} font files copied)`)}function vt(){let a=y.getInstance(),e=a.resolveAppPath(`public/${De}`),t=a.resolveAppPath(`public/${$e}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var Es=["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"],Ns="dndev-config-",bt=".dndev-build";function Oe(a){if(!a)return!1;let e=y.getInstance(),t=e.resolveAppPath(bt),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function Fs(a){if(!a)return;let e=y.getInstance(),t=e.resolveAppPath(bt),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s)}catch{}}function Cs(a,e){if(!a)return;let t=y.getInstance();for(let r of Es){let o=t.resolveAppPath(r);if(t.pathExists(o))try{t.removeSync(o),e.debug(`Cleaned: ${r}`)}catch{}}vt();let s=t.resolveAppPath("src/config");if(t.pathExists(s))try{let r=t.readdirSync(s);for(let o of r)if(o.startsWith(Ns)&&o.endsWith(".js"))try{let n=t.resolvePath(o,s);t.removeSync(n),e.debug(`Cleaned: src/config/${o}`)}catch{}}catch{}}async function yt({routeHandler:a,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:o},n){let i=a?.pathResolver;if(!i)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let l=i.getAppRoot(),p=i.getRepoRoot();if(!l||l===p){n.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(m=>setTimeout(m,0));let f=i.getAppRoot();if(!f||f===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Oe(l)){n.debug("Discoveries already completed this build, skipping");return}Fs(l),Cs(l,n);let c=Date.now();if(a)try{n.info("\u{1F50D} Starting route discovery...");let m=(await a.generateFiles())?.routes?.length||0;n.info(`\u2705 Routes generated: ${m} routes found`),m===0&&n.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(f){throw n.error(`\u274C Route generation failed: ${f.message}`),f.stack&&n.error(`Stack: ${f.stack}`),f}else n.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let u=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:o}],g;for(let{name:f,handler:m}of u)try{let d=await m.generateFiles();f==="I18n"&&d?.supportedLanguages?.length&&(g=d.supportedLanguages)}catch(d){n.debug(`${f} generation failed: ${d.message}`)}try{Ds(i,n)}catch(f){n.debug(`Env config generation failed (non-critical): ${f.message}`)}try{mt({languages:g})}catch(f){n.debug(`Font copy failed (non-critical): ${f.message}`)}let h=Date.now()-c;n.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`)}function Ds(a,e){let t={};for(let[n,i]of Object.entries(process.env))n.startsWith("NEXT_PUBLIC_")&&i!==void 0&&(t[n]=i);let s=`// Auto-generated DnDev env config by @donotdev/config
7
7
  // Generated at: ${new Date().toISOString()}
8
8
  // Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
9
9
 
@@ -20,12 +20,12 @@ if (typeof globalThis !== 'undefined') {
20
20
  timestamp: Date.now(),
21
21
  };
22
22
  }
23
- globalThis._DNDEV_CONFIG_.${I.env} = envConfig;
23
+ globalThis._DNDEV_CONFIG_.${L.env} = envConfig;
24
24
  }
25
25
 
26
26
  // Export for compatibility
27
27
  export default envConfig;
28
- `,r=i.resolveAppPath(W.next.configEnv);i.writeSync(r,s);let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}async function gt(i,e,t){if(t)return!1;try{let s=await i.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 he={debug:!1,verbose:process.env.CI!=="true",features:{},generateManifest:!0,routes:{disabled:!1,debug:!1,routingMode:"app",generateMiddleware:!0},themes:{debug:!1},i18n:{debug:!1,fallbackLanguage:"en"},assets:{debug:!1},pwa:{debug:!1},seo:{disabled:!1,debug:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0,debug:!1},discovery:{debug:!1,verbose:!1,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"}};function ht(i,e){let t={...i};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=ht(i[s]||{},e[s]):t[s]=e[s]}),t}function ft(i={}){return ht(he,i)}function dt(i){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:n={},seo:a={},serverShim:l={},discovery:p={},generateManifest:c,debug:u,verbose:g,...h}=i,f=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:u,verbose:g,mode:f,isDev:f==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:n,seoOptions:a,serverShimOptions:l,discoveryOptions:p,nextConfigOptions:h}}var N=class{constructor(e,t={}){this.options={...t,...this.getHandlerDefaults()},this.logger=E(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=P.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...he.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=W.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=I[t]||t;return`// Auto-generated DnDev config by @donotdev/config
28
+ `,r=a.resolveAppPath(q.next.configEnv);a.writeSync(r,s);let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}async function wt(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 Pt={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 he={...Pt,generateManifest:!0,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function $t(a,e){let t={...a};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=$t(a[s]||{},e[s]):t[s]=e[s]}),t}function St(a={}){return $t(he,a)}function Rt(a){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:n={},seo:i={},serverShim:l={},discovery:p={},generateManifest:c,debug:u,verbose:g,...h}=a,f=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:u,verbose:g,mode:f,isDev:f==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:n,seoOptions:i,serverShimOptions:l,discoveryOptions:p,nextConfigOptions:h}}var D=class{constructor(e,t={}){this.options={...t,...this.getHandlerDefaults()},this.logger=C(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=y.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...he.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=q.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=L[t]||t;return`// Auto-generated DnDev config by @donotdev/config
29
29
  // Generated at: ${new Date().toISOString()}
30
30
  // Populates _DNDEV_CONFIG_ with discovery results
31
31
 
@@ -47,7 +47,7 @@ if (typeof globalThis !== 'undefined') {
47
47
 
48
48
  // Export for compatibility
49
49
  export default ${t}Config;
50
- `}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t),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 Pe=class extends T{constructor(e,t={}){super(e,{assets:O.assets.fallback,assetPatterns:O.assets.patterns,frameworkPackage:_e.package,assetsPath:_e.assetsPath,modernFormats:O.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=[],a=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(n=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,p=await this._processAssetFiles(l),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(ue.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(`${ue.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(`${ue.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(ue.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],n=[],a=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){a.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,l),n.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),a.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),a.push(...r.map(c=>c.name));else for(let c of r){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){a.push(c.name);continue}try{let g=p.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;c.format==="ico"?h=await g.toFormat("png").toBuffer():h=await g.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,h),n.push(c.name)}catch(g){this.logger.debug(`Failed to generate ${c.name}: ${g.message}`),a.push(c.name)}}return{generated:n,skipped:a,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:l.message}}}};var De={data:null},Ce=class extends N{constructor(e={}){super(Pe,e)}getHandlerDefaults(){return{manifestPath:W.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
50
+ `}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t),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 Se=class extends U{constructor(e,t={}){super(e,{assets:z.assets.fallback,assetPatterns:z.assets.patterns,frameworkPackage:Ee.package,assetsPath:Ee.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=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(n=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,p=await this._processAssetFiles(l),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(ue.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(`${ue.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(`${ue.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(ue.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],n=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){i.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,l),n.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),i.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(c=>c.name));else for(let c of r){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){i.push(c.name);continue}try{let g=p.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;c.format==="ico"?h=await g.toFormat("png").toBuffer():h=await g.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,h),n.push(c.name)}catch(g){this.logger.debug(`Failed to generate ${c.name}: ${g.message}`),i.push(c.name)}}return{generated:n,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:l.message}}}};var Ie={data:null},Te=class extends D{constructor(e={}){super(Se,e)}getHandlerDefaults(){return{manifestPath:q.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
51
51
  // Generated at: ${new Date().toISOString()}
52
52
  // Populates _DNDEV_CONFIG_ with discovery results
53
53
 
@@ -64,7 +64,7 @@ if (typeof globalThis !== 'undefined') {
64
64
  timestamp: Date.now(),
65
65
  };
66
66
  }
67
- globalThis._DNDEV_CONFIG_.${I.assets} = {
67
+ globalThis._DNDEV_CONFIG_.${L.assets} = {
68
68
  mapping: assetConfig.manifest,
69
69
  logoSvgContent: ${JSON.stringify(t)},
70
70
  manifest: {
@@ -76,7 +76,7 @@ if (typeof globalThis !== 'undefined') {
76
76
 
77
77
  // Export for compatibility
78
78
  export default assetConfig;
79
- `}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&&(De.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=>` {
79
+ `}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&&(Ie.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=>` {
80
80
  path: '${o.path}',
81
81
  type: '${o.type}',
82
82
  format: '${o.format}',
@@ -123,7 +123,7 @@ ${t}
123
123
  export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
124
124
 
125
125
  export default imageConfigs;
126
- `}};function mt(i={}){return new Ce(i)}var Oe=class extends N{constructor(e={}){super(oe,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...he.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
126
+ `}};function xt(a={}){return new Te(a)}var Me=class extends D{constructor(e={}){super(ae,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...he.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
127
127
  // Generated at: ${new Date().toISOString()}
128
128
  // Populates _DNDEV_CONFIG_ with discovery results
129
129
 
@@ -165,12 +165,12 @@ if (typeof globalThis !== 'undefined') {
165
165
  timestamp: Date.now(),
166
166
  };
167
167
  }
168
- globalThis._DNDEV_CONFIG_.${I.i18n} = i18nConfig;
168
+ globalThis._DNDEV_CONFIG_.${L.i18n} = i18nConfig;
169
169
  }
170
170
 
171
171
  // Export for compatibility
172
172
  export default i18nConfig;
173
- `}};function vt(i={}){return new Oe(i)}var Se=class extends T{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),a=n.filter(g=>g.type==="manifest"||g.type==="service-worker");o.push(...a);let l=n.filter(g=>g.type==="icon"),p=new Set(o.filter(g=>g.type==="icon").map(g=>g.path)),c=l.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
173
+ `}};function kt(a={}){return new Me(a)}var Re=class extends U{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),i=n.filter(g=>g.type==="manifest"||g.type==="service-worker");o.push(...i);let l=n.filter(g=>g.type==="icon"),p=new Set(o.filter(g=>g.type==="icon").map(g=>g.path)),c=l.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
174
174
  // Generated at ${new Date().toISOString()}
175
175
 
176
176
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
@@ -204,20 +204,20 @@ self.addEventListener('message', (event) => {
204
204
  self.addEventListener('activate', (event) => {
205
205
  event.waitUntil(self.clients.claim());
206
206
  });
207
- `}_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:a={}}=s,l=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=[];a.expiration&&c.push(`new ExpirationPlugin({
208
- maxEntries: ${a.expiration.maxEntries||50},
209
- maxAgeSeconds: ${a.expiration.maxAgeSeconds||3600*24},
210
- })`),a.cacheableResponse&&c.push(`new CacheableResponsePlugin({
211
- statuses: ${JSON.stringify(a.cacheableResponse.statuses||[0,200])},
212
- })`),a.backgroundSync&&c.push(`new BackgroundSyncPlugin('${a.backgroundSync.queueName||"background-sync-queue"}', {
213
- maxRetentionTime: ${a.backgroundSync.maxRetentionTime||1440},
214
- })`);let u="";return a.cacheName&&(u+=`
215
- cacheName: '${a.cacheName}',`),c.length>0&&(u+=`
207
+ `}_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:i={}}=s,l=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=[];i.expiration&&c.push(`new ExpirationPlugin({
208
+ maxEntries: ${i.expiration.maxEntries||50},
209
+ maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
210
+ })`),i.cacheableResponse&&c.push(`new CacheableResponsePlugin({
211
+ statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
212
+ })`),i.backgroundSync&&c.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
213
+ maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
214
+ })`);let u="";return i.cacheName&&(u+=`
215
+ cacheName: '${i.cacheName}',`),c.length>0&&(u+=`
216
216
  plugins: [
217
217
  ${c.join(`,
218
218
  `)}
219
- ],`),a.networkTimeoutSeconds&&(u+=`
220
- networkTimeoutSeconds: ${a.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${a.cacheName||"cache-"+r}
219
+ ],`),i.networkTimeoutSeconds&&(u+=`
220
+ networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${i.cacheName||"cache-"+r}
221
221
  registerRoute(
222
222
  ${p},
223
223
  new ${l}({${u}
@@ -238,7 +238,7 @@ registerRoute(
238
238
  }),
239
239
  'POST'
240
240
  );
241
- `}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 a of n){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),a.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of l){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 Ie=class extends N{constructor(e={}){super(Se,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||De.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 bt(i={}){return new Ie(i)}import{createRequire as Rs}from"node:module";function yt(i,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=i.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...i.matchAll(o)].forEach(l=>{let p=l[1],c=l[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var fe=null,wt=null;function $s(i){let t=(i.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var ne=class extends T{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(fe&&wt===s)return this.logger.debug("Using cached route discovery results"),this.routes=fe.routes,this.errors=fe.errors,this.source=fe.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/"),fe={routes:this.routes,errors:this.errors,source:this.source},wt=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)),a=[...r,...n];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=a.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let l=new Map;for(let p of this.routes){let c=p.path;if(l.has(c)){let u=l.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' };`)}l.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),a=$s(o),p=a===pe.HOMEPAGE_COMPONENT?pe.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:g,...h}=n||{};return{path:p,component:a,importPath:o,auth:n?.auth||!1,meta:{...c,...h,entity:c.entity,action:c.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=yt(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(a=>`:${a}`).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])/g," $1").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),n=null,a=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?a="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?a="form":(s.includes("Detail")||s.includes("View"))&&(a="detail")),{title:r,entity:n,action:a,file:e}}};function ks(i,e,t="configuration-error",s={}){let r=`[${i}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=i,o.context=s,o}function Pt(i,e,t,s={}){return ks(i,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function St(i){return i?.languages||i?.supportedLanguages||["en"]}function $t(i){return i?.fallback||i?.fallbackLanguage||"en"}var Te=class extends N{constructor(e={}){super(ne,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:W.next.middleware,manifestPath:W.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
241
+ `}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 i of n){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of l){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 D{constructor(e={}){super(Re,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||Ie.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 _t(a={}){return new je(a)}import{createRequire as Is}from"node:module";function At(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,(l,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(o)].forEach(l=>{let p=l[1],c=l[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var fe=null,Et=null;function Os(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var ie=class extends U{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(fe&&Et===s)return this.logger.debug("Using cached route discovery results"),this.routes=fe.routes,this.errors=fe.errors,this.source=fe.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/"),fe={routes:this.routes,errors:this.errors,source:this.source},Et=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)),i=[...r,...n];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=i.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let l=new Map;for(let p of this.routes){let c=p.path;if(l.has(c)){let u=l.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' };`)}l.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),i=Os(o),p=i===pe.HOMEPAGE_COMPONENT?pe.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:g,...h}=n||{};return{path:p,component:i,importPath:o,auth:n?.auth||!1,meta:{...c,...h,entity:c.entity,action:c.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=At(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(i=>`:${i}`).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,i=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?i="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?i="form":(s.includes("Detail")||s.includes("View"))&&(i="detail")),{title:r,entity:n,action:i,file:e}}};function Ts(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 Nt(a,e,t,s={}){return Ts(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function ze(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 xe(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 Le(a){return a?.languages||a?.supportedLanguages||["en"]}function Ue(a){return a?.fallback||a?.fallbackLanguage||"en"}var Ge=class extends D{constructor(e={}){super(ie,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:q.next.middleware,manifestPath:q.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
242
242
  // Generated at: ${new Date().toISOString()}
243
243
  // Populates _DNDEV_CONFIG_.routes with discovery results
244
244
 
@@ -257,7 +257,7 @@ if (typeof globalThis !== 'undefined') {
257
257
  timestamp: Date.now(),
258
258
  };
259
259
  }
260
- globalThis._DNDEV_CONFIG_.${I.routes} = {
260
+ globalThis._DNDEV_CONFIG_.${L.routes} = {
261
261
  mapping: routeMapping,
262
262
  manifest: routeManifest,
263
263
  };
@@ -267,17 +267,30 @@ if (typeof globalThis !== 'undefined') {
267
267
  export const routes = routeMapping;
268
268
  export const manifest = routeManifest;
269
269
  export default { routes: routeMapping, manifest: routeManifest };
270
- `}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(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 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/[...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);return this.writeGeneratedFile(s,n,`app page: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===pe.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t}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=Rs(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),o=this.isClientComponent(e.filePath),n=e.metaExport&&Object.keys(e.metaExport).length>0,a=this.loadI18nConfig(),l=e.metaExport?.namespace,p=`// Generated by @donotdev/config - DO NOT EDIT
270
+ `}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=Le(t),r=Ue(t),o=process.env.NEXT_PUBLIC_SITE_NAME||"";if(!o)try{let l=this.pathResolver.resolveAppPath("public/seo-manifest.json");this.pathResolver.pathExists(l)&&(o=this.pathResolver.readSync(l,{format:"json"})?.siteName||"")}catch{}let n={};for(let l of e.routes){let p=l.metaExport?.namespace,c=l.metaExport?.seo||{},u={};for(let g of s){let h=p&&t&&ze(p,g,t,this.pathResolver)||ze(p,r,t,this.pathResolver),f=xe(h,"meta")||{},m=xe(h,"title"),d=xe(h,"description"),$;f.fullTitle?$=f.fullTitle:c.fullTitle?$=c.fullTitle:m?$=o?`${m} | ${o}`:m:c.title?$=o?`${c.title} | ${o}`:c.title:c.title===null?$=o:$=o||"";let k;c.description===null?k=void 0:c.description?k=c.description:d&&(k=d);let N=c.image||f.image||"/og-image.png",T=c.type||f.type||"website",E=c.keywords||f.keywords,W=c.noindex||!1;u[g]={title:$,...k&&{description:k},image:N,type:T,...E&&{keywords:E},...W&&{noindex:W}}}n[l.path]={locales:u,defaultLocale:r}}let i=JSON.stringify(n,null,2);this.writeGeneratedFile("public/metadata-manifest.json",i,"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/[...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);return this.writeGeneratedFile(s,n,`app page: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===pe.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t}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=Is(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 this.isClientComponent(e.filePath)?`// Generated by @donotdev/config - DO NOT EDIT
271
271
  // This file will be regenerated when src/pages changes
272
272
  // To customize: edit ${e.filePath} or create manual app/** files
273
- ${o?`'use client';
274
- `:""}
273
+ 'use client';
274
+
275
275
  import ${t} from '${r}';
276
- `;return o||(n&&l&&a?p+=this.generateMetadataFunction(e,l,a):n&&(p+=`
277
- export const metadata = ${this.generateMetadataObject(e.metaExport)};
278
- `)),p+=`
276
+
279
277
  export default ${t};
280
- `,p}generateMetadataFunction(e,t,s){let r=St(s),o=$t(s),n="`",a=r.map(l=>` '${l}': { href: ${n}\${baseUrl}\${currentPath}${n} }`).join(`,
278
+ `:`// Generated by @donotdev/config - DO NOT EDIT
279
+ // This file will be regenerated when src/pages changes
280
+ // To customize: edit ${e.filePath} or create manual app/** files
281
+
282
+ import type { Metadata } from 'next';
283
+
284
+ import { getMetadataForPath } from '@donotdev/core/next';
285
+
286
+ import ${t} from '${r}';
287
+
288
+ export async function generateMetadata(): Promise<Metadata> {
289
+ return getMetadataForPath('${e.path}');
290
+ }
291
+
292
+ export default ${t};
293
+ `}generateMetadataFunction(e,t,s){let r=Le(s),o=Ue(s),n="`",i=r.map(l=>` '${l}': { href: ${n}\${baseUrl}\${currentPath}${n} }`).join(`,
281
294
  `);return`
282
295
  import type { Metadata } from 'next';
283
296
  import { readFileSync } from 'node:fs';
@@ -383,7 +396,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
383
396
  },
384
397
  alternates: {
385
398
  languages: {
386
- ${a}
399
+ ${i}
387
400
  },
388
401
  },
389
402
  };
@@ -498,35 +511,45 @@ export const routeManifest = {
498
511
 
499
512
  export default pageRoutes;
500
513
  `}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}`}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(`
501
- `).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function kt(i={}){return new Te(i)}import{readFileSync as xs,readdirSync as _s,existsSync as As}from"fs";import{join as Rt}from"path";var $e=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:n,crawlDelay:a=1,routes:l={},...p}=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:a,routes:l,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=E("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,s=null){try{let r=this.generateRouteMetaTags(e.routes||[]),o={routes:e.routes||[],routeMetaTags:r,baseUrl:this.options.baseUrl,siteName:this.options.siteName},n=this.discoverBlogPosts(),a={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:o.routes.length,publicRoutes:o.routes.filter(l=>!l.auth||l.auth===!1).length,protectedRoutes:o.routes.filter(l=>l.auth&&l.auth.required).length,blogPosts:n.length};return this.options.generateRobotsTxt&&(a.robotsTxt=await this.generateRobotsTxt(o,t,s)),this.options.generateSitemap&&(a.sitemap=await this.generateSitemap(o,t,s,n)),n.length>0&&(a.rss=await this.generateRSSFeed(n,t,s)),a.manifest=await this.generateManifest(o,t,s),a}catch(r){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`),r}}async generateRobotsTxt(e,t,s=null){if(s&&await s("robots.txt"))return this.logger.info("\u2705 robots.txt already exists, skipping generation"),{fileName:"robots.txt",skipped:!0};let r=[];(e.routes||[]).forEach(n=>{if(n.auth&&n.auth.required){let a=n.path.startsWith("/")?n.path:`/${n.path}`;r.push(a)}}),r.push("/admin","/api","/_next","/static");let o=this.generateRobotsTxtContent({disallowedPaths:[...new Set(r)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",o),{fileName:"robots.txt",content:o,disallowedPaths:r.length}}async generateSitemap(e,t,s=null,r=[]){if(s&&await s("sitemap.xml"))return this.logger.info("\u2705 sitemap.xml already exists, skipping generation"),{fileName:"sitemap.xml",skipped:!0};let n=(e.routes||[]).filter(l=>!l.auth||l.auth===!1).map(l=>({url:l.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:l.path==="/"?"1.0":"0.8"}));if(r.length>0){n.push({url:"/blog",lastmod:r[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let l of r)n.push({url:`/blog/${l.slug}`,lastmod:l.date,changefreq:"monthly",priority:"0.6"})}let a=this.generateSitemapContent(n);return await t("sitemap.xml",a),{fileName:"sitemap.xml",content:a,publicRoutes:n.length}}async generateManifest(e,t,s=null){if(s&&await s("seo-manifest.json"))return this.logger.info("\u2705 seo-manifest.json already exists, skipping generation"),{fileName:"seo-manifest.json",skipped:!0};let r={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(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||[]},o=JSON.stringify(r,null,2);return await t("seo-manifest.json",o),{fileName:"seo-manifest.json",content:o,manifest:r}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:o}=e,n=l=>l?l==="*"?"*":l.startsWith("/")?l:`/${l}`:"/",a=["User-agent: *",...s.map(l=>`Disallow: ${n(l)}`),...t.map(l=>`Allow: ${n(l)}`)];return o&&a.push(`Crawl-delay: ${o}`),r&&a.push(`Sitemap: ${r}`),a.join(`
502
- `)}generateSitemapContent(e){return`<?xml version="1.0" encoding="UTF-8"?>
503
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
504
- ${e.map(({url:s,lastmod:r,changefreq:o,priority:n})=>{let a=[` <loc>${this.options.baseUrl}${s}</loc>`];return r&&a.push(` <lastmod>${r}</lastmod>`),o&&a.push(` <changefreq>${o}</changefreq>`),n&&a.push(` <priority>${n}</priority>`),` <url>
505
- ${a.join(`
514
+ `).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function Ft(a={}){return new Ge(a)}function A(a){return a?a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}function Ct(a){return a?a.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var ke=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:n,crawlDelay:i=1,aiCrawlers:l="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:i,aiCrawlers:l,routes:p,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...c},this.appRoot=c.appRoot||null,this.logger=C("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(i=>!i.auth||i.auth===!1).length,protectedRoutes:r.routes.filter(i=>i.auth&&i.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(i=>!(i.auth&&i.auth!==!1||typeof i.path=="string"&&i.path.includes(":")||s.length>0&&i.path===this.options.blogPath)).map(i=>({url:i.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:i.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 i of s)o.push({url:`${this.options.blogPath}/${i.slug}`,lastmod:i.date,changefreq:"monthly",priority:"0.6",image:i.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}`:"/",i=["User-agent: *",...s.map(p=>`Disallow: ${n(p)}`),...t.map(p=>`Allow: ${n(p)}`)];o&&i.push(`Crawl-delay: ${o}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Ms(l))),i.join(`
515
+ `)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:o,changefreq:n,priority:i,image:l})=>{let p=[` <loc>${A(this.options.baseUrl)}${A(r)}</loc>`];return o&&p.push(` <lastmod>${o}</lastmod>`),n&&p.push(` <changefreq>${n}</changefreq>`),i&&p.push(` <priority>${i}</priority>`),l&&p.push(` <image:image>
516
+ <image:loc>${A(this.options.baseUrl)}${A(l)}</image:loc>
517
+ </image:image>`),` <url>
518
+ ${p.join(`
506
519
  `)}
507
520
  </url>`}).join(`
508
- `)}
509
- </urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(r=`Explore ${o[o.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=Rt(this.appRoot,"src","content","blog");try{if(!As(e))return[];let t=_s(e).filter(r=>r.endsWith("_en.md"));if(t.length===0)return[];let s=[];for(let r of t){let o=xs(Rt(e,r),"utf-8"),n=r.replace(/_en\.md$/,""),a=o.match(/^---\r?\n([\s\S]*?)\r?\n---/),l={};if(a)for(let p of a[1].split(`
510
- `)){let c=p.indexOf(":");c!==-1&&(l[p.slice(0,c).trim()]=p.slice(c+1).trim())}s.push({slug:n,title:l.title||n,description:l.description||"",date:l.date||new Date().toISOString().split("T")[0],tags:l.tags?l.tags.split(",").map(p=>p.trim()):[],image:l.image||null})}return s.sort((r,o)=>o.date.localeCompare(r.date)),this.logger.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(t){return this.logger.debug(`Blog content discovery skipped: ${t.message}`),[]}}async generateRSSFeed(e,t,s=null){if(s&&await s("rss.xml"))return this.logger.info("\u2705 rss.xml already exists, skipping generation"),{fileName:"rss.xml",skipped:!0};let r=e.map(n=>` <item>
511
- <title><![CDATA[${n.title}]]></title>
512
- <link>${this.options.baseUrl}/blog/${n.slug}</link>
513
- <guid>${this.options.baseUrl}/blog/${n.slug}</guid>
514
- <description><![CDATA[${n.description}]]></description>
515
- <pubDate>${n.date?new Date(n.date).toUTCString():""}</pubDate>${n.tags.length?`
516
- <category>${n.tags.join(", ")}</category>`:""}${n.image?`
517
- <enclosure url="${this.options.baseUrl}${n.image}" type="image/png" length="0"/>`:""}
521
+ `);return`<?xml version="1.0" encoding="UTF-8"?>
522
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
523
+ xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
524
+ ${s}
525
+ </urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(r=`Explore ${o[o.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=y.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),i=e.readSync(n,{format:"text"}),l=o.replace(/_en\.md$/,""),p=i.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(p)for(let g of p[1].split(`
526
+ `)){let h=g.indexOf(":");h!==-1&&(c[g.slice(0,h).trim()]=g.slice(h+1).trim())}let u=c.date;if(!u)try{u=e.statSync(n).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no frontmatter date, using file mtime (${u})`)}catch{u=new Date().toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no date and file stat failed, using today`)}r.push({slug:l,title:c.title||l,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>
527
+ <title><![CDATA[${Ct(o.title)}]]></title>
528
+ <link>${A(this.options.baseUrl)}${A(this.options.blogPath)}/${A(o.slug)}</link>
529
+ <guid>${A(this.options.baseUrl)}${A(this.options.blogPath)}/${A(o.slug)}</guid>
530
+ <description><![CDATA[${Ct(o.description)}]]></description>
531
+ <pubDate>${o.date?new Date(o.date).toUTCString():""}</pubDate>${o.tags.length?`
532
+ <category>${A(o.tags.join(", "))}</category>`:""}${o.image?`
533
+ <enclosure url="${A(this.options.baseUrl)}${A(o.image)}" type="image/png" length="0"/>`:""}
518
534
  </item>`).join(`
519
- `),o=`<?xml version="1.0" encoding="UTF-8"?>
535
+ `),r=`<?xml version="1.0" encoding="UTF-8"?>
520
536
  <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
521
537
  <channel>
522
- <title>${this.options.siteName}</title>
523
- <link>${this.options.baseUrl}/blog</link>
524
- <description>${this.options.siteName} Blog</description>
538
+ <title>${A(this.options.siteName)}</title>
539
+ <link>${A(this.options.baseUrl)}${A(this.options.blogPath)}</link>
540
+ <description>${A(this.options.siteName)} Blog</description>
525
541
  <language>en</language>
526
- <atom:link href="${this.options.baseUrl}/rss.xml" rel="self" type="application/rss+xml"/>
527
- ${r}
542
+ <atom:link href="${A(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
543
+ ${s}
528
544
  </channel>
529
- </rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}};var je=class extends N{constructor(e={}){super(ne,e);let t=P.getInstance(),s=E("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 l=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(l)?l:`https://${l}`}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 a=[];if(o||a.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),n||a.push("siteName (APP_NAME in src/config/app.ts)"),a.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),a.forEach(l=>s.warn(` - ${l}`)),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.seoGenerator=new $e({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:o,siteName:n,crawlDelay:this.options.crawlDelay,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(o,n)=>{if(!o){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${o}`,n,o)},s=async o=>{try{let n=this.pathResolver.resolveAppPath(`public/${o}`);return this.pathResolver.pathExists(n)}catch{return!1}},r=await this.seoGenerator.generateSEOFiles(e,t,s);r.robotsTxt&&!r.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${r.robotsTxt.disallowedPaths||0} disallowed paths`),r.sitemap&&!r.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${r.sitemap.publicRoutes||0} routes`),r.rss&&!r.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${r.rss.postCount||0} blog posts`),r.manifest&&!r.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json")}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 xt(i={}){return new je(i)}function _t(i={}){let{debug:e}=i;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),Ge.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var At=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,Et=/['"]([^'"]+)['"]/g,ae=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:{...Ae.selectors,...this.options.customPatterns?.selectors},themes:{...Ae.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,a)=>{let l=n.replace(/[^a-zA-Z0-9]/g,"");return l?a===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!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),a=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(a))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let g=c.match(this.patterns.themes.themeIcon),h=c.match(this.patterns.themes.themeIsDark),f={name:p,displayName:u,isDark:h?h[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(f),s.themes.set(p,{name:p,displayName:u,isDark:f.isDark,file:n,variables:new Set,meta:f.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(At.lastIndex=0;(r=At.exec(t))!==null;){let o=r[1],n;for(Et.lastIndex=0;(n=Et.exec(o))!==null;){let a=n[1].trim();a&&s.add(a)}}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 ke=class extends T{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new ae(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 Ee.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(){Ee.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 Me=class extends N{constructor(e={}){super(ke,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new ae(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 Pt("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
545
+ </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()}}},Be=["GPTBot","Google-Extended","CCBot","ClaudeBot"],We=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Ms(a){let e=["# AI Crawler Management"];if(a==="block-all"){for(let t of[...Be,...We])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(a==="allow-all"){for(let t of[...Be,...We])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of Be)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of We)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Dt(a={}){let{logger:e}=a,t=y.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 Ot(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 l=Dt({appRoot:a.appRoot,logger:n}).routes||[],p=[];p.push(`# ${e}`),p.push(""),s&&(p.push(`> ${s}`),p.push(""));let c=l.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||"/",h=u.meta?.title||js(g),f=u.meta?.description||"",m=`${t}${g}`;f?p.push(`- [${h}](${m}): ${f}`):p.push(`- [${h}](${m})`)}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(`
546
+ `)}function Tt(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 i=y.getInstance(),l=o?i.resolvePath("src/content/blog",o):null;if(!l||!i.pathExists(l))return null;let p=[`# ${e}
547
+ `];a.description&&p.push(`> ${a.description}
548
+ `);for(let c of s){let u=i.resolvePath(`${c.slug}_en.md`,l);try{let g=i.readSync(u,{format:"text"});if(!g)continue;let h=g.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),f=`${t}${r}/${c.slug}`;p.push(`## ${c.title}
549
+ `),p.push(`Source: ${f}
550
+ `),c.date&&p.push(`Date: ${c.date}
551
+ `),p.push(h.trim()),p.push("")}catch{n?.debug?.(`llms-full.txt: could not read ${c.slug}`)}}return p.join(`
552
+ `)}function js(a){return a==="/"||a===""?"Home":(a.split("/").filter(Boolean).pop()||"Home").split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}var He=class extends D{constructor(e={}){super(ie,e);let t=y.getInstance(),s=C("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 l=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(l)?l:`https://${l}`}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 i=[];if(o||i.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),n||i.push("siteName (APP_NAME in src/config/app.ts)"),i.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),i.forEach(l=>s.warn(` - ${l}`)),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 ke({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=Ot({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 i=Tt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});i&&(this.writeGeneratedFile("public/llms-full.txt",i,"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 It(a={}){return new He(a)}function Mt(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),Xe.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var jt=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,zt=/['"]([^'"]+)['"]/g,le=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:{...Ne.selectors,...this.options.customPatterns?.selectors},themes:{...Ne.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,i)=>{let l=n.replace(/[^a-zA-Z0-9]/g,"");return l?i===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,n=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(i))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let g=c.match(this.patterns.themes.themeIcon),h=c.match(this.patterns.themes.themeIsDark),f={name:p,displayName:u,isDark:h?h[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(f),s.themes.set(p,{name:p,displayName:u,isDark:f.isDark,file:n,variables:new Set,meta:f.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(jt.lastIndex=0;(r=jt.exec(t))!==null;){let o=r[1],n;for(zt.lastIndex=0;(n=zt.exec(o))!==null;){let i=n[1].trim();i&&s.add(i)}}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 _e=class extends U{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new le(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 Fe.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(){Fe.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 Ve=class extends D{constructor(e={}){super(_e,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new le(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 Nt("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
530
553
  // Generated at: ${new Date().toISOString()}
531
554
  // Populates _DNDEV_CONFIG_ with discovery results
532
555
 
@@ -558,7 +581,7 @@ if (typeof globalThis !== 'undefined') {
558
581
  timestamp: Date.now(),
559
582
  };
560
583
  }
561
- globalThis._DNDEV_CONFIG_.${I.themes} = themeConfig;
584
+ globalThis._DNDEV_CONFIG_.${L.themes} = themeConfig;
562
585
  }
563
586
 
564
587
  // Export for compatibility
@@ -574,6 +597,6 @@ export function useTheme() {
574
597
  }
575
598
 
576
599
  export default useTheme;
577
- `}};function Nt(i={}){return new Me(i)}function Ft({debug:i,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:a,pwaOptions:l,serverShimOptions:p,appUrl:c,isDev:u,logger:g}){let h=s.debug??i,f=r.debug??i,m=o.debug??i,y=n.debug??i,k=a.debug??i,x=l.debug??i,C=p.debug??i,_=s.verbose??e,H=r.verbose??e,K=o.verbose??e,D=n.verbose??e,U=a.verbose??e,ie=l.verbose??e,ee=p.verbose??e,d={debug:i,verbose:e,generateManifest:t},le=s.disabled?null:kt({...d,...s,debug:h,verbose:_});i&&g.debug(`Route handler created: ${le?"enabled":"disabled"} (debug: ${h})`);let M=Nt({...d,...r,debug:f,verbose:H}),G=vt({...d,...o,debug:m,verbose:K}),V=mt({...d,...n,debug:y,verbose:D}),z=xt({...d,...a,debug:k,verbose:U,appUrl:c,isDev:u}),X=bt({...d,...l,debug:x,verbose:ie}),ce=_t({...d,...p,debug:C,verbose:ee});return{routeHandler:le,themeHandler:M,i18nHandler:G,assetHandler:V,seoHandler:z,pwaHandler:X,serverShimHandler:ce}}function Ct(i,e){let t={};if(i.routeHandler)try{t.routeConfig=i.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:i.themeHandler},{name:"i18n",handler:i.i18nHandler},{name:"asset",handler:i.assetHandler},{name:"seo",handler:i.seoHandler},{name:"pwa",handler:i.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=i.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}function Es(i={}){let{port:e,...t}=i;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let S=process.env.CI==="true";process.env.DNDEV_BUILD_ID=S?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let{appConfig:s,...r}=t;if(!s)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let o=s?.features?{debug:s.features.debug}:void 0,n=s?.seo&&typeof s.seo!="boolean"?{...s.seo,siteName:s.seo.siteName||s.app?.name}:s?.app?.name?{siteName:s.app.name}:void 0,a=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:l,seo:p,...c}=r,u={...o?{features:o}:{},...n?{seo:n}:{},...c},g=ft(u),h=dt(g);if(!h)throw new Error("normalizeOptions returned undefined");let{generateManifest:f,debug:m,verbose:y,mode:k,isDev:x,routeOptions:C,themeOptions:_,i18nOptions:H,assetOptions:K,pwaOptions:D,seoOptions:U,serverShimOptions:ie,nextConfigOptions:ee}=h,d=E("next-config",m,y),{appRoot:le,appRootSet:M}=qe({logger:d,debug:m}),G=!1,V=!1,z=!1,X=process.env.DNDEV_BUILD_ID,ce=C?.routingMode||"app";if(d.info(`
578
- \u{1F3D7}\uFE0F DnDev Framework - Building for ${k}${X?` [build:${X}]`:""}`),d.info(` Platform: Next.js | Routing: ${ce}
579
- `),x){let S=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${S}`,m&&(d.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&d.debug(`Port configured: ${S} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||d.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let v=Ft({debug:m,verbose:y,generateManifest:f,routeOptions:C,themeOptions:_,i18nOptions:H,assetOptions:K,seoOptions:U,pwaOptions:D,serverShimOptions:ie,isDev:x,logger:d}),w=Ct(v,d);return async function($={}){let A=P.getInstance(),te=M?et():[];m&&te.length>0&&d.debug(`Discovered ${te.length} packages: ${te.join(", ")}`);let{missing:J,installed:Re}=ye(A.getAppRoot()),Ot=J.filter(Q=>Q.startsWith("@donotdev/")),It=Re.filter(Q=>Q.startsWith("@donotdev/"));m&&J.length>0&&d.debug(`Missing optional deps (will alias to empty): ${J.join(", ")}`);let Tt=A.getAppRoot();if(M&&!G){G=!0;let Q=A.resolveAppPath(".dndev-build"),xe=process.env.DNDEV_BUILD_ID,Le=!1;try{Le=A.readSync(Q,{format:"text"})?.trim()===xe}catch{}Le?d.debug("Discoveries already completed by another worker, skipping"):(pt(Tt,d),await ut(v,d))}let Z=typeof $=="object"&&$!==null?$:{},{webpack:jt,rewrites:Mt,...zt}=Z;M&&!V&&(V=await gt(v.assetHandler,d,V));let Lt=w.routeConfig(Z),Ut=w.themeConfig(Z),Gt=w.i18nConfig(Z),Wt=w.assetConfig(Z),Bt=w.seoConfig(Z),Ht=w.pwaConfig(Z),Vt=w.serverShimConfig(),ze=(await v.i18nHandler?.getDiscoveryData?.())?.flagCodes||[],Jt=st({originalWebpack:jt,unusedFeaturePackages:Ot,usedFeaturePackages:It,missingOptionalDeps:J,flagCodes:ze,logger:d,debug:m}),qt=rt({originalRewrites:Mt,handlers:[v.routeHandler,v.themeHandler,v.i18nHandler,v.assetHandler,v.pwaHandler],logger:d}),Yt={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Kt=ot({routeResult:Lt,themeResult:Ut,i18nResult:Gt,assetResult:Wt,seoResult:Bt,pwaResult:Ht,serverShimResult:Vt,restNextConfig:zt,discoveredPackages:te,webpackConfig:Jt,rewritesConfig:qt,missingOptionalDeps:J,flagCodes:ze,pathResolver:A,env:Yt,logger:d});if(d.debug("Next.js config generated"),M&&!z){z=!0;let Q=a?.name||"app",xe=A.getAppRoot();d.info(`Name: ${Q}`),d.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),d.info("\u{1F527} Features: auto-detected"),d.info(`App root (final): ${xe}`)}return Kt}}var Dt=Es;export{Dt as default,Dt as defineNextConfig,us as definePostCSSConfig};
600
+ `}};function Lt(a={}){return new Ve(a)}function Ut({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:i,pwaOptions:l,serverShimOptions:p,appUrl:c,isDev:u,logger:g}){let h=s.debug??a,f=r.debug??a,m=o.debug??a,d=n.debug??a,$=i.debug??a,k=l.debug??a,N=p.debug??a,T=s.verbose??e,E=r.verbose??e,W=o.verbose??e,I=n.verbose??e,J=i.verbose??e,re=l.verbose??e,Q=p.verbose??e,w={debug:a,verbose:e,generateManifest:t},S=s.disabled?null:Ft({...w,...s,debug:h,verbose:T});a&&g.debug(`Route handler created: ${S?"enabled":"disabled"} (debug: ${h})`);let ee=Lt({...w,...r,debug:f,verbose:E}),M=kt({...w,...o,debug:m,verbose:W}),K=xt({...w,...n,debug:d,verbose:I}),H=It({...w,...i,debug:$,verbose:J,appUrl:c,isDev:u}),F=_t({...w,...l,debug:k,verbose:re}),G=Mt({...w,...p,debug:N,verbose:Q});return{routeHandler:S,themeHandler:ee,i18nHandler:M,assetHandler:K,seoHandler:H,pwaHandler:F,serverShimHandler:G}}function Gt(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 zs=new Set(["@donotdev/functions"]);function Bt(){try{let a=y.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=>!be.buildTimePackages.includes(r)).filter(r=>!zs.has(r)).sort()}catch{return[]}}var Je=new Map;function Ls(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&&Je.has(s))return Je.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,i=r?.seo&&typeof r.seo!="boolean"?{...r.seo,siteName:r.seo.siteName||r.app?.name}:r?.app?.name?{siteName:r.app.name}:void 0,l=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}:{},...i?{seo:i}:{},...u},h=St(g),f=Rt(h);if(!f)throw new Error("normalizeOptions returned undefined");let{generateManifest:m,debug:d,verbose:$,mode:k,isDev:N,routeOptions:T,themeOptions:E,i18nOptions:W,assetOptions:I,pwaOptions:J,seoOptions:re,serverShimOptions:Q,nextConfigOptions:w}=f,S=C("next-config",d,$),{appRoot:ee,appRootSet:M}=rt({logger:S,debug:d}),K=!1,H=M&&Oe(ee);if(!H){let P=T?.routingMode||"app";S.info(`
601
+ \u{1F3D7}\uFE0F DnDev Framework - Building for ${k}${s?` [build:${s}]`:""}`),S.info(` Platform: Next.js | Routing: ${P}
602
+ `)}if(N){let P=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${P}`,d&&(S.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&S.debug(`Port configured: ${P} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||S.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let F=Ut({debug:d,verbose:$,generateManifest:m,routeOptions:T,themeOptions:E,i18nOptions:W,assetOptions:I,seoOptions:re,pwaOptions:J,serverShimOptions:Q,isDev:N,logger:S}),G=Gt(F,S),v=async function(x={}){let R=y.getInstance(),j=M?Bt():[];d&&j.length>0&&S.debug(`Discovered ${j.length} packages: ${j.join(", ")}`);let{missing:te,installed:me}=Pe(R.getAppRoot()),Ae=te.filter(ce=>ce.startsWith("@donotdev/")),Ht=me.filter(ce=>ce.startsWith("@donotdev/"));d&&te.length>0&&S.debug(`Missing optional deps (will alias to empty): ${te.join(", ")}`),M&&await yt(F,S);let se=typeof x=="object"&&x!==null?x:{},{webpack:Vt,rewrites:Jt,redirects:qt,...Yt}=se;M&&!K&&(K=await wt(F.assetHandler,S,K));let Kt=G.routeConfig(se),Xt=G.themeConfig(se),Zt=G.i18nConfig(se),Qt=G.assetConfig(se),es=G.seoConfig(se),ts=G.pwaConfig(se),ss=G.serverShimConfig(),Ye=(await F.i18nHandler?.getDiscoveryData?.())?.flagCodes||[],rs=pt({originalWebpack:Vt,unusedFeaturePackages:Ae,usedFeaturePackages:Ht,missingOptionalDeps:te,flagCodes:Ye,logger:S,debug:d}),os=ut({originalRewrites:Jt,handlers:[F.routeHandler,F.themeHandler,F.i18nHandler,F.assetHandler,F.pwaHandler],logger:S}),ns=gt({originalRedirects:qt,seoRedirects:re?.redirects||[],logger:S}),as={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},is=ht({routeResult:Kt,themeResult:Xt,i18nResult:Zt,assetResult:Qt,seoResult:es,pwaResult:ts,serverShimResult:ss,restNextConfig:Yt,discoveredPackages:j,webpackConfig:rs,rewritesConfig:os,redirectsConfig:ns,missingOptionalDeps:te,flagCodes:Ye,pathResolver:R,env:as,logger:S});if(S.debug("Next.js config generated"),M&&!H){let ce=l?.name||"app";S.info(`Name: ${ce}`),S.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),S.info(`App root (final): ${R.getAppRoot()}`)}return is};return s&&Je.set(s,{configFn:v}),v}var Wt=Ls;import{readFileSync as Us,existsSync as Gs}from"node:fs";import{join as Bs}from"node:path";var de=null,qe=0,Ws=6e4;function Hs(){let a=Date.now();if(de&&a-qe<Ws)return de;try{let e=Bs(process.cwd(),"public","metadata-manifest.json");if(!Gs(e))return null;let t=Us(e,"utf-8");return de=JSON.parse(t),qe=a,de}catch{return null}}function Vs(a,e,t){let s=Hs(),r={title:t?.siteName||"Site"};if(!s)return r;let o=a.startsWith("/")?a:`/${a}`,n=s[o];if(!n)return r;let i=e||n.defaultLocale||"en",l=n.locales[i]||n.locales[n.defaultLocale]||Object.values(n.locales)[0];if(!l)return r;let p={title:l.title};return l.description&&(p.description=l.description),l.keywords&&(p.keywords=l.keywords),p.openGraph={title:l.title,type:l.type||"website",...l.description&&{description:l.description},...l.image&&{images:[l.image]},...t?.siteName&&{siteName:t.siteName}},p.twitter={card:"summary_large_image",title:l.title,...l.description&&{description:l.description},...l.image&&{images:[l.image]}},l.noindex&&(p.robots={index:!1,follow:!1}),p}function Js(){de=null,qe=0}export{Js as clearMetadataCache,Wt as default,Wt as defineNextConfig,$s as definePostCSSConfig,Vs as getMetadataForPath};