@donotdev/core 0.1.47 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/functions/index.js +13 -11
- package/i18n/locales/lazy/auth_ar.json +1 -1
- package/i18n/locales/lazy/auth_da.json +1 -1
- package/i18n/locales/lazy/auth_de.json +1 -1
- package/i18n/locales/lazy/auth_en.json +1 -1
- package/i18n/locales/lazy/auth_es.json +1 -1
- package/i18n/locales/lazy/auth_fr.json +1 -1
- package/i18n/locales/lazy/auth_it.json +1 -1
- package/i18n/locales/lazy/auth_ja.json +1 -1
- package/i18n/locales/lazy/auth_ko.json +1 -1
- package/i18n/locales/lazy/auth_nl.json +1 -1
- package/i18n/locales/lazy/auth_pt.json +1 -1
- package/i18n/locales/lazy/auth_zh.json +1 -1
- package/i18n/locales/lazy/cookies_ar.json +4 -1
- package/i18n/locales/lazy/cookies_da.json +4 -1
- package/i18n/locales/lazy/cookies_de.json +4 -1
- package/i18n/locales/lazy/cookies_en.json +4 -1
- package/i18n/locales/lazy/cookies_es.json +4 -1
- package/i18n/locales/lazy/cookies_fr.json +4 -1
- package/i18n/locales/lazy/cookies_it.json +4 -1
- package/i18n/locales/lazy/cookies_ja.json +4 -1
- package/i18n/locales/lazy/cookies_ko.json +4 -1
- package/i18n/locales/lazy/cookies_nl.json +4 -1
- package/i18n/locales/lazy/cookies_pt.json +4 -1
- package/i18n/locales/lazy/cookies_zh.json +4 -1
- package/index.d.ts +955 -132
- package/index.js +6 -6
- package/next/index.d.ts +7 -0
- package/next/index.js +59 -57
- package/package.json +24 -24
- package/server.d.ts +858 -108
- package/server.js +1 -14
- package/symbol-index.json +1 -0
- package/vite/index.d.ts +7 -0
- package/vite/index.js +71 -69
package/next/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import*as y from"node:fs";import"node:fs";import{createRequire as Ps}from"node:module";import{resolve as he,join as Y,dirname as K,relative as ot,normalize as Ss,sep as nt,extname as $s}from"node:path";import{fileURLToPath as xs}from"node:url";import Rs from"fast-glob";var ge={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var Ee={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},L={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},F={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ce={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},fe={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},be={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},j={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${be.SOURCE_EAGER}/*_*.json`],lazy:[`${be.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/**"]},ye={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},st=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var Ne={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}};var ne={inter:[300,400,600,700],"playfair-display":[400,500,600,700],roboto:[400,700],"space-grotesk":[300,400,500,600,700],"press-start-2p":[400]},we={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin"],cs:["latin"],sk:["latin"],hr:["latin"],sl:["latin"],hu:["latin"],ro:["latin"],et:["latin"],lv:["latin"],lt:["latin"],mt:["latin"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},Fe=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],tt={base:{absolute:!0,onlyFiles:!0,ignore:j.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...j.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...j.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:j.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:j.globalIgnore}};function rt(i,e=null){let t=j[i];if(!t)throw new Error(`Unknown pattern type: ${i}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Pe(i){return tt[i]||tt.base}var ae={getGlobOptionsFor:Pe||void 0,SCAN_PATTERNS:j||void 0,getPatternsFor:rt||void 0,I18N_PATHS:be||void 0},A={error:(i,e)=>{},warn:(i,e)=>{},info:i=>{}};function at(i,e){return i().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var it={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"},w=class i{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return i._instance||(i._instance=new i(e)),i._instance}static _reset(){i._instance=null}constructor(e={}){if(i._instance)return i._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,i._instance=this}normalizePath(e){if(!e)return"";try{return Ss(e).split(nt).join("/")}catch{return String(e).split(nt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=ot(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(K(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Ps(Y(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let n=e.replace("@donotdev/",""),a=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(a))return a;if(["auth","billing","crud","oauth"].includes(n)){let l=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(l))return l}if(n==="firebase"){let l=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(l))return l}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=he(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=he(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=he(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=y.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:$s(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await y.promises.readFile(e);let n=await y.promises.readFile(e,r),a=this.stripBom(n);return o==="json"?JSON.parse(a):a}catch(n){return this.options.debug&&A.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 y.readFileSync(e);let n=y.readFileSync(e,r),a=this.stripBom(n);return o==="json"?JSON.parse(a):a}catch(n){return this.options.debug&&A.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:a=!1}=s,l=this.normalizePath(e),p=this.normalizePath(K(l)),c=this.pathExists(l);if(c&&!o)return a&&A.info(`Skipping existing file: ${l}`),!1;if(n)return A.info(`[DRY RUN] Would write file: ${l}`),!0;try{await y.promises.mkdir(p,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await at(async()=>(Buffer.isBuffer(g)?await y.promises.writeFile(l,g):await y.promises.writeFile(l,g,"utf8"),a&&A.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:a=!1}=s,l=this.normalizePath(e),p=this.normalizePath(K(l)),c=this.pathExists(l);if(c&&!o)return a&&A.info(`Skipping existing file: ${l}`),!1;if(n)return A.info(`[DRY RUN] Would write file: ${l}`),!0;try{y.mkdirSync(p,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return Buffer.isBuffer(g)?y.writeFileSync(l,g):y.writeFileSync(l,g,"utf8"),a&&A.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!r)return n&&A.info(`Skipping existing file: ${a}`),!1;if(o)return A.info(`[DRY RUN] Would copy file: ${a}`),!0;let p=this.normalizePath(K(a));try{await y.promises.mkdir(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await at(async()=>(await y.promises.copyFile(e,a),n&&A.info(`${l?"Updated":"Created"} file: ${a}`),!0),`Failed to copy file from ${e} to ${a}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!r)return n&&A.info(`Skipping existing file: ${a}`),!1;if(o)return A.info(`[DRY RUN] Would copy file: ${a}`),!0;let p=this.normalizePath(K(a));try{y.mkdirSync(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return y.copyFileSync(e,a),n&&A.info(`${l?"Updated":"Created"} file: ${a}`),!0}catch{return!1}}pathExists(e,t=!1){try{return y.existsSync(e)}catch(s){return t||A.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 y.existsSync(t)||y.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return y.readdirSync(e,t)}catch(s){return this.options.debug&&A.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return y.statSync(e)}catch(t){return this.options.debug&&A.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return y.realpathSync(e)}watch(e,t,s){return y.watch(e,t,s)}lstatSync(e){try{return y.lstatSync(e)}catch(t){return this.options.debug&&A.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await y.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{y.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await y.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){y.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return y.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=Y(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(he(e)),s=this.getAppRoot(),r=ot(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(Y(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),a=r.startsWith(n)?r.slice(n.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:ae.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([a],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ae.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(Y(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await Rs(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=ae.getGlobOptionsFor?ae.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),a=e.framework.map(c=>{let u=this.normalizePath(c);return u.startsWith(n)?u.slice(n.length+1):u}),l=e.consumer.map(c=>{let u=this.normalizePath(c);return u.startsWith(n)?u.slice(n.length+1):u}),p={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=a.length>0?await this._globWithNormalization(a,p):[],u=await this._globWithNormalization(l,p);return{frameworkFiles:c,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ae.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=ae.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=r,p={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return p.all=[...p.eager,...p.lazy,...p.framework.eager,...p.framework.lazy],p}let n=r,a={framework:o?(n.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(n.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return a.all=[...a.consumer,...a.framework],a}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyFlagModulePath(){let e=K(xs(import.meta.url));return this.normalizePath(he(e,"emptyFlag.js"))}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(Y(t,it.TOOLING)),n=this.normalizePath(Y(t,it.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let a=Y(t,"apps");if(this.pathExists(a)&&this.statSync(a)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(Y(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(K(t))===t)return t;let p=this.normalizePath(K(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function lt({logger:i,debug:e=!1}={}){let t=w.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&i&&i.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):i&&i.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&i&&i.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let n=t.resolveRepoPath("apps");if(t.pathExists(n))try{let a=process.cwd(),l=t.normalizePath(a);if(l.includes("/apps/")){let p=l.indexOf("/apps/"),u=l.substring(p+6).split("/")[0];if(u){let g=t.resolveRepoPath(`apps/${u}`),f=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(f)&&(r=g,t.setAppRoot(r),s=!0,e&&i&&i.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&i&&i.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}import mt from"node:fs";function ct(i){let e=new Set(Object.keys(ne)),t=new Set(["latin"]);for(let o of i||[]){let n=we[o];if(n)for(let a of n)t.add(a)}let s=[],r=new Set;for(let o of e){let n=ne[o];for(let a of t)for(let l of n){let p=`@fontsource/${o}/${a}-${l}.css`,c=`${o}-${a}-${l}-normal`;s.push(p),r.add(c)}}return{imports:s,stems:r,subsets:t,fontStems:e}}function De(i){return i.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}import*as T from"@clack/prompts";var B={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function ks(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function H(i,e){return ks()?`${e}${i}${B.reset}`:i}function C(i,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=w.getInstance(),a=null;if(o){let c=n.resolveAppPath(r);n.pathExists(c)||n.mkdir(c),a=n.resolveAppPath(`${r}/${i.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${i} Log Started at ${new Date().toISOString()} ===
|
|
2
|
-
|
|
3
|
-
`;n.appendFile(a,d)}},p=(c,u)=>{if(u.length===0)return c;let g=u.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${c} ${g}`};return{debug:(c,...u)=>{e&&(o?l("DEBUG",c,u):T.log.message(H(p(c,u),B.gray)))},verbose:(c,...u)=>{t&&(o?l("VERBOSE",c,u):T.log.message(p(c,u)))},info:(c,...u)=>{o?l("INFO",c,u):T.log.info(H(p(c,u),B.brightCyan))},warn:(c,...u)=>{e&&o?l("WARN",c,u):T.log.warn(H(p(c,u),B.brightYellow))},error:(c,...u)=>{e&&o?l("ERROR",c,u):T.log.error(H(p(c,u),B.brightRed))},success:(c,...u)=>{e&&o?l("SUCCESS",c,u):T.log.success(H(p(c,u),B.brightGreen))},when:(c,u="debug")=>(g,...f)=>{if(c){let h=p(g,f);switch(u){case"verbose":t&&(T.log.message(h),l("VERBOSE",g,f));break;case"info":T.log.info(H(h,B.brightCyan)),l("INFO",g,f);break;case"warn":T.log.warn(H(h,B.brightYellow)),l("WARN",g,f);break;case"error":T.log.error(H(h,B.brightRed)),l("ERROR",g,f);break;case"success":T.log.success(H(h,B.brightGreen)),l("SUCCESS",g,f);break;default:e&&(T.log.message(H(h,B.gray)),l("DEBUG",g,f))}}},getLogFilePath:()=>a}}var z=class i{constructor(e,t={}){if(this.constructor===i)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=C(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let n=Date.now()-t;return this.logger.debug(`Discovery completed in ${n}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};function _s(i){if(!i)return[];let e=w.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",i);if(!s)return[];let r=e.getDirname(e.getDirname(s)),o;try{o=e.readdirSync(r)}catch{return[]}for(let n of o)try{let a=e.resolvePath(`${n}/package.json`,r),l=e.readSync(a,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[p,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function As(i){if(!i)return[];let e=w.getInstance();try{let t=e.resolvePath("package.json",i),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[o,n]of Object.entries(s.peerDependenciesMeta))n?.optional&&r.add(o);if(s.optionalDependencies)for(let o of Object.keys(s.optionalDependencies))r.add(o);return Array.from(r)}catch{return[]}}function Es(i){let e=ye.optionalFeatures||[],t=_s(i),s=As(i);return[...new Set([...e,...t,...s])]}function Cs(i){let e=w.getInstance();try{let t=e.resolvePath("package.json",i),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function Ns(i,e,t){if(t.resolvePackage(i,e||void 0))return!0;let s=i.startsWith("@")?i.split("/").slice(0,2).join("/"):i.split("/")[0],r=e;for(let o=0;o<10;o++){let n=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(n))return!0;let a=t.getDirname(r);if(a===r)break;r=a}return!1}function Se(i){let e=Es(i),t=[],s=[],r=w.getInstance(),o=Cs(i);for(let n of e)n.startsWith("@donotdev/")?o.has(n)?s.push(n):t.push(n):o.has(n)&&Ns(n,i,r)?s.push(n):t.push(n);return{missing:t,installed:s}}var ie=class i extends z{static LANGUAGE_FLAG_OVERRIDES={en:"gb","en-ca":"ca","es-ar":"ar","fr-be":"be",ar:"sa","ar-ma":"ma","ar-dz":"dz","ar-tn":"tn","ar-ly":"ly","ar-mr":"mr",hi:"in",sl:"si",uk:"ua",ga:"ie",gd:"gb-sct",br:"bzh",co:"fr-cor",am:"et",bn:"bd",gu:"in",kn:"in",ml:"in",mr:"in",ne:"np",pa:"pk",ta:"in",te:"in",ur:"pk",fa:"ir",kk:"kz",ky:"kg",tg:"tj",my:"mm",km:"kh",lo:"la",ka:"ge",hy:"am",be:"by",bs:"ba",sq:"al",ms:"my"};constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],...t})}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Pe("i18n"),n=r.eager||[],a=r.lazy||[],l=(this.options.additionalPaths||[]).map(m=>{let S=m.endsWith(".json")?m:`${m}/*_*.json`;return this.pathResolver.resolveAppPath(S)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let p=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${a.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${c.join(", ")}`),p.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),f=(m,S)=>{let R=this.pathResolver.normalizePath(m),x=this.pathResolver.normalizePath(S);return R.startsWith(x)?R.slice(x.length+1):R},h=n.map(m=>f(m,t)),v=[...a,...l].map(m=>f(m,t)),b=p.map(m=>f(m,s)),k=c.map(m=>f(m,s)),D={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},O=await this.pathResolver._globWithNormalization(h,D),I=await this.pathResolver._globWithNormalization(v,D),_={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(m=>m!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(_.ignore)}`);let M=await this.pathResolver._globWithNormalization(b,_),V=await this.pathResolver._globWithNormalization(k,_);this.logger.debug(`Found ${O.length} eager, ${I.length} lazy, ${M.length} framework eager, ${V.length} framework lazy files`),M.length>0?this.logger.debug(`Framework eager files (first 3): ${M.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),V.length>0?this.logger.debug(`Framework lazy files (first 3): ${V.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let se=[...new Set([...O,...I,...M,...V])],X=new Set([...O,...M]),P={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:re}=Se(t),$=new Set(re.filter(m=>m.startsWith("@donotdev/")).map(m=>m.replace("@donotdev/","")));$.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...$].join(", ")}] (packages not installed)`);let q=new Map,W=[...M,...V];for(let m of W){let S=this._processTranslationFile(m,M.includes(m),t);if(S){if($.has(S.namespace))continue;let R=`${S.namespace}_${S.language}`;q.set(R,S),P.allNamespaces.add(S.namespace),P.supportedLanguages.add(S.language),M.includes(m)&&P.eagerNamespaces.add(S.namespace)}}let U=new Set;for(let m of se){if(W.includes(m))continue;let S=this._processTranslationFile(m,X.has(m),t);if(S){let{namespace:R,language:x,importPath:G,content:pe}=S,Q=`${S.namespace}_${S.language}`;if(q.has(Q)){let ee=q.get(Q);S.content=this._mergeTranslations(ee.content,pe)}P.allNamespaces.add(R),P.supportedLanguages.add(x),U.add(x),X.has(m)&&P.eagerNamespaces.add(R),P.mapping[R]||(P.mapping[R]={}),P.mapping[R][x]=G,S.content&&(P.content[R]||(P.content[R]={}),P.content[R][x]=S.content),P.files.push({path:m,relativePath:this.pathResolver.getRelativePath(m),namespace:R,language:x,eager:X.has(m),size:S.content?JSON.stringify(S.content).length:0})}}for(let[m,S]of q){let R=m.lastIndexOf("_"),x=m.slice(0,R),G=m.slice(R+1);U.size>0&&!U.has(G)||(!P.mapping[x]||!P.mapping[x][G])&&(P.mapping[x]||(P.mapping[x]={}),P.mapping[x][G]=S.importPath,P.content[x]||(P.content[x]={}),P.content[x][G]=S.content,P.files.push({path:S.absolutePath,relativePath:this.pathResolver.getRelativePath(S.absolutePath),namespace:x,language:G,eager:P.eagerNamespaces.has(x),size:S.content?JSON.stringify(S.content).length:0}))}let Z=U.size>0?[...U].sort():[this.options.fallbackLanguage],oe=[...new Set(Z.map(m=>i.LANGUAGE_FLAG_OVERRIDES[m]||m))];return{mapping:P.mapping,content:P.content,eagerNamespaces:[...P.eagerNamespaces].sort(),allNamespaces:[...P.allNamespaces].sort(),supportedLanguages:Z,fallbackLanguage:this.options.fallbackLanguage,flagCodes:oe,files:P.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[i.LANGUAGE_FLAG_OVERRIDES[this.options.fallbackLanguage]||this.options.fallbackLanguage],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,n,a=r.match(/^(.+)_([^_.]+)\.json$/);if(!a)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,n]=a,!o||!n)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let p="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:o,language:n,importPath:p,absolutePath:e,content:c}}_mergeTranslations(e,t){let s={...e};for(let[r,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?s[r]=this._mergeTranslations(s[r]||{},o):s[r]=o;return s}};var Fs=3,pt="dndev-font-preloads.json";function ut({pathResolver:i,debug:e=!1}){let t=C("font-preload-next",e,!1);return{apply(s){s.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(r,o)=>{if(r.compiler.isChild()||r.compiler.name?.includes("server"))return o();try{if(!i.getAppRoot())return o();let l=["en"];try{let v=await new ie(i,{fallbackLanguage:"en"}).discoverTranslations();v?.supportedLanguages?.length&&(l=v.supportedLanguages)}catch{}let c=ct(l).stems,u=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",g=[];for(let[d]of Object.entries(r.assets)){if(!d.endsWith(".woff2"))continue;let v=d.toLowerCase();if(Array.from(c).some(b=>v.includes(b))){let b=u?`${u}/${d}`:`/${d}`;if(g.push({href:b,type:"font/woff2"}),g.length>=Fs)break}}let f=i.resolveAppPath("public");if(!i.pathExists(f))try{i.ensureDirSync(f)}catch(d){return t.debug(`Font preload: could not create public dir: ${d?.message}`),o()}let h=i.resolvePath(pt,f);i.writeSync(h,JSON.stringify(g,null,0),{overwrite:!0}),t.debug(`Font preload: wrote ${g.length} entries to ${pt}`)}catch(a){t.debug(`Font preload manifest: ${a?.message}`)}o()})}}}import{createRequire as Ds}from"node:module";var gt=Ds(import.meta.url),Oe;function Os(){return Oe===void 0&&(Oe=[[gt.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],gt.resolve("@babel/plugin-transform-parameters")]),Oe}function ft({logger:i=C("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:o}=s,{RawSource:n}=o;t.hooks.thisCompilation.tap("DndevLowerDestructuring",a=>{a.compiler.isChild()||a.compiler.name?.includes("server")||a.options.mode==="production"&&a.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async l=>{let p,c;try{p=(await import("@babel/core")).default,c=Os()}catch(g){i.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${g?.message}`);return}let u=0;for(let g of Object.keys(l)){if(!g.endsWith(".js"))continue;let f=a.getAsset(g).source.source(),h=typeof f=="string"?f:f.toString("utf8"),d;try{d=p.transformSync(h,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:c})}catch(v){throw new Error(`[lower-destructuring] failed to transform ${g}: ${v.message}`)}d?.code&&d.code!==h&&(a.updateAsset(g,new n(d.code)),u++)}e&&i.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function ht({postcssImport:i,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?i({resolve:s}):i,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var dt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Ts(i){return(e,t)=>{dt[e]&&(e=dt[e]);let s=i.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),n=i.resolveFrameworkPackage(r,t);if(n){if(o){let l=i.resolvePath(o,n);if(i.pathExists(l))return l;let p=l+".css";if(i.pathExists(p))return p}let a=i.resolvePath("index.css",n);if(i.pathExists(a))return a}}return i.resolvePath(e,t)}}async function Is(){let[i,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=w.getInstance();return ht({postcssImport:i,postcssNesting:e,autoprefixer:t,resolve:Ts(s)})}function J(i){return i&&typeof i=="object"&&!Array.isArray(i)}var vt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function bt({originalWebpack:i,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],logger:o,debug:n}){return(a,l)=>{let{dev:p,isServer:c,webpack:u}=l;p&&!c&&(a.infrastructureLogging={level:"error"},a.stats={...a.stats,logging:"error",loggingTrace:!1},a.ignoreWarnings=[...a.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let g=a.module?.rules?.find(f=>f.test?.test?.(".svg"));g&&(g.exclude=/\.svg$/i),a.module=a.module||{},a.module.rules=a.module.rules||[],a.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),a.module.rules.push({test:/\.md$/,type:"asset/source"}),a.resolve=a.resolve||{},a.resolve.alias=a.resolve.alias||{};try{let f=w.getInstance(),h=f.resolveAppPath(F.next.blogContent);a.resolve.alias[Ee.blog]=mt.existsSync(h)?h:f.getEmptyCjsModulePath()}catch(f){o.debug(`Blog content alias fallback to empty stub: ${f?.message}`)}a.resolve=a.resolve||{},a.resolve.alias={...a.resolve.alias,...vt},u?.IgnorePlugin&&a.plugins.push(new u.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let f=w.getInstance();a.plugins.push(ut({pathResolver:f,debug:n}))}catch(f){o.debug(`Font preload webpack plugin skipped: ${f?.message}`)}if(!c)try{a.plugins.push(ft({logger:o,debug:n}))}catch(f){o.debug(`Lower-destructuring webpack plugin skipped: ${f?.message}`)}if(e.length>0)if(o.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),o.info(`\u2705 Including features: ${t.join(", ")}`),a.externals=a.externals||[],Array.isArray(a.externals))a.externals.push(...e);else{let f=a.externals;a.externals=(h,d,v)=>e.includes(d)?v(null,"commonjs "+d):typeof f=="function"?f(h,d,v):v()}if(s.length>0&&u?.NormalModuleReplacementPlugin){let h=w.getInstance().getEmptyCjsModulePath(),d=s.map(b=>b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),v=new RegExp(`^(${d.join("|")})(\\/|$)`);a.plugins.push(new u.NormalModuleReplacementPlugin(v,h)),n&&o.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&u?.NormalModuleReplacementPlugin){let h=w.getInstance().getEmptyFlagModulePath(),d=new Set(r.map(v=>v.toUpperCase()));a.plugins.push(new u.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,v=>{let b=v.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);b&&b[1].toUpperCase()!=="BASE"&&!d.has(b[1].toUpperCase())&&(v.request=h)})),n&&o.debug(`Flag filter: allowing ${d.size} flags, aliasing rest to empty component`)}return i?i(a,l):a}}function yt({originalRewrites:i,handlers:e,logger:t}){return async function(){try{let s=i?await i():[],o=e.filter(a=>a?.getAPIRewrites).map(a=>a.getAPIRewrites()).reduce((a,l)=>(l?.beforeFiles&&a.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&a.afterFiles.push(...l.afterFiles),l?.fallback&&a.fallback.push(...l.fallback),a),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...o.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function Ms(i){let e=i||[],t=new Set(e.map(o=>o?.path).filter(Boolean)),s=[],r=new Set;for(let o of e){let n=String(o?.file||o?.importPath||"").replace(/\\/g,"/");if(n=n.replace(/^\/?(?:src\/)?/,""),!n.startsWith("pages/")||(n=n.slice(6).replace(/\.[jt]sx?$/,""),!n||n.split("/").some(p=>p.startsWith("_")))||n==="api"||n.startsWith("api/"))continue;n=n.replace(/(?:^|\/)index$/,"");let a=n?"/"+n:"/",l=o?.path;!l||a===l||/[[\]]/.test(a)||/[:[]/.test(l)||t.has(a)||r.has(a)||(r.add(a),s.push({from:a,to:l,permanent:!0}))}return s}function wt({originalRedirects:i,seoRedirects:e,routes:t,logger:s}){return async function(){try{let r=i?await i():[],o=Ms(t),a=[...e||[],...o].map(({from:u,to:g,permanent:f})=>({source:u,destination:g,permanent:f!==!1})),l=[],p=new Set;for(let u of a){let g=u.source.replace(/\/+$/,"")||"/",f=u.destination.replace(/\/+$/,"")||"/";if(g===f){s.warn(`Redirect loop detected: ${u.source} \u2192 ${u.destination} (skipped)`);continue}if(!u.source.startsWith("/")){s.warn(`Redirect source must start with /: "${u.source}" (skipped)`);continue}if(p.has(g)){s.warn(`Duplicate redirect source: "${u.source}" (skipped)`);continue}p.add(g),l.push(u)}let c=[...Array.isArray(r)?r:[],...l];return c.length===0?[]:(s.info(` \u{1F4CE} ${c.length} redirect${c.length>1?"s":""} configured`),c)}catch(r){return s.error(`Failed to merge redirects: ${r.message}`),[]}}}function Pt({routeResult:i,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:a,discoveredPackages:l,reactCompiler:p=!1,webpackConfig:c,rewritesConfig:u,redirectsConfig:g,missingOptionalDeps:f,flagCodes:h=[],pathResolver:d,env:v,logger:b}){let k=a?.output==="export",O=a?.distDir||".next";return{transpilePackages:[...l,...f||[]],...p?{reactCompiler:p}:{},...J(a)?a:(b.warn("restNextConfig is not a plain object:",a),{}),serverExternalPackages:(a?.serverExternalPackages||a?.serverComponentsExternalPackages||[]).filter(_=>!_.startsWith("@donotdev/")&&!f?.includes(_)),turbopack:{...a?.turbopack||{},root:a?.turbopack?.root||d.getRepoRoot(),resolveAlias:{...a?.turbopack?.resolveAlias||{},...vt,[Ee.blog]:(()=>{try{let _=d.resolveAppPath(F.next.blogContent);if(mt.existsSync(_))return"./"+F.next.blogContent}catch{}return"@donotdev/core/empty"})(),...f?.length>0?Object.fromEntries(f.flatMap(_=>[[_,"@donotdev/core/empty"],[`${_}/*`,"@donotdev/core/empty"]])):{}}},distDir:O,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...J(i)?i:(b.error(`Route handler config invalid (got ${typeof i}):`,i),{}),...J(e)?e:(b.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...J(t)?t:(b.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...J(s)?s:(b.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...J(r)?r:(b.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...J(o)?o:(b.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...J(n)?n:(b.warn("serverShimConfig returned non-object:",n),{}),webpack:c,...k?{}:{rewrites:u,...g?{redirects:g}:{}},env:v,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var $e="fonts",Te="dndev-fonts.css",js=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,$t=/url\(\.\/files\/([^)]+)\)/g;function Ls(i){let e=new Set(["latin"]);for(let t of i){let s=we[t];if(s)for(let r of s)e.add(r)}return e}function zs(i,e){let t=i.resolvePath("src/dndev.css",e),s=i.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=js.exec(s))!==null;)r.push([o[1],o[2]]);return r}function Us(i,e,t,s,r){let o=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
4
|
-
|
|
5
|
-
`,...a.map(h=>{let d=l&&Array.from(p).some(b=>h.includes(`${b}-`));return(d?De(h):h).replace($t,(b,k)=>{if(d&&k.endsWith(".woff"))return"url(data:,)";let D=i.resolvePath(k,c);if(!i.pathExists(D))return s.warn(`Font file missing: ${D} \u2014 dropping from CSS`),"url(data:,)";if(!u.has(k)){let I=i.resolvePath(k,t);i.copySync(D,I,{overwrite:!0}),u.add(k)}return`url(/${$e}/${k})`})})],copiedFiles:u}}function xt({debug:i=!1,force:e=!1,languages:t}={}){let s=C("font-copy",i,!1),r=w.getInstance(),o=r.resolveAppPath(`public/${Te}`);if(!e&&r.pathExists(o)){s.debug("dndev-fonts.css already exists, skipping font copy");return}let n=r.resolveFrameworkPackage("@donotdev/ui");if(!n){s.debug("@donotdev/ui not found, skipping font copy");return}let a=r.resolveAppPath(`public/${$e}`);r.ensureDir(a);let l=t?.length?Ls(t):null;l&&s.debug(`Font copy: locale-aware filtering \u2014 locales=[${t.join(",")}] subsets=[${[...l].join(",")}]`);let p=zs(r,n),c,u;if(p.length>0?(s.debug(`Monorepo mode: ${p.length} @fontsource imports found`),{cssChunks:c,copiedFiles:u}=Us(r,p,a,s,l)):(s.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:c,copiedFiles:u}=Bs(r,n,a,s,l)),u.size===0){s.debug("No font files found to copy");return}r.writeSync(o,c.join(`
|
|
6
|
-
`
|
|
1
|
+
import*as w from"node:fs";import"node:fs";import{createRequire as $s}from"node:module";import{resolve as he,join as Z,dirname as Q,relative as it,normalize as Rs,sep as lt,extname as xs}from"node:path";import{fileURLToPath as ks}from"node:url";import _s from"fast-glob";var ge={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var Ne={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},U={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},D={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Fe={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},fe={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},ye={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},z={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${ye.SOURCE_EAGER}/*_*.json`],lazy:[`${ye.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/**"]},we={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},nt=["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 De={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}};var ae={inter:[300,400,600,700],"playfair-display":[400,500,600,700],roboto:[400,700],"space-grotesk":[300,400,500,600,700],"press-start-2p":[400]},Pe={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin"],cs:["latin"],sk:["latin"],hr:["latin"],sl:["latin"],hu:["latin"],ro:["latin"],et:["latin"],lv:["latin"],lt:["latin"],mt:["latin"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},Oe=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],ot={base:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...z.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...z.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore}};function at(a,e=null){let t=z[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Se(a){return ot[a]||ot.base}var ie={getGlobOptionsFor:Se||void 0,SCAN_PATTERNS:z||void 0,getPatternsFor:at||void 0,I18N_PATHS:ye||void 0},E={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function ct(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var pt={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"},S=class a{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,a._instance=this}normalizePath(e){if(!e)return"";try{return Rs(e).split(lt).join("/")}catch{return String(e).split(lt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=it(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(Q(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=$s(Z(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let n=e.replace("@donotdev/",""),l=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(l))return l;if(["auth","billing","crud","oauth"].includes(n)){let i=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(i))return i}if(n==="firebase"){let i=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(i))return i}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=he(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=he(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=he(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=w.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:xs(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await w.promises.readFile(e);let n=await w.promises.readFile(e,r),l=this.stripBom(n);return o==="json"?JSON.parse(l):l}catch(n){return this.options.debug&&E.warn(`Failed to read file: ${e}`,n),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return w.readFileSync(e);let n=w.readFileSync(e,r),l=this.stripBom(n);return o==="json"?JSON.parse(l):l}catch(n){return this.options.debug&&E.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:l=!1}=s,i=this.normalizePath(e),p=this.normalizePath(Q(i)),c=this.pathExists(i);if(c&&!o)return l&&E.info(`Skipping existing file: ${i}`),!1;if(n)return E.info(`[DRY RUN] Would write file: ${i}`),!0;try{await w.promises.mkdir(p,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`:g=String(t);try{return await ct(async()=>(Buffer.isBuffer(g)?await w.promises.writeFile(i,g):await w.promises.writeFile(i,g,"utf8"),l&&E.info(`${c?"Updated":"Created"} file: ${i}`),!0),`Failed to write file: ${i}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:l=!1}=s,i=this.normalizePath(e),p=this.normalizePath(Q(i)),c=this.pathExists(i);if(c&&!o)return l&&E.info(`Skipping existing file: ${i}`),!1;if(n)return E.info(`[DRY RUN] Would write file: ${i}`),!0;try{w.mkdirSync(p,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
|
|
3
|
+
`:g=String(t);try{return Buffer.isBuffer(g)?w.writeFileSync(i,g):w.writeFileSync(i,g,"utf8"),this._writtenPaths?.add(i),l&&E.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch(f){throw new Error(`Failed to write file: ${i}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,l=this.normalizePath(t),i=this.pathExists(l);if(i&&!r)return n&&E.info(`Skipping existing file: ${l}`),!1;if(o)return E.info(`[DRY RUN] Would copy file: ${l}`),!0;let p=this.normalizePath(Q(l));try{await w.promises.mkdir(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await ct(async()=>(await w.promises.copyFile(e,l),n&&E.info(`${i?"Updated":"Created"} file: ${l}`),!0),`Failed to copy file from ${e} to ${l}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,l=this.normalizePath(t),i=this.pathExists(l);if(i&&!r)return n&&E.info(`Skipping existing file: ${l}`),!1;if(o)return E.info(`[DRY RUN] Would copy file: ${l}`),!0;let p=this.normalizePath(Q(l));try{w.mkdirSync(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return w.copyFileSync(e,l),this._writtenPaths?.add(l),n&&E.info(`${i?"Updated":"Created"} file: ${l}`),!0}catch{return!1}}pathExists(e,t=!1){try{return w.existsSync(e)}catch(s){return t||E.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return w.existsSync(t)||w.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return w.readdirSync(e,t)}catch(s){return this.options.debug&&E.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return w.statSync(e)}catch(t){return this.options.debug&&E.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return w.realpathSync(e)}watch(e,t,s){return w.watch(e,t,s)}lstatSync(e){try{return w.lstatSync(e)}catch(t){return this.options.debug&&E.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await w.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{w.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await w.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){w.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return w.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}startWriteRecording(){this._writtenPaths=new Set}stopWriteRecording(){if(!this._writtenPaths)throw new Error("stopWriteRecording() called without startWriteRecording()");let e=this._writtenPaths;return this._writtenPaths=null,e}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=Z(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(he(e)),s=this.getAppRoot(),r=it(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(Z(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),l=r.startsWith(n)?r.slice(n.length+1):r,i={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:ie.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([l],{...i,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ie.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(Z(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await _s(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=ie.getGlobOptionsFor?ie.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},n=this.normalizePath(r),l=e.framework.map(c=>{let u=this.normalizePath(c);return u.startsWith(n)?u.slice(n.length+1):u}),i=e.consumer.map(c=>{let u=this.normalizePath(c);return u.startsWith(n)?u.slice(n.length+1):u}),p={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=l.length>0?await this._globWithNormalization(l,p):[],u=await this._globWithNormalization(i,p);return{frameworkFiles:c,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ie.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=ie.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let i=r,p={eager:i.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:i.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(i.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((i.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(i.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((i.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return p.all=[...p.eager,...p.lazy,...p.framework.eager,...p.framework.lazy],p}let n=r,l={framework:o?(n.framework||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):[],consumer:(n.consumer||[]).map(i=>this.resolveAppPath(i)),all:[]};return l.all=[...l.consumer,...l.framework],l}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyFlagModulePath(){let e=Q(ks(import.meta.url));return this.normalizePath(he(e,"emptyFlag.js"))}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(Z(t,pt.TOOLING)),n=this.normalizePath(Z(t,pt.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let l=Z(t,"apps");if(this.pathExists(l)&&this.statSync(l)?.isDirectory())return this.normalizePath(t);let i=this.normalizePath(Z(t,"package.json"));if(this.pathExists(i)&&this.normalizePath(Q(t))===t)return t;let p=this.normalizePath(Q(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function ut({logger:a,debug:e=!1}={}){let t=S.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):a&&a.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&a&&a.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let n=t.resolveRepoPath("apps");if(t.pathExists(n))try{let l=process.cwd(),i=t.normalizePath(l);if(i.includes("/apps/")){let p=i.indexOf("/apps/"),u=i.substring(p+6).split("/")[0];if(u){let g=t.resolveRepoPath(`apps/${u}`),f=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(f)&&(r=g,t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}import yt from"node:fs";function gt(a){let e=new Set(Object.keys(ae)),t=new Set(["latin"]);for(let o of a||[]){let n=Pe[o];if(n)for(let l of n)t.add(l)}let s=[],r=new Set;for(let o of e){let n=ae[o];for(let l of t)for(let i of n){let p=`@fontsource/${o}/${l}-${i}.css`,c=`${o}-${l}-${i}-normal`;s.push(p),r.add(c)}}return{imports:s,stems:r,subsets:t,fontStems:e}}function Te(a){return a.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}import*as I from"@clack/prompts";var W={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function As(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function V(a,e){return As()?`${e}${a}${W.reset}`:a}function N(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=S.getInstance(),l=null;if(o){let c=n.resolveAppPath(r);n.pathExists(c)||n.mkdir(c),l=n.resolveAppPath(`${r}/${a.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${a} Log Started at ${new Date().toISOString()} ===
|
|
4
|
+
`;n.writeSync(l,u)}let i=(c,u,g)=>{if(l){let f=new Date().toISOString(),h=g.length>0?" "+g.map(d=>typeof d=="object"?JSON.stringify(d,null,2):String(d)).join(" "):"",b=`${f} [${c}] ${u}${h}
|
|
5
|
+
`;n.appendFile(l,b)}},p=(c,u)=>{if(u.length===0)return c;let g=u.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${c} ${g}`};return{debug:(c,...u)=>{e&&(o?i("DEBUG",c,u):I.log.message(V(p(c,u),W.gray)))},verbose:(c,...u)=>{t&&(o?i("VERBOSE",c,u):I.log.message(p(c,u)))},info:(c,...u)=>{o?i("INFO",c,u):I.log.info(V(p(c,u),W.brightCyan))},warn:(c,...u)=>{e&&o?i("WARN",c,u):I.log.warn(V(p(c,u),W.brightYellow))},error:(c,...u)=>{e&&o?i("ERROR",c,u):I.log.error(V(p(c,u),W.brightRed))},success:(c,...u)=>{e&&o?i("SUCCESS",c,u):I.log.success(V(p(c,u),W.brightGreen))},when:(c,u="debug")=>(g,...f)=>{if(c){let h=p(g,f);switch(u){case"verbose":t&&(I.log.message(h),i("VERBOSE",g,f));break;case"info":I.log.info(V(h,W.brightCyan)),i("INFO",g,f);break;case"warn":I.log.warn(V(h,W.brightYellow)),i("WARN",g,f);break;case"error":I.log.error(V(h,W.brightRed)),i("ERROR",g,f);break;case"success":I.log.success(V(h,W.brightGreen)),i("SUCCESS",g,f);break;default:e&&(I.log.message(V(h,W.gray)),i("DEBUG",g,f))}}},getLogFilePath:()=>l}}var G=class a{constructor(e,t={}){if(this.constructor===a)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=N(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let n=Date.now()-t;return this.logger.debug(`Discovery completed in ${n}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};function Es(a){if(!a)return[];let e=S.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",a);if(!s)return[];let r=e.getDirname(e.getDirname(s)),o;try{o=e.readdirSync(r)}catch{return[]}for(let n of o)try{let l=e.resolvePath(`${n}/package.json`,r),i=e.readSync(l,{format:"json"});if(!i?.peerDependenciesMeta)continue;for(let[p,c]of Object.entries(i.peerDependenciesMeta))c?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function Cs(a){if(!a)return[];let e=S.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 Ns(a){let e=we.optionalFeatures||[],t=Es(a),s=Cs(a);return[...new Set([...e,...t,...s])]}function Fs(a){let e=S.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 Ds(a,e,t){if(t.resolvePackage(a,e||void 0))return!0;let s=a.startsWith("@")?a.split("/").slice(0,2).join("/"):a.split("/")[0],r=e;for(let o=0;o<10;o++){let n=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(n))return!0;let l=t.getDirname(r);if(l===r)break;r=l}return!1}function $e(a){let e=Ns(a),t=[],s=[],r=S.getInstance(),o=Fs(a);for(let n of e)n.startsWith("@donotdev/")?o.has(n)?s.push(n):t.push(n):o.has(n)&&Ds(n,a,r)?s.push(n):t.push(n);return{missing:t,installed:s}}var le=class a extends G{static LANGUAGE_FLAG_OVERRIDES={en:"gb","en-ca":"ca","es-ar":"ar","fr-be":"be",ar:"sa","ar-ma":"ma","ar-dz":"dz","ar-tn":"tn","ar-ly":"ly","ar-mr":"mr",hi:"in",sl:"si",uk:"ua",ga:"ie",gd:"gb-sct",br:"bzh",co:"fr-cor",am:"et",bn:"bd",gu:"in",kn:"in",ml:"in",mr:"in",ne:"np",pa:"pk",ta:"in",te:"in",ur:"pk",fa:"ir",kk:"kz",ky:"kg",tg:"tj",my:"mm",km:"kh",lo:"la",ka:"ge",hy:"am",be:"by",bs:"ba",sq:"al",ms:"my"};constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[s,r]of Object.entries(e)){for(let o of Object.keys(r))t.includes(o)||delete r[o];Object.keys(r).length===0&&delete e[s]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Se("i18n"),n=r.eager||[],l=r.lazy||[],i=(this.options.additionalPaths||[]).map(y=>{let P=y.endsWith(".json")?y:`${y}/*_*.json`;return this.pathResolver.resolveAppPath(P)});i.length>0&&this.logger.debug(`Additional i18n paths configured: ${i.join(", ")}`);let p=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${l.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${c.join(", ")}`),p.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),f=(y,P)=>{let R=this.pathResolver.normalizePath(y),k=this.pathResolver.normalizePath(P);return R.startsWith(k)?R.slice(k.length+1):R},h=n.map(y=>f(y,t)),d=[...l,...i].map(y=>f(y,t)),m=p.map(y=>f(y,s)),$=c.map(y=>f(y,s)),O={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},T=await this.pathResolver._globWithNormalization(h,O),M=await this.pathResolver._globWithNormalization(d,O),A={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(y=>y!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(A.ignore)}`);let j=await this.pathResolver._globWithNormalization(m,A),J=await this.pathResolver._globWithNormalization($,A);this.logger.debug(`Found ${T.length} eager, ${M.length} lazy, ${j.length} framework eager, ${J.length} framework lazy files`),j.length>0?this.logger.debug(`Framework eager files (first 3): ${j.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),J.length>0?this.logger.debug(`Framework lazy files (first 3): ${J.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let oe=[...new Set([...T,...M,...j,...J])],ee=new Set([...T,...j]),v={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:ne}=$e(t),x=new Set(ne.filter(y=>y.startsWith("@donotdev/")).map(y=>y.replace("@donotdev/","")));x.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...x].join(", ")}] (packages not installed)`);let K=new Map,H=[...j,...J];for(let y of H){let P=this._processTranslationFile(y,j.includes(y),t);if(P){if(x.has(P.namespace))continue;let R=`${P.namespace}_${P.language}`;K.set(R,P),v.allNamespaces.add(P.namespace),v.supportedLanguages.add(P.language),j.includes(y)&&v.eagerNamespaces.add(P.namespace)}}let B=new Set;for(let y of oe){if(H.includes(y))continue;let P=this._processTranslationFile(y,ee.has(y),t);if(P){let{namespace:R,language:k,importPath:L,content:se}=P,be=`${P.namespace}_${P.language}`;if(K.has(be)){let Ce=K.get(be);P.content=this._mergeTranslations(Ce.content,se)}v.allNamespaces.add(R),v.supportedLanguages.add(k),B.add(k),ee.has(y)&&v.eagerNamespaces.add(R),v.mapping[R]||(v.mapping[R]={}),v.mapping[R][k]=L,P.content&&(v.content[R]||(v.content[R]={}),v.content[R][k]=P.content),v.files.push({path:y,relativePath:this.pathResolver.getRelativePath(y),namespace:R,language:k,eager:ee.has(y),size:P.content?JSON.stringify(P.content).length:0})}}for(let[y,P]of K){let R=y.lastIndexOf("_"),k=y.slice(0,R),L=y.slice(R+1);B.size>0&&!B.has(L)||(!v.mapping[k]||!v.mapping[k][L])&&(v.mapping[k]||(v.mapping[k]={}),v.mapping[k][L]=P.importPath,v.content[k]||(v.content[k]={}),v.content[k][L]=P.content,v.files.push({path:P.absolutePath,relativePath:this.pathResolver.getRelativePath(P.absolutePath),namespace:k,language:L,eager:v.eagerNamespaces.has(k),size:P.content?JSON.stringify(P.content).length:0}))}let te=B.size>0?[...B].sort():[this.options.fallbackLanguage],X=this._getLanguageAllowlist(),_=te;if(X){let y=te.filter(R=>X.includes(R));_=y.length>0?y:[this.options.fallbackLanguage],this._restrictByLanguage(v.mapping,_),this._restrictByLanguage(v.content,_),v.files=v.files.filter(R=>_.includes(R.language));let P=new Set(Object.keys(v.mapping));v.allNamespaces=new Set([...v.allNamespaces].filter(R=>P.has(R))),v.eagerNamespaces=new Set([...v.eagerNamespaces].filter(R=>P.has(R))),this.logger.debug(`I18n restricted by i18n.only [${X.join(", ")}]: languages [${_.join(", ")}], namespaces ${P.size}`)}let q=[...new Set(_.map(y=>a.LANGUAGE_FLAG_OVERRIDES[y]||y))];return{mapping:v.mapping,content:v.content,eagerNamespaces:[...v.eagerNamespaces].sort(),allNamespaces:[...v.allNamespaces].sort(),supportedLanguages:_,fallbackLanguage:this.options.fallbackLanguage,flagCodes:q,files:v.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[a.LANGUAGE_FLAG_OVERRIDES[this.options.fallbackLanguage]||this.options.fallbackLanguage],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,n,l=r.match(/^(.+)_([^_.]+)\.json$/);if(!l)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,n]=l,!o||!n)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let p="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:o,language:n,importPath:p,absolutePath:e,content:c}}_mergeTranslations(e,t){let s={...e};for(let[r,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?s[r]=this._mergeTranslations(s[r]||{},o):s[r]=o;return s}};var Os=3,ft="dndev-font-preloads.json";function ht({pathResolver:a,debug:e=!1,languages:t=[]}){let s=N("font-preload-next",e,!1);return{apply(r){r.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(o,n)=>{if(o.compiler.isChild()||o.compiler.name?.includes("server"))return n();try{if(!a.getAppRoot())return n();let p=t.length?t:["en"];if(!t.length)try{let m=await new le(a,{fallbackLanguage:"en"}).discoverTranslations();m?.supportedLanguages?.length&&(p=m.supportedLanguages)}catch{}let u=gt(p).stems,g=o.outputOptions.publicPath&&String(o.outputOptions.publicPath)!=="auto"?o.outputOptions.publicPath.replace(/\/$/,""):"",f=[];for(let[d]of Object.entries(o.assets)){if(!d.endsWith(".woff2"))continue;let m=d.toLowerCase();if(Array.from(u).some($=>m.includes($))){let $=g?`${g}/${d}`:`/${d}`;if(f.push({href:$,type:"font/woff2"}),f.length>=Os)break}}let h=a.resolveAppPath("public");if(!a.pathExists(h))try{a.ensureDirSync(h)}catch(d){return s.debug(`Font preload: could not create public dir: ${d?.message}`),n()}let b=a.resolvePath(ft,h);a.writeSync(b,JSON.stringify(f,null,0),{overwrite:!0}),s.debug(`Font preload: wrote ${f.length} entries to ${ft}`)}catch(i){s.debug(`Font preload manifest: ${i?.message}`)}n()})}}}import{createRequire as Ts}from"node:module";var dt=Ts(import.meta.url),Ie;function Is(){return Ie===void 0&&(Ie=[[dt.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],dt.resolve("@babel/plugin-transform-parameters")]),Ie}function mt({logger:a=N("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:o}=s,{RawSource:n}=o;t.hooks.thisCompilation.tap("DndevLowerDestructuring",l=>{l.compiler.isChild()||l.compiler.name?.includes("server")||l.options.mode==="production"&&l.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async i=>{let p,c;try{p=(await import("@babel/core")).default,c=Is()}catch(g){a.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${g?.message}`);return}let u=0;for(let g of Object.keys(i)){if(!g.endsWith(".js"))continue;let f=l.getAsset(g).source.source(),h=typeof f=="string"?f:f.toString("utf8"),b;try{b=p.transformSync(h,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:c})}catch(d){throw new Error(`[lower-destructuring] failed to transform ${g}: ${d.message}`)}b?.code&&b.code!==h&&(l.updateAsset(g,new n(b.code)),u++)}e&&a.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function vt({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 bt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Ms(a){return(e,t)=>{bt[e]&&(e=bt[e]);let s=a.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),n=a.resolveFrameworkPackage(r,t);if(n){if(o){let i=a.resolvePath(o,n);if(a.pathExists(i))return i;let p=i+".css";if(a.pathExists(p))return p}let l=a.resolvePath("index.css",n);if(a.pathExists(l))return l}}return a.resolvePath(e,t)}}async function js(){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=S.getInstance();return vt({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:Ms(s)})}function Y(a){return a&&typeof a=="object"&&!Array.isArray(a)}var wt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Pt({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],languages:o=[],logger:n,debug:l}){return(i,p)=>{let{dev:c,isServer:u,webpack:g}=p;c&&!u&&(i.infrastructureLogging={level:"error"},i.stats={...i.stats,logging:"error",loggingTrace:!1},i.ignoreWarnings=[...i.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let f=i.module?.rules?.find(h=>h.test?.test?.(".svg"));f&&(f.exclude=/\.svg$/i),i.module=i.module||{},i.module.rules=i.module.rules||[],i.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),i.module.rules.push({test:/\.md$/,type:"asset/source"}),i.resolve=i.resolve||{},i.resolve.alias=i.resolve.alias||{};try{let h=S.getInstance(),b=h.resolveAppPath(D.next.blogContent);i.resolve.alias[Ne.blog]=yt.existsSync(b)?b:h.getEmptyCjsModulePath()}catch(h){n.debug(`Blog content alias fallback to empty stub: ${h?.message}`)}i.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...wt},g?.IgnorePlugin&&i.plugins.push(new g.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=S.getInstance();i.plugins.push(ht({pathResolver:h,debug:l,languages:o}))}catch(h){n.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(!u)try{i.plugins.push(mt({logger:n,debug:l}))}catch(h){n.debug(`Lower-destructuring webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(n.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),n.info(`\u2705 Including features: ${t.join(", ")}`),i.externals=i.externals||[],Array.isArray(i.externals))i.externals.push(...e);else{let h=i.externals;i.externals=(b,d,m)=>e.includes(d)?m(null,"commonjs "+d):typeof h=="function"?h(b,d,m):m()}if(s.length>0&&g?.NormalModuleReplacementPlugin){let b=S.getInstance().getEmptyCjsModulePath(),d=s.map($=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),m=new RegExp(`^(${d.join("|")})(\\/|$)`);i.plugins.push(new g.NormalModuleReplacementPlugin(m,b)),l&&n.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&g?.NormalModuleReplacementPlugin){let b=S.getInstance().getEmptyFlagModulePath(),d=new Set(r.map(m=>m.toUpperCase()));i.plugins.push(new g.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,m=>{let $=m.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);$&&$[1].toUpperCase()!=="BASE"&&!d.has($[1].toUpperCase())&&(m.request=b)})),l&&n.debug(`Flag filter: allowing ${d.size} flags, aliasing rest to empty component`)}return a?a(i,p):i}}function St({originalRewrites:a,handlers:e,logger:t}){return async function(){try{let s=a?await a():[],o=e.filter(l=>l?.getAPIRewrites).map(l=>l.getAPIRewrites()).reduce((l,i)=>(i?.beforeFiles&&l.beforeFiles.push(...i.beforeFiles),i?.afterFiles&&l.afterFiles.push(...i.afterFiles),i?.fallback&&l.fallback.push(...i.fallback),l),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...o.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function Ls(a){let e=a||[],t=new Set(e.map(o=>o?.path).filter(Boolean)),s=[],r=new Set;for(let o of e){let n=String(o?.file||o?.importPath||"").replace(/\\/g,"/");if(n=n.replace(/^\/?(?:src\/)?/,""),!n.startsWith("pages/")||(n=n.slice(6).replace(/\.[jt]sx?$/,""),!n||n.split("/").some(p=>p.startsWith("_")))||n==="api"||n.startsWith("api/"))continue;n=n.replace(/(?:^|\/)index$/,"");let l=n?"/"+n:"/",i=o?.path;!i||l===i||/[[\]]/.test(l)||/[:[]/.test(i)||t.has(l)||r.has(l)||(r.add(l),s.push({from:l,to:i,permanent:!0}))}return s}function $t({originalRedirects:a,seoRedirects:e,routes:t,logger:s}){return async function(){try{let r=a?await a():[],o=Ls(t),l=[...e||[],...o].map(({from:u,to:g,permanent:f})=>({source:u,destination:g,permanent:f!==!1})),i=[],p=new Set;for(let u of l){let g=u.source.replace(/\/+$/,"")||"/",f=u.destination.replace(/\/+$/,"")||"/";if(g===f){s.warn(`Redirect loop detected: ${u.source} \u2192 ${u.destination} (skipped)`);continue}if(!u.source.startsWith("/")){s.warn(`Redirect source must start with /: "${u.source}" (skipped)`);continue}if(p.has(g)){s.warn(`Duplicate redirect source: "${u.source}" (skipped)`);continue}p.add(g),i.push(u)}let c=[...Array.isArray(r)?r:[],...i];return c.length===0?[]:(s.info(` \u{1F4CE} ${c.length} redirect${c.length>1?"s":""} configured`),c)}catch(r){return s.error(`Failed to merge redirects: ${r.message}`),[]}}}function Rt({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:l,discoveredPackages:i,reactCompiler:p=!1,webpackConfig:c,rewritesConfig:u,redirectsConfig:g,missingOptionalDeps:f,flagCodes:h=[],pathResolver:b,env:d,logger:m}){let $=l?.output==="export",T=l?.distDir||".next";return{transpilePackages:[...i,...f||[]],...p?{reactCompiler:p}:{},...Y(l)?l:(m.warn("restNextConfig is not a plain object:",l),{}),serverExternalPackages:(l?.serverExternalPackages||l?.serverComponentsExternalPackages||[]).filter(A=>!A.startsWith("@donotdev/")&&!f?.includes(A)),turbopack:{...l?.turbopack||{},root:l?.turbopack?.root||b.getRepoRoot(),resolveAlias:{...l?.turbopack?.resolveAlias||{},...wt,[Ne.blog]:(()=>{try{let A=b.resolveAppPath(D.next.blogContent);if(yt.existsSync(A))return"./"+D.next.blogContent}catch{}return"@donotdev/core/empty"})(),...f?.length>0?Object.fromEntries(f.flatMap(A=>[[A,"@donotdev/core/empty"],[`${A}/*`,"@donotdev/core/empty"]])):{}}},distDir:T,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...Y(a)?a:(m.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...Y(e)?e:(m.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...Y(t)?t:(m.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...Y(s)?s:(m.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...Y(r)?r:(m.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...Y(o)?o:(m.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...Y(n)?n:(m.warn("serverShimConfig returned non-object:",n),{}),webpack:c,...$?{}:{rewrites:u,...g?{redirects:g}:{}},env:d,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var Re="fonts",Me="dndev-fonts.css",zs=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,kt=/url\(\.\/files\/([^)]+)\)/g;function Us(a){let e=new Set(["latin"]);for(let t of a){let s=Pe[t];if(s)for(let r of s)e.add(r)}return e}function Gs(a,e){let t=a.resolvePath("src/dndev.css",e),s=a.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=zs.exec(s))!==null;)r.push([o[1],o[2]]);return r}function Bs(a,e,t,s,r){let o=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
6
|
+
`],n=new Set,l=r&&r.size>0;for(let[i,p]of e){let c=a.resolveFrameworkPackage(`@fontsource/${i}`);if(!c){s.debug(`@fontsource/${i} not found`);continue}let u=!!ae[i];if(l&&u)for(let g of r){let f=a.resolvePath(`${g}-${p}.css`,c),h=a.readSync(f,{format:"text"});if(!h)continue;let b=xt(Te(h),a,c,t,n,s,!0);o.push(b)}else{let g=a.resolvePath(`${p}.css`,c),f=a.readSync(g,{format:"text"});if(!f){s.debug(`Missing: @fontsource/${i}/${p}.css`);continue}let h=xt(f,a,c,t,n,s,!1);o.push(h)}}return{cssChunks:o,copiedFiles:n}}function xt(a,e,t,s,r,o,n){return a.replace(kt,(l,i)=>{if(n&&i.endsWith(".woff"))return"url(data:,)";let p=e.resolvePath(`files/${i}`,t);if(!e.pathExists(p))return o.warn(`Font file missing: ${p} \u2014 dropping from CSS`),"url(data:,)";if(!r.has(i)){let u=e.resolvePath(i,s);e.copySync(p,u,{overwrite:!0}),r.add(i)}return`url(/${Re}/${i})`})}var Ws=/@font-face\s*\{[^}]*\}/g;function Hs(a,e,t,s,r){let o=a.resolvePath("dist/dndev.css",e),n=a.readSync(o,{format:"text"});if(!n)return s.debug("dist/dndev.css not found in @donotdev/ui"),{cssChunks:[],copiedFiles:new Set};let l=n.match(Ws);if(!l||l.length===0)return s.debug("No @font-face blocks found in dist/dndev.css"),{cssChunks:[],copiedFiles:new Set};let i=r&&r.size>0,p=new Set(Object.keys(ae));i&&(l=l.filter(h=>{if(!Array.from(p).some(d=>h.includes(`${d}-`)))return!0;for(let d of r)if(h.includes(`-${d}-`))return!0;return!1}));let c=a.resolvePath("dist/files",e),u=new Set;return{cssChunks:[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
7
|
+
`,...l.map(h=>{let b=i&&Array.from(p).some(m=>h.includes(`${m}-`));return(b?Te(h):h).replace(kt,(m,$)=>{if(b&&$.endsWith(".woff"))return"url(data:,)";let O=a.resolvePath($,c);if(!a.pathExists(O))return s.warn(`Font file missing: ${O} \u2014 dropping from CSS`),"url(data:,)";if(!u.has($)){let M=a.resolvePath($,t);a.copySync(O,M,{overwrite:!0}),u.add($)}return`url(/${Re}/${$})`})})],copiedFiles:u}}function _t({debug:a=!1,force:e=!1,languages:t}={}){let s=N("font-copy",a,!1),r=S.getInstance(),o=r.resolveAppPath(`public/${Me}`);if(!e&&r.pathExists(o)){s.debug("dndev-fonts.css already exists, skipping font copy");return}let n=r.resolveFrameworkPackage("@donotdev/ui");if(!n){s.debug("@donotdev/ui not found, skipping font copy");return}let l=r.resolveAppPath(`public/${Re}`);r.ensureDirSync(l);let i=t?.length?Us(t):null;i&&s.debug(`Font copy: locale-aware filtering \u2014 locales=[${t.join(",")}] subsets=[${[...i].join(",")}]`);let p=Gs(r,n),c,u;if(p.length>0?(s.debug(`Monorepo mode: ${p.length} @fontsource imports found`),{cssChunks:c,copiedFiles:u}=Bs(r,p,l,s,i)):(s.debug("Consumer mode: parsing dist/dndev.css for font files"),{cssChunks:c,copiedFiles:u}=Hs(r,n,l,s,i)),u.size===0){s.debug("No font files found to copy");return}r.writeSync(o,c.join(`
|
|
8
|
+
`)),s.debug(`Font copy: wrote ${Me} (${u.size} font files copied)`)}function At(){let a=S.getInstance(),e=a.resolveAppPath(`public/${Me}`),t=a.resolveAppPath(`public/${Re}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var Vs=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json","public/dndev-fonts.css","public/robots.txt","public/sitemap.xml","public/rss.xml","public/llms.txt","public/llms-full.txt"],Js="dndev-config-",Et=".dndev-build";function je(a){if(!a)return!1;let e=S.getInstance(),t=e.resolveAppPath(Et),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function qs(a){if(!a)return;let e=S.getInstance(),t=e.resolveAppPath(Et),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s,{overwrite:!0})}catch{}}function Ys(a,e,t){if(!a)return;let s=S.getInstance(),r=(n,l)=>{let i=s.normalizePath(n);if(!(t.has(i)||!s.pathExists(i)))try{s.removeSync(n),e.debug(`Removed stale: ${l}`)}catch{}};for(let n of Vs)r(s.resolveAppPath(n),n);let o=s.resolveAppPath("src/config");for(let n of s.readdirSync(o))n.startsWith(Js)&&n.endsWith(".js")&&r(s.resolvePath(n,o),`src/config/${n}`)}async function Ct({routeHandler:a,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:o,blogContentHandler:n},l){let i=a?.pathResolver;if(!i)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let p=i.getAppRoot(),c=i.getRepoRoot();if(!p||p===c){l.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(b=>setTimeout(b,0));let h=i.getAppRoot();if(!h||h===c)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(je(p)){l.debug("Discoveries already completed this build, skipping");return}qs(p);let u=Date.now();i.startWriteRecording();let g;try{if(At(),a)try{l.info("\u{1F50D} Starting route discovery...");let m=(await a.generateFiles())?.routes?.length||0;l.info(`\u2705 Routes generated: ${m} routes found`),m===0&&l.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(d){throw l.error(`\u274C Route generation failed: ${d.message}`),d.stack&&l.error(`Stack: ${d.stack}`),d}else l.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let h=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:o},{name:"BlogContent",handler:n}],b;for(let{name:d,handler:m}of h)try{let $=await m.generateFiles();d==="I18n"&&$?.supportedLanguages?.length&&(b=$.supportedLanguages)}catch($){l.debug(`${d} generation failed: ${$.message}`)}try{Ks(i,l)}catch(d){l.debug(`Env config generation failed (non-critical): ${d.message}`)}try{_t({languages:b})}catch(d){l.debug(`Font copy failed (non-critical): ${d.message}`)}}finally{g=i.stopWriteRecording()}Ys(p,l,g);let f=Date.now()-u;l.verbose?.(`\u2705 All discoveries completed in ${f}ms - Next.js can now compile`)}function Ks(a,e){let t={};for(let[n,l]of Object.entries(process.env))n.startsWith("NEXT_PUBLIC_")&&l!==void 0&&(t[n]=l);let s=`// Auto-generated DnDev env config by @donotdev/config
|
|
7
9
|
// Generated at: ${new Date().toISOString()}
|
|
8
10
|
// Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
|
|
9
11
|
|
|
@@ -20,12 +22,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
20
22
|
timestamp: Date.now(),
|
|
21
23
|
};
|
|
22
24
|
}
|
|
23
|
-
globalThis._DNDEV_CONFIG_.${
|
|
25
|
+
globalThis._DNDEV_CONFIG_.${U.env} = envConfig;
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
// Export for compatibility
|
|
27
29
|
export default envConfig;
|
|
28
|
-
`,r=
|
|
30
|
+
`,r=a.resolveAppPath(D.next.configEnv);a.writeSync(r,s,{overwrite:!0});let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}async function Nt(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 Ft={debug:!1,verbose:process.env.CI!=="true",seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1,aiCrawlers:"recommended",llmsTxt:!0,speculationRules:!0,hreflang:!0,breadcrumbSchema:!0,websiteSchema:!0,organizationSchema:!0},serverShim:{enabled:!0},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},features:{}};var de={...Ft,generateManifest:!0,reactCompiler:!1,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function Dt(a,e){let t={...a};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=Dt(a[s]||{},e[s]):t[s]=e[s]}),t}function Ot(a={}){return Dt(de,a)}function Tt(a){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:n={},seo:l={},serverShim:i={},discovery:p={},generateManifest:c,debug:u,verbose:g,...f}=a,h=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:u,verbose:g,mode:h,isDev:h==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:n,seoOptions:l,serverShimOptions:i,discoveryOptions:p,nextConfigOptions:f}}var F=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=N(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=S.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...de.discovery,...this.options};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}createNextConfig(){return(e={})=>(this.options.debug&&this.logger.debug(`${this.getHandlerName()} handler initialized`),{...e,webpack:(t,s)=>{let{dev:r,isServer:o,webpack:n}=s;return this.applyViteIgnorePlugin(t,n),this._generateFiles(),e.webpack?e.webpack(t,s):t},rewrites:async function(){try{let t=e.rewrites?await e.rewrites():[],s=this.getAPIRewrites();return this.mergeRewrites(t,s)}catch(t){return this.logger.error(`${this.getHandlerName()} handler failed to merge rewrites: ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`),[]}}.bind(this)})}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let t=this.getHandlerName().toLowerCase(),s=D.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!s)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let r=this.generateConfigContent(e);this.writeGeneratedFile(s,r,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),s=U[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
29
31
|
// Generated at: ${new Date().toISOString()}
|
|
30
32
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
31
33
|
|
|
@@ -47,7 +49,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
47
49
|
|
|
48
50
|
// Export for compatibility
|
|
49
51
|
export default ${t}Config;
|
|
50
|
-
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var xe=class extends z{constructor(e,t={}){super(e,{assets:j.assets.fallback,assetPatterns:j.assets.patterns,frameworkPackage:Ce.package,assetsPath:Ce.assetsPath,modernFormats:j.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let n=[],a=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(n=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,p=await this._processAssetFiles(l),c=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...c,logoSvgContent:u},copiedAssets:s,generatedAssets:n,pwaIcons:this._extractPWAIcons(p)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(o=>o.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",o=r.match(/(\d+)x(\d+)/),n=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:n,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let n=`/${e}.${o}`;if(s.includes(n))return n}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(fe.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(`${fe.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(`${fe.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(fe.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],n=[],a=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){a.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,l),n.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),a.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),a.push(...r.map(c=>c.name));else for(let c of r){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){a.push(c.name);continue}try{let g=p.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),f;c.format==="ico"?f=await g.toFormat("png").toBuffer():f=await g.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,f),n.push(c.name)}catch(g){this.logger.debug(`Failed to generate ${c.name}: ${g.message}`),a.push(c.name)}}return{generated:n,skipped:a,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:l.message}}}};var je={data:null},Me=class extends N{constructor(e={}){super(xe,e)}getHandlerDefaults(){return{manifestPath:F.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
52
|
+
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t,{overwrite:!0}),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var xe=class extends G{constructor(e,t={}){super(e,{assets:z.assets.fallback,assetPatterns:z.assets.patterns,frameworkPackage:Fe.package,assetsPath:Fe.assetsPath,modernFormats:z.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let n=[],l=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(l)&&this.options.generateAssets!==!1&&(n=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:i}=e,p=await this._processAssetFiles(i),c=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...c,logoSvgContent:u},copiedAssets:s,generatedAssets:n,pwaIcons:this._extractPWAIcons(p)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(o=>o.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",o=r.match(/(\d+)x(\d+)/),n=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:n,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let n=`/${e}.${o}`;if(s.includes(n))return n}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(fe.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(`${fe.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(`${fe.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(fe.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=[],l=[];try{let i=await this.pathResolver.read(t,{format:"text"});if(!i)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){l.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,i),n.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),l.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),l.push(...r.map(c=>c.name));else for(let c of r){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){l.push(c.name);continue}try{let g=p.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),f;c.format==="ico"?f=await g.toFormat("png").toBuffer():f=await g.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,f),n.push(c.name)}catch(g){this.logger.debug(`Failed to generate ${c.name}: ${g.message}`),l.push(c.name)}}return{generated:n,skipped:l,error:null}}catch(i){return this.logger.debug(`Asset generation failed: ${i.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:i.message}}}};var ze={data:null},Le=class extends F{constructor(e={}){super(xe,e)}getHandlerDefaults(){return{manifestPath:D.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
51
53
|
// Generated at: ${new Date().toISOString()}
|
|
52
54
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
53
55
|
|
|
@@ -64,7 +66,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
64
66
|
timestamp: Date.now(),
|
|
65
67
|
};
|
|
66
68
|
}
|
|
67
|
-
globalThis._DNDEV_CONFIG_.${
|
|
69
|
+
globalThis._DNDEV_CONFIG_.${U.assets} = {
|
|
68
70
|
mapping: assetConfig.manifest,
|
|
69
71
|
logoSvgContent: ${JSON.stringify(t)},
|
|
70
72
|
manifest: {
|
|
@@ -76,7 +78,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
76
78
|
|
|
77
79
|
// Export for compatibility
|
|
78
80
|
export default assetConfig;
|
|
79
|
-
`}logDiscoveryResults(e){let t=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(
|
|
81
|
+
`}logDiscoveryResults(e){let t=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(ze.data={pwaIcons:e.pwaIcons}),e}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({path:t.path,type:t.type,format:t.format,size:t.size,optimized:t.optimized})),manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} assets, ${e.copiedAssets.length} copied from framework`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateAssetManifest(e),this.options.optimizeImages&&await this.generateImageOptimization(e),await this.generateAPIHandler(e)}async generateAssetManifest(e){let t=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",t,"asset manifest")}generateAssetManifestContent(e){let t=e.assets.map(o=>` {
|
|
80
82
|
path: '${o.path}',
|
|
81
83
|
type: '${o.type}',
|
|
82
84
|
format: '${o.format}',
|
|
@@ -123,16 +125,16 @@ ${t}
|
|
|
123
125
|
export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
|
|
124
126
|
|
|
125
127
|
export default imageConfigs;
|
|
126
|
-
`}};function
|
|
128
|
+
`}};function It(a={}){return new Le(a)}import Ue from"node:fs";import Xs from"node:path";var Ge=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!Ue.existsSync(e))return{blogDir:e,files:[]};let t;try{t=Ue.readdirSync(e)}catch{return{blogDir:e,files:[]}}let s=t.filter(r=>r.endsWith(".md")&&!r.startsWith(".")).sort();return{blogDir:e,files:s}}},Be=class extends F{constructor(e={}){super(Ge,e)}getHandlerDefaults(){return{outputPath:D.next.blogContent}}getHandlerName(){return"BlogContent"}createDiscovery(e){return new e(this.pathResolver)}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateSpecificFiles(e),this.logger.debug(`Generated BlogContent: ${this.getGenerationSummary(e)}`),e}catch(e){return this.logger.debug(`BlogContent generation failed (non-critical): ${e.message}`),{blogDir:"",files:[]}}}async getDiscoveryData(){return this.discovery.discoverBlogFiles()}logDiscoveryResults(e){this.logger.info(`\u{1F4DD} Blog: ${e.files.length} .md file(s) found`)}getGenerationSummary(e){return`${e.files.length} blog file(s)`}async generateSpecificFiles(e){let{blogDir:t,files:s}=e;if(s.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let r=this._buildGeneratedContent(t,s);this.writeGeneratedFile(this.options.outputPath,r,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
127
129
|
// Regenerated when src/content/blog/*.md files change
|
|
128
130
|
|
|
129
131
|
const blogContent: Record<string, string> = {
|
|
130
|
-
${t.map(r=>{let o=
|
|
132
|
+
${t.map(r=>{let o=Ue.readFileSync(Xs.join(e,r),"utf8");return` './${r}': ${JSON.stringify(o)},`}).join(`
|
|
131
133
|
`)}
|
|
132
134
|
};
|
|
133
135
|
|
|
134
136
|
export default blogContent;
|
|
135
|
-
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function
|
|
137
|
+
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function Mt(a={}){return new Be(a)}var We=class extends F{constructor(e={}){super(le,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...de.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
|
|
136
138
|
// Generated at: ${new Date().toISOString()}
|
|
137
139
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
138
140
|
|
|
@@ -174,12 +176,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
174
176
|
timestamp: Date.now(),
|
|
175
177
|
};
|
|
176
178
|
}
|
|
177
|
-
globalThis._DNDEV_CONFIG_.${
|
|
179
|
+
globalThis._DNDEV_CONFIG_.${U.i18n} = i18nConfig;
|
|
178
180
|
}
|
|
179
181
|
|
|
180
182
|
// Export for compatibility
|
|
181
183
|
export default i18nConfig;
|
|
182
|
-
`}};function
|
|
184
|
+
`}};function jt(a={}){return new We(a)}var ke=class extends G{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:s}=e,r=[...t,...s];this.logger.debug(`Processing ${r.length} PWA files`);let o=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),o=[...this.options.assetData.pwaIcons]);let n=await this._analyzePWAFiles(r),l=n.filter(g=>g.type==="manifest"||g.type==="service-worker");o.push(...l);let i=n.filter(g=>g.type==="icon"),p=new Set(o.filter(g=>g.type==="icon").map(g=>g.path)),c=i.filter(g=>!p.has(g.path));o.push(...c);let u=this._generatePWAManifest(o);return{assets:o,manifest:u,totalFiles:r.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let s of e){let r=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,o=await this._analyzePWAAsset(r);o&&t.push(o)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let s=e.relativePath,r=e.fileName;return r.includes("manifest.json")?this._parseManifestFile(t,s):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,s):this._isPWAIcon(r)?this._parseIconFile(e,s):null}_parseManifestFile(e,t){try{let s=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:s,size:typeof e=="string"?e.length:JSON.stringify(s).length}}catch(s){return this.logger.debug(`Failed to parse manifest: ${s.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let s=e.fileName,r=this._extractIconSize(s);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(s)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(s=>e.includes(s))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(o=>o.type==="icon"),r=e.find(o=>o.type==="manifest")?.content||this._getDefaultManifest();return t.length>0&&(r.icons=t.map(o=>({src:`/${o.path}`,sizes:`${o.size.width}x${o.size.height}`,type:`image/${o.format}`,purpose:o.purpose}))),r}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let t=e.manifest||this._getDefaultManifest();return JSON.stringify(t,null,2)}generateServiceWorkerContent(e,t={}){let s=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,o=t.precacheManifest||[],n=JSON.stringify(o,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
183
185
|
// Generated at ${new Date().toISOString()}
|
|
184
186
|
|
|
185
187
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -213,23 +215,23 @@ self.addEventListener('message', (event) => {
|
|
|
213
215
|
self.addEventListener('activate', (event) => {
|
|
214
216
|
event.waitUntil(self.clients.claim());
|
|
215
217
|
});
|
|
216
|
-
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:o,handler:n,options:
|
|
217
|
-
maxEntries: ${
|
|
218
|
-
maxAgeSeconds: ${
|
|
219
|
-
})`),
|
|
220
|
-
statuses: ${JSON.stringify(
|
|
221
|
-
})`),
|
|
222
|
-
maxRetentionTime: ${
|
|
223
|
-
})`);let u="";return
|
|
224
|
-
cacheName: '${
|
|
218
|
+
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:o,handler:n,options:l={}}=s,i=n==="CacheFirst"?"CacheFirst":n==="NetworkFirst"?"NetworkFirst":n==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",p;typeof o=="function"?p="({ request }) => request.destination === 'document'":o instanceof RegExp?p=o.toString():p=JSON.stringify(o);let c=[];l.expiration&&c.push(`new ExpirationPlugin({
|
|
219
|
+
maxEntries: ${l.expiration.maxEntries||50},
|
|
220
|
+
maxAgeSeconds: ${l.expiration.maxAgeSeconds||3600*24},
|
|
221
|
+
})`),l.cacheableResponse&&c.push(`new CacheableResponsePlugin({
|
|
222
|
+
statuses: ${JSON.stringify(l.cacheableResponse.statuses||[0,200])},
|
|
223
|
+
})`),l.backgroundSync&&c.push(`new BackgroundSyncPlugin('${l.backgroundSync.queueName||"background-sync-queue"}', {
|
|
224
|
+
maxRetentionTime: ${l.backgroundSync.maxRetentionTime||1440},
|
|
225
|
+
})`);let u="";return l.cacheName&&(u+=`
|
|
226
|
+
cacheName: '${l.cacheName}',`),c.length>0&&(u+=`
|
|
225
227
|
plugins: [
|
|
226
228
|
${c.join(`,
|
|
227
229
|
`)}
|
|
228
|
-
],`),
|
|
229
|
-
networkTimeoutSeconds: ${
|
|
230
|
+
],`),l.networkTimeoutSeconds&&(u+=`
|
|
231
|
+
networkTimeoutSeconds: ${l.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${l.cacheName||"cache-"+r}
|
|
230
232
|
registerRoute(
|
|
231
233
|
${p},
|
|
232
|
-
new ${
|
|
234
|
+
new ${i}({${u}
|
|
233
235
|
})
|
|
234
236
|
);`}).join(`
|
|
235
237
|
|
|
@@ -247,7 +249,7 @@ registerRoute(
|
|
|
247
249
|
}),
|
|
248
250
|
'POST'
|
|
249
251
|
);
|
|
250
|
-
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let n=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let a of n){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),a.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of l){let c=this.pathResolver.getRelativePath(p);if(c.startsWith(`${e}/static/`)){let u=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:u,revision:null})}}}}catch(n){this.logger?.warn(`Failed to discover Next.js build assets: ${n.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Be=class extends N{constructor(e={}){super(Re,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||je.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 It(i={}){return new Be(i)}import{createRequire as Zs}from"node:module";function Mt(i,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=i.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...i.matchAll(o)].forEach(l=>{let p=l[1],c=l[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var me=null,jt=null;function Ks(i){let t=(i.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var le=class extends z{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(me&&jt===s)return this.logger.debug("Using cached route discovery results"),this.routes=me.routes,this.errors=me.errors,this.source=me.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/"),me={routes:this.routes,errors:this.errors,source:this.source},jt=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),o=await this._scanAdditionalPatterns(t),n=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),a=[...r,...n];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=a.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let l=new Map;for(let p of this.routes){let c=p.path;if(l.has(c)){let u=l.get(c);throw new Error(`Route conflict: Multiple routes found for path '${c}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}l.set(c,p)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,o="/src/"+r.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let n=this._extractMetaExport(s,e.absolutePath),a=Ks(o),p=a===ge.HOMEPAGE_COMPONENT?ge.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:g,...f}=n||{};return{path:p,component:a,importPath:o,auth:n?.auth||!1,meta:{...c,...f,entity:c.entity,action:c.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=Mt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let n=o.map(a=>`:${a}`).join("/");return`${r}/${n}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),n=null,a=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?a="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?a="form":(s.includes("Detail")||s.includes("View"))&&(a="detail")),{title:r,entity:n,action:a,file:e}}};function Xs(i,e,t="configuration-error",s={}){let r=`[${i}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=i,o.context=s,o}function Lt(i,e,t,s={}){return Xs(i,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function We(i,e,t,s){try{if(t?.content?.[i]?.[e])return t.content[i][e];let r=t?.mapping?.[i]?.[e];if(!r)return null;let o=s.resolveAppPath(r),n=s.readSync(o,{format:"text"});return n?JSON.parse(n):null}catch{return null}}function ke(i,e){if(!i||!e)return;let t=e.split("."),s=i;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function He(i){return i?.languages||i?.supportedLanguages||["en"]}function Ve(i){return i?.fallback||i?.fallbackLanguage||"en"}var Je=class extends N{constructor(e={}){super(le,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:F.next.middleware,manifestPath:F.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(o=>o.auth&&o.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
252
|
+
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let n=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let l of n){let i=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),l.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of i){let c=this.pathResolver.getRelativePath(p);if(c.startsWith(`${e}/static/`)){let u=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:u,revision:null})}}}}catch(n){this.logger?.warn(`Failed to discover Next.js build assets: ${n.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var He=class extends F{constructor(e={}){super(ke,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||ze.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.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 Lt(a={}){return new He(a)}import{createRequire as er}from"node:module";function zt(a,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=a.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(o)].forEach(i=>{let p=i[1],c=i[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var me=null,Ut=null;function Zs(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var ce=class extends G{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(me&&Ut===s)return this.logger.debug("Using cached route discovery results"),this.routes=me.routes,this.errors=me.errors,this.source=me.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/"),me={routes:this.routes,errors:this.errors,source:this.source},Ut=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),o=await this._scanAdditionalPatterns(t),n=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),l=[...r,...n];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=l.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let i=new Map;for(let p of this.routes){let c=p.path;if(i.has(c)){let u=i.get(c);throw new Error(`Route conflict: Multiple routes found for path '${c}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}i.set(c,p)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,o="/src/"+r.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let n=this._extractMetaExport(s,e.absolutePath),l=Zs(o),p=l===ge.HOMEPAGE_COMPONENT?ge.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:g,...f}=n||{};return{path:p,component:l,importPath:o,auth:n?.auth||!1,meta:{...c,...f,entity:c.entity,action:c.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=zt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let n=o.map(l=>`:${l}`).join("/");return`${r}/${n}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),n=null,l=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?l="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?l="form":(s.includes("Detail")||s.includes("View"))&&(l="detail")),{title:r,entity:n,action:l,file:e}}};function Qs(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 Gt(a,e,t,s={}){return Qs(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function Ve(a,e,t,s){try{if(t?.content?.[a]?.[e])return t.content[a][e];let r=t?.mapping?.[a]?.[e];if(!r)return null;let o=s.resolveAppPath(r),n=s.readSync(o,{format:"text"});return n?JSON.parse(n):null}catch{return null}}function _e(a,e){if(!a||!e)return;let t=e.split("."),s=a;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function Je(a){return a?.languages||a?.supportedLanguages||["en"]}function qe(a){return a?.fallback||a?.fallbackLanguage||"en"}var Ye=class extends F{constructor(e={}){super(ce,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:D.next.middleware,manifestPath:D.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(o=>o.auth&&o.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
251
253
|
// Generated at: ${new Date().toISOString()}
|
|
252
254
|
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
253
255
|
|
|
@@ -266,7 +268,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
266
268
|
timestamp: Date.now(),
|
|
267
269
|
};
|
|
268
270
|
}
|
|
269
|
-
globalThis._DNDEV_CONFIG_.${
|
|
271
|
+
globalThis._DNDEV_CONFIG_.${U.routes} = {
|
|
270
272
|
mapping: routeMapping,
|
|
271
273
|
manifest: routeManifest,
|
|
272
274
|
};
|
|
@@ -276,7 +278,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
276
278
|
export const routes = routeMapping;
|
|
277
279
|
export const manifest = routeManifest;
|
|
278
280
|
export default { routes: routeMapping, manifest: routeManifest };
|
|
279
|
-
`}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=
|
|
281
|
+
`}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=Je(t),r=qe(t),o=process.env.NEXT_PUBLIC_SITE_NAME||"";if(!o)try{let i=this.pathResolver.resolveAppPath("public/seo-manifest.json");this.pathResolver.pathExists(i)&&(o=this.pathResolver.readSync(i,{format:"json"})?.siteName||"")}catch{}let n={};for(let i of e.routes){let p=i.metaExport?.namespace,c=i.metaExport?.seo||{},u={};for(let g of s){let f=p&&t&&Ve(p,g,t,this.pathResolver)||Ve(p,r,t,this.pathResolver),h=_e(f,"meta")||{},b=_e(f,"title"),d=_e(f,"description"),m;h.fullTitle?m=h.fullTitle:c.fullTitle?m=c.fullTitle:b?m=o?`${b} | ${o}`:b:c.title?m=o?`${c.title} | ${o}`:c.title:c.title===null?m=o:m=o||"";let $;c.description===null?$=void 0:c.description?$=c.description:d&&($=d);let O=c.image||h.image||"/og-image.png",T=c.type||h.type||"website",M=c.keywords||h.keywords,A=c.noindex||!1;u[g]={title:m,...$&&{description:$},image:O,type:T,...M&&{keywords:M},...A&&{noindex:A}}}n[i.path]={locales:u,defaultLocale:r}}let l=JSON.stringify(n,null,2);this.writeGeneratedFile("public/metadata-manifest.json",l,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(n).length} routes`)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles();let t=0;for(let s of e.routes)await this.generateSingleAppPage(s)&&t++;this.logger.debug(`Successfully generated ${t}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=["src/app/**/page.tsx","src/app/**/*PageClient.tsx","src/app/[...slug]/page.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let o of s)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),r++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(n){this.logger.debug(`Could not clean file ${o}: ${n.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e){try{let t=this.convertRouteToAppPath(e.path),s=`src/app${t}/page.tsx`,r=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(r)&&!await this.hasGenerationMarker(r))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let o={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},n=this.generatePageFileContent(o);this.writeGeneratedFile(s,n,`app page: ${t}`);let l=this.extractComponentName(o.filePath),i=this.calculateRelativeImportPath(o.relativePath,o.path);return o.metaExport?.namespace==="blog"&&this.hasDynamicSegment(o.path)?this.writeGeneratedFile(`src/app${t}/BlogPostClient.tsx`,this.generateBlogPostClientContent(l,i),`app blog client: ${t}`):this.isClientComponent(o.filePath)&&this.writeGeneratedFile(`src/app${t}/${l}Client.tsx`,this.generateMountedClientContent(l,i),`app client wrapper: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===ge.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(s=>s.startsWith(":")?`[${s.slice(1)}]`:s==="*"?"[...slug]":s).join("/")}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=er(t),r=s.resolve(e);delete s.cache[r];let o=s(r);return o.default||o.i18nConfig||o}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e){let t=this.extractComponentName(e.filePath),s=e.relativePath||e.file,r=this.calculateRelativeImportPath(s,e.path);return e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path)?this.generateBlogPostRSCContent(e,t,r):this.isClientComponent(e.filePath)?`// Generated by @donotdev/config - DO NOT EDIT
|
|
280
282
|
// This file will be regenerated when src/pages changes
|
|
281
283
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
282
284
|
|
|
@@ -304,7 +306,7 @@ export default ${t};
|
|
|
304
306
|
// SSR (appConfig.ssr): render at request time \u2014 the provider tree is store-driven
|
|
305
307
|
// and therefore dynamic. Content is fully server-rendered.
|
|
306
308
|
export const dynamic = 'force-dynamic';
|
|
307
|
-
`:""}generateMetadataFunction(e,t,s){let r=
|
|
309
|
+
`:""}generateMetadataFunction(e,t,s){let r=Je(s),o=qe(s),n="`",l=r.map(i=>` '${i}': { href: ${n}\${baseUrl}\${currentPath}${n} }`).join(`,
|
|
308
310
|
`);return`
|
|
309
311
|
import type { Metadata } from 'next';
|
|
310
312
|
import { readFileSync } from 'node:fs';
|
|
@@ -410,7 +412,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
410
412
|
},
|
|
411
413
|
alternates: {
|
|
412
414
|
languages: {
|
|
413
|
-
${
|
|
415
|
+
${l}
|
|
414
416
|
},
|
|
415
417
|
},
|
|
416
418
|
};
|
|
@@ -714,9 +716,9 @@ export default async function BlogPostRoute({ params }: { params: Params }) {
|
|
|
714
716
|
);
|
|
715
717
|
}
|
|
716
718
|
`}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(`
|
|
717
|
-
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function
|
|
718
|
-
`)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:o,changefreq:n,priority:
|
|
719
|
-
<image:loc>${
|
|
719
|
+
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function Bt(a={}){return new Ye(a)}function C(a){return a?a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}function Wt(a){return a?a.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Ae=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:n,crawlDelay:l=1,aiCrawlers:i="recommended",routes:p={},...c}=e;if(!o||!n)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:o,siteName:n,crawlDelay:l,aiCrawlers:i,routes:p,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...c},this.appRoot=c.appRoot||null,this.logger=N("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t){try{let s=this.generateRouteMetaTags(e.routes||[]),r={routes:e.routes||[],routeMetaTags:s,baseUrl:this.options.baseUrl,siteName:this.options.siteName},o=this.discoverBlogPosts(),n={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:r.routes.length,publicRoutes:r.routes.filter(l=>!l.auth||l.auth===!1).length,protectedRoutes:r.routes.filter(l=>l.auth&&l.auth.required).length,blogPosts:o.length};return this.options.generateRobotsTxt&&(n.robotsTxt=await this.generateRobotsTxt(r,t)),this.options.generateSitemap&&(n.sitemap=await this.generateSitemap(r,t,o)),o.length>0&&(n.rss=await this.generateRSSFeed(o,t)),n.manifest=await this.generateManifest(r,t),n}catch(s){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),s}}async generateRobotsTxt(e,t){let s=[];(e.routes||[]).forEach(o=>{if(o.auth&&o.auth.required){let n=o.path.startsWith("/")?o.path:`/${o.path}`;s.push(n)}}),s.push("/admin","/api","/_next","/static");let r=this.generateRobotsTxtContent({disallowedPaths:[...new Set(s)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",r),{fileName:"robots.txt",content:r,disallowedPaths:s.length}}async generateSitemap(e,t,s=[]){let o=(e.routes||[]).filter(l=>!(l.auth&&l.auth!==!1||typeof l.path=="string"&&l.path.includes(":")||s.length>0&&l.path===this.options.blogPath)).map(l=>({url:l.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:l.path==="/"?"1.0":"0.8"}));if(s.length>0){o.push({url:this.options.blogPath,lastmod:s[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let l of s)o.push({url:`${this.options.blogPath}/${l.slug}`,lastmod:l.date,changefreq:"monthly",priority:"0.6",image:l.image||null})}let n=this.generateSitemapContent(o);return await t("sitemap.xml",n),{fileName:"sitemap.xml",content:n,publicRoutes:o.length}}async generateManifest(e,t){let s={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,protectedRoutes:e.routes?.filter(o=>o.auth&&o.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},r=JSON.stringify(s,null,2);return await t("seo-manifest.json",r),{fileName:"seo-manifest.json",content:r,manifest:s}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:o}=e,n=p=>p?p==="*"?"*":p.startsWith("/")?p:`/${p}`:"/",l=["User-agent: *",...s.map(p=>`Disallow: ${n(p)}`),...t.map(p=>`Allow: ${n(p)}`)];o&&l.push(`Crawl-delay: ${o}`),r&&l.push(`Sitemap: ${r}`);let i=this.options.aiCrawlers;return i&&i!==!1&&(l.push(""),l.push(...tr(i))),l.join(`
|
|
720
|
+
`)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:o,changefreq:n,priority:l,image:i})=>{let p=[` <loc>${C(this.options.baseUrl)}${C(r)}</loc>`];return o&&p.push(` <lastmod>${o}</lastmod>`),n&&p.push(` <changefreq>${n}</changefreq>`),l&&p.push(` <priority>${l}</priority>`),i&&p.push(` <image:image>
|
|
721
|
+
<image:loc>${C(this.options.baseUrl)}${C(i)}</image:loc>
|
|
720
722
|
</image:image>`),` <url>
|
|
721
723
|
${p.join(`
|
|
722
724
|
`)}
|
|
@@ -725,34 +727,34 @@ ${p.join(`
|
|
|
725
727
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
|
|
726
728
|
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
|
|
727
729
|
${s}
|
|
728
|
-
</urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(
|
|
729
|
-
`)){let f=g.indexOf(":");f!==-1&&(c[g.slice(0,f).trim()]=g.slice(f+1).trim())}let u=c.date;if(!u)try{u=e.statSync(n).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${
|
|
730
|
-
<title><![CDATA[${
|
|
731
|
-
<link>${
|
|
732
|
-
<guid>${
|
|
733
|
-
<description><![CDATA[${
|
|
730
|
+
</urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(s=`${o[o.length-1].split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let o=t.path.split("/").filter(Boolean);o.length>0&&(r=`Explore ${o[o.length-1].split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=S.getInstance(),t=e.resolvePath("src/content/blog",this.appRoot);try{if(!e.pathExists(t))return[];let s=e.readdirSync(t).filter(o=>o.endsWith("_en.md"));if(s.length===0)return[];let r=[];for(let o of s){let n=e.resolvePath(o,t),l=e.readSync(n,{format:"text"}),i=o.replace(/_en\.md$/,""),p=l.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(p)for(let g of p[1].split(`
|
|
731
|
+
`)){let f=g.indexOf(":");f!==-1&&(c[g.slice(0,f).trim()]=g.slice(f+1).trim())}let u=c.date;if(!u)try{u=e.statSync(n).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${i}" has no frontmatter date, using file mtime (${u})`)}catch{u=new Date().toISOString().split("T")[0],this.logger.warn(`Blog post "${i}" has no date and file stat failed, using today`)}r.push({slug:i,title:c.title||i,description:c.description||"",date:u,tags:c.tags?c.tags.split(",").map(g=>g.trim()):[],image:c.image||null})}return r.sort((o,n)=>n.date.localeCompare(o.date)),this.logger.info(`\u{1F4DD} Discovered ${r.length} blog post(s) in src/content/blog/`),r}catch(s){return this.logger.debug(`Blog content discovery skipped: ${s.message}`),[]}}async generateRSSFeed(e,t){let s=e.map(o=>` <item>
|
|
732
|
+
<title><![CDATA[${Wt(o.title)}]]></title>
|
|
733
|
+
<link>${C(this.options.baseUrl)}${C(this.options.blogPath)}/${C(o.slug)}</link>
|
|
734
|
+
<guid>${C(this.options.baseUrl)}${C(this.options.blogPath)}/${C(o.slug)}</guid>
|
|
735
|
+
<description><![CDATA[${Wt(o.description)}]]></description>
|
|
734
736
|
<pubDate>${o.date?new Date(o.date).toUTCString():""}</pubDate>${o.tags.length?`
|
|
735
|
-
<category>${
|
|
736
|
-
<enclosure url="${
|
|
737
|
+
<category>${C(o.tags.join(", "))}</category>`:""}${o.image?`
|
|
738
|
+
<enclosure url="${C(this.options.baseUrl)}${C(o.image)}" type="image/png" length="0"/>`:""}
|
|
737
739
|
</item>`).join(`
|
|
738
740
|
`),r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
739
741
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
740
742
|
<channel>
|
|
741
|
-
<title>${
|
|
742
|
-
<link>${
|
|
743
|
-
<description>${
|
|
743
|
+
<title>${C(this.options.siteName)}</title>
|
|
744
|
+
<link>${C(this.options.baseUrl)}${C(this.options.blogPath)}</link>
|
|
745
|
+
<description>${C(this.options.siteName)} Blog</description>
|
|
744
746
|
<language>en</language>
|
|
745
|
-
<atom:link href="${
|
|
747
|
+
<atom:link href="${C(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
746
748
|
${s}
|
|
747
749
|
</channel>
|
|
748
|
-
</rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}},
|
|
749
|
-
`)}function
|
|
750
|
-
`];
|
|
751
|
-
`);for(let c of s){let u=
|
|
750
|
+
</rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}},Ke=["GPTBot","Google-Extended","CCBot","ClaudeBot"],Xe=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function tr(a){let e=["# AI Crawler Management"];if(a==="block-all"){for(let t of[...Ke,...Xe])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(a==="allow-all"){for(let t of[...Ke,...Xe])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of Ke)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of Xe)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Ht(a={}){let{logger:e}=a,t=S.getInstance(),s=a.appRoot||t.getAppRoot();try{let r=t.resolvePath("public/route-manifest.json",s),o=t.readSync(r,{format:"json"});if(!o)return e?.error?.(`Route manifest not found at ${r}. Routes will be empty.`),{routes:[],errors:[`Route manifest missing: ${r}`],source:"fallback"};let n=o.routes||[];return{routes:n,errors:[],source:o.source||"generated",totalFiles:n.length}}catch(r){return e?.warn?.(`Error parsing route manifest: ${r.message}, falling back to empty routes`),{routes:[],errors:[r.message],source:"fallback"}}}function Vt(a={}){let{siteName:e,baseUrl:t,description:s,blogPosts:r=[],blogPath:o="/blog",logger:n}=a;if(!e||!t)return n?.warn?.("llms.txt generation skipped: missing siteName or baseUrl"),null;let i=Ht({appRoot:a.appRoot,logger:n}).routes||[],p=[];p.push(`# ${e}`),p.push(""),s&&(p.push(`> ${s}`),p.push(""));let c=i.filter(u=>!u.auth||u.auth===!1);if(c.length>0){p.push("## Pages"),p.push("");for(let u of c){let g=u.path||"/",f=u.meta?.title||sr(g),h=u.meta?.description||"",b=`${t}${g}`;h?p.push(`- [${f}](${b}): ${h}`):p.push(`- [${f}](${b})`)}p.push("")}if(r.length>0){p.push("## Blog"),p.push("");for(let u of r){let g=`${t}${o}/${u.slug}`;u.description?p.push(`- [${u.title}](${g}): ${u.description}`):p.push(`- [${u.title}](${g})`)}p.push("")}return p.join(`
|
|
751
|
+
`)}function Jt(a={}){let{siteName:e,baseUrl:t,blogPosts:s=[],blogPath:r="/blog",appRoot:o,logger:n}=a;if(!e||!t)return null;if(s.length===0)return n?.debug?.("llms-full.txt skipped: no blog posts"),null;let l=S.getInstance(),i=o?l.resolvePath("src/content/blog",o):null;if(!i||!l.pathExists(i))return null;let p=[`# ${e}
|
|
752
|
+
`];a.description&&p.push(`> ${a.description}
|
|
753
|
+
`);for(let c of s){let u=l.resolvePath(`${c.slug}_en.md`,i);try{let g=l.readSync(u,{format:"text"});if(!g)continue;let f=g.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),h=`${t}${r}/${c.slug}`;p.push(`## ${c.title}
|
|
752
754
|
`),p.push(`Source: ${h}
|
|
753
755
|
`),c.date&&p.push(`Date: ${c.date}
|
|
754
756
|
`),p.push(f.trim()),p.push("")}catch{n?.debug?.(`llms-full.txt: could not read ${c.slug}`)}}return p.join(`
|
|
755
|
-
`)}function er(i){return i==="/"||i===""?"Home":(i.split("/").filter(Boolean).pop()||"Home").split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}var Ke=class extends N{constructor(e={}){super(le,e);let t=w.getInstance(),s=C("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let o=e.seo?.baseUrl;if(!o&&r){let l=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(l)?l:`https://${l}`}o?s.debug(`Found app URL: ${o}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let n=e.siteName||e.seo?.siteName||null;if(s.verbose(`Name: ${n||"Not found"}`),s.verbose(`URL: ${o||"Not found"}`),n&&s.debug(` - Site name from appConfig: "${n}"`),e.seo?.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let a=[];if(o||a.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),n||a.push("siteName (APP_NAME in src/config/app.ts)"),a.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),a.forEach(l=>s.warn(` - ${l}`)),s.warn(""),s.warn(" To fix:"),o||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),n||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this._baseUrl=o,this._siteName=n,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this.seoGenerator=new _e({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:o,siteName:n,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(r,o)=>{if(!r){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${r}`,o,r)},s=await this.seoGenerator.generateSEOFiles(e,t);if(s.robotsTxt&&!s.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${s.robotsTxt.disallowedPaths||0} disallowed paths`),s.sitemap&&!s.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${s.sitemap.publicRoutes||0} routes`),s.rss&&!s.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${s.rss.postCount||0} blog posts`),s.manifest&&!s.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json"),this._llmsTxtEnabled){let r=this.seoGenerator.discoverBlogPosts(),o=this.pathResolver.getAppRoot(),n=Bt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});if(n&&(this.writeGeneratedFile("public/llms.txt",n,"llms.txt"),this.logger.info("\u{1F4C4} llms.txt")),r.length>0){let a=Wt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});a&&(this.writeGeneratedFile("public/llms-full.txt",a,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))}}}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}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 Ht(i={}){return new Ke(i)}function Vt(i={}){let{debug:e}=i;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),st.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var Jt=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,qt=/['"]([^'"]+)['"]/g,ce=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{...Ne.selectors,...this.options.customPatterns?.selectors},themes:{...Ne.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(n=>n.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((n,a)=>{let l=n.replace(/[^a-zA-Z0-9]/g,"");return l?a===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,n=this.pathResolver.normalizePath(t),a=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(a))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let g=c.match(this.patterns.themes.themeIcon),f=c.match(this.patterns.themes.themeIsDark),h={name:p,displayName:u,isDark:f?f[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(h),s.themes.set(p,{name:p,displayName:u,isDark:h.isDark,file:n,variables:new Set,meta:h.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${n}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Jt.lastIndex=0;(r=Jt.exec(t))!==null;){let o=r[1],n;for(qt.lastIndex=0;(n=qt.exec(o))!==null;){let a=n[1].trim();a&&s.add(a)}}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let n=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];n&&t.push(`Theme class "${n}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let n=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:n}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};var Ae=class extends z{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new ce(t,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:s}=e;this.logger.debug(`Scanning ${t.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",s),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t),await this._processConsumerFiles(s);let r=this._serializeThemes();return this.logger.debug(`Discovered ${r.length} themes:`,r.map(o=>o.name)),{themes:r,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return Fe.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning framework file ${t}: ${s.message}`)}}async _processConsumerFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${t}: ${s.message}`)}}_addEssentialThemes(){Fe.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var Xe=class extends N{constructor(e={}){super(Ae,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new ce(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 Lt("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
|
|
757
|
+
`)}function sr(a){return a==="/"||a===""?"Home":(a.split("/").filter(Boolean).pop()||"Home").split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}var Ze=class extends F{constructor(e={}){super(ce,e);let t=S.getInstance(),s=N("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let o=e.seo?.baseUrl;if(!o&&r){let i=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(i)?i:`https://${i}`}o?s.debug(`Found app URL: ${o}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let n=e.siteName||e.seo?.siteName||null;if(s.verbose(`Name: ${n||"Not found"}`),s.verbose(`URL: ${o||"Not found"}`),n&&s.debug(` - Site name from appConfig: "${n}"`),e.seo?.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let l=[];if(o||l.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),n||l.push("siteName (APP_NAME in src/config/app.ts)"),l.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),l.forEach(i=>s.warn(` - ${i}`)),s.warn(""),s.warn(" To fix:"),o||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),n||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this._baseUrl=o,this._siteName=n,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this.seoGenerator=new Ae({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:o,siteName:n,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(r,o)=>{if(!r){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${r}`,o,r)},s=await this.seoGenerator.generateSEOFiles(e,t);if(s.robotsTxt&&!s.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${s.robotsTxt.disallowedPaths||0} disallowed paths`),s.sitemap&&!s.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${s.sitemap.publicRoutes||0} routes`),s.rss&&!s.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${s.rss.postCount||0} blog posts`),s.manifest&&!s.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json"),this._llmsTxtEnabled){let r=this.seoGenerator.discoverBlogPosts(),o=this.pathResolver.getAppRoot(),n=Vt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});if(n&&(this.writeGeneratedFile("public/llms.txt",n,"llms.txt"),this.logger.info("\u{1F4C4} llms.txt")),r.length>0){let l=Jt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});l&&(this.writeGeneratedFile("public/llms-full.txt",l,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))}}}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function qt(a={}){return new Ze(a)}function Yt(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),nt.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var Kt=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,Xt=/['"]([^'"]+)['"]/g,pe=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:{...De.selectors,...this.options.customPatterns?.selectors},themes:{...De.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(n=>n.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((n,l)=>{let i=n.replace(/[^a-zA-Z0-9]/g,"");return i?l===0?i.toLowerCase():i.charAt(0).toUpperCase()+i.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,n=this.pathResolver.normalizePath(t),l=this._stripComments(e),i=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=i.exec(l))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let g=c.match(this.patterns.themes.themeIcon),f=c.match(this.patterns.themes.themeIsDark),h={name:p,displayName:u,isDark:f?f[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(h),s.themes.set(p,{name:p,displayName:u,isDark:h.isDark,file:n,variables:new Set,meta:h.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${n}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Kt.lastIndex=0;(r=Kt.exec(t))!==null;){let o=r[1],n;for(Xt.lastIndex=0;(n=Xt.exec(o))!==null;){let l=n[1].trim();l&&s.add(l)}}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let n=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];n&&t.push(`Theme class "${n}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let n=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:n}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};var Ee=class extends G{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new pe(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 Oe.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(){Oe.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 Qe=class extends F{constructor(e={}){super(Ee,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new pe(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 Gt("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
|
|
756
758
|
// Generated at: ${new Date().toISOString()}
|
|
757
759
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
758
760
|
|
|
@@ -784,7 +786,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
784
786
|
timestamp: Date.now(),
|
|
785
787
|
};
|
|
786
788
|
}
|
|
787
|
-
globalThis._DNDEV_CONFIG_.${
|
|
789
|
+
globalThis._DNDEV_CONFIG_.${U.themes} = themeConfig;
|
|
788
790
|
}
|
|
789
791
|
|
|
790
792
|
// Export for compatibility
|
|
@@ -800,6 +802,6 @@ export function useTheme() {
|
|
|
800
802
|
}
|
|
801
803
|
|
|
802
804
|
export default useTheme;
|
|
803
|
-
`}};function
|
|
804
|
-
\u{1F3D7}\uFE0F DnDev Framework - Building for ${
|
|
805
|
-
`)),
|
|
805
|
+
`}};function Zt(a={}){return new Qe(a)}function Qt({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:l,pwaOptions:i,serverShimOptions:p,appUrl:c,isDev:u,logger:g}){let f=s.debug??a,h=r.debug??a,b=o.debug??a,d=n.debug??a,m=l.debug??a,$=i.debug??a,O=p.debug??a,T=s.verbose??e,M=r.verbose??e,A=o.verbose??e,j=n.verbose??e,J=l.verbose??e,oe=i.verbose??e,ee=p.verbose??e,v={debug:a,verbose:e,generateManifest:t},ne=s.disabled?null:Bt({...v,...s,debug:f,verbose:T});a&&g.debug(`Route handler created: ${ne?"enabled":"disabled"} (debug: ${f})`);let x=Zt({...v,...r,debug:h,verbose:M}),K=jt({...v,...o,debug:b,verbose:A}),H=It({...v,...n,debug:d,verbose:j}),B=qt({...v,...l,debug:m,verbose:J,appUrl:c,isDev:u}),te=Lt({...v,...i,debug:$,verbose:oe}),X=Yt({...v,...p,debug:O,verbose:ee}),_=Mt({debug:a,verbose:e});return{routeHandler:ne,themeHandler:x,i18nHandler:K,assetHandler:H,seoHandler:B,pwaHandler:te,serverShimHandler:X,blogContentHandler:_}}function es(a,e){let t={};if(a.routeHandler)try{t.routeConfig=a.routeHandler.createNextConfig()}catch(r){e.error(`Route handler failed during config creation: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.routeConfig=()=>({})}else t.routeConfig=()=>({});let s=[{name:"theme",handler:a.themeHandler},{name:"i18n",handler:a.i18nHandler},{name:"asset",handler:a.assetHandler},{name:"seo",handler:a.seoHandler},{name:"pwa",handler:a.pwaHandler}];for(let{name:r,handler:o}of s)try{t[`${r}Config`]=o.createNextConfig()}catch(n){e.error(`${r.charAt(0).toUpperCase()+r.slice(1)} handler failed: ${n.message}`),e.error(`Stack: ${n.stack||"No stack trace available"}`),t[`${r}Config`]=()=>({})}try{t.serverShimConfig=a.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}var rr=new Set(["@donotdev/functions"]);function ts(){try{let a=S.getInstance(),e=a.resolveAppPath("package.json"),t=a.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(r=>r.startsWith("@donotdev/")).filter(r=>!we.buildTimePackages.includes(r)).filter(r=>!rr.has(r)).sort()}catch{return[]}}var et=new Map;function or(a={}){let{port:e,...t}=a;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let P=process.env.CI==="true";process.env.DNDEV_BUILD_ID=P?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let s=process.env.DNDEV_BUILD_ID;if(s&&et.has(s))return et.get(s).configFn;let{appConfig:r,...o}=t;if(!r)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let n=r?.features?{debug:r.features.debug}:void 0,l=r?.seo&&typeof r.seo!="boolean"?{...r.seo,siteName:r.seo.siteName||r.app?.name}:r?.app?.name?{siteName:r.app.name}:void 0,i=r?.app?{name:r.app.name,shortName:r.app.shortName,description:r.app.description}:void 0,{features:p,seo:c,...u}=o,g={...n?{features:n}:{},...l?{seo:l}:{},...u},f=Ot(g),h=Tt(f);if(!h)throw new Error("normalizeOptions returned undefined");let{generateManifest:b,debug:d,verbose:m,mode:$,isDev:O,routeOptions:T,themeOptions:M,i18nOptions:A,assetOptions:j,pwaOptions:J,seoOptions:oe,serverShimOptions:ee,nextConfigOptions:v,reactCompiler:ne}=h,x=N("next-config",d,m),{appRoot:K,appRootSet:H}=ut({logger:x,debug:d}),B=!1,te=T?.routingMode||"app",X=H&&je(K);if(X||(x.info(`
|
|
806
|
+
\u{1F3D7}\uFE0F DnDev Framework - Building for ${$}${s?` [build:${s}]`:""}`),x.info(` Platform: Next.js | Routing: ${te}
|
|
807
|
+
`)),O){let P=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${P}`,d&&(x.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&x.debug(`Port configured: ${P} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||x.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let _=Qt({debug:d,verbose:m,generateManifest:b,routeOptions:{...T,ssr:r?.ssr!==!1},themeOptions:M,i18nOptions:A,assetOptions:j,seoOptions:oe,pwaOptions:J,serverShimOptions:ee,isDev:O,logger:x}),q=es(_,x),y=async function(R={}){let k=S.getInstance(),L=H?ts():[];d&&L.length>0&&x.debug(`Discovered ${L.length} packages: ${L.join(", ")}`);let{missing:se,installed:be}=$e(k.getAppRoot()),Ce=se.filter(ue=>ue.startsWith("@donotdev/")),rs=be.filter(ue=>ue.startsWith("@donotdev/"));d&&se.length>0&&x.debug(`Missing optional deps (will alias to empty): ${se.join(", ")}`),H&&await Ct(_,x);let re=typeof R=="object"&&R!==null?R:{},{webpack:os,rewrites:ns,redirects:as,...is}=re;H&&!B&&(B=await Nt(_.assetHandler,x,B));let ls=q.routeConfig(re),cs=q.themeConfig(re),ps=q.i18nConfig(re),us=q.assetConfig(re),gs=q.seoConfig(re),fs=q.pwaConfig(re),hs=q.serverShimConfig(),st=await _.i18nHandler?.getDiscoveryData?.(),rt=st?.flagCodes||[],ds=st?.supportedLanguages||[],ms=te==="app"?await _.routeHandler?.getDiscoveryData?.():null,vs=Pt({originalWebpack:os,unusedFeaturePackages:Ce,usedFeaturePackages:rs,missingOptionalDeps:se,flagCodes:rt,languages:ds,logger:x,debug:d}),bs=St({originalRewrites:ns,handlers:[_.routeHandler,_.themeHandler,_.i18nHandler,_.assetHandler,_.pwaHandler],logger:x}),ys=$t({originalRedirects:as,seoRedirects:oe?.redirects||[],routes:ms?.routes||[],logger:x}),ws={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Ps=Rt({routeResult:ls,themeResult:cs,i18nResult:ps,assetResult:us,seoResult:gs,pwaResult:fs,serverShimResult:hs,restNextConfig:is,discoveredPackages:L,reactCompiler:ne,webpackConfig:vs,rewritesConfig:bs,redirectsConfig:ys,missingOptionalDeps:se,flagCodes:rt,pathResolver:k,env:ws,logger:x});if(x.debug("Next.js config generated"),H&&!X){let ue=i?.name||"app";x.info(`Name: ${ue}`),x.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),x.info(`App root (final): ${k.getAppRoot()}`)}return Ps};return s&&et.set(s,{configFn:y}),y}var ss=or;import{readFileSync as nr,existsSync as ar}from"node:fs";import{join as ir}from"node:path";var ve=null,tt=0,lr=6e4;function cr(){let a=Date.now();if(ve&&a-tt<lr)return ve;try{let e=ir(process.cwd(),"public","metadata-manifest.json");if(!ar(e))return null;let t=nr(e,"utf-8");return ve=JSON.parse(t),tt=a,ve}catch{return null}}function pr(a,e,t){let s=cr(),r={title:t?.siteName||"Site"};if(!s)return r;let o=a.startsWith("/")?a:`/${a}`,n=s[o];if(!n)return r;let l=e||n.defaultLocale||"en",i=n.locales[l]||n.locales[n.defaultLocale]||Object.values(n.locales)[0];if(!i)return r;let p=process.env.NEXT_PUBLIC_APP_URL,c={title:i.title,...p&&{metadataBase:new URL(p)}};return i.description&&(c.description=i.description),i.keywords&&(c.keywords=i.keywords),c.openGraph={title:i.title,type:i.type||"website",...i.description&&{description:i.description},...i.image&&{images:[i.image]},...t?.siteName&&{siteName:t.siteName}},c.twitter={card:"summary_large_image",title:i.title,...i.description&&{description:i.description},...i.image&&{images:[i.image]}},i.noindex&&(c.robots={index:!1,follow:!1}),c}function ur(){ve=null,tt=0}export{ur as clearMetadataCache,ss as default,ss as defineNextConfig,js as definePostCSSConfig,pr as getMetadataForPath};
|