@donotdev/core 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/functions/index.js +13 -13
- package/i18n/locales/eager/dndev_ar.json +13 -0
- package/i18n/locales/eager/dndev_da.json +13 -0
- package/i18n/locales/eager/dndev_de.json +13 -0
- package/i18n/locales/eager/dndev_en.json +13 -0
- package/i18n/locales/eager/dndev_es.json +13 -0
- package/i18n/locales/eager/dndev_fr.json +13 -0
- package/i18n/locales/eager/dndev_it.json +13 -0
- package/i18n/locales/eager/dndev_ja.json +13 -0
- package/i18n/locales/eager/dndev_ko.json +13 -0
- package/i18n/locales/eager/dndev_nl.json +13 -0
- package/i18n/locales/eager/dndev_pl.json +645 -0
- package/i18n/locales/eager/dndev_pt.json +13 -0
- package/i18n/locales/eager/dndev_zh.json +13 -0
- package/i18n/locales/lazy/auth_ar.json +5 -2
- package/i18n/locales/lazy/auth_da.json +5 -2
- package/i18n/locales/lazy/auth_de.json +5 -2
- package/i18n/locales/lazy/auth_en.json +5 -2
- package/i18n/locales/lazy/auth_es.json +5 -2
- package/i18n/locales/lazy/auth_fr.json +5 -2
- package/i18n/locales/lazy/auth_it.json +5 -2
- package/i18n/locales/lazy/auth_ja.json +5 -2
- package/i18n/locales/lazy/auth_ko.json +5 -2
- package/i18n/locales/lazy/auth_nl.json +5 -2
- package/i18n/locales/lazy/auth_pl.json +195 -0
- package/i18n/locales/lazy/auth_pt.json +5 -2
- package/i18n/locales/lazy/auth_zh.json +5 -2
- package/i18n/locales/lazy/billing_pl.json +93 -0
- package/i18n/locales/lazy/blog_pl.json +9 -0
- package/i18n/locales/lazy/cookies_pl.json +35 -0
- package/i18n/locales/lazy/crud_ar.json +89 -3
- package/i18n/locales/lazy/crud_da.json +87 -4
- package/i18n/locales/lazy/crud_de.json +89 -3
- package/i18n/locales/lazy/crud_en.json +86 -4
- package/i18n/locales/lazy/crud_es.json +91 -4
- package/i18n/locales/lazy/crud_fr.json +90 -4
- package/i18n/locales/lazy/crud_it.json +91 -4
- package/i18n/locales/lazy/crud_ja.json +89 -3
- package/i18n/locales/lazy/crud_ko.json +89 -3
- package/i18n/locales/lazy/crud_nl.json +87 -4
- package/i18n/locales/lazy/crud_pl.json +632 -0
- package/i18n/locales/lazy/crud_pt.json +89 -5
- package/i18n/locales/lazy/crud_zh.json +87 -4
- package/i18n/locales/lazy/homeTemplate_pl.json +52 -0
- package/i18n/locales/lazy/legalNotice_de.json +55 -0
- package/i18n/locales/lazy/legalNotice_pl.json +55 -0
- package/i18n/locales/lazy/oauth_pl.json +11 -0
- package/i18n/locales/lazy/privacy_pl.json +178 -0
- package/i18n/locales/lazy/terms_pl.json +200 -0
- package/index.d.ts +5696 -2999
- package/index.js +6 -6
- package/next/index.d.ts +139 -4
- package/next/index.js +545 -163
- package/next/runtime.js +3 -0
- package/package.json +5 -3
- package/server.d.ts +5322 -2855
- package/server.js +1 -1
- package/symbol-index.json +1 -1
- package/vite/index.d.ts +10 -0
- package/vite/index.js +69 -68
package/next/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import*as w from"node:fs";import"node:fs";import{createRequire as xs}from"node:module";import{resolve as me,join as Z,dirname as Q,relative as ct,normalize as ks,sep as pt,extname as _s}from"node:path";import{fileURLToPath as As}from"node:url";import Es from"fast-glob";var he={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var De={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},U={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},D={next:{middleware:"middleware.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},oe="/og-image.png",Oe={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},de={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Pe={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},z={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${Pe.SOURCE_EAGER}/*_*.json`],lazy:[`${Pe.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},$e={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},it=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var Te={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}};var le={inter:[300,400,600,700],"playfair-display":[400,500,600,700],roboto:[400,700],"space-grotesk":[300,400,500,600,700],"press-start-2p":[400]},Se={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin"],cs:["latin"],sk:["latin"],hr:["latin"],sl:["latin"],hu:["latin"],ro:["latin"],et:["latin"],lv:["latin"],lt:["latin"],mt:["latin"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},Ie=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],at={base:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...z.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...z.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:z.globalIgnore}};function lt(a,e=null){let t=z[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Re(a){return at[a]||at.base}var ce={getGlobOptionsFor:Re||void 0,SCAN_PATTERNS:z||void 0,getPatternsFor:lt||void 0,I18N_PATHS:Pe||void 0},E={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function ut(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var gt={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},$=class a{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,a._instance=this}normalizePath(e){if(!e)return"";try{return ks(e).split(pt).join("/")}catch{return String(e).split(pt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=ct(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(Q(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=xs(Z(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let n=e.replace("@donotdev/",""),l=this.resolveRepoPath(`packages/${n}`);if(this.pathExists(l))return l;if(["auth","billing","crud","oauth"].includes(n)){let i=this.resolveRepoPath(`packages/features/${n}`);if(this.pathExists(i))return i}if(n==="firebase"){let i=this.resolveRepoPath(`packages/providers/${n}`);if(this.pathExists(i))return i}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=me(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=me(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),o=me(s,r);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=w.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:_s(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await w.promises.readFile(e);let n=await w.promises.readFile(e,r),l=this.stripBom(n);return o==="json"?JSON.parse(l):l}catch(n){return this.options.debug&&E.warn(`Failed to read file: ${e}`,n),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return w.readFileSync(e);let n=w.readFileSync(e,r),l=this.stripBom(n);return o==="json"?JSON.parse(l):l}catch(n){return this.options.debug&&E.warn(`Failed to read file: ${e}`,n),null}}async write(e,t,s={}){let{format:r="auto",overwrite:o=!1,dryRun:n=!1,verbose:l=!1}=s,i=this.normalizePath(e),p=this.normalizePath(Q(i)),c=this.pathExists(i);if(c&&!o)return l&&E.info(`Skipping existing file: ${i}`),!1;if(n)return E.info(`[DRY RUN] Would write file: ${i}`),!0;try{await w.promises.mkdir(p,{recursive:!0})}catch(f){if(f?.code!=="EEXIST")throw f}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
|
|
2
|
-
`:g=String(t);try{return await
|
|
3
|
-
`:g=String(t);try{return Buffer.isBuffer(g)?
|
|
4
|
-
`;
|
|
5
|
-
`;n.appendFile(l,b)}},p=(c,u)=>{if(u.length===0)return c;let g=u.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${c} ${g}`};return{debug:(c,...u)=>{e&&(o?i("DEBUG",c,u):I.log.message(V(p(c,u),W.gray)))},verbose:(c,...u)=>{t&&(o?i("VERBOSE",c,u):I.log.message(p(c,u)))},info:(c,...u)=>{o?i("INFO",c,u):I.log.info(V(p(c,u),W.brightCyan))},warn:(c,...u)=>{e&&o?i("WARN",c,u):I.log.warn(V(p(c,u),W.brightYellow))},error:(c,...u)=>{e&&o?i("ERROR",c,u):I.log.error(V(p(c,u),W.brightRed))},success:(c,...u)=>{e&&o?i("SUCCESS",c,u):I.log.success(V(p(c,u),W.brightGreen))},when:(c,u="debug")=>(g,...f)=>{if(c){let h=p(g,f);switch(u){case"verbose":t&&(I.log.message(h),i("VERBOSE",g,f));break;case"info":I.log.info(V(h,W.brightCyan)),i("INFO",g,f);break;case"warn":I.log.warn(V(h,W.brightYellow)),i("WARN",g,f);break;case"error":I.log.error(V(h,W.brightRed)),i("ERROR",g,f);break;case"success":I.log.success(V(h,W.brightGreen)),i("SUCCESS",g,f);break;default:e&&(I.log.message(V(h,W.gray)),i("DEBUG",g,f))}}},getLogFilePath:()=>l}}var G=class a{constructor(e,t={}){if(this.constructor===a)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=N(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),o=await this._processFiles(r);this.cache={...o,timestamp:Date.now()};let n=Date.now()-t;return this.logger.debug(`Discovery completed in ${n}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],o=s.split(".").pop();return{fileName:s,baseName:r,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};function Ns(a){if(!a)return[];let e=$.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",a);if(!s)return[];let r=e.getDirname(e.getDirname(s)),o;try{o=e.readdirSync(r)}catch{return[]}for(let n of o)try{let l=e.resolvePath(`${n}/package.json`,r),i=e.readSync(l,{format:"json"});if(!i?.peerDependenciesMeta)continue;for(let[p,c]of Object.entries(i.peerDependenciesMeta))c?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function Fs(a){if(!a)return[];let e=$.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[o,n]of Object.entries(s.peerDependenciesMeta))n?.optional&&r.add(o);if(s.optionalDependencies)for(let o of Object.keys(s.optionalDependencies))r.add(o);return Array.from(r)}catch{return[]}}function Ds(a){let e=$e.optionalFeatures||[],t=Ns(a),s=Fs(a);return[...new Set([...e,...t,...s])]}function Os(a){let e=$.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function Ts(a,e,t){if(t.resolvePackage(a,e||void 0))return!0;let s=a.startsWith("@")?a.split("/").slice(0,2).join("/"):a.split("/")[0],r=e;for(let o=0;o<10;o++){let n=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(n))return!0;let l=t.getDirname(r);if(l===r)break;r=l}return!1}function xe(a){let e=Ds(a),t=[],s=[],r=$.getInstance(),o=Os(a);for(let n of e)n.startsWith("@donotdev/")?o.has(n)?s.push(n):t.push(n):o.has(n)&&Ts(n,a,r)?s.push(n):t.push(n);return{missing:t,installed:s}}var pe=class a extends G{static LANGUAGE_FLAG_OVERRIDES={en:"gb","en-ca":"ca","es-ar":"ar","fr-be":"be",ar:"sa","ar-ma":"ma","ar-dz":"dz","ar-tn":"tn","ar-ly":"ly","ar-mr":"mr",hi:"in",sl:"si",uk:"ua",ga:"ie",gd:"gb-sct",br:"bzh",co:"fr-cor",am:"et",bn:"bd",gu:"in",kn:"in",ml:"in",mr:"in",ne:"np",pa:"pk",ta:"in",te:"in",ur:"pk",fa:"ir",kk:"kz",ky:"kg",tg:"tj",my:"mm",km:"kh",lo:"la",ka:"ge",hy:"am",be:"by",bs:"ba",sq:"al",ms:"my"};constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[s,r]of Object.entries(e)){for(let o of Object.keys(r))t.includes(o)||delete r[o];Object.keys(r).length===0&&delete e[s]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Re("i18n"),n=r.eager||[],l=r.lazy||[],i=(this.options.additionalPaths||[]).map(y=>{let P=y.endsWith(".json")?y:`${y}/*_*.json`;return this.pathResolver.resolveAppPath(P)});i.length>0&&this.logger.debug(`Additional i18n paths configured: ${i.join(", ")}`);let p=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${n.join(", ")}, lazy: ${l.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${c.join(", ")}`),p.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),f=(y,P)=>{let R=this.pathResolver.normalizePath(y),k=this.pathResolver.normalizePath(P);return R.startsWith(k)?R.slice(k.length+1):R},h=n.map(y=>f(y,t)),d=[...l,...i].map(y=>f(y,t)),m=p.map(y=>f(y,s)),S=c.map(y=>f(y,s)),O={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},T=await this.pathResolver._globWithNormalization(h,O),M=await this.pathResolver._globWithNormalization(d,O),A={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:o.ignore?.filter(y=>y!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(A.ignore)}`);let L=await this.pathResolver._globWithNormalization(m,A),J=await this.pathResolver._globWithNormalization(S,A);this.logger.debug(`Found ${T.length} eager, ${M.length} lazy, ${L.length} framework eager, ${J.length} framework lazy files`),L.length>0?this.logger.debug(`Framework eager files (first 3): ${L.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),J.length>0?this.logger.debug(`Framework lazy files (first 3): ${J.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let ae=[...new Set([...T,...M,...L,...J])],ee=new Set([...T,...L]),v={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:ie}=xe(t),x=new Set(ie.filter(y=>y.startsWith("@donotdev/")).map(y=>y.replace("@donotdev/","")));x.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...x].join(", ")}] (packages not installed)`);let K=new Map,H=[...L,...J];for(let y of H){let P=this._processTranslationFile(y,L.includes(y),t);if(P){if(x.has(P.namespace))continue;let R=`${P.namespace}_${P.language}`;K.set(R,P),v.allNamespaces.add(P.namespace),v.supportedLanguages.add(P.language),L.includes(y)&&v.eagerNamespaces.add(P.namespace)}}let B=new Set;for(let y of ae){if(H.includes(y))continue;let P=this._processTranslationFile(y,ee.has(y),t);if(P){let{namespace:R,language:k,importPath:j,content:se}=P,we=`${P.namespace}_${P.language}`;if(K.has(we)){let Fe=K.get(we);P.content=this._mergeTranslations(Fe.content,se)}v.allNamespaces.add(R),v.supportedLanguages.add(k),B.add(k),ee.has(y)&&v.eagerNamespaces.add(R),v.mapping[R]||(v.mapping[R]={}),v.mapping[R][k]=j,P.content&&(v.content[R]||(v.content[R]={}),v.content[R][k]=P.content),v.files.push({path:y,relativePath:this.pathResolver.getRelativePath(y),namespace:R,language:k,eager:ee.has(y),size:P.content?JSON.stringify(P.content).length:0})}}for(let[y,P]of K){let R=y.lastIndexOf("_"),k=y.slice(0,R),j=y.slice(R+1);B.size>0&&!B.has(j)||(!v.mapping[k]||!v.mapping[k][j])&&(v.mapping[k]||(v.mapping[k]={}),v.mapping[k][j]=P.importPath,v.content[k]||(v.content[k]={}),v.content[k][j]=P.content,v.files.push({path:P.absolutePath,relativePath:this.pathResolver.getRelativePath(P.absolutePath),namespace:k,language:j,eager:v.eagerNamespaces.has(k),size:P.content?JSON.stringify(P.content).length:0}))}let te=B.size>0?[...B].sort():[this.options.fallbackLanguage],X=this._getLanguageAllowlist(),_=te;if(X){let y=te.filter(R=>X.includes(R));_=y.length>0?y:[this.options.fallbackLanguage],this._restrictByLanguage(v.mapping,_),this._restrictByLanguage(v.content,_),v.files=v.files.filter(R=>_.includes(R.language));let P=new Set(Object.keys(v.mapping));v.allNamespaces=new Set([...v.allNamespaces].filter(R=>P.has(R))),v.eagerNamespaces=new Set([...v.eagerNamespaces].filter(R=>P.has(R))),this.logger.debug(`I18n restricted by i18n.only [${X.join(", ")}]: languages [${_.join(", ")}], namespaces ${P.size}`)}let q=[...new Set(_.map(y=>a.LANGUAGE_FLAG_OVERRIDES[y]||y))];return{mapping:v.mapping,content:v.content,eagerNamespaces:[...v.eagerNamespaces].sort(),allNamespaces:[...v.allNamespaces].sort(),supportedLanguages:_,fallbackLanguage:this.options.fallbackLanguage,flagCodes:q,files:v.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[a.LANGUAGE_FLAG_OVERRIDES[this.options.fallbackLanguage]||this.options.fallbackLanguage],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",o,n,l=r.match(/^(.+)_([^_.]+)\.json$/);if(!l)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,o,n]=l,!o||!n)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let p="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:o,language:n,importPath:p,absolutePath:e,content:c}}_mergeTranslations(e,t){let s={...e};for(let[r,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?s[r]=this._mergeTranslations(s[r]||{},o):s[r]=o;return s}};var Is=3,dt="dndev-font-preloads.json";function mt({pathResolver:a,debug:e=!1,languages:t=[]}){let s=N("font-preload-next",e,!1);return{apply(r){r.hooks.afterEmit.tapAsync("DndevFontPreloadManifest",async(o,n)=>{if(o.compiler.isChild()||o.compiler.name?.includes("server"))return n();try{if(!a.getAppRoot())return n();let p=t.length?t:["en"];if(!t.length)try{let m=await new pe(a,{fallbackLanguage:"en"}).discoverTranslations();m?.supportedLanguages?.length&&(p=m.supportedLanguages)}catch{}let u=ht(p).stems,g=o.outputOptions.publicPath&&String(o.outputOptions.publicPath)!=="auto"?o.outputOptions.publicPath.replace(/\/$/,""):"",f=[];for(let[d]of Object.entries(o.assets)){if(!d.endsWith(".woff2"))continue;let m=d.toLowerCase();if(Array.from(u).some(S=>m.includes(S))){let S=g?`${g}/${d}`:`/${d}`;if(f.push({href:S,type:"font/woff2"}),f.length>=Is)break}}let h=a.resolveAppPath("public");if(!a.pathExists(h))try{a.ensureDirSync(h)}catch(d){return s.debug(`Font preload: could not create public dir: ${d?.message}`),n()}let b=a.resolvePath(dt,h);a.writeSync(b,JSON.stringify(f,null,0),{overwrite:!0}),s.debug(`Font preload: wrote ${f.length} entries to ${dt}`)}catch(i){s.debug(`Font preload manifest: ${i?.message}`)}n()})}}}import{createRequire as Ms}from"node:module";var vt=Ms(import.meta.url),Le;function Ls(){return Le===void 0&&(Le=[[vt.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],vt.resolve("@babel/plugin-transform-parameters")]),Le}function bt({logger:a=N("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:o}=s,{RawSource:n}=o;t.hooks.thisCompilation.tap("DndevLowerDestructuring",l=>{l.compiler.isChild()||l.compiler.name?.includes("server")||l.options.mode==="production"&&l.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async i=>{let p,c;try{p=(await import("@babel/core")).default,c=Ls()}catch(g){a.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${g?.message}`);return}let u=0;for(let g of Object.keys(i)){if(!g.endsWith(".js"))continue;let f=l.getAsset(g).source.source(),h=typeof f=="string"?f:f.toString("utf8"),b;try{b=p.transformSync(h,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:c})}catch(d){throw new Error(`[lower-destructuring] failed to transform ${g}: ${d.message}`)}b?.code&&b.code!==h&&(l.updateAsset(g,new n(b.code)),u++)}e&&a.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function yt({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?a({resolve:s}):a,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var wt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function js(a){return(e,t)=>{wt[e]&&(e=wt[e]);let s=a.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),n=a.resolveFrameworkPackage(r,t);if(n){if(o){let i=a.resolvePath(o,n);if(a.pathExists(i))return i;let p=i+".css";if(a.pathExists(p))return p}let l=a.resolvePath("index.css",n);if(a.pathExists(l))return l}}return a.resolvePath(e,t)}}async function zs(){let[a,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=$.getInstance();return yt({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:js(s)})}function Y(a){return a&&typeof a=="object"&&!Array.isArray(a)}var $t={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function St({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],languages:o=[],logger:n,debug:l}){return(i,p)=>{let{dev:c,isServer:u,webpack:g}=p;c&&!u&&(i.infrastructureLogging={level:"error"},i.stats={...i.stats,logging:"error",loggingTrace:!1},i.ignoreWarnings=[...i.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let f=i.module?.rules?.find(h=>h.test?.test?.(".svg"));f&&(f.exclude=/\.svg$/i),i.module=i.module||{},i.module.rules=i.module.rules||[],i.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),i.module.rules.push({test:/\.md$/,type:"asset/source"}),i.resolve=i.resolve||{},i.resolve.alias=i.resolve.alias||{};try{let h=$.getInstance(),b=h.resolveAppPath(D.next.blogContent);i.resolve.alias[De.blog]=Pt.existsSync(b)?b:h.getEmptyCjsModulePath()}catch(h){n.debug(`Blog content alias fallback to empty stub: ${h?.message}`)}i.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...$t},g?.IgnorePlugin&&i.plugins.push(new g.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/}));try{let h=$.getInstance();i.plugins.push(mt({pathResolver:h,debug:l,languages:o}))}catch(h){n.debug(`Font preload webpack plugin skipped: ${h?.message}`)}if(!u)try{i.plugins.push(bt({logger:n,debug:l}))}catch(h){n.debug(`Lower-destructuring webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(n.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),n.info(`\u2705 Including features: ${t.join(", ")}`),i.externals=i.externals||[],Array.isArray(i.externals))i.externals.push(...e);else{let h=i.externals;i.externals=(b,d,m)=>e.includes(d)?m(null,"commonjs "+d):typeof h=="function"?h(b,d,m):m()}if(s.length>0&&g?.NormalModuleReplacementPlugin){let b=$.getInstance().getEmptyCjsModulePath(),d=s.map(S=>S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),m=new RegExp(`^(${d.join("|")})(\\/|$)`);i.plugins.push(new g.NormalModuleReplacementPlugin(m,b)),l&&n.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&g?.NormalModuleReplacementPlugin){let b=$.getInstance().getEmptyFlagModulePath(),d=new Set(r.map(m=>m.toUpperCase()));i.plugins.push(new g.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,m=>{let S=m.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);S&&S[1].toUpperCase()!=="BASE"&&!d.has(S[1].toUpperCase())&&(m.request=b)})),l&&n.debug(`Flag filter: allowing ${d.size} flags, aliasing rest to empty component`)}return a?a(i,p):i}}function Rt({originalRewrites:a,handlers:e,logger:t}){return async function(){try{let s=a?await a():[],o=e.filter(l=>l?.getAPIRewrites).map(l=>l.getAPIRewrites()).reduce((l,i)=>(i?.beforeFiles&&l.beforeFiles.push(...i.beforeFiles),i?.afterFiles&&l.afterFiles.push(...i.afterFiles),i?.fallback&&l.fallback.push(...i.fallback),l),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...o.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function Us(a){let e=a||[],t=new Set(e.map(o=>o?.path).filter(Boolean)),s=[],r=new Set;for(let o of e){let n=String(o?.file||o?.importPath||"").replace(/\\/g,"/");if(n=n.replace(/^\/?(?:src\/)?/,""),!n.startsWith("pages/")||(n=n.slice(6).replace(/\.[jt]sx?$/,""),!n||n.split("/").some(p=>p.startsWith("_")))||n==="api"||n.startsWith("api/"))continue;n=n.replace(/(?:^|\/)index$/,"");let l=n?"/"+n:"/",i=o?.path;!i||l===i||/[[\]]/.test(l)||/[:[]/.test(i)||t.has(l)||r.has(l)||(r.add(l),s.push({from:l,to:i,permanent:!0}))}return s}function xt({originalRedirects:a,seoRedirects:e,routes:t,logger:s}){return async function(){try{let r=a?await a():[],o=Us(t),l=[...e||[],...o].map(({from:u,to:g,permanent:f})=>({source:u,destination:g,permanent:f!==!1})),i=[],p=new Set;for(let u of l){let g=u.source.replace(/\/+$/,"")||"/",f=u.destination.replace(/\/+$/,"")||"/";if(g===f){s.warn(`Redirect loop detected: ${u.source} \u2192 ${u.destination} (skipped)`);continue}if(!u.source.startsWith("/")){s.warn(`Redirect source must start with /: "${u.source}" (skipped)`);continue}if(p.has(g)){s.warn(`Duplicate redirect source: "${u.source}" (skipped)`);continue}p.add(g),i.push(u)}let c=[...Array.isArray(r)?r:[],...i];return c.length===0?[]:(s.info(` \u{1F4CE} ${c.length} redirect${c.length>1?"s":""} configured`),c)}catch(r){return s.error(`Failed to merge redirects: ${r.message}`),[]}}}function kt({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:o,serverShimResult:n,restNextConfig:l,discoveredPackages:i,reactCompiler:p=!1,webpackConfig:c,rewritesConfig:u,redirectsConfig:g,missingOptionalDeps:f,flagCodes:h=[],pathResolver:b,env:d,logger:m}){let S=l?.output==="export",T=l?.distDir||".next";return{transpilePackages:[...i,...f||[]],...p?{reactCompiler:p}:{},...Y(l)?l:(m.warn("restNextConfig is not a plain object:",l),{}),serverExternalPackages:(l?.serverExternalPackages||l?.serverComponentsExternalPackages||[]).filter(A=>!A.startsWith("@donotdev/")&&!f?.includes(A)),turbopack:{...l?.turbopack||{},root:l?.turbopack?.root||b.getRepoRoot(),resolveAlias:{...l?.turbopack?.resolveAlias||{},...$t,[De.blog]:(()=>{try{let A=b.resolveAppPath(D.next.blogContent);if(Pt.existsSync(A))return"./"+D.next.blogContent}catch{}return"@donotdev/core/empty"})(),...f?.length>0?Object.fromEntries(f.flatMap(A=>[[A,"@donotdev/core/empty"],[`${A}/*`,"@donotdev/core/empty"]])):{}}},distDir:T,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...Y(a)?a:(m.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...Y(e)?e:(m.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...Y(t)?t:(m.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...Y(s)?s:(m.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...Y(r)?r:(m.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...Y(o)?o:(m.error(`PWA handler config invalid (got ${typeof o}):`,o),{}),...Y(n)?n:(m.warn("serverShimConfig returned non-object:",n),{}),webpack:c,...S?{}:{rewrites:u,...g?{redirects:g}:{}},env:d,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var ke="fonts",je="dndev-fonts.css",Gs=/@import\s+['"]@fontsource\/([^/]+)\/(\d+)\.css['"]/g,At=/url\(\.\/files\/([^)]+)\)/g;function Bs(a){let e=new Set(["latin"]);for(let t of a){let s=Se[t];if(s)for(let r of s)e.add(r)}return e}function Ws(a,e){let t=a.resolvePath("src/dndev.css",e),s=a.readSync(t,{format:"text"});if(!s)return[];let r=[],o;for(;(o=Gs.exec(s))!==null;)r.push([o[1],o[2]]);return r}function Hs(a,e,t,s,r){let o=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
6
|
-
`],n=new Set
|
|
7
|
-
|
|
8
|
-
`)),
|
|
1
|
+
import*as S from"node:fs";import"node:fs";import{createRequire as Bs}from"node:module";import{resolve as Se,join as oe,dirname as ae,relative as wt,normalize as Hs,sep as St,extname as Ws}from"node:path";import{fileURLToPath as qs}from"node:url";import Vs from"fast-glob";var ye={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var je={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},J={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},Z={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},O={next:{proxy:"src/proxy.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},pe="/og-image.png",Ge={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},be={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Ae={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},V={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${Ae.SOURCE_EAGER}/*_*.json`],lazy:[`${Ae.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},_e={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},mt=["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 ze={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)/}},vt={Inter:"inter","Space Grotesk":"space-grotesk","Playfair Display":"playfair-display","Press Start 2P":"press-start-2p",Roboto:"roboto"},we={inter:[300,400,600,700],"playfair-display":[400,500,600,700],roboto:[400,700],"space-grotesk":[300,400,500,600,700],"press-start-2p":[400]},yt={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin","latin-ext"],cs:["latin","latin-ext"],sk:["latin","latin-ext"],hr:["latin","latin-ext"],sl:["latin","latin-ext"],hu:["latin","latin-ext"],ro:["latin","latin-ext"],et:["latin","latin-ext"],lv:["latin","latin-ext"],lt:["latin","latin-ext"],mt:["latin","latin-ext"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin","latin-ext"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","latin-ext","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},Be=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],dt={base:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...V.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...V.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore}};function bt(a,e=null){let t=V[a];if(!t)throw new Error(`Unknown pattern type: ${a}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function ke(a){return dt[a]||dt.base}var ge={getGlobOptionsFor:ke||void 0,SCAN_PATTERNS:V||void 0,getPatternsFor:bt||void 0,I18N_PATHS:Ae||void 0},I={error:(a,e)=>{},warn:(a,e)=>{},info:a=>{}};function he(a){return typeof a=="object"&&a!==null&&"code"in a&&a.code==="EEXIST"}function $t(a,e){return a().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Rt={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},R=class a{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return a._instance||(a._instance=new a(e)),a._instance}static _reset(){a._instance=null}constructor(e={}){if(a._instance)return a._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,a._instance=this}normalizePath(e){if(!e)return"";try{return Hs(e).split(St).join("/")}catch{return String(e).split(St).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=wt(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(ae(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),n=Bs(oe(s,"package.json")).resolve(e);return this.normalizePath(n)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let o=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${o}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(o)){let l=this.resolveRepoPath(`packages/features/${o}`);if(this.pathExists(l))return l}if(o==="firebase"){let l=this.resolveRepoPath(`packages/providers/${o}`);if(this.pathExists(l))return l}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let n=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(n)?n:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=Se(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Se(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),n=Se(s,r);return this.normalizePath(n)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=S.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:Ws(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return await S.promises.readFile(e);let o=await S.promises.readFile(e,r),i=this.stripBom(o);return n==="json"?JSON.parse(i):i}catch(o){return this.options.debug&&I.warn(`Failed to read file: ${e}`,o),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return S.readFileSync(e);let o=S.readFileSync(e,r),i=this.stripBom(o);return n==="json"?JSON.parse(i):i}catch(o){return this.options.debug&&I.warn(`Failed to read file: ${e}`,o),null}}async write(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:o=!1,verbose:i=!1}=s,l=this.normalizePath(e),c=this.normalizePath(ae(l)),p=this.pathExists(l);if(p&&!n)return i&&I.info(`Skipping existing file: ${l}`),!1;if(o)return I.info(`[DRY RUN] Would write file: ${l}`),!0;try{await S.promises.mkdir(c,{recursive:!0})}catch(h){if(!he(h))throw h}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`:g=String(t);try{return await $t(async()=>(Buffer.isBuffer(g)?await S.promises.writeFile(l,g):await S.promises.writeFile(l,g,"utf8"),i&&I.info(`${p?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:o=!1,verbose:i=!1}=s,l=this.normalizePath(e),c=this.normalizePath(ae(l)),p=this.pathExists(l);if(p&&!n)return i&&I.info(`Skipping existing file: ${l}`),!1;if(o)return I.info(`[DRY RUN] Would write file: ${l}`),!0;try{S.mkdirSync(c,{recursive:!0})}catch(h){if(!he(h))throw h}let u=this._detectFormat(e,r),g;Buffer.isBuffer(t)?g=t:u==="json"&&typeof t=="object"?g=`${JSON.stringify(t,null,2)}
|
|
3
|
+
`:g=String(t);try{return Buffer.isBuffer(g)?S.writeFileSync(l,g):S.writeFileSync(l,g,"utf8"),this._writtenPaths?.add(l),i&&I.info(`${p?"Updated":"Created"} file: ${l}`),!0}catch(h){throw new Error(`Failed to write file: ${l}: ${h instanceof Error?h.message:String(h)}`)}}async copy(e,t,s={}){let{overwrite:r=!1,dryRun:n=!1,verbose:o=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return o&&I.info(`Skipping existing file: ${i}`),!1;if(n)return I.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(ae(i));try{await S.promises.mkdir(c,{recursive:!0})}catch(p){if(!he(p))throw p}try{return await $t(async()=>(await S.promises.copyFile(e,i),o&&I.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:r=!1,dryRun:n=!1,verbose:o=!1}=s,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!r)return o&&I.info(`Skipping existing file: ${i}`),!1;if(n)return I.info(`[DRY RUN] Would copy file: ${i}`),!0;let c=this.normalizePath(ae(i));try{S.mkdirSync(c,{recursive:!0})}catch(p){if(!he(p))throw p}try{return S.copyFileSync(e,i),this._writtenPaths?.add(i),o&&I.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return S.existsSync(e)}catch(s){return t||I.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return S.existsSync(t)||S.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return S.readdirSync(e,t)}catch(s){return this.options.debug&&I.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return S.statSync(e)}catch(t){return this.options.debug&&I.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return S.realpathSync(e)}watch(e,t,s){return S.watch(e,t,s)}lstatSync(e){try{return S.lstatSync(e)}catch(t){return this.options.debug&&I.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await S.promises.mkdir(e,{recursive:!0})}catch(t){if(!he(t))throw t}}ensureDirSync(e){try{S.mkdirSync(e,{recursive:!0})}catch(t){if(!he(t))throw t}}async remove(e){await S.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){S.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return S.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}startWriteRecording(){this._writtenPaths=new Set}stopWriteRecording(){if(!this._writtenPaths)throw new Error("stopWriteRecording() called without startWriteRecording()");let e=this._writtenPaths;return this._writtenPaths=null,e}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=oe(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Se(e)),s=this.getAppRoot(),r=wt(s,t),n=this.normalizePath(r);return!n.startsWith("../")&&!n.startsWith("/")}async findFiles(e,t,s={}){let r=this.normalizePath(oe(e,t)),n=this.getAppRoot(),o=this.normalizePath(n),i=r.startsWith(o)?r.slice(o.length+1):r,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:ge.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ge.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),r=this.resolveFrameworkPackage("@donotdev/core");if(!r)return null;let n=this.normalizePath(oe(r,t.PUBLISHED_ROOT,s)),o=n.replace(/\/[^/]*\*.*$/,"");return this.pathExists(o),n}async _globWithNormalization(e,t){return(await Vs(e,t)).map(r=>{let n=typeof r=="string"?r:r.path;return this.normalizePath(n)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let p of s)if(typeof p!="string"||p.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let r=this.getAppRoot(),n=ge.getGlobOptionsFor?ge.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},o=this.normalizePath(r),i=e.framework.map(p=>{let u=this.normalizePath(p);return u.startsWith(o)?u.slice(o.length+1):u}),l=e.consumer.map(p=>{let u=this.normalizePath(p);return u.startsWith(o)?u.slice(o.length+1):u}),c={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r};try{let p=i.length>0?await this._globWithNormalization(i,c):[],u=await this._globWithNormalization(l,c);return{frameworkFiles:p,consumerFiles:u}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ge.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=ge.getPatternsFor(e),n=this.isMonorepo();if(e==="i18n"){let l=r,c={eager:l.eager.map(p=>p.startsWith("!")?"!"+this.resolveAppPath(p.slice(1)):this.resolveAppPath(p)),lazy:l.lazy.map(p=>p.startsWith("!")?"!"+this.resolveAppPath(p.slice(1)):this.resolveAppPath(p)),framework:{eager:n?(l.framework?.eager||[]).map(p=>this.resolveRepoPath(p)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(p=>this._resolveFrameworkI18nPattern(p))).then(p=>p.filter(Boolean)),lazy:n?(l.framework?.lazy||[]).map(p=>this.resolveRepoPath(p)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(p=>this._resolveFrameworkI18nPattern(p))).then(p=>p.filter(Boolean))},all:[]};return c.all=[...c.eager,...c.lazy,...c.framework.eager,...c.framework.lazy],c}let o=r,i={framework:n?(o.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(o.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyFlagModulePath(){let e=ae(qs(import.meta.url));return this.normalizePath(Se(e,"emptyFlag.js"))}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),s=0,r=this.options.maxLevels;for(;s<r;){let n=this.normalizePath(oe(t,Rt.TOOLING)),o=this.normalizePath(oe(t,Rt.CORE));if(this.pathExists(n)&&this.pathExists(o))return t;let i=oe(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(oe(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(ae(t))===t)return t;let c=this.normalizePath(ae(t));if(c===t)break;t=c,s++}return this.normalizePath(e)}};function Pt({logger:a,debug:e=!1}={}){let t=R.getInstance(),s=!1,r=null;if(process.env.DNDEV_APP_ROOT?(r=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(r)?(t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root set from DNDEV_APP_ROOT: ${r}`)):a&&a.warn(`DNDEV_APP_ROOT path does not exist: ${r}`)):e&&a&&a.debug("DNDEV_APP_ROOT env var not set"),!s){if(t.getRepoRoot()){let o=t.resolveRepoPath("apps");if(t.pathExists(o))try{let i=process.cwd(),l=t.normalizePath(i);if(l.includes("/apps/")){let c=l.indexOf("/apps/"),u=l.substring(c+6).split("/")[0];if(u){let g=t.resolveRepoPath(`apps/${u}`),h=t.resolveRepoPath(`apps/${u}/next.config.js`);t.pathExists(h)&&(r=g,t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root detected from process.cwd(): ${r}`))}}}catch{}}!s&&!r&&(r=process.cwd(),t.setAppRoot(r),s=!0,e&&a&&a.debug(`App root fallback to process.cwd(): ${r}`))}return{appRoot:r,appRootSet:s}}import Dt from"node:fs";import{createRequire as Xs}from"node:module";import*as B from"@clack/prompts";var Y={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 Js(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function Q(a,e){return Js()?`${e}${a}${Y.reset}`:a}function G(a,e,t,s={}){let{logDir:r=".dndev-logs",fileLogging:n=!1}=s,o=R.getInstance(),i=null;if(n){let p=o.resolveAppPath(r);o.pathExists(p)||o.mkdir(p),i=o.resolveAppPath(`${r}/${a.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let u=`=== ${a} Log Started at ${new Date().toISOString()} ===
|
|
4
|
+
`;o.writeSync(i,u)}let l=(p,u,g)=>{if(i){let h=new Date().toISOString(),f=g.length>0?" "+g.map(y=>typeof y=="object"?JSON.stringify(y,null,2):String(y)).join(" "):"",w=`${h} [${p}] ${u}${f}
|
|
5
|
+
`;o.appendFile(i,w)}},c=(p,u)=>{if(u.length===0)return p;let g=u.map(h=>typeof h=="object"?JSON.stringify(h,null,2):String(h)).join(" ");return`${p} ${g}`};return{debug:(p,...u)=>{e&&(n?l("DEBUG",p,u):B.log.message(Q(c(p,u),Y.gray)))},verbose:(p,...u)=>{t&&(n?l("VERBOSE",p,u):B.log.message(c(p,u)))},info:(p,...u)=>{n?l("INFO",p,u):B.log.info(Q(c(p,u),Y.brightCyan))},warn:(p,...u)=>{e&&n?l("WARN",p,u):B.log.warn(Q(c(p,u),Y.brightYellow))},error:(p,...u)=>{e&&n?l("ERROR",p,u):B.log.error(Q(c(p,u),Y.brightRed))},success:(p,...u)=>{e&&n?l("SUCCESS",p,u):B.log.success(Q(c(p,u),Y.brightGreen))},when:(p,u="debug")=>(g,...h)=>{if(p){let f=c(g,h);switch(u){case"verbose":t&&(B.log.message(f),l("VERBOSE",g,h));break;case"info":B.log.info(Q(f,Y.brightCyan)),l("INFO",g,h);break;case"warn":B.log.warn(Q(f,Y.brightYellow)),l("WARN",g,h);break;case"error":B.log.error(Q(f,Y.brightRed)),l("ERROR",g,h);break;case"success":B.log.success(Q(f,Y.brightGreen)),l("SUCCESS",g,h);break;default:e&&(B.log.message(Q(f,Y.gray)),l("DEBUG",g,h))}}},getLogFilePath:()=>i}}var xt=Xs(import.meta.url),He;function Ks(){return He===void 0&&(He=[[xt.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],xt.resolve("@babel/plugin-transform-parameters")]),He}function Et({logger:a=G("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:n}=s,{RawSource:o}=n;t.hooks.thisCompilation.tap("DndevLowerDestructuring",i=>{i.compiler.isChild()||i.compiler.name?.includes("server")||i.options.mode==="production"&&i.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async l=>{let c,p;try{c=(await import("@babel/core")).default,p=Ks()}catch(g){a.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${g?.message}`);return}let u=0;for(let g of Object.keys(l)){if(!g.endsWith(".js"))continue;let h=i.getAsset(g).source.source(),f=typeof h=="string"?h:h.toString("utf8"),w;try{w=c.transformSync(f,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:p})}catch(y){throw new Error(`[lower-destructuring] failed to transform ${g}: ${y.message}`)}w?.code&&w.code!==f&&(i.updateAsset(g,new o(w.code)),u++)}e&&a.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function At({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?a({resolve:s}):a,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var _t={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Ys(a){return(e,t)=>{_t[e]&&(e=_t[e]);let s=a.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],n=e.split("/").slice(2).join("/"),o=a.resolveFrameworkPackage(r,t);if(o){if(n){let l=a.resolvePath(n,o);if(a.pathExists(l))return l;let c=l+".css";if(a.pathExists(c))return c}let i=a.resolvePath("index.css",o);if(a.pathExists(i))return i}}return a.resolvePath(e,t)}}async function Zs(){let[a,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=R.getInstance();return At({postcssImport:a,postcssNesting:e,autoprefixer:t,resolve:Ys(s)})}import{renameSync as Qs}from"node:fs";import{basename as kt,dirname as er,join as qe,relative as tr}from"node:path";var ie="next",sr=["tsx","ts","jsx","js"],Nt=sr.map(a=>`${ie}.${a}`);function F(a,e){return`${a}.${ie}.${e}`}var rr=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],nr=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],or=["proxy","middleware","instrumentation"],ar="// Generated by @donotdev/config";function We(a,e){let t=a.match(new RegExp(`^(.+?)(\\.${ie})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,s,r,n]=t;return e.includes(s)?{name:s,extension:n,marked:!!r}:null}function ir(a){let e=[],t=a.resolveAppPath("src/app"),s=r=>{for(let n of a.readdirSync(r,{withFileTypes:!0})){let o=qe(r,n.name);if(n.isDirectory()){s(o);continue}if(!n.isFile())continue;let i=We(n.name,rr);i&&e.push({file:o,...i,metadata:!1});let l=We(n.name,nr);l&&e.push({file:o,...l,metadata:!0})}};a.pathExists(t)&&s(t);for(let r of[a.resolveAppPath("src"),a.getAppRoot()])if(a.pathExists(r))for(let n of a.readdirSync(r,{withFileTypes:!0})){let o=n.isFile()&&We(n.name,or);o&&e.push({file:qe(r,n.name),...o,metadata:!1})}return e}function Ct({pathResolver:a,logger:e,isCI:t}){let s=a.getAppRoot(),r=c=>tr(s,c),n=[],o=[],i=[],l=[];for(let c of ir(a)){let p=a.readSync(c.file,{format:"text"})||"";if(!c.marked&&p.startsWith(ar)){a.removeSync(c.file),o.push(r(c.file));continue}c.metadata?l.push(r(c.file)):c.marked||i.push(c)}if(l.length>0)throw new Error(`[dndev] Next ignores code metadata files with the framework's file marker: ${l.join(", ")}. Serve each as a route handler (e.g. src/app/robots.txt/${F("route","ts")}) or a static file (icon.png, opengraph-image.png). The sitemap and llms.txt are generated by the framework.`);if(t&&i.length>0)throw new Error(`[dndev] Next files must carry the .${ie}. marker (src/pages is never a Next route). Rename: `+i.map(({file:c,name:p,extension:u})=>`${r(c)} \u2192 ${F(p,u)}`).join(", ")+". Running the app once in development renames them.");for(let{file:c,name:p,extension:u}of i){let g=qe(er(c),F(p,u));if(a.pathExists(g))throw new Error(`[dndev] Both ${r(c)} and ${r(g)} exist. Next only reads *.${ie}.* files: merge ${kt(c)} into ${kt(g)} and delete it.`);Qs(c,g),n.push(r(c))}return n.length>0&&e.warn(`Next files renamed to *.${ie}.* (src/pages is never a Next route): ${n.join(", ")}. Commit the renames.`),o.length>0&&e.debug(`Removed generated Next files without marker: ${o.join(", ")}`),{renamed:n,removed:o}}function se(a){return a&&typeof a=="object"&&!Array.isArray(a)}var Tt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Ft({originalWebpack:a,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],logger:n,debug:o}){return(i,l)=>{let{dev:c,isServer:p,webpack:u}=l;c&&!p&&(i.infrastructureLogging={level:"error"},i.stats={...i.stats,logging:"error",loggingTrace:!1},i.ignoreWarnings=[...i.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let g=i.module?.rules?.find(h=>h.test?.test?.(".svg"));g&&(g.exclude=/\.svg$/i),i.module=i.module||{},i.module.rules=i.module.rules||[],i.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),i.module.rules.push({test:/\.md$/,type:"asset/source"}),i.resolve=i.resolve||{},i.resolve.alias=i.resolve.alias||{};try{let h=R.getInstance(),f=h.resolveAppPath(O.next.blogContent);i.resolve.alias[je.blog]=Dt.existsSync(f)?f:h.getEmptyCjsModulePath()}catch(h){n.debug(`Blog content alias fallback to empty stub: ${h?.message}`)}if(i.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...Tt},u?.IgnorePlugin&&i.plugins.push(new u.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/})),!p)try{i.plugins.push(Et({logger:n,debug:o}))}catch(h){n.debug(`Lower-destructuring webpack plugin skipped: ${h?.message}`)}if(e.length>0)if(n.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),n.info(`\u2705 Including features: ${t.join(", ")}`),i.externals=i.externals||[],Array.isArray(i.externals))i.externals.push(...e);else{let h=i.externals;i.externals=(f,w,y)=>e.includes(w)?y(null,"commonjs "+w):typeof h=="function"?h(f,w,y):y()}if(s.length>0&&u?.NormalModuleReplacementPlugin){let f=R.getInstance().getEmptyCjsModulePath(),w=s.map(v=>v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),y=new RegExp(`^(${w.join("|")})(\\/|$)`);i.plugins.push(new u.NormalModuleReplacementPlugin(y,f)),o&&n.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&u?.NormalModuleReplacementPlugin){let f=R.getInstance().getEmptyFlagModulePath(),w=new Set(r.map(y=>y.toUpperCase()));i.plugins.push(new u.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,y=>{let v=y.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);v&&v[1].toUpperCase()!=="BASE"&&!w.has(v[1].toUpperCase())&&(y.request=f)})),o&&n.debug(`Flag filter: allowing ${w.size} flags, aliasing rest to empty component`)}return a?a(i,l):i}}function Ot({originalRewrites:a,handlers:e,logger:t}){return async function(){try{let s=a?await a():[],n=e.filter(i=>i?.getAPIRewrites).map(i=>i.getAPIRewrites()).reduce((i,l)=>(l?.beforeFiles&&i.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&i.afterFiles.push(...l.afterFiles),l?.fallback&&i.fallback.push(...l.fallback),i),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...n.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...n.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...n.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function It({originalRedirects:a,seoRedirects:e,logger:t}){return async function(){try{let s=a?await a():[],r=(e||[]).map(({from:l,to:c,permanent:p})=>({source:l,destination:c,permanent:p!==!1})),n=[],o=new Set;for(let l of r){let c=l.source.replace(/\/+$/,"")||"/",p=l.destination.replace(/\/+$/,"")||"/";if(c===p){t.warn(`Redirect loop detected: ${l.source} \u2192 ${l.destination} (skipped)`);continue}if(!l.source.startsWith("/")){t.warn(`Redirect source must start with /: "${l.source}" (skipped)`);continue}if(o.has(c)){t.warn(`Duplicate redirect source: "${l.source}" (skipped)`);continue}o.add(c),n.push(l)}let i=[...Array.isArray(s)?s:[],...n];return i.length===0?[]:(t.info(` \u{1F4CE} ${i.length} redirect${i.length>1?"s":""} configured`),i)}catch(s){return t.error(`Failed to merge redirects: ${s.message}`),[]}}}function Lt({routeResult:a,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:n,serverShimResult:o,restNextConfig:i,discoveredPackages:l,reactCompiler:c=!1,routingMode:p,webpackConfig:u,rewritesConfig:g,redirectsConfig:h,missingOptionalDeps:f,flagCodes:w=[],pathResolver:y,env:v,logger:P}){let b=i?.output==="export";if(p==="app"&&i?.pageExtensions)throw new Error("[dndev] pageExtensions is set by the framework (Next files carry the .next. marker so src/pages is never a route). Remove it from next.config.");let T=i?.distDir||".next";return{transpilePackages:[...l,...f||[]],...c?{reactCompiler:c}:{},...se(i)?i:(P.warn("restNextConfig is not a plain object:",i),{}),...p==="app"&&{pageExtensions:Nt},...p==="app"&&{experimental:{...i?.experimental,globalNotFound:!0}},serverExternalPackages:(i?.serverExternalPackages||i?.serverComponentsExternalPackages||[]).filter(_=>!_.startsWith("@donotdev/")&&!f?.includes(_)),turbopack:{...i?.turbopack||{},root:i?.turbopack?.root||y.getRepoRoot(),resolveAlias:{...i?.turbopack?.resolveAlias||{},...Tt,[je.blog]:(()=>{try{let _=y.resolveAppPath(O.next.blogContent);if(Dt.existsSync(_))return"./"+O.next.blogContent}catch{}return"@donotdev/core/empty"})(),...f?.length>0?Object.fromEntries(f.flatMap(_=>[[_,"@donotdev/core/empty"],[`${_}/*`,"@donotdev/core/empty"]])):{}}},distDir:T,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...se(a)?a:(P.error(`Route handler config invalid (got ${typeof a}):`,a),{}),...se(e)?e:(P.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...se(t)?t:(P.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...se(s)?s:(P.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...se(r)?r:(P.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...se(n)?n:(P.error(`PWA handler config invalid (got ${typeof n}):`,n),{}),...se(o)?o:(P.warn("serverShimConfig returned non-object:",o),{}),webpack:u,...b?{}:{rewrites:g,...h?{redirects:h}:{}},env:v,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}var lr=["--font-family","--font-headline","--font-mono"],fe=":root",cr=/\/\*[\s\S]*?\*\//g,pr=/([^{}]+)\{([^{}]*)\}/g,ur=/^(?::root|html|:where\(:root\))$/,gr=/^(?::root|html)?\.([a-z][\w-]*)$/i,hr=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/;function Mt(a){let e=[],t=0,s="",r=0;for(let n=0;n<a.length;n++){let o=a[n];s?o===s&&(s=""):o==='"'||o==="'"?s=o:o==="("?t++:o===")"?t--:o===","&&t===0&&(e.push(a.slice(r,n)),r=n+1)}return e.push(a.slice(r)),e.map(n=>n.trim())}function fr(a){if(ur.test(a))return fe;let e=gr.exec(a);return e?e[1]:null}function Ut(a){let e=new Map,t=a.replace(cr,"");for(let[,s,r]of t.matchAll(pr)){let n=s.split(";").pop(),o=Mt(n).map(fr).filter(i=>i!==null);if(o.length!==0)for(let i of r.split(";")){let l=i.indexOf(":");if(l===-1)continue;let c=i.slice(0,l).trim();if(!c.startsWith("--"))continue;let p=i.slice(l+1).replace(/!important\s*$/,"").trim();for(let u of o)e.has(u)||e.set(u,new Map),e.get(u).set(c,p)}}return e}function Ve(a,e,t){let s=Mt(a)[0];if(!s)return null;let r=hr.exec(s);if(r){let[,n,o]=r;return e.has(n)&&!t.has(n)?Ve(e.get(n),e,new Set([...t,n])):o===void 0?null:Ve(o,e,t)}return s.replace(/^['"]|['"]$/g,"").trim()}function jt({frameworkCss:a,appCss:e}){let t=Ut(a),s=Ut(e.join(`
|
|
6
|
+
`)),r=new Set([fe,...t.keys(),...s.keys()]),n=new Set;for(let o of r){let i=new Map([...t.get(fe)??[],...s.get(fe)??[],...o===fe?[]:t.get(o)??[],...o===fe?[]:s.get(o)??[]]);for(let l of lr){if(!i.has(l))continue;let c=Ve(i.get(l),i,new Set([l]));c&&n.add(c)}}return[...n]}var dr=new Map(Object.entries(vt).map(([a,e])=>[a.toLowerCase(),e]));function Gt({families:a,locales:e=[]}){if(!Array.isArray(a))throw new Error("resolveFontManifest: families is required (ThemeDiscovery fontFamilies)");let t=new Set;for(let n of a){let o=dr.get(n.toLowerCase());o&&t.add(o)}let s=new Set(["latin"]);for(let n of e)for(let o of yt[n]??[])s.add(o);let r=new Set;for(let n of t)for(let o of s)for(let i of we[n])r.add(`${n}-${o}-${i}-normal`);return{fontStems:t,subsets:s,stems:r}}function zt(a){let e=a.split(/[/\\]/).pop().toLowerCase();for(let t of Object.keys(we)){if(!e.startsWith(`${t}-`))continue;let s=new RegExp(`^${t}-[a-z-]+?-\\d+-(?:normal|italic)`).exec(e);if(s)return s[0]}return null}function Bt(a){return a.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}var Je="fonts",Xe="dndev-fonts.css",mr=/@font-face\s*\{[^}]*\}/g,vr=/url\(\.\/files\/([^)]+)\)/g,yr=/url\(\.\/files\/([^)]+)\)/;function Ht({families:a,languages:e,debug:t=!1,force:s=!1}){let r=G("font-copy",t,!1),n=R.getInstance(),o=Gt({families:a,locales:e});if(o.fontStems.size===0){r.debug(`No framework font used by the theme (families: ${a.join(", ")||"none"})`);return}let i=n.resolveAppPath(`public/${Xe}`);if(!s&&n.pathExists(i)){r.debug("dndev-fonts.css already exists, skipping font copy");return}let l=n.resolveFrameworkPackage("@donotdev/ui");if(!l)throw new Error("Font copy: @donotdev/ui not found");let c=n.resolveAppPath(`public/${Je}`);n.ensureDirSync(c);let p=[`/* Auto-generated by @donotdev/core \u2014 do not edit */
|
|
7
|
+
`],u=new Set;for(let g of o.fontStems)for(let h of we[g]){let f=`@fontsource/${g}/${h}.css`,w=n.resolvePackage(f,l);if(!w)throw new Error(`Font copy: cannot resolve ${f}`);let y=n.readSync(w,{format:"text"}),v=n.resolvePath("files",n.getDirname(w));for(let P of y.match(mr)??[]){let b=zt(yr.exec(P)?.[1]??"");if(!b||!o.stems.has(b))continue;let x=Bt(P).replace(vr,(T,C)=>{let _=n.resolvePath(C,v);if(!n.pathExists(_))throw new Error(`Font copy: font file missing: ${_}`);return u.has(C)||(n.copySync(_,n.resolvePath(C,c),{overwrite:!0}),u.add(C)),`url(/${Je}/${C})`});p.push(x)}}n.writeSync(i,p.join(`
|
|
8
|
+
`)),r.debug(`Font copy: wrote ${Xe} (${u.size} font files: ${[...o.fontStems].join(", ")})`)}function Wt(){let a=R.getInstance(),e=a.resolveAppPath(`public/${Xe}`),t=a.resolveAppPath(`public/${Je}`);if(a.pathExists(e))try{a.removeSync(e)}catch{}if(a.pathExists(t))try{a.removeSync(t)}catch{}}var br=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json","public/dndev-fonts.css","public/robots.txt","public/sitemap.xml","public/rss.xml","public/llms.txt","public/llms-full.txt"],wr="dndev-config-",qt=".dndev-build";function Ke(a){if(!a)return!1;let e=R.getInstance(),t=e.resolveAppPath(qt),s=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===s}catch{return!1}}function Sr(a){if(!a)return;let e=R.getInstance(),t=e.resolveAppPath(qt),s=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,s,{overwrite:!0})}catch{}}function $r(a,e,t){if(!a)return;let s=R.getInstance(),r=(o,i)=>{let l=s.normalizePath(o);if(!(t.has(l)||!s.pathExists(l)))try{s.removeSync(o),e.debug(`Removed stale: ${i}`)}catch{}};for(let o of br)r(s.resolveAppPath(o),o);let n=s.resolveAppPath("src/config");for(let o of s.readdirSync(n))o.startsWith(wr)&&o.endsWith(".js")&&r(s.resolvePath(o,n),`src/config/${o}`)}async function Vt({routeHandler:a,themeHandler:e,i18nHandler:t,assetHandler:s,seoHandler:r,pwaHandler:n,blogContentHandler:o},i){let l=a?.pathResolver;if(!l)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let c=l.getAppRoot(),p=l.getRepoRoot();if(!c||c===p){i.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(w=>setTimeout(w,0));let f=l.getAppRoot();if(!f||f===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Ke(c)){i.debug("Discoveries already completed this build, skipping");return}Sr(c);let u=Date.now();l.startWriteRecording();let g;try{Wt();let f=await t.getDiscoveryData(),w={languages:f.supportedLanguages,defaultLanguage:f.fallbackLanguage};if(r.useLanguages(w),r.useTranslations(f.content),a)try{a.useLanguages(w),i.info("\u{1F50D} Starting route discovery...");let P=(await a.generateFiles())?.routes?.length||0;i.info(`\u2705 Routes generated: ${P} routes found`),P===0&&i.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(v){throw i.error(`\u274C Route generation failed: ${v.message}`),v.stack&&i.error(`Stack: ${v.stack}`),v}else i.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");let y=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:s},{name:"SEO",handler:r},{name:"PWA",handler:n},{name:"BlogContent",handler:o}];for(let{name:v,handler:P}of y)try{await P.generateFiles()}catch(b){i.debug(`${v} generation failed: ${b.message}`)}try{Rr(l,i)}catch(v){i.debug(`Env config generation failed (non-critical): ${v.message}`)}if(e){let{fontFamilies:v}=await e.getDiscoveryData();Ht({families:v,languages:f.supportedLanguages})}}finally{g=l.stopWriteRecording()}$r(c,i,g);let h=Date.now()-u;i.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`)}function Rr(a,e){let t={};for(let[o,i]of Object.entries(process.env))o.startsWith("NEXT_PUBLIC_")&&i!==void 0&&(t[o]=i);let s=`// Auto-generated DnDev env config by @donotdev/config
|
|
9
9
|
// Generated at: ${new Date().toISOString()}
|
|
10
10
|
// Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
|
|
11
11
|
|
|
@@ -22,12 +22,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
22
22
|
timestamp: Date.now(),
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
-
globalThis._DNDEV_CONFIG_.${
|
|
25
|
+
globalThis._DNDEV_CONFIG_.${J.env} = envConfig;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
// Export for compatibility
|
|
29
29
|
export default envConfig;
|
|
30
|
-
`,r=a.resolveAppPath(
|
|
30
|
+
`,r=a.resolveAppPath(O.next.configEnv);a.writeSync(r,s,{overwrite:!0});let n=Object.keys(t).length;e.debug(`Generated env config: ${n} NEXT_PUBLIC_* vars`)}async function Jt(a,e,t){if(t)return!1;try{let s=await a.getDiscoveryData();return s?.copiedAssets?.length>0&&e.info(`\u{1F4E6} Copied ${s.copiedAssets.length} assets from framework`),!0}catch(s){return e.debug(`Asset discovery failed (non-critical): ${s.message}`),!1}}var Xt={debug:!1,verbose:process.env.CI!=="true",seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1,aiCrawlers:"recommended",llmsTxt:!0,speculationRules:!0,hreflang:!0,breadcrumbSchema:!0,websiteSchema:!0,organizationSchema:!0},serverShim:{enabled:!0},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},features:{}};var $e={...Xt,generateManifest:!0,reactCompiler:!1,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function Kt(a,e){let t={...a};return e&&Object.keys(e).forEach(s=>{e[s]&&typeof e[s]=="object"&&!Array.isArray(e[s])?t[s]=Kt(a[s]||{},e[s]):t[s]=e[s]}),t}function Yt(a={}){return Kt($e,a)}function Zt(a){let{features:e={},routes:t={},themes:s={},i18n:r={},assets:n={},pwa:o={},seo:i={},serverShim:l={},discovery:c={},generateManifest:p,debug:u,verbose:g,...h}=a,f=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:p,debug:u,verbose:g,mode:f,isDev:f==="development",routeOptions:t,themeOptions:s,i18nOptions:r,assetOptions:n,featureOptions:e,pwaOptions:o,seoOptions:i,serverShimOptions:l,discoveryOptions:c,nextConfigOptions:h}}var M=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=G(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=R.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}revalidate(){let e=this.options.revalidate??Z.revalidateSeconds;if(e===!1||Number.isInteger(e)&&e>0)return e;throw new Error(`appConfig.revalidate must be a whole number of seconds above 0, or false (kept until the next deploy). Got ${JSON.stringify(e)}.`)}revalidateLabel(){let e=this.revalidate();return e===!1?"kept until the next deploy":`re-rendered at most every ${e}s`}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...$e.discovery,...this.options};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}createNextConfig(){return(e={})=>(this.options.debug&&this.logger.debug(`${this.getHandlerName()} handler initialized`),{...e,webpack:(t,s)=>{let{dev:r,isServer:n,webpack:o}=s;return this.applyViteIgnorePlugin(t,o),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=O.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=J[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
31
31
|
// Generated at: ${new Date().toISOString()}
|
|
32
32
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
33
33
|
|
|
@@ -49,7 +49,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
49
49
|
|
|
50
50
|
// Export for compatibility
|
|
51
51
|
export default ${t}Config;
|
|
52
|
-
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t,{overwrite:!0}),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var ne={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},_e=class extends G{constructor(e,t={}){super(e,{assets:z.assets.fallback,assetPatterns:z.assets.patterns,frameworkPackage:Oe.package,assetsPath:Oe.assetsPath,modernFormats:z.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let n=[],l=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(l)&&this.options.generateAssets!==!1&&(n=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:i}=e,p=await this._processAssetFiles(i),c=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...c,logoSvgContent:u},copiedAssets:s,generatedAssets:n,pwaIcons:this._extractPWAIcons(p)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(o=>o.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",o=r.match(/(\d+)x(\d+)/),n=o?{width:parseInt(o[1]),height:parseInt(o[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:n,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(o=>o.path),r=t||this.options.modernFormats;for(let o of r){let n=`/${e}.${o}`;if(s.includes(n))return n}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(de.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let o of this.options.assets)await this._ensureAsset(o,r,s)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${de.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let o=s.split("/").pop()||s.split("\\").pop(),n=this._analyzeAsset(o,r.size);n&&t.push(n)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(n=>this._matchesPattern(e,n))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let o=`/${e}.${r}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${de.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(de.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let o=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,o)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _renderOgImage(e,t){let{width:s,height:r}=await e(t).metadata(),o=Math.min(ne.logoWidth/s,ne.logoHeight/r),n=await e(t,{density:Math.ceil(72*o)}).resize(ne.logoWidth,ne.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:ne.width,height:ne.height,channels:4,background:ne.background}}).composite([{input:n}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],n=[],l=[];try{let i=await this.pathResolver.read(t,{format:"text"});if(!i)return{generated:[],skipped:[...o,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){l.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,i),n.push(c.name)}catch(g){this.logger.debug(`Failed to copy ${c.name}: ${g.message}`),l.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),l.push(...r.map(c=>c.name));else{for(let u of r){let g=`${s}/${u.name}`;if(this.pathResolver.pathExists(g)){l.push(u.name);continue}try{let f=p.default(t).resize(u.size,u.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;u.format==="ico"?h=await f.toFormat("png").toBuffer():h=await f.toFormat(u.format).toBuffer(),await this.pathResolver.write(`public/${u.name}`,h),n.push(u.name)}catch(f){this.logger.debug(`Failed to generate ${u.name}: ${f.message}`),l.push(u.name)}}let c=oe.slice(1);if(this.pathResolver.pathExists(`${s}/${c}`))l.push(c);else try{let u=await this._renderOgImage(p.default,t);await this.pathResolver.write(`public/${c}`,u),n.push(c)}catch(u){this.logger.debug(`Failed to generate ${c}: ${u.message}`),l.push(c)}}return{generated:n,skipped:l,error:null}}catch(i){return this.logger.debug(`Asset generation failed: ${i.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:i.message}}}};var Ge={data:null},Ue=class extends F{constructor(e={}){super(_e,e)}getHandlerDefaults(){return{manifestPath:D.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
52
|
+
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t,{overwrite:!0}),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var X=class a{constructor(e,t={}){if(this.constructor===a)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=G(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),n=await this._processFiles(r);this.cache={...n,timestamp:Date.now()};let o=Date.now()-t;return this.logger.debug(`Discovery completed in ${o}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],n=s.split(".").pop();return{fileName:s,baseName:r,extension:n,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var ue={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Ne=class extends X{constructor(e,t={}){super(e,{assets:V.assets.fallback,assetPatterns:V.assets.patterns,frameworkPackage:Ge.package,assetsPath:Ge.assetsPath,modernFormats:V.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 o=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(o=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,c=await this._processAssetFiles(l),p=this._buildAssetManifest(c),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:c,manifest:{...p,logoSvgContent:u},copiedAssets:s,generatedAssets:o,pwaIcons:this._extractPWAIcons(c)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(n=>n.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",n=r.match(/(\d+)x(\d+)/),o=n?{width:parseInt(n[1]),height:parseInt(n[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:o,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(n=>n.path),r=t||this.options.modernFormats;for(let n of r){let o=`/${e}.${n}`;if(s.includes(o))return o}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(be.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let n of this.options.assets)await this._ensureAsset(n,r,s)&&t.push(n);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${be.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let n=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(n)){if(await this.pathResolver.copy(n,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let n=s.split("/").pop()||s.split("\\").pop(),o=this._analyzeAsset(n,r.size);o&&t.push(o)}}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(o=>this._matchesPattern(e,o))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let n=`/${e}.${r}`;if(t.includes(n))return n}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${be.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(be.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let n=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,n)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _renderOgImage(e,t){let{width:s,height:r}=await e(t).metadata(),n=Math.min(ue.logoWidth/s,ue.logoHeight/r),o=await e(t,{density:Math.ceil(72*n)}).resize(ue.logoWidth,ue.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:ue.width,height:ue.height,channels:4,background:ue.background}}).composite([{input:o}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],n=[{name:"favicon.svg",format:"svg"}],o=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...n,...r].map(p=>p.name),error:"Failed to read logo.svg"};for(let p of n){let u=`${s}/${p.name}`;if(this.pathResolver.pathExists(u)){i.push(p.name);continue}try{await this.pathResolver.write(`public/${p.name}`,l),o.push(p.name)}catch(g){this.logger.debug(`Failed to copy ${p.name}: ${g.message}`),i.push(p.name)}}let c=await import("sharp").catch(()=>null);if(!c)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(p=>p.name));else{for(let u of r){let g=`${s}/${u.name}`;if(this.pathResolver.pathExists(g)){i.push(u.name);continue}try{let h=c.default(t).resize(u.size,u.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),f;u.format==="ico"?f=await h.toFormat("png").toBuffer():f=await h.toFormat(u.format).toBuffer(),await this.pathResolver.write(`public/${u.name}`,f),o.push(u.name)}catch(h){this.logger.debug(`Failed to generate ${u.name}: ${h.message}`),i.push(u.name)}}let p=pe.slice(1);if(this.pathResolver.pathExists(`${s}/${p}`))i.push(p);else try{let u=await this._renderOgImage(c.default,t);await this.pathResolver.write(`public/${p}`,u),o.push(p)}catch(u){this.logger.debug(`Failed to generate ${p}: ${u.message}`),i.push(p)}}return{generated:o,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(c=>c.name),error:l.message}}}};var Ze={data:null},Ye=class extends M{constructor(e={}){super(Ne,e)}getHandlerDefaults(){return{manifestPath:O.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
53
53
|
// Generated at: ${new Date().toISOString()}
|
|
54
54
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
55
55
|
|
|
@@ -66,7 +66,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
66
66
|
timestamp: Date.now(),
|
|
67
67
|
};
|
|
68
68
|
}
|
|
69
|
-
globalThis._DNDEV_CONFIG_.${
|
|
69
|
+
globalThis._DNDEV_CONFIG_.${J.assets} = {
|
|
70
70
|
mapping: assetConfig.manifest,
|
|
71
71
|
logoSvgContent: ${JSON.stringify(t)},
|
|
72
72
|
manifest: {
|
|
@@ -78,14 +78,14 @@ if (typeof globalThis !== 'undefined') {
|
|
|
78
78
|
|
|
79
79
|
// Export for compatibility
|
|
80
80
|
export default assetConfig;
|
|
81
|
-
`}logDiscoveryResults(e){let t=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(
|
|
82
|
-
path: '${
|
|
83
|
-
type: '${
|
|
84
|
-
format: '${
|
|
85
|
-
size: ${
|
|
86
|
-
optimized: ${
|
|
81
|
+
`}logDiscoveryResults(e){let t=e.assets?.length||0,s=e.generatedAssets?.length||0;s>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${s} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}async getDiscoveryData(){let e=await this.discovery.discoverAssets();return e?.pwaIcons&&(Ze.data={pwaIcons:e.pwaIcons}),e}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({path:t.path,type:t.type,format:t.format,size:t.size,optimized:t.optimized})),manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} assets, ${e.copiedAssets.length} copied from framework`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateAssetManifest(e),this.options.optimizeImages&&await this.generateImageOptimization(e),await this.generateAPIHandler(e)}async generateAssetManifest(e){let t=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",t,"asset manifest")}generateAssetManifestContent(e){let t=e.assets.map(n=>` {
|
|
82
|
+
path: '${n.path}',
|
|
83
|
+
type: '${n.type}',
|
|
84
|
+
format: '${n.format}',
|
|
85
|
+
size: ${n.size},
|
|
86
|
+
optimized: ${n.optimized||!1}
|
|
87
87
|
}`).join(`,
|
|
88
|
-
`),s=Object.entries(e.manifest).map(([o
|
|
88
|
+
`),s=Object.entries(e.manifest).map(([n,o])=>` ${n}: ${JSON.stringify(o)}`).join(`,
|
|
89
89
|
`),r=e.manifest.logoSvgContent||null;return`// Auto-generated asset manifest by @donotdev/config
|
|
90
90
|
// Generated at ${new Date().toISOString()}
|
|
91
91
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
@@ -125,16 +125,16 @@ ${t}
|
|
|
125
125
|
export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
|
|
126
126
|
|
|
127
127
|
export default imageConfigs;
|
|
128
|
-
`}};function
|
|
128
|
+
`}};function Qt(a={}){return new Ye(a)}import Qe from"node:fs";import Pr from"node:path";var et=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!Qe.existsSync(e))return{blogDir:e,files:[]};let t;try{t=Qe.readdirSync(e)}catch{return{blogDir:e,files:[]}}let s=t.filter(r=>r.endsWith(".md")&&!r.startsWith(".")).sort();return{blogDir:e,files:s}}},tt=class extends M{constructor(e={}){super(et,e)}getHandlerDefaults(){return{outputPath:O.next.blogContent}}getHandlerName(){return"BlogContent"}createDiscovery(e){return new e(this.pathResolver)}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateSpecificFiles(e),this.logger.debug(`Generated BlogContent: ${this.getGenerationSummary(e)}`),e}catch(e){return this.logger.debug(`BlogContent generation failed (non-critical): ${e.message}`),{blogDir:"",files:[]}}}async getDiscoveryData(){return this.discovery.discoverBlogFiles()}logDiscoveryResults(e){this.logger.info(`\u{1F4DD} Blog: ${e.files.length} .md file(s) found`)}getGenerationSummary(e){return`${e.files.length} blog file(s)`}async generateSpecificFiles(e){let{blogDir:t,files:s}=e;if(s.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let r=this._buildGeneratedContent(t,s);this.writeGeneratedFile(this.options.outputPath,r,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
129
129
|
// Regenerated when src/content/blog/*.md files change
|
|
130
130
|
|
|
131
131
|
const blogContent: Record<string, string> = {
|
|
132
|
-
${t.map(r=>{let
|
|
132
|
+
${t.map(r=>{let n=Qe.readFileSync(Pr.join(e,r),"utf8");return` './${r}': ${JSON.stringify(n)},`}).join(`
|
|
133
133
|
`)}
|
|
134
134
|
};
|
|
135
135
|
|
|
136
136
|
export default blogContent;
|
|
137
|
-
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function jt(a={}){return new He(a)}var Ve=class extends F{constructor(e={}){super(pe,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...ve.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:o,content:n}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
137
|
+
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function es(a={}){return new tt(a)}function xr(a){if(!a)return[];let e=R.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",a);if(!s)return[];let r=e.getDirname(e.getDirname(s)),n;try{n=e.readdirSync(r)}catch{return[]}for(let o of n)try{let i=e.resolvePath(`${o}/package.json`,r),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[c,p]of Object.entries(l.peerDependenciesMeta))p?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function Er(a){if(!a)return[];let e=R.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[n,o]of Object.entries(s.peerDependenciesMeta))o?.optional&&r.add(n);if(s.optionalDependencies)for(let n of Object.keys(s.optionalDependencies))r.add(n);return Array.from(r)}catch{return[]}}function Ar(a){let e=_e.optionalFeatures||[],t=xr(a),s=Er(a);return[...new Set([...e,...t,...s])]}function _r(a){let e=R.getInstance();try{let t=e.resolvePath("package.json",a),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function kr(a,e,t){if(t.resolvePackage(a,e||void 0))return!0;let s=a.startsWith("@")?a.split("/").slice(0,2).join("/"):a.split("/")[0],r=e;for(let n=0;n<10;n++){let o=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(o))return!0;let i=t.getDirname(r);if(i===r)break;r=i}return!1}function Ce(a){let e=Ar(a),t=[],s=[],r=R.getInstance(),n=_r(a);for(let o of e)o.startsWith("@donotdev/")?n.has(o)?s.push(o):t.push(o):n.has(o)&&kr(o,a,r)?s.push(o):t.push(o);return{missing:t,installed:s}}var De=class a extends X{static LANGUAGE_FLAG_OVERRIDES={en:"gb","en-ca":"ca","es-ar":"ar","fr-be":"be",ar:"sa","ar-ma":"ma","ar-dz":"dz","ar-tn":"tn","ar-ly":"ly","ar-mr":"mr",hi:"in",sl:"si",uk:"ua",ga:"ie",gd:"gb-sct",br:"bzh",co:"fr-cor",am:"et",bn:"bd",gu:"in",kn:"in",ml:"in",mr:"in",ne:"np",pa:"pk",ta:"in",te:"in",ur:"pk",fa:"ir",kk:"kz",ky:"kg",tg:"tj",my:"mm",km:"kh",lo:"la",ka:"ge",hy:"am",be:"by",bs:"ba",sq:"al",ms:"my"};constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[s,r]of Object.entries(e)){for(let n of Object.keys(r))t.includes(n)||delete r[n];Object.keys(r).length===0&&delete e[s]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let n=ke("i18n"),o=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(m=>{let $=m.endsWith(".json")?m:`${m}/*_*.json`;return this.pathResolver.resolveAppPath($)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let c=r.framework?.eager||[],p=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${o.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${p.join(", ")}`),c.length===0&&p.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),g=this.pathResolver.normalizePath(s),h=(m,$)=>{let A=this.pathResolver.normalizePath(m),D=this.pathResolver.normalizePath($);return A.startsWith(D)?A.slice(D.length+1):A},f=o.map(m=>h(m,t)),y=[...i,...l].map(m=>h(m,t)),v=c.map(m=>h(m,s)),P=p.map(m=>h(m,s)),b={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},x=await this.pathResolver._globWithNormalization(f,b),T=await this.pathResolver._globWithNormalization(y,b),C={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:n.ignore?.filter(m=>m!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(C.ignore)}`);let _=await this.pathResolver._globWithNormalization(v,C),j=await this.pathResolver._globWithNormalization(P,C);this.logger.debug(`Found ${x.length} eager, ${T.length} lazy, ${_.length} framework eager, ${j.length} framework lazy files`),_.length>0?this.logger.debug(`Framework eager files (first 3): ${_.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),j.length>0?this.logger.debug(`Framework lazy files (first 3): ${j.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${p.join(", ")}`);let re=[...new Set([...x,...T,..._,...j])],ee=new Set([...x,..._]),d={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:ne}=Ce(t),E=new Set(ne.filter(m=>m.startsWith("@donotdev/")).map(m=>m.replace("@donotdev/","")));E.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...E].join(", ")}] (packages not installed)`);let K=new Map,z=[..._,...j];for(let m of z){let $=this._processTranslationFile(m,_.includes(m),t);if($){if(E.has($.namespace))continue;let A=`${$.namespace}_${$.language}`;K.set(A,$),d.allNamespaces.add($.namespace),d.supportedLanguages.add($.language),_.includes(m)&&d.eagerNamespaces.add($.namespace)}}let U=new Set;for(let m of re){if(z.includes(m))continue;let $=this._processTranslationFile(m,ee.has(m),t);if($){let{namespace:A,language:D,importPath:q,content:le}=$,Ee=`${$.namespace}_${$.language}`;if(K.has(Ee)){let Me=K.get(Ee);$.content=this._mergeTranslations(Me.content,le)}d.allNamespaces.add(A),d.supportedLanguages.add(D),U.add(D),ee.has(m)&&d.eagerNamespaces.add(A),d.mapping[A]||(d.mapping[A]={}),d.mapping[A][D]=q,$.content&&(d.content[A]||(d.content[A]={}),d.content[A][D]=$.content),d.files.push({path:m,relativePath:this.pathResolver.getRelativePath(m),namespace:A,language:D,eager:ee.has(m),size:$.content?JSON.stringify($.content).length:0})}}for(let[m,$]of K){let A=m.lastIndexOf("_"),D=m.slice(0,A),q=m.slice(A+1);U.size>0&&!U.has(q)||(!d.mapping[D]||!d.mapping[D][q])&&(d.mapping[D]||(d.mapping[D]={}),d.mapping[D][q]=$.importPath,d.content[D]||(d.content[D]={}),d.content[D][q]=$.content,d.files.push({path:$.absolutePath,relativePath:this.pathResolver.getRelativePath($.absolutePath),namespace:D,language:q,eager:d.eagerNamespaces.has(D),size:$.content?JSON.stringify($.content).length:0}))}let W=U.size>0?[...U].sort():[this.options.fallbackLanguage],N=this._getLanguageAllowlist(),k=W;if(N){let m=W.filter(A=>N.includes(A));k=m.length>0?m:[this.options.fallbackLanguage],this._restrictByLanguage(d.mapping,k),this._restrictByLanguage(d.content,k),d.files=d.files.filter(A=>k.includes(A.language));let $=new Set(Object.keys(d.mapping));d.allNamespaces=new Set([...d.allNamespaces].filter(A=>$.has(A))),d.eagerNamespaces=new Set([...d.eagerNamespaces].filter(A=>$.has(A))),this.logger.debug(`I18n restricted by i18n.only [${N.join(", ")}]: languages [${k.join(", ")}], namespaces ${$.size}`)}let te=[...new Set(k.map(m=>a.LANGUAGE_FLAG_OVERRIDES[m]||m))];return{mapping:d.mapping,content:d.content,eagerNamespaces:[...d.eagerNamespaces].sort(),allNamespaces:[...d.allNamespaces].sort(),supportedLanguages:k,fallbackLanguage:this.options.fallbackLanguage,flagCodes:te,files:d.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[a.LANGUAGE_FLAG_OVERRIDES[this.options.fallbackLanguage]||this.options.fallbackLanguage],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",n,o,i=r.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,n,o]=i,!n||!o)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),p;try{if(p=this.pathResolver.readSync(e,{format:"json"}),!p)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:n,language:o,importPath:c,absolutePath:e,content:p}}_mergeTranslations(e,t){let s={...e};for(let[r,n]of Object.entries(t))typeof n=="object"&&n!==null&&!Array.isArray(n)?s[r]=this._mergeTranslations(s[r]||{},n):s[r]=n;return s}};var st=class extends M{constructor(e={}){super(De,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...$e.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:n,content:o}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
138
138
|
// Generated at: ${new Date().toISOString()}
|
|
139
139
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
140
140
|
|
|
@@ -142,8 +142,8 @@ const i18nConfig = {
|
|
|
142
142
|
mapping: ${JSON.stringify(t,null,2)},
|
|
143
143
|
languages: ${JSON.stringify(s,null,2)},
|
|
144
144
|
eager: ${JSON.stringify(r,null,2)},
|
|
145
|
-
fallback: '${
|
|
146
|
-
content: ${JSON.stringify(
|
|
145
|
+
fallback: '${n}',
|
|
146
|
+
content: ${JSON.stringify(o||{},null,2)},
|
|
147
147
|
storage: {
|
|
148
148
|
type: 'localStorage',
|
|
149
149
|
prefix: 'dndev_i18n_',
|
|
@@ -176,12 +176,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
176
176
|
timestamp: Date.now(),
|
|
177
177
|
};
|
|
178
178
|
}
|
|
179
|
-
globalThis._DNDEV_CONFIG_.${
|
|
179
|
+
globalThis._DNDEV_CONFIG_.${J.i18n} = i18nConfig;
|
|
180
180
|
}
|
|
181
181
|
|
|
182
182
|
// Export for compatibility
|
|
183
183
|
export default i18nConfig;
|
|
184
|
-
`}};function
|
|
184
|
+
`}};function ts(a={}){return new st(a)}var Te=class extends X{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:s}=e,r=[...t,...s];this.logger.debug(`Processing ${r.length} PWA files`);let n=[];this.options.assetData?.pwaIcons&&(this.logger.debug(`Using ${this.options.assetData.pwaIcons.length} icons from AssetDiscovery`),n=[...this.options.assetData.pwaIcons]);let o=await this._analyzePWAFiles(r),i=o.filter(g=>g.type==="manifest"||g.type==="service-worker");n.push(...i);let l=o.filter(g=>g.type==="icon"),c=new Set(n.filter(g=>g.type==="icon").map(g=>g.path)),p=l.filter(g=>!c.has(g.path));n.push(...p);let u=this._generatePWAManifest(n);return{assets:n,manifest:u,totalFiles:r.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let s of e){let r=typeof s=="string"?{absolutePath:s,relativePath:this.pathResolver.getRelativePath(s),fileName:s.split("/").pop()||"",extension:(s.split(".").pop()||"").toLowerCase()}:s,n=await this._analyzePWAAsset(r);n&&t.push(n)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let s=e.relativePath,r=e.fileName;return r==="manifest.json"?this._parseManifestFile(t,s):r.includes("service-worker")||r.includes("sw.")?this._parseServiceWorkerFile(t,s):this._isPWAIcon(r)?this._parseIconFile(e,s):null}_parseManifestFile(e,t){try{let s=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:s,size:typeof e=="string"?e.length:JSON.stringify(s).length}}catch(s){return this.logger.debug(`Failed to parse manifest: ${s.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let s=e.fileName,r=this._extractIconSize(s);return{type:"icon",path:t,size:r,format:e.extension,purpose:this._getIconPurpose(s)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(s=>e.includes(s))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(r=>r.type==="icon"),s=this._getDefaultManifest();return t.length>0&&(s.icons=t.map(r=>this.toManifestIcon(r))),s}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},s=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:s==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[s]||`image/${s}`,purpose:e.purpose==="maskable"?"maskable":"any"}}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let t=e.manifest||this._getDefaultManifest();return JSON.stringify(t,null,2)}generateServiceWorkerContent(e,t={}){let s=this._getWorkboxDefaults(t),r=t.backgroundSync!==!1&&t.backgroundSync,n=t.precacheManifest||[],o=JSON.stringify(n,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
185
185
|
// Generated at ${new Date().toISOString()}
|
|
186
186
|
|
|
187
187
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -197,7 +197,7 @@ ${r?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
|
|
|
197
197
|
cleanupOutdatedPrecaches();
|
|
198
198
|
|
|
199
199
|
// Precache static assets
|
|
200
|
-
const precacheManifest = ${
|
|
200
|
+
const precacheManifest = ${o.length>2?o:"self.__WB_MANIFEST || []"};
|
|
201
201
|
precacheAndRoute(precacheManifest);
|
|
202
202
|
|
|
203
203
|
// Runtime caching strategies
|
|
@@ -215,31 +215,31 @@ self.addEventListener('message', (event) => {
|
|
|
215
215
|
self.addEventListener('activate', (event) => {
|
|
216
216
|
event.waitUntil(self.clients.claim());
|
|
217
217
|
});
|
|
218
|
-
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:
|
|
219
|
-
maxEntries: ${
|
|
220
|
-
maxAgeSeconds: ${
|
|
221
|
-
})`),
|
|
222
|
-
statuses: ${JSON.stringify(
|
|
223
|
-
})`),
|
|
224
|
-
maxRetentionTime: ${
|
|
225
|
-
})`);let u="";return
|
|
226
|
-
cacheName: '${
|
|
218
|
+
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s,r)=>{let{urlPattern:n,handler:o,options:i={}}=s,l=o==="CacheFirst"?"CacheFirst":o==="NetworkFirst"?"NetworkFirst":o==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",c;typeof n=="function"?c="({ request }) => request.destination === 'document'":n instanceof RegExp?c=n.toString():c=JSON.stringify(n);let p=[];i.expiration&&p.push(`new ExpirationPlugin({
|
|
219
|
+
maxEntries: ${i.expiration.maxEntries||50},
|
|
220
|
+
maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
|
|
221
|
+
})`),i.cacheableResponse&&p.push(`new CacheableResponsePlugin({
|
|
222
|
+
statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
|
|
223
|
+
})`),i.backgroundSync&&p.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
|
|
224
|
+
maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
|
|
225
|
+
})`);let u="";return i.cacheName&&(u+=`
|
|
226
|
+
cacheName: '${i.cacheName}',`),p.length>0&&(u+=`
|
|
227
227
|
plugins: [
|
|
228
|
-
${
|
|
228
|
+
${p.join(`,
|
|
229
229
|
`)}
|
|
230
|
-
],`),
|
|
231
|
-
networkTimeoutSeconds: ${
|
|
230
|
+
],`),i.networkTimeoutSeconds&&(u+=`
|
|
231
|
+
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${r+1}: ${i.cacheName||"cache-"+r}
|
|
232
232
|
registerRoute(
|
|
233
|
-
${
|
|
234
|
-
new ${
|
|
233
|
+
${c},
|
|
234
|
+
new ${l}({${u}
|
|
235
235
|
})
|
|
236
236
|
);`}).join(`
|
|
237
237
|
|
|
238
|
-
`)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",s=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,
|
|
238
|
+
`)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",s=e.maxRetentionTime||1440,r=e.urlPattern||/\/api\/.*/i,n;return typeof r=="function"||r instanceof RegExp?n=r.toString():n=JSON.stringify(r),`
|
|
239
239
|
// Background sync for offline actions
|
|
240
240
|
const { NetworkOnly } = workbox.strategies;
|
|
241
241
|
registerRoute(
|
|
242
|
-
${
|
|
242
|
+
${n},
|
|
243
243
|
new NetworkOnly({
|
|
244
244
|
plugins: [
|
|
245
245
|
new BackgroundSyncPlugin('${t}', {
|
|
@@ -249,7 +249,7 @@ registerRoute(
|
|
|
249
249
|
}),
|
|
250
250
|
'POST'
|
|
251
251
|
);
|
|
252
|
-
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let n=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let l of n){let i=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),l.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of i){let c=this.pathResolver.getRelativePath(p);if(c.startsWith(`${e}/static/`)){let u=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:u,revision:null})}}}}catch(n){this.logger?.warn(`Failed to discover Next.js build assets: ${n.message}`)}return o}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Je=class extends F{constructor(e={}){super(Ae,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Ge.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(!this.options.enabled){this.logger.debug("PWA disabled, skipping generation");return}this.options.generateManifest&&await this.generatePWAManifest(e),this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,t,"PWA manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:o,webpack:n}=s;return this.applyViteIgnorePlugin(t,n),!r&&!o&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function Ut(a={}){return new Je(a)}import{createRequire as sr}from"node:module";function Gt(a,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=a.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,p)=>`icon: '${p}'`);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(o)].forEach(i=>{let p=i[1],c=i[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var be=null,Bt=null;function er(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}var ue=class extends G{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if(be&&Bt===s)return this.logger.debug("Using cached route discovery results"),this.routes=be.routes,this.errors=be.errors,this.source=be.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let o=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(o)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),be={routes:this.routes,errors:this.errors,source:this.source},Bt=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),o=await this._scanAdditionalPatterns(t),n=await this._batchProcessFiles(o,p=>this._analyzePageFile(p,t)),l=[...r,...n];this.logger.debug(`Auto-discovering from ${s.length} app + ${o.length} additional files`),this.routes=l.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let i=new Map;for(let p of this.routes){let c=p.path;if(i.has(c)){let u=i.get(c);throw new Error(`Route conflict: Multiple routes found for path '${c}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}i.set(c,p)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,o="/src/"+r.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let n=this._extractMetaExport(s,e.absolutePath),l=er(o),p=l===he.HOMEPAGE_COMPONENT?he.HOMEPAGE_PATH:this._resolveRoutePath(n,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:g,...f}=n||{};return{path:p,component:l,importPath:o,auth:n?.auth||!1,meta:{...c,...f,entity:c.entity,action:c.action},metaExport:n,file:r}}_extractMetaExport(e,t){try{let s=Gt(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let n=o.map(l=>`:${l}`).join("/");return`${r}/${n}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),n=null,l=null;return o.length>1&&(n=o[o.length-2],s.includes("List")?l="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?l="form":(s.includes("Detail")||s.includes("View"))&&(l="detail")),{title:r,entity:n,action:l,file:e}}};function tr(a,e,t="configuration-error",s={}){let r=`[${a}] ${e}`,o=new Error(r);return o.code=t,o.pluginName=a,o.context=s,o}function Wt(a,e,t,s={}){return tr(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function qe(a,e,t,s){try{if(t?.content?.[a]?.[e])return t.content[a][e];let r=t?.mapping?.[a]?.[e];if(!r)return null;let o=s.resolveAppPath(r),n=s.readSync(o,{format:"text"});return n?JSON.parse(n):null}catch{return null}}function Ee(a,e){if(!a||!e)return;let t=e.split("."),s=a;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function Ye(a){return a?.languages||a?.supportedLanguages||["en"]}function Ke(a){return a?.fallback||a?.fallbackLanguage||"en"}var Xe=class extends F{constructor(e={}){super(ue,e)}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,middlewarePath:D.next.middleware,manifestPath:D.next.routeManifest}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(o=>o.auth&&o.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
252
|
+
`}getPWAHeaders(){return[{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:"public, max-age=3600"}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),n=[];try{let o=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let i of o){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let c of l){let p=this.pathResolver.getRelativePath(c);if(p.startsWith(`${e}/static/`)){let u=`/_next/${p.replace(`${e}/static/`,"")}`;n.push({url:u,revision:null})}}}}catch(o){this.logger?.warn(`Failed to discover Next.js build assets: ${o.message}`)}return n}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var rt=class extends M{constructor(e={}){super(Te,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/pwa-manifest.json",webManifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||Ze.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(this.options.generateManifest&&await this.generatePWAManifest(e),!this.options.enabled){this.logger.debug("PWA disabled, skipping service worker generation");return}this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.webManifestPath,t,"web app manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let n=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(n,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,async headers(){let t=e.headers?await e.headers():[],s=this.discovery.getPWAHeaders();return[...t,...s]},webpack:(t,s)=>{let{dev:r,isServer:n,webpack:o}=s;return this.applyViteIgnorePlugin(t,o),!r&&!n&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function ss(a={}){return new rt(a)}import{createRequire as Tr}from"node:module";function rs(a,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=a.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,c)=>`icon: '${c}'`);let n=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...a.matchAll(n)].forEach(l=>{let c=l[1],p=l[2];r=r.replace(new RegExp(`\\b${c}\\b`,"g"),`'${p}'`)}),Function(`return ${r}`)()}catch{return null}}var Re=null,ns=null;function Nr(a){let t=(a.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Cr(a){let e=a.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw new Error(`PageMeta signedInRedirect in ${a.file} must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`);if(e.split(/[?#]/)[0]===a.path)throw new Error(`PageMeta signedInRedirect in ${a.file} points at the page itself (${e}): signed-in visitors would loop. Use another page.`)}}var de=class extends X{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(Re&&ns===s)return this.logger.debug("Using cached route discovery results"),this.routes=Re.routes,this.errors=Re.errors,this.source=Re.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let n=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(n)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),Re={routes:this.routes,errors:this.errors,source:this.source},ns=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,c=>this._analyzePageFile(c,t)),n=await this._scanAdditionalPatterns(t),o=await this._batchProcessFiles(n,c=>this._analyzePageFile(c,t)),i=[...r,...o];this.logger.debug(`Auto-discovering from ${s.length} app + ${n.length} additional files`),this.routes=i.filter(c=>c.path==="home"||c.path==="/home"?(this.logger.debug(`Filtered reserved route: ${c.path} - Use root "/" instead (${c.file})`),!1):!0);let l=new Map;for(let c of this.routes){let p=c.path;if(l.has(p)){let u=l.get(p);throw new Error(`Route conflict: Multiple routes found for path '${p}'. Routes: ${u.file} and ${c.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}l.set(p,c),Cr(c)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+n.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,n="/src/"+r.replace(/\\/g,"/");n=n.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let o=this._extractMetaExport(s,e.absolutePath),i=Nr(n),c=i===ye.HOMEPAGE_COMPONENT?ye.HOMEPAGE_PATH:this._resolveRoutePath(o,r,e.absolutePath),p=this._extractPageMeta(r,s),{entity:u,action:g,...h}=o||{};return{path:c,component:i,importPath:n,auth:o?.auth||!1,meta:{...p,...h,entity:p.entity,action:p.action},metaExport:o,file:r}}_extractMetaExport(e,t){try{let s=rs(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),n=e.route.params;if(Array.isArray(n)&&n.length>0){let o=n.map(i=>`:${i}`).join("/");return`${r}/${o}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let n=e.split("/"),o=null,i=null;return n.length>1&&(o=n[n.length-2],s.includes("List")?i="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?i="form":(s.includes("Detail")||s.includes("View"))&&(i="detail")),{title:r,entity:o,action:i,file:e}}};function Dr(a,e,t="configuration-error",s={}){let r=`[${a}] ${e}`,n=new Error(r);return n.code=t,n.pluginName=a,n.context=s,n}function os(a,e,t,s={}){return Dr(a,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function nt(a,e,t,s){try{if(t?.content?.[a]?.[e])return t.content[a][e];let r=t?.mapping?.[a]?.[e];if(!r)return null;let n=s.resolveAppPath(r),o=s.readSync(n,{format:"text"});return o?JSON.parse(o):null}catch{return null}}function Fe(a,e){if(!a||!e)return;let t=e.split("."),s=a;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function ot(a){return a?.languages||a?.supportedLanguages||["en"]}function at(a){return a?.fallback||a?.fallbackLanguage||"en"}var it=class extends M{constructor(e={}){super(de,e),this.rendersSessionTree=!1,this.appRouteSegments=[]}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,proxyPath:O.next.proxy,manifestPath:O.next.routeManifest,languages:[],defaultLanguage:null}}useLanguages({languages:e,defaultLanguage:t}){if(e.length>1&&!e.includes(t))throw new Error(`i18n fallbackLanguage "${t}" has no translations among [${e.join(", ")}]: it is the language served at the root URL. Add its locale files or set i18n.fallbackLanguage to one of them.`);this.options.languages=e,this.options.defaultLanguage=t}isMultilingual(){return this.options.languages.length>1}rootDir(){return this.isMultilingual()?"/[lang]":""}treeDir(e="site"){return`${this.rootDir()}/${e==="session"?Z.sessionSegment:Z.siteGroup}`}appDirFor(e,t="site"){return`${this.treeDir(t)}${this.convertRouteToAppPath(e)}`}appImport(e,t){let s=e.split("/").filter(Boolean).length;return s===0?`./${t}`:`${"../".repeat(s)}${t}`}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(n=>n.auth&&n.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
253
253
|
// Generated at: ${new Date().toISOString()}
|
|
254
254
|
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
255
255
|
|
|
@@ -268,7 +268,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
268
268
|
timestamp: Date.now(),
|
|
269
269
|
};
|
|
270
270
|
}
|
|
271
|
-
globalThis._DNDEV_CONFIG_.${
|
|
271
|
+
globalThis._DNDEV_CONFIG_.${J.routes} = {
|
|
272
272
|
mapping: routeMapping,
|
|
273
273
|
manifest: routeManifest,
|
|
274
274
|
};
|
|
@@ -278,35 +278,185 @@ if (typeof globalThis !== 'undefined') {
|
|
|
278
278
|
export const routes = routeMapping;
|
|
279
279
|
export const manifest = routeManifest;
|
|
280
280
|
export default { routes: routeMapping, manifest: routeManifest };
|
|
281
|
-
`}async generateSpecificFiles(e){this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=
|
|
282
|
-
//
|
|
283
|
-
//
|
|
281
|
+
`}async generateSpecificFiles(e){await this.assertAppDocument(),this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&await this.generateAppPageFiles(e),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=ot(t),r=at(t),n=process.env.NEXT_PUBLIC_SITE_NAME||"";if(!n)try{let l=this.pathResolver.resolveAppPath("public/seo-manifest.json");this.pathResolver.pathExists(l)&&(n=this.pathResolver.readSync(l,{format:"json"})?.siteName||"")}catch{}let o={};for(let l of e.routes){let c=l.metaExport?.namespace,p=l.metaExport?.seo||{},u={};for(let g of s){let h=c&&t&&nt(c,g,t,this.pathResolver)||nt(c,r,t,this.pathResolver),f=Fe(h,"meta")||{},w=Fe(h,"title"),y=Fe(h,"description"),v;f.fullTitle?v=f.fullTitle:p.fullTitle?v=p.fullTitle:w?v=n?`${w} | ${n}`:w:p.title?v=n?`${p.title} | ${n}`:p.title:p.title===null?v=n:v=n||"";let P;p.description===null?P=void 0:p.description?P=p.description:y&&(P=y);let b=p.image||f.image||pe,x=p.type||f.type||"website",T=p.keywords||f.keywords,C=p.noindex||!1;u[g]={title:v,...P&&{description:P},image:b,type:x,...T&&{keywords:T},...C&&{noindex:C}}}o[l.path]={locales:u,defaultLocale:r}}let i=JSON.stringify(o,null,2);this.writeGeneratedFile("public/metadata-manifest.json",i,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(o).length} routes`)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles(),this.generateRootLayout(),this.generateNotFoundPages();let t=this.rendersSessionTree?["site","session"]:["site"];for(let r of t)await this.generateTreeLayout(r);let s=0;for(let r of e.routes){let n=this.isSessionOnlyRoute(r)?"session":"site",o=await this.generateSingleAppPage(r,n);o&&s++,o&&n==="site"&&this.rendersSessionTree&&this.generateSessionPage(r)}this.logger.debug(`Successfully generated ${s}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}requestDocumentParts(e){return[[/<ClientLayout\b/,"renders <ClientLayout>"],[/from\s+['"]next\/headers['"]/,"imports next/headers"],[/export\s+const\s+dynamic\b/,"exports `dynamic`"]].filter(([t])=>t.test(e)).map(([,t])=>t)}async assertAppDocument(){let e=O.next.appDocument,t=`${e} exports \`metadata\` (site-level: metadataBase) and \`AppDocument({ lang, children })\`, which renders <html lang={lang}>, the <head> links (favicon, <FontPreloadLinks />), imports the global CSS and puts {children} in <body> (see the @donotdev/cli app-next template)`,s=[];for(let o of this.frameworkRootFiles()){let i=this.pathResolver.resolveAppPath(o);this.pathResolver.pathExists(i)&&!await this.hasGenerationMarker(i)&&s.push(o)}if(s.length>0)throw new Error(`[dndev] ${s.join(", ")}: the framework generates the root layout and the 404 pages, so every page's HTML carries its language (<html lang>). Move the HTML shell into ${e}: ${t}. Then delete ${s.join(", ")}.`);let r=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(r))throw new Error(`[dndev] ${e} is missing: ${t}.`);let n=this.requestDocumentParts(await this.pathResolver.read(r,{format:"text"}));if(n.length!==0)throw new Error(`[dndev] ${e} ${n.join(", ")}. It must be the HTML shell: render {children} in <body>, drop the ClientLayout / headers() wrapper and \`export const dynamic\`. The generated layouts render ClientLayout: cached pages for guests, per-request pages for visitors with an auth cookie.`)}frameworkRootFiles(){let e=F("layout","tsx"),t=F("not-found","tsx");return[O.next.appLayout,`src/app/[lang]/${e}`,`src/app/${t}`,`src/app/[lang]/${t}`,`src/app/${F("global-not-found","tsx")}`]}async generateTreeLayout(e){let t=`src/app${this.treeDir(e)}/${F("layout","tsx")}`,s=this.pathResolver.resolveAppPath(t);if(this.pathResolver.pathExists(s)&&!await this.hasGenerationMarker(s)){this.logger.debug(`Skipping ${t} - user-created file detected`);return}this.writeGeneratedFile(t,e==="session"?this.generateSessionLayoutContent():this.generateSiteLayoutContent(),`${e} layout`)}generateSiteLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
282
|
+
// Cached pages: rendered without request data (no cookies, no headers), served from the
|
|
283
|
+
// cache and ${this.revalidateLabel()} (appConfig.revalidate). One entry per URL (page and language).
|
|
284
|
+
|
|
285
|
+
import type { ReactNode } from 'react';
|
|
286
|
+
|
|
287
|
+
import { ClientLayout } from '${this.appImport(this.treeDir("site"),"ClientLayout")}';
|
|
288
|
+
|
|
289
|
+
export const revalidate = ${this.revalidate()};
|
|
290
|
+
|
|
291
|
+
export default function SiteLayout({ children }: { children: ReactNode }) {
|
|
292
|
+
return (
|
|
293
|
+
<ClientLayout serverCookies="" acceptLanguage={null}>
|
|
294
|
+
{children}
|
|
295
|
+
</ClientLayout>
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
`}generateSessionLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
299
|
+
// Per-request pages for visitors with an auth cookie (the proxy rewrites them here; a
|
|
300
|
+
// direct hit is a 404): the providers read the request cookies, so the server render
|
|
301
|
+
// shows the visitor's signed-in state and data. Never cached.
|
|
302
|
+
|
|
303
|
+
import { headers } from 'next/headers';
|
|
304
|
+
import type { ReactNode } from 'react';
|
|
305
|
+
|
|
306
|
+
import { ClientLayout } from '${this.appImport(this.treeDir("session"),"ClientLayout")}';
|
|
284
307
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
308
|
+
export default async function SessionLayout({ children }: { children: ReactNode }) {
|
|
309
|
+
const requestHeaders = await headers();
|
|
310
|
+
return (
|
|
311
|
+
<ClientLayout
|
|
312
|
+
serverCookies={requestHeaders.get('cookie') ?? ''}
|
|
313
|
+
acceptLanguage={requestHeaders.get('accept-language')}
|
|
314
|
+
>
|
|
315
|
+
{children}
|
|
316
|
+
</ClientLayout>
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
`}generateRootLayout(){this.writeGeneratedFile(`src/app${this.rootDir()}/${F("layout","tsx")}`,this.generateRootLayoutContent(),"root layout")}generateRootLayoutContent(){let e=this.appImport(this.rootDir(),"AppDocument");return this.isMultilingual()?`// Generated by @donotdev/config - DO NOT EDIT
|
|
320
|
+
// Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the URL's language.
|
|
321
|
+
// One URL per language: the default language (${this.options.defaultLanguage}) at the root, served here by
|
|
322
|
+
// the proxy's rewrite; the others under their prefix. Any other first segment is a 404.
|
|
323
|
+
|
|
324
|
+
import { notFound } from 'next/navigation';
|
|
325
|
+
import type { ReactNode } from 'react';
|
|
326
|
+
|
|
327
|
+
import { AppDocument } from '${e}';
|
|
328
|
+
|
|
329
|
+
export { metadata } from '${e}';
|
|
330
|
+
|
|
331
|
+
const LANGUAGES: readonly string[] = ${JSON.stringify(this.options.languages)};
|
|
332
|
+
|
|
333
|
+
export function generateStaticParams() {
|
|
334
|
+
return LANGUAGES.map((lang) => ({ lang }));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export default async function RootLayout({
|
|
338
|
+
children,
|
|
339
|
+
params,
|
|
340
|
+
}: {
|
|
341
|
+
children: ReactNode;
|
|
342
|
+
params: Promise<{ lang: string }>;
|
|
343
|
+
}) {
|
|
344
|
+
const { lang } = await params;
|
|
345
|
+
if (!LANGUAGES.includes(lang)) notFound();
|
|
346
|
+
return <AppDocument lang={lang}>{children}</AppDocument>;
|
|
289
347
|
}
|
|
290
348
|
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
349
|
+
// Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the app's language.
|
|
350
|
+
|
|
351
|
+
import type { ReactNode } from 'react';
|
|
352
|
+
|
|
353
|
+
import { AppDocument } from '${e}';
|
|
354
|
+
|
|
355
|
+
export { metadata } from '${e}';
|
|
356
|
+
|
|
357
|
+
export default function RootLayout({ children }: { children: ReactNode }) {
|
|
358
|
+
return <AppDocument lang=${JSON.stringify(this.options.defaultLanguage)}>{children}</AppDocument>;
|
|
359
|
+
}
|
|
360
|
+
`}generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${F("not-found","tsx")}`,this.generateNotFoundContent(),"404 page"),this.writeGeneratedFile(`src/app/${F("global-not-found","tsx")}`,this.generateGlobalNotFoundContent(),"global 404 page")}generateNotFoundContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
361
|
+
// 404 page: the app's providers without request data (static, like every cached page).
|
|
362
|
+
// Shared fallback content must not expose the pathname captured during prerendering.
|
|
363
|
+
// The Suspense boundary keeps a query-string read (useSearchParams) to the 404 content.
|
|
364
|
+
|
|
365
|
+
import { Suspense } from 'react';
|
|
366
|
+
|
|
367
|
+
import { NotFoundPage } from '@donotdev/ui';
|
|
368
|
+
|
|
369
|
+
import { ClientLayout } from '${this.appImport(this.rootDir(),"ClientLayout")}';
|
|
370
|
+
|
|
371
|
+
export default function NotFound() {
|
|
372
|
+
return (
|
|
373
|
+
<ClientLayout serverCookies="" acceptLanguage={null}>
|
|
374
|
+
<Suspense fallback={null}>
|
|
375
|
+
<NotFoundPage showRequestedPath={false} />
|
|
376
|
+
</Suspense>
|
|
377
|
+
</ClientLayout>
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
`}generateGlobalNotFoundContent(){let e=`
|
|
381
|
+
<AppDocument lang={lang}>
|
|
382
|
+
<ClientLayout serverCookies="" acceptLanguage={null}>
|
|
383
|
+
<Suspense fallback={null}>
|
|
384
|
+
<NotFoundPage showRequestedPath={false} />
|
|
385
|
+
</Suspense>
|
|
386
|
+
</ClientLayout>
|
|
387
|
+
</AppDocument>`;return this.isMultilingual()?`// Generated by @donotdev/config - DO NOT EDIT
|
|
388
|
+
// 404 of an unknown URL (no root layout above [lang]): the app's AppDocument in the URL's
|
|
389
|
+
// language, which the proxy sets on the request (${Z.languageHeader}); a request the proxy
|
|
390
|
+
// does not see (API route, file) gets the default language (${this.options.defaultLanguage}).
|
|
391
|
+
|
|
392
|
+
import { headers } from 'next/headers';
|
|
393
|
+
import { Suspense } from 'react';
|
|
394
|
+
|
|
395
|
+
import { NotFoundPage } from '@donotdev/ui';
|
|
396
|
+
|
|
397
|
+
import { AppDocument } from './AppDocument';
|
|
398
|
+
import { ClientLayout } from './ClientLayout';
|
|
399
|
+
|
|
400
|
+
export { metadata } from './AppDocument';
|
|
401
|
+
|
|
402
|
+
const LANGUAGES: readonly string[] = ${JSON.stringify(this.options.languages)};
|
|
403
|
+
|
|
404
|
+
export default async function GlobalNotFound() {
|
|
405
|
+
const requested = (await headers()).get(${JSON.stringify(Z.languageHeader)});
|
|
406
|
+
const lang =
|
|
407
|
+
requested && LANGUAGES.includes(requested) ? requested : ${JSON.stringify(this.options.defaultLanguage)};
|
|
408
|
+
return (${e}
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
412
|
+
// 404 of an unknown URL: the app's AppDocument in the app's language (static).
|
|
413
|
+
|
|
414
|
+
import { Suspense } from 'react';
|
|
415
|
+
|
|
416
|
+
import { NotFoundPage } from '@donotdev/ui';
|
|
417
|
+
|
|
418
|
+
import { AppDocument } from './AppDocument';
|
|
419
|
+
import { ClientLayout } from './ClientLayout';
|
|
420
|
+
|
|
421
|
+
export { metadata } from './AppDocument';
|
|
422
|
+
|
|
423
|
+
const lang = ${JSON.stringify(this.options.defaultLanguage)};
|
|
424
|
+
|
|
425
|
+
export default function GlobalNotFound() {
|
|
426
|
+
return (${e}
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
`}isSessionOnlyRoute(e){return this.rendersSessionTree&&!!this.normalizeAuth(e.auth)}generateSessionPage(e){let t=this.appDirFor(e.path,"session"),r=`${"../".repeat(t.split("/").filter(Boolean).length)}${this.appDirFor(e.path).slice(1)}/${F("page","tsx").replace(/\.tsx$/,"")}`,n=["default"];e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path)&&n.push("generateMetadata"),this.writeGeneratedFile(`src/app${t}/${F("page","tsx")}`,`// Generated by @donotdev/config - DO NOT EDIT
|
|
430
|
+
// Per-request render of ${e.path} (visitors with an auth cookie): same page as the cached one.
|
|
431
|
+
|
|
432
|
+
export { ${n.join(", ")} } from '${r}';
|
|
433
|
+
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${F("page","tsx")}`,`src/app/**/${F("layout","tsx")}`,`src/app/**/${F("not-found","tsx")}`,`src/app/${F("global-not-found","tsx")}`,"src/app/**/*PageClient.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let n of s)if(await this.hasGenerationMarker(n))try{await this.pathResolver.remove(n),r++,this.logger.debug(`Cleaned generated file: ${n}`)}catch(o){this.logger.debug(`Could not clean file ${n}: ${o.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,t="site"){try{let s=this.appDirFor(e.path,t),r=`src/app${s}/${F("page","tsx")}`,n=this.pathResolver.resolveAppPath(r);if(this.pathResolver.pathExists(n)&&!await this.hasGenerationMarker(n))return this.logger.debug(`Skipping ${r} - 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},i=this.generatePageFileContent(o,t);this.writeGeneratedFile(r,i,`app page: ${s}`);let l=this.extractComponentName(o.filePath),c=this.calculateRelativeImportPath(o.relativePath,o.path);return o.metaExport?.namespace==="blog"&&this.hasDynamicSegment(o.path)?this.writeGeneratedFile(`src/app${s}/BlogPostClient.tsx`,this.generateBlogPostClientContent(l,c),`app blog client: ${s}`):this.isClientComponent(o.filePath)&&this.writeGeneratedFile(`src/app${s}/${l}Client.tsx`,this.generateMountedClientContent(l,c),`app client wrapper: ${s}`),!0}catch(s){return this.logger.debug(`Error generating page for route ${e.path}: ${s.message}`),!1}}convertRouteToAppPath(e){if(e===ye.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(s=>s.startsWith(":")?`[${s.slice(1)}]`:s==="*"?"[...slug]":s).join("/")}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=Tr(t),r=s.resolve(e);delete s.cache[r];let n=s(r);return n.default||n.i18nConfig||n}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e,t="site"){let s=this.extractComponentName(e.filePath),r=e.relativePath||e.file,n=this.calculateRelativeImportPath(r,e.path);if(e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path))return this.generateBlogPostRSCContent(e,s,n);let o=this.isClientComponent(e.filePath),i=this.normalizeAuth(e.auth)?e.auth:null,l=e.meta?.signedInRedirect??null,c=[...i?["AuthGuard"]:[],...l?["SignedInRedirect"]:[]],p=c.length?`import { ${c.join(", ")} } from '@donotdev/ui';
|
|
434
|
+
`:"",u=g=>{let h=l?`<SignedInRedirect to={${JSON.stringify(l)}}>${g}</SignedInRedirect>`:g;return i?`<AuthGuard auth={${JSON.stringify(i===!0?{required:!0}:i)}}>${h}</AuthGuard>`:h};return o?`// Generated by @donotdev/config - DO NOT EDIT
|
|
291
435
|
// This file will be regenerated when src/pages changes
|
|
292
436
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
293
437
|
|
|
294
|
-
import
|
|
295
|
-
|
|
296
|
-
|
|
438
|
+
${p}import ${s}Client from './${s}Client';
|
|
439
|
+
${t==="site"?this.onDemandParamsExport(e):""}
|
|
440
|
+
export default function ${s}Route() {
|
|
441
|
+
return ${u(`<${s}Client />`)};
|
|
442
|
+
}
|
|
443
|
+
`:c.length?`// Generated by @donotdev/config - DO NOT EDIT
|
|
444
|
+
// This file will be regenerated when src/pages changes
|
|
445
|
+
// To customize: edit ${e.filePath} or create manual app/** files
|
|
297
446
|
|
|
298
|
-
import ${
|
|
299
|
-
${this.
|
|
300
|
-
export
|
|
301
|
-
return
|
|
447
|
+
${p}import ${s} from '${n}';
|
|
448
|
+
${t==="site"?this.onDemandParamsExport(e):""}
|
|
449
|
+
export default function ${s}Route(props: Record<string, unknown>) {
|
|
450
|
+
return ${u(`<${s} {...props} />`)};
|
|
302
451
|
}
|
|
452
|
+
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
453
|
+
// This file will be regenerated when src/pages changes
|
|
454
|
+
// To customize: edit ${e.filePath} or create manual app/** files
|
|
303
455
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
export const dynamic = 'force-dynamic';
|
|
309
|
-
`:""}generateMetadataFunction(e,t,s){let r=Ye(s),o=Ke(s),n="`",l=r.map(i=>` '${i}': { href: ${n}\${baseUrl}\${currentPath}${n} }`).join(`,
|
|
456
|
+
import ${s} from '${n}';
|
|
457
|
+
${t==="site"?this.onDemandParamsExport(e):""}
|
|
458
|
+
export default ${s};
|
|
459
|
+
`}generateMetadataFunction(e,t,s){let r=ot(s),n=at(s),o="`",i=r.map(l=>` '${l}': { href: ${o}\${baseUrl}\${currentPath}${o} }`).join(`,
|
|
310
460
|
`);return`
|
|
311
461
|
import type { Metadata } from 'next';
|
|
312
462
|
import { readFileSync } from 'node:fs';
|
|
@@ -345,7 +495,7 @@ function getTranslationValue(translation, keyPath) {
|
|
|
345
495
|
// I18n config (inlined from build-time config)
|
|
346
496
|
const i18nConfig = ${JSON.stringify(s,null,2)};
|
|
347
497
|
const supportedLocales = ${JSON.stringify(r)};
|
|
348
|
-
const fallbackLocale = '${
|
|
498
|
+
const fallbackLocale = '${n}';
|
|
349
499
|
|
|
350
500
|
export async function generateMetadata({ params }): Promise<Metadata> {
|
|
351
501
|
// Detect locale from params or use fallback
|
|
@@ -356,7 +506,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
356
506
|
// Get base URL from environment or construct from request
|
|
357
507
|
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
|
|
358
508
|
(typeof process !== 'undefined' && process.env.VERCEL_URL
|
|
359
|
-
? ${
|
|
509
|
+
? ${o}https://\${process.env.VERCEL_URL}${o}
|
|
360
510
|
: '');
|
|
361
511
|
const currentPath = '${e.path}';
|
|
362
512
|
|
|
@@ -381,9 +531,9 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
381
531
|
}
|
|
382
532
|
}
|
|
383
533
|
|
|
384
|
-
const pageTitle = title ? ${
|
|
534
|
+
const pageTitle = title ? ${o}\${title} | \${siteName}${o} : siteName;
|
|
385
535
|
const pageDescription = description || '';
|
|
386
|
-
const pageImage = metaObject?.image || '${
|
|
536
|
+
const pageImage = metaObject?.image || '${pe}';
|
|
387
537
|
const pageType = metaObject?.type || 'website';
|
|
388
538
|
const pageKeywords = metaObject?.keywords;
|
|
389
539
|
const pageAuthor = metaObject?.author;
|
|
@@ -400,7 +550,7 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
400
550
|
title: pageTitle,
|
|
401
551
|
...(pageDescription && { description: pageDescription }),
|
|
402
552
|
type: pageType,
|
|
403
|
-
url: ${
|
|
553
|
+
url: ${o}\${baseUrl}\${currentPath}${o},
|
|
404
554
|
...(pageImage && { images: [pageImage] }),
|
|
405
555
|
siteName: siteName,
|
|
406
556
|
},
|
|
@@ -412,82 +562,248 @@ export async function generateMetadata({ params }): Promise<Metadata> {
|
|
|
412
562
|
},
|
|
413
563
|
alternates: {
|
|
414
564
|
languages: {
|
|
415
|
-
${
|
|
565
|
+
${i}
|
|
416
566
|
},
|
|
417
567
|
},
|
|
418
568
|
};
|
|
419
569
|
|
|
420
570
|
return metadata;
|
|
421
571
|
}
|
|
422
|
-
`}generateMetadataObject(e){let t={};return e.title&&(t.title=e.title),e.description&&(t.description=e.description),(e.title||e.description)&&(t.openGraph={},e.title&&(t.openGraph.title=e.title),e.description&&(t.openGraph.description=e.description),t.openGraph.type="website"),(e.title||e.description)&&(t.twitter={card:"summary_large_image"},e.title&&(t.twitter.title=e.title),e.description&&(t.twitter.description=e.description)),Object.keys(e).forEach(s=>{["title","description"].includes(s)||(t[s]=e[s])}),JSON.stringify(t,null,2)}extractComponentName(e){let s=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return s.charAt(0).toUpperCase()+s.slice(1)}async hasGenerationMarker(e){try{let t=await this.pathResolver.read(e,{format:"text"});return t&&t.includes("// Generated by @donotdev/config")}catch{return!1}}async generateMiddleware(e){let t=e.routes.filter(
|
|
423
|
-
`)
|
|
424
|
-
|
|
572
|
+
`}generateMetadataObject(e){let t={};return e.title&&(t.title=e.title),e.description&&(t.description=e.description),(e.title||e.description)&&(t.openGraph={},e.title&&(t.openGraph.title=e.title),e.description&&(t.openGraph.description=e.description),t.openGraph.type="website"),(e.title||e.description)&&(t.twitter={card:"summary_large_image"},e.title&&(t.twitter.title=e.title),e.description&&(t.twitter.description=e.description)),Object.keys(e).forEach(s=>{["title","description"].includes(s)||(t[s]=e[s])}),JSON.stringify(t,null,2)}extractComponentName(e){let s=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return s.charAt(0).toUpperCase()+s.slice(1)}async hasGenerationMarker(e){try{let t=await this.pathResolver.read(e,{format:"text"});return t&&t.includes("// Generated by @donotdev/config")}catch{return!1}}async generateMiddleware(e){this.removeLegacyMiddleware(),this.rendersSessionTree=!1;let t=e.routes.filter(c=>!!this.normalizeAuth(c.auth)),s=e.routes.filter(c=>c.meta?.signedInRedirect),r=this.usesCookieSession();(t.length>0||s.length>0)&&!r&&this.logger.debug("Auth session not in cookies (no Supabase createBrowserClient): pages use the client AuthGuard / SignedInRedirect only, no proxy auth redirects");let n=r?t:[],o=r?s:[],i=this.pathResolver.resolveAppPath(this.options.proxyPath),l=this.pathResolver.pathExists(i)&&!await this.hasGenerationMarker(i);if(!this.isMultilingual()&&!r){this.logger.debug("One language and no cookie session: no proxy.next.ts"),this.pathResolver.pathExists(i)&&!l&&await this.pathResolver.remove(i);return}if(l){this.logger.warn(`${this.options.proxyPath} is hand-written: not generating language routing / session refresh / auth redirects / per-request pages (add them to your proxy; every visitor gets the cached pages)`);return}this.isMultilingual()&&(this.appRouteSegments=await this.findAppRouteSegments()),this.writeGeneratedFile(this.options.proxyPath,this.generateMiddlewareContent(n,e.routes,o,r),"proxy"),this.rendersSessionTree=r}async findAppRouteSegments(){let e=this.pathResolver.getAppRoot(),t=this.pathResolver.resolveAppPath(O.next.appPages),s=await this.pathResolver._globWithNormalization([`${O.next.appPages}/**/{route,page}.${ie}.{ts,tsx,js,jsx}`],{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0}),r=new Set;for(let n of s){if(await this.hasGenerationMarker(n))continue;let[o]=n.slice(t.length+1).split("/").slice(0,-1).filter(i=>!/^\(.*\)$/.test(i));o&&o!=="[lang]"&&r.add(o)}return[...r].sort()}routePattern(e){return"^"+e.split("/").map(t=>t==="*"?".*":t.startsWith(":")?"[^/]+":t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("/")+"$"}generateMiddlewareContent(e,t=[],s=[],r=!1){let n=this.isMultilingual(),o=e.length>0,i=s.length>0,l=o||i,c=r||l,p=this.options.auth??{},u=e.map(N=>{let{role:k}=this.normalizeAuth(N.auth);return` { pattern: new RegExp(${JSON.stringify(this.routePattern(N.path))})${k?`, role: ${JSON.stringify(k)}`:""} },`}).join(`
|
|
573
|
+
`),g=s.map(N=>` { pattern: new RegExp(${JSON.stringify(this.routePattern(N.path))}), to: ${JSON.stringify(N.meta.signedInRedirect)} },`).join(`
|
|
574
|
+
`),h=[...new Set(t.map(N=>N.path))].map(N=>` new RegExp(${JSON.stringify(this.routePattern(N))}),`).join(`
|
|
575
|
+
`),f=` ${JSON.stringify("/((?!api|_next|.*\\..*).*)")},`,w=[...o?["hasRoleAccess"]:[],...n?["LANGUAGE_COOKIE",...l?["localizePath"]:[],"parseAcceptLanguage","readCookieValue","resolveLanguageRoute","splitLanguagePath"]:[]],y=["hasSupabaseSessionCookie","refreshSupabaseSession",...l?["type SupabaseProxySession"]:[]],v=l?`,
|
|
576
|
+
session: SupabaseProxySession['session']`:"",P=n?`,
|
|
577
|
+
language: string`:"",b=c?"{ request }":"",x=`/${Z.sessionSegment}`,T=`// Generated by @donotdev/config - DO NOT EDIT
|
|
578
|
+
// Request gate (Next 16 proxy)${n?`: one URL per language, the default language (${this.options.defaultLanguage}) at the
|
|
579
|
+
// root, the others under their prefix (resolveLanguageRoute in @donotdev/core)`:""}.${c?`
|
|
580
|
+
// Session: the Supabase cookie (createBrowserClient). No auth cookie: signed out, the
|
|
581
|
+
// page comes from the cache (src/app${this.treeDir("site")}, static). With one: verified and refreshed
|
|
582
|
+
// when expired (refreshSupabaseSession), then rendered per request with the refreshed
|
|
583
|
+
// cookies (src/app${this.rootDir()}${x}, an internal path: a direct hit is a 404); the browser
|
|
584
|
+
// gets the refreshed cookies on the response.`:""}${o?`
|
|
585
|
+
// Auth redirects for pages whose PageMeta sets \`auth\`, on the verified session.
|
|
586
|
+
// Redirect gate only: data access stays enforced by RLS, and the page's AuthGuard still
|
|
587
|
+
// runs on the client. Those pages have no cached copy: rendered per request for every
|
|
588
|
+
// visitor that is not redirected.`:""}${i?"\n// Signed-in redirects for pages whose PageMeta sets `signedInRedirect` (verified\n// session); the page's SignedInRedirect still runs on the client.":""}
|
|
425
589
|
|
|
426
590
|
import { NextResponse } from 'next/server';
|
|
427
591
|
import type { NextRequest } from 'next/server';
|
|
428
592
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
593
|
+
${w.length?`import { ${w.join(", ")} } from '@donotdev/core/server';
|
|
594
|
+
`:""}${c?`import { ${y.join(", ")} } from '@donotdev/supabase/server';
|
|
595
|
+
`:""}`,C=c?`
|
|
596
|
+
/** Supabase project of the cookie session (same env as src/config/providers.ts) */
|
|
597
|
+
const SUPABASE = supabaseProject(
|
|
598
|
+
process.env.NEXT_PUBLIC_SUPABASE_URL,
|
|
599
|
+
process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY
|
|
600
|
+
);
|
|
601
|
+
|
|
602
|
+
function supabaseProject(url: string | undefined, publicKey: string | undefined) {
|
|
603
|
+
if (!url || !publicKey) {
|
|
604
|
+
throw new Error(
|
|
605
|
+
'[dndev] Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLIC_KEY: the proxy refreshes the auth session on every page request.'
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
return { url, publicKey };
|
|
609
|
+
}
|
|
610
|
+
${n?`
|
|
611
|
+
/** Internal tree of the per-request pages (src/app/[lang]${x}), after the language: never a public URL */
|
|
612
|
+
const SESSION_SEGMENT = ${JSON.stringify(Z.sessionSegment)};
|
|
613
|
+
|
|
614
|
+
/** Internal URL path of a page rendered per request: \`/fr/compte\` \u2192 \`/fr${x}/compte\` */
|
|
615
|
+
function sessionPath(path: string): string {
|
|
616
|
+
const [, language, ...rest] = path.split('/');
|
|
617
|
+
return ['', language, SESSION_SEGMENT, ...rest].join('/');
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** A direct request for the internal tree (\`/fr${x}/\u2026\`) */
|
|
621
|
+
function isSessionTreePath(pathname: string): boolean {
|
|
622
|
+
return pathname.split('/').slice(1, 3).includes(SESSION_SEGMENT);
|
|
623
|
+
}
|
|
624
|
+
`:`
|
|
625
|
+
/** Internal tree of the per-request pages (src/app${x}): never a public URL */
|
|
626
|
+
const SESSION_TREE = ${JSON.stringify(x)};
|
|
627
|
+
|
|
628
|
+
/** Internal URL path of a page rendered per request */
|
|
629
|
+
function sessionPath(path: string): string {
|
|
630
|
+
return path === '/' ? SESSION_TREE : SESSION_TREE + path;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** A direct request for the internal tree */
|
|
634
|
+
function isSessionTreePath(pathname: string): boolean {
|
|
635
|
+
return pathname === SESSION_TREE || pathname.startsWith(\`\${SESSION_TREE}/\`);
|
|
636
|
+
}
|
|
637
|
+
`}${l?`
|
|
638
|
+
/** Session of a request without an auth cookie: signed out, nothing to verify */
|
|
639
|
+
const SIGNED_OUT: SupabaseProxySession['session'] = { user: null };
|
|
640
|
+
`:""}`:"",_=o?`
|
|
641
|
+
/** appConfig.auth.authRoute: where a signed-out visitor goes (null: page fallback) */
|
|
642
|
+
const AUTH_ROUTE: string | null = ${JSON.stringify(p.authRoute??null)};
|
|
643
|
+
/** appConfig.auth.roleRoute: where a visitor without the role goes (null: page fallback) */
|
|
644
|
+
const ROLE_ROUTE: string | null = ${JSON.stringify(p.roleRoute??null)};
|
|
645
|
+
|
|
646
|
+
const protectedRoutes: Array<{ pattern: RegExp; role?: string }> = [
|
|
647
|
+
${u}
|
|
432
648
|
];
|
|
433
649
|
|
|
434
|
-
|
|
435
|
-
function
|
|
436
|
-
|
|
437
|
-
// Example: check for auth cookie, JWT token, etc.
|
|
438
|
-
const authToken = request.cookies.get('auth-token')?.value;
|
|
439
|
-
return Boolean(authToken);
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
// Route matching function
|
|
443
|
-
function matchesProtectedRoute(pathname: string): boolean {
|
|
444
|
-
return protectedRoutes.some(pattern => {
|
|
445
|
-
if (pattern.includes(':')) {
|
|
446
|
-
// Dynamic route matching
|
|
447
|
-
const regex = new RegExp('^' + pattern.replace(/:[^/]+/g, '[^/]+') + '$');
|
|
448
|
-
return regex.test(pathname);
|
|
449
|
-
}
|
|
450
|
-
if (pattern.includes('*')) {
|
|
451
|
-
// Wildcard matching
|
|
452
|
-
const regex = new RegExp('^' + pattern.replace(/*/g, '.*') + '$');
|
|
453
|
-
return regex.test(pathname);
|
|
454
|
-
}
|
|
455
|
-
// Exact match
|
|
456
|
-
return pathname === pattern;
|
|
457
|
-
});
|
|
650
|
+
/** Protected pages exist only in the per-request tree (no cached copy) */
|
|
651
|
+
function isProtectedRoute(routePath: string): boolean {
|
|
652
|
+
return protectedRoutes.some((r) => r.pattern.test(routePath));
|
|
458
653
|
}
|
|
459
654
|
|
|
460
|
-
|
|
461
|
-
|
|
655
|
+
/** Redirect of a protected route, or null to let the page render. */
|
|
656
|
+
function authRedirect(
|
|
657
|
+
request: NextRequest${v},
|
|
658
|
+
routePath: string${P}
|
|
659
|
+
): NextResponse | null {
|
|
660
|
+
const route = protectedRoutes.find((r) => r.pattern.test(routePath));
|
|
661
|
+
if (!route) return null;
|
|
662
|
+
// Cannot tell (Supabase unreachable, several projects' cookies): the page's AuthGuard decides
|
|
663
|
+
if (session === null) return null;
|
|
664
|
+
|
|
665
|
+
if (!session.user) {
|
|
666
|
+
if (!AUTH_ROUTE) return null;
|
|
667
|
+
const url = new URL(${n?"localizePath(AUTH_ROUTE, language, LANGUAGE_ROUTING)":"AUTH_ROUTE"}, request.url);
|
|
668
|
+
url.searchParams.set('returnTo', request.nextUrl.pathname + request.nextUrl.search);
|
|
669
|
+
return NextResponse.redirect(url);
|
|
670
|
+
}
|
|
671
|
+
if (route.role && !hasRoleAccess(session.user.role, route.role)) {
|
|
672
|
+
if (!ROLE_ROUTE) return null;
|
|
673
|
+
return NextResponse.redirect(new URL(${n?"localizePath(ROLE_ROUTE, language, LANGUAGE_ROUTING)":"ROLE_ROUTE"}, request.url));
|
|
674
|
+
}
|
|
675
|
+
return null;
|
|
676
|
+
}
|
|
677
|
+
`:"",j=i?`
|
|
678
|
+
/** PageMeta \`signedInRedirect\`: where a signed-in visitor of the page goes */
|
|
679
|
+
const signedInRoutes: Array<{ pattern: RegExp; to: string }> = [
|
|
680
|
+
${g}
|
|
681
|
+
];
|
|
682
|
+
|
|
683
|
+
/** Redirect of a signed-in visitor, or null to let the page render. */
|
|
684
|
+
function signedInRedirect(
|
|
685
|
+
request: NextRequest${v},
|
|
686
|
+
routePath: string${P}
|
|
687
|
+
): NextResponse | null {
|
|
688
|
+
const route = signedInRoutes.find((r) => r.pattern.test(routePath));
|
|
689
|
+
if (!route) return null;
|
|
690
|
+
// A pending return-to wins: the page's AuthReturnTo takes the visitor there
|
|
691
|
+
if (request.nextUrl.searchParams.has('returnTo')) return null;
|
|
692
|
+
// Signed out, or cannot tell: the page renders (its SignedInRedirect decides on the client)
|
|
693
|
+
if (!session?.user) return null;
|
|
694
|
+
return NextResponse.redirect(new URL(${n?"localizePath(route.to, language, LANGUAGE_ROUTING)":"route.to"}, request.url));
|
|
695
|
+
}
|
|
696
|
+
`:"",re=n?`
|
|
697
|
+
const LANGUAGE_ROUTING = {
|
|
698
|
+
languages: ${JSON.stringify(this.options.languages)},
|
|
699
|
+
defaultLanguage: ${JSON.stringify(this.options.defaultLanguage)},
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
/** Request header of the URL's language, read by the 404 page (src/app/global-not-found) */
|
|
703
|
+
const LANGUAGE_HEADER = ${JSON.stringify(Z.languageHeader)};
|
|
462
704
|
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
705
|
+
/** First URL segments of the app's hand-written routes outside src/app/[lang] (route handlers) */
|
|
706
|
+
const APP_ROUTE_SEGMENTS: readonly string[] = ${JSON.stringify(this.appRouteSegments)};
|
|
707
|
+
`:"",ee=n||c?`
|
|
708
|
+
/** App pages (src/pages): API routes, files and hand-written app routes pass untouched */
|
|
709
|
+
const pageRoutes: RegExp[] = [
|
|
710
|
+
${h}
|
|
711
|
+
];
|
|
712
|
+
`:"",d=l?"session, ":"",ne=" // Verified session, refreshed when expired: the redirects and the server render\n // (refreshed cookies forwarded with `request`) see the same signed-in state\n const auth = await refreshSupabaseSession(request, SUPABASE.url, SUPABASE.publicKey);",E=`
|
|
713
|
+
request: NextRequest${v}${c?`,
|
|
714
|
+
personal: boolean`:""}
|
|
715
|
+
`,K=(N,k)=>`${o?`
|
|
716
|
+
const redirect = authRedirect(request, ${d}${N}${k});
|
|
717
|
+
if (redirect) return redirect;
|
|
718
|
+
`:""}${i?`
|
|
719
|
+
const signedIn = signedInRedirect(request, ${d}${N}${k});
|
|
720
|
+
if (signedIn) return signedIn;
|
|
721
|
+
`:""}`,z=(N,k)=>c?`
|
|
722
|
+
// Auth cookie: rendered per request with the visitor's cookies${o?`. Protected pages
|
|
723
|
+
// have no cached copy: per request for every visitor`:""}
|
|
724
|
+
if (personal${o?` || isProtectedRoute(${k})`:""}) {${N==="pathname"?"":`
|
|
725
|
+
const page = ${N};`}
|
|
726
|
+
return NextResponse.rewrite(new URL(sessionPath(${N==="pathname"?"pathname":"page"}) + search, request.url), { request });
|
|
727
|
+
}`:"",U;n?U=`
|
|
728
|
+
/** Language routing, redirects and render tree of a page request. */
|
|
729
|
+
function route(${E}): NextResponse {
|
|
730
|
+
const { pathname, search } = request.nextUrl;
|
|
731
|
+
const decision = resolveLanguageRoute(
|
|
732
|
+
pathname,
|
|
733
|
+
{
|
|
734
|
+
stored: readCookieValue(request.headers.get('cookie'), LANGUAGE_COOKIE),
|
|
735
|
+
preferred: parseAcceptLanguage(request.headers.get('accept-language')),
|
|
736
|
+
},
|
|
737
|
+
LANGUAGE_ROUTING
|
|
738
|
+
);
|
|
739
|
+
if (!pageRoutes.some((pattern) => pattern.test(decision.path))) {
|
|
740
|
+
// Not a page (API route, hand-written route, unknown URL): an unknown URL's 404
|
|
741
|
+
// renders in the URL's language
|
|
742
|
+
const url = splitLanguagePath(pathname, LANGUAGE_ROUTING);
|
|
743
|
+
request.headers.set(LANGUAGE_HEADER, url.language);
|
|
744
|
+
// Unprefixed and not a hand-written route: the app/[lang] route would read its first
|
|
745
|
+
// segment as a language. Served as an unknown URL of the default language instead.
|
|
746
|
+
if (!url.prefixed && !APP_ROUTE_SEGMENTS.includes(pathname.split('/')[1] ?? '')) {
|
|
747
|
+
return NextResponse.rewrite(
|
|
748
|
+
new URL('/' + LANGUAGE_ROUTING.defaultLanguage + pathname + search, request.url),
|
|
749
|
+
{ request }
|
|
750
|
+
);
|
|
470
751
|
}
|
|
752
|
+
return NextResponse.next({ request });
|
|
471
753
|
}
|
|
472
754
|
|
|
473
|
-
|
|
755
|
+
// Language redirects set no language cookie (the browser language store does)
|
|
756
|
+
if (decision.type === 'redirect') {
|
|
757
|
+
return NextResponse.redirect(
|
|
758
|
+
new URL(decision.location + search, request.url),
|
|
759
|
+
decision.permanent ? 308 : 307
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
${K("decision.path",", decision.language")}${z("decision.type === 'rewrite' ? decision.destination : pathname","decision.path")}
|
|
763
|
+
if (decision.type === 'rewrite') {
|
|
764
|
+
return NextResponse.rewrite(new URL(decision.destination + search, request.url)${c?", { request }":""});
|
|
765
|
+
}
|
|
766
|
+
return NextResponse.next(${b});
|
|
767
|
+
}
|
|
768
|
+
`:U=`
|
|
769
|
+
/** Redirects and render tree of a page request. */
|
|
770
|
+
function route(${E}): NextResponse {
|
|
771
|
+
const { ${c?"pathname, search":"pathname"} } = request.nextUrl;
|
|
772
|
+
if (!pageRoutes.some((pattern) => pattern.test(pathname))) {
|
|
773
|
+
return NextResponse.next({ request });
|
|
774
|
+
}
|
|
775
|
+
${K("pathname","")}${z("pathname","pathname")}
|
|
776
|
+
return NextResponse.next({ request });
|
|
474
777
|
}
|
|
778
|
+
`;let W;return c?W=`
|
|
779
|
+
export async function proxy(request: NextRequest) {
|
|
780
|
+
if (isSessionTreePath(request.nextUrl.pathname)) {
|
|
781
|
+
return new NextResponse(null, { status: 404 });
|
|
782
|
+
}
|
|
783
|
+
// No auth cookie: signed out. Nothing to verify or refresh, no cookie written: the
|
|
784
|
+
// page is served from the cache.
|
|
785
|
+
if (!hasSupabaseSessionCookie(request)) {
|
|
786
|
+
return route(request${l?", SIGNED_OUT":""}, false);
|
|
787
|
+
}
|
|
475
788
|
|
|
789
|
+
${ne}
|
|
790
|
+
// Signed in, or cannot tell (Supabase unreachable): per-request render. Signed out
|
|
791
|
+
// (refresh failed, session revoked): the cached page, with the cleared cookies.
|
|
792
|
+
return auth.apply(route(request, ${l?"auth.session, ":""}auth.session?.user !== null));
|
|
793
|
+
}
|
|
794
|
+
${U}`:W=`
|
|
795
|
+
export function proxy(request: NextRequest) {
|
|
796
|
+
return route(request);
|
|
797
|
+
}
|
|
798
|
+
${U}`,`${T}${C}${re}${ee}${_}${j}${W}
|
|
476
799
|
export const config = {
|
|
477
800
|
matcher: [
|
|
478
|
-
|
|
479
|
-
* Match all request paths except for the ones starting with:
|
|
480
|
-
* - api (API routes)
|
|
481
|
-
* - _next/static (static files)
|
|
482
|
-
* - _next/image (image optimization files)
|
|
483
|
-
* - favicon.ico (favicon file)
|
|
484
|
-
*/
|
|
485
|
-
'/((?!api|_next/static|_next/image|favicon.ico).*)',
|
|
801
|
+
${f}
|
|
486
802
|
],
|
|
487
803
|
};
|
|
488
|
-
`}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),
|
|
804
|
+
`}normalizeAuth(e){return e===!0?{}:!e||typeof e!="object"||!e.required&&!e.role&&!e.tier?null:{role:e.role,tier:e.tier}}usesCookieSession(){try{let e=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"));if(!{...e.dependencies,...e.devDependencies}["@donotdev/supabase"])return!1;let s=this.pathResolver.resolveAppPath("src/config/providers.ts");return this.pathResolver.pathExists(s)?this.pathResolver.readSync(s).includes("createBrowserClient("):!1}catch(e){return this.logger.debug(`Cookie session detection failed: ${e.message}`),!1}}removeLegacyMiddleware(){for(let e of["middleware.ts","src/middleware.ts"]){let t=this.pathResolver.resolveAppPath(e);try{this.pathResolver.pathExists(t)&&this.pathResolver.readSync(t).startsWith("// Auto-generated middleware by @donotdev/config")&&(this.pathResolver.removeSync(t),this.logger.debug(`Removed legacy generated ${e}`))}catch(s){this.logger.debug(`Could not remove legacy ${e}: ${s.message}`)}}}async generateAppRoutes(e){let t=this.generateAppRoutesContent(e.routes);this.writeGeneratedFile("src/app/routes.generated.ts",t,"app routes index")}generateAppRoutesContent(e){let t=e.map(s=>{let r=s.componentName||this.pathToComponentName(s.path),n=s.relativePath||s.file;if(!n)return this.logger.warn(`Route ${s.path} missing file path, skipping`),null;let o=n.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
|
|
489
805
|
path: '${s.path}',
|
|
490
|
-
component: lazy(() => import('${
|
|
806
|
+
component: lazy(() => import('${o}')),
|
|
491
807
|
auth: ${JSON.stringify(s.auth)},
|
|
492
808
|
meta: ${JSON.stringify(s.meta)}
|
|
493
809
|
}`}).filter(s=>s!==null).join(`,
|
|
@@ -526,7 +842,12 @@ export const routeManifest = {
|
|
|
526
842
|
};
|
|
527
843
|
|
|
528
844
|
export default pageRoutes;
|
|
529
|
-
`}pathToComponentName(e){return e.split("/").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")+"Page"}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let r=e.replace(/\.tsx$/,"").replace(/^src\//,""),
|
|
845
|
+
`}pathToComponentName(e){return e.split("/").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")+"Page"}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let r=e.replace(/\.tsx$/,"").replace(/^src\//,""),n=this.appDirFor(t).split("/").filter(Boolean).length;return`${"../".repeat(n+1)}${r}`}onDemandParamsExport(e){return this.convertRouteToAppPath(e.path).includes("[")?`
|
|
846
|
+
// Each URL renders on its first request, then is cached like the static pages (ISR)
|
|
847
|
+
export function generateStaticParams() {
|
|
848
|
+
return [];
|
|
849
|
+
}
|
|
850
|
+
`:""}hasDynamicSegment(e){return e.includes(":")||e.includes("[")}extractDynamicParam(e){let t=e.match(/:([a-zA-Z0-9_]+)/);if(t)return t[1];let s=e.match(/\[([^\]]+)\]/);return s?s[1]:"slug"}generateMountedClientContent(e,t){return this.options.ssr?`// Generated by @donotdev/config - DO NOT EDIT
|
|
530
851
|
// This file will be regenerated when src/pages changes
|
|
531
852
|
'use client';
|
|
532
853
|
|
|
@@ -575,7 +896,7 @@ export default function BlogPostClient() {
|
|
|
575
896
|
if (!mounted) return null;
|
|
576
897
|
return <${e} />;
|
|
577
898
|
}
|
|
578
|
-
`}calculateBlogContentImportPath(e){let s=this.
|
|
899
|
+
`}calculateBlogContentImportPath(e){let s=this.appDirFor(e).split("/").filter(Boolean);return`${"../".repeat(s.length+1)}content/blog/blog-content.generated`}generateBlogPostRSCContent(e,t,s){let r=this.extractDynamicParam(e.path);return`// Generated by @donotdev/config - DO NOT EDIT
|
|
579
900
|
// This file will be regenerated when src/pages changes
|
|
580
901
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
581
902
|
|
|
@@ -716,45 +1037,116 @@ export default async function BlogPostRoute({ params }: { params: Params }) {
|
|
|
716
1037
|
);
|
|
717
1038
|
}
|
|
718
1039
|
`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let s=this.pathResolver.readSync(t);return s?s.split(`
|
|
719
|
-
`).slice(0,50).some(
|
|
720
|
-
`)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:
|
|
721
|
-
<image:loc>${
|
|
1040
|
+
`).slice(0,50).some(n=>n.trim()==="'use client';"||n.trim()==='"use client";'):!1}catch{return!1}}};function as(a={}){return new it(a)}function L(a){return a?a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}function is(a){return a?a.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Fr=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function cs(a,e){let t;try{let s=new URL(a);if(s.protocol!=="https:"&&s.protocol!=="http:")throw new Error;t=s.hostname}catch{throw new Error(`[dndev] SEO: base URL "${a}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(Fr.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: production build with base URL "${a}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}function ls(a){return a.auth&&a.auth!==!1?!1:a.meta?.seo?.noindex!==!0}var Oe=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:n,siteName:o,crawlDelay:i=1,aiCrawlers:l="recommended",routes:c={},...p}=e;if(!n||!o)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:n,siteName:o,crawlDelay:i,aiCrawlers:l,routes:c,defaultImage:pe,twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...p},this.appRoot=p.appRoot||null,this.logger=G("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t){try{let s=this.generateRouteMetaTags(e.routes||[]),r={routes:e.routes||[],routeMetaTags:s,baseUrl:this.options.baseUrl,siteName:this.options.siteName},n=this.discoverBlogPosts(),o={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:r.routes.length,publicRoutes:r.routes.filter(i=>!i.auth||i.auth===!1).length,protectedRoutes:r.routes.filter(i=>i.auth&&i.auth.required).length,blogPosts:n.length};return this.options.generateRobotsTxt&&(o.robotsTxt=await this.generateRobotsTxt(r,t)),this.options.generateSitemap&&(o.sitemap=await this.generateSitemap(r,t,n)),n.length>0&&(o.rss=await this.generateRSSFeed(n,t)),o.manifest=await this.generateManifest(r,t),o}catch(s){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),s}}async generateRobotsTxt(e,t){let s=[];(e.routes||[]).forEach(n=>{if(n.auth&&n.auth.required){let o=n.path.startsWith("/")?n.path:`/${n.path}`;s.push(o)}}),s.push("/admin","/api");let r=this.generateRobotsTxtContent({disallowedPaths:[...new Set(s)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",r),{fileName:"robots.txt",content:r,disallowedPaths:s.length}}async generateSitemap(e,t,s=[]){let n=(e.routes||[]).filter(i=>!(!ls(i)||typeof i.path=="string"&&i.path.includes(":")||s.length>0&&i.path===this.options.blogPath)).map(i=>({url:i.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:i.path==="/"?"1.0":"0.8"}));if(s.length>0){n.push({url:this.options.blogPath,lastmod:s[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let i of s)n.push({url:`${this.options.blogPath}/${i.slug}`,lastmod:i.date,changefreq:"monthly",priority:"0.6",image:i.image||null})}let o=this.generateSitemapContent(n);return await t("sitemap.xml",o),{fileName:"sitemap.xml",content:o,publicRoutes:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:s}=this.options,r=[];for(let n of e||[]){if(!ls(n)||typeof n.path!="string")continue;let o=n.path===s||n.path.startsWith(`${s}/`);if(!(t.length>0&&o))if(n.path.includes(":")){if(o)continue;r.push({path:n.path,...n.meta?.entity&&{collection:n.meta.entity}})}else r.push({path:n.path})}if(t.length>0){r.push({path:s,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let n of t)r.push({path:`${s}/${n.slug}`,priority:.6,changeFrequency:"monthly",...n.date&&{lastModified:n.date}})}return r}async generateManifest(e,t){let s={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,protectedRoutes:e.routes?.filter(n=>n.auth&&n.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},r=JSON.stringify(s,null,2);return await t("seo-manifest.json",r),{fileName:"seo-manifest.json",content:r,manifest:s}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:n}=e,o=c=>c?c==="*"?"*":c.startsWith("/")?c:`/${c}`:"/",i=["User-agent: *",...s.map(c=>`Disallow: ${o(c)}`),...t.map(c=>`Allow: ${o(c)}`)];n&&i.push(`Crawl-delay: ${n}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Or(l))),i.join(`
|
|
1041
|
+
`)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:n,changefreq:o,priority:i,image:l})=>{let c=[` <loc>${L(this.options.baseUrl)}${L(r)}</loc>`];return n&&c.push(` <lastmod>${n}</lastmod>`),o&&c.push(` <changefreq>${o}</changefreq>`),i&&c.push(` <priority>${i}</priority>`),l&&c.push(` <image:image>
|
|
1042
|
+
<image:loc>${L(this.options.baseUrl)}${L(l)}</image:loc>
|
|
722
1043
|
</image:image>`),` <url>
|
|
723
|
-
${
|
|
1044
|
+
${c.join(`
|
|
724
1045
|
`)}
|
|
725
1046
|
</url>`}).join(`
|
|
726
1047
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
727
1048
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
|
|
728
1049
|
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
|
|
729
1050
|
${s}
|
|
730
|
-
</urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let
|
|
731
|
-
`)){let
|
|
732
|
-
<title><![CDATA[${
|
|
733
|
-
<link>${
|
|
734
|
-
<guid>${
|
|
735
|
-
<description><![CDATA[${
|
|
736
|
-
<pubDate>${
|
|
737
|
-
<category>${
|
|
738
|
-
<enclosure url="${
|
|
1051
|
+
</urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let n=t.path.split("/").filter(Boolean);n.length>0&&(s=`${n[n.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let n=t.path.split("/").filter(Boolean);n.length>0&&(r=`Explore ${n[n.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=R.getInstance(),t=e.resolvePath("src/content/blog",this.appRoot);try{if(!e.pathExists(t))return[];let s=e.readdirSync(t).filter(n=>n.endsWith("_en.md"));if(s.length===0)return[];let r=[];for(let n of s){let o=e.resolvePath(n,t),i=e.readSync(o,{format:"text"}),l=n.replace(/_en\.md$/,""),c=i.match(/^---\r?\n([\s\S]*?)\r?\n---/),p={};if(c)for(let g of c[1].split(`
|
|
1052
|
+
`)){let h=g.indexOf(":");h!==-1&&(p[g.slice(0,h).trim()]=g.slice(h+1).trim())}let u=p.date;if(!u)try{u=e.statSync(o).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no frontmatter date, using file mtime (${u})`)}catch{u=new Date().toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no date and file stat failed, using today`)}r.push({slug:l,title:p.title||l,description:p.description||"",date:u,tags:p.tags?p.tags.split(",").map(g=>g.trim()):[],image:p.image||null})}return r.sort((n,o)=>o.date.localeCompare(n.date)),this.logger.info(`\u{1F4DD} Discovered ${r.length} blog post(s) in src/content/blog/`),r}catch(s){return this.logger.debug(`Blog content discovery skipped: ${s.message}`),[]}}async generateRSSFeed(e,t){let s=e.map(n=>` <item>
|
|
1053
|
+
<title><![CDATA[${is(n.title)}]]></title>
|
|
1054
|
+
<link>${L(this.options.baseUrl)}${L(this.options.blogPath)}/${L(n.slug)}</link>
|
|
1055
|
+
<guid>${L(this.options.baseUrl)}${L(this.options.blogPath)}/${L(n.slug)}</guid>
|
|
1056
|
+
<description><![CDATA[${is(n.description)}]]></description>
|
|
1057
|
+
<pubDate>${n.date?new Date(n.date).toUTCString():""}</pubDate>${n.tags.length?`
|
|
1058
|
+
<category>${L(n.tags.join(", "))}</category>`:""}${n.image?`
|
|
1059
|
+
<enclosure url="${L(this.options.baseUrl)}${L(n.image)}" type="image/png" length="0"/>`:""}
|
|
739
1060
|
</item>`).join(`
|
|
740
1061
|
`),r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
741
1062
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
742
1063
|
<channel>
|
|
743
|
-
<title>${
|
|
744
|
-
<link>${
|
|
745
|
-
<description>${
|
|
1064
|
+
<title>${L(this.options.siteName)}</title>
|
|
1065
|
+
<link>${L(this.options.baseUrl)}${L(this.options.blogPath)}</link>
|
|
1066
|
+
<description>${L(this.options.siteName)} Blog</description>
|
|
746
1067
|
<language>en</language>
|
|
747
|
-
<atom:link href="${
|
|
1068
|
+
<atom:link href="${L(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
748
1069
|
${s}
|
|
749
1070
|
</channel>
|
|
750
|
-
</rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(
|
|
751
|
-
`)}function
|
|
752
|
-
`];a.description&&
|
|
753
|
-
`);for(let
|
|
754
|
-
`),
|
|
755
|
-
`),
|
|
756
|
-
`),
|
|
757
|
-
`)}function or(a){return a==="/"||a===""?"Home":(a.split("/").filter(Boolean).pop()||"Home").split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}var et=class extends F{constructor(e={}){super(ue,e);let t=$.getInstance(),s=N("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let o=e.seo?.baseUrl;if(!o&&r){let i=r.trim().replace(/\/+$/,"");o=/^https?:\/\//i.test(i)?i:`https://${i}`}o?s.debug(`Found app URL: ${o}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let n=e.siteName||e.seo?.siteName||null;if(s.verbose(`Name: ${n||"Not found"}`),s.verbose(`URL: ${o||"Not found"}`),n&&s.debug(` - Site name from appConfig: "${n}"`),e.seo?.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let l=[];if(o||l.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),n||l.push("siteName (APP_NAME in src/config/app.ts)"),l.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),l.forEach(i=>s.warn(` - ${i}`)),s.warn(""),s.warn(" To fix:"),o||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),n||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this._baseUrl=o,this._siteName=n,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this.seoGenerator=new Ce({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,generateSitemap:this.options.generateSitemap,baseUrl:o,siteName:n,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(r,o)=>{if(!r){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${r}`,o,r)},s=await this.seoGenerator.generateSEOFiles(e,t);if(s.robotsTxt&&!s.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${s.robotsTxt.disallowedPaths||0} disallowed paths`),s.sitemap&&!s.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${s.sitemap.publicRoutes||0} routes`),s.rss&&!s.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${s.rss.postCount||0} blog posts`),s.manifest&&!s.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json"),this._llmsTxtEnabled){let r=this.seoGenerator.discoverBlogPosts(),o=this.pathResolver.getAppRoot(),n=qt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});if(n&&(this.writeGeneratedFile("public/llms.txt",n,"llms.txt"),this.logger.info("\u{1F4C4} llms.txt")),r.length>0){let l=Yt({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:o,blogPosts:r,logger:this.logger});l&&(this.writeGeneratedFile("public/llms-full.txt",l,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))}}}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function Kt(a={}){return new et(a)}function Xt(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:o}=r;return o||(s.externals||(s.externals={}),it.forEach(n=>{s.externals[n]=`commonjs ${n}`})),t.webpack?t.webpack(s,r):s}})}var Zt=/--(?:font-family|font-headline)\s*:\s*([^;]+);/g,Qt=/['"]([^'"]+)['"]/g,ge=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(s,...r)=>{this.options.debug}},this.patterns={selectors:{...Te.selectors,...this.options.customPatterns?.selectors},themes:{...Te.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let s=t.split("-").filter(n=>n.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((n,l)=>{let i=n.replace(/[^a-zA-Z0-9]/g,"");return i?l===0?i.toLowerCase():i.charAt(0).toUpperCase()+i.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],o,n=this.pathResolver.normalizePath(t),l=this._stripComments(e),i=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=i.exec(l))!==null;){let[,p,c,u]=o;if(!p||!u)continue;let g=c.match(this.patterns.themes.themeIcon),f=c.match(this.patterns.themes.themeIsDark),h={name:p,displayName:u,isDark:f?f[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${p} (${u})`),r.push(h),s.themes.set(p,{name:p,displayName:u,isDark:h.isDark,file:n,variables:new Set,meta:h.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${n}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let o=r.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?s==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractFontFamilies(e){if(!e||typeof e!="string")return[];let t=this._stripComments(e),s=new Set,r;for(Zt.lastIndex=0;(r=Zt.exec(t))!==null;){let o=r[1],n;for(Qt.lastIndex=0;(n=Qt.exec(o))!==null;){let l=n[1].trim();l&&s.add(l)}}return Array.from(s)}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let o=r.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let n=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];n&&t.push(`Theme class "${n}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let n=this.validateCSS(e);return{themes:o,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:n}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};var Ne=class extends G{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new ge(t,{debug:s.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:s}=e;this.logger.debug(`Scanning ${t.length} framework + ${s.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",s),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),s.length>0?(this.logger.debug(`Consumer files found: ${s.length}`),this.logger.debug("Consumer files:",s)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t),await this._processConsumerFiles(s);let r=this._serializeThemes();return this.logger.debug(`Discovered ${r.length} themes:`,r.map(o=>o.name)),{themes:r,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort()}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return Ie.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractClasses(s,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"framework"),this.cssExtractor.extractKeyframes(s,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning framework file ${t}: ${s.message}`)}}async _processConsumerFiles(e){for(let t of e)try{let s=await this.pathResolver.read(t,{format:"text"}),r=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(s,r,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(r)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${t}: ${s.message}`)}}_addEssentialThemes(){Ie.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var tt=class extends F{constructor(e={}){super(Ne,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new ge(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(o=>!o.essential).length,r=t.length;if(r===0)throw Wt("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
1071
|
+
</rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,r=e.routes?.filter(n=>n.auth&&n.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}},lt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],ct=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Or(a){let e=["# AI Crawler Management"];if(a==="block-all"){for(let t of[...lt,...ct])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(a==="allow-all"){for(let t of[...lt,...ct])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of lt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of ct)e.push(`User-agent: ${t}`,"Allow: /","");return e}function Pe(a){return a.replace(/\s+/g," ").trim()}function ps(a){let e=[`# ${Pe(a.name)}`,""];a.summary&&e.push(`> ${Pe(a.summary)}`,"");for(let t of a.sections)if(t.links.length!==0){e.push(`## ${Pe(t.heading)}`,"");for(let s of t.links){let r=`- [${Pe(s.title)}](${s.url})`;e.push(s.description?`${r}: ${Pe(s.description)}`:r)}e.push("")}return e.join(`
|
|
1072
|
+
`)}var Ir="dndev",Lr="crud",Ur="entity-";function us(a,e,t){return e?a?.[e]?.[t]:void 0}function H(a){return typeof a=="string"&&a.trim()!==""?a.trim():void 0}function Mr(a,e,t){let s=a.metaExport||a.meta||{},r=s.seo||{},n=us(e,s.namespace,t),o=H(n?.title)??H(r.title)??H(n?.meta?.fullTitle)??H(r.fullTitle),i=r.description===null?void 0:H(r.description)??H(n?.description);return{...o&&{title:o},...i&&{description:i}}}function gs(a){let{siteName:e,description:t,baseUrl:s,sitemapRoutes:r,routes:n,blogPosts:o=[],blogPath:i="/blog",translations:l,language:c}=a,p=us(l,Ir,c)?.seo,u=H(p?.llmsPages),g=H(p?.llmsBlog);if(!u||!g)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${c}".`);let h=new Map(n.map(b=>[b.path,b])),f=new Map(o.map(b=>[`${i}/${b.slug}`,b])),w=r.map(({path:b,collection:x})=>{let T=f.get(b);if(T)return{path:b,title:T.title,...H(T.description)&&{description:H(T.description)},section:g};if(x)return{path:b,collection:x};let C=y(b);if(b===i&&!C.title)return{path:b,...C,title:g};if(!C.title){let _=h.get(b),j=(_?.metaExport||_?.meta)?.namespace;throw new Error(`[dndev] llms.txt: page "${b}" has no title in "${c}". Add "title" to `+(j?`${j}_${c}.json`:"its translations")+" or `seo: { title }` to its PageMeta.")}return{path:b,...C}});function y(b){let x=h.get(b);return x?Mr(x,l,c):{}}let v={},P={};for(let[b,x]of Object.entries(l||{})){if(b===Lr&&x?.[c]&&(P[b]=x[c]),!b.startsWith(Ur))continue;x?.[c]&&(P[b]=x[c]);let T=H(x?.[c]?.namePlural);T&&(v[b]=T)}return{name:e,...H(t)&&{summary:H(t)},baseUrl:s,pagesHeading:u,routes:w,entityHeadings:v,language:c,translations:P}}function hs(a={}){let{siteName:e,baseUrl:t,blogPosts:s=[],blogPath:r="/blog",appRoot:n,logger:o}=a;if(!e||!t)return null;if(s.length===0)return o?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=R.getInstance(),l=n?i.resolvePath("src/content/blog",n):null;if(!l||!i.pathExists(l))return null;let c=[`# ${e}
|
|
1073
|
+
`];a.description&&c.push(`> ${a.description}
|
|
1074
|
+
`);for(let p of s){let u=i.resolvePath(`${p.slug}_en.md`,l);try{let g=i.readSync(u,{format:"text"});if(!g)continue;let h=g.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),f=`${t}${r}/${p.slug}`;c.push(`## ${p.title}
|
|
1075
|
+
`),c.push(`Source: ${f}
|
|
1076
|
+
`),p.date&&c.push(`Date: ${p.date}
|
|
1077
|
+
`),c.push(h.trim()),c.push("")}catch{o?.debug?.(`llms-full.txt: could not read ${p.slug}`)}}return c.join(`
|
|
1078
|
+
`)}var fs=`src/app/sitemap.xml/${F("route","ts")}`,ds=`src/app/llms.txt/${F("route","ts")}`;function ms(a){let e=a.filter(r=>r.path.includes(":")),t=`${a.length-e.length} static + ${e.length} dynamic`;if(e.length===0)return t;let s=e.map(r=>`${r.path} \u2192 ${r.collection??"no collection"}`);return`${t} (${s.join(", ")})`}var pt=class extends M{constructor(e={}){super(de,e);let t=R.getInstance(),s=G("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let n=e.baseUrl;if(!n&&r){let l=r.trim().replace(/\/+$/,"");n=/^https?:\/\//i.test(l)?l:`https://${l}`}n?s.debug(`Found app URL: ${n}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let o=e.siteName||null;if(s.verbose(`Name: ${o||"Not found"}`),s.verbose(`URL: ${n||"Not found"}`),o&&s.debug(` - Site name from appConfig: "${o}"`),e.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let i=[];if(n||i.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),o||i.push("siteName (APP_NAME in src/config/app.ts)"),i.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),i.forEach(l=>s.warn(` - ${l}`)),s.warn(""),s.warn(" To fix:"),n||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),o||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this.options.isDev||cs(n,"NEXT_PUBLIC_APP_URL"),this._baseUrl=n,this._siteName=o,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this._sitemapEnabled=this.options.generateSitemap!==!1,this.seoGenerator=new Oe({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,baseUrl:n,siteName:o,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e,generateSitemap:!1})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(r,n)=>{if(!r){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${r}`,n,r)},s=await this.seoGenerator.generateSEOFiles(e,t);if(this._sitemapEnabled&&await this.generateSitemapRoute(e.routes||[]),s.robotsTxt&&!s.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${s.robotsTxt.disallowedPaths||0} disallowed paths`),s.sitemap&&!s.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${s.sitemap.publicRoutes||0} routes`),s.rss&&!s.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${s.rss.postCount||0} blog posts`),s.manifest&&!s.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json"),this._llmsTxtEnabled){let r=this.seoGenerator.discoverBlogPosts(),n=this.pathResolver.getAppRoot();if(await this.generateLlmsTxtRoute(e.routes||[],r),r.length>0){let o=hs({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:n,blogPosts:r,logger:this.logger});o&&(this.writeGeneratedFile("public/llms-full.txt",o,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))}}}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}useLanguages(e){this._languageRouting=e}async generateSitemapRoute(e){if(!this._languageRouting)throw new Error("SEO handler: languages not set before sitemap generation (runDiscoveries calls useLanguages)");let t=this.seoGenerator.getSitemapRoutes(e,this.seoGenerator.discoverBlogPosts()),s=this.serverCrudReader(t),r=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1079
|
+
// Regenerated on every build from src/pages (PageMeta) and appConfig.
|
|
1080
|
+
// Public routes + one URL per published record of each dynamic route's entity
|
|
1081
|
+
// (read with the public role). Keep a page out with \`seo: { noindex: true }\`.
|
|
1082
|
+
|
|
1083
|
+
import { HIDDEN_STATUSES, languageUrls } from '@donotdev/core/server';
|
|
1084
|
+
import type { LanguageRouting } from '@donotdev/core/server';
|
|
1085
|
+
import { buildSitemap, formatSitemapXml } from '@donotdev/core/next';
|
|
1086
|
+
import type { SitemapRoute } from '@donotdev/core/next';
|
|
1087
|
+
${s.imports}
|
|
1088
|
+
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
1089
|
+
export const revalidate = ${this.revalidate()};
|
|
1090
|
+
|
|
1091
|
+
const BASE_URL = ${JSON.stringify(this._baseUrl)};
|
|
1092
|
+
|
|
1093
|
+
const LANGUAGE_ROUTING: LanguageRouting = ${JSON.stringify(this._languageRouting)};
|
|
1094
|
+
|
|
1095
|
+
const ROUTES: SitemapRoute[] = ${JSON.stringify(t,null,2)};
|
|
1096
|
+
${s.setup}
|
|
1097
|
+
export async function GET(): Promise<Response> {
|
|
1098
|
+
const entries = await buildSitemap(ROUTES, {
|
|
1099
|
+
baseUrl: BASE_URL,
|
|
1100
|
+
routing: LANGUAGE_ROUTING,
|
|
1101
|
+
languageUrls,
|
|
1102
|
+
hiddenStatuses: HIDDEN_STATUSES,${s.expr?`
|
|
1103
|
+
crud: ${s.expr},`:""}
|
|
1104
|
+
});
|
|
1105
|
+
return new Response(formatSitemapXml(entries), {
|
|
1106
|
+
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
`;this.writeGeneratedFile(fs,r,"sitemap route");let n=this.pathResolver.resolveAppPath("public/sitemap.xml");this.pathResolver.pathExists(n)&&await this.pathResolver.remove(n),this.logger.info(`\u{1F5FA}\uFE0F sitemap: ${ms(t)} (${fs}); URL count printed by dndev build`)}useTranslations(e){this._translations=e}async generateLlmsTxtRoute(e,t){if(!this._languageRouting||!this._translations)throw new Error("SEO handler: languages/translations not set before llms.txt generation (runDiscoveries calls useLanguages and useTranslations)");let s=gs({siteName:this._siteName,description:this._siteDescription,baseUrl:this._baseUrl,sitemapRoutes:this.seoGenerator.getSitemapRoutes(e,t),routes:e,blogPosts:t,blogPath:this.seoGenerator.options.blogPath,translations:this._translations,language:this._languageRouting.defaultLanguage}),r=this.serverCrudReader(s.routes),n=this.appDependsOn("entities"),o=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1110
|
+
// Regenerated on every build from src/pages (PageMeta), translations and appConfig.
|
|
1111
|
+
// Same URLs as app/sitemap.xml: public pages + one link per published record of each
|
|
1112
|
+
// dynamic route's entity. Keep a page out with \`seo: { noindex: true }\`.
|
|
1113
|
+
|
|
1114
|
+
import { HIDDEN_STATUSES, deriveEntitySeo } from '@donotdev/core/server';
|
|
1115
|
+
import { buildLlmsTxt } from '@donotdev/core/next';
|
|
1116
|
+
import type { LlmsTxtSource } from '@donotdev/core/next';
|
|
1117
|
+
${n?`import * as entities from 'entities';
|
|
1118
|
+
`:""}${r.imports}
|
|
1119
|
+
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
1120
|
+
export const revalidate = ${this.revalidate()};
|
|
1121
|
+
|
|
1122
|
+
const SOURCE: LlmsTxtSource = ${JSON.stringify(s,null,2)};
|
|
1123
|
+
${r.setup}
|
|
1124
|
+
export async function GET(): Promise<Response> {
|
|
1125
|
+
const body = await buildLlmsTxt({
|
|
1126
|
+
...SOURCE,
|
|
1127
|
+
entities: ${n?"entities":"{}"},
|
|
1128
|
+
deriveEntitySeo,
|
|
1129
|
+
hiddenStatuses: HIDDEN_STATUSES,${r.expr?`
|
|
1130
|
+
crud: ${r.expr},`:""}
|
|
1131
|
+
});
|
|
1132
|
+
return new Response(body, {
|
|
1133
|
+
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
`;this.writeGeneratedFile(ds,o,"llms.txt route"),this.logger.info(`\u{1F4C4} llms.txt: ${ms(s.routes)} (${ds})`)}appDependsOn(e){let t=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"),{format:"json"});return!!(t?.dependencies?.[e]||t?.devDependencies?.[e])}serverCrudReader(e){let t=e.filter(s=>s.collection);if(t.length===0)return{imports:"",setup:"",expr:null};if(this.appDependsOn("@donotdev/supabase"))return{imports:`import { createPublicServerClient, SupabaseCrudAdapter } from '@donotdev/supabase/server';
|
|
1137
|
+
`,setup:`
|
|
1138
|
+
// Public (anonymous) reader: RLS returns what a signed-out visitor can read.
|
|
1139
|
+
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
|
1140
|
+
const SUPABASE_PUBLIC_KEY = process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY;
|
|
1141
|
+
if (!SUPABASE_URL || !SUPABASE_PUBLIC_KEY) {
|
|
1142
|
+
throw new Error(
|
|
1143
|
+
'[dndev] Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLIC_KEY: the sitemap and llms.txt list published records.'
|
|
1144
|
+
);
|
|
1145
|
+
}
|
|
1146
|
+
const CRUD = new SupabaseCrudAdapter(
|
|
1147
|
+
createPublicServerClient(SUPABASE_URL, SUPABASE_PUBLIC_KEY)
|
|
1148
|
+
);
|
|
1149
|
+
`,expr:"CRUD"};throw new Error(`[dndev] SEO: ${t.map(s=>s.path).join(", ")} list published records, but the app's backend provider has no server reader (supported: @donotdev/supabase). Mark these pages \`seo: { noindex: true }\`.`)}createManifestContent(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}formatAPIResponse(e){return this.disabled?{}:this.seoGenerator.formatAPIResponse(e)}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function vs(a={}){return new pt(a)}function ys(a={}){let{debug:e}=a;return(t={})=>({...t,webpack:(s,r)=>{let{isServer:n}=r;return n||(s.externals||(s.externals={}),mt.forEach(o=>{s.externals[o]=`commonjs ${o}`})),t.webpack?t.webpack(s,r):s}})}var me=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:{...ze.selectors,...this.options.customPatterns?.selectors},themes:{...ze.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(o=>o.length>0);if(s.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let r=s.map((o,i)=>{let l=o.replace(/[^a-zA-Z0-9]/g,"");return l?i===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!r||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(r)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${r}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(r)?`${r}Var`:r}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,s){let r=[],n,o=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(n=l.exec(i))!==null;){let[,c,p,u]=n;if(!c||!u)continue;let g=p.match(this.patterns.themes.themeIcon),h=p.match(this.patterns.themes.themeIsDark),f={name:c,displayName:u,isDark:h?h[1]==="1":!1,meta:{icon:g?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${u})`),r.push(f),s.themes.set(c,{name:c,displayName:u,isDark:f.isDark,file:o,variables:new Set,meta:f.meta})}return r.length>0&&this._debug(`Extracted ${r.length} themes from ${o}`),r}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(r=>{let n=r.slice(1);n.startsWith("_")||t.classes.add(n)})}extractVariables(e,t,s){(e.match(this.patterns.selectors.variable)||[]).forEach(n=>{n.startsWith("--")&&n.length>2?s==="framework"?t.variables.framework.add(n):t.variables.consumer.add(n):this._debug(`Skipping invalid CSS variable: ${n}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(r=>{let n=r.replace("@keyframes","").trim();n&&t.keyframes.add(n)})}validateCSS(e){let t=[],s=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return s&&s.forEach(n=>{t.push(`Possible malformed CSS variable: ${n}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(n=>{if(!n.includes("--theme-label")&&n.includes("--")){let o=n.match(/\.([a-z][a-z0-9-]+)/)?.[1];o&&t.push(`Theme class "${o}" missing --theme-label`)}}),t}extractAll(e,t,s="consumer"){let r={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},n=this.extractThemes(e,t,r);this.extractClasses(e,r),this.extractVariables(e,r,s),this.extractKeyframes(e,r);let o=this.validateCSS(e);return{themes:n,classes:Array.from(r.classes),variables:{framework:Array.from(r.variables.framework),consumer:Array.from(r.variables.consumer),all:[...Array.from(r.variables.framework),...Array.from(r.variables.consumer)].sort()},keyframes:Array.from(r.keyframes),warnings:o}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};var bs="@donotdev/components/styles",jr=/@import\s+['"](\.[^'"]+)['"]\s*;/g,Ie=class extends X{constructor(e,t,s={}){super(t,s),this.cssExtractor=e||new me(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);let r=await this._processConsumerFiles(s),n=this._serializeThemes(),o=jt({frameworkCss:this._readFrameworkTokenCss(),appCss:r});return this.logger.debug("Theme font families:",o),this.logger.debug(`Discovered ${n.length} themes:`,n.map(i=>i.name)),{themes:n,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(),fontFamilies:o}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return Be.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){let t=[];for(let s of e)try{let r=await this.pathResolver.read(s,{format:"text"});t.push(r);let n=this.pathResolver.normalizePath(s);this.cssExtractor.extractThemes(r,n,this.discovered),this.cssExtractor.extractVariables(r,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(n)}`)}catch(r){this.logger.debug(`Error scanning consumer file ${s}: ${r.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(bs,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw new Error(`Theme discovery: cannot resolve ${bs} (framework font defaults)`);let t=new Set,s=r=>{if(t.has(r))return"";t.add(r);let n=this.pathResolver.readSync(r,{format:"text"});if(typeof n!="string")throw new Error(`Theme discovery: cannot read ${r}`);let o=this.pathResolver.getDirname(r);return n.replace(jr,(i,l)=>s(this.pathResolver.resolvePath(l,o)))};return s(e)}_addEssentialThemes(){Be.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};var ut=class extends M{constructor(e={}){super(Ie,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new me(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],s=t.filter(n=>!n.essential).length,r=t.length;if(r===0)throw os("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${r} discovered${s>0?` (${s} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}formatAPIResponse(e){return{themes:e.themes,variables:e.variables,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(e){await this.generateAPIHandler(e)}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:s}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
758
1150
|
// Generated at: ${new Date().toISOString()}
|
|
759
1151
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
760
1152
|
|
|
@@ -786,22 +1178,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
786
1178
|
timestamp: Date.now(),
|
|
787
1179
|
};
|
|
788
1180
|
}
|
|
789
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1181
|
+
globalThis._DNDEV_CONFIG_.${J.themes} = themeConfig;
|
|
790
1182
|
}
|
|
791
1183
|
|
|
792
1184
|
// Export for compatibility
|
|
793
1185
|
export default themeConfig;
|
|
794
|
-
`}
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
import { useThemeStore } from '@donotdev/stores';
|
|
799
|
-
|
|
800
|
-
export function useTheme() {
|
|
801
|
-
return useThemeStore();
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
export default useTheme;
|
|
805
|
-
`}};function es(a={}){return new tt(a)}function ts({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:o,assetOptions:n,seoOptions:l,pwaOptions:i,serverShimOptions:p,appUrl:c,isDev:u,logger:g}){let f=s.debug??a,h=r.debug??a,b=o.debug??a,d=n.debug??a,m=l.debug??a,S=i.debug??a,O=p.debug??a,T=s.verbose??e,M=r.verbose??e,A=o.verbose??e,L=n.verbose??e,J=l.verbose??e,ae=i.verbose??e,ee=p.verbose??e,v={debug:a,verbose:e,generateManifest:t},ie=s.disabled?null:Ht({...v,...s,debug:f,verbose:T});a&&g.debug(`Route handler created: ${ie?"enabled":"disabled"} (debug: ${f})`);let x=es({...v,...r,debug:h,verbose:M}),K=zt({...v,...o,debug:b,verbose:A}),H=Lt({...v,...n,debug:d,verbose:L}),B=Kt({...v,...l,debug:m,verbose:J,appUrl:c,isDev:u}),te=Ut({...v,...i,debug:S,verbose:ae}),X=Xt({...v,...p,debug:O,verbose:ee}),_=jt({debug:a,verbose:e});return{routeHandler:ie,themeHandler:x,i18nHandler:K,assetHandler:H,seoHandler:B,pwaHandler:te,serverShimHandler:X,blogContentHandler:_}}function ss(a,e){let t={};if(a.routeHandler)try{t.routeConfig=a.routeHandler.createNextConfig()}catch(r){e.error(`Route handler failed during config creation: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.routeConfig=()=>({})}else t.routeConfig=()=>({});let s=[{name:"theme",handler:a.themeHandler},{name:"i18n",handler:a.i18nHandler},{name:"asset",handler:a.assetHandler},{name:"seo",handler:a.seoHandler},{name:"pwa",handler:a.pwaHandler}];for(let{name:r,handler:o}of s)try{t[`${r}Config`]=o.createNextConfig()}catch(n){e.error(`${r.charAt(0).toUpperCase()+r.slice(1)} handler failed: ${n.message}`),e.error(`Stack: ${n.stack||"No stack trace available"}`),t[`${r}Config`]=()=>({})}try{t.serverShimConfig=a.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}var nr=new Set(["@donotdev/functions"]);function rs(){try{let a=$.getInstance(),e=a.resolveAppPath("package.json"),t=a.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(r=>r.startsWith("@donotdev/")).filter(r=>!$e.buildTimePackages.includes(r)).filter(r=>!nr.has(r)).sort()}catch{return[]}}var st=new Map;function ar(a={}){let{port:e,...t}=a;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let P=process.env.CI==="true";process.env.DNDEV_BUILD_ID=P?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let s=process.env.DNDEV_BUILD_ID;if(s&&st.has(s))return st.get(s).configFn;let{appConfig:r,...o}=t;if(!r)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let n=r?.features?{debug:r.features.debug}:void 0,l=r?.seo&&typeof r.seo!="boolean"?{...r.seo,siteName:r.seo.siteName||r.app?.name}:r?.app?.name?{siteName:r.app.name}:void 0,i=r?.app?{name:r.app.name,shortName:r.app.shortName,description:r.app.description}:void 0,{features:p,seo:c,...u}=o,g={...n?{features:n}:{},...l?{seo:l}:{},...u},f=It(g),h=Mt(f);if(!h)throw new Error("normalizeOptions returned undefined");let{generateManifest:b,debug:d,verbose:m,mode:S,isDev:O,routeOptions:T,themeOptions:M,i18nOptions:A,assetOptions:L,pwaOptions:J,seoOptions:ae,serverShimOptions:ee,nextConfigOptions:v,reactCompiler:ie}=h,x=N("next-config",d,m),{appRoot:K,appRootSet:H}=ft({logger:x,debug:d}),B=!1,te=T?.routingMode||"app",X=H&&ze(K);if(X||(x.info(`
|
|
806
|
-
\u{1F3D7}\uFE0F DnDev Framework - Building for ${S}${s?` [build:${s}]`:""}`),x.info(` Platform: Next.js | Routing: ${te}
|
|
807
|
-
`)),O){let P=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${P}`,d&&(x.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&x.debug(`Port configured: ${P} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||x.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let _=ts({debug:d,verbose:m,generateManifest:b,routeOptions:{...T,ssr:r?.ssr!==!1},themeOptions:M,i18nOptions:A,assetOptions:L,seoOptions:ae,pwaOptions:J,serverShimOptions:ee,isDev:O,logger:x}),q=ss(_,x),y=async function(R={}){let k=$.getInstance(),j=H?rs():[];d&&j.length>0&&x.debug(`Discovered ${j.length} packages: ${j.join(", ")}`);let{missing:se,installed:we}=xe(k.getAppRoot()),Fe=se.filter(fe=>fe.startsWith("@donotdev/")),ns=we.filter(fe=>fe.startsWith("@donotdev/"));d&&se.length>0&&x.debug(`Missing optional deps (will alias to empty): ${se.join(", ")}`),H&&await Ft(_,x);let re=typeof R=="object"&&R!==null?R:{},{webpack:as,rewrites:is,redirects:ls,...cs}=re;H&&!B&&(B=await Dt(_.assetHandler,x,B));let ps=q.routeConfig(re),us=q.themeConfig(re),gs=q.i18nConfig(re),fs=q.assetConfig(re),hs=q.seoConfig(re),ds=q.pwaConfig(re),ms=q.serverShimConfig(),ot=await _.i18nHandler?.getDiscoveryData?.(),nt=ot?.flagCodes||[],vs=ot?.supportedLanguages||[],bs=te==="app"?await _.routeHandler?.getDiscoveryData?.():null,ys=St({originalWebpack:as,unusedFeaturePackages:Fe,usedFeaturePackages:ns,missingOptionalDeps:se,flagCodes:nt,languages:vs,logger:x,debug:d}),ws=Rt({originalRewrites:is,handlers:[_.routeHandler,_.themeHandler,_.i18nHandler,_.assetHandler,_.pwaHandler],logger:x}),Ps=xt({originalRedirects:ls,seoRedirects:ae?.redirects||[],routes:bs?.routes||[],logger:x}),$s={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Ss=kt({routeResult:ps,themeResult:us,i18nResult:gs,assetResult:fs,seoResult:hs,pwaResult:ds,serverShimResult:ms,restNextConfig:cs,discoveredPackages:j,reactCompiler:ie,webpackConfig:ys,rewritesConfig:ws,redirectsConfig:Ps,missingOptionalDeps:se,flagCodes:nt,pathResolver:k,env:$s,logger:x});if(x.debug("Next.js config generated"),H&&!X){let fe=i?.name||"app";x.info(`Name: ${fe}`),x.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),x.info(`App root (final): ${k.getAppRoot()}`)}return Ss};return s&&st.set(s,{configFn:y}),y}var os=ar;import{readFileSync as ir,existsSync as lr}from"node:fs";import{join as cr}from"node:path";var ye=null,rt=0,pr=6e4;function ur(){let a=Date.now();if(ye&&a-rt<pr)return ye;try{let e=cr(process.cwd(),"public","metadata-manifest.json");if(!lr(e))return null;let t=ir(e,"utf-8");return ye=JSON.parse(t),rt=a,ye}catch{return null}}function gr(a,e,t){let s=ur(),r={title:t?.siteName||"Site"};if(!s)return r;let o=a.startsWith("/")?a:`/${a}`,n=s[o];if(!n)return r;let l=e||n.defaultLocale||"en",i=n.locales[l]||n.locales[n.defaultLocale]||Object.values(n.locales)[0];if(!i)return r;let p=process.env.NEXT_PUBLIC_APP_URL,c={title:i.title,...p&&{metadataBase:new URL(p)}};return i.description&&(c.description=i.description),i.keywords&&(c.keywords=i.keywords),c.openGraph={title:i.title,type:i.type||"website",...i.description&&{description:i.description},...i.image&&{images:[i.image]},...t?.siteName&&{siteName:t.siteName}},c.twitter={card:"summary_large_image",title:i.title,...i.description&&{description:i.description},...i.image&&{images:[i.image]}},i.noindex&&(c.robots={index:!1,follow:!1}),c}function fr(){ye=null,rt=0}export{fr as clearMetadataCache,os as default,os as defineNextConfig,zs as definePostCSSConfig,gr as getMetadataForPath};
|
|
1186
|
+
`}};function ws(a={}){return new ut(a)}function Ss({debug:a,verbose:e,generateManifest:t,routeOptions:s,themeOptions:r,i18nOptions:n,assetOptions:o,seoOptions:i,pwaOptions:l,serverShimOptions:c,appUrl:p,isDev:u,logger:g}){let h=s.debug??a,f=r.debug??a,w=n.debug??a,y=o.debug??a,v=i.debug??a,P=l.debug??a,b=c.debug??a,x=s.verbose??e,T=r.verbose??e,C=n.verbose??e,_=o.verbose??e,j=i.verbose??e,re=l.verbose??e,ee=c.verbose??e,d={debug:a,verbose:e,generateManifest:t},ne=s.disabled?null:as({...d,...s,debug:h,verbose:x});a&&g.debug(`Route handler created: ${ne?"enabled":"disabled"} (debug: ${h})`);let E=ws({...d,...r,debug:f,verbose:T}),K=ts({...d,...n,debug:w,verbose:C}),z=Qt({...d,...o,debug:y,verbose:_}),U=vs({...d,...i,debug:v,verbose:j,appUrl:p,isDev:u}),W=ss({...d,...l,debug:P,verbose:re}),N=ys({...d,...c,debug:b,verbose:ee}),k=es({debug:a,verbose:e});return{routeHandler:ne,themeHandler:E,i18nHandler:K,assetHandler:z,seoHandler:U,pwaHandler:W,serverShimHandler:N,blogContentHandler:k}}function $s(a,e){let t={};if(a.routeHandler)try{t.routeConfig=a.routeHandler.createNextConfig()}catch(r){e.error(`Route handler failed during config creation: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.routeConfig=()=>({})}else t.routeConfig=()=>({});let s=[{name:"theme",handler:a.themeHandler},{name:"i18n",handler:a.i18nHandler},{name:"asset",handler:a.assetHandler},{name:"seo",handler:a.seoHandler},{name:"pwa",handler:a.pwaHandler}];for(let{name:r,handler:n}of s)try{t[`${r}Config`]=n.createNextConfig()}catch(o){e.error(`${r.charAt(0).toUpperCase()+r.slice(1)} handler failed: ${o.message}`),e.error(`Stack: ${o.stack||"No stack trace available"}`),t[`${r}Config`]=()=>({})}try{t.serverShimConfig=a.serverShimHandler}catch(r){e.error(`ServerShim handler failed: ${r.message}`),e.error(`Stack: ${r.stack||"No stack trace available"}`),t.serverShimConfig=()=>({})}return t}var Gr=new Set(["@donotdev/functions"]);function Rs(){try{let a=R.getInstance(),e=a.resolveAppPath("package.json"),t=a.readSync(e,{format:"json"});if(!t)return[];let s={...t.dependencies,...t.devDependencies};return Object.keys(s).filter(r=>r.startsWith("@donotdev/")).filter(r=>!_e.buildTimePackages.includes(r)).filter(r=>!Gr.has(r)).sort()}catch{return[]}}var gt=new Map;function zr(a={}){let{port:e,...t}=a;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let $=process.env.CI==="true";process.env.DNDEV_BUILD_ID=$?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let s=process.env.DNDEV_BUILD_ID;if(s&>.has(s))return gt.get(s).configFn;let{appConfig:r,...n}=t;if(!r)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let o=r?.features?{debug:r.features.debug}:void 0,i=r?.seo===!1?{disabled:!0}:r?.seo&&typeof r.seo!="boolean"?{...r.seo,siteName:r.seo.siteName||r.app?.name,siteDescription:r.app?.description}:r?.app?.name?{siteName:r.app.name,siteDescription:r.app.description}:void 0,l=r?.app?{name:r.app.name,shortName:r.app.shortName,description:r.app.description}:void 0,{features:c,seo:p,...u}=n,g={...o?{features:o}:{},...i?{seo:i}:{},...u},h=Yt(g),f=Zt(h);if(!f)throw new Error("normalizeOptions returned undefined");let{generateManifest:w,debug:y,verbose:v,mode:P,isDev:b,routeOptions:x,themeOptions:T,i18nOptions:C,assetOptions:_,pwaOptions:j,seoOptions:re,serverShimOptions:ee,nextConfigOptions:d,reactCompiler:ne}=f,E=G("next-config",y,v),{appRoot:K,appRootSet:z}=Pt({logger:E,debug:y}),U=!1,W=x?.routingMode||"app",N=z&&Ke(K);if(N||(E.info(`
|
|
1187
|
+
\u{1F3D7}\uFE0F DnDev Framework - Building for ${P}${s?` [build:${s}]`:""}`),E.info(` Platform: Next.js | Routing: ${W}
|
|
1188
|
+
`)),b){let $=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${$}`,y&&(E.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&E.debug(`Port configured: ${$} (set PORT env var)`))}else process.env.NEXT_PUBLIC_APP_URL||E.warn("NEXT_PUBLIC_APP_URL not found in environment. Set it in .env.production");let k=Ss({debug:y,verbose:v,generateManifest:w,routeOptions:{...x,ssr:r?.ssr!==!1,auth:r?.auth,revalidate:r?.revalidate},themeOptions:T,i18nOptions:C,assetOptions:_,seoOptions:{...re,revalidate:r?.revalidate},pwaOptions:{...j,app:l},serverShimOptions:ee,isDev:b,logger:E}),te=$s(k,E),m=async function(A={}){let D=R.getInstance(),q=z?Rs():[];y&&q.length>0&&E.debug(`Discovered ${q.length} packages: ${q.join(", ")}`);let{missing:le,installed:Ee}=Ce(D.getAppRoot()),Me=le.filter(ve=>ve.startsWith("@donotdev/")),xs=Ee.filter(ve=>ve.startsWith("@donotdev/"));y&&le.length>0&&E.debug(`Missing optional deps (will alias to empty): ${le.join(", ")}`),z&&(W==="app"&&Ct({pathResolver:D,logger:E,isCI:!!(process.env.CI||process.env.VERCEL)}),await Vt(k,E));let ce=typeof A=="object"&&A!==null?A:{},{webpack:Es,rewrites:As,redirects:_s,...ks}=ce;z&&!U&&(U=await Jt(k.assetHandler,E,U));let Ns=te.routeConfig(ce),Cs=te.themeConfig(ce),Ds=te.i18nConfig(ce),Ts=te.assetConfig(ce),Fs=te.seoConfig(ce),Os=te.pwaConfig(ce),Is=te.serverShimConfig(),ft=(await k.i18nHandler?.getDiscoveryData?.())?.flagCodes||[],Ls=Ft({originalWebpack:Es,unusedFeaturePackages:Me,usedFeaturePackages:xs,missingOptionalDeps:le,flagCodes:ft,logger:E,debug:y}),Us=Ot({originalRewrites:As,handlers:[k.routeHandler,k.themeHandler,k.i18nHandler,k.assetHandler,k.pwaHandler],logger:E}),Ms=It({originalRedirects:_s,seoRedirects:re?.redirects||[],logger:E}),js={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Gs=Lt({routeResult:Ns,themeResult:Cs,i18nResult:Ds,assetResult:Ts,seoResult:Fs,pwaResult:Os,serverShimResult:Is,restNextConfig:ks,discoveredPackages:q,reactCompiler:ne,routingMode:W,webpackConfig:Ls,rewritesConfig:Us,redirectsConfig:Ms,missingOptionalDeps:le,flagCodes:ft,pathResolver:D,env:js,logger:E});if(E.debug("Next.js config generated"),z&&!N){let ve=l?.name||"app";E.info(`Name: ${ve}`),E.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),E.info(`App root (final): ${D.getAppRoot()}`)}return Gs};return s&>.set(s,{configFn:m}),m}var Ps=zr;import{readFileSync as Br,existsSync as Hr}from"node:fs";import{join as Wr}from"node:path";var xe=null,ht=0,qr=6e4;function Vr(){let a=Date.now();if(xe&&a-ht<qr)return xe;try{let e=Wr(process.cwd(),"public","metadata-manifest.json");if(!Hr(e))return null;let t=Br(e,"utf-8");return xe=JSON.parse(t),ht=a,xe}catch{return null}}function Jr(a,e,t){let s=Vr(),r={title:t?.siteName||"Site"};if(!s)return r;let n=a.startsWith("/")?a:`/${a}`,o=s[n];if(!o)return r;let i=e||o.defaultLocale||"en",l=o.locales[i]||o.locales[o.defaultLocale]||Object.values(o.locales)[0];if(!l)return r;let c=process.env.NEXT_PUBLIC_APP_URL,p={title:l.title,...c&&{metadataBase:new URL(c)}};return l.description&&(p.description=l.description),l.keywords&&(p.keywords=l.keywords),p.openGraph={title:l.title,type:l.type||"website",...l.description&&{description:l.description},...l.image&&{images:[l.image]},...t?.siteName&&{siteName:t.siteName}},p.twitter={card:"summary_large_image",title:l.title,...l.description&&{description:l.description},...l.image&&{images:[l.image]}},l.noindex&&(p.robots={index:!1,follow:!1}),p}function Xr(){xe=null,ht=0}function Kr(a){return a.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}async function Le(a,e,t){let s=[];for(let r of a){let n=Kr(r.path);if(n.length===0){s.push({route:r,path:r.path});continue}let o=n[0];if(n.length>1||!r.collection||!o)throw new Error(`[dndev] Cannot list the public URLs of route "${r.path}". Only single-param routes of an entity collection are expanded. Mark the page \`seo: { noindex: true }\` to keep it out of the sitemap and llms.txt.`);if(!e)throw new Error(`[dndev] Route "${r.path}" lists "${r.collection}" records but no server CRUD reader was given.`);let i=await e.query(r.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3});for(let l of i.items){let c=l[o];typeof c!="string"&&typeof c!="number"||s.push({route:r,path:r.path.replace(`:${o}`,encodeURIComponent(String(c))),record:l})}}return s}function Ue(a){return String(a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function Yr(a,{baseUrl:e,routing:t,crud:s,languageUrls:r,hiddenStatuses:n}){let o=[],i=(l,c)=>{let p=r(l,e,t),u=t.languages.length>1?{alternates:{languages:p}}:{};for(let g of t.languages)o.push({url:p[g],...c,...u})};for(let{route:l,path:c,record:p}of await Le(a,s,n)){if(!p){i(c,{changeFrequency:l.changeFrequency??"weekly",priority:l.priority??(c==="/"?1:.8),...l.lastModified&&{lastModified:l.lastModified}});continue}let u=p.updatedAt instanceof Date?p.updatedAt.toISOString():p.updatedAt;i(c,{changeFrequency:l.changeFrequency??"weekly",priority:l.priority??.7,...typeof u=="string"&&{lastModified:u}})}return o}function Zr(a){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${a.some(s=>s.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let s of a){t.push(" <url>",` <loc>${Ue(s.url)}</loc>`);for(let[r,n]of Object.entries(s.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${Ue(r)}" href="${Ue(n)}" />`);s.lastModified&&t.push(` <lastmod>${Ue(s.lastModified)}</lastmod>`),s.changeFrequency&&t.push(` <changefreq>${s.changeFrequency}</changefreq>`),s.priority!==void 0&&t.push(` <priority>${s.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
|
|
1189
|
+
`)}import Qr from"i18next";function en(a){let e=new Map;for(let t of Object.values(a))typeof t=="object"&&t!==null&&"collection"in t&&"fields"in t&&e.set(t.collection,t);return e}function tn(a,e){let t=Qr.createInstance();return t.init({lng:a,resources:{[a]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),s=>t.getFixedT(a,[s,"crud"])}async function sn(a){let{crud:e,deriveEntitySeo:t,hiddenStatuses:s}=a,r=en(a.entities),n,o=new Map,i=l=>{let c=o.get(l);return c||(c={heading:l,links:[]},o.set(l,c)),c};i(a.pagesHeading);for(let{route:l,path:c,record:p}of await Le(a.routes,e,s)){let u=`${a.baseUrl}${c}`;if(!p){if(!l.title)throw new Error(`[dndev] llms.txt: page "${l.path}" has no label in the app language.`);i(l.section??a.pagesHeading).links.push({title:l.title,url:u,...l.description&&{description:l.description}});continue}let g=r.get(l.collection);if(!g)throw new Error(`[dndev] llms.txt: no entity definition for collection "${l.collection}" (route "${l.path}"). Export it from the app's \`entities\` package.`);let h=l.section??(g.namespace?a.entityHeadings[g.namespace]:void 0);if(!h)throw new Error(`[dndev] llms.txt: no heading for route "${l.path}". Add "namePlural" to the ${g.namespace??`entity-${g.name.toLowerCase()}`} translations.`);if(!n){if(!a.language||!a.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");n=tn(a.language,a.translations)}let f=t(g,p,{t:n(g.namespace),locale:a.language});if(!f.title)throw new Error(`[dndev] llms.txt: published "${l.collection}" record at "${c}" has no title (listCardFields title fields, or first text field, are empty).`);i(h).links.push({title:f.title,url:u,...f.description&&{description:f.description}})}return ps({name:a.name,...a.summary&&{summary:a.summary},sections:[...o.values()]})}export{sn as buildLlmsTxt,Yr as buildSitemap,Xr as clearMetadataCache,Ps as default,Ps as defineNextConfig,Zs as definePostCSSConfig,Zr as formatSitemapXml,Jr as getMetadataForPath};
|