@donotdev/core 0.0.39 → 0.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/next/index.js CHANGED
@@ -1,9 +1,9 @@
1
- var ne={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},We={available:["auth","oauth","billing","crud"],packageNames:{auth:"@donotdev/auth",oauth:"@donotdev/oauth",billing:"@donotdev/billing",crud:"@donotdev/crud"},hooks:{auth:["useAuth"],oauth:["useOAuth","useOAuthPartner","useOAuthConnection"],billing:["useStripeBilling","useStripeCheckout"],crud:["useCrud","useCrudCollection"]}};var O={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},X={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ae={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ae={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},he={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"},F={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:[`${he.SOURCE_EAGER}/*_*.json`],lazy:[`${he.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/**"]},fe={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"]},Be=["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 _e={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)/}},ie={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},Ee=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ge={base:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore}};function He(a,e=null){let t=F[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function de(a){return Ge[a]||Ge.base}import*as m from"node:fs";import"node:fs";import{createRequire as Vt}from"node:module";import{resolve as me,join as W,dirname as Z,relative as Ve,normalize as Jt,sep as Je,extname as qt}from"node:path";import"node:url";import Yt from"fast-glob";var se={getGlobOptionsFor:de||void 0,SCAN_PATTERNS:F||void 0,getPatternsFor:He||void 0,I18N_PATHS:he||void 0},S={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function qe(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Ye={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"},b=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 Jt(e).split(Je).join("/")}catch{return String(e).split(Je).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Ve(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=Vt(W(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 c=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(c))return c}if(n==="firebase"){let c=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(c))return c}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=me(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=me(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=me(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=m.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:qt(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 m.promises.readFile(e);let n=await m.promises.readFile(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&S.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 m.readFileSync(e);let n=m.readFileSync(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&S.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,c=this.normalizePath(e),p=this.normalizePath(Z(c)),l=this.pathExists(c);if(l&&!o)return i&&S.info(`Skipping existing file: ${c}`),!1;if(n)return S.info(`[DRY RUN] Would write file: ${c}`),!0;try{await m.promises.mkdir(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return await qe(async()=>(Buffer.isBuffer(h)?await m.promises.writeFile(c,h):await m.promises.writeFile(c,h,"utf8"),i&&S.info(`${l?"Updated":"Created"} file: ${c}`),!0),`Failed to write file: ${c}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:i=!1}=s,c=this.normalizePath(e),p=this.normalizePath(Z(c)),l=this.pathExists(c);if(l&&!o)return i&&S.info(`Skipping existing file: ${c}`),!1;if(n)return S.info(`[DRY RUN] Would write file: ${c}`),!0;try{m.mkdirSync(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return Buffer.isBuffer(h)?m.writeFileSync(c,h):m.writeFileSync(c,h,"utf8"),i&&S.info(`${l?"Updated":"Created"} file: ${c}`),!0}catch(g){throw new Error(`Failed to write file: ${c}: ${g instanceof Error?g.message:String(g)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,i=this.normalizePath(t),c=this.pathExists(i);if(c&&!r)return n&&S.info(`Skipping existing file: ${i}`),!1;if(o)return S.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{await m.promises.mkdir(p,{recursive:!0})}catch(l){if(l?.code!=="EEXIST")throw l}try{return await qe(async()=>(await m.promises.copyFile(e,i),n&&S.info(`${c?"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),c=this.pathExists(i);if(c&&!r)return n&&S.info(`Skipping existing file: ${i}`),!1;if(o)return S.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{m.mkdirSync(p,{recursive:!0})}catch(l){if(l?.code!=="EEXIST")throw l}try{return m.copyFileSync(e,i),n&&S.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return m.existsSync(e)}catch(s){return t||S.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 m.existsSync(t)||m.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return m.readdirSync(e,t)}catch(s){return this.options.debug&&S.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return m.statSync(e)}catch(t){return this.options.debug&&S.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return m.realpathSync(e)}watch(e,t,s){return m.watch(e,t,s)}lstatSync(e){try{return m.lstatSync(e)}catch(t){return this.options.debug&&S.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await m.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{m.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await m.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){m.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return m.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=W(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(me(e)),s=this.getAppRoot(),r=Ve(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(W(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),i=r.startsWith(n)?r.slice(n.length+1):r,c={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:se.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...c,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=se.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(W(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await Yt(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 l of s)if(typeof l!="string"||l.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=se.getGlobOptionsFor?se.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),i=e.framework.map(l=>{let u=this.normalizePath(l);return u.startsWith(n)?u.slice(n.length+1):u}),c=e.consumer.map(l=>{let u=this.normalizePath(l);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 l=i.length>0?await this._globWithNormalization(i,p):[],u=await this._globWithNormalization(c,p);return{frameworkFiles:l,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!se.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=se.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let c=r,p={eager:c.eager.map(l=>l.startsWith("!")?"!"+this.resolveAppPath(l.slice(1)):this.resolveAppPath(l)),lazy:c.lazy.map(l=>l.startsWith("!")?"!"+this.resolveAppPath(l.slice(1)):this.resolveAppPath(l)),framework:{eager:o?(c.framework?.eager||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):await Promise.all((c.framework?.eager||[]).map(l=>this._resolveFrameworkI18nPattern(l))).then(l=>l.filter(Boolean)),lazy:o?(c.framework?.lazy||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):await Promise.all((c.framework?.lazy||[]).map(l=>this._resolveFrameworkI18nPattern(l))).then(l=>l.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(c=>this.resolveRepoPath(c)).filter(Boolean):[],consumer:(n.consumer||[]).map(c=>this.resolveAppPath(c)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(W(t,Ye.TOOLING)),n=this.normalizePath(W(t,Ye.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let i=W(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let c=this.normalizePath(W(t,"package.json"));if(this.pathExists(c)&&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 Ke({logger:a,debug:e=!1}={}){let t=b.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(),c=t.normalizePath(i);if(c.includes("/apps/")){let p=c.indexOf("/apps/"),u=c.substring(p+6).split("/")[0];if(u){let h=t.resolveRepoPath(`apps/${u}`),g=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(g)&&(r=h,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}}var Xe=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,B=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:{..._e.selectors,...this.options.customPatterns?.selectors},themes:{..._e.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 c=n.replace(/[^a-zA-Z0-9]/g,"");return c?i===0?c.toLowerCase():c.charAt(0).toUpperCase()+c.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),c=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=c.exec(i))!==null;){let[,p,l,u]=o;if(!p||!u)continue;let h=l.match(this.patterns.themes.themeIcon),g=l.match(this.patterns.themes.themeIsDark),d={name:p,displayName:u,isDark:g?g[1]==="1":!1,meta:{icon:h?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(d),s.themes.set(p,{name:p,displayName:u,isDark:d.isDark,file:n,variables:new Set,meta:d.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(Xe.lastIndex=0;(r=Xe.exec(t))!==null;){let o=r[1];o&&o.trim()&&s.add(o.trim())}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let 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||"")}};import*as _ from"@clack/prompts";var D={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 Kt(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function T(a,e){return Kt()?`${e}${a}${D.reset}`:a}function R(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=b.getInstance(),i=null;if(o){let l=n.resolveAppPath(r);n.pathExists(l)||n.mkdir(l),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 c=(l,u,h)=>{if(i){let g=new Date().toISOString(),d=h.length>0?" "+h.map($=>typeof $=="object"?JSON.stringify($,null,2):String($)).join(" "):"",w=`${g} [${l}] ${u}${d}
3
- `;n.appendFile(i,w)}},p=(l,u)=>{if(u.length===0)return l;let h=u.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${l} ${h}`};return{debug:(l,...u)=>{e&&(o?c("DEBUG",l,u):_.log.message(T(p(l,u),D.gray)))},verbose:(l,...u)=>{t&&(o?c("VERBOSE",l,u):_.log.message(p(l,u)))},info:(l,...u)=>{o?c("INFO",l,u):_.log.info(T(p(l,u),D.brightCyan))},warn:(l,...u)=>{e&&o?c("WARN",l,u):_.log.warn(T(p(l,u),D.brightYellow))},error:(l,...u)=>{e&&o?c("ERROR",l,u):_.log.error(T(p(l,u),D.brightRed))},success:(l,...u)=>{e&&o?c("SUCCESS",l,u):_.log.success(T(p(l,u),D.brightGreen))},when:(l,u="debug")=>(h,...g)=>{if(l){let d=p(h,g);switch(u){case"verbose":t&&(_.log.message(d),c("VERBOSE",h,g));break;case"info":_.log.info(T(d,D.brightCyan)),c("INFO",h,g);break;case"warn":_.log.warn(T(d,D.brightYellow)),c("WARN",h,g);break;case"error":_.log.error(T(d,D.brightRed)),c("ERROR",h,g);break;case"success":_.log.success(T(d,D.brightGreen)),c("SUCCESS",h,g);break;default:e&&(_.log.message(T(d,D.gray)),c("DEBUG",h,g))}}},getLogFilePath:()=>i}}var Xt=3,Ze="dndev-font-preloads.json";async function Zt(a,e){let t=R("font-preload-next",e,!1);try{let s=await a.resolvePatterns("css"),{consumerFiles:r}=await a.resolveFiles(s,"css");if(!r?.length)return[ie.Inter];let o=new B(a,{debug:e,logger:t}),n=new Set;for(let c of r)try{let p=await a.read(c,{format:"text"});p&&o.extractFontFamilies(p).forEach(l=>n.add(l))}catch{}if(n.size===0)return[ie.Inter];let i=new Set;for(let c of n){let p=ie[c];p&&i.add(p)}return Array.from(i)}catch{return[ie.Inter]}}function Qe({pathResolver:a,debug:e=!1}){let t=R("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 c=await Zt(a,e),p=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",l=[];for(let[g]of Object.entries(r.assets)){if(!g.endsWith(".woff2")&&!g.endsWith(".woff"))continue;let d=g.toLowerCase();if(c.some(w=>d.includes(w))){let w=p?`${p}/${g}`:`/${g}`;if(l.push({href:w,type:"font/woff2"}),l.length>=Xt)break}}let u=a.resolveAppPath("public");if(!a.pathExists(u))try{a.ensureDirSync(u)}catch(g){return t.debug(`Font preload: could not create public dir: ${g?.message}`),o()}let h=a.resolvePath(Ze,u);a.writeSync(h,JSON.stringify(l,null,0),{overwrite:!0}),t.debug(`Font preload: wrote ${l.length} entries to ${Ze}`)}catch(i){t.debug(`Font preload manifest: ${i?.message}`)}o()})}}}function et({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 tt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Qt(a){return(e,t)=>{tt[e]&&(e=tt[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 c=a.resolvePath(o,n);if(a.pathExists(c))return c;let p=c+".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 es(){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=b.getInstance();return et({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:Qt(s)})}function st(){try{let a=b.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(o=>{let n=s[o];return n&&typeof n=="string"&&n.startsWith("workspace:")}).filter(o=>!fe.buildTimePackages.includes(o)).sort()}catch{return[]}}function U(a){return a&&typeof a=="object"&&!Array.isArray(a)}var rt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function ot({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],logger:r,debug:o}){return(n,i)=>{let{dev:c,isServer:p,webpack:l}=i;c&&!p&&(n.infrastructureLogging={level:"error"},n.stats={...n.stats,logging:"error",loggingTrace:!1},n.ignoreWarnings=[...n.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let u=n.module?.rules?.find(h=>h.test?.test?.(".svg"));u&&(u.exclude=/\.svg$/i),n.module=n.module||{},n.module.rules=n.module.rules||[],n.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),n.resolve=n.resolve||{},n.resolve.alias={...n.resolve.alias,...rt},l?.IgnorePlugin&&n.plugins.push(new l.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=b.getInstance();n.plugins.push(Qe({pathResolver:h,debug:o}))}catch(h){r.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(r.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),r.info(`\u2705 Including features: ${t.join(", ")}`),n.externals=n.externals||[],Array.isArray(n.externals))n.externals.push(...e);else{let h=n.externals;n.externals=(g,d,w)=>e.includes(d)?w(null,"commonjs "+d):typeof h=="function"?h(g,d,w):w()}if(s.length>0&&l?.NormalModuleReplacementPlugin){let g=b.getInstance().getEmptyModulePath(),d=s.map($=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),w=new RegExp(`^(${d.join("|")})(\\/|$)`);n.plugins.push(new l.NormalModuleReplacementPlugin(w,g)),o&&r.debug(`Aliased ${s.length} missing optional deps to empty module`)}return a?a(n,i):n}}function nt({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,c)=>(c?.beforeFiles&&i.beforeFiles.push(...c.beforeFiles),c?.afterFiles&&i.afterFiles.push(...c.afterFiles),c?.fallback&&i.fallback.push(...c.fallback),i),{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 at({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:i,discoveredPackages:c,webpackConfig:p,rewritesConfig:l,missingOptionalDeps:u,pathResolver:h,env:g,logger:d}){let w=i?.output==="export",H=i?.distDir||".next";return{transpilePackages:c,...U(i)?i:(d.warn("restNextConfig is not a plain object:",i),{}),serverExternalPackages:(i?.serverExternalPackages||i?.serverComponentsExternalPackages||[]).filter(x=>!x.startsWith("@donotdev/")&&!u?.includes(x)),turbopack:{...i?.turbopack||{},root:i?.turbopack?.root||h.getRepoRoot(),resolveAlias:{...i?.turbopack?.resolveAlias||{},...rt,...u?.length>0?Object.fromEntries(u.flatMap(x=>[[x,"@donotdev/core/empty"],[`${x}/*`,"@donotdev/core/empty"]])):{}}},distDir:H,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...U(a)?a:(d.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...U(e)?e:(d.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...U(t)?t:(d.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...U(s)?s:(d.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...U(r)?r:(d.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...U(o)?o:(d.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...U(n)?n:(d.warn("serverShimConfig returned non-object:",n),{}),webpack:p,...w?{}:{rewrites:async()=>await l()||void 0},env:g,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var ve="fonts",Ne="dndev-fonts.css",ts=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,it=/url\(\.\/files\/([^)]+)\)/g;function ss(a,e){let t=a.resolvePath("src/dndev.css",e),s=a.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=ts.exec(s))!==null;)r.push([o[1],o[2]]);return r}function rs(a,e,t,s){let r=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
1
+ var ne={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},We={available:["auth","oauth","billing","crud"],packageNames:{auth:"@donotdev/auth",oauth:"@donotdev/oauth",billing:"@donotdev/billing",crud:"@donotdev/crud"},hooks:{auth:["useAuth"],oauth:["useOAuth","useOAuthPartner","useOAuthConnection"],billing:["useStripeBilling","useStripeCheckout"],crud:["useCrud","useCrudCollection"]}};var I={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},X={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ae={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ae={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},he={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"},F={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:[`${he.SOURCE_EAGER}/*_*.json`],lazy:[`${he.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/**"]},fe={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"]},Be=["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 _e={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)/}},ie={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},Ee=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ge={base:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore}};function He(a,e=null){let t=F[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function de(a){return Ge[a]||Ge.base}import*as m from"node:fs";import"node:fs";import{createRequire as Vt}from"node:module";import{resolve as me,join as W,dirname as Z,relative as Ve,normalize as Jt,sep as Je,extname as qt}from"node:path";import"node:url";import Yt from"fast-glob";var se={getGlobOptionsFor:de||void 0,SCAN_PATTERNS:F||void 0,getPatternsFor:He||void 0,I18N_PATHS:he||void 0},S={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function qe(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Ye={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 Jt(e).split(Je).join("/")}catch{return String(e).split(Je).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Ve(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=Vt(W(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 c=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(c))return c}if(n==="firebase"){let c=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(c))return c}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=me(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=me(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=me(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=m.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:qt(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 m.promises.readFile(e);let n=await m.promises.readFile(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&S.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 m.readFileSync(e);let n=m.readFileSync(e,r),i=this.stripBom(n);return o==="json"?JSON.parse(i):i}catch(n){return this.options.debug&&S.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,c=this.normalizePath(e),p=this.normalizePath(Z(c)),l=this.pathExists(c);if(l&&!o)return i&&S.info(`Skipping existing file: ${c}`),!1;if(n)return S.info(`[DRY RUN] Would write file: ${c}`),!0;try{await m.promises.mkdir(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return await qe(async()=>(Buffer.isBuffer(h)?await m.promises.writeFile(c,h):await m.promises.writeFile(c,h,"utf8"),i&&S.info(`${l?"Updated":"Created"} file: ${c}`),!0),`Failed to write file: ${c}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:i=!1}=s,c=this.normalizePath(e),p=this.normalizePath(Z(c)),l=this.pathExists(c);if(l&&!o)return i&&S.info(`Skipping existing file: ${c}`),!1;if(n)return S.info(`[DRY RUN] Would write file: ${c}`),!0;try{m.mkdirSync(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return Buffer.isBuffer(h)?m.writeFileSync(c,h):m.writeFileSync(c,h,"utf8"),i&&S.info(`${l?"Updated":"Created"} file: ${c}`),!0}catch(g){throw new Error(`Failed to write file: ${c}: ${g instanceof Error?g.message:String(g)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,i=this.normalizePath(t),c=this.pathExists(i);if(c&&!r)return n&&S.info(`Skipping existing file: ${i}`),!1;if(o)return S.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{await m.promises.mkdir(p,{recursive:!0})}catch(l){if(l?.code!=="EEXIST")throw l}try{return await qe(async()=>(await m.promises.copyFile(e,i),n&&S.info(`${c?"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),c=this.pathExists(i);if(c&&!r)return n&&S.info(`Skipping existing file: ${i}`),!1;if(o)return S.info(`[DRY RUN] Would copy file: ${i}`),!0;let p=this.normalizePath(Z(i));try{m.mkdirSync(p,{recursive:!0})}catch(l){if(l?.code!=="EEXIST")throw l}try{return m.copyFileSync(e,i),n&&S.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return m.existsSync(e)}catch(s){return t||S.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 m.existsSync(t)||m.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return m.readdirSync(e,t)}catch(s){return this.options.debug&&S.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return m.statSync(e)}catch(t){return this.options.debug&&S.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return m.realpathSync(e)}watch(e,t,s){return m.watch(e,t,s)}lstatSync(e){try{return m.lstatSync(e)}catch(t){return this.options.debug&&S.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await m.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{m.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await m.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){m.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return m.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=W(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(me(e)),s=this.getAppRoot(),r=Ve(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(W(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),i=r.startsWith(n)?r.slice(n.length+1):r,c={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:se.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...c,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=se.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(W(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await Yt(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 l of s)if(typeof l!="string"||l.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=se.getGlobOptionsFor?se.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),i=e.framework.map(l=>{let u=this.normalizePath(l);return u.startsWith(n)?u.slice(n.length+1):u}),c=e.consumer.map(l=>{let u=this.normalizePath(l);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 l=i.length>0?await this._globWithNormalization(i,p):[],u=await this._globWithNormalization(c,p);return{frameworkFiles:l,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!se.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=se.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let c=r,p={eager:c.eager.map(l=>l.startsWith("!")?"!"+this.resolveAppPath(l.slice(1)):this.resolveAppPath(l)),lazy:c.lazy.map(l=>l.startsWith("!")?"!"+this.resolveAppPath(l.slice(1)):this.resolveAppPath(l)),framework:{eager:o?(c.framework?.eager||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):await Promise.all((c.framework?.eager||[]).map(l=>this._resolveFrameworkI18nPattern(l))).then(l=>l.filter(Boolean)),lazy:o?(c.framework?.lazy||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):await Promise.all((c.framework?.lazy||[]).map(l=>this._resolveFrameworkI18nPattern(l))).then(l=>l.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(c=>this.resolveRepoPath(c)).filter(Boolean):[],consumer:(n.consumer||[]).map(c=>this.resolveAppPath(c)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(W(t,Ye.TOOLING)),n=this.normalizePath(W(t,Ye.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let i=W(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let c=this.normalizePath(W(t,"package.json"));if(this.pathExists(c)&&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 Ke({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(),c=t.normalizePath(i);if(c.includes("/apps/")){let p=c.indexOf("/apps/"),u=c.substring(p+6).split("/")[0];if(u){let h=t.resolveRepoPath(`apps/${u}`),g=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(g)&&(r=h,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}}var Xe=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,B=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:{..._e.selectors,...this.options.customPatterns?.selectors},themes:{..._e.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 c=n.replace(/[^a-zA-Z0-9]/g,"");return c?i===0?c.toLowerCase():c.charAt(0).toUpperCase()+c.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),c=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=c.exec(i))!==null;){let[,p,l,u]=o;if(!p||!u)continue;let h=l.match(this.patterns.themes.themeIcon),g=l.match(this.patterns.themes.themeIsDark),d={name:p,displayName:u,isDark:g?g[1]==="1":!1,meta:{icon:h?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(d),s.themes.set(p,{name:p,displayName:u,isDark:d.isDark,file:n,variables:new Set,meta:d.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(Xe.lastIndex=0;(r=Xe.exec(t))!==null;){let o=r[1];o&&o.trim()&&s.add(o.trim())}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let 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||"")}};import*as _ from"@clack/prompts";var D={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 Kt(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function T(a,e){return Kt()?`${e}${a}${D.reset}`:a}function x(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=y.getInstance(),i=null;if(o){let l=n.resolveAppPath(r);n.pathExists(l)||n.mkdir(l),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 c=(l,u,h)=>{if(i){let g=new Date().toISOString(),d=h.length>0?" "+h.map($=>typeof $=="object"?JSON.stringify($,null,2):String($)).join(" "):"",P=`${g} [${l}] ${u}${d}
3
+ `;n.appendFile(i,P)}},p=(l,u)=>{if(u.length===0)return l;let h=u.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${l} ${h}`};return{debug:(l,...u)=>{e&&(o?c("DEBUG",l,u):_.log.message(T(p(l,u),D.gray)))},verbose:(l,...u)=>{t&&(o?c("VERBOSE",l,u):_.log.message(p(l,u)))},info:(l,...u)=>{o?c("INFO",l,u):_.log.info(T(p(l,u),D.brightCyan))},warn:(l,...u)=>{e&&o?c("WARN",l,u):_.log.warn(T(p(l,u),D.brightYellow))},error:(l,...u)=>{e&&o?c("ERROR",l,u):_.log.error(T(p(l,u),D.brightRed))},success:(l,...u)=>{e&&o?c("SUCCESS",l,u):_.log.success(T(p(l,u),D.brightGreen))},when:(l,u="debug")=>(h,...g)=>{if(l){let d=p(h,g);switch(u){case"verbose":t&&(_.log.message(d),c("VERBOSE",h,g));break;case"info":_.log.info(T(d,D.brightCyan)),c("INFO",h,g);break;case"warn":_.log.warn(T(d,D.brightYellow)),c("WARN",h,g);break;case"error":_.log.error(T(d,D.brightRed)),c("ERROR",h,g);break;case"success":_.log.success(T(d,D.brightGreen)),c("SUCCESS",h,g);break;default:e&&(_.log.message(T(d,D.gray)),c("DEBUG",h,g))}}},getLogFilePath:()=>i}}var Xt=3,Ze="dndev-font-preloads.json";async function Zt(a,e){let t=x("font-preload-next",e,!1);try{let s=await a.resolvePatterns("css"),{consumerFiles:r}=await a.resolveFiles(s,"css");if(!r?.length)return[ie.Inter];let o=new B(a,{debug:e,logger:t}),n=new Set;for(let c of r)try{let p=await a.read(c,{format:"text"});p&&o.extractFontFamilies(p).forEach(l=>n.add(l))}catch{}if(n.size===0)return[ie.Inter];let i=new Set;for(let c of n){let p=ie[c];p&&i.add(p)}return Array.from(i)}catch{return[ie.Inter]}}function Qe({pathResolver:a,debug:e=!1}){let t=x("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 c=await Zt(a,e),p=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",l=[];for(let[g]of Object.entries(r.assets)){if(!g.endsWith(".woff2")&&!g.endsWith(".woff"))continue;let d=g.toLowerCase();if(c.some(P=>d.includes(P))){let P=p?`${p}/${g}`:`/${g}`;if(l.push({href:P,type:"font/woff2"}),l.length>=Xt)break}}let u=a.resolveAppPath("public");if(!a.pathExists(u))try{a.ensureDirSync(u)}catch(g){return t.debug(`Font preload: could not create public dir: ${g?.message}`),o()}let h=a.resolvePath(Ze,u);a.writeSync(h,JSON.stringify(l,null,0),{overwrite:!0}),t.debug(`Font preload: wrote ${l.length} entries to ${Ze}`)}catch(i){t.debug(`Font preload manifest: ${i?.message}`)}o()})}}}function et({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 tt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Qt(a){return(e,t)=>{tt[e]&&(e=tt[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 c=a.resolvePath(o,n);if(a.pathExists(c))return c;let p=c+".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 es(){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 et({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:Qt(s)})}function st(){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(o=>{let n=s[o];return n&&typeof n=="string"&&n.startsWith("workspace:")}).filter(o=>!fe.buildTimePackages.includes(o)).sort()}catch{return[]}}function U(a){return a&&typeof a=="object"&&!Array.isArray(a)}var rt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function ot({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],logger:r,debug:o}){return(n,i)=>{let{dev:c,isServer:p,webpack:l}=i;c&&!p&&(n.infrastructureLogging={level:"error"},n.stats={...n.stats,logging:"error",loggingTrace:!1},n.ignoreWarnings=[...n.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let u=n.module?.rules?.find(h=>h.test?.test?.(".svg"));u&&(u.exclude=/\.svg$/i),n.module=n.module||{},n.module.rules=n.module.rules||[],n.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),n.resolve=n.resolve||{},n.resolve.alias={...n.resolve.alias,...rt},l?.IgnorePlugin&&n.plugins.push(new l.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=y.getInstance();n.plugins.push(Qe({pathResolver:h,debug:o}))}catch(h){r.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(r.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),r.info(`\u2705 Including features: ${t.join(", ")}`),n.externals=n.externals||[],Array.isArray(n.externals))n.externals.push(...e);else{let h=n.externals;n.externals=(g,d,P)=>e.includes(d)?P(null,"commonjs "+d):typeof h=="function"?h(g,d,P):P()}if(s.length>0&&l?.NormalModuleReplacementPlugin){let g=y.getInstance().getEmptyModulePath(),d=s.map($=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),P=new RegExp(`^(${d.join("|")})(\\/|$)`);n.plugins.push(new l.NormalModuleReplacementPlugin(P,g)),o&&r.debug(`Aliased ${s.length} missing optional deps to empty module`)}return a?a(n,i):n}}function nt({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,c)=>(c?.beforeFiles&&i.beforeFiles.push(...c.beforeFiles),c?.afterFiles&&i.afterFiles.push(...c.afterFiles),c?.fallback&&i.fallback.push(...c.fallback),i),{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 at({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:i,discoveredPackages:c,webpackConfig:p,rewritesConfig:l,missingOptionalDeps:u,pathResolver:h,env:g,logger:d}){let P=i?.output==="export",H=i?.distDir||".next";return{transpilePackages:c,...U(i)?i:(d.warn("restNextConfig is not a plain object:",i),{}),serverExternalPackages:(i?.serverExternalPackages||i?.serverComponentsExternalPackages||[]).filter(k=>!k.startsWith("@donotdev/")&&!u?.includes(k)),turbopack:{...i?.turbopack||{},root:i?.turbopack?.root||h.getRepoRoot(),resolveAlias:{...i?.turbopack?.resolveAlias||{},...rt,...u?.length>0?Object.fromEntries(u.flatMap(k=>[[k,"@donotdev/core/empty"],[`${k}/*`,"@donotdev/core/empty"]])):{}}},distDir:H,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...U(a)?a:(d.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...U(e)?e:(d.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...U(t)?t:(d.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...U(s)?s:(d.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...U(r)?r:(d.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...U(o)?o:(d.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...U(n)?n:(d.warn("serverShimConfig returned non-object:",n),{}),webpack:p,...P?{}:{rewrites:async()=>await l()||void 0},env:g,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var ve="fonts",Ne="dndev-fonts.css",ts=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,it=/url\(\.\/files\/([^)]+)\)/g;function ss(a,e){let t=a.resolvePath("src/dndev.css",e),s=a.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=ts.exec(s))!==null;)r.push([o[1],o[2]]);return r}function rs(a,e,t,s){let r=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
4
4
  `],o=new Set;for(let[n,i]of e){let c=a.resolveFrameworkPackage(`@fontsource/${n}`);if(!c){s.debug(`@fontsource/${n} not found`);continue}let p=a.resolvePath(`${i}.css`,c),l=a.readSync(p,{format:"text"});if(!l){s.debug(`Missing: @fontsource/${n}/${i}.css`);continue}let u=l.replace(it,(h,g)=>{let d=a.resolvePath(`files/${g}`,c);if(!a.pathExists(d))return s.warn(`Font file missing: ${d} \u2014 dropping from CSS`),"url(data:,)";if(!o.has(g)){let $=a.resolvePath(g,t);a.copySync(d,$,{overwrite:!0}),o.add(g)}return`url(/${ve}/${g})`});r.push(u)}return{cssChunks:r,copiedFiles:o}}function os(a,e,t,s){let r=a.resolvePath("dist/dndev.css",e),o=a.readSync(r,{format:"text"});if(!o)return s.debug("dist/dndev.css not found in @donotdev/ui"),{cssChunks:[],copiedFiles:new Set};let n=a.resolvePath("dist/files",e),i=new Set;return{cssChunks:[`/* Auto-generated by @donotdev/core \u2014 do not edit */
5
- `,o.replace(it,(l,u)=>{let h=a.resolvePath(u,n);if(!a.pathExists(h))return s.warn(`Font file missing: ${h} \u2014 dropping from CSS`),"url(data:,)";if(!i.has(u)){let d=a.resolvePath(u,t);a.copySync(h,d,{overwrite:!0}),i.add(u)}return`url(/${ve}/${u})`})],copiedFiles:i}}function ct({debug:a=!1,force:e=!1}={}){let t=R("font-copy",a,!1),s=b.getInstance(),r=s.resolveAppPath(`public/${Ne}`);if(!e&&s.pathExists(r)){t.debug("dndev-fonts.css already exists, skipping font copy");return}let o=s.resolveFrameworkPackage("@donotdev/ui");if(!o){t.debug("@donotdev/ui not found, skipping font copy");return}let n=s.resolveAppPath(`public/${ve}`);s.ensureDir(n);let i=ss(s,o),c,p;if(i.length>0?(t.debug(`Monorepo mode: ${i.length} @fontsource imports found`),{cssChunks:c,copiedFiles:p}=rs(s,i,n,t)):(t.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:c,copiedFiles:p}=os(s,o,n,t)),p.size===0){t.debug("No font files found to copy");return}s.writeSync(r,c.join(`
6
- `)),t.debug(`Font copy: wrote ${Ne} (${p.size} font files copied)`)}function lt(){let a=b.getInstance(),e=a.resolveAppPath(`public/${Ne}`),t=a.resolveAppPath(`public/${ve}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var ns=["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"],as="dndev-config-",pt=".dndev-build";function is(a){if(!a)return!1;let e=b.getInstance(),t=e.resolveAppPath(pt),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function cs(a){if(!a)return;let e=b.getInstance(),t=e.resolveAppPath(pt),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s)}catch{}}function Fe(a,e){if(!a)return;let t=b.getInstance();for(let r of ns){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(as)&&o.endsWith(".js"))try{let n=t.resolvePath(o,s);t.removeSync(n),e.debug(`Cleaned: src/config/${o}`)}catch{}}catch{}}async function Ce({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 c=i.getAppRoot(),p=i.getRepoRoot();if(!c||c===p){n.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(d=>setTimeout(d,0));let g=i.getAppRoot();if(!g||g===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(is(c)){n.debug("Discoveries already completed this build, skipping");return}let l=Date.now();if(a)try{n.info("\u{1F50D} Starting route discovery...");let d=(await a.generateFiles())?.routes?.length||0;n.info(`\u2705 Routes generated: ${d} routes found`),d===0&&n.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(g){throw n.error(`\u274C Route generation failed: ${g.message}`),g.stack&&n.error(`Stack: ${g.stack}`),g}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}];for(let{name:g,handler:d}of u)try{await d.generateFiles()}catch(w){n.debug(`${g} generation failed: ${w.message}`)}try{ct()}catch(g){n.debug(`Font copy failed (non-critical): ${g.message}`)}let h=Date.now()-l;n.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`),cs(c)}async function ut(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 ce={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 gt(a,e){let t={...a};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=gt(a[s]||{},e[s]):t[s]=e[s]}),t}function ht(a={}){return gt(ce,a)}function ft(a){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:n={},seo:i={},serverShim:c={},discovery:p={},generateManifest:l,debug:u,verbose:h,...g}=a,d=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:l,debug:u,verbose:h,mode:d,isDev:d==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:n,seoOptions:i,serverShimOptions:c,discoveryOptions:p,nextConfigOptions:g}}var A=class{constructor(e,t={}){this.options={...t,...this.getHandlerDefaults()},this.logger=R(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=b.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...ce.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=X.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=O[t]||t;return`// Auto-generated DnDev config by @donotdev/config
5
+ `,o.replace(it,(l,u)=>{let h=a.resolvePath(u,n);if(!a.pathExists(h))return s.warn(`Font file missing: ${h} \u2014 dropping from CSS`),"url(data:,)";if(!i.has(u)){let d=a.resolvePath(u,t);a.copySync(h,d,{overwrite:!0}),i.add(u)}return`url(/${ve}/${u})`})],copiedFiles:i}}function ct({debug:a=!1,force:e=!1}={}){let t=x("font-copy",a,!1),s=y.getInstance(),r=s.resolveAppPath(`public/${Ne}`);if(!e&&s.pathExists(r)){t.debug("dndev-fonts.css already exists, skipping font copy");return}let o=s.resolveFrameworkPackage("@donotdev/ui");if(!o){t.debug("@donotdev/ui not found, skipping font copy");return}let n=s.resolveAppPath(`public/${ve}`);s.ensureDir(n);let i=ss(s,o),c,p;if(i.length>0?(t.debug(`Monorepo mode: ${i.length} @fontsource imports found`),{cssChunks:c,copiedFiles:p}=rs(s,i,n,t)):(t.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:c,copiedFiles:p}=os(s,o,n,t)),p.size===0){t.debug("No font files found to copy");return}s.writeSync(r,c.join(`
6
+ `)),t.debug(`Font copy: wrote ${Ne} (${p.size} font files copied)`)}function lt(){let a=y.getInstance(),e=a.resolveAppPath(`public/${Ne}`),t=a.resolveAppPath(`public/${ve}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var ns=["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"],as="dndev-config-",pt=".dndev-build";function is(a){if(!a)return!1;let e=y.getInstance(),t=e.resolveAppPath(pt),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function cs(a){if(!a)return;let e=y.getInstance(),t=e.resolveAppPath(pt),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s)}catch{}}function Fe(a,e){if(!a)return;let t=y.getInstance();for(let r of ns){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(as)&&o.endsWith(".js"))try{let n=t.resolvePath(o,s);t.removeSync(n),e.debug(`Cleaned: src/config/${o}`)}catch{}}catch{}}async function Ce({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 c=i.getAppRoot(),p=i.getRepoRoot();if(!c||c===p){n.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(d=>setTimeout(d,0));let g=i.getAppRoot();if(!g||g===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(is(c)){n.debug("Discoveries already completed this build, skipping");return}let l=Date.now();if(a)try{n.info("\u{1F50D} Starting route discovery...");let d=(await a.generateFiles())?.routes?.length||0;n.info(`\u2705 Routes generated: ${d} routes found`),d===0&&n.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(g){throw n.error(`\u274C Route generation failed: ${g.message}`),g.stack&&n.error(`Stack: ${g.stack}`),g}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}];for(let{name:g,handler:d}of u)try{await d.generateFiles()}catch(P){n.debug(`${g} generation failed: ${P.message}`)}try{ct()}catch(g){n.debug(`Font copy failed (non-critical): ${g.message}`)}let h=Date.now()-l;n.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`),cs(c)}async function ut(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 ce={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 gt(a,e){let t={...a};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=gt(a[s]||{},e[s]):t[s]=e[s]}),t}function ht(a={}){return gt(ce,a)}function ft(a){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:n={},seo:i={},serverShim:c={},discovery:p={},generateManifest:l,debug:u,verbose:h,...g}=a,d=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:l,debug:u,verbose:h,mode:d,isDev:d==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:n,seoOptions:i,serverShimOptions:c,discoveryOptions:p,nextConfigOptions:g}}var A=class{constructor(e,t={}){this.options={...t,...this.getHandlerDefaults()},this.logger=x(`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={...ce.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=X.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
7
7
  // Generated at: ${new Date().toISOString()}
8
8
  // Populates _DNDEV_CONFIG_ with discovery results
9
9
 
@@ -25,7 +25,7 @@ if (typeof globalThis !== 'undefined') {
25
25
 
26
26
  // Export for compatibility
27
27
  export default ${t}Config;
28
- `}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 C=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=R(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}};var be=class extends C{constructor(e,t={}){super(e,{assets:F.assets.fallback,assetPatterns:F.assets.patterns,frameworkPackage:Ae.package,assetsPath:Ae.assetsPath,modernFormats:F.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:c}=e,p=await this._processAssetFiles(c),l=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...l,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(ae.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(`${ae.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(`${ae.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(ae.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 c=await this.pathResolver.read(t,{format:"text"});if(!c)return{generated:[],skipped:[...o,...r].map(l=>l.name),error:"Failed to read logo.svg"};for(let l of o){let u=`${s}/${l.name}`;if(this.pathResolver.pathExists(u)){i.push(l.name);continue}try{await this.pathResolver.write(`public/${l.name}`,c),n.push(l.name)}catch(h){this.logger.debug(`Failed to copy ${l.name}: ${h.message}`),i.push(l.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(l=>l.name));else for(let l of r){let u=`${s}/${l.name}`;if(this.pathResolver.pathExists(u)){i.push(l.name);continue}try{let h=p.default(t).resize(l.size,l.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;l.format==="ico"?g=await h.toFormat("png").toBuffer():g=await h.toFormat(l.format).toBuffer(),await this.pathResolver.write(`public/${l.name}`,g),n.push(l.name)}catch(h){this.logger.debug(`Failed to generate ${l.name}: ${h.message}`),i.push(l.name)}}return{generated:n,skipped:i,error:null}}catch(c){return this.logger.debug(`Asset generation failed: ${c.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:c.message}}}};var Ie={data:null},De=class extends A{constructor(e={}){super(be,e)}getHandlerDefaults(){return{manifestPath:X.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
28
+ `}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 C=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=x(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}};var be=class extends C{constructor(e,t={}){super(e,{assets:F.assets.fallback,assetPatterns:F.assets.patterns,frameworkPackage:Ae.package,assetsPath:Ae.assetsPath,modernFormats:F.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:c}=e,p=await this._processAssetFiles(c),l=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...l,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(ae.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(`${ae.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(`${ae.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(ae.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 c=await this.pathResolver.read(t,{format:"text"});if(!c)return{generated:[],skipped:[...o,...r].map(l=>l.name),error:"Failed to read logo.svg"};for(let l of o){let u=`${s}/${l.name}`;if(this.pathResolver.pathExists(u)){i.push(l.name);continue}try{await this.pathResolver.write(`public/${l.name}`,c),n.push(l.name)}catch(h){this.logger.debug(`Failed to copy ${l.name}: ${h.message}`),i.push(l.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(l=>l.name));else for(let l of r){let u=`${s}/${l.name}`;if(this.pathResolver.pathExists(u)){i.push(l.name);continue}try{let h=p.default(t).resize(l.size,l.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;l.format==="ico"?g=await h.toFormat("png").toBuffer():g=await h.toFormat(l.format).toBuffer(),await this.pathResolver.write(`public/${l.name}`,g),n.push(l.name)}catch(h){this.logger.debug(`Failed to generate ${l.name}: ${h.message}`),i.push(l.name)}}return{generated:n,skipped:i,error:null}}catch(c){return this.logger.debug(`Asset generation failed: ${c.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:c.message}}}};var Oe={data:null},De=class extends A{constructor(e={}){super(be,e)}getHandlerDefaults(){return{manifestPath:X.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
29
29
  // Generated at: ${new Date().toISOString()}
30
30
  // Populates _DNDEV_CONFIG_ with discovery results
31
31
 
@@ -42,7 +42,7 @@ if (typeof globalThis !== 'undefined') {
42
42
  timestamp: Date.now(),
43
43
  };
44
44
  }
45
- globalThis._DNDEV_CONFIG_.${O.assets} = {
45
+ globalThis._DNDEV_CONFIG_.${I.assets} = {
46
46
  mapping: assetConfig.manifest,
47
47
  logoSvgContent: ${JSON.stringify(t)},
48
48
  manifest: {
@@ -54,7 +54,7 @@ if (typeof globalThis !== 'undefined') {
54
54
 
55
55
  // Export for compatibility
56
56
  export default assetConfig;
57
- `}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=>` {
57
+ `}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&&(Oe.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=>` {
58
58
  path: '${o.path}',
59
59
  type: '${o.type}',
60
60
  format: '${o.format}',
@@ -122,7 +122,7 @@ ${t}
122
122
  export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
123
123
 
124
124
  export default imageConfigs;
125
- `}};function dt(a={}){return new De(a)}var ye=class extends C{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=de("i18n"),n=r.eager||[],i=r.lazy||[],c=(this.options.additionalPaths||[]).map(v=>{let y=v.endsWith(".json")?v:`${v}/*_*.json`;return this.pathResolver.resolveAppPath(y)});c.length>0&&this.logger.debug(`Additional i18n paths configured: ${c.join(", ")}`);let p=r.framework?.eager||[],l=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${l.join(", ")}`),p.length===0&&l.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),h=this.pathResolver.normalizePath(s),g=(v,y)=>{let P=this.pathResolver.normalizePath(v),k=this.pathResolver.normalizePath(y);return P.startsWith(k)?P.slice(k.length+1):P},d=n.map(v=>g(v,t)),$=[...i,...c].map(v=>g(v,t)),H=p.map(v=>g(v,s)),V=l.map(v=>g(v,s)),x={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},J=await this.pathResolver._globWithNormalization(d,x),Q=await this.pathResolver._globWithNormalization($,x),q={...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(q.ignore)}`);let E=await this.pathResolver._globWithNormalization(H,q),j=await this.pathResolver._globWithNormalization(V,q);this.logger.debug(`Found ${J.length} eager, ${Q.length} lazy, ${E.length} framework eager, ${j.length} framework lazy files`),E.length>0?this.logger.debug(`Framework eager files (first 3): ${E.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: ${l.join(", ")}`);let oe=[...new Set([...J,...Q,...E,...j])],ee=new Set([...J,...E]),f={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},G=new Map,M=[...E,...j];for(let v of M){let y=this._processTranslationFile(v,E.includes(v),t);if(y){let P=`${y.namespace}_${y.language}`;G.set(P,y),f.allNamespaces.add(y.namespace),f.supportedLanguages.add(y.language),E.includes(v)&&f.eagerNamespaces.add(y.namespace)}}let I=new Set;for(let v of oe){if(M.includes(v))continue;let y=this._processTranslationFile(v,ee.has(v),t);if(y){let{namespace:P,language:k,importPath:pe,content:$e}=y,N=`${y.namespace}_${y.language}`;if(G.has(N)){let z=G.get(N);y.content=this._mergeTranslations(z.content,$e)}f.allNamespaces.add(P),f.supportedLanguages.add(k),I.add(k),ee.has(v)&&f.eagerNamespaces.add(P),f.mapping[P]||(f.mapping[P]={}),f.mapping[P][k]=pe,y.content&&(f.content[P]||(f.content[P]={}),f.content[P][k]=y.content),f.files.push({path:v,relativePath:this.pathResolver.getRelativePath(v),namespace:P,language:k,eager:ee.has(v),size:y.content?JSON.stringify(y.content).length:0})}}for(let[v,y]of G){let[P,k]=v.split("_");(!f.mapping[P]||!f.mapping[P][k])&&(f.mapping[P]||(f.mapping[P]={}),f.mapping[P][k]=y.importPath,f.content[P]||(f.content[P]={}),f.content[P][k]=y.content)}let Y=I.size>0?[...I].sort():[this.options.fallbackLanguage];return{mapping:f.mapping,content:f.content,eagerNamespaces:[...f.eagerNamespaces].sort(),allNamespaces:[...f.allNamespaces].sort(),supportedLanguages:Y,fallbackLanguage:this.options.fallbackLanguage,files:f.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,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,"/"),l;try{if(l=this.pathResolver.readSync(e,{format:"json"}),!l)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,content:l}}_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 Oe=class extends A{constructor(e={}){super(ye,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...ce.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
125
+ `}};function dt(a={}){return new De(a)}var ye=class extends C{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=de("i18n"),n=r.eager||[],i=r.lazy||[],c=(this.options.additionalPaths||[]).map(v=>{let b=v.endsWith(".json")?v:`${v}/*_*.json`;return this.pathResolver.resolveAppPath(b)});c.length>0&&this.logger.debug(`Additional i18n paths configured: ${c.join(", ")}`);let p=r.framework?.eager||[],l=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${l.join(", ")}`),p.length===0&&l.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),h=this.pathResolver.normalizePath(s),g=(v,b)=>{let w=this.pathResolver.normalizePath(v),R=this.pathResolver.normalizePath(b);return w.startsWith(R)?w.slice(R.length+1):w},d=n.map(v=>g(v,t)),$=[...i,...c].map(v=>g(v,t)),H=p.map(v=>g(v,s)),V=l.map(v=>g(v,s)),k={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},J=await this.pathResolver._globWithNormalization(d,k),Q=await this.pathResolver._globWithNormalization($,k),q={...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(q.ignore)}`);let E=await this.pathResolver._globWithNormalization(H,q),j=await this.pathResolver._globWithNormalization(V,q);this.logger.debug(`Found ${J.length} eager, ${Q.length} lazy, ${E.length} framework eager, ${j.length} framework lazy files`),E.length>0?this.logger.debug(`Framework eager files (first 3): ${E.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: ${l.join(", ")}`);let oe=[...new Set([...J,...Q,...E,...j])],ee=new Set([...J,...E]),f={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},G=new Map,M=[...E,...j];for(let v of M){let b=this._processTranslationFile(v,E.includes(v),t);if(b){let w=`${b.namespace}_${b.language}`;G.set(w,b),f.allNamespaces.add(b.namespace),f.supportedLanguages.add(b.language),E.includes(v)&&f.eagerNamespaces.add(b.namespace)}}let O=new Set;for(let v of oe){if(M.includes(v))continue;let b=this._processTranslationFile(v,ee.has(v),t);if(b){let{namespace:w,language:R,importPath:pe,content:$e}=b,N=`${b.namespace}_${b.language}`;if(G.has(N)){let z=G.get(N);b.content=this._mergeTranslations(z.content,$e)}f.allNamespaces.add(w),f.supportedLanguages.add(R),O.add(R),ee.has(v)&&f.eagerNamespaces.add(w),f.mapping[w]||(f.mapping[w]={}),f.mapping[w][R]=pe,b.content&&(f.content[w]||(f.content[w]={}),f.content[w][R]=b.content),f.files.push({path:v,relativePath:this.pathResolver.getRelativePath(v),namespace:w,language:R,eager:ee.has(v),size:b.content?JSON.stringify(b.content).length:0})}}for(let[v,b]of G){let[w,R]=v.split("_");(!f.mapping[w]||!f.mapping[w][R])&&(f.mapping[w]||(f.mapping[w]={}),f.mapping[w][R]=b.importPath,f.content[w]||(f.content[w]={}),f.content[w][R]=b.content,f.files.push({path:b.absolutePath,relativePath:this.pathResolver.getRelativePath(b.absolutePath),namespace:w,language:R,eager:f.eagerNamespaces.has(w),size:b.content?JSON.stringify(b.content).length:0}))}let Y=O.size>0?[...O].sort():[this.options.fallbackLanguage];return{mapping:f.mapping,content:f.content,eagerNamespaces:[...f.eagerNamespaces].sort(),allNamespaces:[...f.allNamespaces].sort(),supportedLanguages:Y,fallbackLanguage:this.options.fallbackLanguage,files:f.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,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,"/"),l;try{if(l=this.pathResolver.readSync(e,{format:"json"}),!l)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:l}}_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 Ie=class extends A{constructor(e={}){super(ye,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...ce.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
126
  // Generated at: ${new Date().toISOString()}
127
127
  // Populates _DNDEV_CONFIG_ with discovery results
128
128
 
@@ -164,12 +164,12 @@ if (typeof globalThis !== 'undefined') {
164
164
  timestamp: Date.now(),
165
165
  };
166
166
  }
167
- globalThis._DNDEV_CONFIG_.${O.i18n} = i18nConfig;
167
+ globalThis._DNDEV_CONFIG_.${I.i18n} = i18nConfig;
168
168
  }
169
169
 
170
170
  // Export for compatibility
171
171
  export default i18nConfig;
172
- `}};function mt(a={}){return new Oe(a)}var we=class extends C{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(h=>h.type==="manifest"||h.type==="service-worker");o.push(...i);let c=n.filter(h=>h.type==="icon"),p=new Set(o.filter(h=>h.type==="icon").map(h=>h.path)),l=c.filter(h=>!p.has(h.path));o.push(...l);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
172
+ `}};function mt(a={}){return new Ie(a)}var we=class extends C{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(h=>h.type==="manifest"||h.type==="service-worker");o.push(...i);let c=n.filter(h=>h.type==="icon"),p=new Set(o.filter(h=>h.type==="icon").map(h=>h.path)),l=c.filter(h=>!p.has(h.path));o.push(...l);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
173
  // Generated at ${new Date().toISOString()}
174
174
 
175
175
  importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
@@ -237,7 +237,7 @@ registerRoute(
237
237
  }),
238
238
  'POST'
239
239
  );
240
- `}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 c=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of c){let l=this.pathResolver.getRelativePath(p);if(l.startsWith(`${e}/static/`)){let u=`/_next/${l.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 Te=class extends A{constructor(e={}){super(we,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 vt(a={}){return new Te(a)}import{createRequire as us}from"node:module";function bt(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,(c,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(o)].forEach(c=>{let p=c[1],l=c[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${l}'`)}),Function(`return ${r}`)()}catch{return null}}var le=null,yt=null;function ls(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var re=class extends C{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(le&&yt===s)return this.logger.debug("Using cached route discovery results"),this.routes=le.routes,this.errors=le.errors,this.source=le.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/"),le={routes:this.routes,errors:this.errors,source:this.source},yt=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 c=new Map;for(let p of this.routes){let l=p.path;if(c.has(l)){let u=c.get(l);throw new Error(`Route conflict: Multiple routes found for path '${l}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}c.set(l,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=ls(o),p=i===ne.HOMEPAGE_COMPONENT?ne.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),l=this._extractPageMeta(r,s),{entity:u,action:h,...g}=n||{};return{path:p,component:i,importPath:o,auth:n?.auth||!1,meta:{...l,...g,entity:l.entity,action:l.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=bt(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])/g," $1").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 ps(a,e,t="configuration-error",s={}){let r=`[${a}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=a,o.context=s,o}function wt(a,e,t,s={}){return ps(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function Pt(a){return a?.languages||a?.supportedLanguages||["en"]}function St(a){return a?.fallback||a?.fallbackLanguage||"en"}var je=class extends A{constructor(e={}){super(re,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:X.next.middleware,manifestPath:X.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
240
+ `}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 c=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of c){let l=this.pathResolver.getRelativePath(p);if(l.startsWith(`${e}/static/`)){let u=`/_next/${l.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 Te=class extends A{constructor(e={}){super(we,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||Oe.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 vt(a={}){return new Te(a)}import{createRequire as us}from"node:module";function bt(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,(c,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(o)].forEach(c=>{let p=c[1],l=c[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${l}'`)}),Function(`return ${r}`)()}catch{return null}}var le=null,yt=null;function ls(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var re=class extends C{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(le&&yt===s)return this.logger.debug("Using cached route discovery results"),this.routes=le.routes,this.errors=le.errors,this.source=le.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/"),le={routes:this.routes,errors:this.errors,source:this.source},yt=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 c=new Map;for(let p of this.routes){let l=p.path;if(c.has(l)){let u=c.get(l);throw new Error(`Route conflict: Multiple routes found for path '${l}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}c.set(l,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=ls(o),p=i===ne.HOMEPAGE_COMPONENT?ne.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),l=this._extractPageMeta(r,s),{entity:u,action:h,...g}=n||{};return{path:p,component:i,importPath:o,auth:n?.auth||!1,meta:{...l,...g,entity:l.entity,action:l.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=bt(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])/g," $1").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 ps(a,e,t="configuration-error",s={}){let r=`[${a}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=a,o.context=s,o}function wt(a,e,t,s={}){return ps(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function Pt(a){return a?.languages||a?.supportedLanguages||["en"]}function St(a){return a?.fallback||a?.fallbackLanguage||"en"}var je=class extends A{constructor(e={}){super(re,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:X.next.middleware,manifestPath:X.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
241
  // Generated at: ${new Date().toISOString()}
242
242
  // Populates _DNDEV_CONFIG_.routes with discovery results
243
243
 
@@ -256,7 +256,7 @@ if (typeof globalThis !== 'undefined') {
256
256
  timestamp: Date.now(),
257
257
  };
258
258
  }
259
- globalThis._DNDEV_CONFIG_.${O.routes} = {
259
+ globalThis._DNDEV_CONFIG_.${I.routes} = {
260
260
  mapping: routeMapping,
261
261
  manifest: routeManifest,
262
262
  };
@@ -497,7 +497,7 @@ export const routeManifest = {
497
497
 
498
498
  export default pageRoutes;
499
499
  `}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(`
500
- `).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function $t(a={}){return new je(a)}import{readFileSync as gs,readdirSync as hs,existsSync as fs}from"fs";import{join as Rt}from"path";var Pe=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:n,crawlDelay:i=1,routes:c={},...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:i,routes:c,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=R("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(),i={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:o.routes.length,publicRoutes:o.routes.filter(c=>!c.auth||c.auth===!1).length,protectedRoutes:o.routes.filter(c=>c.auth&&c.auth.required).length,blogPosts:n.length};return this.options.generateRobotsTxt&&(i.robotsTxt=await this.generateRobotsTxt(o,t,s)),this.options.generateSitemap&&(i.sitemap=await this.generateSitemap(o,t,s,n)),n.length>0&&(i.rss=await this.generateRSSFeed(n,t,s)),i.manifest=await this.generateManifest(o,t,s),i}catch(r){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`),r}}async generateRobotsTxt(e,t,s=null){if(s&&await s("robots.txt"))return this.logger.info("\u2705 robots.txt already exists, skipping generation"),{fileName:"robots.txt",skipped:!0};let r=[];(e.routes||[]).forEach(n=>{if(n.auth&&n.auth.required){let i=n.path.startsWith("/")?n.path:`/${n.path}`;r.push(i)}}),r.push("/admin","/api","/_next","/static");let o=this.generateRobotsTxtContent({disallowedPaths:[...new Set(r)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",o),{fileName:"robots.txt",content:o,disallowedPaths:r.length}}async generateSitemap(e,t,s=null,r=[]){if(s&&await s("sitemap.xml"))return this.logger.info("\u2705 sitemap.xml already exists, skipping generation"),{fileName:"sitemap.xml",skipped:!0};let n=(e.routes||[]).filter(c=>!c.auth||c.auth===!1).map(c=>({url:c.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:c.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 c of r)n.push({url:`/blog/${c.slug}`,lastmod:c.date,changefreq:"monthly",priority:"0.6"})}let i=this.generateSitemapContent(n);return await t("sitemap.xml",i),{fileName:"sitemap.xml",content:i,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=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...s.map(c=>`Disallow: ${n(c)}`),...t.map(c=>`Allow: ${n(c)}`)];return o&&i.push(`Crawl-delay: ${o}`),r&&i.push(`Sitemap: ${r}`),i.join(`
500
+ `).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function $t(a={}){return new je(a)}import{readFileSync as gs,readdirSync as hs,existsSync as fs}from"fs";import{join as Rt}from"path";var Pe=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:n,crawlDelay:i=1,routes:c={},...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:i,routes:c,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=x("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(),i={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:o.routes.length,publicRoutes:o.routes.filter(c=>!c.auth||c.auth===!1).length,protectedRoutes:o.routes.filter(c=>c.auth&&c.auth.required).length,blogPosts:n.length};return this.options.generateRobotsTxt&&(i.robotsTxt=await this.generateRobotsTxt(o,t,s)),this.options.generateSitemap&&(i.sitemap=await this.generateSitemap(o,t,s,n)),n.length>0&&(i.rss=await this.generateRSSFeed(n,t,s)),i.manifest=await this.generateManifest(o,t,s),i}catch(r){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`),r}}async generateRobotsTxt(e,t,s=null){if(s&&await s("robots.txt"))return this.logger.info("\u2705 robots.txt already exists, skipping generation"),{fileName:"robots.txt",skipped:!0};let r=[];(e.routes||[]).forEach(n=>{if(n.auth&&n.auth.required){let i=n.path.startsWith("/")?n.path:`/${n.path}`;r.push(i)}}),r.push("/admin","/api","/_next","/static");let o=this.generateRobotsTxtContent({disallowedPaths:[...new Set(r)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",o),{fileName:"robots.txt",content:o,disallowedPaths:r.length}}async generateSitemap(e,t,s=null,r=[]){if(s&&await s("sitemap.xml"))return this.logger.info("\u2705 sitemap.xml already exists, skipping generation"),{fileName:"sitemap.xml",skipped:!0};let n=(e.routes||[]).filter(c=>!c.auth||c.auth===!1).map(c=>({url:c.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:c.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 c of r)n.push({url:`/blog/${c.slug}`,lastmod:c.date,changefreq:"monthly",priority:"0.6"})}let i=this.generateSitemapContent(n);return await t("sitemap.xml",i),{fileName:"sitemap.xml",content:i,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=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...s.map(c=>`Disallow: ${n(c)}`),...t.map(c=>`Allow: ${n(c)}`)];return o&&i.push(`Crawl-delay: ${o}`),r&&i.push(`Sitemap: ${r}`),i.join(`
501
501
  `)}generateSitemapContent(e){return`<?xml version="1.0" encoding="UTF-8"?>
502
502
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
503
503
  ${e.map(({url:s,lastmod:r,changefreq:o,priority:n})=>{let i=[` <loc>${this.options.baseUrl}${s}</loc>`];return r&&i.push(` <lastmod>${r}</lastmod>`),o&&i.push(` <changefreq>${o}</changefreq>`),n&&i.push(` <priority>${n}</priority>`),` <url>
@@ -525,7 +525,7 @@ ${i.join(`
525
525
  <atom:link href="${this.options.baseUrl}/rss.xml" rel="self" type="application/rss+xml"/>
526
526
  ${r}
527
527
  </channel>
528
- </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 Me=class extends A{constructor(e={}){super(re,e);let t=b.getInstance(),s=R("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 c=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(c)?c:`https://${c}`}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(c=>s.warn(` - ${c}`)),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 Pe({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(a={}){return new Me(a)}function kt(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),Be.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var Se=class extends C{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new B(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 ze=class extends A{constructor(e={}){super(Se,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new B(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(o=>!o.essential).length,r=t.length;if(r===0)throw wt("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
528
+ </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 Me=class extends A{constructor(e={}){super(re,e);let t=y.getInstance(),s=x("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 c=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(c)?c:`https://${c}`}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(c=>s.warn(` - ${c}`)),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 Pe({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(a={}){return new Me(a)}function kt(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),Be.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var Se=class extends C{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new B(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 ze=class extends A{constructor(e={}){super(Se,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new B(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(o=>!o.essential).length,r=t.length;if(r===0)throw wt("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
529
529
  // Generated at: ${new Date().toISOString()}
530
530
  // Populates _DNDEV_CONFIG_ with discovery results
531
531
 
@@ -557,7 +557,7 @@ if (typeof globalThis !== 'undefined') {
557
557
  timestamp: Date.now(),
558
558
  };
559
559
  }
560
- globalThis._DNDEV_CONFIG_.${O.themes} = themeConfig;
560
+ globalThis._DNDEV_CONFIG_.${I.themes} = themeConfig;
561
561
  }
562
562
 
563
563
  // Export for compatibility
@@ -573,6 +573,6 @@ export function useTheme() {
573
573
  }
574
574
 
575
575
  export default useTheme;
576
- `}};function At(a={}){return new ze(a)}function _t({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:i,pwaOptions:c,serverShimOptions:p,appUrl:l,isDev:u,logger:h}){let g=s.debug??a,d=r.debug??a,w=o.debug??a,$=n.debug??a,H=i.debug??a,V=c.debug??a,x=p.debug??a,J=s.verbose??e,Q=r.verbose??e,q=o.verbose??e,E=n.verbose??e,j=i.verbose??e,oe=c.verbose??e,ee=p.verbose??e,f={debug:a,verbose:e,generateManifest:t},G=s.disabled?null:$t({...f,...s,debug:g,verbose:J});a&&h.debug(`Route handler created: ${G?"enabled":"disabled"} (debug: ${g})`);let M=At({...f,...r,debug:d,verbose:Q}),I=mt({...f,...o,debug:w,verbose:q}),Y=dt({...f,...n,debug:$,verbose:E}),v=xt({...f,...i,debug:H,verbose:j,appUrl:l,isDev:u}),y=vt({...f,...c,debug:V,verbose:oe}),P=kt({...f,...p,debug:x,verbose:ee});return{routeHandler:G,themeHandler:M,i18nHandler:I,assetHandler:Y,seoHandler:v,pwaHandler:y,serverShimHandler:P}}function Et(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}function ds(a){if(!a)return[];let e=b.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),c=e.readSync(i,{format:"json"});if(!c?.peerDependenciesMeta)continue;for(let[p,l]of Object.entries(c.peerDependenciesMeta))l?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function ms(a){if(!a)return[];let e=b.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=fe.optionalFeatures||[],t=ds(a),s=ms(a);return[...new Set([...e,...t,...s])]}function bs(a){let e=b.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 Le(a){let e=vs(a),t=[],s=[],r=b.getInstance(),o=bs(a);for(let n of e)n.startsWith("@donotdev/")?o.has(n)?s.push(n):t.push(n):ys(n,a,r)?s.push(n):t.push(n);return{missing:t,installed:s}}function ws(a={}){let{port:e,...t}=a;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let L=process.env.CI==="true";process.env.DNDEV_BUILD_ID=L?`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,i=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:c,seo:p,...l}=r,u={...o?{features:o}:{},...n?{seo:n}:{},...l},h=ht(u),g=ft(h);if(!g)throw new Error("normalizeOptions returned undefined");let{generateManifest:d,debug:w,verbose:$,mode:H,isDev:V,routeOptions:x,themeOptions:J,i18nOptions:Q,assetOptions:q,pwaOptions:E,seoOptions:j,serverShimOptions:oe,nextConfigOptions:ee}=g,f=R("next-config",w,$),{appRoot:G,appRootSet:M}=Ke({logger:f,debug:w}),I=!1,Y=!1,{installed:v}=Le(process.cwd()),y=Object.values(We.packageNames),P=y.filter(L=>!v.includes(L)),k=y.filter(L=>v.includes(L)),pe=process.env.DNDEV_BUILD_ID,$e=x?.routingMode||"app";if(f.info(`
576
+ `}};function At(a={}){return new ze(a)}function _t({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:i,pwaOptions:c,serverShimOptions:p,appUrl:l,isDev:u,logger:h}){let g=s.debug??a,d=r.debug??a,P=o.debug??a,$=n.debug??a,H=i.debug??a,V=c.debug??a,k=p.debug??a,J=s.verbose??e,Q=r.verbose??e,q=o.verbose??e,E=n.verbose??e,j=i.verbose??e,oe=c.verbose??e,ee=p.verbose??e,f={debug:a,verbose:e,generateManifest:t},G=s.disabled?null:$t({...f,...s,debug:g,verbose:J});a&&h.debug(`Route handler created: ${G?"enabled":"disabled"} (debug: ${g})`);let M=At({...f,...r,debug:d,verbose:Q}),O=mt({...f,...o,debug:P,verbose:q}),Y=dt({...f,...n,debug:$,verbose:E}),v=xt({...f,...i,debug:H,verbose:j,appUrl:l,isDev:u}),b=vt({...f,...c,debug:V,verbose:oe}),w=kt({...f,...p,debug:k,verbose:ee});return{routeHandler:G,themeHandler:M,i18nHandler:O,assetHandler:Y,seoHandler:v,pwaHandler:b,serverShimHandler:w}}function Et(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}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),c=e.readSync(i,{format:"json"});if(!c?.peerDependenciesMeta)continue;for(let[p,l]of Object.entries(c.peerDependenciesMeta))l?.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=fe.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 Le(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):ys(n,a,r)?s.push(n):t.push(n);return{missing:t,installed:s}}function ws(a={}){let{port:e,...t}=a;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let L=process.env.CI==="true";process.env.DNDEV_BUILD_ID=L?`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,i=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:c,seo:p,...l}=r,u={...o?{features:o}:{},...n?{seo:n}:{},...l},h=ht(u),g=ft(h);if(!g)throw new Error("normalizeOptions returned undefined");let{generateManifest:d,debug:P,verbose:$,mode:H,isDev:V,routeOptions:k,themeOptions:J,i18nOptions:Q,assetOptions:q,pwaOptions:E,seoOptions:j,serverShimOptions:oe,nextConfigOptions:ee}=g,f=x("next-config",P,$),{appRoot:G,appRootSet:M}=Ke({logger:f,debug:P}),O=!1,Y=!1,{installed:v}=Le(process.cwd()),b=Object.values(We.packageNames),w=b.filter(L=>!v.includes(L)),R=b.filter(L=>v.includes(L)),pe=process.env.DNDEV_BUILD_ID,$e=k?.routingMode||"app";if(f.info(`
577
577
  \u{1F3D7}\uFE0F DnDev Framework - Building for ${H}${pe?` [build:${pe}]`:""}`),f.info(` Platform: Next.js | Routing: ${$e}
578
- `),V){let L=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${L}`,w&&(f.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&f.debug(`Port configured: ${L} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||f.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let N=_t({debug:w,verbose:$,generateManifest:d,routeOptions:x,themeOptions:J,i18nOptions:Q,assetOptions:q,seoOptions:j,pwaOptions:E,serverShimOptions:oe,isDev:V,logger:f}),z=Et(N,f);return async function(Re={}){let te=b.getInstance(),ue=M?st():[];w&&ue.length>0&&f.debug(`Discovered ${ue.length} packages: ${ue.join(", ")}`);let{missing:ge}=Le(te.getAppRoot());w&&ge.length>0&&f.debug(`Missing optional deps (will alias to empty): ${ge.join(", ")}`);let Ue=te.getAppRoot();if(M&&!I){let xe=te.resolveAppPath(".dndev-build"),ke=process.env.DNDEV_BUILD_ID;try{te.readSync(xe,{format:"text"})?.trim()===ke?(f.debug("Discoveries already completed by another worker, skipping"),I=!0):(Fe(Ue,f),await Ce(N,f),I=!0)}catch{Fe(Ue,f),await Ce(N,f),I=!0}}let K=typeof Re=="object"&&Re!==null?Re:{},{webpack:Ft,rewrites:Ct,...Dt}=K;M&&!Y&&(Y=await ut(N.assetHandler,f,Y));let It=z.routeConfig(K),Ot=z.themeConfig(K),Tt=z.i18nConfig(K),jt=z.assetConfig(K),Mt=z.seoConfig(K),zt=z.pwaConfig(K),Lt=z.serverShimConfig(),Ut=ot({originalWebpack:Ft,unusedFeaturePackages:P,usedFeaturePackages:k,missingOptionalDeps:ge,logger:f,debug:w}),Gt=nt({originalRewrites:Ct,handlers:[N.routeHandler,N.themeHandler,N.i18nHandler,N.assetHandler,N.pwaHandler],logger:f}),Wt={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()}),...process.env.NEXT_PUBLIC_APP_URL?{NEXT_PUBLIC_APP_URL:process.env.NEXT_PUBLIC_APP_URL}:{},...process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY?{NEXT_PUBLIC_DONOTDEV_LICENSE_KEY:process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY}:{}},Bt=at({routeResult:It,themeResult:Ot,i18nResult:Tt,assetResult:jt,seoResult:Mt,pwaResult:zt,serverShimResult:Lt,restNextConfig:Dt,discoveredPackages:ue,webpackConfig:Ut,rewritesConfig:Gt,missingOptionalDeps:ge,pathResolver:te,env:Wt,logger:f});if(f.debug("Next.js config generated"),M){let xe=i?.name||"app",ke=te.getAppRoot();f.info(`Name: ${xe}`),f.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),f.info("\u{1F527} Features: auto-detected"),f.info(`App root (final): ${ke}`)}return Bt}}var Nt=ws;export{Nt as default,Nt as defineNextConfig,es as definePostCSSConfig};
578
+ `),V){let L=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${L}`,P&&(f.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&f.debug(`Port configured: ${L} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||f.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let N=_t({debug:P,verbose:$,generateManifest:d,routeOptions:k,themeOptions:J,i18nOptions:Q,assetOptions:q,seoOptions:j,pwaOptions:E,serverShimOptions:oe,isDev:V,logger:f}),z=Et(N,f);return async function(Re={}){let te=y.getInstance(),ue=M?st():[];P&&ue.length>0&&f.debug(`Discovered ${ue.length} packages: ${ue.join(", ")}`);let{missing:ge}=Le(te.getAppRoot());P&&ge.length>0&&f.debug(`Missing optional deps (will alias to empty): ${ge.join(", ")}`);let Ue=te.getAppRoot();if(M&&!O){let xe=te.resolveAppPath(".dndev-build"),ke=process.env.DNDEV_BUILD_ID;try{te.readSync(xe,{format:"text"})?.trim()===ke?(f.debug("Discoveries already completed by another worker, skipping"),O=!0):(Fe(Ue,f),await Ce(N,f),O=!0)}catch{Fe(Ue,f),await Ce(N,f),O=!0}}let K=typeof Re=="object"&&Re!==null?Re:{},{webpack:Ft,rewrites:Ct,...Dt}=K;M&&!Y&&(Y=await ut(N.assetHandler,f,Y));let Ot=z.routeConfig(K),It=z.themeConfig(K),Tt=z.i18nConfig(K),jt=z.assetConfig(K),Mt=z.seoConfig(K),zt=z.pwaConfig(K),Lt=z.serverShimConfig(),Ut=ot({originalWebpack:Ft,unusedFeaturePackages:w,usedFeaturePackages:R,missingOptionalDeps:ge,logger:f,debug:P}),Gt=nt({originalRewrites:Ct,handlers:[N.routeHandler,N.themeHandler,N.i18nHandler,N.assetHandler,N.pwaHandler],logger:f}),Wt={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()}),...process.env.NEXT_PUBLIC_APP_URL?{NEXT_PUBLIC_APP_URL:process.env.NEXT_PUBLIC_APP_URL}:{},...process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY?{NEXT_PUBLIC_DONOTDEV_LICENSE_KEY:process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY}:{}},Bt=at({routeResult:Ot,themeResult:It,i18nResult:Tt,assetResult:jt,seoResult:Mt,pwaResult:zt,serverShimResult:Lt,restNextConfig:Dt,discoveredPackages:ue,webpackConfig:Ut,rewritesConfig:Gt,missingOptionalDeps:ge,pathResolver:te,env:Wt,logger:f});if(f.debug("Next.js config generated"),M){let xe=i?.name||"app",ke=te.getAppRoot();f.info(`Name: ${xe}`),f.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),f.info("\u{1F527} Features: auto-detected"),f.info(`App root (final): ${ke}`)}return Bt}}var Nt=ws;export{Nt as default,Nt as defineNextConfig,es as definePostCSSConfig};