@donotdev/core 0.0.33 → 0.0.35
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/empty.js +16 -2
- package/functions/index.js +11 -11
- package/index.d.ts +3 -3
- package/index.js +22 -22
- package/next/index.d.ts +18 -1
- package/next/index.js +53 -51
- package/package.json +2 -2
- package/server.js +1 -1
- package/vite/index.js +15 -15
package/next/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
var ne={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},Ge={available:["auth","oauth","billing","crud"],packageNames:{auth:"@donotdev/auth",oauth:"@donotdev/oauth",billing:"@donotdev/billing",crud:"@donotdev/crud"},hooks:{auth:["useAuth"],oauth:["useOAuth","useOAuthPartner","useOAuthConnection"],billing:["useStripeBilling","useStripeCheckout"],crud:["useCrud","useCrudCollection"]}};var O={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},X={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},ke={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ie={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},ge={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"},N={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:[`${ge.SOURCE_EAGER}/*_*.json`],lazy:[`${ge.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/**"]},he={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async","@donotdev/core","@donotdev/components","@donotdev/ui","@donotdev/templates","@donotdev/firebase"],optionalFeatures:["@donotdev/components","@donotdev/auth","@donotdev/billing","@donotdev/crud","@donotdev/oauth","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder"],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"]},We=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var _e={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}},Z={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},Ae=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ue={base:{absolute:!0,onlyFiles:!0,ignore:N.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...N.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...N.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:N.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:N.globalIgnore}};function Be(l,e=null){let t=N[l];if(!t)throw new Error(`Unknown pattern type: ${l}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function fe(l){return Ue[l]||Ue.base}import*as m from"node:fs";import"node:fs";import{createRequire as Lt}from"node:module";import{resolve as de,join as U,dirname as B,relative as He,normalize as Ut,sep as Ve,extname as Gt}from"node:path";import{fileURLToPath as Wt}from"node:url";import Bt from"fast-glob";var se={getGlobOptionsFor:fe||void 0,SCAN_PATTERNS:N||void 0,getPatternsFor:Be||void 0,I18N_PATHS:ge||void 0},R={error:(l,e)=>{},warn:(l,e)=>{},info:l=>{}};function Je(l,e){return l().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var qe={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},P=class l{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return l._instance||(l._instance=new l(e)),l._instance}static _reset(){l._instance=null}constructor(e={}){if(l._instance)return l._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,l._instance=this}normalizePath(e){if(!e)return"";try{return Ut(e).split(Ve).join("/")}catch{return String(e).split(Ve).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=He(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(B(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Lt(U(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 a=e.replace("@donotdev/",""),n=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(n))return n;if(["auth","billing","crud","oauth"].includes(a)){let i=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(i))return i}if(a==="firebase"){let i=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(i))return i}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let 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=de(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=de(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=de(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=m.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:Gt(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await m.promises.readFile(e);let a=await m.promises.readFile(e,r),n=this.stripBom(a);return o==="json"?JSON.parse(n):n}catch(a){return this.options.debug&&R.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return m.readFileSync(e);let a=m.readFileSync(e,r),n=this.stripBom(a);return o==="json"?JSON.parse(n):n}catch(a){return this.options.debug&&R.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:a=!1,verbose:n=!1}=s,i=this.normalizePath(e),p=this.normalizePath(B(i)),c=this.pathExists(i);if(c&&!o)return n&&R.info(`Skipping existing file: ${i}`),!1;if(a)return R.info(`[DRY RUN] Would write file: ${i}`),!0;try{await m.promises.mkdir(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return await Je(async()=>(Buffer.isBuffer(h)?await m.promises.writeFile(i,h):await m.promises.writeFile(i,h,"utf8"),n&&R.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:a=!1,verbose:n=!1}=s,i=this.normalizePath(e),p=this.normalizePath(B(i)),c=this.pathExists(i);if(c&&!o)return n&&R.info(`Skipping existing file: ${i}`),!1;if(a)return R.info(`[DRY RUN] Would write file: ${i}`),!0;try{m.mkdirSync(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return Buffer.isBuffer(h)?m.writeFileSync(i,h):m.writeFileSync(i,h,"utf8"),n&&R.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch(g){throw new Error(`Failed to write file: ${i}: ${g instanceof Error?g.message:String(g)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,n=this.normalizePath(t),i=this.pathExists(n);if(i&&!r)return a&&R.info(`Skipping existing file: ${n}`),!1;if(o)return R.info(`[DRY RUN] Would copy file: ${n}`),!0;let p=this.normalizePath(B(n));try{await m.promises.mkdir(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await Je(async()=>(await m.promises.copyFile(e,n),a&&R.info(`${i?"Updated":"Created"} file: ${n}`),!0),`Failed to copy file from ${e} to ${n}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:a=!1}=s,n=this.normalizePath(t),i=this.pathExists(n);if(i&&!r)return a&&R.info(`Skipping existing file: ${n}`),!1;if(o)return R.info(`[DRY RUN] Would copy file: ${n}`),!0;let p=this.normalizePath(B(n));try{m.mkdirSync(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return m.copyFileSync(e,n),a&&R.info(`${i?"Updated":"Created"} file: ${n}`),!0}catch{return!1}}pathExists(e,t=!1){try{return m.existsSync(e)}catch(s){return t||R.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return m.existsSync(t)||m.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return m.readdirSync(e,t)}catch(s){return this.options.debug&&R.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return m.statSync(e)}catch(t){return this.options.debug&&R.warn(`Failed to stat file: ${e}`,t),null}}lstatSync(e){try{return m.lstatSync(e)}catch(t){return this.options.debug&&R.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await m.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{m.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await m.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){m.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return m.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=U(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(de(e)),s=this.getAppRoot(),r=He(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(U(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),n=r.startsWith(a)?r.slice(a.length+1):r,i={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:se.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([n],{...i,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=se.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(U(r,t.PUBLISHED_ROOT,s)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await Bt(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=se.getGlobOptionsFor?se.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(r),n=e.framework.map(c=>{let u=this.normalizePath(c);return u.startsWith(a)?u.slice(a.length+1):u}),i=e.consumer.map(c=>{let u=this.normalizePath(c);return u.startsWith(a)?u.slice(a.length+1):u}),p={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let c=n.length>0?await this._globWithNormalization(n,p):[],u=await this._globWithNormalization(i,p);return{frameworkFiles:c,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!se.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let r=se.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let 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 a=r,n={framework:o?(a.framework||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):[],consumer:(a.consumer||[]).map(i=>this.resolveAppPath(i)),all:[]};return n.all=[...n.consumer,...n.framework],n}getEmptyModulePath(e=!1){if(e)return"@donotdev/core/empty";let t=this.resolvePackage("@donotdev/core/empty");if(t)return t;let s=B(Wt(import.meta.url));return this.normalizePath(U(s,"../empty.js"))}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(U(t,qe.TOOLING)),a=this.normalizePath(U(t,qe.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let n=U(t,"apps");if(this.pathExists(n)&&this.statSync(n)?.isDirectory())return this.normalizePath(t);let i=this.normalizePath(U(t,"package.json"));if(this.pathExists(i)&&this.normalizePath(B(t))===t)return t;let p=this.normalizePath(B(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function Ye({logger:l,debug:e=!1}={}){let t=P.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):l&&l.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&l&&l.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let a=t.resolveRepoPath("apps");if(t.pathExists(a))try{let n=process.cwd(),i=t.normalizePath(n);if(i.includes("/apps/")){let p=i.indexOf("/apps/"),u=i.substring(p+6).split("/")[0];if(u){let h=t.resolveRepoPath(`apps/${u}`),g=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(g)&&(r=h,t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}function Ke(){try{let l=P.getInstance(),e=l.resolveAppPath("package.json"),t=l.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(o=>{let a=o.startsWith("@donotdev/"),n=o==="entities",i=s[o]&&typeof s[o]=="string"&&s[o].startsWith("workspace:");return a||n||i}).filter(o=>!he.buildTimePackages.includes(o)).sort()}catch{return[]}}function G(l){return l&&typeof l=="object"&&!Array.isArray(l)}import Ee from"node:fs";import Ze from"node:path";var Xe=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,H=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{..._e.selectors,...this.options.customPatterns?.selectors},themes:{..._e.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(a=>a.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((a,n)=>{let i=a.replace(/[^a-zA-Z0-9]/g,"");return i?n===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,a=this.pathResolver.normalizePath(t),n=this._stripComments(e),i=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=i.exec(n))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let h=c.match(this.patterns.themes.themeIcon),g=c.match(this.patterns.themes.themeIsDark),d={name:p,displayName:u,isDark:g?g[1]==="1":!1,meta:{icon:h?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(d),s.themes.set(p,{name:p,displayName:u,isDark:d.isDark,file:a,variables:new Set,meta:d.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${a}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Xe.lastIndex=0;(r=Xe.exec(t))!==null;){let o=r[1];o&&o.trim()&&s.add(o.trim())}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let a=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let a=this.validateCSS(e);return{themes: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:a}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};import*as x from"@clack/prompts";var C={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 Ht(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function I(l,e){return Ht()?`${e}${l}${C.reset}`:l}function k(l,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,a=P.getInstance(),n=null;if(o){let c=a.resolveAppPath(r);a.pathExists(c)||a.mkdir(c),n=a.resolveAppPath(`${r}/${l.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${l} Log Started at ${new Date().toISOString()} ===
|
|
2
|
-
`;
|
|
3
|
-
`;a.appendFile(n,w)}},p=(c,u)=>{if(u.length===0)return c;let h=u.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${c} ${h}`};return{debug:(c,...u)=>{e&&(o?i("DEBUG",c,u):x.log.message(I(p(c,u),C.gray)))},verbose:(c,...u)=>{t&&(o?i("VERBOSE",c,u):x.log.message(p(c,u)))},info:(c,...u)=>{o?i("INFO",c,u):x.log.info(I(p(c,u),C.brightCyan))},warn:(c,...u)=>{e&&o?i("WARN",c,u):x.log.warn(I(p(c,u),C.brightYellow))},error:(c,...u)=>{e&&o?i("ERROR",c,u):x.log.error(I(p(c,u),C.brightRed))},success:(c,...u)=>{e&&o?i("SUCCESS",c,u):x.log.success(I(p(c,u),C.brightGreen))},when:(c,u="debug")=>(h,...g)=>{if(c){let d=p(h,g);switch(u){case"verbose":t&&(x.log.message(d),i("VERBOSE",h,g));break;case"info":x.log.info(I(d,C.brightCyan)),i("INFO",h,g);break;case"warn":x.log.warn(I(d,C.brightYellow)),i("WARN",h,g);break;case"error":x.log.error(I(d,C.brightRed)),i("ERROR",h,g);break;case"success":x.log.success(I(d,C.brightGreen)),i("SUCCESS",h,g);break;default:e&&(x.log.message(I(d,C.gray)),i("DEBUG",h,g))}}},getLogFilePath:()=>n}}var Vt=3,Qe="dndev-font-preloads.json";async function Jt(l,e){let t=k("font-preload-next",e,!1);try{let s=await l.resolvePatterns("css"),{consumerFiles:r}=await l.resolveFiles(s,"css");if(!r?.length)return[Z.Inter];let o=new H(l,{debug:e,logger:t}),a=new Set;for(let i of r)try{let p=await l.read(i,{format:"text"});p&&o.extractFontFamilies(p).forEach(c=>a.add(c))}catch{}if(a.size===0)return[Z.Inter];let n=new Set;for(let i of a){let p=Z[i];p&&n.add(p)}return Array.from(n)}catch{return[Z.Inter]}}function et({pathResolver:l,debug:e=!1}){let t=k("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{let n=l.getAppRoot();if(!n)return o();let i=await Jt(l,e),p=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",c=[];for(let[g]of Object.entries(r.assets)){if(!g.endsWith(".woff2")&&!g.endsWith(".woff"))continue;let d=g.toLowerCase();if(i.some(w=>d.includes(w))){let w=p?`${p}/${g}`:`/${g}`;if(c.push({href:w,type:"font/woff2"}),c.length>=Vt)break}}let u=Ze.join(n,"public");if(!Ee.existsSync(u))try{Ee.mkdirSync(u,{recursive:!0})}catch(g){return t.debug(`Font preload: could not create public dir: ${g?.message}`),o()}let h=Ze.join(u,Qe);Ee.writeFileSync(h,JSON.stringify(c,null,0),"utf8"),t.debug(`Font preload: wrote ${c.length} entries to ${Qe}`)}catch(n){t.debug(`Font preload manifest: ${n?.message}`)}o()})}}}var qt=[...new Set(Object.values(Z).map(l=>`@fontsource/${l.replace(/-latin$/,"")}`))];function tt({originalWebpack:l,unusedFeaturePackages:e,usedFeaturePackages:t,logger:s,debug:r}){return(o,a)=>{let{dev:n,isServer:i,webpack:p}=a;n&&!i&&(o.infrastructureLogging={level:"error"},o.stats={...o.stats,logging:"error",loggingTrace:!1},o.ignoreWarnings=[...o.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let c=o.module?.rules?.find(u=>u.test?.test?.(".svg"));c&&(c.exclude=/\.svg$/i),o.module=o.module||{},o.module.rules=o.module.rules||[],o.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),p?.IgnorePlugin&&o.plugins.push(new p.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let u=P.getInstance();o.plugins.push(et({pathResolver:u,debug:r}))}catch(u){s.debug(`Font preload webpack plugin skipped: ${u?.message}`)}if(e.length>0)if(s.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),s.info(`\u2705 Including features: ${t.join(", ")}`),o.externals=o.externals||[],Array.isArray(o.externals))o.externals.push(...e);else{let u=o.externals;o.externals=(h,g,d)=>e.includes(g)?d(null,"commonjs "+g):typeof u=="function"?u(h,g,d):d()}return l?l(o,a):o}}function st({originalRewrites:l,handlers:e,logger:t}){return async function(){try{let s=l?await l():[],o=e.filter(n=>n?.getAPIRewrites).map(n=>n.getAPIRewrites()).reduce((n,i)=>(i?.beforeFiles&&n.beforeFiles.push(...i.beforeFiles),i?.afterFiles&&n.afterFiles.push(...i.afterFiles),i?.fallback&&n.fallback.push(...i.fallback),n),{beforeFiles:[],afterFiles:[],fallback:[]}),a={beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...o.fallback]};return a.beforeFiles.length===0&&a.afterFiles.length===0&&a.fallback.length===0?null:a}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),null}}}function rt({routeResult:l,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:a,restNextConfig:n,discoveredPackages:i,webpackConfig:p,rewritesConfig:c,missingOptionalDeps:u,env:h,logger:g}){let d=n?.output==="export",_=n?.distDir||".next";return{transpilePackages:[...i,...qt],...n?.serverExternalPackages||n?.serverComponentsExternalPackages?{serverExternalPackages:(n?.serverExternalPackages||n?.serverComponentsExternalPackages||[]).filter(T=>!T.startsWith("@donotdev/"))}:{},...G(n)?n:(g.warn("restNextConfig is not a plain object:",n),{}),distDir:_,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...G(l)?l:(g.error(`Route handler config invalid (got ${typeof l}):`,l),{}),...G(e)?e:(g.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...G(t)?t:(g.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...G(s)?s:(g.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...G(r)?r:(g.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...G(o)?o:(g.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...G(a)?a:(g.warn("serverShimConfig returned non-object:",a),{}),webpack:p,...d?{}:{rewrites:async()=>await c()||void 0},env:h,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var Yt=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json"],Kt="dndev-config-",ot=".dndev-build";function Xt(l){if(!l)return!1;let e=P.getInstance(),t=e.resolveAppPath(ot),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function Zt(l){if(!l)return;let e=P.getInstance(),t=e.resolveAppPath(ot),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s)}catch{}}function Ne(l,e){if(!l)return;let t=P.getInstance();for(let r of Yt){let o=t.resolveAppPath(r);if(t.pathExists(o))try{t.removeSync(o),e.debug(`Cleaned: ${r}`)}catch{}}let s=t.resolveAppPath("src/config");if(t.pathExists(s))try{let r=t.readdirSync(s);for(let o of r)if(o.startsWith(Kt)&&o.endsWith(".js"))try{let a=t.resolvePath(o,s);t.removeSync(a),e.debug(`Cleaned: src/config/${o}`)}catch{}}catch{}}async function Fe({routeHandler:l,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:o},a){let n=l?.pathResolver;if(!n)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let i=n.getAppRoot(),p=n.getRepoRoot();if(!i||i===p){a.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(d=>setTimeout(d,0));let g=n.getAppRoot();if(!g||g===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Xt(i)){a.debug("Discoveries already completed this build, skipping");return}let c=Date.now();if(l)try{a.info("\u{1F50D} Starting route discovery...");let d=(await l.generateFiles())?.routes?.length||0;a.info(`\u2705 Routes generated: ${d} routes found`),d===0&&a.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(g){throw a.error(`\u274C Route generation failed: ${g.message}`),g.stack&&a.error(`Stack: ${g.stack}`),g}else a.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let u=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:o}];for(let{name:g,handler:d}of u)try{await d.generateFiles()}catch(w){a.debug(`${g} generation failed: ${w.message}`)}let h=Date.now()-c;a.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`),Zt(i)}async function at(l,e,t){if(t)return!1;try{let s=await l.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 le={debug:!1,verbose:process.env.CI!=="true",features:{},generateManifest:!0,routes:{disabled:!1,debug:!1,routingMode:"app",generateMiddleware:!0},themes:{debug:!1},i18n:{debug:!1,fallbackLanguage:"en"},assets:{debug:!1},pwa:{debug:!1},seo:{disabled:!1,debug:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0,debug:!1},discovery:{debug:!1,verbose:!1,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"}};function nt(l,e){let t={...l};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=nt(l[s]||{},e[s]):t[s]=e[s]}),t}function it(l={}){return nt(le,l)}function lt(l){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:a={},seo:n={},serverShim:i={},discovery:p={},generateManifest:c,debug:u,verbose:h,...g}=l,d=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:u,verbose:h,mode:d,isDev:d==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:a,seoOptions:n,serverShimOptions:i,discoveryOptions:p,nextConfigOptions:g}}var $=class{constructor(e,t={}){this.options={...t,...this.getHandlerDefaults()},this.logger=k(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=P.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...le.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:a}=s;return this.applyViteIgnorePlugin(t,a),this._generateFiles(),e.webpack?e.webpack(t,s):t},rewrites:async function(){try{let t=e.rewrites?await e.rewrites():[],s=this.getAPIRewrites();return this.mergeRewrites(t,s)}catch(t){return this.logger.error(`${this.getHandlerName()} handler failed to merge rewrites: ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`),[]}}.bind(this)})}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let t=this.getHandlerName().toLowerCase(),s=X.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!s)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let r=this.generateConfigContent(e);this.writeGeneratedFile(s,r,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),s=O[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
1
|
+
var ne={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},We={available:["auth","oauth","billing","crud"],packageNames:{auth:"@donotdev/auth",oauth:"@donotdev/oauth",billing:"@donotdev/billing",crud:"@donotdev/crud"},hooks:{auth:["useAuth"],oauth:["useOAuth","useOAuthPartner","useOAuthConnection"],billing:["useStripeBilling","useStripeCheckout"],crud:["useCrud","useCrudCollection"]}};var I={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},Z={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configServer:"src/config/dndev-config-server.js"},vite:{routeInspection:"src/routes.generated.log",themeInspection:"src/themes.generated.log",i18nInspection:"src/i18n.generated.log",assetInspection:"src/assets.generated.log",envInspection:"src/env.generated.log"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},ke={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},ae={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},he={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},F={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${he.SOURCE_EAGER}/*_*.json`],lazy:[`${he.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},fe={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","lucide-react","valibot","i18next","i18next-browser-languagedetector","i18next-http-backend","react-i18next","@tanstack/react-query","react-helmet-async","@donotdev/core","@donotdev/components","@donotdev/ui","@donotdev/templates","@donotdev/firebase"],optionalFeatures:["@donotdev/components","@donotdev/auth","@donotdev/billing","@donotdev/crud","@donotdev/oauth","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder"],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},Be=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var Ae={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}},ie={Inter:"inter-latin","Space Grotesk":"space-grotesk-latin","Playfair Display":"playfair-display-latin","Press Start 2P":"press-start-2p-latin",Roboto:"roboto-latin"},_e=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Ge={base:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...F.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:F.globalIgnore}};function He(l,e=null){let t=F[l];if(!t)throw new Error(`Unknown pattern type: ${l}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function de(l){return Ge[l]||Ge.base}import*as m from"node:fs";import"node:fs";import{createRequire as Ht}from"node:module";import{resolve as me,join as W,dirname as V,relative as Ve,normalize as Vt,sep as Je,extname as Jt}from"node:path";import{fileURLToPath as qt}from"node:url";import Yt from"fast-glob";var te={getGlobOptionsFor:de||void 0,SCAN_PATTERNS:F||void 0,getPatternsFor:He||void 0,I18N_PATHS:he||void 0},R={error:(l,e)=>{},warn:(l,e)=>{},info:l=>{}};function qe(l,e){return l().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Ye={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},y=class l{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return l._instance||(l._instance=new l(e)),l._instance}static _reset(){l._instance=null}constructor(e={}){if(l._instance)return l._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,l._instance=this}normalizePath(e){if(!e)return"";try{return Vt(e).split(Je).join("/")}catch{return String(e).split(Je).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Ve(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(V(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=Ht(W(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let n=e.replace("@donotdev/",""),a=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(a))return a;if(["auth","billing","crud","oauth"].includes(n)){let i=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(i))return i}if(n==="firebase"){let i=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(i))return i}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=me(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=me(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=me(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=m.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:Jt(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await m.promises.readFile(e);let n=await m.promises.readFile(e,r),a=this.stripBom(n);return o==="json"?JSON.parse(a):a}catch(n){return this.options.debug&&R.warn(`Failed to read file: ${e}`,n),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return m.readFileSync(e);let n=m.readFileSync(e,r),a=this.stripBom(n);return o==="json"?JSON.parse(a):a}catch(n){return this.options.debug&&R.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:a=!1}=s,i=this.normalizePath(e),p=this.normalizePath(V(i)),c=this.pathExists(i);if(c&&!o)return a&&R.info(`Skipping existing file: ${i}`),!1;if(n)return R.info(`[DRY RUN] Would write file: ${i}`),!0;try{await m.promises.mkdir(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return await qe(async()=>(Buffer.isBuffer(h)?await m.promises.writeFile(i,h):await m.promises.writeFile(i,h,"utf8"),a&&R.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:a=!1}=s,i=this.normalizePath(e),p=this.normalizePath(V(i)),c=this.pathExists(i);if(c&&!o)return a&&R.info(`Skipping existing file: ${i}`),!1;if(n)return R.info(`[DRY RUN] Would write file: ${i}`),!0;try{m.mkdirSync(p,{recursive:!0})}catch(g){if(g?.code!=="EEXIST")throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=JSON.stringify(t,null,2):h=String(t);try{return Buffer.isBuffer(h)?m.writeFileSync(i,h):m.writeFileSync(i,h,"utf8"),a&&R.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch(g){throw new Error(`Failed to write file: ${i}: ${g instanceof Error?g.message:String(g)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:o=!1,verbose:n=!1}=s,a=this.normalizePath(t),i=this.pathExists(a);if(i&&!r)return n&&R.info(`Skipping existing file: ${a}`),!1;if(o)return R.info(`[DRY RUN] Would copy file: ${a}`),!0;let p=this.normalizePath(V(a));try{await m.promises.mkdir(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await qe(async()=>(await m.promises.copyFile(e,a),n&&R.info(`${i?"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),i=this.pathExists(a);if(i&&!r)return n&&R.info(`Skipping existing file: ${a}`),!1;if(o)return R.info(`[DRY RUN] Would copy file: ${a}`),!0;let p=this.normalizePath(V(a));try{m.mkdirSync(p,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return m.copyFileSync(e,a),n&&R.info(`${i?"Updated":"Created"} file: ${a}`),!0}catch{return!1}}pathExists(e,t=!1){try{return m.existsSync(e)}catch(s){return t||R.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return m.existsSync(t)||m.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return m.readdirSync(e,t)}catch(s){return this.options.debug&&R.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return m.statSync(e)}catch(t){return this.options.debug&&R.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return m.realpathSync(e)}watch(e,t,s){return m.watch(e,t,s)}lstatSync(e){try{return m.lstatSync(e)}catch(t){return this.options.debug&&R.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await m.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{m.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await m.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){m.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return m.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=W(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(me(e)),s=this.getAppRoot(),r=Ve(s,t),o=this.normalizePath(r);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(W(e,t)),o=this.getAppRoot(),n=this.normalizePath(o),a=r.startsWith(n)?r.slice(n.length+1):r,i={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:te.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([a],{...i,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=te.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let o=this.normalizePath(W(r,t.PUBLISHED_ROOT,s)),n=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(n),o}async _globWithNormalization(e,t){return(await Yt(e,t)).map(r=>{let o=typeof r=="string"?r:r.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),o=te.getGlobOptionsFor?te.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}),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=a.length>0?await this._globWithNormalization(a,p):[],u=await this._globWithNormalization(i,p);return{frameworkFiles:c,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!te.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=te.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,a={framework:o?(n.framework||[]).map(i=>this.resolveRepoPath(i)).filter(Boolean):[],consumer:(n.consumer||[]).map(i=>this.resolveAppPath(i)),all:[]};return a.all=[...a.consumer,...a.framework],a}getEmptyModulePath(e=!1){if(e)return"@donotdev/core/empty";let t=this.resolvePackage("@donotdev/core/empty");if(t)return t;let s=V(qt(import.meta.url));return this.normalizePath(W(s,"../empty.js"))}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let o=this.normalizePath(W(t,Ye.TOOLING)),n=this.normalizePath(W(t,Ye.CORE));if(this.pathExists(o)&&this.pathExists(n))return t;let a=W(t,"apps");if(this.pathExists(a)&&this.statSync(a)?.isDirectory())return this.normalizePath(t);let i=this.normalizePath(W(t,"package.json"));if(this.pathExists(i)&&this.normalizePath(V(t))===t)return t;let p=this.normalizePath(V(t));if(p===t)break;t=p,s++}return this.normalizePath(e)}};function Ke({logger:l,debug:e=!1}={}){let t=y.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):l&&l.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&l&&l.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(),i=t.normalizePath(a);if(i.includes("/apps/")){let p=i.indexOf("/apps/"),u=i.substring(p+6).split("/")[0];if(u){let h=t.resolveRepoPath(`apps/${u}`),g=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(g)&&(r=h,t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&l&&l.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}var Xe=/--(?:font-family|font-headline)\s*:\s*(?:['"]([^'"]+)['"]|([^;]+?));/g,J=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{...Ae.selectors,...this.options.customPatterns?.selectors},themes:{...Ae.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(n=>n.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((n,a)=>{let i=n.replace(/[^a-zA-Z0-9]/g,"");return i?a===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),a=this._stripComments(e),i=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=i.exec(a))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let h=c.match(this.patterns.themes.themeIcon),g=c.match(this.patterns.themes.themeIsDark),d={name:p,displayName:u,isDark:g?g[1]==="1":!1,meta:{icon:h?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(d),s.themes.set(p,{name:p,displayName:u,isDark:d.isDark,file:n,variables:new Set,meta:d.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${n}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Xe.lastIndex=0;(r=Xe.exec(t))!==null;){let o=r[1];o&&o.trim()&&s.add(o.trim())}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let n=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];n&&t.push(`Theme class "${n}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let n=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:n}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};import*as _ from"@clack/prompts";var D={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function Kt(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function T(l,e){return Kt()?`${e}${l}${D.reset}`:l}function x(l,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:o=!1}=s,n=y.getInstance(),a=null;if(o){let c=n.resolveAppPath(r);n.pathExists(c)||n.mkdir(c),a=n.resolveAppPath(`${r}/${l.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${l} Log Started at ${new Date().toISOString()} ===
|
|
2
|
+
`;n.writeSync(a,u)}let i=(c,u,h)=>{if(a){let g=new Date().toISOString(),d=h.length>0?" "+h.map(S=>typeof S=="object"?JSON.stringify(S,null,2):String(S)).join(" "):"",P=`${g} [${c}] ${u}${d}
|
|
3
|
+
`;n.appendFile(a,P)}},p=(c,u)=>{if(u.length===0)return c;let h=u.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${c} ${h}`};return{debug:(c,...u)=>{e&&(o?i("DEBUG",c,u):_.log.message(T(p(c,u),D.gray)))},verbose:(c,...u)=>{t&&(o?i("VERBOSE",c,u):_.log.message(p(c,u)))},info:(c,...u)=>{o?i("INFO",c,u):_.log.info(T(p(c,u),D.brightCyan))},warn:(c,...u)=>{e&&o?i("WARN",c,u):_.log.warn(T(p(c,u),D.brightYellow))},error:(c,...u)=>{e&&o?i("ERROR",c,u):_.log.error(T(p(c,u),D.brightRed))},success:(c,...u)=>{e&&o?i("SUCCESS",c,u):_.log.success(T(p(c,u),D.brightGreen))},when:(c,u="debug")=>(h,...g)=>{if(c){let d=p(h,g);switch(u){case"verbose":t&&(_.log.message(d),i("VERBOSE",h,g));break;case"info":_.log.info(T(d,D.brightCyan)),i("INFO",h,g);break;case"warn":_.log.warn(T(d,D.brightYellow)),i("WARN",h,g);break;case"error":_.log.error(T(d,D.brightRed)),i("ERROR",h,g);break;case"success":_.log.success(T(d,D.brightGreen)),i("SUCCESS",h,g);break;default:e&&(_.log.message(T(d,D.gray)),i("DEBUG",h,g))}}},getLogFilePath:()=>a}}var Xt=3,Ze="dndev-font-preloads.json";async function Zt(l,e){let t=x("font-preload-next",e,!1);try{let s=await l.resolvePatterns("css"),{consumerFiles:r}=await l.resolveFiles(s,"css");if(!r?.length)return[ie.Inter];let o=new J(l,{debug:e,logger:t}),n=new Set;for(let i of r)try{let p=await l.read(i,{format:"text"});p&&o.extractFontFamilies(p).forEach(c=>n.add(c))}catch{}if(n.size===0)return[ie.Inter];let a=new Set;for(let i of n){let p=ie[i];p&&a.add(p)}return Array.from(a)}catch{return[ie.Inter]}}function Qe({pathResolver:l,debug:e=!1}){let t=x("font-preload-next",e,!1);return{apply(s){s.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(r,o)=>{if(r.compiler.isChild()||r.compiler.name?.includes("server"))return o();try{if(!l.getAppRoot())return o();let i=await Zt(l,e),p=r.outputOptions.publicPath&&String(r.outputOptions.publicPath)!=="auto"?r.outputOptions.publicPath.replace(/\/$/,""):"",c=[];for(let[g]of Object.entries(r.assets)){if(!g.endsWith(".woff2")&&!g.endsWith(".woff"))continue;let d=g.toLowerCase();if(i.some(P=>d.includes(P))){let P=p?`${p}/${g}`:`/${g}`;if(c.push({href:P,type:"font/woff2"}),c.length>=Xt)break}}let u=l.resolveAppPath("public");if(!l.pathExists(u))try{l.ensureDirSync(u)}catch(g){return t.debug(`Font preload: could not create public dir: ${g?.message}`),o()}let h=l.resolvePath(Ze,u);l.writeSync(h,JSON.stringify(c,null,0),{overwrite:!0}),t.debug(`Font preload: wrote ${c.length} entries to ${Ze}`)}catch(a){t.debug(`Font preload manifest: ${a?.message}`)}o()})}}}function et({postcssImport:l,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?l({resolve:s}):l,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var tt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Qt(l){return(e,t)=>{tt[e]&&(e=tt[e]);let s=l.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=l.resolveFrameworkPackage(r,t);if(n){if(o){let i=l.resolvePath(o,n);if(l.pathExists(i))return i;let p=i+".css";if(l.pathExists(p))return p}let a=l.resolvePath("index.css",n);if(l.pathExists(a))return a}}return l.resolvePath(e,t)}}async function es(){let[l,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=y.getInstance();return et({postcssImport:l,postcssNesting:e,autoprefixer:t,resolve:Qt(s)})}function st(){try{let l=y.getInstance(),e=l.resolveAppPath("package.json"),t=l.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(o=>{let n=o.startsWith("@donotdev/"),a=o==="entities",i=s[o]&&typeof s[o]=="string"&&s[o].startsWith("workspace:");return n||a||i}).filter(o=>!fe.buildTimePackages.includes(o)).sort()}catch{return[]}}function B(l){return l&&typeof l=="object"&&!Array.isArray(l)}var rt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function ot({originalWebpack:l,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],logger:r,debug:o}){return(n,a)=>{let{dev:i,isServer:p,webpack:c}=a;i&&!p&&(n.infrastructureLogging={level:"error"},n.stats={...n.stats,logging:"error",loggingTrace:!1},n.ignoreWarnings=[...n.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let u=n.module?.rules?.find(h=>h.test?.test?.(".svg"));u&&(u.exclude=/\.svg$/i),n.module=n.module||{},n.module.rules=n.module.rules||[],n.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),n.resolve=n.resolve||{},n.resolve.alias={...n.resolve.alias,...rt},c?.IgnorePlugin&&n.plugins.push(new c.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=y.getInstance();n.plugins.push(Qe({pathResolver:h,debug:o}))}catch(h){r.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(r.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),r.info(`\u2705 Including features: ${t.join(", ")}`),n.externals=n.externals||[],Array.isArray(n.externals))n.externals.push(...e);else{let h=n.externals;n.externals=(g,d,P)=>e.includes(d)?P(null,"commonjs "+d):typeof h=="function"?h(g,d,P):P()}if(s.length>0&&c?.NormalModuleReplacementPlugin){let g=y.getInstance().getEmptyModulePath(),d=s.map(S=>S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),P=new RegExp(`^(${d.join("|")})(\\/|$)`);n.plugins.push(new c.NormalModuleReplacementPlugin(P,g)),o&&r.debug(`Aliased ${s.length} missing optional deps to empty module`)}return l?l(n,a):n}}function nt({originalRewrites:l,handlers:e,logger:t}){return async function(){try{let s=l?await l():[],o=e.filter(a=>a?.getAPIRewrites).map(a=>a.getAPIRewrites()).reduce((a,i)=>(i?.beforeFiles&&a.beforeFiles.push(...i.beforeFiles),i?.afterFiles&&a.afterFiles.push(...i.afterFiles),i?.fallback&&a.fallback.push(...i.fallback),a),{beforeFiles:[],afterFiles:[],fallback:[]}),n={beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...o.fallback]};return n.beforeFiles.length===0&&n.afterFiles.length===0&&n.fallback.length===0?null:n}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),null}}}function at({routeResult:l,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:a,discoveredPackages:i,webpackConfig:p,rewritesConfig:c,missingOptionalDeps:u,env:h,logger:g}){let d=a?.output==="export",S=a?.distDir||".next";return{transpilePackages:i,...a?.serverExternalPackages||a?.serverComponentsExternalPackages?{serverExternalPackages:(a?.serverExternalPackages||a?.serverComponentsExternalPackages||[]).filter($=>!$.startsWith("@donotdev/"))}:{},...B(a)?a:(g.warn("restNextConfig is not a plain object:",a),{}),turbopack:{...a?.turbopack||{},resolveAlias:{...a?.turbopack?.resolveAlias||{},...rt,...u?.length>0?Object.fromEntries(u.flatMap($=>[[$,"@donotdev/core/empty"],[`${$}/*`,"@donotdev/core/empty"]])):{}}},distDir:S,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...B(l)?l:(g.error(`Route handler config invalid (got ${typeof l}):`,l),{}),...B(e)?e:(g.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...B(t)?t:(g.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...B(s)?s:(g.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...B(r)?r:(g.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...B(o)?o:(g.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...B(n)?n:(g.warn("serverShimConfig returned non-object:",n),{}),webpack:p,...d?{}:{rewrites:async()=>await c()||void 0},env:h,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var Ee="fonts",Ne="dndev-fonts.css",ts=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g;function ss(l){let e=l.resolveFrameworkPackage("@donotdev/ui");if(!e)return[];let t=l.resolvePath("src/dndev.css",e),s=l.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=ts.exec(s))!==null;)r.push([o[1],o[2]]);return r}function it({debug:l=!1,force:e=!1}={}){let t=x("font-copy",l,!1),s=y.getInstance(),r=s.resolveAppPath(`public/${Ne}`);if(!e&&s.pathExists(r)){t.debug("dndev-fonts.css already exists, skipping font copy");return}let o=ss(s);if(o.length===0){t.debug("No @fontsource imports found in dndev.css");return}let n=s.resolveAppPath(`public/${Ee}`);s.ensureDir(n);let a=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
4
|
+
`],i=new Set;for(let[p,c]of o){let u=s.resolveFrameworkPackage(`@fontsource/${p}`);if(!u){t.debug(`@fontsource/${p} not found`);continue}let h=s.resolvePath(`${c}.css`,u),g=s.readSync(h,{format:"text"});if(!g){t.debug(`Missing: @fontsource/${p}/${c}.css`);continue}let d=g.replace(/url\(\.\/files\/([^)]+)\)/g,(P,S)=>{let M=s.resolvePath(`files/${S}`,u),$=s.pathExists(M);if($&&!i.has(S)){let j=s.resolvePath(S,n);s.copySync(M,j,{overwrite:!0}),i.add(S)}return $?`url(/${Ee}/${S})`:`url(./files/${S})`});a.push(d)}s.writeSync(r,a.join(`
|
|
5
|
+
`)),t.debug(`Font copy: wrote ${Ne} (${i.size} font files copied)`)}function lt(){let l=y.getInstance(),e=l.resolveAppPath(`public/${Ne}`),t=l.resolveAppPath(`public/${Ee}`);if(l.pathExists(e))try{l.removeSync(e)}catch{}if(l.pathExists(t))try{l.removeSync(t)}catch{}}var rs=["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"],os="dndev-config-",ct=".dndev-build";function ns(l){if(!l)return!1;let e=y.getInstance(),t=e.resolveAppPath(ct),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function as(l){if(!l)return;let e=y.getInstance(),t=e.resolveAppPath(ct),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s)}catch{}}function Fe(l,e){if(!l)return;let t=y.getInstance();for(let r of rs){let o=t.resolveAppPath(r);if(t.pathExists(o))try{t.removeSync(o),e.debug(`Cleaned: ${r}`)}catch{}}lt();let s=t.resolveAppPath("src/config");if(t.pathExists(s))try{let r=t.readdirSync(s);for(let o of r)if(o.startsWith(os)&&o.endsWith(".js"))try{let n=t.resolvePath(o,s);t.removeSync(n),e.debug(`Cleaned: src/config/${o}`)}catch{}}catch{}}async function Ce({routeHandler:l,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:o},n){let a=l?.pathResolver;if(!a)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let i=a.getAppRoot(),p=a.getRepoRoot();if(!i||i===p){n.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(d=>setTimeout(d,0));let g=a.getAppRoot();if(!g||g===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(ns(i)){n.debug("Discoveries already completed this build, skipping");return}let c=Date.now();if(l)try{n.info("\u{1F50D} Starting route discovery...");let d=(await l.generateFiles())?.routes?.length||0;n.info(`\u2705 Routes generated: ${d} routes found`),d===0&&n.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(g){throw n.error(`\u274C Route generation failed: ${g.message}`),g.stack&&n.error(`Stack: ${g.stack}`),g}else n.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let u=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:o}];for(let{name:g,handler:d}of u)try{await d.generateFiles()}catch(P){n.debug(`${g} generation failed: ${P.message}`)}try{it()}catch(g){n.debug(`Font copy failed (non-critical): ${g.message}`)}let h=Date.now()-c;n.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`),as(i)}async function pt(l,e,t){if(t)return!1;try{let s=await l.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 le={debug:!1,verbose:process.env.CI!=="true",features:{},generateManifest:!0,routes:{disabled:!1,debug:!1,routingMode:"app",generateMiddleware:!0},themes:{debug:!1},i18n:{debug:!1,fallbackLanguage:"en"},assets:{debug:!1},pwa:{debug:!1},seo:{disabled:!1,debug:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1},serverShim:{enabled:!0,debug:!1},discovery:{debug:!1,verbose:!1,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"}};function ut(l,e){let t={...l};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=ut(l[s]||{},e[s]):t[s]=e[s]}),t}function gt(l={}){return ut(le,l)}function ht(l){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:o={},pwa:n={},seo:a={},serverShim:i={},discovery:p={},generateManifest:c,debug:u,verbose:h,...g}=l,d=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:u,verbose:h,mode:d,isDev:d==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:o,featureOptions:e,pwaOptions:n,seoOptions:a,serverShimOptions:i,discoveryOptions:p,nextConfigOptions:g}}var A=class{constructor(e,t={}){this.options={...t,...this.getHandlerDefaults()},this.logger=x(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=y.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...le.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=Z.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!s)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let r=this.generateConfigContent(e);this.writeGeneratedFile(s,r,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),s=I[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
4
6
|
// Generated at: ${new Date().toISOString()}
|
|
5
7
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
6
8
|
|
|
@@ -22,7 +24,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
22
24
|
|
|
23
25
|
// Export for compatibility
|
|
24
26
|
export default ${t}Config;
|
|
25
|
-
`}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 F=class l{constructor(e,t={}){if(this.constructor===l)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=k(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 a=Date.now()-t;return this.logger.debug(`Discovery completed in ${a}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var me=class extends F{constructor(e,t={}){super(e,{assets:N.assets.fallback,assetPatterns:N.assets.patterns,frameworkPackage:ke.package,assetsPath:ke.assetsPath,modernFormats:N.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let a=[],n=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(n)&&this.options.generateAssets!==!1&&(a=(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:a,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+)/),a=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:a,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let a=`/${e}.${o}`;if(s.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(ie.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(`${ie.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(),a=this._analyzeAsset(o,r.size);a&&t.push(a)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let 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(`${ie.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(ie.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"}],a=[],n=[];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)){n.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,i),a.push(c.name)}catch(h){this.logger.debug(`Failed to copy ${c.name}: ${h.message}`),n.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),n.push(...r.map(c=>c.name));else for(let c of r){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){n.push(c.name);continue}try{let h=p.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;c.format==="ico"?g=await h.toFormat("png").toBuffer():g=await h.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,g),a.push(c.name)}catch(h){this.logger.debug(`Failed to generate ${c.name}: ${h.message}`),n.push(c.name)}}return{generated:a,skipped:n,error:null}}catch(i){return this.logger.debug(`Asset generation failed: ${i.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:i.message}}}};var De={data:null},Ce=class extends ${constructor(e={}){super(me,e)}getHandlerDefaults(){return{manifestPath:X.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
27
|
+
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var C=class l{constructor(e,t={}){if(this.constructor===l)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=x(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let n=Date.now()-t;return this.logger.debug(`Discovery completed in ${n}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var ve=class extends C{constructor(e,t={}){super(e,{assets:F.assets.fallback,assetPatterns:F.assets.patterns,frameworkPackage:ke.package,assetsPath:ke.assetsPath,modernFormats:F.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let n=[],a=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(a)&&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(ae.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let o of this.options.assets)await this._ensureAsset(o,r,s)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${ae.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let o=s.split("/").pop()||s.split("\\").pop(),n=this._analyzeAsset(o,r.size);n&&t.push(n)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(n=>this._matchesPattern(e,n))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let o=`/${e}.${r}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${ae.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(ae.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],n=[],a=[];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)){a.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,i),n.push(c.name)}catch(h){this.logger.debug(`Failed to copy ${c.name}: ${h.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 h=p.default(t).resize(c.size,c.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;c.format==="ico"?g=await h.toFormat("png").toBuffer():g=await h.toFormat(c.format).toBuffer(),await this.pathResolver.write(`public/${c.name}`,g),n.push(c.name)}catch(h){this.logger.debug(`Failed to generate ${c.name}: ${h.message}`),a.push(c.name)}}return{generated:n,skipped:a,error:null}}catch(i){return this.logger.debug(`Asset generation failed: ${i.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:i.message}}}};var Oe={data:null},De=class extends A{constructor(e={}){super(ve,e)}getHandlerDefaults(){return{manifestPath:Z.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
|
|
26
28
|
// Generated at: ${new Date().toISOString()}
|
|
27
29
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
28
30
|
|
|
@@ -39,7 +41,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
39
41
|
timestamp: Date.now(),
|
|
40
42
|
};
|
|
41
43
|
}
|
|
42
|
-
globalThis._DNDEV_CONFIG_.${
|
|
44
|
+
globalThis._DNDEV_CONFIG_.${I.assets} = {
|
|
43
45
|
mapping: assetConfig.manifest,
|
|
44
46
|
logoSvgContent: ${JSON.stringify(t)},
|
|
45
47
|
manifest: {
|
|
@@ -51,14 +53,14 @@ if (typeof globalThis !== 'undefined') {
|
|
|
51
53
|
|
|
52
54
|
// Export for compatibility
|
|
53
55
|
export default assetConfig;
|
|
54
|
-
`}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&&(
|
|
56
|
+
`}logDiscoveryResults(e){let t=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(Oe.data={pwaIcons:e.pwaIcons}),e}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({path:t.path,type:t.type,format:t.format,size:t.size,optimized:t.optimized})),manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} assets, ${e.copiedAssets.length} copied from framework`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateAssetManifest(e),this.options.optimizeImages&&await this.generateImageOptimization(e),await this.generateAPIHandler(e)}async generateAssetManifest(e){let t=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",t,"asset manifest")}generateAssetManifestContent(e){let t=e.assets.map(o=>` {
|
|
55
57
|
path: '${o.path}',
|
|
56
58
|
type: '${o.type}',
|
|
57
59
|
format: '${o.format}',
|
|
58
60
|
size: ${o.size},
|
|
59
61
|
optimized: ${o.optimized||!1}
|
|
60
62
|
}`).join(`,
|
|
61
|
-
`),s=Object.entries(e.manifest).map(([o,
|
|
63
|
+
`),s=Object.entries(e.manifest).map(([o,n])=>` ${o}: ${JSON.stringify(n)}`).join(`,
|
|
62
64
|
`),r=e.manifest.logoSvgContent||null;return`// Auto-generated asset manifest by @donotdev/config
|
|
63
65
|
// Generated at ${new Date().toISOString()}
|
|
64
66
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
@@ -119,7 +121,7 @@ ${t}
|
|
|
119
121
|
export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
|
|
120
122
|
|
|
121
123
|
export default imageConfigs;
|
|
122
|
-
`}};function
|
|
124
|
+
`}};function ft(l={}){return new De(l)}var be=class extends C{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],...t})}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=de("i18n"),n=r.eager||[],a=r.lazy||[],i=(this.options.additionalPaths||[]).map(v=>{let b=v.endsWith(".json")?v:`${v}/*_*.json`;return this.pathResolver.resolveAppPath(b)});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: ${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),h=this.pathResolver.normalizePath(s),g=(v,b)=>{let w=this.pathResolver.normalizePath(v),k=this.pathResolver.normalizePath(b);return w.startsWith(k)?w.slice(k.length+1):w},d=n.map(v=>g(v,t)),S=[...a,...i].map(v=>g(v,t)),M=p.map(v=>g(v,s)),$=c.map(v=>g(v,s)),j={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},q=await this.pathResolver._globWithNormalization(d,j),Q=await this.pathResolver._globWithNormalization(S,j),Y={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(v=>v!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(Y.ignore)}`);let E=await this.pathResolver._globWithNormalization(M,Y),z=await this.pathResolver._globWithNormalization($,Y);this.logger.debug(`Found ${q.length} eager, ${Q.length} lazy, ${E.length} framework eager, ${z.length} framework lazy files`),E.length>0?this.logger.debug(`Framework eager files (first 3): ${E.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),z.length>0?this.logger.debug(`Framework lazy files (first 3): ${z.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let re=[...new Set([...q,...Q,...E,...z])],ee=new Set([...q,...E]),f={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},H=new Map,L=[...E,...z];for(let v of L){let b=this._processTranslationFile(v,E.includes(v),t);if(b){let w=`${b.namespace}_${b.language}`;H.set(w,b),f.allNamespaces.add(b.namespace),f.supportedLanguages.add(b.language),E.includes(v)&&f.eagerNamespaces.add(b.namespace)}}let O=new Set;for(let v of re){if(L.includes(v))continue;let b=this._processTranslationFile(v,ee.has(v),t);if(b){let{namespace:w,language:k,importPath:pe,content:Se}=b,N=`${b.namespace}_${b.language}`;if(H.has(N)){let U=H.get(N);b.content=this._mergeTranslations(U.content,Se)}f.allNamespaces.add(w),f.supportedLanguages.add(k),O.add(k),ee.has(v)&&f.eagerNamespaces.add(w),f.mapping[w]||(f.mapping[w]={}),f.mapping[w][k]=pe,b.content&&(f.content[w]||(f.content[w]={}),f.content[w][k]=b.content),f.files.push({path:v,relativePath:this.pathResolver.getRelativePath(v),namespace:w,language:k,eager:ee.has(v),size:b.content?JSON.stringify(b.content).length:0})}}for(let[v,b]of H){let[w,k]=v.split("_");(!f.mapping[w]||!f.mapping[w][k])&&(f.mapping[w]||(f.mapping[w]={}),f.mapping[w][k]=b.importPath,f.content[w]||(f.content[w]={}),f.content[w][k]=b.content)}let K=O.size>0?[...O].sort():[this.options.fallbackLanguage];return{mapping:f.mapping,content:f.content,eagerNamespaces:[...f.eagerNamespaces].sort(),allNamespaces:[...f.allNamespaces].sort(),supportedLanguages:K,fallbackLanguage:this.options.fallbackLanguage,files:f.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,n,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,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 Ie=class extends A{constructor(e={}){super(be,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...le.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
|
|
123
125
|
// Generated at: ${new Date().toISOString()}
|
|
124
126
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
125
127
|
|
|
@@ -128,7 +130,7 @@ const i18nConfig = {
|
|
|
128
130
|
languages: ${JSON.stringify(s,null,2)},
|
|
129
131
|
eager: ${JSON.stringify(r,null,2)},
|
|
130
132
|
fallback: '${o}',
|
|
131
|
-
content: ${JSON.stringify(
|
|
133
|
+
content: ${JSON.stringify(n||{},null,2)},
|
|
132
134
|
storage: {
|
|
133
135
|
type: 'localStorage',
|
|
134
136
|
prefix: 'dndev_i18n_',
|
|
@@ -161,12 +163,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
161
163
|
timestamp: Date.now(),
|
|
162
164
|
};
|
|
163
165
|
}
|
|
164
|
-
globalThis._DNDEV_CONFIG_.${
|
|
166
|
+
globalThis._DNDEV_CONFIG_.${I.i18n} = i18nConfig;
|
|
165
167
|
}
|
|
166
168
|
|
|
167
169
|
// Export for compatibility
|
|
168
170
|
export default i18nConfig;
|
|
169
|
-
`}};function
|
|
171
|
+
`}};function dt(l={}){return new Ie(l)}var ye=class extends C{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:s}=e,r=[...t,...s];this.logger.debug(`Processing ${r.length} PWA files`);let o=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),o=[...this.options.assetData.pwaIcons]);let n=await this._analyzePWAFiles(r),a=n.filter(h=>h.type==="manifest"||h.type==="service-worker");o.push(...a);let i=n.filter(h=>h.type==="icon"),p=new Set(o.filter(h=>h.type==="icon").map(h=>h.path)),c=i.filter(h=>!p.has(h.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
|
|
170
172
|
// Generated at ${new Date().toISOString()}
|
|
171
173
|
|
|
172
174
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -182,7 +184,7 @@ ${r?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
|
|
|
182
184
|
cleanupOutdatedPrecaches();
|
|
183
185
|
|
|
184
186
|
// Precache static assets
|
|
185
|
-
const precacheManifest = ${
|
|
187
|
+
const precacheManifest = ${n.length>2?n:"self.__WB_MANIFEST || []"};
|
|
186
188
|
precacheAndRoute(precacheManifest);
|
|
187
189
|
|
|
188
190
|
// Runtime caching strategies
|
|
@@ -200,20 +202,20 @@ self.addEventListener('message', (event) => {
|
|
|
200
202
|
self.addEventListener('activate', (event) => {
|
|
201
203
|
event.waitUntil(self.clients.claim());
|
|
202
204
|
});
|
|
203
|
-
`}_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:
|
|
204
|
-
maxEntries: ${
|
|
205
|
-
maxAgeSeconds: ${
|
|
206
|
-
})`),
|
|
207
|
-
statuses: ${JSON.stringify(
|
|
208
|
-
})`),
|
|
209
|
-
maxRetentionTime: ${
|
|
210
|
-
})`);let u="";return
|
|
211
|
-
cacheName: '${
|
|
205
|
+
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:o,handler:n,options:a={}}=s,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=[];a.expiration&&c.push(`new ExpirationPlugin({
|
|
206
|
+
maxEntries: ${a.expiration.maxEntries||50},
|
|
207
|
+
maxAgeSeconds: ${a.expiration.maxAgeSeconds||3600*24},
|
|
208
|
+
})`),a.cacheableResponse&&c.push(`new CacheableResponsePlugin({
|
|
209
|
+
statuses: ${JSON.stringify(a.cacheableResponse.statuses||[0,200])},
|
|
210
|
+
})`),a.backgroundSync&&c.push(`new BackgroundSyncPlugin('${a.backgroundSync.queueName||"background-sync-queue"}', {
|
|
211
|
+
maxRetentionTime: ${a.backgroundSync.maxRetentionTime||1440},
|
|
212
|
+
})`);let u="";return a.cacheName&&(u+=`
|
|
213
|
+
cacheName: '${a.cacheName}',`),c.length>0&&(u+=`
|
|
212
214
|
plugins: [
|
|
213
215
|
${c.join(`,
|
|
214
216
|
`)}
|
|
215
|
-
],`),
|
|
216
|
-
networkTimeoutSeconds: ${
|
|
217
|
+
],`),a.networkTimeoutSeconds&&(u+=`
|
|
218
|
+
networkTimeoutSeconds: ${a.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${a.cacheName||"cache-"+r}
|
|
217
219
|
registerRoute(
|
|
218
220
|
${p},
|
|
219
221
|
new ${i}({${u}
|
|
@@ -234,7 +236,7 @@ registerRoute(
|
|
|
234
236
|
}),
|
|
235
237
|
'POST'
|
|
236
238
|
);
|
|
237
|
-
`}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 a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let n of a){let i=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),n.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(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Ie=class extends ${constructor(e={}){super(be,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||De.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.enabled){this.logger.debug("PWA disabled, skipping generation");return}this.options.generateManifest&&await this.generatePWAManifest(e),this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,t,"PWA manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:o,webpack:a}=s;return this.applyViteIgnorePlugin(t,a),!r&&!o&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function ut(l={}){return new Ie(l)}import{createRequire as ts}from"node:module";function gt(l,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=l.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[...l.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 ce=null,ht=null;function Qt(l){let t=(l.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var re=class extends F{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(ce&&ht===s)return this.logger.debug("Using cached route discovery results"),this.routes=ce.routes,this.errors=ce.errors,this.source=ce.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/"),ce={routes:this.routes,errors:this.errors,source:this.source},ht=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),a=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),n=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=n.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 a=this._extractMetaExport(s,e.absolutePath),n=Qt(o),p=n===ne.HOMEPAGE_COMPONENT?ne.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:h,...g}=a||{};return{path:p,component:n,importPath:o,auth:a?.auth||!1,meta:{...c,...g,entity:c.entity,action:c.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=gt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let a=o.map(n=>`:${n}`).join("/");return`${r}/${a}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z])/g," $1").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),a=null,n=null;return o.length>1&&(a=o[o.length-2],s.includes("List")?n="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?n="form":(s.includes("Detail")||s.includes("View"))&&(n="detail")),{title:r,entity:a,action:n,file:e}}};function es(l,e,t="configuration-error",s={}){let r=`[${l}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=l,o.context=s,o}function ft(l,e,t,s={}){return es(l,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}import{readFileSync as Ar}from"node:fs";import{join as Nr}from"node:path";function dt(l){return l?.languages||l?.supportedLanguages||["en"]}function mt(l){return l?.fallback||l?.fallbackLanguage||"en"}var Te=class extends ${constructor(e={}){super(re,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:X.next.middleware,manifestPath:X.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(o=>o.auth&&o.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
239
|
+
`}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 i=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),a.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 Te=class extends A{constructor(e={}){super(ye,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Oe.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.enabled){this.logger.debug("PWA disabled, skipping generation");return}this.options.generateManifest&&await this.generatePWAManifest(e),this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,t,"PWA manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:o,webpack:n}=s;return this.applyViteIgnorePlugin(t,n),!r&&!o&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function mt(l={}){return new Te(l)}import{createRequire as cs}from"node:module";function vt(l,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=l.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[...l.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 ce=null,bt=null;function is(l){let t=(l.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var se=class extends C{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(ce&&bt===s)return this.logger.debug("Using cached route discovery results"),this.routes=ce.routes,this.errors=ce.errors,this.source=ce.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/"),ce={routes:this.routes,errors:this.errors,source:this.source},bt=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),o=await this._scanAdditionalPatterns(t),n=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),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 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),a=is(o),p=a===ne.HOMEPAGE_COMPONENT?ne.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:h,...g}=n||{};return{path:p,component:a,importPath:o,auth:n?.auth||!1,meta:{...c,...g,entity:c.entity,action:c.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=vt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let n=o.map(a=>`:${a}`).join("/");return`${r}/${n}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z])/g," $1").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),n=null,a=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?a="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?a="form":(s.includes("Detail")||s.includes("View"))&&(a="detail")),{title:r,entity:n,action:a,file:e}}};function ls(l,e,t="configuration-error",s={}){let r=`[${l}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=l,o.context=s,o}function yt(l,e,t,s={}){return ls(l,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function wt(l){return l?.languages||l?.supportedLanguages||["en"]}function Pt(l){return l?.fallback||l?.fallbackLanguage||"en"}var Me=class extends A{constructor(e={}){super(se,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:Z.next.middleware,manifestPath:Z.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
|
|
238
240
|
// Generated at: ${new Date().toISOString()}
|
|
239
241
|
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
240
242
|
|
|
@@ -253,7 +255,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
253
255
|
timestamp: Date.now(),
|
|
254
256
|
};
|
|
255
257
|
}
|
|
256
|
-
globalThis._DNDEV_CONFIG_.${
|
|
258
|
+
globalThis._DNDEV_CONFIG_.${I.routes} = {
|
|
257
259
|
mapping: routeMapping,
|
|
258
260
|
manifest: routeManifest,
|
|
259
261
|
};
|
|
@@ -263,17 +265,17 @@ if (typeof globalThis !== 'undefined') {
|
|
|
263
265
|
export const routes = routeMapping;
|
|
264
266
|
export const manifest = routeManifest;
|
|
265
267
|
export default { routes: routeMapping, manifest: routeManifest };
|
|
266
|
-
`}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles();let t=0;for(let s of e.routes)await this.generateSingleAppPage(s)&&t++;this.logger.debug(`Successfully generated ${t}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=["src/app/**/page.tsx","src/app/[...slug]/page.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let o of s)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),r++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(
|
|
268
|
+
`}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles();let t=0;for(let s of e.routes)await this.generateSingleAppPage(s)&&t++;this.logger.debug(`Successfully generated ${t}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=["src/app/**/page.tsx","src/app/[...slug]/page.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let o of s)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),r++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(n){this.logger.debug(`Could not clean file ${o}: ${n.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e){try{let t=this.convertRouteToAppPath(e.path),s=`src/app${t}/page.tsx`,r=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(r)&&!await this.hasGenerationMarker(r))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let o={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},n=this.generatePageFileContent(o);return this.writeGeneratedFile(s,n,`app page: ${t}`),!0}catch(t){return this.logger.debug(`Error generating page for route ${e.path}: ${t.message}`),!1}}convertRouteToAppPath(e){if(e===ne.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=cs(t),r=s.resolve(e);delete s.cache[r];let o=s(r);return o.default||o.i18nConfig||o}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e){let t=this.extractComponentName(e.filePath),s=e.relativePath||e.file,r=this.calculateRelativeImportPath(s,e.path),o=this.isClientComponent(e.filePath),n=e.metaExport&&Object.keys(e.metaExport).length>0,a=this.loadI18nConfig(),i=e.metaExport?.namespace,p=`// Generated by @donotdev/config - DO NOT EDIT
|
|
267
269
|
// This file will be regenerated when src/pages changes
|
|
268
270
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
269
271
|
${o?`'use client';
|
|
270
272
|
`:""}
|
|
271
273
|
import ${t} from '${r}';
|
|
272
|
-
`;return o||(
|
|
274
|
+
`;return o||(n&&i&&a?p+=this.generateMetadataFunction(e,i,a):n&&(p+=`
|
|
273
275
|
export const metadata = ${this.generateMetadataObject(e.metaExport)};
|
|
274
276
|
`)),p+=`
|
|
275
277
|
export default ${t};
|
|
276
|
-
`,p}generateMetadataFunction(e,t,s){let r=
|
|
278
|
+
`,p}generateMetadataFunction(e,t,s){let r=wt(s),o=Pt(s),n="`",a=r.map(i=>` '${i}': { href: ${n}\${baseUrl}\${currentPath}${n} }`).join(`,
|
|
277
279
|
`);return`
|
|
278
280
|
import type { Metadata } from 'next';
|
|
279
281
|
import { readFileSync } from 'node:fs';
|
|
@@ -323,7 +325,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
323
325
|
// Get base URL from environment or construct from request
|
|
324
326
|
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
|
|
325
327
|
(typeof process !== 'undefined' && process.env.VERCEL_URL
|
|
326
|
-
? ${
|
|
328
|
+
? ${n}https://\${process.env.VERCEL_URL}${n}
|
|
327
329
|
: '');
|
|
328
330
|
const currentPath = '${e.path}';
|
|
329
331
|
|
|
@@ -348,7 +350,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
348
350
|
}
|
|
349
351
|
}
|
|
350
352
|
|
|
351
|
-
const pageTitle = title ? ${
|
|
353
|
+
const pageTitle = title ? ${n}\${title} | \${siteName}${n} : siteName;
|
|
352
354
|
const pageDescription = description || '';
|
|
353
355
|
const pageImage = metaObject?.image || '/og-image.png';
|
|
354
356
|
const pageType = metaObject?.type || 'website';
|
|
@@ -367,7 +369,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
367
369
|
title: pageTitle,
|
|
368
370
|
...(pageDescription && { description: pageDescription }),
|
|
369
371
|
type: pageType,
|
|
370
|
-
url: ${
|
|
372
|
+
url: ${n}\${baseUrl}\${currentPath}${n},
|
|
371
373
|
...(pageImage && { images: [pageImage] }),
|
|
372
374
|
siteName: siteName,
|
|
373
375
|
},
|
|
@@ -379,7 +381,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
379
381
|
},
|
|
380
382
|
alternates: {
|
|
381
383
|
languages: {
|
|
382
|
-
${
|
|
384
|
+
${a}
|
|
383
385
|
},
|
|
384
386
|
},
|
|
385
387
|
};
|
|
@@ -452,9 +454,9 @@ export const config = {
|
|
|
452
454
|
'/((?!api|_next/static|_next/image|favicon.ico).*)',
|
|
453
455
|
],
|
|
454
456
|
};
|
|
455
|
-
`}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),o=s.relativePath||s.file;if(!o)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let
|
|
457
|
+
`}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),o=s.relativePath||s.file;if(!o)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let n=o.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
|
|
456
458
|
path: '${s.path}',
|
|
457
|
-
component: lazy(() => import('${
|
|
459
|
+
component: lazy(() => import('${n}')),
|
|
458
460
|
auth: ${JSON.stringify(s.auth)},
|
|
459
461
|
meta: ${JSON.stringify(s.meta)}
|
|
460
462
|
}`}).filter(s=>s!==null).join(`,
|
|
@@ -494,23 +496,23 @@ export const routeManifest = {
|
|
|
494
496
|
|
|
495
497
|
export default pageRoutes;
|
|
496
498
|
`}pathToComponentName(e){return e.split("/").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")+"Page"}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let r=e.replace(/\.tsx$/,"").replace(/^src\//,""),o=t==="/"?0:t.split("/").filter(Boolean).length;return`${"../".repeat(o+1)}${r}`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let s=this.pathResolver.readSync(t);return s?s.split(`
|
|
497
|
-
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function
|
|
499
|
+
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};function St(l={}){return new Me(l)}import{readFileSync as ps,readdirSync as us,existsSync as gs}from"fs";import{join as Rt}from"path";var we=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:o,siteName:n,crawlDelay:a=1,routes:i={},...p}=e;if(!o||!n)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:o,siteName:n,crawlDelay:a,routes:i,defaultImage:"/og-image.jpg",twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=x("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,s=null){try{let r=this.generateRouteMetaTags(e.routes||[]),o={routes:e.routes||[],routeMetaTags:r,baseUrl:this.options.baseUrl,siteName:this.options.siteName},n=this.discoverBlogPosts(),a={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:o.routes.length,publicRoutes:o.routes.filter(i=>!i.auth||i.auth===!1).length,protectedRoutes:o.routes.filter(i=>i.auth&&i.auth.required).length,blogPosts:n.length};return this.options.generateRobotsTxt&&(a.robotsTxt=await this.generateRobotsTxt(o,t,s)),this.options.generateSitemap&&(a.sitemap=await this.generateSitemap(o,t,s,n)),n.length>0&&(a.rss=await this.generateRSSFeed(n,t,s)),a.manifest=await this.generateManifest(o,t,s),a}catch(r){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${r.message}`),this.logger.error(`Stack: ${r.stack||"No stack trace available"}`),r}}async generateRobotsTxt(e,t,s=null){if(s&&await s("robots.txt"))return this.logger.info("\u2705 robots.txt already exists, skipping generation"),{fileName:"robots.txt",skipped:!0};let r=[];(e.routes||[]).forEach(n=>{if(n.auth&&n.auth.required){let a=n.path.startsWith("/")?n.path:`/${n.path}`;r.push(a)}}),r.push("/admin","/api","/_next","/static");let o=this.generateRobotsTxtContent({disallowedPaths:[...new Set(r)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",o),{fileName:"robots.txt",content:o,disallowedPaths:r.length}}async generateSitemap(e,t,s=null,r=[]){if(s&&await s("sitemap.xml"))return this.logger.info("\u2705 sitemap.xml already exists, skipping generation"),{fileName:"sitemap.xml",skipped:!0};let n=(e.routes||[]).filter(i=>!i.auth||i.auth===!1).map(i=>({url:i.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:i.path==="/"?"1.0":"0.8"}));if(r.length>0){n.push({url:"/blog",lastmod:r[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let i of r)n.push({url:`/blog/${i.slug}`,lastmod:i.date,changefreq:"monthly",priority:"0.6"})}let a=this.generateSitemapContent(n);return await t("sitemap.xml",a),{fileName:"sitemap.xml",content:a,publicRoutes:n.length}}async generateManifest(e,t,s=null){if(s&&await s("seo-manifest.json"))return this.logger.info("\u2705 seo-manifest.json already exists, skipping generation"),{fileName:"seo-manifest.json",skipped:!0};let r={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,protectedRoutes:e.routes?.filter(n=>n.auth&&n.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},o=JSON.stringify(r,null,2);return await t("seo-manifest.json",o),{fileName:"seo-manifest.json",content:o,manifest:r}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:o}=e,n=i=>i?i==="*"?"*":i.startsWith("/")?i:`/${i}`:"/",a=["User-agent: *",...s.map(i=>`Disallow: ${n(i)}`),...t.map(i=>`Allow: ${n(i)}`)];return o&&a.push(`Crawl-delay: ${o}`),r&&a.push(`Sitemap: ${r}`),a.join(`
|
|
498
500
|
`)}generateSitemapContent(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
499
501
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
500
|
-
${e.map(({url:s,lastmod:r,changefreq:o,priority:
|
|
501
|
-
${
|
|
502
|
+
${e.map(({url:s,lastmod:r,changefreq:o,priority:n})=>{let a=[` <loc>${this.options.baseUrl}${s}</loc>`];return r&&a.push(` <lastmod>${r}</lastmod>`),o&&a.push(` <changefreq>${o}</changefreq>`),n&&a.push(` <priority>${n}</priority>`),` <url>
|
|
503
|
+
${a.join(`
|
|
502
504
|
`)}
|
|
503
505
|
</url>`}).join(`
|
|
504
506
|
`)}
|
|
505
|
-
</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=
|
|
506
|
-
`)){let c=p.indexOf(":");c!==-1&&(i[p.slice(0,c).trim()]=p.slice(c+1).trim())}s.push({slug:
|
|
507
|
-
<title><![CDATA[${
|
|
508
|
-
<link>${this.options.baseUrl}/blog/${
|
|
509
|
-
<guid>${this.options.baseUrl}/blog/${
|
|
510
|
-
<description><![CDATA[${
|
|
511
|
-
<pubDate>${
|
|
512
|
-
<category>${
|
|
513
|
-
<enclosure url="${this.options.baseUrl}${
|
|
507
|
+
</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=Rt(this.appRoot,"src","content","blog");try{if(!gs(e))return[];let t=us(e).filter(r=>r.endsWith("_en.md"));if(t.length===0)return[];let s=[];for(let r of t){let o=ps(Rt(e,r),"utf-8"),n=r.replace(/_en\.md$/,""),a=o.match(/^---\r?\n([\s\S]*?)\r?\n---/),i={};if(a)for(let p of a[1].split(`
|
|
508
|
+
`)){let c=p.indexOf(":");c!==-1&&(i[p.slice(0,c).trim()]=p.slice(c+1).trim())}s.push({slug:n,title:i.title||n,description:i.description||"",date:i.date||new Date().toISOString().split("T")[0],tags:i.tags?i.tags.split(",").map(p=>p.trim()):[],image:i.image||null})}return s.sort((r,o)=>o.date.localeCompare(r.date)),this.logger.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(t){return this.logger.debug(`Blog content discovery skipped: ${t.message}`),[]}}async generateRSSFeed(e,t,s=null){if(s&&await s("rss.xml"))return this.logger.info("\u2705 rss.xml already exists, skipping generation"),{fileName:"rss.xml",skipped:!0};let r=e.map(n=>` <item>
|
|
509
|
+
<title><![CDATA[${n.title}]]></title>
|
|
510
|
+
<link>${this.options.baseUrl}/blog/${n.slug}</link>
|
|
511
|
+
<guid>${this.options.baseUrl}/blog/${n.slug}</guid>
|
|
512
|
+
<description><![CDATA[${n.description}]]></description>
|
|
513
|
+
<pubDate>${n.date?new Date(n.date).toUTCString():""}</pubDate>${n.tags.length?`
|
|
514
|
+
<category>${n.tags.join(", ")}</category>`:""}${n.image?`
|
|
515
|
+
<enclosure url="${this.options.baseUrl}${n.image}" type="image/png" length="0"/>`:""}
|
|
514
516
|
</item>`).join(`
|
|
515
517
|
`),o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
516
518
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
@@ -522,7 +524,7 @@ ${n.join(`
|
|
|
522
524
|
<atom:link href="${this.options.baseUrl}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
523
525
|
${r}
|
|
524
526
|
</channel>
|
|
525
|
-
</rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}};var
|
|
527
|
+
</rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(o=>!o.auth||o.auth===!1).length||0,r=e.routes?.filter(o=>o.auth&&o.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}};var je=class extends A{constructor(e={}){super(se,e);let t=y.getInstance(),s=x("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let o=e.seo?.baseUrl;if(!o&&r){let 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 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(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.seoGenerator=new we({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:o,siteName:n,crawlDelay:this.options.crawlDelay,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(o,n)=>{if(!o){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${o}`,n,o)},s=async o=>{try{let n=this.pathResolver.resolveAppPath(`public/${o}`);return this.pathResolver.pathExists(n)}catch{return!1}},r=await this.seoGenerator.generateSEOFiles(e,t,s);r.robotsTxt&&!r.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${r.robotsTxt.disallowedPaths||0} disallowed paths`),r.sitemap&&!r.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${r.sitemap.publicRoutes||0} routes`),r.rss&&!r.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${r.rss.postCount||0} blog posts`),r.manifest&&!r.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json")}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function $t(l={}){return new je(l)}function xt(l={}){let{debug:e}=l;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),Be.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var Pe=class extends C{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new J(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 _e.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(){_e.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var ze=class extends A{constructor(e={}){super(Pe,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new J(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 yt("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
|
|
526
528
|
// Generated at: ${new Date().toISOString()}
|
|
527
529
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
528
530
|
|
|
@@ -554,7 +556,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
554
556
|
timestamp: Date.now(),
|
|
555
557
|
};
|
|
556
558
|
}
|
|
557
|
-
globalThis._DNDEV_CONFIG_.${
|
|
559
|
+
globalThis._DNDEV_CONFIG_.${I.themes} = themeConfig;
|
|
558
560
|
}
|
|
559
561
|
|
|
560
562
|
// Export for compatibility
|
|
@@ -570,6 +572,6 @@ export function useTheme() {
|
|
|
570
572
|
}
|
|
571
573
|
|
|
572
574
|
export default useTheme;
|
|
573
|
-
`}};function
|
|
574
|
-
\u{1F3D7}\uFE0F DnDev Framework - Building for ${
|
|
575
|
-
`)
|
|
575
|
+
`}};function kt(l={}){return new ze(l)}function At({debug:l,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:a,pwaOptions:i,serverShimOptions:p,appUrl:c,isDev:u,logger:h}){let g=s.debug??l,d=r.debug??l,P=o.debug??l,S=n.debug??l,M=a.debug??l,$=i.debug??l,j=p.debug??l,q=s.verbose??e,Q=r.verbose??e,Y=o.verbose??e,E=n.verbose??e,z=a.verbose??e,re=i.verbose??e,ee=p.verbose??e,f={debug:l,verbose:e,generateManifest:t},H=s.disabled?null:St({...f,...s,debug:g,verbose:q});l&&h.debug(`Route handler created: ${H?"enabled":"disabled"} (debug: ${g})`);let L=kt({...f,...r,debug:d,verbose:Q}),O=dt({...f,...o,debug:P,verbose:Y}),K=ft({...f,...n,debug:S,verbose:E}),v=$t({...f,...a,debug:M,verbose:z,appUrl:c,isDev:u}),b=mt({...f,...i,debug:$,verbose:re}),w=xt({...f,...p,debug:j,verbose:ee});return{routeHandler:H,themeHandler:L,i18nHandler:O,assetHandler:K,seoHandler:v,pwaHandler:b,serverShimHandler:w}}function _t(l,e){let t={};if(l.routeHandler)try{t.routeConfig=l.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:l.themeHandler},{name:"i18n",handler:l.i18nHandler},{name:"asset",handler:l.assetHandler},{name:"seo",handler:l.seoHandler},{name:"pwa",handler:l.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=l.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}function hs(l){if(!l)return[];let e=y.getInstance();try{let t=e.resolvePath("package.json",l),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 fs(l){let e=fe.optionalFeatures||[],t=hs(l);return[...new Set([...e,...t])]}function Le(l){let e=fs(l),t=[],s=[],r=y.getInstance();for(let o of e)r.resolvePackage(o,l||void 0)?s.push(o):t.push(o);return{missing:t,installed:s}}function ds(l={}){let{port:e,...t}=l;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let G=process.env.CI==="true";process.env.DNDEV_BUILD_ID=G?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let{appConfig:s,...r}=t;if(!s)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let o=s?.features?{debug:s.features.debug}:void 0,n=s?.seo&&typeof s.seo!="boolean"?{...s.seo,siteName:s.seo.siteName||s.app?.name}:s?.app?.name?{siteName:s.app.name}:void 0,a=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:i,seo:p,...c}=r,u={...o?{features:o}:{},...n?{seo:n}:{},...c},h=gt(u),g=ht(h);if(!g)throw new Error("normalizeOptions returned undefined");let{generateManifest:d,debug:P,verbose:S,mode:M,isDev:$,routeOptions:j,themeOptions:q,i18nOptions:Q,assetOptions:Y,pwaOptions:E,seoOptions:z,serverShimOptions:re,nextConfigOptions:ee}=g,f=x("next-config",P,S),{appRoot:H,appRootSet:L}=Ke({logger:f,debug:P}),O=!1,K=!1,{installed:v}=Le(process.cwd()),b=Object.values(We.packageNames),w=b.filter(G=>!v.includes(G)),k=b.filter(G=>v.includes(G)),pe=process.env.DNDEV_BUILD_ID,Se=j?.routingMode||"app";if(f.info(`
|
|
576
|
+
\u{1F3D7}\uFE0F DnDev Framework - Building for ${M}${pe?` [build:${pe}]`:""}`),f.info(` Platform: Next.js | Routing: ${Se}
|
|
577
|
+
`),$){let G=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${G}`,P&&(f.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&f.debug(`Port configured: ${G} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||f.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let N=At({debug:P,verbose:S,generateManifest:d,routeOptions:j,themeOptions:q,i18nOptions:Q,assetOptions:Y,seoOptions:z,pwaOptions:E,serverShimOptions:re,isDev:$,logger:f}),U=_t(N,f);return async function(Re={}){let oe=y.getInstance(),ue=L?st():[];P&&ue.length>0&&f.debug(`Discovered ${ue.length} packages: ${ue.join(", ")}`);let{missing:ge}=Le(oe.getAppRoot());P&&ge.length>0&&f.debug(`Missing optional deps (will alias to empty): ${ge.join(", ")}`);let Ue=oe.getAppRoot();if(L&&!O){let $e=oe.resolveAppPath(".dndev-build"),xe=process.env.DNDEV_BUILD_ID;try{oe.readSync($e,{format:"text"})?.trim()===xe?(f.debug("Discoveries already completed by another worker, skipping"),O=!0):(Fe(Ue,f),await Ce(N,f),O=!0)}catch{Fe(Ue,f),await Ce(N,f),O=!0}}let X=typeof Re=="object"&&Re!==null?Re:{},{webpack:Nt,rewrites:Ft,...Ct}=X;L&&!K&&(K=await pt(N.assetHandler,f,K));let Dt=U.routeConfig(X),Ot=U.themeConfig(X),It=U.i18nConfig(X),Tt=U.assetConfig(X),Mt=U.seoConfig(X),jt=U.pwaConfig(X),zt=U.serverShimConfig(),Lt=ot({originalWebpack:Nt,unusedFeaturePackages:w,usedFeaturePackages:k,missingOptionalDeps:ge,logger:f,debug:P}),Ut=nt({originalRewrites:Ft,handlers:[N.routeHandler,N.themeHandler,N.i18nHandler,N.assetHandler,N.pwaHandler],logger:f}),Gt={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()}),...process.env.NEXT_PUBLIC_APP_URL?{NEXT_PUBLIC_APP_URL:process.env.NEXT_PUBLIC_APP_URL}:{},...process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY?{NEXT_PUBLIC_DONOTDEV_LICENSE_KEY:process.env.NEXT_PUBLIC_DONOTDEV_LICENSE_KEY}:{}},Wt=at({routeResult:Dt,themeResult:Ot,i18nResult:It,assetResult:Tt,seoResult:Mt,pwaResult:jt,serverShimResult:zt,restNextConfig:Ct,discoveredPackages:ue,webpackConfig:Lt,rewritesConfig:Ut,missingOptionalDeps:ge,env:Gt,logger:f});if(f.debug("Next.js config generated"),L){let $e=a?.name||"app",xe=oe.getAppRoot();f.info(`Name: ${$e}`),f.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),f.info("\u{1F527} Features: auto-detected"),f.info(`App root (final): ${xe}`)}return Wt}}var Et=ds;export{Et as default,Et as defineNextConfig,es as definePostCSSConfig};
|