@donotdev/core 0.3.2 → 0.3.3
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 +19 -19
- package/i18n/locales/eager/dndev_ar.json +2 -1
- package/i18n/locales/eager/dndev_da.json +2 -1
- package/i18n/locales/eager/dndev_de.json +2 -1
- package/i18n/locales/eager/dndev_en.json +2 -1
- package/i18n/locales/eager/dndev_es.json +2 -1
- package/i18n/locales/eager/dndev_fr.json +2 -1
- package/i18n/locales/eager/dndev_it.json +2 -1
- package/i18n/locales/eager/dndev_ja.json +2 -1
- package/i18n/locales/eager/dndev_ko.json +2 -1
- package/i18n/locales/eager/dndev_nl.json +2 -1
- package/i18n/locales/eager/dndev_pl.json +2 -1
- package/i18n/locales/eager/dndev_pt.json +2 -1
- package/i18n/locales/eager/dndev_zh.json +2 -1
- package/i18n/locales/lazy/auth_ar.json +19 -2
- package/i18n/locales/lazy/auth_da.json +22 -2
- package/i18n/locales/lazy/auth_de.json +19 -2
- package/i18n/locales/lazy/auth_en.json +19 -2
- package/i18n/locales/lazy/auth_es.json +19 -2
- package/i18n/locales/lazy/auth_fr.json +19 -2
- package/i18n/locales/lazy/auth_it.json +19 -2
- package/i18n/locales/lazy/auth_ja.json +19 -2
- package/i18n/locales/lazy/auth_ko.json +19 -2
- package/i18n/locales/lazy/auth_nl.json +22 -2
- package/i18n/locales/lazy/auth_pl.json +19 -2
- package/i18n/locales/lazy/auth_pt.json +19 -2
- package/i18n/locales/lazy/auth_zh.json +19 -2
- package/i18n/locales/lazy/crud_ar.json +3 -1
- package/i18n/locales/lazy/crud_da.json +3 -1
- package/i18n/locales/lazy/crud_de.json +3 -1
- package/i18n/locales/lazy/crud_en.json +3 -1
- package/i18n/locales/lazy/crud_es.json +3 -1
- package/i18n/locales/lazy/crud_fr.json +3 -1
- package/i18n/locales/lazy/crud_it.json +3 -1
- package/i18n/locales/lazy/crud_ja.json +3 -1
- package/i18n/locales/lazy/crud_ko.json +3 -1
- package/i18n/locales/lazy/crud_nl.json +3 -1
- package/i18n/locales/lazy/crud_pl.json +3 -1
- package/i18n/locales/lazy/crud_pt.json +3 -1
- package/i18n/locales/lazy/crud_zh.json +3 -1
- package/index.d.ts +158 -6
- package/index.js +3 -3
- package/next/index.d.ts +65 -1
- package/next/index.js +222 -184
- package/package.json +2 -2
- package/server.d.ts +158 -4
- package/shared.js +1 -1
- package/symbol-index.json +1 -1
- package/vite/index.d.ts +64 -0
- package/vite/index.js +180 -174
package/next/index.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
|
-
import*as S from"node:fs";import"node:fs";import{createRequire as Rn}from"node:module";import{resolve as Le,join as ie,dirname as ue,relative as qt,normalize as xn,sep as Jt,extname as $n}from"node:path";import Pn from"fast-glob";var Re={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var Gt={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"},V={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},k={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.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"}},xe="/og-image.png";var st={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},$e={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},fe={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",PUBLISHED_FLAGS:"i18n/flags"},q={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:[`${fe.SOURCE_EAGER}/*_*.json`],lazy:[`${fe.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","icon-*x*.png",xe.slice(1)],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},Fe={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","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"]};var nt={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)/}},Pe={Inter:"inter","Space Grotesk":"space-grotesk","Playfair Display":"playfair-display","Press Start 2P":"press-start-2p",Roboto:"roboto"},he={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]},zt={inter:"sans-serif","playfair-display":"serif",roboto:"sans-serif","space-grotesk":"sans-serif","press-start-2p":"sans-serif"},Ht={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:[]},ot=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],jt={base:{absolute:!0,onlyFiles:!0,ignore:q.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...q.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...q.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:q.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:q.globalIgnore}};function Wt(s,e=null){let t=q[s];if(!t)throw new Error(`Unknown pattern type: ${s}`);return e&&t.framework?{...t,framework:t.framework.map(r=>`${e}/${r}`)}:t}function Ie(s){return jt[s]||jt.base}var ge={getGlobOptionsFor:Ie||void 0,SCAN_PATTERNS:q||void 0,getPatternsFor:Wt||void 0,I18N_PATHS:fe||void 0},M={error:(s,e)=>{},warn:(s,e)=>{},info:s=>{}};function me(s){return typeof s=="object"&&s!==null&&"code"in s&&s.code==="EEXIST"}function Vt(s,e){return s().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Kt={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"},x=class s{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return s._instance||(s._instance=new s(e)),s._instance}static _reset(){s._instance=null}constructor(e={}){if(s._instance)return s._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,s._instance=this}normalizePath(e){if(!e)return"";try{return xn(e).split(Jt).join("/")}catch{return String(e).split(Jt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),r=qt(t,e);return this.normalizePath(r)}getBasename(e){if(!e)return"";let r=this.normalizePath(e).split("/");return r[r.length-1]||""}getDirname(e){return e?this.normalizePath(ue(e)):""}resolvePackage(e,t=null){try{let r=t||this.getAppRoot(),o=Rn(ie(r,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let r=this.resolvePackage(`${e}/package.json`,t);if(r)return this.getDirname(r);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let n=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(n))return n;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(),r=Le(t,e);return this.normalizePath(r)}resolveRepoPath(e){let t=this.getRepoRoot(),r=this.normalizePath(e),n=Le(t,r);return this.normalizePath(n)}resolvePath(e,t){let r=this.normalizePath(t),n=this.normalizePath(e),o=Le(r,n);return this.normalizePath(o)}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:$n(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:r="auto",encoding:n="utf8"}=t,o=this._detectFormat(e,r);try{if(o==="buffer")return await S.promises.readFile(e);let a=await S.promises.readFile(e,n),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&M.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:r="auto",encoding:n="utf8"}=t,o=this._detectFormat(e,r);try{if(o==="buffer")return S.readFileSync(e);let a=S.readFileSync(e,n),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&M.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,r={}){let{format:n="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=r,l=this.normalizePath(e),u=this.normalizePath(ue(l)),c=this.pathExists(l);if(c&&!o)return i&&M.info(`Skipping existing file: ${l}`),!1;if(a)return M.info(`[DRY RUN] Would write file: ${l}`),!0;try{await S.promises.mkdir(u,{recursive:!0})}catch(f){if(!me(f))throw f}let p=this._detectFormat(e,n),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
2
|
-
`:d=String(t);try{return await
|
|
3
|
-
`:d=String(t);try{return Buffer.isBuffer(d)?S.writeFileSync(l,d):S.writeFileSync(l,d,"utf8"),this._writtenPaths?.add(l),i&&M.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,r={}){let{overwrite:n=!1,dryRun:o=!1,verbose:a=!1}=r,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!n)return a&&M.info(`Skipping existing file: ${i}`),!1;if(o)return M.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(ue(i));try{await S.promises.mkdir(u,{recursive:!0})}catch(c){if(!me(c))throw c}try{return await Vt(async()=>(await S.promises.copyFile(e,i),a&&M.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,r={}){let{overwrite:n=!1,dryRun:o=!1,verbose:a=!1}=r,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!n)return a&&M.info(`Skipping existing file: ${i}`),!1;if(o)return M.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(ue(i));try{S.mkdirSync(u,{recursive:!0})}catch(c){if(!me(c))throw c}try{return S.copyFileSync(e,i),this._writtenPaths?.add(i),a&&M.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return S.existsSync(e)}catch(r){return t||M.error(`Error checking path existence: ${e}`,r),!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(r){return this.options.debug&&M.warn(`Failed to read directory: ${e}`,r),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return S.statSync(e)}catch(t){return this.options.debug&&M.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return S.realpathSync(e)}watch(e,t,r){return S.watch(e,t,r)}lstatSync(e){try{return S.lstatSync(e)}catch(t){return this.options.debug&&M.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await S.promises.mkdir(e,{recursive:!0})}catch(t){if(!me(t))throw t}}ensureDirSync(e){try{S.mkdirSync(e,{recursive:!0})}catch(t){if(!me(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=ie(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Le(e)),r=this.getAppRoot(),n=qt(r,t),o=this.normalizePath(n);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,r={}){let n=this.normalizePath(ie(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=n.startsWith(a)?n.slice(a.length+1):n,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:ge.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...r})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=ge.I18N_PATHS;if(!t)return null;let r=e.replace(t.SOURCE_ROOT+"/",""),n=this.resolveFrameworkPackage("@donotdev/core");if(!n)return null;let o=this.normalizePath(ie(n,t.PUBLISHED_ROOT,r)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await Pn(e,t)).map(n=>{let o=typeof n=="string"?n:n.path;return this.normalizePath(o)}).sort()}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 r=[...e.framework,...e.consumer];for(let c of r)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let n=this.getAppRoot(),o=ge.getGlobOptionsFor?ge.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(n),i=e.framework.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),u={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n};try{let c=i.length>0?await this._globWithNormalization(i,u):[],p=await this._globWithNormalization(l,u);return{frameworkFiles:c,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!ge.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),r=this.getRepoRoot();if(e==="i18n"&&(!t||t===r))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${r}). Ensure configResolved hook has run before discovery.`);let n=ge.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=n,u={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let a=n,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),r=0,n=this.options.maxLevels;for(;r<n;){let o=this.normalizePath(ie(t,Kt.TOOLING)),a=this.normalizePath(ie(t,Kt.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=ie(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(ie(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(ue(t))===t)return t;let u=this.normalizePath(ue(t));if(u===t)break;t=u,r++}return this.normalizePath(e)}};function Xt({logger:s,debug:e=!1}={}){let t=x.getInstance(),r=!1,n=null;if(process.env.DNDEV_APP_ROOT?(n=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(n)?(t.setAppRoot(n),r=!0,e&&s&&s.debug(`App root set from DNDEV_APP_ROOT: ${n}`)):s&&s.warn(`DNDEV_APP_ROOT path does not exist: ${n}`)):e&&s&&s.debug("DNDEV_APP_ROOT env var not set"),!r){if(t.getRepoRoot()){let a=t.resolveRepoPath("apps");if(t.pathExists(a))try{let i=process.cwd(),l=t.normalizePath(i);if(l.includes("/apps/")){let u=l.indexOf("/apps/"),p=l.substring(u+6).split("/")[0];if(p){let d=t.resolveRepoPath(`apps/${p}`),f=t.resolveRepoPath(`apps/${p}/next.config.js`);t.pathExists(f)&&(n=d,t.setAppRoot(n),r=!0,e&&s&&s.debug(`App root detected from process.cwd(): ${n}`))}}}catch{}}!r&&!n&&(n=process.cwd(),t.setAppRoot(n),r=!0,e&&s&&s.debug(`App root fallback to process.cwd(): ${n}`))}return{appRoot:n,appRootSet:r}}import Hn from"node:fs";import{readdirSync as Cn,readFileSync as An,writeFileSync as Nn}from"node:fs";import{createRequire as _n}from"node:module";import{join as it,resolve as kn}from"node:path";var Me=_n(import.meta.url),at=[14,1];function Yt(s){if(!s)return!1;let[e,t=0]=String(s).split(".").map(Number);return e<at[0]||e===at[0]&&t<at[1]}function Dn(s){let e=Me("@babel/core"),{targets:t}=e.loadPartialConfig({cwd:s,root:s,babelrc:!1,configFile:!1,filename:it(s,"index.js")}).options;return Yt(t?.safari)||Yt(t?.ios)}function*Zt(s){for(let e of Cn(s,{withFileTypes:!0})){let t=it(s,e.name);e.isDirectory()?yield*Zt(t):e.name.endsWith(".js")&&(yield t)}}async function Qt({distDir:s,projectDir:e}){if(!Dn(e))return 0;let t=Me("@babel/core"),r=[[Me.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],Me.resolve("@babel/plugin-transform-parameters")],n=0;for(let o of Zt(it(kn(e,s),"static"))){let a=An(o,"utf8"),i;try{i=t.transformSync(a,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:r})}catch(l){throw new Error(`[dndev] Safari destructuring fix: cannot transform ${o}: ${l.message}`)}i?.code&&i.code!==a&&(Nn(o,i.code),n++)}return n}function er({postcssImport:s,postcssNesting:e,autoprefixer:t,resolve:r}){return{plugins:[r?s({resolve:r}):s,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var tr={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Tn(s){return(e,t)=>{tr[e]&&(e=tr[e]);let r=s.resolvePackage(e,t);if(r)return r;if(e.startsWith("@donotdev/")){let n=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),a=s.resolveFrameworkPackage(n,t);if(a){if(o){let l=s.resolvePath(o,a);if(s.pathExists(l))return l;let u=l+".css";if(s.pathExists(u))return u}let i=s.resolvePath("index.css",a);if(s.pathExists(i))return i}}return s.resolvePath(e,t)}}async function On(){let[s,e,t]=await Promise.all([import("postcss-import").then(n=>n.default),import("postcss-nesting").then(n=>n.default),import("autoprefixer").then(n=>n.default)]),r=x.getInstance();return er({postcssImport:s,postcssNesting:e,autoprefixer:t,resolve:Tn(r)})}import{renameSync as Fn}from"node:fs";import{basename as rr,dirname as In,join as ct,relative as Ln}from"node:path";var le="next",Mn=["tsx","ts","jsx","js"],sr=Mn.map(s=>`${le}.${s}`);function O(s,e){return`${s}.${le}.${e}`}var Un=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],Bn=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],jn=["proxy","middleware","instrumentation"],Gn="// Generated by @donotdev/config";function lt(s,e){let t=s.match(new RegExp(`^(.+?)(\\.${le})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,r,n,o]=t;return e.includes(r)?{name:r,extension:o,marked:!!n}:null}function zn(s){let e=[],t=s.resolveAppPath("src/app"),r=n=>{for(let o of s.readdirSync(n,{withFileTypes:!0})){let a=ct(n,o.name);if(o.isDirectory()){r(a);continue}if(!o.isFile())continue;let i=lt(o.name,Un);i&&e.push({file:a,...i,metadata:!1});let l=lt(o.name,Bn);l&&e.push({file:a,...l,metadata:!0})}};s.pathExists(t)&&r(t);for(let n of[s.resolveAppPath("src"),s.getAppRoot()])if(s.pathExists(n))for(let o of s.readdirSync(n,{withFileTypes:!0})){let a=o.isFile()&<(o.name,jn);a&&e.push({file:ct(n,o.name),...a,metadata:!1})}return e}function nr({pathResolver:s,logger:e,isCI:t}){let r=s.getAppRoot(),n=u=>Ln(r,u),o=[],a=[],i=[],l=[];for(let u of zn(s)){let c=s.readSync(u.file,{format:"text"})||"";if(!u.marked&&c.startsWith(Gn)){s.removeSync(u.file),a.push(n(u.file));continue}u.metadata?l.push(n(u.file)):u.marked||i.push(u)}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/${O("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 .${le}. marker (src/pages is never a Next route). Rename: `+i.map(({file:u,name:c,extension:p})=>`${n(u)} \u2192 ${O(c,p)}`).join(", ")+". Running the app once in development renames them.");for(let{file:u,name:c,extension:p}of i){let d=ct(In(u),O(c,p));if(s.pathExists(d))throw new Error(`[dndev] Both ${n(u)} and ${n(d)} exist. Next only reads *.${le}.* files: merge ${rr(u)} into ${rr(d)} and delete it.`);Fn(u,d),o.push(n(u))}return o.length>0&&e.warn(`Next files renamed to *.${le}.* (src/pages is never a Next route): ${o.join(", ")}. Commit the renames.`),a.length>0&&e.debug(`Removed generated Next files without marker: ${a.join(", ")}`),{renamed:o,removed:a}}function or(s){return s&&typeof s=="object"&&!Array.isArray(s)}var Wn={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function ar({originalRewrites:s,handlers:e,logger:t}){return async function(){try{let r=s?await s():[],o=e.filter(i=>i?.getAPIRewrites).map(i=>i.getAPIRewrites()).reduce((i,l)=>(l?.beforeFiles&&i.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&i.afterFiles.push(...l.afterFiles),l?.fallback&&i.fallback.push(...l.fallback),i),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(r)?[]:r?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(r)?r:r?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(r)?[]:r?.fallback||[],...o.fallback]}}catch(r){return t.error(`Next.js config failed to merge rewrites: ${r.message}`),t.error(`Stack: ${r.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function ir({originalRedirects:s,seoRedirects:e,logger:t}){return async function(){try{let r=s?await s():[],n=(e||[]).map(({from:l,to:u,permanent:c})=>({source:l,destination:u,permanent:c!==!1})),o=[],a=new Set;for(let l of n){let u=l.source.replace(/\/+$/,"")||"/",c=l.destination.replace(/\/+$/,"")||"/";if(u===c){t.warn(`Redirect loop detected: ${l.source} \u2192 ${l.destination} (skipped)`);continue}if(!l.source.startsWith("/")){t.warn(`Redirect source must start with /: "${l.source}" (skipped)`);continue}if(a.has(u)){t.warn(`Duplicate redirect source: "${l.source}" (skipped)`);continue}a.add(u),o.push(l)}let i=[...Array.isArray(r)?r:[],...o];return i.length===0?[]:(t.info(` \u{1F4CE} ${i.length} redirect${i.length>1?"s":""} configured`),i)}catch(r){return t.error(`Failed to merge redirects: ${r.message}`),[]}}}function lr({policyRules:s,originalHeaders:e}){if(e!==void 0&&typeof e!="function")throw new Error("[dndev] next.config headers must be a function returning an array (Next headers() contract).");return async function(){let r=e?await e():[];if(!Array.isArray(r))throw new Error(`[dndev] next.config headers() must return an array (got ${typeof r}).`);return[...s,...r]}}function cr({restNextConfig:s,discoveredPackages:e,reactCompiler:t=!1,routingMode:r,rewritesConfig:n,redirectsConfig:o,headersConfig:a,missingOptionalDeps:i,pathResolver:l,env:u,logger:c}){let p=s?.output==="export";if(r==="app"&&s?.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 f=s?.distDir||".next";return{transpilePackages:[...e,...i||[]],...t?{reactCompiler:t}:{},...or(s)?s:(c.warn("restNextConfig is not a plain object:",s),{}),...r==="app"&&{pageExtensions:sr},...r==="app"&&{experimental:{...s?.experimental,globalNotFound:!0}},serverExternalPackages:(s?.serverExternalPackages||s?.serverComponentsExternalPackages||[]).filter(g=>!g.startsWith("@donotdev/")&&!i?.includes(g)),turbopack:{...s?.turbopack||{},root:s?.turbopack?.root||l.getRepoRoot(),resolveAlias:{...s?.turbopack?.resolveAlias||{},...Wn,[Gt.blog]:(()=>{try{let g=l.resolveAppPath(k.next.blogContent);if(Hn.existsSync(g))return"./"+k.next.blogContent}catch{}return"@donotdev/core/empty"})(),...i?.length>0?Object.fromEntries(i.flatMap(g=>[[g,"@donotdev/core/empty"],[`${g}/*`,"@donotdev/core/empty"]])):{}}},distDir:f,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},compiler:{...s?.compiler,runAfterProductionCompile:async g=>{let m=await Qt(g);m>0&&c.info(`Safari < 14.1 destructuring fix: ${m} client chunks lowered`),await s?.compiler?.runAfterProductionCompile?.(g)}},...p?{}:{rewrites:n,...o?{redirects:o}:{},...a?{headers:a}:{}},env:u,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}function _(s,e,t="configuration-error",r={}){let n=`[${s}] ${e}`,o=new Error(n);return o.code=t,o.pluginName=s,o.context=r,o}function ne(s){return s instanceof Error&&typeof s.pluginName=="string"}function ur(s,e,t,r={}){return _(s,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},r))}import{existsSync as pt,readFileSync as ut,realpathSync as qn}from"node:fs";import{dirname as pr,join as Ce,resolve as dr}from"node:path";var oe="dndev-routes",Ue="entities",Jn="@donotdev/core",fr=[".ts",".tsx",".js",".jsx"],Vn=`import { productEntity } from 'entities';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
`)),
|
|
8
|
-
`;a.writeSync(i,p)}let l=(c,p,d)=>{if(i){let f=new Date().toISOString(),h=d.length>0?" "+d.map(m=>typeof m=="object"?JSON.stringify(m,null,2):String(m)).join(" "):"",g=`${f} [${c}] ${p}${h}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`))
|
|
1
|
+
import*as $ from"node:fs";import"node:fs";import{createRequire as Ls}from"node:module";import{resolve as Ue,join as fe,dirname as ye,relative as rn,normalize as Ms,sep as sn,extname as Us}from"node:path";import js from"fast-glob";var Ae={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var Qt={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},Y={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},Z={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},L={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.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",fonts:"src/app/fonts.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"}},Ne="/og-image.png";var lt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},le={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},we={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",PUBLISHED_FLAGS:"i18n/flags"},X={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:[`${we.SOURCE_EAGER}/*_*.json`],lazy:[`${we.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","icon-*x*.png",Ne.slice(1)],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/**"]},Le={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"]};var ct={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)/}},en=["-apple-system","BlinkMacSystemFont","SF Pro","SF Pro Text","SF Pro Display","SF Mono","Helvetica Neue","Helvetica","Menlo","Monaco","Apple SD Gothic Neo","Hiragino Sans","Hiragino Kaku Gothic ProN","PingFang SC","PingFang TC","Apple Color Emoji","Segoe UI","Segoe UI Emoji","Segoe UI Symbol","Cascadia Code","Cascadia Mono","Consolas","Arial","Georgia","Times New Roman","Times","Courier New","Courier","Verdana","Tahoma","Trebuchet MS","Malgun Gothic","Yu Gothic","Meiryo","Microsoft YaHei","Microsoft JhengHei","Liberation Sans","Liberation Serif","Liberation Mono","DejaVu Sans","DejaVu Serif","DejaVu Sans Mono","Ubuntu","Cantarell","Noto Sans","Noto Serif","Noto Color Emoji","Droid Sans","Droid Sans Mono"],tn={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:[]},ut=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Zt={base:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...X.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...X.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore}};function nn(r,e=null){let t=X[r];if(!t)throw new Error(`Unknown pattern type: ${r}`);return e&&t.framework?{...t,framework:t.framework.map(n=>`${e}/${n}`)}:t}function Me(r){return Zt[r]||Zt.base}var Se={getGlobOptionsFor:Me||void 0,SCAN_PATTERNS:X||void 0,getPatternsFor:nn||void 0,I18N_PATHS:we||void 0},z={error:(r,e)=>{},warn:(r,e)=>{},info:r=>{}};function Ee(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="EEXIST"}function on(r,e){return r().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var an={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"},D=class r{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return r._instance||(r._instance=new r(e)),r._instance}static _reset(){r._instance=null}constructor(e={}){if(r._instance)return r._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,r._instance=this}normalizePath(e){if(!e)return"";try{return Ms(e).split(sn).join("/")}catch{return String(e).split(sn).join("/")}}getRelativePath(e){let t=this.getAppRoot(),n=rn(t,e);return this.normalizePath(n)}getBasename(e){if(!e)return"";let n=this.normalizePath(e).split("/");return n[n.length-1]||""}getDirname(e){return e?this.normalizePath(ye(e)):""}resolvePackage(e,t=null){try{let n=t||this.getAppRoot(),o=Ls(fe(n,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let n=this.resolvePackage(`${e}/package.json`,t);if(n)return this.getDirname(n);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let s=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(s))return s;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(),n=Ue(t,e);return this.normalizePath(n)}resolveRepoPath(e){let t=this.getRepoRoot(),n=this.normalizePath(e),s=Ue(t,n);return this.normalizePath(s)}resolvePath(e,t){let n=this.normalizePath(t),s=this.normalizePath(e),o=Ue(n,s);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=$.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:Us(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:n="auto",encoding:s="utf8"}=t,o=this._detectFormat(e,n);try{if(o==="buffer")return await $.promises.readFile(e);let a=await $.promises.readFile(e,s),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&z.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:n="auto",encoding:s="utf8"}=t,o=this._detectFormat(e,n);try{if(o==="buffer")return $.readFileSync(e);let a=$.readFileSync(e,s),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&z.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,n={}){let{format:s="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),u=this.normalizePath(ye(l)),c=this.pathExists(l);if(c&&!o)return i&&z.info(`Skipping existing file: ${l}`),!1;if(a)return z.info(`[DRY RUN] Would write file: ${l}`),!0;try{await $.promises.mkdir(u,{recursive:!0})}catch(f){if(!Ee(f))throw f}let p=this._detectFormat(e,s),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`:d=String(t);try{return await on(async()=>(Buffer.isBuffer(d)?await $.promises.writeFile(l,d):await $.promises.writeFile(l,d,"utf8"),i&&z.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,n={}){let{format:s="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),u=this.normalizePath(ye(l)),c=this.pathExists(l);if(c&&!o)return i&&z.info(`Skipping existing file: ${l}`),!1;if(a)return z.info(`[DRY RUN] Would write file: ${l}`),!0;try{$.mkdirSync(u,{recursive:!0})}catch(f){if(!Ee(f))throw f}let p=this._detectFormat(e,s),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
3
|
+
`:d=String(t);try{return Buffer.isBuffer(d)?$.writeFileSync(l,d):$.writeFileSync(l,d,"utf8"),this._writtenPaths?.add(l),i&&z.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,n={}){let{overwrite:s=!1,dryRun:o=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!s)return a&&z.info(`Skipping existing file: ${i}`),!1;if(o)return z.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(ye(i));try{await $.promises.mkdir(u,{recursive:!0})}catch(c){if(!Ee(c))throw c}try{return await on(async()=>(await $.promises.copyFile(e,i),a&&z.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,n={}){let{overwrite:s=!1,dryRun:o=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!s)return a&&z.info(`Skipping existing file: ${i}`),!1;if(o)return z.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(ye(i));try{$.mkdirSync(u,{recursive:!0})}catch(c){if(!Ee(c))throw c}try{return $.copyFileSync(e,i),this._writtenPaths?.add(i),a&&z.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return $.existsSync(e)}catch(n){return t||z.error(`Error checking path existence: ${e}`,n),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return $.existsSync(t)||$.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return $.readdirSync(e,t)}catch(n){return this.options.debug&&z.warn(`Failed to read directory: ${e}`,n),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return $.statSync(e)}catch(t){return this.options.debug&&z.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return $.realpathSync(e)}watch(e,t,n){return $.watch(e,t,n)}lstatSync(e){try{return $.lstatSync(e)}catch(t){return this.options.debug&&z.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await $.promises.mkdir(e,{recursive:!0})}catch(t){if(!Ee(t))throw t}}ensureDirSync(e){try{$.mkdirSync(e,{recursive:!0})}catch(t){if(!Ee(t))throw t}}async remove(e){await $.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){$.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return $.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=fe(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Ue(e)),n=this.getAppRoot(),s=rn(n,t),o=this.normalizePath(s);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,n={}){let s=this.normalizePath(fe(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=s.startsWith(a)?s.slice(a.length+1):s,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:Se.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...n})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Se.I18N_PATHS;if(!t)return null;let n=e.replace(t.SOURCE_ROOT+"/",""),s=this.resolveFrameworkPackage("@donotdev/core");if(!s)return null;let o=this.normalizePath(fe(s,t.PUBLISHED_ROOT,n)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await js(e,t)).map(s=>{let o=typeof s=="string"?s:s.path;return this.normalizePath(o)}).sort()}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 n=[...e.framework,...e.consumer];for(let c of n)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let s=this.getAppRoot(),o=Se.getGlobOptionsFor?Se.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(s),i=e.framework.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),u={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s};try{let c=i.length>0?await this._globWithNormalization(i,u):[],p=await this._globWithNormalization(l,u);return{frameworkFiles:c,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!Se.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),n=this.getRepoRoot();if(e==="i18n"&&(!t||t===n))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${n}). Ensure configResolved hook has run before discovery.`);let s=Se.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=s,u={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let a=s,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),n=0,s=this.options.maxLevels;for(;n<s;){let o=this.normalizePath(fe(t,an.TOOLING)),a=this.normalizePath(fe(t,an.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=fe(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(fe(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(ye(t))===t)return t;let u=this.normalizePath(ye(t));if(u===t)break;t=u,n++}return this.normalizePath(e)}};function ln({logger:r,debug:e=!1}={}){let t=D.getInstance(),n=!1,s=null;if(process.env.DNDEV_APP_ROOT?(s=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(s)?(t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root set from DNDEV_APP_ROOT: ${s}`)):r&&r.warn(`DNDEV_APP_ROOT path does not exist: ${s}`)):e&&r&&r.debug("DNDEV_APP_ROOT env var not set"),!n){if(t.getRepoRoot()){let a=t.resolveRepoPath("apps");if(t.pathExists(a))try{let i=process.cwd(),l=t.normalizePath(i);if(l.includes("/apps/")){let u=l.indexOf("/apps/"),p=l.substring(u+6).split("/")[0];if(p){let d=t.resolveRepoPath(`apps/${p}`),f=t.resolveRepoPath(`apps/${p}/next.config.js`);t.pathExists(f)&&(s=d,t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root detected from process.cwd(): ${s}`))}}}catch{}}!n&&!s&&(s=process.cwd(),t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root fallback to process.cwd(): ${s}`))}return{appRoot:s,appRootSet:n}}import oo from"node:fs";import{readdirSync as Bs,readFileSync as Gs,writeFileSync as zs}from"node:fs";import{createRequire as Hs}from"node:module";import{join as dt,resolve as Ws}from"node:path";var je=Hs(import.meta.url),pt=[14,1];function cn(r){if(!r)return!1;let[e,t=0]=String(r).split(".").map(Number);return e<pt[0]||e===pt[0]&&t<pt[1]}function qs(r){let e=je("@babel/core"),{targets:t}=e.loadPartialConfig({cwd:r,root:r,babelrc:!1,configFile:!1,filename:dt(r,"index.js")}).options;return cn(t?.safari)||cn(t?.ios)}function*un(r){for(let e of Bs(r,{withFileTypes:!0})){let t=dt(r,e.name);e.isDirectory()?yield*un(t):e.name.endsWith(".js")&&(yield t)}}function Js(){return{pre(r){r.metadata.script=r.path.node.sourceType==="script";let e=Object.keys(r.scope.bindings);if(r.metadata.script&&e.length>0)throw new Error(`declares top-level ${e.join(", ")}, which its own function scope would hide from the other chunks`)}}}async function pn({distDir:r,projectDir:e}){if(!qs(e))return 0;let t=je("@babel/core"),n=[Js,[je.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],je.resolve("@babel/plugin-transform-parameters")],s=0;for(let o of un(dt(Ws(e,r),"static"))){let a=Gs(o,"utf8"),i;try{i=t.transformSync(a,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:n})}catch(l){throw new Error(`[dndev] Safari destructuring fix: cannot transform ${o}: ${l.message}`)}i?.code&&i.code!==a&&(zs(o,i.metadata.script?`(function(){${i.code}
|
|
4
|
+
}).call(this);`:i.code),s++)}return s}function dn({postcssImport:r,postcssNesting:e,autoprefixer:t,resolve:n}){return{plugins:[n?r({resolve:n}):r,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function Vs(r){return(e,t)=>{let n=r.resolvePackage(e,t);if(n)return n;if(e.startsWith("@donotdev/")){let s=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),a=r.resolveFrameworkPackage(s,t);if(a){if(o){let l=r.resolvePath(o,a);if(r.pathExists(l))return l;let u=l+".css";if(r.pathExists(u))return u}let i=r.resolvePath("index.css",a);if(r.pathExists(i))return i}}return r.resolvePath(e,t)}}async function Ks(){let[r,e,t]=await Promise.all([import("postcss-import").then(s=>s.default),import("postcss-nesting").then(s=>s.default),import("autoprefixer").then(s=>s.default)]),n=D.getInstance();return dn({postcssImport:r,postcssNesting:e,autoprefixer:t,resolve:Vs(n)})}import{renameSync as Xs}from"node:fs";import{basename as fn,dirname as Ys,join as ht,relative as Zs}from"node:path";var he="next",Qs=["tsx","ts","jsx","js"],hn=Qs.map(r=>`${he}.${r}`);function U(r,e){return`${r}.${he}.${e}`}var eo=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],to=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],no=["proxy","middleware","instrumentation"],ro="// Generated by @donotdev/config";function ft(r,e){let t=r.match(new RegExp(`^(.+?)(\\.${he})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,n,s,o]=t;return e.includes(n)?{name:n,extension:o,marked:!!s}:null}function so(r){let e=[],t=r.resolveAppPath("src/app"),n=s=>{for(let o of r.readdirSync(s,{withFileTypes:!0})){let a=ht(s,o.name);if(o.isDirectory()){n(a);continue}if(!o.isFile())continue;let i=ft(o.name,eo);i&&e.push({file:a,...i,metadata:!1});let l=ft(o.name,to);l&&e.push({file:a,...l,metadata:!0})}};r.pathExists(t)&&n(t);for(let s of[r.resolveAppPath("src"),r.getAppRoot()])if(r.pathExists(s))for(let o of r.readdirSync(s,{withFileTypes:!0})){let a=o.isFile()&&ft(o.name,no);a&&e.push({file:ht(s,o.name),...a,metadata:!1})}return e}function gn({pathResolver:r,logger:e,isCI:t}){let n=r.getAppRoot(),s=u=>Zs(n,u),o=[],a=[],i=[],l=[];for(let u of so(r)){let c=r.readSync(u.file,{format:"text"})||"";if(!u.marked&&c.startsWith(ro)){r.removeSync(u.file),a.push(s(u.file));continue}u.metadata?l.push(s(u.file)):u.marked||i.push(u)}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/${U("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 .${he}. marker (src/pages is never a Next route). Rename: `+i.map(({file:u,name:c,extension:p})=>`${s(u)} \u2192 ${U(c,p)}`).join(", ")+". Running the app once in development renames them.");for(let{file:u,name:c,extension:p}of i){let d=ht(Ys(u),U(c,p));if(r.pathExists(d))throw new Error(`[dndev] Both ${s(u)} and ${s(d)} exist. Next only reads *.${he}.* files: merge ${fn(u)} into ${fn(d)} and delete it.`);Xs(u,d),o.push(s(u))}return o.length>0&&e.warn(`Next files renamed to *.${he}.* (src/pages is never a Next route): ${o.join(", ")}. Commit the renames.`),a.length>0&&e.debug(`Removed generated Next files without marker: ${a.join(", ")}`),{renamed:o,removed:a}}function mn(r){return r&&typeof r=="object"&&!Array.isArray(r)}function yn({originalRewrites:r,handlers:e,logger:t}){return async function(){try{let n=r?await r():[],o=e.filter(i=>i?.getAPIRewrites).map(i=>i.getAPIRewrites()).reduce((i,l)=>(l?.beforeFiles&&i.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&i.afterFiles.push(...l.afterFiles),l?.fallback&&i.fallback.push(...l.fallback),i),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(n)?[]:n?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(n)?n:n?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(n)?[]:n?.fallback||[],...o.fallback]}}catch(n){return t.error(`Next.js config failed to merge rewrites: ${n.message}`),t.error(`Stack: ${n.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function vn({originalRedirects:r,seoRedirects:e,logger:t}){return async function(){try{let n=r?await r():[],s=(e||[]).map(({from:l,to:u,permanent:c})=>({source:l,destination:u,permanent:c!==!1})),o=[],a=new Set;for(let l of s){let u=l.source.replace(/\/+$/,"")||"/",c=l.destination.replace(/\/+$/,"")||"/";if(u===c){t.warn(`Redirect loop detected: ${l.source} \u2192 ${l.destination} (skipped)`);continue}if(!l.source.startsWith("/")){t.warn(`Redirect source must start with /: "${l.source}" (skipped)`);continue}if(a.has(u)){t.warn(`Duplicate redirect source: "${l.source}" (skipped)`);continue}a.add(u),o.push(l)}let i=[...Array.isArray(n)?n:[],...o];return i.length===0?[]:(t.info(` \u{1F4CE} ${i.length} redirect${i.length>1?"s":""} configured`),i)}catch(n){return t.error(`Failed to merge redirects: ${n.message}`),[]}}}function bn({policyRules:r,originalHeaders:e}){if(e!==void 0&&typeof e!="function")throw new Error("[dndev] next.config headers must be a function returning an array (Next headers() contract).");return async function(){let n=e?await e():[];if(!Array.isArray(n))throw new Error(`[dndev] next.config headers() must return an array (got ${typeof n}).`);return[...r,...n]}}function wn({restNextConfig:r,discoveredPackages:e,reactCompiler:t=!1,routingMode:n,rewritesConfig:s,redirectsConfig:o,headersConfig:a,missingOptionalDeps:i,pathResolver:l,env:u,logger:c}){let p=r?.output==="export";if(n==="app"&&r?.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 f=r?.distDir||".next";return{transpilePackages:[...e,...i||[]],...t?{reactCompiler:t}:{},...mn(r)?r:(c.warn("restNextConfig is not a plain object:",r),{}),...n==="app"&&{pageExtensions:hn},...n==="app"&&{experimental:{...r?.experimental,globalNotFound:!0}},serverExternalPackages:(r?.serverExternalPackages||r?.serverComponentsExternalPackages||[]).filter(m=>!m.startsWith("@donotdev/")&&!i?.includes(m)),turbopack:{...r?.turbopack||{},root:r?.turbopack?.root||l.getRepoRoot(),resolveAlias:{...r?.turbopack?.resolveAlias||{},[Qt.blog]:(()=>{try{let m=l.resolveAppPath(L.next.blogContent);if(oo.existsSync(m))return"./"+L.next.blogContent}catch{}return"@donotdev/core/empty"})(),...i?.length>0?Object.fromEntries(i.flatMap(m=>[[m,"@donotdev/core/empty"],[`${m}/*`,"@donotdev/core/empty"]])):{}}},distDir:f,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},compiler:{...r?.compiler,runAfterProductionCompile:async m=>{let y=await pn(m);y>0&&c.info(`Safari < 14.1 destructuring fix: ${y} client chunks lowered`),await r?.compiler?.runAfterProductionCompile?.(m)}},...p?{}:{rewrites:s,...o?{redirects:o}:{},...a?{headers:a}:{}},env:u,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}import{createHash as jo}from"node:crypto";function C(r,e,t="configuration-error",n={}){let s=`[${r}] ${e}`,o=new Error(s);return o.code=t,o.pluginName=r,o.context=n,o}function ce(r){return r instanceof Error&&typeof r.pluginName=="string"}function Sn(r,e,t,n={}){return C(r,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},n))}var $n="src/**/*.{ts,tsx,js,jsx,mjs,cjs}",gt=/\/\*[\s\S]*?\*\//g,ao=/(^|\s)\/\/.*$/gm,io=/<!--[\s\S]*?-->/g,lo=/(?:from\s*|import\s*\(\s*|require\s*\(\s*)['"]next\/font(?:\/[^'"]*)?['"]/g,co=/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)['"]@fontsource(?:-variable)?\/[^'"]*['"]/g,uo=/@import\s+(?:url\(\s*)?['"]?@fontsource(?:-variable)?\/[^'";)]*/g,En=/@font-face\b/g,Rn="Name the family in src/themes.css (e.g. --font-sans: Manrope, 'Manrope Fallback', sans-serif;) and keep @fontsource-variable/<slug> or @fontsource/<slug> in package.json, or declare its woff2 files in appConfig.fonts.",po={"next-font":{message:`imports next/font: its preload cannot work in a framework app (page files carry the \`.next.\` marker, Next's font manifest is keyed without it) and it is a second font pipeline. The framework ships the theme's fonts (preloaded, inline @font-face, size-matched fallback). ${Rn}`},fontsource:{message:`imports an @fontsource package: the framework ships the fonts the theme names (preloaded, inline @font-face, hashed /fonts/ files). Remove the import. ${Rn}`},"font-face":{message:"declares @font-face: the framework writes every @font-face of the app (one place, preloaded, hashed files). Declare the woff2 files in appConfig.fonts (src/config/app.ts: { category, faces: [{ file, weight, unicodeRange? }] }) and name the family in src/themes.css."}};function fo(r,e){let t=r;for(let n of e)t=t.replace(n,(s,o)=>{let a=typeof o=="string"?o:"";return a+s.slice(a.length).replace(/[^\n]/g," ")});return t}var ho=(r,e)=>r.slice(0,e).split(`
|
|
5
|
+
`).length;function go(r){let e=[];for(let{file:t,content:n}of r){if(/\.generated\.[a-z]+$/.test(t))continue;let s=t.endsWith(".css"),o=t.endsWith(".html"),a=fo(n,o?[io,gt]:s?[gt]:[gt,ao]),i=s?[["fontsource",uo],["font-face",En]]:o?[["font-face",En]]:[["next-font",lo],["fontsource",co]];for(let[l,u]of i)for(let c of a.matchAll(u))e.push({file:t,line:ho(a,c.index),rule:l})}return e}function xn(r){let e=go(r);if(e.length===0)return;let t=e.map(({file:n,line:s,rule:o})=>` ${n}:${s} ${po[o].message}`);throw C("dndev-fonts",`the app loads fonts itself; the framework font plan is the one way:
|
|
6
|
+
${t.join(`
|
|
7
|
+
`)}`,"configuration-error")}import{brotliDecompressSync as mo}from"node:zlib";var Pn="aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ",yo={"sans-serif":{locals:["Arial","Liberation Sans"],azAvgWidth:934.5116279069767,unitsPerEm:2048},serif:{locals:["Times New Roman","Liberation Serif"],azAvgWidth:854.3953488372093,unitsPerEm:2048}},vo={0:"cmap",1:"head",2:"hhea",3:"hmtx"},bo=63,Cn=48,wo=2001684018;function An(r,e){let t=0;for(let n=0;n<5;n++){let s=r[e+n];if(t=t*128+(s&127),(s&128)===0)return[t,e+n+1]}throw new Error("woff2: invalid UIntBase128")}function So(r){if(r.length<Cn||r.readUInt32BE(0)!==wo)throw new Error("woff2: bad signature");if(r.readUInt32BE(4)===1953784678)throw new Error("woff2: font collections are not supported");let e=r.readUInt16BE(12),t=r.readUInt32BE(20),n=Cn,s=[];for(let l=0;l<e;l++){let u=r[n++],c=u&63,p=u>>6,d=vo[c]??`#${c}`;c===bo&&(d=r.toString("latin1",n,n+4),n+=4);let f;[f,n]=An(r,n);let h=c===10||c===11?p!==3:p!==0,m=f;h&&([m,n]=An(r,n)),s.push({tag:d,length:m,transformed:h})}let o=mo(r.subarray(n,n+t)),a=new Map,i=0;for(let{tag:l,length:u,transformed:c}of s)a.set(l,{data:o.subarray(i,i+u),transformed:c}),i+=u;return a}function Eo(r){let e=r.readUInt16BE(2),t=[];for(let c=0;c<e;c++){let p=4+c*8,d=r.readUInt16BE(p),f=r.readUInt16BE(p+2),h=r.readUInt32BE(p+4);(d===0||d===3&&(f===1||f===10))&&t.push({offset:h,format:r.readUInt16BE(h)})}let n=t.find(c=>c.format===12)??t.find(c=>c.format===4);if(!n)throw new Error("font: no Unicode cmap (format 4 or 12)");let s=n.offset;if(n.format===12){let c=r.readUInt32BE(s+12);return p=>{for(let d=0;d<c;d++){let f=s+16+d*12,h=r.readUInt32BE(f),m=r.readUInt32BE(f+4);if(p>=h&&p<=m)return r.readUInt32BE(f+8)+(p-h)}return 0}}let o=r.readUInt16BE(s+6)/2,a=s+14,i=a+o*2+2,l=i+o*2,u=l+o*2;return c=>{for(let p=0;p<o;p++){if(c>r.readUInt16BE(a+p*2))continue;let d=r.readUInt16BE(i+p*2);if(c<d)return 0;let f=r.readInt16BE(l+p*2),h=u+p*2,m=r.readUInt16BE(h);if(m===0)return c+f&65535;let y=r.readUInt16BE(h+m+(c-d)*2);return y===0?0:y+f&65535}return 0}}function _n(r){let e=So(r);for(let u of["head","hhea","hmtx","cmap"])if(!e.has(u))throw new Error(`font: missing ${u} table`);let t=e.get("head").data,n=e.get("hhea").data,s=e.get("hmtx"),o=n.readUInt16BE(34),a=u=>{let c=Math.min(u,o-1);return s.transformed?s.data.readUInt16BE(1+c*2):s.data.readUInt16BE(c*4)},i=Eo(e.get("cmap").data),l=0;for(let u of Pn){let c=i(u.codePointAt(0));if(c===0)throw new Error(`font: no glyph for '${u}'`);l+=a(c)}return{unitsPerEm:t.readUInt16BE(18),ascent:n.readInt16BE(4),descent:n.readInt16BE(6),lineGap:n.readInt16BE(8),azAvgWidth:l/Pn.length}}var Nn=r=>`${Math.abs(r*100).toFixed(2)}%`;function Be(r){return`${r} Fallback`}function kn({family:r,category:e,metrics:t}){let n=yo[e];if(!n)throw new Error(`font fallback: unknown category '${e}'`);let{unitsPerEm:s,ascent:o,descent:a,lineGap:i,azAvgWidth:l}=t,u=l/s/(n.azAvgWidth/n.unitsPerEm),c=d=>Nn(d/(s*u)),p=Be(r);return[`/* ${p}: ${n.locals[0]} size-matched to ${r} */`,"@font-face {",` font-family: '${p}';`,` src: ${n.locals.map(d=>`local('${d}')`).join(", ")};`,` ascent-override: ${c(o)};`,` descent-override: ${c(a)};`,` line-gap-override: ${c(i)};`,` size-adjust: ${Nn(u)};`,"}"].join(`
|
|
8
|
+
`)}var Ro=2001684018,Ge=400;function He(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function $o(r){let[e,t=e]=String(r).trim().split(/\s+/).map(Number);return[e,t]}var ze=([r,e],t)=>t>=r&&t<=e;function Dn(r,e){if(e.some(o=>ze(o,r)))return r;let t=[...new Set(e.flat())],n=(o=1/0)=>t.filter(a=>a>r&&a<=o).sort((a,i)=>a-i)[0],s=()=>t.filter(o=>o<r).sort((o,a)=>a-o)[0];return r>=400&&r<=500?n(500)??s()??n():r<400?s()??n():n()??s()}function Q(r){return C("dndev-fonts",r,"configuration-error")}function xo(r){return!!(r&&r.length>=4&&r.readUInt32BE(0)===Ro)}var Po=r=>r==="serif"?"serif":"sans-serif";function Co({family:r,packageName:e,dir:t,pathResolver:n}){let s=n.readSync(n.resolvePath("metadata.json",t),{format:"json"}),o=n.readSync(n.resolvePath("unicode.json",t),{format:"json"});if(!s||!o)throw Q(`${e}: metadata.json or unicode.json missing in ${t} (not a fontsource package?).`);if(String(s.family).toLowerCase()!==r.toLowerCase())throw Q(`${e} is the family '${s.family}', the font stack names '${r}'. Write the family as the package names it.`);let a=e.startsWith("@fontsource-variable/"),i=s.variable?.wght;if(a&&!i)throw Q(`${e} has no wght axis: use @fontsource/${s.id} (static weights).`);let l=a?[Number(i.min),Number(i.max)]:null,u=["normal","italic"].filter(h=>s.styles.includes(h)),c=(h,m,y)=>n.resolvePath(`files/${s.id}-${h}-${a?"wght":m}-${y}.woff2`,t),p=h=>{if(!n.pathExists(h))throw Q(`${e}: font file missing: ${h}`);return h},d=s.subsets.includes("latin")?"latin":s.defSubset,f=s.weights.reduce((h,m)=>Math.abs(m-Ge)<Math.abs(h-Ge)?m:h);return{family:r,kind:a?"variable":"static",category:Po(s.category),label:e,provides:h=>a?ze(l,h):s.weights.includes(h),matchWeight:h=>Dn(h,a?[l]:s.weights.map(m=>[m,m])),faces({weights:h,subsets:m}){let y=m.filter(R=>s.subsets.includes(R)),S=a?[`${l[0]} ${l[1]}`]:h.map(String),T=[];for(let R of y)for(let v of S)for(let x of u)T.push({file:p(c(R,v,x)),weight:v,style:x,subset:R,unicodeRange:o[R]??null});return T},metricsFile:p(c(d,f,"normal"))}}function Ao({family:r,config:e,pathResolver:t}){let n=`appConfig.fonts['${r}']`;if(e?.category!=="sans-serif"&&e?.category!=="serif")throw Q(`${n}.category must be 'sans-serif' or 'serif' (picks the size-matched fallback face's system font).`);if(!Array.isArray(e.faces)||e.faces.length===0)throw Q(`${n}.faces must list the family's woff2 files ({ file, weight, style?, unicodeRange?, subset? }).`);let s=e.faces.map((u,c)=>{let p=`${n}.faces[${c}]`;if(typeof u?.file!="string"||!u.file.endsWith(".woff2"))throw Q(`${p}.file must be a .woff2 path relative to the app root (e.g. 'src/assets/fonts/brand.woff2').`);let[d,f]=$o(u.weight);if(!Number.isFinite(d)||!Number.isFinite(f)||d>f)throw Q(`${p}.weight must be a weight (400) or a variable range ('300 600'). Got ${JSON.stringify(u.weight)}.`);let h=u.style??"normal";if(h!=="normal"&&h!=="italic")throw Q(`${p}.style must be 'normal' or 'italic'.`);let m=t.resolveAppPath(u.file),y=t.pathExists(m)?t.readSync(m,{format:"buffer"}):null;if(!y)throw Q(`${p}.file: ${u.file} does not exist.`);if(!xo(y))throw Q(`${p}.file: ${u.file} is not a woff2 font.`);return{file:m,weight:d===f?String(d):`${d} ${f}`,range:[d,f],style:h,subset:u.subset??null,unicodeRange:u.unicodeRange??null}}),o=s.filter(u=>u.style==="normal"),a=o.filter(u=>u.unicodeRange===null),i=({range:u})=>ze(u,Ge)?0:Math.min(...u.map(c=>Math.abs(c-Ge))),l=[...a.length>0?a:o].sort((u,c)=>i(u)-i(c))[0];if(!l)throw Q(`${n}.faces has no normal-style face: the size-matched fallback face is measured on one.`);return{family:r,kind:"local",category:e.category,label:n,provides:u=>o.some(c=>ze(c.range,u)),matchWeight:u=>Dn(u,o.map(c=>c.range)),faces:()=>s.map(({range:u,...c})=>c),metricsFile:l.file}}function No(r,e,t){if(!e)return null;let n=t.resolvePackage(`${r}/package.json`,e);return n?t.getDirname(n):null}function Tn(r,{appFonts:e={},appRoot:t,uiRoot:n,pathResolver:s}){let o=Object.keys(e).find(i=>i.toLowerCase()===r.toLowerCase());if(o)return Ao({family:r,config:e[o],pathResolver:s});let a=He(r);for(let i of[t,n])for(let l of[`@fontsource-variable/${a}`,`@fontsource/${a}`]){let u=No(l,i,s);if(u)return Co({family:r,packageName:l,dir:u,pathResolver:s})}return null}var vt=Object.freeze({body:"--font-family",headline:"--font-headline",mono:"--font-mono"}),_o="--font-weight-",se=":root",ko="@donotdev/components/styles",Do=/\/\*[\s\S]*?\*\//g,To=/([^{}]+)\{([^{}]*)\}/g,Oo=/^(?::root|html|:where\(:root\))$/,Fo=/^(?::root|html)?\.([a-z][\w-]*)$/i,bt=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/,On={normal:400,bold:700};function wt(r){let e=[],t=0,n="",s=0;for(let o=0;o<r.length;o++){let a=r[o];n?a===n&&(n=""):a==='"'||a==="'"?n=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(r.slice(s,o)),s=o+1)}return e.push(r.slice(s)),e.map(o=>o.trim()).filter(Boolean)}function Io(r){return r.replace(/^['"]|['"]$/g,"").trim()}function Lo(r){if(Oo.test(r))return se;let e=Fo.exec(r);return e?e[1]:null}function Fn(r,e=""){let t=new Map,n=r.replace(Do,"");for(let[,s,o]of n.matchAll(To)){let a=s.split(";").pop(),i=wt(a).map(Lo).filter(l=>l!==null);if(i.length!==0)for(let l of o.split(";")){let u=l.indexOf(":");if(u===-1)continue;let c=l.slice(0,u).trim();if(!c.startsWith("--"))continue;let p=l.slice(u+1).replace(/!important\s*$/,"").replace(/\s+/g," ").trim();for(let d of i)t.has(d)||t.set(d,new Map),t.get(d).set(c,{value:p,source:e,scope:d})}}return t}function Mo(r){let e=new Map;for(let t of r)for(let[n,s]of t){e.has(n)||e.set(n,new Map);for(let[o,a]of s)e.get(n).set(o,a)}return e}function In({source:r,scope:e}){return`${r||"CSS"} (${e===se?":root":`.${e}`})`}function mt(r,e,t,n){let s=[];for(let o of wt(e)){let a=bt.exec(o);if(!a){s.push(Io(o));continue}let[,i,l]=a;if(t.has(i)&&!n.has(i))s.push(...mt(i,t.get(i).value,t,new Set([...n,i])));else if(l!==void 0)s.push(...mt(r,l,t,n));else throw C("dndev-fonts",`${r}: ${e} uses var(${i}), which no theme CSS defines (src/**/*.css and the framework tokens). Name the font family in the stack itself, e.g. ${r}: Manrope, 'Manrope Fallback', sans-serif; (a next/font or other runtime class variable is not a framework font).`,"configuration-error")}return s}function Uo(r,e){let t=new Set,n=r;for(;e.has(n)&&!t.has(n);){t.add(n);let s=e.get(n),o=wt(s.value),a=o[0]&&bt.exec(o[0]);if(!a)return{token:n,declaration:s,entries:o};n=a[1]}return null}function yt(r,e,t=new Set){let{value:n}=e.get(r),s=bt.exec(n);if(s){let[,a,i]=s;if(e.has(a)&&!t.has(a))return yt(a,e,new Set([...t,r]));if(i!==void 0)return yt(r,new Map([[r,{value:i.trim()}]]),t)}if(n in On)return On[n];let o=Number(n);if(Number.isFinite(o)&&o>=1&&o<=1e3)return o;throw C("dndev-fonts",`${r}: ${n} is not a font weight (a number from 1 to 1000, normal or bold): the font plan ships the weights the --font-weight-* tokens name.`,"configuration-error")}function Ln({frameworkCss:r,appCss:e}){if(typeof r!="string"||!Array.isArray(e))throw new Error("resolveThemeFonts: frameworkCss (string) and appCss ({ file, css }[]) are required (ThemeDiscovery fontCss)");let t=Fn(r,ko),n=Mo(e.map(({file:o,css:a})=>Fn(a,o)));return[se,...new Set([...t.keys(),...n.keys()])].filter((o,a,i)=>i.indexOf(o)===a).map(o=>{let a=new Map([...t.get(se)??[],...n.get(se)??[],...o===se?[]:t.get(o)??[],...o===se?[]:n.get(o)??[]]),i={};for(let[u,c]of Object.entries(vt))a.has(c)&&(i[u]={stack:mt(c,a.get(c).value,a,new Set([c])),origin:Uo(c,a)});let l=new Map;for(let u of a.keys())u.startsWith(_o)&&l.set(u,{weight:yt(u,a),declaration:a.get(u)});return{scope:o,roles:i,weights:l}})}var Un="optional",Et=le.fonts,Rt=`/${Et}`,Bo=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),Go=new Set(en.map(r=>r.toLowerCase())),zo="--font-weight-normal",Ho="--font-weight-bold",St=r=>C("dndev-fonts",r,"configuration-error");function Mn(r){let e=tn[r];return e&&e.length>0?[...e]:["latin"]}var jn=r=>`'${r.replace(/'/g,"\\'")}'`;function Wo(r,e){return["@font-face{",`font-family:${jn(r)};`,`font-style:${e.style};`,`font-weight:${e.weight};`,`font-display:${Un};`,`src:url(${e.url}) format('woff2');`,e.unicodeRange?`unicode-range:${e.unicodeRange};`:"","}"].join("")}function qo(r,e){let[t,n=t]=r.split(" ").map(Number);return e>=t&&e<=n}async function Bn({fontCss:r,appFonts:e={},languages:t,publicPath:n="",indexHtml:s=null,pathResolver:o}){if(!r||typeof r.framework!="string"||!Array.isArray(r.app))throw new Error("[dndev-fonts] buildFontPlan: fontCss is required (ThemeDiscovery fontCss: theme discovery failed?)");if(!Array.isArray(t)||t.length===0)throw new Error("[dndev-fonts] buildFontPlan: languages is required (i18n discovery supportedLanguages)");let a=o.getAppRoot(),i=await o.findFiles(a,$n);xn([...r.app.map(({file:g,css:b})=>({file:g,content:b})),...i.map(g=>({file:o.getRelativePath(g),content:o.readSync(g,{format:"text"})??""})),...s===null?[]:[{file:"index.html",content:s}]]);let l=Ln({frameworkCss:r.framework,appCss:r.app}),u=o.resolveFrameworkPackage("@donotdev/ui"),c=new Map,p=g=>{let b=g.toLowerCase();return c.has(b)||c.set(b,Tn(g,{appFonts:e,appRoot:a,uiRoot:u,pathResolver:o})),c.get(b)},d=new Map,f=new Map,h=new Map,m=new Map,y=new Map;for(let{scope:g,roles:b,weights:k}of l)for(let[N,_]of Object.entries(b)){if(!_)continue;let F=vt[N];_.stack.forEach((A,G)=>{let j=A.toLowerCase();if(Bo.has(j)||Go.has(j))return;let re=/^(.+) fallback$/i.exec(A)?.[1];if(re&&p(re))return;let w=p(A);if(!w){d.has(j)||d.set(j,{family:A,token:F,scope:g});return}m.has(j)||m.set(j,{source:w,weights:new Set,scopes:new Set});let E=m.get(j);E.scopes.add(g);for(let{weight:ie}of k.values())E.weights.add(w.matchWeight(ie)),!w.provides(ie)&&!h.has(`${j}:${ie}`)&&h.set(`${j}:${ie}`,`${w.family}: weight ${ie} not in source, browser-synthesized`);if(G!==0)return;y.set(j,w);let P=_.origin,I=P?P.entries[1]:_.stack[1],V=Be(A);if(I&&I.replace(/^['"]|['"]$/g,"").trim().toLowerCase()===V.toLowerCase())return;let ge=P?.declaration??{source:"",scope:g},de=P?.token??F,me=`${ge.source}|${de}|${ge.value??A}`;if(f.has(me))return;let Ie=P?P.entries:[A],it=`${de}: ${[Ie[0],jn(V),...Ie.slice(1)].join(", ")};`;f.set(me,{location:In(ge),declared:de,family:A,expected:V,line:it})})}let S=[];for(let{family:g,token:b,scope:k}of d.values())S.push(`${b} (${k===se?":root":`.${k}`}) names '${g}', which nothing provides: install @fontsource-variable/${He(g)} or @fontsource/${He(g)} in the app, declare its woff2 files in appConfig.fonts['${g}'], or use a system family (SYSTEM_FONT_FAMILIES) or a generic one (sans-serif, serif, monospace, system-ui\u2026).`);for(let{location:g,declared:b,family:k,expected:N,line:_}of f.values())S.push(`${g}: ${b} lacks '${N}' right after '${k}' (the size-matched fallback face: no layout shift, no flicker). Write:
|
|
9
|
+
${_}`);if(S.length>0)throw St(`the theme fonts cannot ship:
|
|
10
|
+
- ${S.join(`
|
|
11
|
+
- `)}`);let T=[...new Set(["latin",...t.flatMap(Mn)])],R=new Map,v=g=>{if(!R.has(g)){let b=o.readSync(g,{format:"buffer"}),k=jo("sha256").update(b).digest("hex").slice(0,8),N=o.getBasename(g).replace(/\.woff2$/,"");R.set(g,`${n}${Rt}/${N}.${k}.woff2`)}return R.get(g)},x=[],O=[];for(let[g,{source:b,weights:k}]of m){let N=b.faces({weights:[...k].sort((_,F)=>_-F),subsets:T}).map(_=>({..._,family:b.family,url:v(_.file)}));O.push(...N),x.push({family:b.family,kind:b.kind,category:b.category,source:b.label,fallback:y.has(g)?Be(b.family):null})}let B=[...y.values()].map(g=>{try{return kn({family:g.family,category:g.category,metrics:_n(o.readSync(g.metricsFile,{format:"buffer"}))})}catch(b){throw St(`'${g.family}' (${g.label}): cannot measure ${g.metricsFile} for its fallback face (${b.message}). Its core file must be a woff2 with the Latin letters a-z.`)}}),M=l.find(({scope:g})=>g===se),te=[["body",zo],["headline",Ho]].flatMap(([g,b])=>{let k=M.roles[g]?.stack[0];if(!k||!m.has(k.toLowerCase()))return[];let N=M.weights.get(b)?.weight;if(N===void 0)throw St(`${b} is not defined: the framework tokens (@donotdev/components/styles) define it.`);let{source:_}=m.get(k.toLowerCase());return[{family:_.family,weight:_.matchWeight(N)}]}),W={};for(let g of t){let b=Mn(g),k=[];for(let{family:N,weight:_}of te)for(let F of O){if(F.family!==N||F.style!=="normal"||!qo(F.weight,_))continue;(F.subset===null?F.unicodeRange===null:b.includes(F.subset))&&!k.includes(F.url)&&k.push(F.url)}W[g]=k}return{display:Un,families:x,files:[...R].map(([g,b])=>({source:g,url:b})),css:[...O.map(g=>Wo(g.family,g)),...B].join(`
|
|
12
|
+
`),preloads:W,notices:[...h.values()]}}function Gn(r,{pathResolver:e,publicPath:t=""}){let n=e.resolveAppPath(`public/${Et}`);e.removeSync(n),e.ensureDirSync(n);let s=`${t}${Rt}/`;for(let{source:o,url:a}of r.files){if(!a.startsWith(s))throw new Error(`[dndev-fonts] writeFontPlan: ${a} is not under ${s}`);e.copySync(o,e.resolvePath(a.slice(s.length),n),{overwrite:!0})}return n}import{existsSync as xt,readFileSync as $t,realpathSync as Jo}from"node:fs";import{dirname as zn,join as _e,resolve as Hn}from"node:path";var ue="dndev-routes",We="entities",Vo="@donotdev/core",Wn=[".ts",".tsx",".js",".jsx"],Ko=`import { productEntity } from 'entities';
|
|
13
|
+
export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,qn=null;async function Xn(){return qn??=import("@babel/core").then(r=>r.default??r),qn}function Yn(r,e,t){let n=/\.[jt]sx$/.test(t);try{return r.parseSync(e,{configFile:!1,babelrc:!1,filename:t,sourceType:"module",parserOpts:{plugins:n?["typescript","jsx"]:["typescript"]}}).program}catch(s){throw C(ue,`${t} could not be parsed to resolve entities (PageMeta entity, entity field types): ${s.message}. Fix the syntax error.`,"invalid-configuration")}}function ve(r){return r.type==="StringLiteral"?r.value:r.name}function Re(r){let e=r;for(;e&&["TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","ParenthesizedExpression"].includes(e.type);)e=e.expression;return e}function Xo(r,e){for(let t of r.body)if(!(t.type!=="ImportDeclaration"||t.importKind==="type")){for(let n of t.specifiers)if(n.local.name===e)return t.source.value!==We||n.type!=="ImportSpecifier"||n.importKind==="type"?null:ve(n.imported)}return null}function ke(r){let e=null,t=new Map;function n(){let c=_e(r,"package.json"),p=xt(c)?JSON.parse($t(c,"utf8")):null;return!!(p?.dependencies?.[We]||p?.devDependencies?.[We])}function s(c){if(e)return e;let p=n(),d=r,f=null;for(;p;){let y=_e(d,"node_modules",We);if(xt(_e(y,"package.json"))){f=Jo(y);break}let S=zn(d);if(S===d)break;d=S}if(!f)throw C(ue,`${c}, but the app has no \`entities\` package (${p?"not installed: run bun install":"not in the dependencies of its package.json"}). The entity is read from the app's defineEntity definitions. Fix: add \`"entities": "workspace:*"\` to the app's dependencies and export the entity from the entities package.`,"missing-required-resource");let h=JSON.parse($t(_e(f,"package.json"),"utf8")),m=Kn(Hn(f,h.main??"./index.ts"));if(!m)throw C(ue,`The \`entities\` package (${f}) has no entry module (package.json "main": ${JSON.stringify(h.main??"./index.ts")}). Fix: set "main" to its index file (./index.ts).`,"missing-required-resource");return e=m,e}async function o(c){if(!t.has(c)){let p=await Xn();t.set(c,Yn(p,$t(c,"utf8"),c))}return t.get(c)}function a(c,p){return p.startsWith(".")?Kn(Hn(zn(c),p)):null}async function i(c,p,d){let f=`${c}#${p}`;if(d.has(f))return null;d.add(f);let h=await o(c),m=[];for(let y of h.body)if(y.type==="ExportNamedDeclaration"&&y.exportKind!=="type"){let S=Vn(y.declaration,p);if(S!==void 0)return{init:S,program:h,file:c};for(let T of y.specifiers??[]){if(T.exportKind==="type"||ve(T.exported)!==p)continue;if(T.type!=="ExportSpecifier")return null;let R=ve(T.local);if(y.source){let v=a(c,y.source.value);return v?i(v,R,d):null}return l(c,h,R,d)}}else if(y.type==="ExportAllDeclaration"&&y.exportKind!=="type"){let S=a(c,y.source.value);S&&m.push(S)}for(let y of m){let S=await i(y,p,d);if(S)return S}return null}async function l(c,p,d,f){for(let h of p.body){let m=Vn(h,d);if(m!==void 0)return{init:m,program:p,file:c};if(!(h.type!=="ImportDeclaration"||h.importKind==="type"))for(let y of h.specifiers){if(y.local.name!==d||y.type!=="ImportSpecifier")continue;let S=a(c,h.source.value);return S?i(S,ve(y.imported),f):null}}return null}async function u(c){let p=[c];for(let d=0;d<p.length;d+=1){let f=await o(p[d]);for(let h of f.body){if(!(h.type==="ImportDeclaration"&&h.importKind!=="type"||h.type==="ExportNamedDeclaration"&&h.source&&h.exportKind!=="type"||h.type==="ExportAllDeclaration"&&h.exportKind!=="type"))continue;let y=a(p[d],h.source.value);y&&!p.includes(y)&&p.push(y)}}return p}return{async usesFieldType(c){if(!n())return!1;for(let p of await u(s("The app's package.json lists `entities` (its entity field types are read)")))if(Yo(await o(p),c))return!0;return!1},async collectionOf(c,p){let d=await i(s(`${p} declares a PageMeta entity`),c,new Set);if(!d)throw C(ue,`${p}: PageMeta entity \`${c}\` is not exported by the \`entities\` package. The page names the entity definition it shows a record of. Fix: export it from the entities package index (export { ${c} } from './\u2026').`,"invalid-configuration");return Zo(d,c,p)}}}function Zn(r){return r.body.filter(e=>e.type==="ImportDeclaration"&&e.source.value===Vo).flatMap(e=>e.specifiers).find(e=>e.type==="ImportSpecifier"&&ve(e.imported)==="defineEntity")?.local.name}function Jn(r,e){if(r?.type!=="ObjectExpression")return;let t=r.properties.find(n=>n.type==="ObjectProperty"&&!n.computed&&ve(n.key)===e);return Re(t?.value)}function Yo(r,e){let t=Zn(r);if(!t)return!1;let n=s=>{if(!s||typeof s.type!="string")return!1;if(s.type==="CallExpression"&&s.callee.type==="Identifier"&&s.callee.name===t){let o=Jn(Re(s.arguments[0]),"fields");if(o?.type==="ObjectExpression"&&o.properties.some(a=>{let i=Jn(Re(a.value),"type");return i?.type==="StringLiteral"&&i.value===e}))return!0}for(let o of Object.keys(s)){if(o==="loc"||o==="leadingComments"||o==="trailingComments")continue;let a=s[o];if(Array.isArray(a)?a.some(n):a&&typeof a=="object"&&n(a))return!0}return!1};return n(r)}function Vn(r,e){if(r?.type==="VariableDeclaration"){for(let t of r.declarations)if(t.id.type==="Identifier"&&t.id.name===e)return t.init??null}}function Kn(r){let e=r.replace(/\.[cm]?js$/,""),t=[r,...Wn.map(n=>`${e}${n}`),...Wn.map(n=>_e(r,`index${n}`))];for(let n of t)if(/\.[cm]?[jt]sx?$/.test(n)&&xt(n))return n;return null}function Zo({init:r,program:e,file:t},n,s){let o=Re(r),a=Zn(e);if(o?.type!=="CallExpression"||o.callee.type!=="Identifier"||!a||o.callee.name!==a)throw C(ue,`${s}: PageMeta entity \`${n}\` (${t}) is not a defineEntity definition. The build reads the collection from \`defineEntity({ collection: ... })\` in the entities package. Fix: export const ${n} = defineEntity({ name: '...', collection: '...', fields: { ... } }) with defineEntity imported from '@donotdev/core'.`,"invalid-configuration");let i=Re(o.arguments[0]),l=i?.type==="ObjectExpression"?i.properties.find(p=>p.type==="ObjectProperty"&&!p.computed&&ve(p.key)==="collection"):void 0,u=Re(l?.value),c=u?.type==="StringLiteral"?u.value:u?.type==="TemplateLiteral"&&u.expressions.length===0?u.quasis[0].value.cooked:null;if(!c)throw C(ue,`${s}: PageMeta entity \`${n}\` (${t}) has no literal \`collection\` in its defineEntity options. The page's records (sitemap, prerender, server metadata) are read from it. Fix: set collection: 'products' (a string literal) in the defineEntity call.`,"invalid-configuration");return c}async function Qn(r,e,t,n){if(!r||r.entity===void 0)return null;let s=r.entity?.identifier,o=r.entity?.expression;if(typeof o=="string"){let l=o.match(/^[A-Za-z_$][\w$]*\s*\??\.\s*([A-Za-z_$][\w$]*)$/)?.[1]??"productEntity";throw C(ue,`${t}: PageMeta entity \`${o}\` is not a bare identifier. The build reads the entity statically: only a defineEntity definition named-imported from 'entities' resolves to its collection (no namespace import, member access or call). Fix: import { ${l} } from 'entities'; then entity: ${l}`,"invalid-configuration")}if(typeof s!="string")throw C(ue,`${t}: PageMeta entity must be the entity definition imported from 'entities' (got ${JSON.stringify(r.entity)}). The build resolves it to the entity's collection. Fix:
|
|
14
|
+
${Ko}`,"invalid-configuration");let a=Yn(await Xn(),e,t),i=Xo(a,s);if(!i)throw C(ue,`${t}: PageMeta entity \`${s}\` is not imported from 'entities'. The page's entity must be a defineEntity definition of the app's \`entities\` package (one source for its collection). Fix: import { ${s} } from 'entities';`,"invalid-configuration");return n.collectionOf(i,t)}var Qo=["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",L.next.revalidateRoute],ea="dndev-config-",er=".dndev-build";function Pt(r){if(!r)return!1;let e=D.getInstance(),t=e.resolveAppPath(er),n=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===n}catch{return!1}}function ta(r){if(!r)return;let e=D.getInstance(),t=e.resolveAppPath(er),n=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,n,{overwrite:!0})}catch{}}function na(r,e,t){if(!r)return;let n=D.getInstance(),s=(a,i)=>{let l=n.normalizePath(a);if(!(t.has(l)||!n.pathExists(l)))try{n.removeSync(a),e.debug(`Removed stale: ${i}`)}catch{}};for(let a of Qo)s(n.resolveAppPath(a),a);let o=n.resolveAppPath("src/config");for(let a of n.readdirSync(o))a.startsWith(ea)&&a.endsWith(".js")&&s(n.resolvePath(a,o),`src/config/${a}`)}async function tr({routeHandler:r,themeHandler:e,i18nHandler:t,assetHandler:n,seoHandler:s,pwaHandler:o,blogContentHandler:a},i,{appFonts:l}={}){let u=r?.pathResolver;if(!u)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let c=u.getAppRoot(),p=u.getRepoRoot();if(!c||c===p){i.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(y=>setTimeout(y,0));let m=u.getAppRoot();if(!m||m===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Pt(c)){i.debug("Discoveries already completed this build, skipping");return}ta(c);let d=Date.now();u.startWriteRecording();let f;try{let m=await t.getDiscoveryData(),y={languages:m.supportedLanguages,defaultLanguage:m.fallbackLanguage};s.useLanguages(y),s.useTranslations(m.content);let{fontCss:S}=e?await e.getDiscoveryData():{},T=await Bn({fontCss:S,appFonts:l,languages:m.supportedLanguages,pathResolver:u});Gn(T,{pathResolver:u}),i.debug(`Font plan: ${T.families.map(({family:v})=>v).join(", ")||"system fonts only"} (${T.files.length} files)`);for(let v of T.notices)i.info(`\u{1F524} ${v}`);if(r)try{r.useLanguages(y),r.useI18n(m),r.useFonts(T),i.info("\u{1F50D} Starting route discovery...");let v=await r.generateFiles();s.useRoutes(v);let x=v?.routes?.length||0;i.info(`\u2705 Routes generated: ${x} routes found`),x===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");n.useFlagCodes(m.flagCodes,r?r.getEntityResolver():ke(c));let R=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:n},{name:"SEO",handler:s},{name:"PWA",handler:o},{name:"BlogContent",handler:a}];for(let{name:v,handler:x}of R)try{await x.generateFiles()}catch(O){if(ce(O))throw O;i.debug(`${v} generation failed: ${O.message}`)}try{ra(u,i)}catch(v){i.debug(`Env config generation failed (non-critical): ${v.message}`)}}finally{f=u.stopWriteRecording()}na(c,i,f);let h=Date.now()-d;i.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`)}function ra(r,e){let t={};for(let[a,i]of Object.entries(process.env))a.startsWith("NEXT_PUBLIC_")&&i!==void 0&&(t[a]=i);let n=`// Auto-generated DnDev env config by @donotdev/config
|
|
12
15
|
// Generated at: ${new Date().toISOString()}
|
|
13
16
|
// Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
|
|
14
17
|
|
|
@@ -25,16 +28,18 @@ if (typeof globalThis !== 'undefined') {
|
|
|
25
28
|
timestamp: Date.now(),
|
|
26
29
|
};
|
|
27
30
|
}
|
|
28
|
-
globalThis._DNDEV_CONFIG_.${
|
|
31
|
+
globalThis._DNDEV_CONFIG_.${Y.env} = envConfig;
|
|
29
32
|
}
|
|
30
33
|
|
|
31
34
|
// Export for compatibility
|
|
32
35
|
export default envConfig;
|
|
33
|
-
`,
|
|
36
|
+
`,s=r.resolveAppPath(L.next.configEnv);r.writeSync(s,n,{overwrite:!0});let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}var nr={debug:!1,verbose:process.env.CI!=="true",seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1,aiCrawlers:"recommended",llmsTxt:!0,speculationRules:!0,hreflang:!0,breadcrumbSchema:!0,websiteSchema:!0,organizationSchema:!0},serverShim:{enabled:!0},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},features:{}};var De={...nr,generateManifest:!0,reactCompiler:!1,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function rr(r,e){let t={...r};return e&&Object.keys(e).forEach(n=>{e[n]&&typeof e[n]=="object"&&!Array.isArray(e[n])?t[n]=rr(r[n]||{},e[n]):t[n]=e[n]}),t}function sr(r={}){return rr(De,r)}function or(r){let{features:e={},routes:t={},themes:n={},i18n:s={},assets:o={},pwa:a={},seo:i={},serverShim:l,discovery:u={},generateManifest:c,debug:p,verbose:d,...f}=r,h=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:p,verbose:d,mode:h,isDev:h==="development",routeOptions:t,themeOptions:n,i18nOptions:s,assetOptions:o,featureOptions:e,pwaOptions:a,seoOptions:i,discoveryOptions:u,nextConfigOptions:f}}import*as K from"@clack/prompts";var ne={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 sa(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function oe(r,e){return sa()?`${e}${r}${ne.reset}`:r}function ae(r,e,t,n={}){let{logDir:s=".dndev-logs",fileLogging:o=!1}=n,a=D.getInstance(),i=null;if(o){let c=a.resolveAppPath(s);a.pathExists(c)||a.mkdir(c),i=a.resolveAppPath(`${s}/${r.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${r} Log Started at ${new Date().toISOString()} ===
|
|
37
|
+
`;a.writeSync(i,p)}let l=(c,p,d)=>{if(i){let f=new Date().toISOString(),h=d.length>0?" "+d.map(y=>typeof y=="object"?JSON.stringify(y,null,2):String(y)).join(" "):"",m=`${f} [${c}] ${p}${h}
|
|
38
|
+
`;a.appendFile(i,m)}},u=(c,p)=>{if(p.length===0)return c;let d=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${c} ${d}`};return{debug:(c,...p)=>{e&&(o?l("DEBUG",c,p):K.log.message(oe(u(c,p),ne.gray)))},verbose:(c,...p)=>{t&&(o?l("VERBOSE",c,p):K.log.message(u(c,p)))},info:(c,...p)=>{o?l("INFO",c,p):K.log.info(oe(u(c,p),ne.brightCyan))},warn:(c,...p)=>{e&&o?l("WARN",c,p):K.log.warn(oe(u(c,p),ne.brightYellow))},error:(c,...p)=>{e&&o?l("ERROR",c,p):K.log.error(oe(u(c,p),ne.brightRed))},success:(c,...p)=>{e&&o?l("SUCCESS",c,p):K.log.success(oe(u(c,p),ne.brightGreen))},when:(c,p="debug")=>(d,...f)=>{if(c){let h=u(d,f);switch(p){case"verbose":t&&(K.log.message(h),l("VERBOSE",d,f));break;case"info":K.log.info(oe(h,ne.brightCyan)),l("INFO",d,f);break;case"warn":K.log.warn(oe(h,ne.brightYellow)),l("WARN",d,f);break;case"error":K.log.error(oe(h,ne.brightRed)),l("ERROR",d,f);break;case"success":K.log.success(oe(h,ne.brightGreen)),l("SUCCESS",d,f);break;default:e&&(K.log.message(oe(h,ne.gray)),l("DEBUG",d,f))}}},getLogFilePath:()=>i}}var ar=Object.freeze([{dependency:"@donotdev/supabase",module:"@donotdev/supabase/server",env:["SUPABASE_URL","SUPABASE_PUBLIC_KEY"],create:(r,[e,t])=>new r.SupabasePublicReader(r.createPublicServerClient(e,t))},{dependency:"@donotdev/firebase",module:"@donotdev/firebase/public",env:["FIREBASE_API_KEY","FIREBASE_PROJECT_ID"],create:(r,[e,t])=>new r.FirestorePublicReader(r.createPublicServerFirestore({apiKey:e,projectId:t}))}]);function ir(r){return ar.find(({dependency:e})=>r(e))}var lr=ar.map(({dependency:r})=>r).join(", ");var Ct=Object.freeze({pageGenerateMetadata:!0}),oa=Object.freeze({"@donotdev/supabase":{exports:"createPublicServerClient, SupabasePublicReader",comment:"RLS returns what a signed-out visitor can read.",construct:`new SupabasePublicReader(
|
|
34
39
|
createPublicServerClient(SUPABASE_URL, SUPABASE_PUBLIC_KEY)
|
|
35
40
|
)`},"@donotdev/firebase":{exports:"createPublicServerFirestore, FirestorePublicReader",comment:"Security Rules return what a signed-out visitor can read.",construct:`new FirestorePublicReader(
|
|
36
41
|
createPublicServerFirestore({ apiKey: FIREBASE_API_KEY, projectId: FIREBASE_PROJECT_ID })
|
|
37
|
-
)`}}),
|
|
42
|
+
)`}}),H=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=ae(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=D.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`}appDependsOn(e){let t=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"),{format:"json"});return!!(t?.dependencies?.[e]||t?.devDependencies?.[e])}serverCrudReader(e,t="the sitemap and llms.txt list published records",n="Mark these pages `seo: { noindex: true }`."){let s=e.filter(d=>d.collection);if(s.length===0)return{imports:"",setup:"",expr:null,schemas:null,named:{}};let o=s.map(d=>d.path).join(", "),a=ir(d=>this.appDependsOn(d));if(!a)throw new Error(`[dndev] ${o} list published records, but the app's backend provider has no server reader (supported: ${lr}). ${n}`);if(!this.appDependsOn("entities")){let d=[...new Set(s.map(f=>f.collection))];throw C("dndev-routes",`${o} ${s.length===1?"lists":"list"} published ${d.map(f=>`"${f}"`).join(", ")} records, read with their entity definition's read schema, but the app does not depend on an \`entities\` package. Add the app's \`entities\` package (exporting the defineEntity definition) to its dependencies. `+n,"missing-entities-package",{routes:s.map(f=>f.path),collections:d})}let{exports:i,comment:l,construct:u}=oa[a.dependency],c=a.env,p=s.map(({path:d,collection:f})=>({path:d,collection:f}));return{imports:`import { ${i} } from '${a.module}';
|
|
38
43
|
import * as entities from 'entities';
|
|
39
44
|
`,setup:`
|
|
40
45
|
// Public (anonymous) reader: ${l}
|
|
@@ -50,7 +55,7 @@ const CRUD = ${u};
|
|
|
50
55
|
// Records are read with their entity's read schema: keyed by the entity's field names
|
|
51
56
|
// (RLS / Security Rules decide what a signed-out visitor reads)
|
|
52
57
|
const READ_SCHEMAS = entityReadSchemas(entities, ${JSON.stringify(p)}, createSchemas);
|
|
53
|
-
`,expr:"CRUD",schemas:"READ_SCHEMAS",named:{"@donotdev/core/server":["createSchemas"],"@donotdev/core/next":["entityReadSchemas"]}}}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...
|
|
58
|
+
`,expr:"CRUD",schemas:"READ_SCHEMAS",named:{"@donotdev/core/server":["createSchemas"],"@donotdev/core/next":["entityReadSchemas"]}}}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...De.discovery,...this.options,...Ct};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}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(),n=L.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!n)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 s=this.generateConfigContent(e);this.writeGeneratedFile(n,s,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),n=Y[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
54
59
|
// Generated at: ${new Date().toISOString()}
|
|
55
60
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
56
61
|
|
|
@@ -67,12 +72,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
67
72
|
timestamp: Date.now(),
|
|
68
73
|
};
|
|
69
74
|
}
|
|
70
|
-
globalThis._DNDEV_CONFIG_.${
|
|
75
|
+
globalThis._DNDEV_CONFIG_.${n} = ${t}Config;
|
|
71
76
|
}
|
|
72
77
|
|
|
73
78
|
// Export for compatibility
|
|
74
79
|
export default ${t}Config;
|
|
75
|
-
`}writeGeneratedFile(e,t,r="file"){let n=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(n,t,{overwrite:!0}),this.logger.debug(`Generated ${r}: ${n}`),n}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}`)}}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")}getAPIRewrites(){throw new Error("getAPIRewrites() 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 s{constructor(e,t={}){if(this.constructor===s)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=K(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let r=await this._getPatterns();this.options.verbose&&r&&(typeof r=="object"&&r.pattern?this.logger.verbose(`Pattern: ${r.pattern}`):typeof r=="string"&&this.logger.verbose(`Pattern: ${r}`),r.dirs&&this.logger.verbose(`Search directories: ${r.dirs.slice(0,3).join(", ")}${r.dirs.length>3?` (${r.dirs.length} total)`:""}`));let n=await this._prepareFiles(),o=await this._scanFiles(r),a=await this._processFiles(o,n);this.cache={...a,timestamp:Date.now()};let i=Date.now()-t;return this.logger.debug(`Discovery completed in ${i}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(r){if(ne(r))throw r;return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${r.message}`),this.logger.error(`Stack: ${r.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 _prepareFiles(){return{}}async _processFiles(e,t){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("/"),r=t[t.length-1],n=r.split(".")[0],o=r.split(".").pop();return{fileName:r,baseName:n,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let r=this.pathResolver.getFileInfo(e);return r?await t(r):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(r){if(ne(r))throw r;return this.logger.debug(`Error processing file ${e}: ${r.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(n=>this._processSingleFile(n,t)))).filter(n=>n!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var ul={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},qr=[{id:"en",name:"English",nativeName:"English",flagCode:"gb"},{id:"us",name:"English (US)",nativeName:"English (US)",countryCode:"US",dialCode:"+1"},{id:"gb",name:"English (UK)",nativeName:"English (UK)",countryCode:"GB",dialCode:"+44"},{id:"en-ca",name:"English (Canada)",nativeName:"English (Canada)",flagCode:"ca",countryCode:"CA",dialCode:"+1"},{id:"au",name:"English (Australia)",nativeName:"English (Australia)",countryCode:"AU",dialCode:"+61"},{id:"ie",name:"English (Ireland)",nativeName:"English (Ireland)",countryCode:"IE",dialCode:"+353"},{id:"es",name:"Spanish",nativeName:"Espa\xF1ol",countryCode:"ES",dialCode:"+34"},{id:"mx",name:"Spanish (Mexico)",nativeName:"Espa\xF1ol (M\xE9xico)",countryCode:"MX",dialCode:"+52"},{id:"es-ar",name:"Spanish (Argentina)",nativeName:"Espa\xF1ol (Argentina)",flagCode:"ar",countryCode:"AR",dialCode:"+54"},{id:"fr",name:"French",nativeName:"Fran\xE7ais",flagCode:"fr",countryCode:"FR",dialCode:"+33"},{id:"fr-be",name:"French (Belgium)",nativeName:"Fran\xE7ais (Belgique)",flagCode:"be",countryCode:"BE",dialCode:"+32"},{id:"ch",name:"French (Switzerland)",nativeName:"Fran\xE7ais (Suisse)",countryCode:"CH",dialCode:"+41"},{id:"de",name:"German",nativeName:"Deutsch",countryCode:"DE",dialCode:"+49"},{id:"at",name:"German (Austria)",nativeName:"Deutsch (\xD6sterreich)",countryCode:"AT",dialCode:"+43"},{id:"it",name:"Italian",nativeName:"Italiano",countryCode:"IT",dialCode:"+39"},{id:"pt",name:"Portuguese",nativeName:"Portugu\xEAs",countryCode:"PT",dialCode:"+351"},{id:"br",name:"Portuguese (Brazil)",nativeName:"Portugu\xEAs (Brasil)",flagCode:"br",countryCode:"BR",dialCode:"+55"},{id:"ru",name:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",countryCode:"RU",dialCode:"+7"},{id:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",countryCode:"JP",dialCode:"+81"},{id:"ko",name:"Korean",nativeName:"\uD55C\uAD6D\uC5B4",countryCode:"KR",dialCode:"+82"},{id:"zh",name:"Chinese",nativeName:"\u4E2D\u6587",countryCode:"CN",dialCode:"+86"},{id:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flagCode:"sa",countryCode:"SA",dialCode:"+966"},{id:"ar-ma",name:"Arabic (Morocco)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0645\u063A\u0631\u0628)",flagCode:"ma",countryCode:"MA",dialCode:"+212"},{id:"ar-dz",name:"Arabic (Algeria)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u062C\u0632\u0627\u0626\u0631)",flagCode:"dz",countryCode:"DZ",dialCode:"+213"},{id:"ar-tn",name:"Arabic (Tunisia)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u062A\u0648\u0646\u0633)",flagCode:"tn",countryCode:"TN",dialCode:"+216"},{id:"ar-ly",name:"Arabic (Libya)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0644\u064A\u0628\u064A\u0627)",flagCode:"ly",countryCode:"LY",dialCode:"+218"},{id:"ar-mr",name:"Arabic (Mauritania)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627)",flagCode:"mr",countryCode:"MR",dialCode:"+222"},{id:"hi",name:"Hindi",nativeName:"\u0939\u093F\u0928\u094D\u0926\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"nl",name:"Dutch",nativeName:"Nederlands",countryCode:"NL",dialCode:"+31"},{id:"sv",name:"Swedish",nativeName:"Svenska",countryCode:"SE",dialCode:"+46"},{id:"da",name:"Danish",nativeName:"Dansk",countryCode:"DK",dialCode:"+45"},{id:"no",name:"Norwegian",nativeName:"Norsk",countryCode:"NO",dialCode:"+47"},{id:"fi",name:"Finnish",nativeName:"Suomi",countryCode:"FI",dialCode:"+358"},{id:"pl",name:"Polish",nativeName:"Polski",countryCode:"PL",dialCode:"+48"},{id:"tr",name:"Turkish",nativeName:"T\xFCrk\xE7e",countryCode:"TR",dialCode:"+90"},{id:"th",name:"Thai",nativeName:"\u0E44\u0E17\u0E22",countryCode:"TH",dialCode:"+66"},{id:"vi",name:"Vietnamese",nativeName:"Ti\u1EBFng Vi\u1EC7t",countryCode:"VN",dialCode:"+84"},{id:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",countryCode:"ID",dialCode:"+62"},{id:"ms",name:"Malay",nativeName:"Bahasa Melayu",flagCode:"my",countryCode:"MY",dialCode:"+60"},{id:"tl",name:"Filipino",nativeName:"Tagalog",countryCode:"PH",dialCode:"+63"},{id:"bg",name:"Bulgarian",nativeName:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",countryCode:"BG",dialCode:"+359"},{id:"cs",name:"Czech",nativeName:"\u010Ce\u0161tina",countryCode:"CZ",dialCode:"+420"},{id:"el",name:"Greek",nativeName:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",countryCode:"GR",dialCode:"+30"},{id:"he",name:"Hebrew",nativeName:"\u05E2\u05D1\u05E8\u05D9\u05EA",countryCode:"IL",dialCode:"+972"},{id:"hu",name:"Hungarian",nativeName:"Magyar",countryCode:"HU",dialCode:"+36"},{id:"is",name:"Icelandic",nativeName:"\xCDslenska",countryCode:"IS",dialCode:"+354"},{id:"lt",name:"Lithuanian",nativeName:"Lietuvi\u0173",countryCode:"LT",dialCode:"+370"},{id:"lv",name:"Latvian",nativeName:"Latvie\u0161u",countryCode:"LV",dialCode:"+371"},{id:"mt",name:"Maltese",nativeName:"Malti",countryCode:"MT",dialCode:"+356"},{id:"ro",name:"Romanian",nativeName:"Rom\xE2n\u0103",countryCode:"RO",dialCode:"+40"},{id:"sk",name:"Slovak",nativeName:"Sloven\u010Dina",countryCode:"SK",dialCode:"+421"},{id:"sl",name:"Slovenian",nativeName:"Sloven\u0161\u010Dina",flagCode:"si",countryCode:"SI",dialCode:"+386"},{id:"uk",name:"Ukrainian",nativeName:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flagCode:"ua",countryCode:"UA",dialCode:"+380"},{id:"et",name:"Estonian",nativeName:"Eesti",countryCode:"EE",dialCode:"+372"},{id:"ca",name:"Catalan",nativeName:"Catal\xE0",countryCode:"ES",dialCode:"+34"},{id:"eu",name:"Basque",nativeName:"Euskara",countryCode:"ES",dialCode:"+34"},{id:"gl",name:"Galician",nativeName:"Galego",countryCode:"ES",dialCode:"+34"},{id:"cy",name:"Welsh",nativeName:"Cymraeg",countryCode:"GB",dialCode:"+44"},{id:"ga",name:"Irish",nativeName:"Gaeilge",flagCode:"ie",countryCode:"IE",dialCode:"+353"},{id:"gd",name:"Scottish Gaelic",nativeName:"G\xE0idhlig",flagCode:"gb-sct",countryCode:"GB",dialCode:"+44"},{id:"br-fr",name:"Breton",nativeName:"Brezhoneg",flagCode:"bzh",countryCode:"FR",dialCode:"+33"},{id:"co",name:"Corsican",nativeName:"Corsu",flagCode:"fr-cor",countryCode:"FR",dialCode:"+33"},{id:"oc",name:"Occitan",nativeName:"Occitan",countryCode:"FR",dialCode:"+33"},{id:"rm",name:"Romansh",nativeName:"Rumantsch",countryCode:"CH",dialCode:"+41"},{id:"lb",name:"Luxembourgish",nativeName:"L\xEBtzebuergesch",countryCode:"LU",dialCode:"+352"},{id:"af",name:"Afrikaans",nativeName:"Afrikaans",countryCode:"ZA",dialCode:"+27"},{id:"sw",name:"Swahili",nativeName:"Kiswahili",countryCode:"KE",dialCode:"+254"},{id:"am",name:"Amharic",nativeName:"\u12A0\u121B\u122D\u129B",flagCode:"et",countryCode:"ET",dialCode:"+251"},{id:"bn",name:"Bengali",nativeName:"\u09AC\u09BE\u0982\u09B2\u09BE",flagCode:"bd",countryCode:"BD",dialCode:"+880"},{id:"gu",name:"Gujarati",nativeName:"\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"kn",name:"Kannada",nativeName:"\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ml",name:"Malayalam",nativeName:"\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"mr",name:"Marathi",nativeName:"\u092E\u0930\u093E\u0920\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ne",name:"Nepali",nativeName:"\u0928\u0947\u092A\u093E\u0932\u0940",flagCode:"np",countryCode:"NP",dialCode:"+977"},{id:"pa",name:"Punjabi",nativeName:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"si",name:"Sinhala",nativeName:"\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",countryCode:"LK",dialCode:"+94"},{id:"ta",name:"Tamil",nativeName:"\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"te",name:"Telugu",nativeName:"\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ur",name:"Urdu",nativeName:"\u0627\u0631\u062F\u0648",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"fa",name:"Persian",nativeName:"\u0641\u0627\u0631\u0633\u06CC",flagCode:"ir",countryCode:"IR",dialCode:"+98"},{id:"ps",name:"Pashto",nativeName:"\u067E\u069A\u062A\u0648",countryCode:"AF",dialCode:"+93"},{id:"uz",name:"Uzbek",nativeName:"O\u02BBzbek",countryCode:"UZ",dialCode:"+998"},{id:"kk",name:"Kazakh",nativeName:"\u049A\u0430\u0437\u0430\u049B",flagCode:"kz",countryCode:"KZ",dialCode:"+7"},{id:"ky",name:"Kyrgyz",nativeName:"\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430",flagCode:"kg",countryCode:"KG",dialCode:"+996"},{id:"tg",name:"Tajik",nativeName:"\u0422\u043E\u04B7\u0438\u043A\u04E3",flagCode:"tj",countryCode:"TJ",dialCode:"+992"},{id:"mn",name:"Mongolian",nativeName:"\u041C\u043E\u043D\u0433\u043E\u043B",countryCode:"MN",dialCode:"+976"},{id:"my",name:"Burmese",nativeName:"\u1019\u103C\u1014\u103A\u1019\u102C",flagCode:"mm",countryCode:"MM",dialCode:"+95"},{id:"km",name:"Khmer",nativeName:"\u1781\u17D2\u1798\u17C2\u179A",flagCode:"kh",countryCode:"KH",dialCode:"+855"},{id:"lo",name:"Lao",nativeName:"\u0EA5\u0EB2\u0EA7",flagCode:"la",countryCode:"LA",dialCode:"+856"},{id:"ka",name:"Georgian",nativeName:"\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",flagCode:"ge",countryCode:"GE",dialCode:"+995"},{id:"hy",name:"Armenian",nativeName:"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",flagCode:"am",countryCode:"AM",dialCode:"+374"},{id:"az",name:"Azerbaijani",nativeName:"Az\u0259rbaycan",countryCode:"AZ",dialCode:"+994"},{id:"be",name:"Belarusian",nativeName:"\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",flagCode:"by",countryCode:"BY",dialCode:"+375"},{id:"mk",name:"Macedonian",nativeName:"\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",countryCode:"MK",dialCode:"+389"},{id:"sr",name:"Serbian",nativeName:"\u0421\u0440\u043F\u0441\u043A\u0438",countryCode:"RS",dialCode:"+381"},{id:"bs",name:"Bosnian",nativeName:"Bosanski",flagCode:"ba",countryCode:"BA",dialCode:"+387"},{id:"hr",name:"Croatian",nativeName:"Hrvatski",countryCode:"HR",dialCode:"+385"},{id:"sq",name:"Albanian",nativeName:"Shqip",flagCode:"al",countryCode:"AL",dialCode:"+355"},{id:"md",name:"Moldovan",nativeName:"Moldoveneasc\u0103",countryCode:"MD",dialCode:"+373"}],Po={US:"United States",GB:"United Kingdom",CA:"Canada",AU:"Australia",IE:"Ireland",FR:"France",BE:"Belgium",CH:"Switzerland",DE:"Germany",AT:"Austria",IT:"Italy",PT:"Portugal",BR:"Brazil",ES:"Spain",MX:"Mexico",AR:"Argentina",RU:"Russia",JP:"Japan",KR:"South Korea",CN:"China",SE:"Sweden",NO:"Norway",DK:"Denmark",FI:"Finland",NL:"Netherlands",PL:"Poland",CZ:"Czech Republic",HU:"Hungary",RO:"Romania",BG:"Bulgaria",GR:"Greece",TR:"Turkey",IL:"Israel",IN:"India",ZA:"South Africa"};function Co(){return qr.filter(s=>s.countryCode!==void 0&&s.dialCode!==void 0).map(s=>({code:s.countryCode,dialCode:s.dialCode,flagCode:s.flagCode||s.id,name:s.countryName||Po[s.countryCode]||s.name}))}var Ao=Co(),yt="/flags";function Jr(s){return`${s.toLowerCase()}.svg`}function vt(s){return qr.find(t=>t.id===s)?.flagCode||s}function Vr(){return[...new Set(Ao.map(s=>s.flagCode))]}var de={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},No="public/logo.svg is missing: it is the site logo (Organization / publisher logo in the JSON-LD, the default logo) and the source of the favicon, PWA icons and og-image.png. Add public/logo.svg.",Kr="/manifest.json",Be=class extends X{constructor(e,t={}){super(e,{assets:q.assets.fallback,assetPatterns:q.assets.patterns,frameworkPackage:st.package,assetsPath:st.assetsPath,modernFormats:q.assets.modern,...t}),this.hasRunForSession=!1,this.flagCodes=null,this.entityResolver=null}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _prepareFiles(){let e=this.pathResolver.getAppRoot(),t=await this._ensureDefaultAssets(e);if(this.flagCodes){let i=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(i?[...new Set([...this.flagCodes,...Vr()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${yt}/: ${l.join(", ")}`)}let r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn(No);let o=[],a=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(o=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:o}}async _processFiles(e,{copiedAssets:t,generatedAssets:r}){let n=this.pathResolver.getAppRoot(),{consumerFiles:o}=e,a=await this._processAssetFiles(o),i=this._buildAssetManifest(a,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${Kr}`))}),l=await this._readLogoSvgContent("/logo.svg",n);return{assets:a,manifest:{...i,logoSvgContent:l},copiedAssets:t,generatedAssets:r}}_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`}useFlagCodes(e,t){this.flagCodes=e,this.entityResolver=t}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 r=this.getAssets().map(o=>o.path),n=t||this.options.modernFormats;for(let o of n){let a=`/${e}.${o}`;if(r.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let r=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${r}`),!r)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let n=this.pathResolver.resolveAppPath($e.public);this.pathResolver.pathExists(n)||(this.pathResolver.mkdir(n),this.logger.debug(`Created public directory: ${n}`));for(let o of this.options.assets)await this._ensureAsset(o,n,r)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(r){this.logger.debug(`Failed to ensure default assets: ${r.message}`)}return t}async _ensureAsset(e,t,r){let n=this.pathResolver.resolveAppPath(`${$e.public}/${e}`);if(this.pathResolver.pathExists(n))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${r}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,n))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}_ensureFlags(e){let t=this.pathResolver.resolveFrameworkPackage("@donotdev/core");if(!t)throw new Error("Flag copy: @donotdev/core not found");let r=this.pathResolver.normalizePath(`${t}/${fe.PUBLISHED_FLAGS}`),n=`${$e.public}${yt}`,o=[];for(let a of e){let i=Jr(a),l=this.pathResolver.resolveAppPath(`${n}/${i}`);if(this.pathResolver.pathExists(l))continue;let u=`${r}/${i}`;if(!this.pathResolver.pathExists(u)){this.logger.warn(`No flag artwork for "${a}": add ${n}/${i} to the app`);continue}if(!this.pathResolver.copySync(u,l))throw new Error(`Flag copy: cannot copy ${u} to ${l}`);o.push(i)}return o}async _processAssetFiles(e){let t=[];for(let r of e)try{let n=this.pathResolver.getFileInfo(r);if(n&&n.isFile){let o=r.split("/").pop()||r.split("\\").pop(),a=this._analyzeAsset(o,n.size);a&&t.push(a)}}catch(n){this.logger.debug(`Error processing asset file ${r}: ${n.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let r=this._determineAssetType(e),n=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:r,format:n,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(n)}:(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 r=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(r)?"image":["woff2","woff","ttf","otf"].includes(r)?"font":["json"].includes(r)?"json":["ico"].includes(r)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,r=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+r[n]}_matchesPattern(e,t){let r=t.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${r}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let r=e.map(o=>o.path);return{logo:{optimal:this._getOptimalAsset("logo",r,this.options.modernFormats),fallback:this._getOptimalAsset("logo",r,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",r,["svg","ico"]),fallback:this._getOptimalAsset("favicon",r,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",r,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",r,["png"]),512:this._getOptimalAsset("android-chrome-512x512",r,["png"])},manifest:t?Kr:null,modernFormats:e.filter(o=>o.isModern).map(o=>o.path),fallbackFormats:e.filter(o=>!o.isModern).map(o=>o.path)}}_getOptimalAsset(e,t,r){for(let n of r){let o=`/${e}.${n}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),r=await this._resolvePackage("@donotdev/ui",t);if(!r)return this.logger.debug("@donotdev/ui package not found"),null;let n=this.pathResolver.normalizePath(`${r}/assets`);return this.pathResolver.pathExists(n)?(this.logger.debug(`Using framework assets from: ${n}`),n):(this.logger.debug(`Assets directory not found: ${n}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let r=this.pathResolver.resolveFrameworkPackage(e,t);return r?(this.logger.debug(`Found package: ${r}`),r):(this.logger.debug(`Package ${e} not found`),null)}catch(r){return this.logger.debug(`Error resolving package ${e}: ${r.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 r=e.slice(1),n=this.pathResolver.resolveAppPath(`${$e.public}/${r}`);return this.pathResolver.pathExists(n)&&await this.pathResolver.read(n,{format:"text"})||null}catch(r){return this.logger.debug(`Failed to read logo SVG content: ${r.message}`),null}}async _renderOgImage(e,t){let{width:r,height:n}=await e(t).metadata(),o=Math.min(de.logoWidth/r,de.logoHeight/n),a=await e(t,{density:Math.ceil(72*o)}).resize(de.logoWidth,de.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:de.width,height:de.height,channels:4,background:de.background}}).composite([{input:a}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),r=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 n=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...n].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let p=`${r}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{await this.pathResolver.write(p,l),a.push(c.name)}catch(d){this.logger.debug(`Failed to copy ${c.name}: ${d.message}`),i.push(c.name)}}let u=await import("sharp").catch(()=>null);if(!u)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...n.map(c=>c.name));else{for(let p of n){let d=`${r}/${p.name}`;if(this.pathResolver.pathExists(d)){i.push(p.name);continue}try{let f=u.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;p.format==="ico"?h=await f.toFormat("png").toBuffer():h=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(d,h),a.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),i.push(p.name)}}let c=xe.slice(1);if(this.pathResolver.pathExists(`${r}/${c}`))i.push(c);else try{let p=await this._renderOgImage(u.default,t);await this.pathResolver.write(`${r}/${c}`,p),a.push(c)}catch(p){this.logger.debug(`Failed to generate ${c}: ${p.message}`),i.push(c)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:[...o,...n].map(u=>u.name),error:l.message}}}};var bt=class extends B{constructor(e={}){super(Be,e)}getHandlerDefaults(){return{manifestPath:k.next.assetManifest,generateManifest:!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
|
|
80
|
+
`}writeGeneratedFile(e,t,n="file"){let s=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(s,t,{overwrite:!0}),this.logger.debug(`Generated ${n}: ${s}`),s}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}`)}}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")}getAPIRewrites(){throw new Error("getAPIRewrites() 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 ee=class r{constructor(e,t={}){if(this.constructor===r)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=ae(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 n=await this._getPatterns();this.options.verbose&&n&&(typeof n=="object"&&n.pattern?this.logger.verbose(`Pattern: ${n.pattern}`):typeof n=="string"&&this.logger.verbose(`Pattern: ${n}`),n.dirs&&this.logger.verbose(`Search directories: ${n.dirs.slice(0,3).join(", ")}${n.dirs.length>3?` (${n.dirs.length} total)`:""}`));let s=await this._prepareFiles(),o=await this._scanFiles(n),a=await this._processFiles(o,s);this.cache={...a,timestamp:Date.now()};let i=Date.now()-t;return this.logger.debug(`Discovery completed in ${i}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){if(ce(n))throw n;return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${n.message}`),this.logger.error(`Stack: ${n.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 _prepareFiles(){return{}}async _processFiles(e,t){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("/"),n=t[t.length-1],s=n.split(".")[0],o=n.split(".").pop();return{fileName:n,baseName:s,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let n=this.pathResolver.getFileInfo(e);return n?await t(n):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(n){if(ce(n))throw n;return this.logger.debug(`Error processing file ${e}: ${n.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(s=>this._processSingleFile(s,t)))).filter(s=>s!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var tc={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},cr=[{id:"en",name:"English",nativeName:"English",flagCode:"gb"},{id:"us",name:"English (US)",nativeName:"English (US)",countryCode:"US",dialCode:"+1"},{id:"gb",name:"English (UK)",nativeName:"English (UK)",countryCode:"GB",dialCode:"+44"},{id:"en-ca",name:"English (Canada)",nativeName:"English (Canada)",flagCode:"ca",countryCode:"CA",dialCode:"+1"},{id:"au",name:"English (Australia)",nativeName:"English (Australia)",countryCode:"AU",dialCode:"+61"},{id:"ie",name:"English (Ireland)",nativeName:"English (Ireland)",countryCode:"IE",dialCode:"+353"},{id:"es",name:"Spanish",nativeName:"Espa\xF1ol",countryCode:"ES",dialCode:"+34"},{id:"mx",name:"Spanish (Mexico)",nativeName:"Espa\xF1ol (M\xE9xico)",countryCode:"MX",dialCode:"+52"},{id:"es-ar",name:"Spanish (Argentina)",nativeName:"Espa\xF1ol (Argentina)",flagCode:"ar",countryCode:"AR",dialCode:"+54"},{id:"fr",name:"French",nativeName:"Fran\xE7ais",flagCode:"fr",countryCode:"FR",dialCode:"+33"},{id:"fr-be",name:"French (Belgium)",nativeName:"Fran\xE7ais (Belgique)",flagCode:"be",countryCode:"BE",dialCode:"+32"},{id:"ch",name:"French (Switzerland)",nativeName:"Fran\xE7ais (Suisse)",countryCode:"CH",dialCode:"+41"},{id:"de",name:"German",nativeName:"Deutsch",countryCode:"DE",dialCode:"+49"},{id:"at",name:"German (Austria)",nativeName:"Deutsch (\xD6sterreich)",countryCode:"AT",dialCode:"+43"},{id:"it",name:"Italian",nativeName:"Italiano",countryCode:"IT",dialCode:"+39"},{id:"pt",name:"Portuguese",nativeName:"Portugu\xEAs",countryCode:"PT",dialCode:"+351"},{id:"br",name:"Portuguese (Brazil)",nativeName:"Portugu\xEAs (Brasil)",flagCode:"br",countryCode:"BR",dialCode:"+55"},{id:"ru",name:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",countryCode:"RU",dialCode:"+7"},{id:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",countryCode:"JP",dialCode:"+81"},{id:"ko",name:"Korean",nativeName:"\uD55C\uAD6D\uC5B4",countryCode:"KR",dialCode:"+82"},{id:"zh",name:"Chinese",nativeName:"\u4E2D\u6587",countryCode:"CN",dialCode:"+86"},{id:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flagCode:"sa",countryCode:"SA",dialCode:"+966"},{id:"ar-ma",name:"Arabic (Morocco)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0645\u063A\u0631\u0628)",flagCode:"ma",countryCode:"MA",dialCode:"+212"},{id:"ar-dz",name:"Arabic (Algeria)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u062C\u0632\u0627\u0626\u0631)",flagCode:"dz",countryCode:"DZ",dialCode:"+213"},{id:"ar-tn",name:"Arabic (Tunisia)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u062A\u0648\u0646\u0633)",flagCode:"tn",countryCode:"TN",dialCode:"+216"},{id:"ar-ly",name:"Arabic (Libya)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0644\u064A\u0628\u064A\u0627)",flagCode:"ly",countryCode:"LY",dialCode:"+218"},{id:"ar-mr",name:"Arabic (Mauritania)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627)",flagCode:"mr",countryCode:"MR",dialCode:"+222"},{id:"hi",name:"Hindi",nativeName:"\u0939\u093F\u0928\u094D\u0926\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"nl",name:"Dutch",nativeName:"Nederlands",countryCode:"NL",dialCode:"+31"},{id:"sv",name:"Swedish",nativeName:"Svenska",countryCode:"SE",dialCode:"+46"},{id:"da",name:"Danish",nativeName:"Dansk",countryCode:"DK",dialCode:"+45"},{id:"no",name:"Norwegian",nativeName:"Norsk",countryCode:"NO",dialCode:"+47"},{id:"fi",name:"Finnish",nativeName:"Suomi",countryCode:"FI",dialCode:"+358"},{id:"pl",name:"Polish",nativeName:"Polski",countryCode:"PL",dialCode:"+48"},{id:"tr",name:"Turkish",nativeName:"T\xFCrk\xE7e",countryCode:"TR",dialCode:"+90"},{id:"th",name:"Thai",nativeName:"\u0E44\u0E17\u0E22",countryCode:"TH",dialCode:"+66"},{id:"vi",name:"Vietnamese",nativeName:"Ti\u1EBFng Vi\u1EC7t",countryCode:"VN",dialCode:"+84"},{id:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",countryCode:"ID",dialCode:"+62"},{id:"ms",name:"Malay",nativeName:"Bahasa Melayu",flagCode:"my",countryCode:"MY",dialCode:"+60"},{id:"tl",name:"Filipino",nativeName:"Tagalog",countryCode:"PH",dialCode:"+63"},{id:"bg",name:"Bulgarian",nativeName:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",countryCode:"BG",dialCode:"+359"},{id:"cs",name:"Czech",nativeName:"\u010Ce\u0161tina",countryCode:"CZ",dialCode:"+420"},{id:"el",name:"Greek",nativeName:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",countryCode:"GR",dialCode:"+30"},{id:"he",name:"Hebrew",nativeName:"\u05E2\u05D1\u05E8\u05D9\u05EA",countryCode:"IL",dialCode:"+972"},{id:"hu",name:"Hungarian",nativeName:"Magyar",countryCode:"HU",dialCode:"+36"},{id:"is",name:"Icelandic",nativeName:"\xCDslenska",countryCode:"IS",dialCode:"+354"},{id:"lt",name:"Lithuanian",nativeName:"Lietuvi\u0173",countryCode:"LT",dialCode:"+370"},{id:"lv",name:"Latvian",nativeName:"Latvie\u0161u",countryCode:"LV",dialCode:"+371"},{id:"mt",name:"Maltese",nativeName:"Malti",countryCode:"MT",dialCode:"+356"},{id:"ro",name:"Romanian",nativeName:"Rom\xE2n\u0103",countryCode:"RO",dialCode:"+40"},{id:"sk",name:"Slovak",nativeName:"Sloven\u010Dina",countryCode:"SK",dialCode:"+421"},{id:"sl",name:"Slovenian",nativeName:"Sloven\u0161\u010Dina",flagCode:"si",countryCode:"SI",dialCode:"+386"},{id:"uk",name:"Ukrainian",nativeName:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flagCode:"ua",countryCode:"UA",dialCode:"+380"},{id:"et",name:"Estonian",nativeName:"Eesti",countryCode:"EE",dialCode:"+372"},{id:"ca",name:"Catalan",nativeName:"Catal\xE0",countryCode:"ES",dialCode:"+34"},{id:"eu",name:"Basque",nativeName:"Euskara",countryCode:"ES",dialCode:"+34"},{id:"gl",name:"Galician",nativeName:"Galego",countryCode:"ES",dialCode:"+34"},{id:"cy",name:"Welsh",nativeName:"Cymraeg",countryCode:"GB",dialCode:"+44"},{id:"ga",name:"Irish",nativeName:"Gaeilge",flagCode:"ie",countryCode:"IE",dialCode:"+353"},{id:"gd",name:"Scottish Gaelic",nativeName:"G\xE0idhlig",flagCode:"gb-sct",countryCode:"GB",dialCode:"+44"},{id:"br-fr",name:"Breton",nativeName:"Brezhoneg",flagCode:"bzh",countryCode:"FR",dialCode:"+33"},{id:"co",name:"Corsican",nativeName:"Corsu",flagCode:"fr-cor",countryCode:"FR",dialCode:"+33"},{id:"oc",name:"Occitan",nativeName:"Occitan",countryCode:"FR",dialCode:"+33"},{id:"rm",name:"Romansh",nativeName:"Rumantsch",countryCode:"CH",dialCode:"+41"},{id:"lb",name:"Luxembourgish",nativeName:"L\xEBtzebuergesch",countryCode:"LU",dialCode:"+352"},{id:"af",name:"Afrikaans",nativeName:"Afrikaans",countryCode:"ZA",dialCode:"+27"},{id:"sw",name:"Swahili",nativeName:"Kiswahili",countryCode:"KE",dialCode:"+254"},{id:"am",name:"Amharic",nativeName:"\u12A0\u121B\u122D\u129B",flagCode:"et",countryCode:"ET",dialCode:"+251"},{id:"bn",name:"Bengali",nativeName:"\u09AC\u09BE\u0982\u09B2\u09BE",flagCode:"bd",countryCode:"BD",dialCode:"+880"},{id:"gu",name:"Gujarati",nativeName:"\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"kn",name:"Kannada",nativeName:"\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ml",name:"Malayalam",nativeName:"\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"mr",name:"Marathi",nativeName:"\u092E\u0930\u093E\u0920\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ne",name:"Nepali",nativeName:"\u0928\u0947\u092A\u093E\u0932\u0940",flagCode:"np",countryCode:"NP",dialCode:"+977"},{id:"pa",name:"Punjabi",nativeName:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"si",name:"Sinhala",nativeName:"\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",countryCode:"LK",dialCode:"+94"},{id:"ta",name:"Tamil",nativeName:"\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"te",name:"Telugu",nativeName:"\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ur",name:"Urdu",nativeName:"\u0627\u0631\u062F\u0648",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"fa",name:"Persian",nativeName:"\u0641\u0627\u0631\u0633\u06CC",flagCode:"ir",countryCode:"IR",dialCode:"+98"},{id:"ps",name:"Pashto",nativeName:"\u067E\u069A\u062A\u0648",countryCode:"AF",dialCode:"+93"},{id:"uz",name:"Uzbek",nativeName:"O\u02BBzbek",countryCode:"UZ",dialCode:"+998"},{id:"kk",name:"Kazakh",nativeName:"\u049A\u0430\u0437\u0430\u049B",flagCode:"kz",countryCode:"KZ",dialCode:"+7"},{id:"ky",name:"Kyrgyz",nativeName:"\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430",flagCode:"kg",countryCode:"KG",dialCode:"+996"},{id:"tg",name:"Tajik",nativeName:"\u0422\u043E\u04B7\u0438\u043A\u04E3",flagCode:"tj",countryCode:"TJ",dialCode:"+992"},{id:"mn",name:"Mongolian",nativeName:"\u041C\u043E\u043D\u0433\u043E\u043B",countryCode:"MN",dialCode:"+976"},{id:"my",name:"Burmese",nativeName:"\u1019\u103C\u1014\u103A\u1019\u102C",flagCode:"mm",countryCode:"MM",dialCode:"+95"},{id:"km",name:"Khmer",nativeName:"\u1781\u17D2\u1798\u17C2\u179A",flagCode:"kh",countryCode:"KH",dialCode:"+855"},{id:"lo",name:"Lao",nativeName:"\u0EA5\u0EB2\u0EA7",flagCode:"la",countryCode:"LA",dialCode:"+856"},{id:"ka",name:"Georgian",nativeName:"\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",flagCode:"ge",countryCode:"GE",dialCode:"+995"},{id:"hy",name:"Armenian",nativeName:"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",flagCode:"am",countryCode:"AM",dialCode:"+374"},{id:"az",name:"Azerbaijani",nativeName:"Az\u0259rbaycan",countryCode:"AZ",dialCode:"+994"},{id:"be",name:"Belarusian",nativeName:"\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",flagCode:"by",countryCode:"BY",dialCode:"+375"},{id:"mk",name:"Macedonian",nativeName:"\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",countryCode:"MK",dialCode:"+389"},{id:"sr",name:"Serbian",nativeName:"\u0421\u0440\u043F\u0441\u043A\u0438",countryCode:"RS",dialCode:"+381"},{id:"bs",name:"Bosnian",nativeName:"Bosanski",flagCode:"ba",countryCode:"BA",dialCode:"+387"},{id:"hr",name:"Croatian",nativeName:"Hrvatski",countryCode:"HR",dialCode:"+385"},{id:"sq",name:"Albanian",nativeName:"Shqip",flagCode:"al",countryCode:"AL",dialCode:"+355"},{id:"md",name:"Moldovan",nativeName:"Moldoveneasc\u0103",countryCode:"MD",dialCode:"+373"}],aa={US:"United States",GB:"United Kingdom",CA:"Canada",AU:"Australia",IE:"Ireland",FR:"France",BE:"Belgium",CH:"Switzerland",DE:"Germany",AT:"Austria",IT:"Italy",PT:"Portugal",BR:"Brazil",ES:"Spain",MX:"Mexico",AR:"Argentina",RU:"Russia",JP:"Japan",KR:"South Korea",CN:"China",SE:"Sweden",NO:"Norway",DK:"Denmark",FI:"Finland",NL:"Netherlands",PL:"Poland",CZ:"Czech Republic",HU:"Hungary",RO:"Romania",BG:"Bulgaria",GR:"Greece",TR:"Turkey",IL:"Israel",IN:"India",ZA:"South Africa"};function ia(){return cr.filter(r=>r.countryCode!==void 0&&r.dialCode!==void 0).map(r=>({code:r.countryCode,dialCode:r.dialCode,flagCode:r.flagCode||r.id,name:r.countryName||aa[r.countryCode]||r.name}))}var la=ia(),At="/flags";function ur(r){return`${r.toLowerCase()}.svg`}function Nt(r){return cr.find(t=>t.id===r)?.flagCode||r}function pr(){return[...new Set(la.map(r=>r.flagCode))]}var be={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},ca="public/logo.svg is missing: it is the site logo (Organization / publisher logo in the JSON-LD, the default logo) and the source of the favicon, PWA icons and og-image.png. Add public/logo.svg.",dr="/manifest.json",qe=class extends ee{constructor(e,t={}){super(e,{assets:X.assets.fallback,assetPatterns:X.assets.patterns,frameworkPackage:lt.package,assetsPath:lt.assetsPath,modernFormats:X.assets.modern,...t}),this.hasRunForSession=!1,this.flagCodes=null,this.entityResolver=null}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _prepareFiles(){let e=this.pathResolver.getAppRoot(),t=await this._ensureDefaultAssets(e);if(this.flagCodes){let i=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(i?[...new Set([...this.flagCodes,...pr()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${At}/: ${l.join(", ")}`)}let n=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(n)||this.logger.warn(ca);let o=[],a=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(o=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:o}}async _processFiles(e,{copiedAssets:t,generatedAssets:n}){let s=this.pathResolver.getAppRoot(),{consumerFiles:o}=e,a=await this._processAssetFiles(o),i=this._buildAssetManifest(a,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${dr}`))}),l=await this._readLogoSvgContent("/logo.svg",s);return{assets:a,manifest:{...i,logoSvgContent:l},copiedAssets:t,generatedAssets:n}}_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`}useFlagCodes(e,t){this.flagCodes=e,this.entityResolver=t}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 n=this.getAssets().map(o=>o.path),s=t||this.options.modernFormats;for(let o of s){let a=`/${e}.${o}`;if(n.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let n=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${n}`),!n)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let s=this.pathResolver.resolveAppPath(le.public);this.pathResolver.pathExists(s)||(this.pathResolver.mkdir(s),this.logger.debug(`Created public directory: ${s}`));for(let o of this.options.assets)await this._ensureAsset(o,s,n)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(n){this.logger.debug(`Failed to ensure default assets: ${n.message}`)}return t}async _ensureAsset(e,t,n){let s=this.pathResolver.resolveAppPath(`${le.public}/${e}`);if(this.pathResolver.pathExists(s))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${n}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,s))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}_ensureFlags(e){let t=this.pathResolver.resolveFrameworkPackage("@donotdev/core");if(!t)throw new Error("Flag copy: @donotdev/core not found");let n=this.pathResolver.normalizePath(`${t}/${we.PUBLISHED_FLAGS}`),s=`${le.public}${At}`,o=[];for(let a of e){let i=ur(a),l=this.pathResolver.resolveAppPath(`${s}/${i}`);if(this.pathResolver.pathExists(l))continue;let u=`${n}/${i}`;if(!this.pathResolver.pathExists(u)){this.logger.warn(`No flag artwork for "${a}": add ${s}/${i} to the app`);continue}if(!this.pathResolver.copySync(u,l))throw new Error(`Flag copy: cannot copy ${u} to ${l}`);o.push(i)}return o}async _processAssetFiles(e){let t=[];for(let n of e)try{let s=this.pathResolver.getFileInfo(n);if(s&&s.isFile){let o=n.split("/").pop()||n.split("\\").pop(),a=this._analyzeAsset(o,s.size);a&&t.push(a)}}catch(s){this.logger.debug(`Error processing asset file ${n}: ${s.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let n=this._determineAssetType(e),s=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:n,format:s,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(s)}:(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 n=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(n)?"image":["woff2","woff","ttf","otf"].includes(n)?"font":["json"].includes(n)?"json":["ico"].includes(n)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,n=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+n[s]}_matchesPattern(e,t){let n=t.split("*").map(s=>s.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let n=e.map(o=>o.path);return{logo:{optimal:this._getOptimalAsset("logo",n,this.options.modernFormats),fallback:this._getOptimalAsset("logo",n,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",n,["svg","ico"]),fallback:this._getOptimalAsset("favicon",n,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",n,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",n,["png"]),512:this._getOptimalAsset("android-chrome-512x512",n,["png"])},manifest:t?dr:null,modernFormats:e.filter(o=>o.isModern).map(o=>o.path),fallbackFormats:e.filter(o=>!o.isModern).map(o=>o.path)}}_getOptimalAsset(e,t,n){for(let s of n){let o=`/${e}.${s}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),n=await this._resolvePackage("@donotdev/ui",t);if(!n)return this.logger.debug("@donotdev/ui package not found"),null;let s=this.pathResolver.normalizePath(`${n}/assets`);return this.pathResolver.pathExists(s)?(this.logger.debug(`Using framework assets from: ${s}`),s):(this.logger.debug(`Assets directory not found: ${s}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let n=this.pathResolver.resolveFrameworkPackage(e,t);return n?(this.logger.debug(`Found package: ${n}`),n):(this.logger.debug(`Package ${e} not found`),null)}catch(n){return this.logger.debug(`Error resolving package ${e}: ${n.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 n=e.slice(1),s=this.pathResolver.resolveAppPath(`${le.public}/${n}`);return this.pathResolver.pathExists(s)&&await this.pathResolver.read(s,{format:"text"})||null}catch(n){return this.logger.debug(`Failed to read logo SVG content: ${n.message}`),null}}async _renderOgImage(e,t){let{width:n,height:s}=await e(t).metadata(),o=Math.min(be.logoWidth/n,be.logoHeight/s),a=await e(t,{density:Math.ceil(72*o)}).resize(be.logoWidth,be.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:be.width,height:be.height,channels:4,background:be.background}}).composite([{input:a}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),n=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 s=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...s].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let p=`${n}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{await this.pathResolver.write(p,l),a.push(c.name)}catch(d){this.logger.debug(`Failed to copy ${c.name}: ${d.message}`),i.push(c.name)}}let u=await import("sharp").catch(()=>null);if(!u)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...s.map(c=>c.name));else{for(let p of s){let d=`${n}/${p.name}`;if(this.pathResolver.pathExists(d)){i.push(p.name);continue}try{let f=u.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;p.format==="ico"?h=await f.toFormat("png").toBuffer():h=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(d,h),a.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),i.push(p.name)}}let c=Ne.slice(1);if(this.pathResolver.pathExists(`${n}/${c}`))i.push(c);else try{let p=await this._renderOgImage(u.default,t);await this.pathResolver.write(`${n}/${c}`,p),a.push(c)}catch(p){this.logger.debug(`Failed to generate ${c}: ${p.message}`),i.push(c)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:[...o,...s].map(u=>u.name),error:l.message}}}};var _t=class extends H{constructor(e={}){super(qe,e)}getHandlerDefaults(){return{manifestPath:L.next.assetManifest,generateManifest:!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
|
|
76
81
|
// Generated at: ${new Date().toISOString()}
|
|
77
82
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
78
83
|
|
|
@@ -89,7 +94,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
89
94
|
timestamp: Date.now(),
|
|
90
95
|
};
|
|
91
96
|
}
|
|
92
|
-
globalThis._DNDEV_CONFIG_.${
|
|
97
|
+
globalThis._DNDEV_CONFIG_.${Y.assets} = {
|
|
93
98
|
mapping: assetConfig.manifest,
|
|
94
99
|
logoSvgContent: ${JSON.stringify(t)},
|
|
95
100
|
manifest: {
|
|
@@ -101,15 +106,15 @@ if (typeof globalThis !== 'undefined') {
|
|
|
101
106
|
|
|
102
107
|
// Export for compatibility
|
|
103
108
|
export default assetConfig;
|
|
104
|
-
`}logDiscoveryResults(e){let t=e.assets?.length||0,
|
|
109
|
+
`}logDiscoveryResults(e){let t=e.assets?.length||0,n=e.generatedAssets?.length||0;n>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${n} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}useFlagCodes(e,t){this.discovery.useFlagCodes(e,t)}async getDiscoveryData(){return await this.discovery.discoverAssets()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}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)}async generateAssetManifest(e){let t=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",t,"asset manifest")}generateAssetManifestContent(e){let t=e.assets.map(o=>` {
|
|
105
110
|
path: '${o.path}',
|
|
106
111
|
type: '${o.type}',
|
|
107
112
|
format: '${o.format}',
|
|
108
113
|
size: ${o.size},
|
|
109
114
|
optimized: ${o.optimized||!1}
|
|
110
115
|
}`).join(`,
|
|
111
|
-
`),
|
|
112
|
-
`),
|
|
116
|
+
`),n=Object.entries(e.manifest).map(([o,a])=>` ${o}: ${JSON.stringify(a)}`).join(`,
|
|
117
|
+
`),s=e.manifest.logoSvgContent||null;return`// Auto-generated asset manifest by @donotdev/config
|
|
113
118
|
// Generated at ${new Date().toISOString()}
|
|
114
119
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
115
120
|
|
|
@@ -118,7 +123,7 @@ ${t}
|
|
|
118
123
|
];
|
|
119
124
|
|
|
120
125
|
export const assetManifest = {
|
|
121
|
-
${
|
|
126
|
+
${n}
|
|
122
127
|
};
|
|
123
128
|
|
|
124
129
|
export const copiedAssets = ${JSON.stringify(e.copiedAssets,null,2)};
|
|
@@ -131,23 +136,23 @@ export const assetStats = {
|
|
|
131
136
|
};
|
|
132
137
|
|
|
133
138
|
export default assets;
|
|
134
|
-
`}};function
|
|
139
|
+
`}};function fr(r={}){return new _t(r)}import kt from"node:fs";import ua from"node:path";var Dt=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!kt.existsSync(e))return{blogDir:e,files:[]};let t;try{t=kt.readdirSync(e)}catch{return{blogDir:e,files:[]}}let n=t.filter(s=>s.endsWith(".md")&&!s.startsWith(".")).sort();return{blogDir:e,files:n}}},Tt=class extends H{constructor(e={}){super(Dt,e)}getHandlerDefaults(){return{outputPath:L.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:n}=e;if(n.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let s=this._buildGeneratedContent(t,n);this.writeGeneratedFile(this.options.outputPath,s,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
135
140
|
// Regenerated when src/content/blog/*.md files change
|
|
136
141
|
|
|
137
142
|
const blogContent: Record<string, string> = {
|
|
138
|
-
${t.map(
|
|
143
|
+
${t.map(s=>{let o=kt.readFileSync(ua.join(e,s),"utf8");return` './${s}': ${JSON.stringify(o)},`}).join(`
|
|
139
144
|
`)}
|
|
140
145
|
};
|
|
141
146
|
|
|
142
147
|
export default blogContent;
|
|
143
|
-
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function Yr(s={}){return new Et(s)}function ko(s){if(!s)return[];let e=x.getInstance(),t=new Set;try{let r=e.resolvePackage("@donotdev/core",s);if(!r)return[];let n=e.getDirname(e.getDirname(r)),o;try{o=e.readdirSync(n)}catch{return[]}for(let a of o)try{let i=e.resolvePath(`${a}/package.json`,n),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[u,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(u)}catch{}}catch{}return Array.from(t)}function Do(s){if(!s)return[];let e=x.getInstance();try{let t=e.resolvePath("package.json",s),r=e.readSync(t,{format:"json"});if(!r)return[];let n=new Set;if(r.peerDependenciesMeta)for(let[o,a]of Object.entries(r.peerDependenciesMeta))a?.optional&&n.add(o);if(r.optionalDependencies)for(let o of Object.keys(r.optionalDependencies))n.add(o);return Array.from(n)}catch{return[]}}function To(s){let e=Fe.optionalFeatures||[],t=ko(s),r=Do(s);return[...new Set([...e,...t,...r])]}function Oo(s){let e=x.getInstance();try{let t=e.resolvePath("package.json",s),r=e.readSync(t,{format:"json"});return r?new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.devDependencies||{})]):new Set}catch{return new Set}}function Fo(s,e,t){if(t.resolvePackage(s,e||void 0))return!0;let r=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0],n=e;for(let o=0;o<10;o++){let a=t.resolvePath(`node_modules/${r}`,n);if(t.pathExists(a))return!0;let i=t.getDirname(n);if(i===n)break;n=i}return!1}function je(s){let e=To(s),t=[],r=[],n=x.getInstance(),o=Oo(s);for(let a of e)a.startsWith("@donotdev/")?o.has(a)?r.push(a):t.push(a):o.has(a)&&Fo(a,s,n)?r.push(a):t.push(a);return{missing:t,installed:r}}var Ge=class extends X{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[r,n]of Object.entries(e)){for(let o of Object.keys(n))t.includes(o)||delete n[o];Object.keys(n).length===0&&delete e[r]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),r=this.pathResolver.getRepoRoot();if(!t||t===r)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${r})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${r}`);let n=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${n.eager.length}, lazy: ${n.lazy.length}, framework eager: ${n.framework?.eager?.length||0}, framework lazy: ${n.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Ie("i18n"),a=n.eager||[],i=n.lazy||[],l=(this.options.additionalPaths||[]).map(b=>{let E=b.endsWith(".json")?b:`${b}/*_*.json`;return this.pathResolver.resolveAppPath(E)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let u=n.framework?.eager||[],c=n.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${u.join(", ")}, framework lazy: ${c.join(", ")}`),u.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),d=this.pathResolver.normalizePath(r),f=(b,E)=>{let $=this.pathResolver.normalizePath(b),F=this.pathResolver.normalizePath(E);return $.startsWith(F)?$.slice(F.length+1):$},h=a.map(b=>f(b,t)),m=[...i,...l].map(b=>f(b,t)),y=u.map(b=>f(b,r)),C=c.map(b=>f(b,r)),R={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},v=await this.pathResolver._globWithNormalization(h,R),P=await this.pathResolver._globWithNormalization(m,R),A={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r,ignore:o.ignore?.filter(b=>b!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${r}, ignore: ${JSON.stringify(A.ignore)}`);let D=await this.pathResolver._globWithNormalization(y,A),I=await this.pathResolver._globWithNormalization(C,A);this.logger.debug(`Found ${v.length} eager, ${P.length} lazy, ${D.length} framework eager, ${I.length} framework lazy files`),D.length>0?this.logger.debug(`Framework eager files (first 3): ${D.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${u.join(", ")}`),I.length>0?this.logger.debug(`Framework lazy files (first 3): ${I.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let re=[...new Set([...v,...P,...D,...I])],Y=new Set([...v,...D]),w={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:N}=je(t),Q=new Set(N.filter(b=>b.startsWith("@donotdev/")).map(b=>b.replace("@donotdev/","")));Q.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...Q].join(", ")}] (packages not installed)`);let U=new Map,z=[...D,...I];for(let b of z){let E=this._processTranslationFile(b,D.includes(b),t);if(E){if(Q.has(E.namespace))continue;let $=`${E.namespace}_${E.language}`;U.set($,E),w.allNamespaces.add(E.namespace),w.supportedLanguages.add(E.language),D.includes(b)&&w.eagerNamespaces.add(E.namespace)}}let W=new Set;for(let b of re){if(z.includes(b))continue;let E=this._processTranslationFile(b,Y.has(b),t);if(E){let{namespace:$,language:F,importPath:se,content:tt}=E,Te=`${E.namespace}_${E.language}`;if(U.has(Te)){let Oe=U.get(Te);E.content=this._mergeTranslations(Oe.content,tt)}w.allNamespaces.add($),w.supportedLanguages.add(F),W.add(F),Y.has(b)&&w.eagerNamespaces.add($),w.mapping[$]||(w.mapping[$]={}),w.mapping[$][F]=se,E.content&&(w.content[$]||(w.content[$]={}),w.content[$][F]=E.content),w.files.push({path:b,relativePath:this.pathResolver.getRelativePath(b),namespace:$,language:F,eager:Y.has(b),size:E.content?JSON.stringify(E.content).length:0})}}for(let[b,E]of U){let $=b.lastIndexOf("_"),F=b.slice(0,$),se=b.slice($+1);W.size>0&&!W.has(se)||(!w.mapping[F]||!w.mapping[F][se])&&(w.mapping[F]||(w.mapping[F]={}),w.mapping[F][se]=E.importPath,w.content[F]||(w.content[F]={}),w.content[F][se]=E.content,w.files.push({path:E.absolutePath,relativePath:this.pathResolver.getRelativePath(E.absolutePath),namespace:F,language:se,eager:w.eagerNamespaces.has(F),size:E.content?JSON.stringify(E.content).length:0}))}let T=W.size>0?[...W].sort():[this.options.fallbackLanguage],L=this._getLanguageAllowlist(),ee=T;if(L){let b=T.filter($=>L.includes($));ee=b.length>0?b:[this.options.fallbackLanguage],this._restrictByLanguage(w.mapping,ee),this._restrictByLanguage(w.content,ee),w.files=w.files.filter($=>ee.includes($.language));let E=new Set(Object.keys(w.mapping));w.allNamespaces=new Set([...w.allNamespaces].filter($=>E.has($))),w.eagerNamespaces=new Set([...w.eagerNamespaces].filter($=>E.has($))),this.logger.debug(`I18n restricted by i18n.only [${L.join(", ")}]: languages [${ee.join(", ")}], namespaces ${E.size}`)}let ce=[...new Set(ee.map(vt))];return{mapping:w.mapping,content:w.content,eagerNamespaces:[...w.eagerNamespaces].sort(),allNamespaces:[...w.allNamespaces].sort(),supportedLanguages:ee,fallbackLanguage:this.options.fallbackLanguage,flagCodes:ce,files:w.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[vt(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 r=await this._processFiles([]);this.cache={...r,timestamp:Date.now()};let n=Date.now()-t;return this.logger.debug(`Discovery completed in ${n}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(r){throw this.logger.error(`I18n discovery failed: ${r.message}`),r}}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,r){let n=e.split("/").pop()||e.split("\\").pop()||"",o,a,i=n.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${n}`),null;if([,o,a]=i,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${n}`),null;let u="./"+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(p){return this.logger.debug(`Error parsing JSON from ${e}: ${p.message}`),null}return{namespace:o,language:a,importPath:u,absolutePath:e,content:c}}_mergeTranslations(e,t){let r={...e};for(let[n,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?r[n]=this._mergeTranslations(r[n]||{},o):r[n]=o;return r}};var Rt=class extends B{constructor(e={}){super(Ge,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...Ne.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],r=Object.keys(e.mapping||{}).filter(n=>n!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${r} 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:[]}}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||{},r=t.totalNamespaces||0,n=t.totalLanguages||0;return`${r} namespaces, ${n} languages`}async generateSpecificFiles(){}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:r,eagerNamespaces:n,fallbackLanguage:o,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
148
|
+
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function hr(r={}){return new Tt(r)}function pa(r){if(!r)return[];let e=D.getInstance(),t=new Set;try{let n=e.resolvePackage("@donotdev/core",r);if(!n)return[];let s=e.getDirname(e.getDirname(n)),o;try{o=e.readdirSync(s)}catch{return[]}for(let a of o)try{let i=e.resolvePath(`${a}/package.json`,s),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[u,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(u)}catch{}}catch{}return Array.from(t)}function da(r){if(!r)return[];let e=D.getInstance();try{let t=e.resolvePath("package.json",r),n=e.readSync(t,{format:"json"});if(!n)return[];let s=new Set;if(n.peerDependenciesMeta)for(let[o,a]of Object.entries(n.peerDependenciesMeta))a?.optional&&s.add(o);if(n.optionalDependencies)for(let o of Object.keys(n.optionalDependencies))s.add(o);return Array.from(s)}catch{return[]}}function fa(r){let e=Le.optionalFeatures||[],t=pa(r),n=da(r);return[...new Set([...e,...t,...n])]}function ha(r){let e=D.getInstance();try{let t=e.resolvePath("package.json",r),n=e.readSync(t,{format:"json"});return n?new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{})]):new Set}catch{return new Set}}function ga(r,e,t){let n=new Set,s=t.resolvePackage("@donotdev/core",r);if(!s)return n;let o=t.getDirname(t.getDirname(s));for(let a of e){if(!a.startsWith("@donotdev/"))continue;let i=t.resolvePath(`${a.slice(10)}/package.json`,o);if(!t.pathExists(i))continue;let l=t.readSync(i,{format:"json"});for(let u of Object.keys(l?.dependencies||{}))n.add(u)}return n}function ma(r,e,t){if(t.resolvePackage(r,e||void 0))return!0;let n=r.startsWith("@")?r.split("/").slice(0,2).join("/"):r.split("/")[0],s=e;for(let o=0;o<10;o++){let a=t.resolvePath(`node_modules/${n}`,s);if(t.pathExists(a))return!0;let i=t.getDirname(s);if(i===s)break;s=i}return!1}function Je(r){let e=fa(r),t=[],n=[],s=D.getInstance(),o=ha(r),a=ga(r,o,s);for(let i of e)i.startsWith("@donotdev/")?o.has(i)?n.push(i):t.push(i):(o.has(i)||a.has(i))&&ma(i,r,s)?n.push(i):t.push(i);return{missing:t,installed:n}}var Ve=class extends ee{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[n,s]of Object.entries(e)){for(let o of Object.keys(s))t.includes(o)||delete s[o];Object.keys(s).length===0&&delete e[n]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),n=this.pathResolver.getRepoRoot();if(!t||t===n)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${n})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${n}`);let s=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${s.eager.length}, lazy: ${s.lazy.length}, framework eager: ${s.framework?.eager?.length||0}, framework lazy: ${s.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Me("i18n"),a=s.eager||[],i=s.lazy||[],l=(this.options.additionalPaths||[]).map(w=>{let E=w.endsWith(".json")?w:`${w}/*_*.json`;return this.pathResolver.resolveAppPath(E)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let u=s.framework?.eager||[],c=s.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${u.join(", ")}, framework lazy: ${c.join(", ")}`),u.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),d=this.pathResolver.normalizePath(n),f=(w,E)=>{let P=this.pathResolver.normalizePath(w),I=this.pathResolver.normalizePath(E);return P.startsWith(I)?P.slice(I.length+1):P},h=a.map(w=>f(w,t)),y=[...i,...l].map(w=>f(w,t)),S=u.map(w=>f(w,n)),T=c.map(w=>f(w,n)),R={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},v=await this.pathResolver._globWithNormalization(h,R),x=await this.pathResolver._globWithNormalization(y,R),O={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:o.ignore?.filter(w=>w!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${n}, ignore: ${JSON.stringify(O.ignore)}`);let B=await this.pathResolver._globWithNormalization(S,O),M=await this.pathResolver._globWithNormalization(T,O);this.logger.debug(`Found ${v.length} eager, ${x.length} lazy, ${B.length} framework eager, ${M.length} framework lazy files`),B.length>0?this.logger.debug(`Framework eager files (first 3): ${B.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${u.join(", ")}`),M.length>0?this.logger.debug(`Framework lazy files (first 3): ${M.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let te=[...new Set([...v,...x,...B,...M])],W=new Set([...v,...B]),g={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:b}=Je(t),k=new Set(b.filter(w=>w.startsWith("@donotdev/")).map(w=>w.replace("@donotdev/","")));k.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...k].join(", ")}] (packages not installed)`);let N=new Map,_=[...B,...M];for(let w of _){let E=this._processTranslationFile(w,B.includes(w),t);if(E){if(k.has(E.namespace))continue;let P=`${E.namespace}_${E.language}`;N.set(P,E),g.allNamespaces.add(E.namespace),g.supportedLanguages.add(E.language),B.includes(w)&&g.eagerNamespaces.add(E.namespace)}}let F=new Set;for(let w of te){if(_.includes(w))continue;let E=this._processTranslationFile(w,W.has(w),t);if(E){let{namespace:P,language:I,importPath:V,content:ge}=E,de=`${E.namespace}_${E.language}`;if(N.has(de)){let me=N.get(de);E.content=this._mergeTranslations(me.content,ge)}g.allNamespaces.add(P),g.supportedLanguages.add(I),F.add(I),W.has(w)&&g.eagerNamespaces.add(P),g.mapping[P]||(g.mapping[P]={}),g.mapping[P][I]=V,E.content&&(g.content[P]||(g.content[P]={}),g.content[P][I]=E.content),g.files.push({path:w,relativePath:this.pathResolver.getRelativePath(w),namespace:P,language:I,eager:W.has(w),size:E.content?JSON.stringify(E.content).length:0})}}for(let[w,E]of N){let P=w.lastIndexOf("_"),I=w.slice(0,P),V=w.slice(P+1);F.size>0&&!F.has(V)||(!g.mapping[I]||!g.mapping[I][V])&&(g.mapping[I]||(g.mapping[I]={}),g.mapping[I][V]=E.importPath,g.content[I]||(g.content[I]={}),g.content[I][V]=E.content,g.files.push({path:E.absolutePath,relativePath:this.pathResolver.getRelativePath(E.absolutePath),namespace:I,language:V,eager:g.eagerNamespaces.has(I),size:E.content?JSON.stringify(E.content).length:0}))}let A=F.size>0?[...F].sort():[this.options.fallbackLanguage],G=this._getLanguageAllowlist(),j=A;if(G){let w=A.filter(P=>G.includes(P));j=w.length>0?w:[this.options.fallbackLanguage],this._restrictByLanguage(g.mapping,j),this._restrictByLanguage(g.content,j),g.files=g.files.filter(P=>j.includes(P.language));let E=new Set(Object.keys(g.mapping));g.allNamespaces=new Set([...g.allNamespaces].filter(P=>E.has(P))),g.eagerNamespaces=new Set([...g.eagerNamespaces].filter(P=>E.has(P))),this.logger.debug(`I18n restricted by i18n.only [${G.join(", ")}]: languages [${j.join(", ")}], namespaces ${E.size}`)}let re=[...new Set(j.map(Nt))];return{mapping:g.mapping,content:g.content,eagerNamespaces:[...g.eagerNamespaces].sort(),allNamespaces:[...g.allNamespaces].sort(),supportedLanguages:j,fallbackLanguage:this.options.fallbackLanguage,flagCodes:re,files:g.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[Nt(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 n=await this._processFiles([]);this.cache={...n,timestamp:Date.now()};let s=Date.now()-t;return this.logger.debug(`Discovery completed in ${s}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){throw this.logger.error(`I18n discovery failed: ${n.message}`),n}}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,n){let s=e.split("/").pop()||e.split("\\").pop()||"",o,a,i=s.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${s}`),null;if([,o,a]=i,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${s}`),null;let u="./"+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(p){return this.logger.debug(`Error parsing JSON from ${e}: ${p.message}`),null}return{namespace:o,language:a,importPath:u,absolutePath:e,content:c}}_mergeTranslations(e,t){let n={...e};for(let[s,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?n[s]=this._mergeTranslations(n[s]||{},o):n[s]=o;return n}};var Ot=class extends H{constructor(e={}){super(Ve,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...De.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],n=Object.keys(e.mapping||{}).filter(s=>s!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${n} 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:[]}}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||{},n=t.totalNamespaces||0,s=t.totalLanguages||0;return`${n} namespaces, ${s} languages`}async generateSpecificFiles(){}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:n,eagerNamespaces:s,fallbackLanguage:o,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
144
149
|
// Generated at: ${new Date().toISOString()}
|
|
145
150
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
146
151
|
|
|
147
152
|
const i18nConfig = {
|
|
148
153
|
mapping: ${JSON.stringify(t,null,2)},
|
|
149
|
-
languages: ${JSON.stringify(
|
|
150
|
-
eager: ${JSON.stringify(
|
|
154
|
+
languages: ${JSON.stringify(n,null,2)},
|
|
155
|
+
eager: ${JSON.stringify(s,null,2)},
|
|
151
156
|
fallback: '${o}',
|
|
152
157
|
content: ${JSON.stringify(a||{},null,2)},
|
|
153
158
|
storage: {
|
|
@@ -164,8 +169,8 @@ const i18nConfig = {
|
|
|
164
169
|
manifest: {
|
|
165
170
|
totalFiles: ${Object.keys(t).length},
|
|
166
171
|
totalNamespaces: ${Object.keys(t).length},
|
|
167
|
-
totalLanguages: ${
|
|
168
|
-
eagerNamespaces: ${
|
|
172
|
+
totalLanguages: ${n.length},
|
|
173
|
+
eagerNamespaces: ${s.length},
|
|
169
174
|
generatedAt: new Date().toISOString(),
|
|
170
175
|
},
|
|
171
176
|
debug: ${this.options.debug},
|
|
@@ -182,12 +187,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
182
187
|
timestamp: Date.now(),
|
|
183
188
|
};
|
|
184
189
|
}
|
|
185
|
-
globalThis._DNDEV_CONFIG_.${
|
|
190
|
+
globalThis._DNDEV_CONFIG_.${Y.i18n} = i18nConfig;
|
|
186
191
|
}
|
|
187
192
|
|
|
188
193
|
// Export for compatibility
|
|
189
194
|
export default i18nConfig;
|
|
190
|
-
`}};function
|
|
195
|
+
`}};function gr(r={}){return new Ot(r)}var Ke=class extends ee{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:n}=e,s=[...t,...n];this.logger.debug(`Processing ${s.length} PWA files`);let o=await this._analyzePWAFiles(s),a=[...o.filter(l=>l.type==="manifest"||l.type==="service-worker"),...o.filter(l=>l.type==="icon")],i=this._generatePWAManifest(a);return{assets:a,manifest:i,totalFiles:s.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 n of e){let s=typeof n=="string"?{absolutePath:n,relativePath:this.pathResolver.getRelativePath(n),fileName:n.split("/").pop()||"",extension:(n.split(".").pop()||"").toLowerCase()}:n,o=await this._analyzePWAAsset(s);o&&t.push(o)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let n=e.relativePath,s=e.fileName;return s==="manifest.json"?this._parseManifestFile(t,n):s.includes("service-worker")||s.includes("sw.")?this._parseServiceWorkerFile(t,n):this._isPWAIcon(s)?this._parseIconFile(e,n):null}_parseManifestFile(e,t){try{let n=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:n,size:typeof e=="string"?e.length:JSON.stringify(n).length}}catch(n){return this.logger.debug(`Failed to parse manifest: ${n.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let n=e.fileName,s=this._extractIconSize(n);return{type:"icon",path:t,size:s,format:e.extension,purpose:this._getIconPurpose(n)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(n=>e.includes(n))}_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(s=>s.type==="icon"),n=this._getDefaultManifest();return t.length>0&&(n.icons=t.map(s=>this.toManifestIcon(s))),n}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},n=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:n==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[n]||`image/${n}`,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 n=this._getWorkboxDefaults(t),s=t.backgroundSync!==!1&&t.backgroundSync,o=t.precacheManifest||[],a=JSON.stringify(o,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
191
196
|
// Generated at ${new Date().toISOString()}
|
|
192
197
|
|
|
193
198
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -197,7 +202,7 @@ const { registerRoute } = workbox.routing;
|
|
|
197
202
|
const { CacheFirst, NetworkFirst, StaleWhileRevalidate } = workbox.strategies;
|
|
198
203
|
const { ExpirationPlugin } = workbox.expiration;
|
|
199
204
|
const { CacheableResponsePlugin } = workbox.cacheableResponse;
|
|
200
|
-
${
|
|
205
|
+
${s?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
|
|
201
206
|
|
|
202
207
|
// Clean up outdated caches
|
|
203
208
|
cleanupOutdatedPrecaches();
|
|
@@ -207,9 +212,9 @@ const precacheManifest = ${a.length>2?a:"self.__WB_MANIFEST || []"};
|
|
|
207
212
|
precacheAndRoute(precacheManifest);
|
|
208
213
|
|
|
209
214
|
// Runtime caching strategies
|
|
210
|
-
${this._generateWorkboxRuntimeCaching(
|
|
215
|
+
${this._generateWorkboxRuntimeCaching(n.runtimeCaching,t)}
|
|
211
216
|
|
|
212
|
-
${
|
|
217
|
+
${s?this._generateBackgroundSync(t.backgroundSync):""}
|
|
213
218
|
|
|
214
219
|
// Skip waiting and claim clients
|
|
215
220
|
self.addEventListener('message', (event) => {
|
|
@@ -221,7 +226,7 @@ self.addEventListener('message', (event) => {
|
|
|
221
226
|
self.addEventListener('activate', (event) => {
|
|
222
227
|
event.waitUntil(self.clients.claim());
|
|
223
228
|
});
|
|
224
|
-
`}_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((
|
|
229
|
+
`}_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((n,s)=>{let{urlPattern:o,handler:a,options:i={}}=n,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",u;typeof o=="function"?u="({ request }) => request.destination === 'document'":o instanceof RegExp?u=o.toString():u=JSON.stringify(o);let c=[];i.expiration&&c.push(`new ExpirationPlugin({
|
|
225
230
|
maxEntries: ${i.expiration.maxEntries||50},
|
|
226
231
|
maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
|
|
227
232
|
})`),i.cacheableResponse&&c.push(`new CacheableResponsePlugin({
|
|
@@ -234,14 +239,14 @@ self.addEventListener('activate', (event) => {
|
|
|
234
239
|
${c.join(`,
|
|
235
240
|
`)}
|
|
236
241
|
],`),i.networkTimeoutSeconds&&(p+=`
|
|
237
|
-
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${
|
|
242
|
+
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${s+1}: ${i.cacheName||"cache-"+s}
|
|
238
243
|
registerRoute(
|
|
239
244
|
${u},
|
|
240
245
|
new ${l}({${p}
|
|
241
246
|
})
|
|
242
247
|
);`}).join(`
|
|
243
248
|
|
|
244
|
-
`)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",
|
|
249
|
+
`)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",n=e.maxRetentionTime||1440,s=e.urlPattern||/\/api\/.*/i,o;return typeof s=="function"||s instanceof RegExp?o=s.toString():o=JSON.stringify(s),`
|
|
245
250
|
// Background sync for offline actions
|
|
246
251
|
const { NetworkOnly } = workbox.strategies;
|
|
247
252
|
registerRoute(
|
|
@@ -249,13 +254,13 @@ registerRoute(
|
|
|
249
254
|
new NetworkOnly({
|
|
250
255
|
plugins: [
|
|
251
256
|
new BackgroundSyncPlugin('${t}', {
|
|
252
|
-
maxRetentionTime: ${
|
|
257
|
+
maxRetentionTime: ${n},
|
|
253
258
|
}),
|
|
254
259
|
],
|
|
255
260
|
}),
|
|
256
261
|
'POST'
|
|
257
262
|
);
|
|
258
|
-
`}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`),
|
|
263
|
+
`}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`),n=this.pathResolver.resolveAppPath(`${e}/static/chunks`),s=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${n}/**/*.{js,css}`,`${s}/**/*.css`];for(let i of a){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let u of l){let c=this.pathResolver.getRelativePath(u);if(c.startsWith(`${e}/static/`)){let p=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:p,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return o}generatePrecacheManifest(e=[],t=null){let n=e;return t&&typeof t=="function"&&(n=t(n)),n}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Ft=class extends H{constructor(e={}){super(Ke,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){return new e(this.pathResolver,this.options)}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}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)}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||{},n=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");n=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let s=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:n});this.writeGeneratedFile(this.options.serviceWorkerPath,s,"service worker")}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function mr(r={}){return new Ft(r)}var yr={requestDocumentParts(r){return[[/<ClientLayout\b/,"renders <ClientLayout>"],[/from\s+['"]next\/headers['"]/,"imports next/headers"],[/export\s+const\s+dynamic\b/,"exports `dynamic`"]].filter(([e])=>e.test(r)).map(([,e])=>e)},async assertAppDocument(){let r=L.next.appDocument,e=`${r} exports \`metadata\` (site-level: metadataBase) and \`AppDocument({ lang, children })\`, which renders <html lang={lang}>, the <head> links the app needs (the framework renders the favicon and font tags), imports the global CSS and puts {children} in <body> (see the @donotdev/cli app-next template)`,t=[];for(let o of this.frameworkRootFiles()){let a=this.pathResolver.resolveAppPath(o);this.pathResolver.pathExists(a)&&!await this.hasGenerationMarker(a)&&t.push(o)}if(t.length>0)throw new Error(`[dndev] ${t.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 ${r}: ${e}. Then delete ${t.join(", ")}.`);let n=this.pathResolver.resolveAppPath(r);if(!this.pathResolver.pathExists(n))throw new Error(`[dndev] ${r} is missing: ${e}.`);let s=this.requestDocumentParts(await this.pathResolver.read(n,{format:"text"}));if(s.length!==0)throw new Error(`[dndev] ${r} ${s.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 r=U("layout","tsx"),e=U("not-found","tsx");return[L.next.appLayout,`src/app/[lang]/${r}`,`src/app/${e}`,`src/app/[lang]/${e}`,`src/app/${U("global-not-found","tsx")}`]},async generateTreeLayout(r){let e=`src/app${this.treeDir(r)}/${U("layout","tsx")}`,t=this.pathResolver.resolveAppPath(e);if(this.pathResolver.pathExists(t)&&!await this.hasGenerationMarker(t)){this.logger.debug(`Skipping ${e} - user-created file detected`);return}this.writeGeneratedFile(e,r==="session"?this.generateSessionLayoutContent():this.generateSiteLayoutContent(),`${r} layout`)},generateSiteLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
259
264
|
// Cached pages: rendered without request data (no cookies, no headers), served from the
|
|
260
265
|
// cache and ${this.revalidateLabel()} (appConfig.revalidate). One entry per URL (page and language).
|
|
261
266
|
|
|
@@ -293,17 +298,29 @@ export default async function SessionLayout({ children }: { children: ReactNode
|
|
|
293
298
|
</ClientLayout>
|
|
294
299
|
);
|
|
295
300
|
}
|
|
296
|
-
`},generateRootLayout(){this.writeGeneratedFile(`src/app${this.rootDir()}/${
|
|
297
|
-
//
|
|
301
|
+
`},generateRootLayout(){this.writeGeneratedFile(L.next.fonts,this.generateFontsContent(),"font plan"),this.writeGeneratedFile(`src/app${this.rootDir()}/${U("layout","tsx")}`,this.generateRootLayoutContent(),"root layout")},generateFontsContent(){if(!this.fonts)throw new Error("[dndev] NextRouteHandler: the font plan is not set (runDiscoveries calls useFonts before generating routes).");let r={css:this.fonts.css,preloads:this.fonts.preloads};return`// Generated by @donotdev/config - DO NOT EDIT
|
|
302
|
+
// The app's font plan (@donotdev/core config fonts/buildFontPlan.js, from the theme font tokens
|
|
303
|
+
// and appConfig.fonts): inline @font-face rules and each language's font preloads, rendered
|
|
304
|
+
// by FontHead in the root layout and the global 404. Files: public/fonts/ (content-hashed).
|
|
305
|
+
|
|
306
|
+
import type { FontHeadData } from '@donotdev/ui/next';
|
|
307
|
+
|
|
308
|
+
export const FONTS: FontHeadData = ${JSON.stringify(r,null,2)};
|
|
309
|
+
`},generateRootLayoutContent(){let r=this.appImport(this.rootDir(),"AppDocument"),e=this.appImport(this.rootDir(),"fonts.generated");return this.isMultilingual()?`// Generated by @donotdev/config - DO NOT EDIT
|
|
310
|
+
// Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the URL's language, with
|
|
311
|
+
// the framework's font tags (FontHead: the language's font preloads + inline @font-face).
|
|
298
312
|
// One URL per language: the default language (${this.options.defaultLanguage}) at the root, served here by
|
|
299
313
|
// the proxy's rewrite; the others under their prefix. Any other first segment is a 404.
|
|
300
314
|
|
|
301
315
|
import { notFound } from 'next/navigation';
|
|
302
316
|
import type { ReactNode } from 'react';
|
|
303
317
|
|
|
304
|
-
import {
|
|
318
|
+
import { FontHead } from '@donotdev/ui/next';
|
|
305
319
|
|
|
306
|
-
|
|
320
|
+
import { AppDocument } from '${r}';
|
|
321
|
+
import { FONTS } from '${e}';
|
|
322
|
+
|
|
323
|
+
export { metadata } from '${r}';
|
|
307
324
|
|
|
308
325
|
const LANGUAGES: readonly string[] = ${JSON.stringify(this.options.languages)};
|
|
309
326
|
|
|
@@ -320,21 +337,37 @@ export default async function RootLayout({
|
|
|
320
337
|
}) {
|
|
321
338
|
const { lang } = await params;
|
|
322
339
|
if (!LANGUAGES.includes(lang)) notFound();
|
|
323
|
-
return
|
|
340
|
+
return (
|
|
341
|
+
<AppDocument lang={lang}>
|
|
342
|
+
<FontHead fonts={FONTS} lang={lang} />
|
|
343
|
+
{children}
|
|
344
|
+
</AppDocument>
|
|
345
|
+
);
|
|
324
346
|
}
|
|
325
347
|
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
326
|
-
// Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the app's language
|
|
348
|
+
// Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the app's language, with
|
|
349
|
+
// the framework's font tags (FontHead: font preloads + inline @font-face, hoisted to <head>).
|
|
327
350
|
|
|
328
351
|
import type { ReactNode } from 'react';
|
|
329
352
|
|
|
330
|
-
import {
|
|
353
|
+
import { FontHead } from '@donotdev/ui/next';
|
|
331
354
|
|
|
332
|
-
|
|
355
|
+
import { AppDocument } from '${r}';
|
|
356
|
+
import { FONTS } from '${e}';
|
|
357
|
+
|
|
358
|
+
export { metadata } from '${r}';
|
|
359
|
+
|
|
360
|
+
const lang = ${JSON.stringify(this.options.defaultLanguage)};
|
|
333
361
|
|
|
334
362
|
export default function RootLayout({ children }: { children: ReactNode }) {
|
|
335
|
-
return
|
|
363
|
+
return (
|
|
364
|
+
<AppDocument lang={lang}>
|
|
365
|
+
<FontHead fonts={FONTS} lang={lang} />
|
|
366
|
+
{children}
|
|
367
|
+
</AppDocument>
|
|
368
|
+
);
|
|
336
369
|
}
|
|
337
|
-
`},generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${
|
|
370
|
+
`},generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${U("not-found","tsx")}`,this.generateNotFoundContent(),"404 page"),this.writeGeneratedFile(`src/app/${U("global-not-found","tsx")}`,this.generateGlobalNotFoundContent(),"global 404 page")},generateNotFoundContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
338
371
|
// 404 page: the app's providers without request data (static, like every cached page).
|
|
339
372
|
// Shared fallback content must not expose the pathname captured during prerendering:
|
|
340
373
|
// NotFoundDocument drops URL-derived output (canonical, JSON-LD, breadcrumbs).
|
|
@@ -357,8 +390,9 @@ export default function NotFound() {
|
|
|
357
390
|
</NotFoundDocument>
|
|
358
391
|
);
|
|
359
392
|
}
|
|
360
|
-
`},generateGlobalNotFoundContent(){let
|
|
393
|
+
`},generateGlobalNotFoundContent(){let r=`
|
|
361
394
|
<AppDocument lang={lang}>
|
|
395
|
+
<FontHead fonts={FONTS} lang={lang} />
|
|
362
396
|
<NotFoundDocument>
|
|
363
397
|
<ClientLayout serverCookies="" acceptLanguage={null}>
|
|
364
398
|
<Suspense fallback={null}>
|
|
@@ -368,26 +402,28 @@ export default function NotFound() {
|
|
|
368
402
|
</NotFoundDocument>
|
|
369
403
|
</AppDocument>`;return this.isMultilingual()?`// Generated by @donotdev/config - DO NOT EDIT
|
|
370
404
|
// 404 of an unknown URL (no root layout above [lang]): the app's AppDocument in the URL's
|
|
371
|
-
// language, which the proxy sets on the request (${
|
|
405
|
+
// language, which the proxy sets on the request (${Z.languageHeader}); a request the proxy
|
|
372
406
|
// does not see (API route, file) gets the default language (${this.options.defaultLanguage}).
|
|
373
407
|
|
|
374
408
|
import { headers } from 'next/headers';
|
|
375
409
|
import { Suspense } from 'react';
|
|
376
410
|
|
|
377
411
|
import { NotFoundDocument, NotFoundPage } from '@donotdev/ui';
|
|
412
|
+
import { FontHead } from '@donotdev/ui/next';
|
|
378
413
|
|
|
379
414
|
import { AppDocument } from './AppDocument';
|
|
380
415
|
import { ClientLayout } from './ClientLayout';
|
|
416
|
+
import { FONTS } from './fonts.generated';
|
|
381
417
|
|
|
382
418
|
export { metadata } from './AppDocument';
|
|
383
419
|
|
|
384
420
|
const LANGUAGES: readonly string[] = ${JSON.stringify(this.options.languages)};
|
|
385
421
|
|
|
386
422
|
export default async function GlobalNotFound() {
|
|
387
|
-
const requested = (await headers()).get(${JSON.stringify(
|
|
423
|
+
const requested = (await headers()).get(${JSON.stringify(Z.languageHeader)});
|
|
388
424
|
const lang =
|
|
389
425
|
requested && LANGUAGES.includes(requested) ? requested : ${JSON.stringify(this.options.defaultLanguage)};
|
|
390
|
-
return (${
|
|
426
|
+
return (${r}
|
|
391
427
|
);
|
|
392
428
|
}
|
|
393
429
|
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
@@ -396,25 +432,27 @@ export default async function GlobalNotFound() {
|
|
|
396
432
|
import { Suspense } from 'react';
|
|
397
433
|
|
|
398
434
|
import { NotFoundDocument, NotFoundPage } from '@donotdev/ui';
|
|
435
|
+
import { FontHead } from '@donotdev/ui/next';
|
|
399
436
|
|
|
400
437
|
import { AppDocument } from './AppDocument';
|
|
401
438
|
import { ClientLayout } from './ClientLayout';
|
|
439
|
+
import { FONTS } from './fonts.generated';
|
|
402
440
|
|
|
403
441
|
export { metadata } from './AppDocument';
|
|
404
442
|
|
|
405
443
|
const lang = ${JSON.stringify(this.options.defaultLanguage)};
|
|
406
444
|
|
|
407
445
|
export default function GlobalNotFound() {
|
|
408
|
-
return (${
|
|
446
|
+
return (${r}
|
|
409
447
|
);
|
|
410
448
|
}
|
|
411
|
-
`}};var
|
|
449
|
+
`}};var vr={isBlogPostRoute(r){return r.metaExport?.namespace==="blog"&&this.hasDynamicSegment(r.path)},extractDynamicParam(r){let e=r.match(/:([a-zA-Z0-9_]+)/);if(e)return e[1];let t=r.match(/\[([^\]]+)\]/);return t?t[1]:"slug"},generateBlogPostClientContent(r,e){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
412
450
|
// This file will be regenerated when src/pages changes
|
|
413
451
|
'use client';
|
|
414
452
|
|
|
415
453
|
import { useEffect, useState } from 'react';
|
|
416
454
|
|
|
417
|
-
import ${
|
|
455
|
+
import ${r} from '${e}';
|
|
418
456
|
|
|
419
457
|
export default function BlogPostClient() {
|
|
420
458
|
const [mounted, setMounted] = useState(false);
|
|
@@ -428,20 +466,20 @@ export default function BlogPostClient() {
|
|
|
428
466
|
}, []);
|
|
429
467
|
|
|
430
468
|
if (!mounted) return null;
|
|
431
|
-
return <${
|
|
469
|
+
return <${r} />;
|
|
432
470
|
}
|
|
433
|
-
`},calculateBlogContentImportPath(
|
|
471
|
+
`},calculateBlogContentImportPath(r){let t=this.appDirFor(r).split("/").filter(Boolean);return`${"../".repeat(t.length+1)}content/blog/blog-content.generated`},generateBlogPostRSCContent(r,e,t){let n=this.extractDynamicParam(r.path);return`// Generated by @donotdev/config - DO NOT EDIT
|
|
434
472
|
// This file will be regenerated when src/pages changes
|
|
435
|
-
// To customize: edit ${
|
|
473
|
+
// To customize: edit ${r.filePath} or create manual app/** files
|
|
436
474
|
|
|
437
475
|
import type { Metadata } from 'next';
|
|
438
476
|
|
|
439
477
|
import { parseBlogFrontmatter } from '@donotdev/core/server';
|
|
440
478
|
|
|
441
479
|
import BlogPostClient from './BlogPostClient';
|
|
442
|
-
import blogContent from '${this.calculateBlogContentImportPath(
|
|
480
|
+
import blogContent from '${this.calculateBlogContentImportPath(r.path)}';
|
|
443
481
|
|
|
444
|
-
type Params = Promise<{ ${
|
|
482
|
+
type Params = Promise<{ ${n}: string }>;
|
|
445
483
|
|
|
446
484
|
interface BlogMeta {
|
|
447
485
|
title: string;
|
|
@@ -492,7 +530,7 @@ function getEnglishPosts(): BlogPost[] {
|
|
|
492
530
|
const englishPosts = getEnglishPosts();
|
|
493
531
|
|
|
494
532
|
export async function generateStaticParams() {
|
|
495
|
-
return englishPosts.map((post) => ({ ${
|
|
533
|
+
return englishPosts.map((post) => ({ ${n}: post.slug }));
|
|
496
534
|
}
|
|
497
535
|
|
|
498
536
|
export async function generateMetadata({
|
|
@@ -500,8 +538,8 @@ export async function generateMetadata({
|
|
|
500
538
|
}: {
|
|
501
539
|
params: Params;
|
|
502
540
|
}): Promise<Metadata> {
|
|
503
|
-
const { ${
|
|
504
|
-
const post = englishPosts.find((item) => item.slug === ${
|
|
541
|
+
const { ${n} } = await params;
|
|
542
|
+
const post = englishPosts.find((item) => item.slug === ${n}) ?? null;
|
|
505
543
|
if (!post) return { title: 'Post not found' };
|
|
506
544
|
const appUrl = process.env.NEXT_PUBLIC_APP_URL;
|
|
507
545
|
return {
|
|
@@ -533,8 +571,8 @@ function escapeHtml(value: string): string {
|
|
|
533
571
|
}
|
|
534
572
|
|
|
535
573
|
export default async function BlogPostRoute({ params }: { params: Params }) {
|
|
536
|
-
const { ${
|
|
537
|
-
const post = englishPosts.find((item) => item.slug === ${
|
|
574
|
+
const { ${n} } = await params;
|
|
575
|
+
const post = englishPosts.find((item) => item.slug === ${n}) ?? null;
|
|
538
576
|
|
|
539
577
|
return (
|
|
540
578
|
<>
|
|
@@ -559,13 +597,13 @@ export default async function BlogPostRoute({ params }: { params: Params }) {
|
|
|
559
597
|
</>
|
|
560
598
|
);
|
|
561
599
|
}
|
|
562
|
-
`}};function
|
|
563
|
-
`),p=t.map(
|
|
564
|
-
`),d=[...new Set(e.map(
|
|
565
|
-
`),f=` ${JSON.stringify("/((?!api|_next|.*\\..*).*)")},`,h=[...o?["hasRoleAccess"]:[],...
|
|
566
|
-
session: SupabaseProxySession['session']`:"",
|
|
567
|
-
language: string`:"",
|
|
568
|
-
// Request gate (Next 16 proxy)${
|
|
600
|
+
`}};function It(r,e,t,n){try{if(t?.content?.[r]?.[e])return t.content[r][e];let s=t?.mapping?.[r]?.[e];if(!s)return null;let o=n.resolveAppPath(s),a=n.readSync(o,{format:"text"});return a?JSON.parse(a):null}catch{return null}}function br(r){return r?.languages||r?.supportedLanguages||["en"]}function wr(r){return r?.fallback||r?.fallbackLanguage||"en"}function ya(r,e,t,n={}){let{minLength:s=0,excludeEmpty:o=!0,customFilter:a}=n;return Array.from({length:t},(i,l)=>{let u=`${e}.${l}`;return r(u)}).filter((i,l)=>{let u=`${e}.${l}`;return!(i===u||o&&i.trim()===""||i.length<s||a&&!a(i,l))})}var va=20,Sr={defaultValue:""};function Er(r,e,t){if(r!==null)return r!==void 0?r:t(e,Sr)||void 0}function Rr(r,e){let t=o=>r(o,Sr),n=o=>t(`${e}:meta.${o}`)||void 0,s=ya(t,`${e}:meta.keywords`,va);return{fullTitle:n("fullTitle"),image:n("image"),type:n("type"),keywords:s.length>0?s:void 0,author:n("author")}}function ba(r,e){return r===!0?"noindex, nofollow":r===!1?null:e?"noindex":null}function Lt(r){let{meta:e,ns:t,defaultNs:n,t:s,siteName:o}=r,a=e.seo;if(!t&&!n)return{title:a?.fullTitle||o};let i=t?Er(a?.title,`${t}:title`,s):a?.title??void 0;return{title:a?.fullTitle||(t?Rr(s,t).fullTitle:void 0)||(i?`${i} | ${o}`:o),...i&&{pageTitle:i}}}function $r(r){let{meta:e,ns:t,defaultNs:n,t:s,siteName:o,baseUrl:a,url:i,defaultImage:l}=r,u=e.seo,c=t??n,p=c?Rr(s,c):null,{title:d}=Lt({meta:e,ns:t,defaultNs:n,t:s,siteName:o}),f=c?Er(u?.description,`${c}:description`,s):void 0,h=u?.image||p?.image||l||void 0,m=u?.keywords||p?.keywords,y=e.author||p?.author;return{title:d,...f&&{description:f},...h&&{image:h.startsWith("http")?h:`${a}${h}`},url:i,type:u?.type||p?.type||"website",robots:ba(u?.noindex??e.noindex,r.authOnly),...m&&{keywords:m},...y&&{author:y},...e.publishDate&&{publishDate:e.publishDate},...e.modifiedDate&&{modifiedDate:e.modifiedDate}}}function Xe(r){return(e,t)=>{let n=e.indexOf(":"),s=r[e.slice(0,n)];for(let o of e.slice(n+1).split("."))s=s&&typeof s=="object"&&o in s?s[o]:void 0;return typeof s=="string"?s:t?.defaultValue??e}}var xr={async generateMetadataManifest(r){let e=this.i18n;if(!e)throw new Error("Route handler: translations not set before the metadata manifest (runDiscoveries calls useI18n)");let t=br(e),n=wr(e),s=this.options.siteName||"",o={};for(let i of r.routes){let l=i.metaExport?.namespace||null,u=this.defaultNamespace(),c=l||u,p={};for(let d of t){let f=It(c,d,e,this.pathResolver)||It(c,n,e,this.pathResolver),h=$r({meta:i.metaExport||{},ns:l,defaultNs:u,t:Xe({[c]:f}),siteName:s,baseUrl:"",url:null,defaultImage:this.defaultImage(),authOnly:!!i.auth});p[d]={title:h.title,...h.description&&{description:h.description},image:h.image,type:h.type,...h.keywords&&{keywords:h.keywords},...h.robots&&{robots:h.robots}}}o[i.path]={locales:p,defaultLocale:n}}let a=JSON.stringify(o,null,2);this.writeGeneratedFile("public/metadata-manifest.json",a,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(o).length} routes`)}};var Pr={async generateMiddleware(r){this.removeLegacyMiddleware(),this.rendersSessionTree=!1;let e=r.routes.filter(l=>!!this.normalizeAuth(l.auth)),t=r.routes.filter(l=>l.meta?.signedInRedirect),n=this.usesCookieSession();(e.length>0||t.length>0)&&!n&&this.logger.debug("Auth session not in cookies (no Supabase createBrowserClient): pages use the client AuthGuard / SignedInRedirect only, no proxy auth redirects");let s=n?e:[],o=n?t:[],a=this.pathResolver.resolveAppPath(this.options.proxyPath),i=this.pathResolver.pathExists(a)&&!await this.hasGenerationMarker(a);if(!this.isMultilingual()&&!n){this.logger.debug("One language and no cookie session: no proxy.next.ts"),this.pathResolver.pathExists(a)&&!i&&await this.pathResolver.remove(a);return}if(i){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(s,r.routes,o,n),"proxy"),this.rendersSessionTree=n},async findAppRouteSegments(){let r=this.pathResolver.getAppRoot(),e=this.pathResolver.resolveAppPath(L.next.appPages),t=await this.pathResolver._globWithNormalization([`${L.next.appPages}/**/{route,page}.${he}.{ts,tsx,js,jsx}`],{cwd:r,absolute:!0,onlyFiles:!0,braceExpansion:!0}),n=new Set;for(let s of t){if(await this.hasGenerationMarker(s))continue;let[o]=s.slice(e.length+1).split("/").slice(0,-1).filter(a=>!/^\(.*\)$/.test(a));o&&o!=="[lang]"&&n.add(o)}return[...n].sort()},routePattern(r){return"^"+r.split("/").map(e=>e==="*"?".*":e.startsWith(":")?"[^/]+":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("/")+"$"},generateMiddlewareContent(r,e=[],t=[],n=!1){let s=this.isMultilingual(),o=r.length>0,a=t.length>0,i=o||a,l=n||i,u=this.options.auth??{},c=r.map(A=>{let{role:G}=this.normalizeAuth(A.auth);return` { pattern: new RegExp(${JSON.stringify(this.routePattern(A.path))})${G?`, role: ${JSON.stringify(G)}`:""} },`}).join(`
|
|
601
|
+
`),p=t.map(A=>` { pattern: new RegExp(${JSON.stringify(this.routePattern(A.path))}), to: ${JSON.stringify(A.meta.signedInRedirect)} },`).join(`
|
|
602
|
+
`),d=[...new Set(e.map(A=>A.path))].map(A=>` new RegExp(${JSON.stringify(this.routePattern(A))}),`).join(`
|
|
603
|
+
`),f=` ${JSON.stringify("/((?!api|_next|.*\\..*).*)")},`,h=[...o?["hasRoleAccess"]:[],...s?["LANGUAGE_COOKIE",...i?["localizePath"]:[],"parseAcceptLanguage","readCookieValue","resolveLanguageRoute","splitLanguagePath"]:[]],m=["hasSupabaseSessionCookie","refreshSupabaseSession",...i?["type SupabaseProxySession"]:[]],y=i?`,
|
|
604
|
+
session: SupabaseProxySession['session']`:"",S=s?`,
|
|
605
|
+
language: string`:"",T=l?"{ request }":"",R=`/${Z.sessionSegment}`,v=`// Generated by @donotdev/config - DO NOT EDIT
|
|
606
|
+
// Request gate (Next 16 proxy)${s?`: one URL per language, the default language (${this.options.defaultLanguage}) at the
|
|
569
607
|
// root, the others under their prefix (resolveLanguageRoute in @donotdev/core)`:""}.${l?`
|
|
570
608
|
// Session: the Supabase cookie (createBrowserClient). No auth cookie: signed out, the
|
|
571
609
|
// page comes from the cache (src/app${this.treeDir("site")}, static). With one: verified and refreshed
|
|
@@ -582,8 +620,8 @@ import { NextResponse } from 'next/server';
|
|
|
582
620
|
import type { NextRequest } from 'next/server';
|
|
583
621
|
|
|
584
622
|
${h.length?`import { ${h.join(", ")} } from '@donotdev/core/server';
|
|
585
|
-
`:""}${l?`import { ${
|
|
586
|
-
`:""}`,
|
|
623
|
+
`:""}${l?`import { ${m.join(", ")} } from '@donotdev/supabase/server';
|
|
624
|
+
`:""}`,x=l?`
|
|
587
625
|
/** Supabase project of the cookie session (same env as src/config/providers.ts) */
|
|
588
626
|
const SUPABASE = supabaseProject(
|
|
589
627
|
process.env.NEXT_PUBLIC_SUPABASE_URL,
|
|
@@ -598,9 +636,9 @@ function supabaseProject(url: string | undefined, publicKey: string | undefined)
|
|
|
598
636
|
}
|
|
599
637
|
return { url, publicKey };
|
|
600
638
|
}
|
|
601
|
-
${
|
|
639
|
+
${s?`
|
|
602
640
|
/** Internal tree of the per-request pages (src/app/[lang]${R}), after the language: never a public URL */
|
|
603
|
-
const SESSION_SEGMENT = ${JSON.stringify(
|
|
641
|
+
const SESSION_SEGMENT = ${JSON.stringify(Z.sessionSegment)};
|
|
604
642
|
|
|
605
643
|
/** Internal URL path of a page rendered per request: \`/fr/compte\` \u2192 \`/fr${R}/compte\` */
|
|
606
644
|
function sessionPath(path: string): string {
|
|
@@ -628,7 +666,7 @@ function isSessionTreePath(pathname: string): boolean {
|
|
|
628
666
|
`}${i?`
|
|
629
667
|
/** Session of a request without an auth cookie: signed out, nothing to verify */
|
|
630
668
|
const SIGNED_OUT: SupabaseProxySession['session'] = { user: null };
|
|
631
|
-
`:""}`:"",
|
|
669
|
+
`:""}`:"",O=o?`
|
|
632
670
|
/** appConfig.auth.authRoute: where a signed-out visitor goes (null: page fallback) */
|
|
633
671
|
const AUTH_ROUTE: string | null = ${JSON.stringify(u.authRoute??null)};
|
|
634
672
|
/** appConfig.auth.roleRoute: where a visitor without the role goes (null: page fallback) */
|
|
@@ -645,8 +683,8 @@ function isProtectedRoute(routePath: string): boolean {
|
|
|
645
683
|
|
|
646
684
|
/** Redirect of a protected route, or null to let the page render. */
|
|
647
685
|
function authRedirect(
|
|
648
|
-
request: NextRequest${
|
|
649
|
-
routePath: string${
|
|
686
|
+
request: NextRequest${y},
|
|
687
|
+
routePath: string${S}
|
|
650
688
|
): NextResponse | null {
|
|
651
689
|
const route = protectedRoutes.find((r) => r.pattern.test(routePath));
|
|
652
690
|
if (!route) return null;
|
|
@@ -655,17 +693,17 @@ function authRedirect(
|
|
|
655
693
|
|
|
656
694
|
if (!session.user) {
|
|
657
695
|
if (!AUTH_ROUTE) return null;
|
|
658
|
-
const url = new URL(${
|
|
696
|
+
const url = new URL(${s?"localizePath(AUTH_ROUTE, language, LANGUAGE_ROUTING)":"AUTH_ROUTE"}, request.url);
|
|
659
697
|
url.searchParams.set('returnTo', request.nextUrl.pathname + request.nextUrl.search);
|
|
660
698
|
return NextResponse.redirect(url);
|
|
661
699
|
}
|
|
662
700
|
if (route.role && !hasRoleAccess(session.user.role, route.role)) {
|
|
663
701
|
if (!ROLE_ROUTE) return null;
|
|
664
|
-
return NextResponse.redirect(new URL(${
|
|
702
|
+
return NextResponse.redirect(new URL(${s?"localizePath(ROLE_ROUTE, language, LANGUAGE_ROUTING)":"ROLE_ROUTE"}, request.url));
|
|
665
703
|
}
|
|
666
704
|
return null;
|
|
667
705
|
}
|
|
668
|
-
`:"",
|
|
706
|
+
`:"",B=a?`
|
|
669
707
|
/** PageMeta \`signedInRedirect\`: where a signed-in visitor of the page goes */
|
|
670
708
|
const signedInRoutes: Array<{ pattern: RegExp; to: string }> = [
|
|
671
709
|
${p}
|
|
@@ -673,8 +711,8 @@ ${p}
|
|
|
673
711
|
|
|
674
712
|
/** Redirect of a signed-in visitor, or null to let the page render. */
|
|
675
713
|
function signedInRedirect(
|
|
676
|
-
request: NextRequest${
|
|
677
|
-
routePath: string${
|
|
714
|
+
request: NextRequest${y},
|
|
715
|
+
routePath: string${S}
|
|
678
716
|
): NextResponse | null {
|
|
679
717
|
const route = signedInRoutes.find((r) => r.pattern.test(routePath));
|
|
680
718
|
if (!route) return null;
|
|
@@ -682,42 +720,42 @@ function signedInRedirect(
|
|
|
682
720
|
if (request.nextUrl.searchParams.has('returnTo')) return null;
|
|
683
721
|
// Signed out, or cannot tell: the page renders (its SignedInRedirect decides on the client)
|
|
684
722
|
if (!session?.user) return null;
|
|
685
|
-
return NextResponse.redirect(new URL(${
|
|
723
|
+
return NextResponse.redirect(new URL(${s?"localizePath(route.to, language, LANGUAGE_ROUTING)":"route.to"}, request.url));
|
|
686
724
|
}
|
|
687
|
-
`:"",
|
|
725
|
+
`:"",M=s?`
|
|
688
726
|
const LANGUAGE_ROUTING = {
|
|
689
727
|
languages: ${JSON.stringify(this.options.languages)},
|
|
690
728
|
defaultLanguage: ${JSON.stringify(this.options.defaultLanguage)},
|
|
691
729
|
};
|
|
692
730
|
|
|
693
731
|
/** Request header of the URL's language, read by the 404 page (src/app/global-not-found) */
|
|
694
|
-
const LANGUAGE_HEADER = ${JSON.stringify(
|
|
732
|
+
const LANGUAGE_HEADER = ${JSON.stringify(Z.languageHeader)};
|
|
695
733
|
|
|
696
734
|
/** First URL segments of the app's hand-written routes outside src/app/[lang] (route handlers) */
|
|
697
735
|
const APP_ROUTE_SEGMENTS: readonly string[] = ${JSON.stringify(this.appRouteSegments)};
|
|
698
|
-
`:"",
|
|
736
|
+
`:"",te=s||l?`
|
|
699
737
|
/** App pages (src/pages): API routes, files and hand-written app routes pass untouched */
|
|
700
738
|
const pageRoutes: RegExp[] = [
|
|
701
739
|
${d}
|
|
702
740
|
];
|
|
703
|
-
`:"",
|
|
704
|
-
request: NextRequest${
|
|
741
|
+
`:"",W=i?"session, ":"",g=" // 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);",b=`
|
|
742
|
+
request: NextRequest${y}${l?`,
|
|
705
743
|
personal: boolean`:""}
|
|
706
|
-
`,
|
|
707
|
-
const redirect = authRedirect(request, ${
|
|
744
|
+
`,k=(A,G)=>`${o?`
|
|
745
|
+
const redirect = authRedirect(request, ${W}${A}${G});
|
|
708
746
|
if (redirect) return redirect;
|
|
709
747
|
`:""}${a?`
|
|
710
|
-
const signedIn = signedInRedirect(request, ${
|
|
748
|
+
const signedIn = signedInRedirect(request, ${W}${A}${G});
|
|
711
749
|
if (signedIn) return signedIn;
|
|
712
|
-
`:""}`,
|
|
750
|
+
`:""}`,N=(A,G)=>l?`
|
|
713
751
|
// Auth cookie: rendered per request with the visitor's cookies${o?`. Protected pages
|
|
714
752
|
// have no cached copy: per request for every visitor`:""}
|
|
715
|
-
if (personal${o?` || isProtectedRoute(${
|
|
716
|
-
const page = ${
|
|
717
|
-
return NextResponse.rewrite(new URL(sessionPath(${
|
|
718
|
-
}`:"",
|
|
753
|
+
if (personal${o?` || isProtectedRoute(${G})`:""}) {${A==="pathname"?"":`
|
|
754
|
+
const page = ${A};`}
|
|
755
|
+
return NextResponse.rewrite(new URL(sessionPath(${A==="pathname"?"pathname":"page"}) + search, request.url), { request });
|
|
756
|
+
}`:"",_;s?_=`
|
|
719
757
|
/** Language routing, redirects and render tree of a page request. */
|
|
720
|
-
function route(${
|
|
758
|
+
function route(${b}): NextResponse {
|
|
721
759
|
const { pathname, search } = request.nextUrl;
|
|
722
760
|
const decision = resolveLanguageRoute(
|
|
723
761
|
pathname,
|
|
@@ -750,23 +788,23 @@ function route(${N}): NextResponse {
|
|
|
750
788
|
decision.permanent ? 308 : 307
|
|
751
789
|
);
|
|
752
790
|
}
|
|
753
|
-
${
|
|
791
|
+
${k("decision.path",", decision.language")}${N("decision.type === 'rewrite' ? decision.destination : pathname","decision.path")}
|
|
754
792
|
if (decision.type === 'rewrite') {
|
|
755
793
|
return NextResponse.rewrite(new URL(decision.destination + search, request.url)${l?", { request }":""});
|
|
756
794
|
}
|
|
757
|
-
return NextResponse.next(${
|
|
795
|
+
return NextResponse.next(${T});
|
|
758
796
|
}
|
|
759
|
-
`:
|
|
797
|
+
`:_=`
|
|
760
798
|
/** Redirects and render tree of a page request. */
|
|
761
|
-
function route(${
|
|
799
|
+
function route(${b}): NextResponse {
|
|
762
800
|
const { ${l?"pathname, search":"pathname"} } = request.nextUrl;
|
|
763
801
|
if (!pageRoutes.some((pattern) => pattern.test(pathname))) {
|
|
764
802
|
return NextResponse.next({ request });
|
|
765
803
|
}
|
|
766
|
-
${
|
|
804
|
+
${k("pathname","")}${N("pathname","pathname")}
|
|
767
805
|
return NextResponse.next({ request });
|
|
768
806
|
}
|
|
769
|
-
`;let
|
|
807
|
+
`;let F;return l?F=`
|
|
770
808
|
export async function proxy(request: NextRequest) {
|
|
771
809
|
if (isSessionTreePath(request.nextUrl.pathname)) {
|
|
772
810
|
return new NextResponse(null, { status: 404 });
|
|
@@ -777,25 +815,25 @@ export async function proxy(request: NextRequest) {
|
|
|
777
815
|
return route(request${i?", SIGNED_OUT":""}, false);
|
|
778
816
|
}
|
|
779
817
|
|
|
780
|
-
${
|
|
818
|
+
${g}
|
|
781
819
|
// Signed in, or cannot tell (Supabase unreachable): per-request render. Signed out
|
|
782
820
|
// (refresh failed, session revoked): the cached page, with the cleared cookies.
|
|
783
821
|
return auth.apply(route(request, ${i?"auth.session, ":""}auth.session?.user !== null));
|
|
784
822
|
}
|
|
785
|
-
${
|
|
823
|
+
${_}`:F=`
|
|
786
824
|
export function proxy(request: NextRequest) {
|
|
787
825
|
return route(request);
|
|
788
826
|
}
|
|
789
|
-
${
|
|
827
|
+
${_}`,`${v}${x}${M}${te}${O}${B}${F}
|
|
790
828
|
export const config = {
|
|
791
829
|
matcher: [
|
|
792
830
|
${f}
|
|
793
831
|
],
|
|
794
832
|
};
|
|
795
|
-
`},usesCookieSession(){try{let
|
|
833
|
+
`},usesCookieSession(){try{let r=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"));if(!{...r.dependencies,...r.devDependencies}["@donotdev/supabase"])return!1;let t=this.pathResolver.resolveAppPath("src/config/providers.ts");return this.pathResolver.pathExists(t)?this.pathResolver.readSync(t).includes("createBrowserClient("):!1}catch(r){return this.logger.debug(`Cookie session detection failed: ${r.message}`),!1}},removeLegacyMiddleware(){for(let r of["middleware.ts","src/middleware.ts"]){let e=this.pathResolver.resolveAppPath(r);try{this.pathResolver.pathExists(e)&&this.pathResolver.readSync(e).startsWith("// Auto-generated middleware by @donotdev/config")&&(this.pathResolver.removeSync(e),this.logger.debug(`Removed legacy generated ${r}`))}catch(t){this.logger.debug(`Could not remove legacy ${r}: ${t.message}`)}}}};function q(r){return r.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function Mt(r,e){let t=e&&Object.hasOwn(e,r.collection)?e[r.collection]:void 0;if(!t)throw new Error(`[dndev] Route "${r.path}" reads "${r.collection}" records but no read schema was given for that collection (entityReadSchemas of the app's entities).`);return t}async function Cr(r,e,t,n){let s=q(r.path),o=s[0];if(s.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 a=Mt(r,n),i;try{i=await e.query(r.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3},a)}catch(u){let c=u?.details?.originalMessage??u?.message??String(u);throw new Error(`[dndev] Route "${r.path}" could not read its public "${r.collection}" records (signed-out visitor: RLS / Security Rules must allow it): ${c}`,{cause:u})}let l=[];for(let u of i.items){let c=u[o];typeof c!="string"&&typeof c!="number"||l.push({param:o,value:String(c),record:u})}return l}async function Ye(r,e,t,n){let s=[];for(let o of r){if(q(o.path).length===0){s.push({route:o,path:o.path});continue}for(let{param:a,value:i,record:l}of await Cr(o,e,t,n))s.push({route:o,path:o.path.replace(`:${a}`,encodeURIComponent(i)),record:l})}return s}async function wa(r,e,t,n){return(await Cr(r,e,t,n)).map(({param:s,value:o})=>({[s]:o}))}import{createHash as Sa,timingSafeEqual as Ea}from"node:crypto";var Te="DNDEV_REVALIDATE_SECRET",_r="/api/dndev/revalidate",Ar=32,Nr="public",Ra=["/sitemap.xml","/llms.txt"];function $a(r){return r.replace(/[/#?\\]|%(2f|23|3f|5c)/gi,e=>encodeURIComponent(e))}function xa(r,e){return e.languages.length<2?[r]:e.languages.map(t=>`/${t}${r==="/"?"":r}`)}function kr(r,e,t){let n=new Set,s=new Set;for(let o of r){let a=q(o.path);if(a.length===0){n.add(o.path);continue}let[i]=a;if(!(a.length!==1||!i||o.collection!==e.table)){for(let l of[e.record,e.oldRecord]){let u=l?.[i];typeof u!="string"&&typeof u!="number"||n.add(o.path.replace(`:${i}`,$a(String(u))))}for(let l of Ra)s.add(l)}}for(let o of n)for(let a of xa(o,t))s.add(a);return[...s].sort()}function Pa(r,e){let t=/^Bearer (.+)$/.exec(r??"");if(!t)return!1;let n=s=>Sa("sha256").update(s).digest();return Ea(n(t[1]),n(e))}async function Ca(r,{secret:e,routes:t,routing:n,readChange:s,revalidatePath:o}){if(!e||e.length<Ar)throw new Error(`[dndev] Set ${Te} to a random secret of at least ${Ar} characters: the revalidation webhook (${_r}) authenticates with it.`);if(!Pa(r.headers.get("authorization"),e))return Response.json({error:"Unauthorized"},{status:401});let a;try{a=s(await r.json())}catch(l){if(!(l instanceof Error))throw l;return Response.json({error:l.message},{status:400})}if(a.schema!==Nr)return Response.json({error:`Table "${a.schema}.${a.table}" is not in the "${Nr}" schema: only public content tables are revalidated.`},{status:400});let i=kr(t,a,n);for(let l of i)o(l);return Response.json({revalidated:i})}var Dr={revalidationRoute(r){if(this.isSessionOnlyRoute(r)||r.path.includes("*"))return null;let e=q(r.path);if(e.length===0)return{path:r.path};let t=r.meta?.entity;return e.length===1&&t?{path:r.path,collection:t}:null},generateRevalidationContent(r){let e=r.routes.map(n=>this.revalidationRoute(n)).filter(Boolean),t={languages:this.options.languages,defaultLanguage:this.options.defaultLanguage};return`// Generated by @donotdev/config - DO NOT EDIT
|
|
796
834
|
// Regenerated on every build from src/pages (PageMeta).
|
|
797
835
|
// On-demand revalidation: a Supabase database webhook POSTs each row change here
|
|
798
|
-
// (Authorization: Bearer $${
|
|
836
|
+
// (Authorization: Bearer $${Te}). The cached pages showing the row (its entity
|
|
799
837
|
// pages in every language, the static pages, sitemap.xml, llms.txt) are invalidated and
|
|
800
838
|
// re-rendered on their next visit. Secret unset or under 32 characters: every call fails
|
|
801
839
|
// (500), loudly. Watch public content tables only: each call invalidates every static page.
|
|
@@ -814,14 +852,14 @@ const ROUTES: PublicRoute[] = ${JSON.stringify(e,null,2)};
|
|
|
814
852
|
|
|
815
853
|
export async function POST(request: Request): Promise<Response> {
|
|
816
854
|
return handleRevalidationWebhook(request, {
|
|
817
|
-
secret: process.env.${
|
|
855
|
+
secret: process.env.${Te},
|
|
818
856
|
routes: ROUTES,
|
|
819
857
|
routing: LANGUAGE_ROUTING,
|
|
820
858
|
readChange: readDatabaseWebhook,
|
|
821
859
|
revalidatePath,
|
|
822
860
|
});
|
|
823
861
|
}
|
|
824
|
-
`},generateRevalidationRoute(
|
|
862
|
+
`},generateRevalidationRoute(r){this.options.routingMode==="app"&&this.appDependsOn("@donotdev/supabase")&&this.writeGeneratedFile(L.next.revalidateRoute,this.generateRevalidationContent(r),"revalidation route")}};var Tr={async generateAppRoutes(r){let e=this.generateAppRoutesContent(r.routes);this.writeGeneratedFile("src/app/routes.generated.ts",e,"app routes index")},generateAppRoutesContent(r){let e=r.map(t=>{let n=t.componentName||this.pathToComponentName(t.path),s=t.relativePath||t.file;if(!s)return this.logger.warn(`Route ${t.path} missing file path, skipping`),null;let o=s.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
|
|
825
863
|
path: '${t.path}',
|
|
826
864
|
component: lazy(() => import('${o}')),
|
|
827
865
|
auth: ${JSON.stringify(t.auth)},
|
|
@@ -837,13 +875,13 @@ ${e}
|
|
|
837
875
|
];
|
|
838
876
|
|
|
839
877
|
export const routeManifest = {
|
|
840
|
-
totalRoutes: ${
|
|
878
|
+
totalRoutes: ${r.length},
|
|
841
879
|
routingMode: 'app',
|
|
842
880
|
generatedAt: '${new Date().toISOString()}'
|
|
843
881
|
};
|
|
844
882
|
|
|
845
883
|
export default appRoutes;
|
|
846
|
-
`},async generatePagesRoutes(
|
|
884
|
+
`},async generatePagesRoutes(r){let e=this.generatePagesRoutesContent(r.routes);this.writeGeneratedFile("src/pages/routes.generated.ts",e,"pages routes index")},generatePagesRoutesContent(r){let e=r.map(t=>` '${t.path}': {
|
|
847
885
|
auth: ${JSON.stringify(t.auth)},
|
|
848
886
|
meta: ${JSON.stringify(t.meta)},
|
|
849
887
|
file: '${t.file}'
|
|
@@ -856,34 +894,34 @@ ${e}
|
|
|
856
894
|
};
|
|
857
895
|
|
|
858
896
|
export const routeManifest = {
|
|
859
|
-
totalRoutes: ${
|
|
897
|
+
totalRoutes: ${r.length},
|
|
860
898
|
routingMode: 'pages',
|
|
861
899
|
generatedAt: '${new Date().toISOString()}'
|
|
862
900
|
};
|
|
863
901
|
|
|
864
902
|
export default pageRoutes;
|
|
865
|
-
`},pathToComponentName(
|
|
866
|
-
`)){let n
|
|
867
|
-
`)}discoverBlogPosts(){return this.appRoot?
|
|
868
|
-
<title><![CDATA[${
|
|
869
|
-
<link>${
|
|
870
|
-
<guid>${
|
|
871
|
-
<description><![CDATA[${
|
|
903
|
+
`},pathToComponentName(r){return r.split("/").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")+"Page"}};import{existsSync as _a,readdirSync as ka}from"node:fs";import{join as Da}from"node:path";var Aa=/^---\r?\n([\s\S]*?)\r?\n---/,Na=/^\r?\n/;function Or(r){let e=r.match(Aa);if(!e)return{meta:{},content:r};let t={};for(let n of(e[1]??"").split(`
|
|
904
|
+
`)){let s=n.indexOf(":");if(s===-1)continue;let o=n.slice(0,s).trim();if(!o)continue;let a=n.slice(s+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[o]=a}return{meta:t,content:r.slice(e[0].length).replace(Na,"")}}function Fr(r){return r.filter(e=>e.endsWith("_en.md")).sort()}function Ir(r){let e=Da(r,"src","content","blog");try{return _a(e)?Fr(ka(e)).length>0:!1}catch{return!1}}function Lr(r,e){let t=D.getInstance(),n=t.resolvePath("src/content/blog",r);try{if(!t.pathExists(n))return[];let s=Fr(t.readdirSync(n));if(s.length===0)return[];let o=[];for(let a of s){let i=t.resolvePath(a,n),l=t.readSync(i,{format:"text"}),u=a.replace(/_en\.md$/,""),{meta:c}=Or(l),p=c.date;if(!p)try{p=t.statSync(i).mtime.toISOString().split("T")[0],e.warn(`Blog post "${u}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],e.warn(`Blog post "${u}" has no date and file stat failed, using today`)}o.push({slug:u,title:c.title||u,description:c.description||"",date:p,tags:c.tags?c.tags.split(",").map(d=>d.trim()):[],image:c.image||null})}return o.sort((a,i)=>i.date.localeCompare(a.date)),e.info(`\u{1F4DD} Discovered ${o.length} blog post(s) in src/content/blog/`),o}catch(s){return e.debug(`Blog content discovery skipped: ${s.message}`),[]}}function J(r){return r?r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}function Mr(r){return r?r.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Br=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function Ta(r,e){let t;try{let n=new URL(r);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error;t=n.hostname}catch{throw new Error(`[dndev] SEO: base URL "${r}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(Br.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: deploy build with base URL "${r}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}var Oa="DNDEV_DEPLOY";function Qe(r=process.env){let e=r.CI;return r[Oa]==="1"||r.VERCEL==="1"||e!==void 0&&e!==""&&e!=="false"&&e!=="0"}var Ur=new Set;function Gr(r,e,t,n=process.env){if(Qe(n)){if(!r)throw new Error(`[dndev] SEO: deploy build without ${e}. The sitemap, robots.txt, llms.txt and canonical URLs need the production URL: set ${e} (or seo.baseUrl) in the build environment.`);return Ta(r,e),r}let s=o=>{Ur.has(o)||(Ur.add(o),t.warn(o))};return!r||!Fa(r)?(s(`[dndev] Local build without a usable ${e}${r?` ("${r}")`:""}: no sitemap.xml, llms.txt, robots.txt, rss.xml, canonical URLs or record pages. Set ${e} to build them.`),null):(Ia(r)||s(`[dndev] Local build: sitemap.xml, llms.txt, canonical URLs and record pages carry ${r} (${e}). A deploy build (dndev deploy, Vercel, CI) needs the production URL.`),r)}async function $e(r,e,t,n=process.env){try{return await e(),!0}catch(s){if(ce(s))throw s;let o=`${r.join(", ")} not written: ${s.message}`;if(Qe(n))throw C("dndev-seo",`${o}. A deploy build publishes every SEO file.`,"seo-generation-failed",{files:r});return t.warn(`[dndev] Local build: ${o} (a deploy build fails on it).`),!1}}function Fa(r){try{let{protocol:e}=new URL(r);return e==="https:"||e==="http:"}catch{return!1}}function Ia(r){let{hostname:e}=new URL(r);return!Br.has(e)&&!e.endsWith(".localhost")}var Ut=Object.freeze(["/api"]),jr=new Set(["/404","/not-found","/500","/error"]);function et(r){return r.auth&&r.auth!==!1||jr.has(r.path)||jr.has(r.meta?.route)?!1:r.meta?.seo?.noindex!==!0}function Gt(r){return typeof r.path=="string"&&r.path.split("/").includes("*")}function zr(r){if(!(typeof r.path!="string"||!r.path.includes(":"))&&et(r))return r.meta?.entity||void 0}function tt(r){if(typeof r.path!="string"||r.path.includes("*")||q(r.path).length!==1)return null;let e=zr(r);return e?{path:r.path,collection:e}:null}function La(r=[]){return{totalRoutes:r.length,publicRoutes:r.filter(e=>!e.auth||e.auth===!1).length,protectedRoutes:r.filter(e=>e.auth&&e.auth.required).length}}var Ze=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:n=!0,baseUrl:s,siteName:o,crawlDelay:a=1,aiCrawlers:i="recommended",routes:l={},...u}=e;if(!s||!o)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:n,baseUrl:s,siteName:o,crawlDelay:a,aiCrawlers:i,routes:l,blogPath:"/blog",...u},this.appRoot=u.appRoot||null,this.logger=ae("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,n){let s={routes:e.routes||[],baseUrl:this.options.baseUrl,siteName:this.options.siteName},o={robotsTxt:null,rss:null,manifest:null};return this.options.generateRobotsTxt&&(o.robotsTxt=await this.generateRobotsTxt(s,t)),n.length>0&&(o.rss=await this.generateRSSFeed(n,t)),o.manifest=await this.generateManifest(s,t),o}async generateRobotsTxt(e,t){let n=this.options.shellPath?[...Ut,this.options.shellPath]:Ut,s=this.generateRobotsTxtContent({disallowedPaths:n,sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",s),{fileName:"robots.txt",content:s,disallowedPaths:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:n}=this.options,s=[];for(let o of e||[]){if(!et(o)||typeof o.path!="string"||Gt(o))continue;let a=o.path===n||o.path.startsWith(`${n}/`);if(!(t.length>0&&a))if(o.path.includes(":")){if(a)continue;let i=zr(o);s.push({path:o.path,...i&&{collection:i}})}else s.push({path:o.path})}if(t.length>0){s.push({path:n,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let o of t)s.push({path:`${n}/${o.slug}`,priority:.6,changeFrequency:"monthly",...o.date&&{lastModified:o.date}})}return s}async generateManifest(e,t){let n={...La(e.routes),baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()},s=JSON.stringify(n,null,2);return await t("seo-manifest.json",s),{fileName:"seo-manifest.json",content:s,manifest:n}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:n=Ut,sitemap:s,crawlDelay:o}=e,a=u=>u?u==="*"?"*":u.startsWith("/")?u:`/${u}`:"/",i=["User-agent: *",...n.map(u=>`Disallow: ${a(u)}`),...t.map(u=>`Allow: ${a(u)}`)];o&&i.push(`Crawl-delay: ${o}`),s&&i.push(`Sitemap: ${s}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Ma(l))),i.join(`
|
|
905
|
+
`)}discoverBlogPosts(){return this.appRoot?Lr(this.appRoot,this.logger):[]}async generateRSSFeed(e,t){let n=e.map(o=>` <item>
|
|
906
|
+
<title><![CDATA[${Mr(o.title)}]]></title>
|
|
907
|
+
<link>${J(this.options.baseUrl)}${J(this.options.blogPath)}/${J(o.slug)}</link>
|
|
908
|
+
<guid>${J(this.options.baseUrl)}${J(this.options.blogPath)}/${J(o.slug)}</guid>
|
|
909
|
+
<description><![CDATA[${Mr(o.description)}]]></description>
|
|
872
910
|
<pubDate>${o.date?new Date(o.date).toUTCString():""}</pubDate>${o.tags.length?`
|
|
873
|
-
<category>${
|
|
874
|
-
<enclosure url="${
|
|
911
|
+
<category>${J(o.tags.join(", "))}</category>`:""}${o.image?`
|
|
912
|
+
<enclosure url="${J(this.options.baseUrl)}${J(o.image)}" type="image/png" length="0"/>`:""}
|
|
875
913
|
</item>`).join(`
|
|
876
|
-
`),
|
|
914
|
+
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
877
915
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
878
916
|
<channel>
|
|
879
|
-
<title>${
|
|
880
|
-
<link>${
|
|
881
|
-
<description>${
|
|
917
|
+
<title>${J(this.options.siteName)}</title>
|
|
918
|
+
<link>${J(this.options.baseUrl)}${J(this.options.blogPath)}</link>
|
|
919
|
+
<description>${J(this.options.siteName)} Blog</description>
|
|
882
920
|
<language>en</language>
|
|
883
|
-
<atom:link href="${
|
|
884
|
-
${
|
|
921
|
+
<atom:link href="${J(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
922
|
+
${n}
|
|
885
923
|
</channel>
|
|
886
|
-
</rss>`;return await t("rss.xml",
|
|
924
|
+
</rss>`;return await t("rss.xml",s),{fileName:"rss.xml",content:s,postCount:e.length}}},jt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],Bt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Ma(r){let e=["# AI Crawler Management"];if(r==="block-all"){for(let t of[...jt,...Bt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(r==="allow-all"){for(let t of[...jt,...Bt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of jt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of Bt)e.push(`User-agent: ${t}`,"Allow: /","");return e}var Hr={prerendersRecords(){let r=this.options.prerenderRecords??!0;if(typeof r=="boolean")return r;throw new Error(`appConfig.prerenderRecords must be true or false. Got ${JSON.stringify(r)}.`)},prerenderedRecordsRoute(r){return this.prerendersRecords()?tt(r):null},serverMetadataSource(r){return r.exportsGenerateMetadata?"page":this.isBlogPostRoute(r)?"blog":tt(r)?"entity":null},entityMetadataRoute(r){return this.serverMetadataSource(r)==="entity"?tt(r):null},assertServerMetadata(r){for(let e of r){if(e.exportsGenerateMetadata){if(this.isBlogPostRoute(e))throw new Error(`[dndev] ${e.file} exports \`generateMetadata\`, but blog post pages get theirs generated from the post's frontmatter (a second one would conflict). Remove it from the page.`);if(this.isClientComponent(e.file))throw new Error(`[dndev] ${e.file} exports \`generateMetadata\` but is a client module ('use client'). Next reads generateMetadata only from server modules, so the page would ship without its title and description. Keep the page module a server component (no 'use client') that exports generateMetadata and renders a 'use client' component, or remove generateMetadata.`);continue}let t=this.entityMetadataRoute(e);if(t){if(!this.appDependsOn("entities"))throw new Error(`[dndev] ${e.path} is an entity page ("${t.collection}" records): its metadata derives from the entity definition, but the app does not depend on an \`entities\` package. Add the entity to the app's \`entities\` package, mark the page \`seo: { noindex: true }\`, or export \`generateMetadata\` from a server page module.`);this.entityMetadataExport(e,this.entityPageReader(e,"site"))}}},entityPageReader(r,e){let t=e==="site"?this.prerenderedRecordsRoute(r):null,n=this.entityMetadataRoute(r),s=n??t;if(!s)return{imports:"",setup:"",expr:null,schemas:null,named:{}};let o=[n&&"entity pages read their record on the server (metadata, JSON-LD, 404)",t&&"entity pages prerender their published records at build"].filter(Boolean).join("; "),a=n?"Mark the page `seo: { noindex: true }`, or export `generateMetadata` from a server page module and set `appConfig.prerenderRecords: false`.":"Set `appConfig.prerenderRecords: false` to render them on their first request.";return this.serverCrudReader([s],o,a)},staticParamsExport(r,e){if(!this.convertRouteToAppPath(r.path).includes("["))return{named:{},code:""};let t=this.prerenderedRecordsRoute(r);return t?{named:{"@donotdev/core/next":["listStaticParams"]},code:`
|
|
887
925
|
// Every published "${t.collection}" record is prerendered at build (the sitemap's records,
|
|
888
926
|
// public reader). A record published later renders on its first request. All are cached
|
|
889
927
|
// like the static pages (ISR). Opt out: appConfig.prerenderRecords = false.
|
|
@@ -895,7 +933,7 @@ export async function generateStaticParams() {
|
|
|
895
933
|
export function generateStaticParams() {
|
|
896
934
|
return [];
|
|
897
935
|
}
|
|
898
|
-
`}},entityMetadataExport(
|
|
936
|
+
`}},entityMetadataExport(r,e){let t=this.entityMetadataRoute(r);if(!t)return null;let{defaultLanguage:n,languages:s}=this.options;if(!n)throw new Error("Route handler: languages not set before page generation (runDiscoveries calls useLanguages)");let[o]=q(t.path),a=this.isMultilingual(),i=r.meta?.seo?.type??"website",l=this.calculateRelativeImportPath("src/config/dndev-config-i18n.js",r.path),u=this.options.siteName;if(!u)throw new Error(`[dndev] ${r.path}: entity page titles end with the site name. Set appConfig.app.name (or appConfig.seo.siteName).`);return{vendorImports:`import type { Metadata } from 'next';
|
|
899
937
|
import { notFound } from 'next/navigation';
|
|
900
938
|
import { cache } from 'react';
|
|
901
939
|
`,named:{"@donotdev/core/server":["buildBreadcrumbJsonLd","buildProductJsonLd","deriveEntitySeo","languageUrl"],"@donotdev/core/next":["appBaseUrl","entityPageSeo","jsonLdScript","readEntityPageRecord"],"@donotdev/core/rsc":["useTranslation"]},typeImports:`import type { LanguageRouting } from '@donotdev/core/server';
|
|
@@ -907,7 +945,7 @@ import '${l}';
|
|
|
907
945
|
// and hreflang come from AutoMetaTags. No public record (missing, hidden status): HTTP 404.
|
|
908
946
|
const ROUTE = ${JSON.stringify(t)};
|
|
909
947
|
|
|
910
|
-
const LANGUAGE_ROUTING: LanguageRouting = ${JSON.stringify({languages:
|
|
948
|
+
const LANGUAGE_ROUTING: LanguageRouting = ${JSON.stringify({languages:s,defaultLanguage:n})};
|
|
911
949
|
|
|
912
950
|
// next.config trailingSlash: page URLs end with \`/\` when true
|
|
913
951
|
const TRAILING_SLASH = ${JSON.stringify(this.options.trailingSlash)};
|
|
@@ -940,7 +978,7 @@ const pageSeo = cache(async (language: string, value: string) => {
|
|
|
940
978
|
/** The URL's page identity; \`notFound()\` (HTTP 404) when no public record matches. */
|
|
941
979
|
async function requireSeo(params: Params) {
|
|
942
980
|
const { ${a?"lang, ":""}${o} } = await params;
|
|
943
|
-
const seo = await pageSeo(${a?"lang":JSON.stringify(
|
|
981
|
+
const seo = await pageSeo(${a?"lang":JSON.stringify(n)}, ${o});
|
|
944
982
|
if (!seo) notFound();
|
|
945
983
|
return seo;
|
|
946
984
|
}
|
|
@@ -966,15 +1004,15 @@ export async function generateMetadata({ params }: { params: Params }): Promise<
|
|
|
966
1004
|
/>
|
|
967
1005
|
)}
|
|
968
1006
|
</>
|
|
969
|
-
);`}}};var
|
|
970
|
-
`+t.map((
|
|
971
|
-
`),"invalid-configuration")}var
|
|
1007
|
+
);`}}};var Ua=/^[A-Za-z_$][\w$]*$/,ja=/^(?:'[^'\\]*'|"[^"\\]*"|`[^`\\$]*`|-?\d[\w.]*|null|undefined|true|false)$/;function Ba(r,e){let t=0;for(let n=e;n<r.length;n++){let s=r[n];if(s==="'"||s==='"'||s==="`"){for(n++;n<r.length&&r[n]!==s;n++)r[n]==="\\"&&n++;continue}if(t===0&&(s===","||s==="/"&&/[/*]/.test(r[n+1]??"")))return n;if("([{".includes(s))t++;else if(")]}".includes(s)){if(t===0)return n;t--}}return r.length}function Ga(r){let e=/(^|[{,\s])entity\s*:\s*/gm,t="",n=0,s;for(;s=e.exec(r);){let o=s.index+s[0].length,a=Ba(r,o),i=r.slice(o,a).trimEnd();if(!i)continue;let l=ja.test(i)?i:Ua.test(i)?`{ identifier: '${i}' }`:`{ expression: ${JSON.stringify(i)} }`;t+=r.slice(n,o)+l,n=o+i.length,e.lastIndex=n}return t+r.slice(n)}function za(r){let e=r instanceof Error?r.message:String(r),t=/^(\S+) is not defined$/.exec(e)?.[1];return t?`\`${t}\` is not a literal value (an import, a variable or a call)`:`it is not a plain object literal (${e})`}function Wr(r,e="unknown"){let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,n=r.match(t);if(!n)return null;let s=n[1];s=s.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,l)=>`icon: '${l}'`),s=Ga(s);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;[...r.matchAll(o)].forEach(i=>{let l=i[1],u=i[2];s=s.replace(new RegExp(`\\b${l}\\b`,"g"),`'${u}'`)});try{return Function(`return ${s}`)()}catch(i){throw C("dndev-routes",`${e}: PageMeta cannot be read at build: ${za(i)}. Without it the page would lose its route, auth and seo. The build reads PageMeta statically: write every value as a literal in the object (strings, numbers, booleans, null, arrays and objects of those, icon: <Icon />, a string constant declared in the page file: const NAMESPACE = 'home'), except entity, the defineEntity identifier imported from 'entities'. Example: auth: { required: true, role: 'admin' } instead of auth: ADMIN_ONLY.`,"invalid-configuration")}}function qr(r){return/^[ \t]*export\s+(?:(?:async\s+)?function\s*\*?\s*generateMetadata\b|(?:const|let)\s+generateMetadata\b|\{[^}]*\bgenerateMetadata\b[^}]*\})/m.test(r)}var xe=null,Jr=null;function Ha(r){let t=(r.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Wa(r){let e=r.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw C("dndev-routes",`${r.file}: PageMeta signedInRedirect must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`,"invalid-configuration");if(e.split(/[?#]/)[0]===r.path)throw C("dndev-routes",`${r.file}: PageMeta signedInRedirect points at the page itself (${e}): signed-in visitors would loop. Use another page.`,"invalid-configuration")}}function qa(r,{pageGenerateMetadata:e=!1}={}){if(!r.path.split("/").some(n=>n.startsWith(":"))||Gt(r)||!et(r)||r.meta?.entity||r.metaExport?.namespace==="blog"||e&&r.exportsGenerateMetadata)return;let t=["declare the record entity it shows: import { productEntity } from 'entities'; then entity: productEntity in its PageMeta (title, description and image from the record)",...e?["export Next's generateMetadata from the page module (a server module, no 'use client')"]:[],"keep it out of search engines: seo: { noindex: true } in its PageMeta"];throw C("dndev-routes",`${r.file}: public dynamic route ${r.path} has no per-URL SEO: every URL would get the same title and description (PageMeta + i18n), duplicate pages for search engines. Fix, one of:
|
|
1008
|
+
`+t.map((n,s)=>` ${s+1}. ${n}`).join(`
|
|
1009
|
+
`),"invalid-configuration")}var Pe=class extends ee{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(),n=process.env.DNDEV_BUILD_ID;if(xe&&Jr===n)return this.logger.debug("Using cached route discovery results"),this.routes=xe.routes,this.errors=xe.errors,this.source=xe.source,this.entityResolver=xe.entityResolver,{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 s=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${s} 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/"),xe={routes:this.routes,errors:this.errors,source:this.source,entityResolver:this.entityResolver},Jr=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"}`}getEntityResolver(){return this.entityResolver??=ke(this.pathResolver.getAppRoot()),this.entityResolver}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:n}=e;this.entityResolver=ke(t);let s=await this._batchProcessFiles(n,u=>this._analyzePageFile(u,t)),o=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(o,u=>this._analyzePageFile(u,t)),i=[...s,...a];this.logger.debug(`Auto-discovering from ${n.length} app + ${o.length} additional files`),this.routes=i.filter(u=>u.path==="home"||u.path==="/home"?(this.logger.debug(`Filtered reserved route: ${u.path} - Use root "/" instead (${u.file})`),!1):!0);let l=new Map;for(let u of this.routes){let c=u.path;if(l.has(c)){let p=l.get(c);throw C("dndev-routes",`${u.file}: route ${c} is also the route of ${p.file}: two pages cannot share a URL. Give one of them another path with a PageMeta route override, e.g. export const meta: PageMeta = { route: '/custom-path' };`,"invalid-configuration")}l.set(c,u),Wa(u),qa(u,{pageGenerateMetadata:this.options.pageGenerateMetadata===!0})}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${n.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(n=>this.pathResolver.resolveAppPath(n));if(t.length===0)return[];try{let{consumerFiles:n}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return n}catch(n){return this.logger.debug(`Error scanning additional patterns: ${n.message}`),[]}}async _analyzePageFile(e,t){let n=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!n)return null;let s=e.relativePath,o="/src/"+s.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(n,s),i=Ha(o),u=i===Ae.HOMEPAGE_COMPONENT?Ae.HOMEPAGE_PATH:this._resolveRoutePath(a,s,e.absolutePath),c=this._extractPageMeta(s),p=await Qn(a,n,s,this.entityResolver),{entity:d,action:f,...h}=a||{};return{path:u,component:i,importPath:o,auth:a?.auth||!1,meta:{...c,...h,...p&&{entity:p},action:c.action},metaExport:a&&{...a,...p&&{entity:p}},exportsGenerateMetadata:qr(n),file:s}}_extractMetaExport(e,t){try{let n=Wr(e,t);return n?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(n)}`),n):null}catch(n){if(ce(n))throw n;return this.logger.debug(`Error parsing meta export from ${t}: ${n.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,n){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let s=e.route.trim();return s==="/"?"/":(s=s.replace(/\/+/g,"/"),s.startsWith("/")||(s="/"+s),s)}if(typeof e.route=="object"&&e.route!==null){let s=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let a=o.map(i=>`:${i}`).join("/");return`${s}/${a}`}return s}return this.logger.warn(`Invalid route format in ${n}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${n}`),this._generateRoutePath(t)}_extractPageMeta(e){let t=e.split("/").pop()?.replace(".tsx","")||"",n=t.replace(/Page$/,"");n=n.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),n=n.charAt(0).toUpperCase()+n.slice(1);let s=e.split("/"),o=null;return s.length>1&&(t.includes("List")?o="list":t.includes("Form")||t.includes("Create")||t.includes("Edit")?o="form":(t.includes("Detail")||t.includes("View"))&&(o="detail")),{title:n,action:o,file:e}}};var nt=class extends H{constructor(e={}){super(Pe,e),this.rendersSessionTree=!1,this.appRouteSegments=[],this.i18n=null,this.fonts=null}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,proxyPath:L.next.proxy,manifestPath:L.next.routeManifest,languages:[],defaultLanguage:null,trailingSlash:!1,siteName:null,defaultImage:void 0,defaultNamespace:void 0}}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}useI18n(e){this.i18n=e}useFonts(e){this.fonts=e}isMultilingual(){return this.options.languages.length>1}defaultImage(){return this.options.defaultImage||Ne}defaultNamespace(){return this.options.defaultNamespace||"home"}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 n=e.split("/").filter(Boolean).length;return n===0?`./${t}`:`${"../".repeat(n)}${t}`}createDiscovery(e){return new e(this.pathResolver,{...this.options,...Ct})}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],n=t.filter(o=>o.auth&&o.auth.required).length,s=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${s} found${n>0?`, ${n} are authguarded`:""}`)}getEntityResolver(){return this.discovery.getEntityResolver()}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}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||[];this.options.generateAppPages&&this.assertServerMetadata(t);let n={totalRoutes:t.length,authRequired:t.filter(s=>s.auth&&s.auth.required).length,publicRoutes:t.filter(s=>!s.auth||s.auth===!1).length,source:e.source,hasBlogFeed:Ir(this.pathResolver.getAppRoot()),trailingSlash:this.options.trailingSlash,serverMetadataPaths:this.options.generateAppPages?t.filter(s=>this.serverMetadataSource(s)).map(s=>s.path):[],recordBreadcrumbPaths:this.options.generateAppPages?t.filter(s=>this.entityMetadataRoute(s)).map(s=>s.path):[],generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
972
1010
|
// Generated at: ${new Date().toISOString()}
|
|
973
1011
|
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
974
1012
|
|
|
975
1013
|
const routeMapping = ${JSON.stringify(t,null,2)};
|
|
976
1014
|
|
|
977
|
-
const routeManifest = ${JSON.stringify(
|
|
1015
|
+
const routeManifest = ${JSON.stringify(n,null,2)};
|
|
978
1016
|
|
|
979
1017
|
// Populate unified DnDev config for runtime access (universal CSR/SSR)
|
|
980
1018
|
if (typeof globalThis !== 'undefined') {
|
|
@@ -987,7 +1025,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
987
1025
|
timestamp: Date.now(),
|
|
988
1026
|
};
|
|
989
1027
|
}
|
|
990
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1028
|
+
globalThis._DNDEV_CONFIG_.${Y.routes} = {
|
|
991
1029
|
mapping: routeMapping,
|
|
992
1030
|
manifest: routeManifest,
|
|
993
1031
|
};
|
|
@@ -997,35 +1035,35 @@ if (typeof globalThis !== 'undefined') {
|
|
|
997
1035
|
export const routes = routeMapping;
|
|
998
1036
|
export const manifest = routeManifest;
|
|
999
1037
|
export default { routes: routeMapping, manifest: routeManifest };
|
|
1000
|
-
`}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.generateRevalidationRoute(e)),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e)}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
|
|
1038
|
+
`}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.generateRevalidationRoute(e)),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e)}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 s of t)await this.generateTreeLayout(s);let n=0;for(let s of e.routes){let o=this.isSessionOnlyRoute(s)?"session":"site",a=await this.generateSingleAppPage(s,o);a&&n++,a&&o==="site"&&this.rendersSessionTree&&this.generateSessionPage(s)}this.logger.debug(`Successfully generated ${n}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}isSessionOnlyRoute(e){return this.rendersSessionTree&&!!this.normalizeAuth(e.auth)}generateSessionPage(e){let t=this.appDirFor(e.path,"session"),s=`${"../".repeat(t.split("/").filter(Boolean).length)}${this.appDirFor(e.path).slice(1)}/${U("page","tsx").replace(/\.tsx$/,"")}`,o=["default"];this.serverMetadataSource(e)&&o.push("generateMetadata"),this.writeGeneratedFile(`src/app${t}/${U("page","tsx")}`,`// Generated by @donotdev/config - DO NOT EDIT
|
|
1001
1039
|
// Per-request render of ${e.path} (visitors with an auth cookie): same page as the cached one.
|
|
1002
1040
|
|
|
1003
|
-
export { ${o.join(", ")} } from '${
|
|
1004
|
-
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${
|
|
1005
|
-
`:"",p=this.entityPageReader(e,t),d=t==="site"?this.staticParamsExport(e,p):{named:{},code:""},f=this.entityMetadataExport(e,p),h={"@donotdev/core/server":p.expr?["HIDDEN_STATUSES"]:[],"@donotdev/core/next":[],"@donotdev/core/rsc":[]};for(let v of[d.named,f?.named??{},p.named])for(let[
|
|
1006
|
-
`).join(""),
|
|
1041
|
+
export { ${o.join(", ")} } from '${s}';
|
|
1042
|
+
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${U("page","tsx")}`,`src/app/**/${U("layout","tsx")}`,`src/app/**/${U("not-found","tsx")}`,`src/app/${U("global-not-found","tsx")}`,"src/app/**/*PageClient.tsx"],n=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),s=0;for(let o of n)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),s++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(a){this.logger.debug(`Could not clean file ${o}: ${a.message}`)}s>0&&this.logger.debug(`Cleaned ${s} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e,t="site"){try{let n=this.appDirFor(e.path,t),s=`src/app${n}/${U("page","tsx")}`,o=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(o)&&!await this.hasGenerationMarker(o))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let a={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},i=this.generatePageFileContent(a,t);this.writeGeneratedFile(s,i,`app page: ${n}`);let l=this.extractComponentName(a.filePath),u=this.calculateRelativeImportPath(a.relativePath,a.path);return this.isBlogPostRoute(a)?this.writeGeneratedFile(`src/app${n}/BlogPostClient.tsx`,this.generateBlogPostClientContent(l,u),`app blog client: ${n}`):this.isClientComponent(a.filePath)&&this.writeGeneratedFile(`src/app${n}/${l}Client.tsx`,this.generateMountedClientContent(l,u),`app client wrapper: ${n}`),!0}catch(n){return this.logger.debug(`Error generating page for route ${e.path}: ${n.message}`),!1}}convertRouteToAppPath(e){if(e===Ae.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(n=>n.startsWith(":")?`[${n.slice(1)}]`:n==="*"?"[...slug]":n).join("/")}generatePageFileContent(e,t="site"){let n=this.extractComponentName(e.filePath),s=e.relativePath||e.file,o=this.calculateRelativeImportPath(s,e.path);if(this.isBlogPostRoute(e))return this.generateBlogPostRSCContent(e,n,o);let a=this.isClientComponent(e.filePath),i=this.normalizeAuth(e.auth)?e.auth:null,l=e.meta?.signedInRedirect??null,u=[...i?["AuthGuard"]:[],...l?["SignedInRedirect"]:[]],c=u.length?`import { ${u.join(", ")} } from '@donotdev/ui';
|
|
1043
|
+
`:"",p=this.entityPageReader(e,t),d=t==="site"?this.staticParamsExport(e,p):{named:{},code:""},f=this.entityMetadataExport(e,p),h={"@donotdev/core/server":p.expr?["HIDDEN_STATUSES"]:[],"@donotdev/core/next":[],"@donotdev/core/rsc":[]};for(let v of[d.named,f?.named??{},p.named])for(let[x,O]of Object.entries(v))h[x].push(...O);let m=Object.entries(h).filter(([,v])=>v.length>0).map(([v,x])=>`import { ${x.join(", ")} } from '${v}';
|
|
1044
|
+
`).join(""),y=this.serverMetadataSource(e)==="page"?`
|
|
1007
1045
|
// The page module's own Next metadata
|
|
1008
1046
|
export { generateMetadata } from '${o}';
|
|
1009
|
-
`:"",
|
|
1047
|
+
`:"",S=v=>{let x=l?`<SignedInRedirect to={${JSON.stringify(l)}}>${v}</SignedInRedirect>`:v;return i?`<AuthGuard auth={${JSON.stringify(i===!0?{required:!0}:i)}}>${x}</AuthGuard>`:x},T=a?`import ${n}Client from './${n}Client';`:`import ${n} from '${o}';`,R=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1010
1048
|
// This file will be regenerated when src/pages changes
|
|
1011
1049
|
// To customize: edit ${e.filePath} or create manual app/** files
|
|
1012
1050
|
|
|
1013
|
-
${f?.vendorImports??""}${
|
|
1014
|
-
${p.setup}${d.code}${f?f.code:""}${
|
|
1015
|
-
export default async function ${
|
|
1016
|
-
${f.render.replace("{PAGE}",
|
|
1051
|
+
${f?.vendorImports??""}${m}${f?.typeImports??""}${c}${p.imports}${f?.appImports??""}${T}
|
|
1052
|
+
${p.setup}${d.code}${f?f.code:""}${y}`;if(f){let v=a?`<${n}Client />`:`<${n} {...props} />`;return`${R}
|
|
1053
|
+
export default async function ${n}Route(props: { params: Params }) {
|
|
1054
|
+
${f.render.replace("{PAGE}",S(v))}
|
|
1017
1055
|
}
|
|
1018
1056
|
`}return a?`${R}
|
|
1019
|
-
export default function ${
|
|
1020
|
-
return ${
|
|
1057
|
+
export default function ${n}Route() {
|
|
1058
|
+
return ${S(`<${n}Client />`)};
|
|
1021
1059
|
}
|
|
1022
1060
|
`:u.length?`${R}
|
|
1023
|
-
export default function ${
|
|
1024
|
-
return ${
|
|
1061
|
+
export default function ${n}Route(props: Record<string, unknown>) {
|
|
1062
|
+
return ${S(`<${n} {...props} />`)};
|
|
1025
1063
|
}
|
|
1026
1064
|
`:`${R}
|
|
1027
|
-
export default ${
|
|
1028
|
-
`}extractComponentName(e){let
|
|
1065
|
+
export default ${n};
|
|
1066
|
+
`}extractComponentName(e){let n=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return n.charAt(0).toUpperCase()+n.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}}normalizeAuth(e){return e===!0?{}:!e||typeof e!="object"||!e.required&&!e.role&&!e.tier?null:{role:e.role,tier:e.tier}}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let s=e.replace(/\.tsx$/,"").replace(/^src\//,""),o=this.appDirFor(t).split("/").filter(Boolean).length;return`${"../".repeat(o+1)}${s}`}hasDynamicSegment(e){return e.includes(":")||e.includes("[")}generateMountedClientContent(e,t){return this.options.ssr?`// Generated by @donotdev/config - DO NOT EDIT
|
|
1029
1067
|
// This file will be regenerated when src/pages changes
|
|
1030
1068
|
'use client';
|
|
1031
1069
|
|
|
@@ -1052,21 +1090,21 @@ export default function ${e}Client() {
|
|
|
1052
1090
|
if (!mounted) return null;
|
|
1053
1091
|
return <${e} />;
|
|
1054
1092
|
}
|
|
1055
|
-
`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let
|
|
1056
|
-
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};Object.assign(
|
|
1057
|
-
`];
|
|
1058
|
-
`);for(let c of
|
|
1093
|
+
`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let n=this.pathResolver.readSync(t);return n?n.split(`
|
|
1094
|
+
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};Object.assign(nt.prototype,yr,xr,Pr,Tr,Hr,Dr,vr);function Vr(r={}){return new nt(r)}var Ja="dndev",Va="crud",Ka="entity-";function Kr(r,e,t){return e?r?.[e]?.[t]:void 0}function pe(r){return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function Xr(r){return r?.metaExport||r?.meta||{}}function Xa(r,{siteName:e,defaultNamespace:t,t:n}){let s=Xr(r),{title:o,pageTitle:a}=Lt({meta:s,ns:s.namespace||null,defaultNs:t,t:n,siteName:e});return a??o}function Ya(r,e,t){let n=Xr(r),s=n.seo||{};if(s.description===null)return;let o=Kr(e,n.namespace,t);return pe(s.description)??pe(o?.description)}function Yr(r){let{siteName:e,description:t,baseUrl:n,sitemapRoutes:s,routes:o,blogPosts:a=[],blogPath:i="/blog",translations:l,language:u,defaultNamespace:c}=r,p=Kr(l,Ja,u)?.seo,d=pe(p?.llmsPages),f=pe(p?.llmsBlog);if(!d||!f)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${u}".`);if(!c)throw new Error('[dndev] llms.txt: getLlmsTxtSource needs options.defaultNamespace (appConfig.seo.defaultNamespace, else "home").');let h=new Map(o.map(v=>[v.path,v])),m={siteName:e,defaultNamespace:c,t:Xe(Object.fromEntries(Object.entries(l||{}).map(([v,x])=>[v,x?.[u]])))},y=new Map(a.map(v=>[`${i}/${v.slug}`,v])),S=s.map(({path:v,collection:x})=>{let O=y.get(v);if(O)return{path:v,title:O.title,...pe(O.description)&&{description:pe(O.description)},section:f};if(x)return{path:v,collection:x};let B=h.get(v);if(!B&&v===i)return{path:v,title:f};let M=Ya(B,l,u);return{path:v,title:Xa(B,m),...M&&{description:M}}}),T={},R={};for(let[v,x]of Object.entries(l||{})){if(v===Va&&x?.[u]&&(R[v]=x[u]),!v.startsWith(Ka))continue;x?.[u]&&(R[v]=x[u]);let O=pe(x?.[u]?.namePlural);O&&(T[v]=O)}return{name:e,...pe(t)&&{summary:pe(t)},baseUrl:n,pagesHeading:d,routes:S,entityHeadings:T,language:u,translations:R}}function Zr(r={}){let{siteName:e,baseUrl:t,blogPosts:n=[],blogPath:s="/blog",appRoot:o,logger:a}=r;if(!e||!t)return null;if(n.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=D.getInstance(),l=o?i.resolvePath("src/content/blog",o):null;if(!l||!i.pathExists(l))return null;let u=[`# ${e}
|
|
1095
|
+
`];r.description&&u.push(`> ${r.description}
|
|
1096
|
+
`);for(let c of n){let p=i.resolvePath(`${c.slug}_en.md`,l);try{let d=i.readSync(p,{format:"text"});if(!d)continue;let f=d.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),h=`${t}${s}/${c.slug}`;u.push(`## ${c.title}
|
|
1059
1097
|
`),u.push(`Source: ${h}
|
|
1060
1098
|
`),c.date&&u.push(`Date: ${c.date}
|
|
1061
1099
|
`),u.push(f.trim()),u.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${c.slug}`)}}return u.join(`
|
|
1062
|
-
`)}function
|
|
1100
|
+
`)}function zt(r){let e=(r??"").trim().replace(/\/+$/,"");return e?/^https?:\/\//i.test(e)?e:`https://${e}`:null}function Za(r){let e=zt(r);if(!e)throw new Error("[dndev] Set NEXT_PUBLIC_APP_URL: the sitemap and llms.txt publish absolute URLs.");return e}var Qr=`src/app/sitemap.xml/${U("route","ts")}`,es=`src/app/llms.txt/${U("route","ts")}`;function ts(r){let e=r.filter(s=>s.path.includes(":")),t=`${r.length-e.length} static + ${e.length} dynamic`;if(e.length===0)return t;let n=e.map(s=>`${s.path} \u2192 ${s.collection??"no collection"}`);return`${t} (${n.join(", ")})`}function rt(r,e,t){return`import { ${[...e,...t.named[r]??[]].join(", ")} } from '${r}';`}var Ht=class extends H{constructor(e={}){super(Pe,e);let t=D.getInstance(),n=ae("SEO Handler",this.options.debug,this.options.verbose),s=process.env.NEXT_PUBLIC_APP_URL||null;s&&this.options.debug&&n.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${s}`);let o=e.baseUrl;!o&&s&&(o=zt(s)),this._baseUrlExpr=e.baseUrl?`appBaseUrl(${JSON.stringify(e.baseUrl)})`:"appBaseUrl(process.env.NEXT_PUBLIC_APP_URL)",o?n.debug(`Found app URL: ${o}`):n.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let a=e.siteName||null;if(n.verbose(`Name: ${a||"Not found"}`),n.verbose(`URL: ${o||"Not found"}`),a&&n.debug(` - Site name from appConfig: "${a}"`),e.disabled===!0){n.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}if(!this.options.isDev&&(o=Gr(o||null,"NEXT_PUBLIC_APP_URL",n),!o)){this.disabled=!0;return}let i=[];if(o||i.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),a||i.push("siteName (APP_NAME in src/config/app.ts)"),i.length>0){n.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),i.forEach(l=>n.warn(` - ${l}`)),n.warn(""),n.warn(" To fix:"),o||n.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),a||(n.warn(" 2. Add APP_NAME export to src/config/app.ts:"),n.warn(' export const APP_NAME = "Your App Name";')),n.warn(""),n.warn(" robots.txt and sitemap.xml will NOT be generated."),n.warn(""),this.disabled=!0;return}this._baseUrl=o,this._siteName=a,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this._sitemapEnabled=this.options.generateSitemap!==!1,this.seoGenerator=new Ze({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,baseUrl:o,siteName:a,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json",trailingSlash:!1}}useRoutes(e){this._routeData=e}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:this._routeData??await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}async generateManifest(e){this.disabled&&await super.generateManifest(e)}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(this.disabled)return;let t=async(i,l)=>{if(!i){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${i}`,l,i)},n=e.routes,s,o;await $e(["robots.txt","rss.xml","seo-manifest.json","sitemap.xml","llms.txt","llms-full.txt"],()=>{s=this.seoGenerator.discoverBlogPosts(),o=this.seoGenerator.getSitemapRoutes(n,s)},this.logger)&&(await $e(["robots.txt","rss.xml","seo-manifest.json"],async()=>{let i=await this.seoGenerator.generateSEOFiles(e,t,s);i.robotsTxt&&!i.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${i.robotsTxt.disallowedPaths||0} disallowed paths`),i.rss&&!i.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${i.rss.postCount||0} blog posts`),i.manifest&&!i.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json")},this.logger),this._sitemapEnabled&&await $e(["sitemap.xml"],()=>this.generateSitemapRoute(o),this.logger),this._llmsTxtEnabled&&(await $e(["llms.txt"],()=>this.generateLlmsTxtRoute(n,s,o),this.logger),s.length>0&&await $e(["llms-full.txt"],()=>{let i=Zr({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:this.pathResolver.getAppRoot(),blogPosts:s,logger:this.logger});i&&(this.writeGeneratedFile("public/llms-full.txt",i,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))},this.logger)))}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.serverCrudReader(e),n=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1063
1101
|
// Regenerated on every build from src/pages (PageMeta) and appConfig.
|
|
1064
1102
|
// Public routes + one URL per published record of each dynamic route's entity
|
|
1065
1103
|
// (read with the public role). Keep a page out with \`seo: { noindex: true }\`.
|
|
1066
1104
|
|
|
1067
|
-
${
|
|
1105
|
+
${rt("@donotdev/core/server",["HIDDEN_STATUSES","languageUrls"],t)}
|
|
1068
1106
|
import type { LanguageRouting } from '@donotdev/core/server';
|
|
1069
|
-
${
|
|
1107
|
+
${rt("@donotdev/core/next",["appBaseUrl","buildSitemap","formatSitemapXml"],t)}
|
|
1070
1108
|
import type { SitemapRoute } from '@donotdev/core/next';
|
|
1071
1109
|
${t.imports}
|
|
1072
1110
|
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
@@ -1095,13 +1133,13 @@ export async function GET(): Promise<Response> {
|
|
|
1095
1133
|
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
|
|
1096
1134
|
});
|
|
1097
1135
|
}
|
|
1098
|
-
`;this.writeGeneratedFile(
|
|
1136
|
+
`;this.writeGeneratedFile(Qr,n,"sitemap route");let s=this.pathResolver.resolveAppPath("public/sitemap.xml");this.pathResolver.pathExists(s)&&await this.pathResolver.remove(s),this.logger.info(`\u{1F5FA}\uFE0F sitemap: ${ts(e)} (${Qr}); URL count printed by dndev build`)}useTranslations(e){this._translations=e}async generateLlmsTxtRoute(e,t,n){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=Yr({siteName:this._siteName,description:this._siteDescription,baseUrl:this._baseUrl,sitemapRoutes:n,routes:e,blogPosts:t,blogPath:this.seoGenerator.options.blogPath,translations:this._translations,language:this._languageRouting.defaultLanguage,defaultNamespace:this.options.defaultNamespace||"home"}),{baseUrl:o,...a}=s,i=this.serverCrudReader(s.routes),l=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1099
1137
|
// Regenerated on every build from src/pages (PageMeta), translations and appConfig.
|
|
1100
1138
|
// Same URLs as app/sitemap.xml: public pages + one link per published record of each
|
|
1101
1139
|
// dynamic route's entity. Keep a page out with \`seo: { noindex: true }\`.
|
|
1102
1140
|
|
|
1103
|
-
${
|
|
1104
|
-
${
|
|
1141
|
+
${rt("@donotdev/core/server",["HIDDEN_STATUSES","deriveEntitySeo","formatTrailingSlash"],i)}
|
|
1142
|
+
${rt("@donotdev/core/next",["appBaseUrl","buildLlmsTxt"],i)}
|
|
1105
1143
|
import type { LlmsTxtSource } from '@donotdev/core/next';
|
|
1106
1144
|
${i.imports}
|
|
1107
1145
|
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
@@ -1130,26 +1168,26 @@ export async function GET(): Promise<Response> {
|
|
|
1130
1168
|
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
1131
1169
|
});
|
|
1132
1170
|
}
|
|
1133
|
-
`;this.writeGeneratedFile(
|
|
1134
|
-
`}function
|
|
1171
|
+
`;this.writeGeneratedFile(es,l,"llms.txt route"),this.logger.info(`\u{1F4C4} llms.txt: ${ts(s.routes)} (${es})`)}createManifestContent(){return{}}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function ns(r={}){return new Ht(r)}var Ce=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(n,...s)=>{this.options.debug}},this.patterns={selectors:{...ct.selectors,...this.options.customPatterns?.selectors},themes:{...ct.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 n=t.split("-").filter(a=>a.length>0);if(n.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let s=n.map((a,i)=>{let l=a.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!s||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(s)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${s}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(s)?`${s}Var`:s}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,n){let s=[],o,a=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(i))!==null;){let[,u,c,p]=o;if(!u||!p)continue;let d=c.match(this.patterns.themes.themeIcon),f=c.match(this.patterns.themes.themeIsDark),h={name:u,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:d?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${u} (${p})`),s.push(h),n.themes.set(u,{name:u,displayName:p,isDark:h.isDark,file:a,variables:new Set,meta:h.meta})}return s.length>0&&this._debug(`Extracted ${s.length} themes from ${a}`),s}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(s=>{let o=s.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,n){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?n==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(s=>{let o=s.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],n=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return n&&n.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let a=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,n="consumer"){let s={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,s);this.extractClasses(e,s),this.extractVariables(e,s,n),this.extractKeyframes(e,s);let a=this.validateCSS(e);return{themes:o,classes:Array.from(s.classes),variables:{framework:Array.from(s.variables.framework),consumer:Array.from(s.variables.consumer),all:[...Array.from(s.variables.framework),...Array.from(s.variables.consumer)].sort()},keyframes:Array.from(s.keyframes),warnings:a}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};var rs="@donotdev/components/styles",Qa=/@import\s+['"](\.[^'"]+)['"]\s*;/g,st=class extends ee{constructor(e,t,n={}){super(t,n),this.cssExtractor=e||new Ce(t,{debug:n.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:n}=e;this.logger.debug(`Scanning ${t.length} framework + ${n.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",n),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),n.length>0?(this.logger.debug(`Consumer files found: ${n.length}`),this.logger.debug("Consumer files:",n)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t);let s=await this._processConsumerFiles(n),o=this._serializeThemes(),a={framework:this._readFrameworkTokenCss(),app:s};return this.logger.debug(`Discovered ${o.length} themes:`,o.map(i=>i.name)),{themes:o,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(),fontCss:a}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return ut.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 n=await this.pathResolver.read(t,{format:"text"}),s=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(n,s,this.discovered),this.cssExtractor.extractClasses(n,this.discovered),this.cssExtractor.extractVariables(n,this.discovered,"framework"),this.cssExtractor.extractKeyframes(n,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(s)}`)}catch(n){this.logger.debug(`Error scanning framework file ${t}: ${n.message}`)}}async _processConsumerFiles(e){let t=[];for(let n of e)try{let s=await this.pathResolver.read(n,{format:"text"}),o=this.pathResolver.normalizePath(n);t.push({file:this.pathResolver.getRelativePath(o),css:s}),this.cssExtractor.extractThemes(s,o,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(o)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${n}: ${s.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(rs,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw C("dndev-theme",`cannot resolve ${rs} (framework font defaults), resolved from @donotdev/ui: check that @donotdev/ui and @donotdev/components are installed`,"missing-required-resource");let t=new Set,n=s=>{if(t.has(s))return"";t.add(s);let o=this.pathResolver.readSync(s,{format:"text"});if(typeof o!="string")throw C("dndev-theme",`cannot read ${s} (framework font defaults)`,"missing-required-resource");let a=this.pathResolver.getDirname(s);return o.replace(Qa,(i,l)=>n(this.pathResolver.resolvePath(l,a)))};return n(e)}_addEssentialThemes(){ut.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}))}};import{createRequire as ei}from"node:module";var ti=ei(import.meta.url),os="ThemeIcon_",ss;function ni(){return ss??=new Set(Object.keys(ti("lucide-react"))),ss}function as(r,e){let t=ni(),n=new Set;for(let s of r){let o=s.meta?.icon;if(!o)continue;let a=String(o).replace(/['"]/g,"").trim();/^[A-Za-z][A-Za-z0-9]*$/.test(a)&&t.has(a)?n.add(a):e.warn(`\u{1F3A8} Theme "${s.name}": --theme-icon '${a}' is not a lucide-react icon name (theme toggle shows the Palette icon)`)}return[...n].sort()}function is(r){return r.length===0?"":`import { ${r.map(t=>`${t} as ${os}${t}`).join(", ")} } from 'lucide-react';
|
|
1172
|
+
`}function ls(r){return`{ ${r.map(t=>`${JSON.stringify(t)}: ${os}${t}`).join(", ")} }`}var Wt=class extends H{constructor(e={}){super(st,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new Ce(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],n=t.filter(o=>!o.essential).length,s=t.length;if(s===0)throw Sn("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: ${s} discovered${n>0?` (${n} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}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(){}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:n}=e,s=as(t,this.logger);return`// Auto-generated DnDev config by @donotdev/config
|
|
1135
1173
|
// Generated at: ${new Date().toISOString()}
|
|
1136
1174
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
1137
|
-
${
|
|
1175
|
+
${is(s)}
|
|
1138
1176
|
const themeConfig = {
|
|
1139
1177
|
discovered: ${JSON.stringify(t,null,2)},
|
|
1140
1178
|
// Theme icons (--theme-icon), imported by name: server-rendered without the lucide namespace
|
|
1141
|
-
icons: ${
|
|
1142
|
-
variables: ${JSON.stringify(
|
|
1179
|
+
icons: ${ls(s)},
|
|
1180
|
+
variables: ${JSON.stringify(n,null,2)},
|
|
1143
1181
|
utilities: {
|
|
1144
|
-
framework: ${JSON.stringify(
|
|
1145
|
-
consumer: ${JSON.stringify(
|
|
1146
|
-
all: ${JSON.stringify(
|
|
1182
|
+
framework: ${JSON.stringify(n.framework,null,2)},
|
|
1183
|
+
consumer: ${JSON.stringify(n.consumer,null,2)},
|
|
1184
|
+
all: ${JSON.stringify(n.all,null,2)},
|
|
1147
1185
|
},
|
|
1148
1186
|
manifest: {
|
|
1149
1187
|
totalThemes: ${t.length},
|
|
1150
|
-
totalVariables: ${
|
|
1151
|
-
frameworkVariables: ${
|
|
1152
|
-
consumerVariables: ${
|
|
1188
|
+
totalVariables: ${n.all.length},
|
|
1189
|
+
frameworkVariables: ${n.framework.length},
|
|
1190
|
+
consumerVariables: ${n.consumer.length},
|
|
1153
1191
|
generatedAt: new Date().toISOString(),
|
|
1154
1192
|
},
|
|
1155
1193
|
};
|
|
@@ -1165,14 +1203,14 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1165
1203
|
timestamp: Date.now(),
|
|
1166
1204
|
};
|
|
1167
1205
|
}
|
|
1168
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1206
|
+
globalThis._DNDEV_CONFIG_.${Y.themes} = themeConfig;
|
|
1169
1207
|
}
|
|
1170
1208
|
|
|
1171
1209
|
// Export for compatibility
|
|
1172
1210
|
export default themeConfig;
|
|
1173
|
-
`}};function
|
|
1174
|
-
`;return
|
|
1175
|
-
\u{1F3D7}\uFE0F DnDev Framework - Building for ${
|
|
1176
|
-
`)),R){let
|
|
1177
|
-
`)}import
|
|
1178
|
-
`)}function
|
|
1211
|
+
`}};function cs(r={}){return new Wt(r)}function us({debug:r,verbose:e,generateManifest:t,routeOptions:n,themeOptions:s,i18nOptions:o,assetOptions:a,seoOptions:i,pwaOptions:l,appUrl:u,isDev:c,logger:p}){let d=n.debug??r,f=s.debug??r,h=o.debug??r,m=a.debug??r,y=i.debug??r,S=l.debug??r,T=n.verbose??e,R=s.verbose??e,v=o.verbose??e,x=a.verbose??e,O=i.verbose??e,B=l.verbose??e,M={debug:r,verbose:e,generateManifest:t},te=n.disabled?null:Vr({...M,...n,debug:d,verbose:T});r&&p.debug(`Route handler created: ${te?"enabled":"disabled"} (debug: ${d})`);let W=cs({...M,...s,debug:f,verbose:R}),g=gr({...M,...o,debug:h,verbose:v}),b=fr({...M,...a,debug:m,verbose:x}),k=ns({...M,...i,debug:y,verbose:O,appUrl:u,isDev:c}),N=mr({...M,...l,debug:S,verbose:B}),_=hr({debug:r,verbose:e});return{routeHandler:te,themeHandler:W,i18nHandler:g,assetHandler:b,seoHandler:k,pwaHandler:N,blogContentHandler:_}}import{existsSync as gs,readFileSync as ms,writeFileSync as ri}from"node:fs";import{join as ys}from"node:path";var si="/(.*)",Jt=Object.freeze(["default-src","script-src","style-src","img-src","font-src","connect-src","media-src","worker-src","manifest-src","frame-src","object-src","base-uri","form-action","frame-ancestors"]),oi=Object.freeze({"default-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"frame-src":["'none'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"]}),ps=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),vs=Object.freeze({"@donotdev/supabase":{"connect-src":["https://*.supabase.co","wss://*.supabase.co"]},"@donotdev/firebase":{"script-src":["https://accounts.google.com","https://apis.google.com"],"connect-src":["https://identitytoolkit.googleapis.com","https://securetoken.googleapis.com","https://www.googleapis.com","https://*.googleapis.com","https://*.firebaseio.com"],"frame-src":["https://accounts.google.com"]}}),ai=Object.freeze([{key:"X-Content-Type-Options",value:"nosniff"},{key:"X-Frame-Options",value:"DENY"},{key:"X-XSS-Protection",value:"1; mode=block"},{key:"Referrer-Policy",value:"strict-origin-when-cross-origin"},{key:"Permissions-Policy",value:"geolocation=(), microphone=(), camera=()"}]),ii=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),li=31536e3,ci=86400,bs=3600,ds=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(r=>`/assets/:path*.${r}`),"next-export":["/_next/static/:path*"],next:[]}),ui=`/${le.fonts}/:path*`,pi=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),di=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${bs}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),fs=Object.freeze(["csp","cache"]);function ot(r,e=!1){return`public, max-age=${r}${e?", immutable":""}`}function qt(r,e){return{source:r,headers:[{key:"Cache-Control",value:e}]}}var hs=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),fi=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function hi(r,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${r}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!hs.includes(e)&&!fi.test(e))throw new Error(`[dndev] appConfig.headers.csp['${r}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${hs.join(" ")} or a hash like 'sha256-<base64>').`)}function gi(r){if(r===void 0)return{csp:{},cache:[]};if(!r||typeof r!="object"||Array.isArray(r))throw new Error("[dndev] appConfig.headers must be an object.");for(let n of Object.keys(r))if(!fs.includes(n))throw new Error(`[dndev] appConfig.headers.${n} is not a header option (allowed: ${fs.join(", ")}).`);let e=r.csp??{};for(let[n,s]of Object.entries(e)){if(!Jt.includes(n))throw new Error(`[dndev] appConfig.headers.csp['${n}'] is not a CSP directive the framework merges (allowed: ${Jt.join(", ")}).`);if(!Array.isArray(s))throw new Error(`[dndev] appConfig.headers.csp['${n}'] must be an array of sources.`);for(let o of s)hi(n,o)}let t=r.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let n of t){if(typeof n?.source!="string"||!n.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(n?.source)}).`);if(!Number.isInteger(n.maxAge)||n.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${n.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(n.maxAge)}).`)}return{csp:e,cache:t}}function mi({csp:r={},providers:e=[],target:t}){if(!(t in ps))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...Jt.map(s=>{let o=[...s==="script-src"?ps[t]:oi[s]??[],...e.flatMap(l=>vs[l]?.[s]??[]),...r[s]??[]],a=[...new Set(o)],i=a.length>1?a.filter(l=>l!=="'none'"):a;return i.length>0?`${s} ${i.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function ws({appConfig:r,target:e,providers:t=[],pwa:n=!1}){if(!(e in ds))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:s,cache:o}=gi(r?.headers),a=[{key:"Content-Security-Policy",value:mi({csp:s,providers:t,target:e})},...r?.seo===!1?[ii]:[],...ai].map(i=>({...i}));return[{source:si,headers:a},...[...ds[e],ui].map(i=>qt(i,ot(li,!0))),...pi.map(i=>qt(`/:path*.${i}`,ot(ci))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:ot(bs)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...n?di.map(i=>({source:i.source,headers:i.headers.map(l=>({...l}))})):[],...o.map(i=>qt(i.source,ot(i.maxAge,i.immutable===!0)))]}function Ss(r){let e=ys(r,"package.json");if(!gs(e))return[];let t=JSON.parse(ms(e,"utf8")),n={...t.dependencies,...t.devDependencies};return Object.keys(vs).filter(s=>!!n[s])}function Es(r){let e=ys(r,"vercel.json");if(!gs(e))return null;try{return{path:e,config:JSON.parse(ms(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function Rs({appRoot:r,rules:e,ci:t,logger:n}){let s=Es(r);if(!s)return"absent";if(JSON.stringify(s.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${s.path}: "headers" differ from the framework header policy (appConfig.headers, appConfig.seo). The host reads the committed file, so this deploy would serve stale headers. Run the app locally (dev or build) to regenerate vercel.json, then commit it.`);let o=`${JSON.stringify({...s.config,headers:e},null,2)}
|
|
1212
|
+
`;return ri(s.path,o),n?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function $s(r){let e=Es(r);if(e&&"headers"in e.config)throw new Error(`[dndev] ${e.path} has "headers": Next serves the framework header policy from next.config headers(). Remove the "headers" key; declare app deltas (CSP sources, cache overrides) in appConfig.headers.`)}var yi=new Set(["@donotdev/functions"]);function xs(){try{let r=D.getInstance(),e=r.resolveAppPath("package.json"),t=r.readSync(e,{format:"json"});if(!t)return[];let n={...t.dependencies,...t.devDependencies};return Object.keys(n).filter(s=>s.startsWith("@donotdev/")).filter(s=>!Le.buildTimePackages.includes(s)).filter(s=>!yi.has(s)).sort()}catch{return[]}}var Vt=new Map;function vi(r={}){let{port:e,...t}=r;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let re=process.env.CI==="true";process.env.DNDEV_BUILD_ID=re?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let n=process.env.DNDEV_BUILD_ID;if(n&&Vt.has(n))return Vt.get(n).configFn;let{appConfig:s,...o}=t;if(!s)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let a=s?.features?{debug:s.features.debug}:void 0,i=s?.seo===!1?{disabled:!0}:s?.seo&&typeof s.seo!="boolean"?{...s.seo,siteName:s.seo.siteName||s.app?.name,siteDescription:s.app?.description}:s?.app?.name?{siteName:s.app.name,siteDescription:s.app.description}:void 0,l=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:u,seo:c,...p}=o,d={...a?{features:a}:{},...i?{seo:i}:{},...p},f=sr(d),h=or(f);if(!h)throw new Error("normalizeOptions returned undefined");let{generateManifest:m,debug:y,verbose:S,mode:T,isDev:R,routeOptions:v,themeOptions:x,i18nOptions:O,assetOptions:B,pwaOptions:M,seoOptions:te,nextConfigOptions:W,reactCompiler:g}=h,b=ae("next-config",y,S),{appRoot:k,appRootSet:N}=ln({logger:b,debug:y}),_=v?.routingMode||"app",F=N&&Pt(k);if(F||(b.info(`
|
|
1213
|
+
\u{1F3D7}\uFE0F DnDev Framework - Building for ${T}${n?` [build:${n}]`:""}`),b.info(` Platform: Next.js | Routing: ${_}
|
|
1214
|
+
`)),R){let re=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${re}`,y&&(b.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&b.debug(`Port configured: ${re} (set PORT env var)`))}else!process.env.NEXT_PUBLIC_APP_URL&&!Qe()&&(process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${process.env.PORT||3e3}`);let A=W.trailingSlash===!0,G=us({debug:y,verbose:S,generateManifest:m,routeOptions:{...v,ssr:s?.ssr!==!1,auth:s?.auth,revalidate:s?.revalidate,prerenderRecords:s?.prerenderRecords,trailingSlash:A,siteName:s?.seo?.siteName||s?.app?.name,defaultImage:s?.seo?.defaultImage,defaultNamespace:s?.seo?.defaultNamespace},themeOptions:x,i18nOptions:O,assetOptions:B,seoOptions:{...te,revalidate:s?.revalidate,trailingSlash:A},pwaOptions:{...M,app:l},isDev:R,logger:b}),j=async function(){let w=D.getInstance(),E=N?xs():[];y&&E.length>0&&b.debug(`Discovered ${E.length} packages: ${E.join(", ")}`);let{missing:P}=Je(w.getAppRoot());y&&P.length>0&&b.debug(`Missing optional deps (will alias to empty): ${P.join(", ")}`),N&&(_==="app"&&gn({pathResolver:w,logger:b,isCI:!!(process.env.CI||process.env.VERCEL)}),await tr(G,b,{appFonts:s?.fonts}));let I=W,{rewrites:V,redirects:ge,headers:de,...me}=I,Ie=yn({originalRewrites:V,handlers:[G.routeHandler,G.themeHandler,G.i18nHandler,G.assetHandler,G.pwaHandler],logger:b}),it=vn({originalRedirects:ge,seoRedirects:te?.redirects||[],logger:b}),ie=me.output==="export",Yt=N?ws({appConfig:s,target:ie?"next-export":"next",providers:Ss(w.getAppRoot()),pwa:M?.enabled===!0}):[];N&&ie?Rs({appRoot:w.getAppRoot(),rules:Yt,ci:!!(process.env.CI||process.env.VERCEL),logger:b}):N&&$s(w.getAppRoot());let Ds=ie?null:bn({policyRules:R?[]:Yt,originalHeaders:de}),Ts={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Os=wn({restNextConfig:me,discoveredPackages:E,reactCompiler:g,routingMode:_,rewritesConfig:Ie,redirectsConfig:it,headersConfig:Ds,missingOptionalDeps:P,pathResolver:w,env:Ts,logger:b});if(b.debug("Next.js config generated"),N&&!F){let Fs=l?.name||"app";b.info(`Name: ${Fs}`),b.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),b.info(`App root (final): ${w.getAppRoot()}`)}return Os};return n&&Vt.set(n,{configFn:j}),j}var Ps=vi;import{readFileSync as bi,existsSync as wi}from"node:fs";import{join as Si}from"node:path";var Oe=null,Kt=0,Ei=6e4;function Ri(){let r=Date.now();if(Oe&&r-Kt<Ei)return Oe;try{let e=Si(process.cwd(),"public","metadata-manifest.json");if(!wi(e))return null;let t=bi(e,"utf-8");return Oe=JSON.parse(t),Kt=r,Oe}catch{return null}}function $i(r,e,t){let n=Ri(),s={title:t?.siteName||"Site"};if(!n)return s;let o=r.startsWith("/")?r:`/${r}`,a=n[o];if(!a)return s;let i=e||a.defaultLocale||"en",l=a.locales[i]||a.locales[a.defaultLocale]||Object.values(a.locales)[0];if(!l)return s;let u=process.env.NEXT_PUBLIC_APP_URL,c={title:l.title,...u&&{metadataBase:new URL(u)}};return l.description&&(c.description=l.description),l.keywords&&(c.keywords=l.keywords),c.openGraph={title:l.title,type:l.type||"website",...l.description&&{description:l.description},...l.image&&{images:[l.image]},...t?.siteName&&{siteName:t.siteName}},c.twitter={card:"summary_large_image",title:l.title,...l.description&&{description:l.description},...l.image&&{images:[l.image]}},l.robots&&(c.robots={index:!1,...l.robots==="noindex, nofollow"&&{follow:!1}}),c}function xi(){Oe=null,Kt=0}function at(r){return String(r).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function Pi(r,{baseUrl:e,routing:t,trailingSlash:n,crud:s,readSchemas:o,languageUrls:a,hiddenStatuses:i}){let l=[],u=(c,p)=>{let d=a(c,e,t,n),f=t.languages.length>1?{alternates:{languages:d}}:{};for(let h of t.languages)l.push({url:d[h],...p,...f})};for(let{route:c,path:p,record:d}of await Ye(r,s,i,o)){if(!d){u(p,{changeFrequency:c.changeFrequency??"weekly",priority:c.priority??(p==="/"?1:.8),...c.lastModified&&{lastModified:c.lastModified}});continue}let f=d.updatedAt instanceof Date?d.updatedAt.toISOString():d.updatedAt;u(p,{changeFrequency:c.changeFrequency??"weekly",priority:c.priority??.7,...typeof f=="string"&&{lastModified:f}})}return l}function Ci(r){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${r.some(n=>n.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let n of r){t.push(" <url>",` <loc>${at(n.url)}</loc>`);for(let[s,o]of Object.entries(n.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${at(s)}" href="${at(o)}" />`);n.lastModified&&t.push(` <lastmod>${at(n.lastModified)}</lastmod>`),n.changeFrequency&&t.push(` <changefreq>${n.changeFrequency}</changefreq>`),n.priority!==void 0&&t.push(` <priority>${n.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
|
|
1215
|
+
`)}import Ni from"i18next";function Cs(r,e){return r.startsWith("/")?`${e}${r}`:r}function Xt(r){return typeof r=="object"&&r!==null&&"collection"in r&&"fields"in r}function As(r,e,t){for(let n of Object.values(r))if(Xt(n)&&n.collection===e)return n;throw new Error(`[dndev] Entity page "${t}": no entity definition for collection "${e}". Export it from the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`)}function Ai(r,e,t){let n=Object.create(null);for(let s of e)!s.collection||Object.hasOwn(n,s.collection)||(n[s.collection]=t(As(r,s.collection,s.path)).get);return Object.freeze(n)}function Ns(r,e){let{route:t,value:n,language:s,baseUrl:o,siteName:a,type:i}=e,l=As(e.entities,t.collection,t.path),u=e.deriveEntitySeo(l,r,{t:e.translate([l.namespace,"crud"]),locale:s}),c=q(t.path)[0],p=t.path.replace(`:${c}`,encodeURIComponent(n)),d=S=>e.languageUrl(S,s,o,e.routing,e.trailingSlash),f=d(p),h=u.title?`${u.title} | ${a}`:a,m=Cs(u.image||e.defaultImage,o),y=i==="product"?e.buildProductJsonLd({...u,images:[...new Set(u.images.map(S=>Cs(S,o)))]},f):null;return{url:f,title:h,...u.description&&{description:u.description},image:m,type:i,jsonLd:y,breadcrumb:u.title?e.buildBreadcrumbJsonLd(p,a,d,u.title):null}}function Fe(r){return r.replace(/\s+/g," ").trim()}function _s(r){let e=[`# ${Fe(r.name)}`,""];r.summary&&e.push(`> ${Fe(r.summary)}`,"");for(let t of r.sections)if(t.links.length!==0){e.push(`## ${Fe(t.heading)}`,"");for(let n of t.links){let s=`- [${Fe(n.title)}](${n.url})`;e.push(n.description?`${s}: ${Fe(n.description)}`:s)}e.push("")}return e.join(`
|
|
1216
|
+
`)}function _i(r){let e=new Map;for(let t of Object.values(r))Xt(t)&&e.set(t.collection,t);return e}function ki(r,e){let t=Ni.createInstance();return t.init({lng:r,resources:{[r]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),n=>t.getFixedT(r,[n,"crud"])}async function Di(r){let{crud:e,readSchemas:t,deriveEntitySeo:n,hiddenStatuses:s,formatTrailingSlash:o,trailingSlash:a}=r,i=_i(r.entities),l,u=new Map,c=p=>{let d=u.get(p);return d||(d={heading:p,links:[]},u.set(p,d)),d};c(r.pagesHeading);for(let{route:p,path:d,record:f}of await Ye(r.routes,e,s,t)){let h=`${r.baseUrl}${o(d,a)}`;if(!f){if(!p.title)throw new Error(`[dndev] llms.txt: source route "${p.path}" has no title (getLlmsTxtSource gives every static page one).`);c(p.section??r.pagesHeading).links.push({title:p.title,url:h,...p.description&&{description:p.description}});continue}let m=i.get(p.collection);if(!m)throw new Error(`[dndev] llms.txt: no entity definition for collection "${p.collection}" (route "${p.path}"). Export it from the app's \`entities\` package.`);let y=p.section??(m.namespace?r.entityHeadings[m.namespace]:void 0);if(!y)throw new Error(`[dndev] llms.txt: no heading for route "${p.path}". Add "namePlural" to the ${m.namespace??`entity-${m.name.toLowerCase()}`} translations.`);if(!l){if(!r.language||!r.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");l=ki(r.language,r.translations)}let S=n(m,f,{t:l(m.namespace),locale:r.language});c(y).links.push({title:S.title||r.name,url:h,...S.description&&{description:S.description}})}return _s({name:r.name,...r.summary&&{summary:r.summary},sections:[...u.values()]})}var ks=new Set(["website","article"]);async function Ti(r,e,t,n,s){let o=q(r.path),a=o[0];if(o.length!==1||!r.collection||!a)throw new Error(`[dndev] Entity page "${r.path}": only single-param routes of an entity collection read a record.`);if(!t)throw new Error(`[dndev] Entity page "${r.path}" reads a "${r.collection}" record but no server CRUD reader was given.`);let i=Mt(r,s),l;try{l=await t.query(r.collection,{where:[{field:a,operator:"==",value:e},{field:"status",operator:"not-in",value:[...n]}],limit:1},i)}catch(u){let c=u?.details?.originalMessage??u?.message??String(u);throw new Error(`[dndev] Entity page "${r.path}" could not read its public "${r.collection}" record (signed-out visitor: RLS / Security Rules must allow it): ${c}`,{cause:u})}return l.items[0]??null}function Oi(r,e){let{title:t,description:n,image:s,type:o,jsonLd:a,breadcrumb:i}=Ns(r,e);return{metadata:{title:{absolute:t},...n&&{description:n},openGraph:{title:{absolute:t},...n&&{description:n},...ks.has(o)&&{type:o},images:[s]},twitter:{card:"summary_large_image",title:{absolute:t},...n&&{description:n},images:[s]}},ogType:ks.has(o)?null:o,jsonLd:a,breadcrumb:i}}function Fi(r){return JSON.stringify(r).replace(/</g,"\\u003c")}export{_r as REVALIDATE_ROUTE_PATH,Te as REVALIDATE_SECRET_ENV,Za as appBaseUrl,Di as buildLlmsTxt,Pi as buildSitemap,xi as clearMetadataCache,Ps as default,Ps as defineNextConfig,Ks as definePostCSSConfig,Oi as entityPageSeo,Ai as entityReadSchemas,Ci as formatSitemapXml,$i as getMetadataForPath,Ca as handleRevalidationWebhook,Fi as jsonLdScript,wa as listStaticParams,Ti as readEntityPageRecord,kr as revalidationPaths};
|