@donotdev/core 0.3.2 → 0.3.4
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 +25 -2
- package/i18n/locales/lazy/auth_da.json +28 -2
- package/i18n/locales/lazy/auth_de.json +25 -2
- package/i18n/locales/lazy/auth_en.json +25 -2
- package/i18n/locales/lazy/auth_es.json +25 -2
- package/i18n/locales/lazy/auth_fr.json +25 -2
- package/i18n/locales/lazy/auth_it.json +25 -2
- package/i18n/locales/lazy/auth_ja.json +25 -2
- package/i18n/locales/lazy/auth_ko.json +25 -2
- package/i18n/locales/lazy/auth_nl.json +28 -2
- package/i18n/locales/lazy/auth_pl.json +25 -2
- package/i18n/locales/lazy/auth_pt.json +25 -2
- package/i18n/locales/lazy/auth_zh.json +25 -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 +455 -49
- package/index.js +5 -5
- package/next/index.d.ts +80 -10
- package/next/index.js +259 -216
- package/next/runtime.js +2 -2
- package/package.json +2 -2
- package/server.d.ts +323 -24
- package/shared.js +2 -2
- package/symbol-index.json +1 -1
- package/vite/index.d.ts +65 -1
- package/vite/index.js +113 -107
package/vite/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var _o=Object.defineProperty;var xt=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var Ao=(n,e)=>{for(var t in e)_o(n,t,{get:e[t],enumerable:!0})};function ir(n,e=null){let t=ce[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(r=>`${e}/${r}`)}:t}function ot(n){return rr[n]||rr.base}var Rt,U,ee,me,He,nt,Pt,Je,Te,ce,we,nr,$t,Ct,or,_t,sr,At,rr,J=xt(()=>{"use strict";Rt={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},U={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},ee={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},me={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"}},He="/og-image.png",nt="_shell.html",Pt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},Je={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},Te={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"},ce={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:[`${Te.SOURCE_EAGER}/*_*.json`],lazy:[`${Te.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",He.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/**"]},we={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]},nr=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"],$t=["@donotdev/core/functions","@donotdev/core/server"],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)/}},or={Inter:"inter","Space Grotesk":"space-grotesk","Playfair Display":"playfair-display","Press Start 2P":"press-start-2p",Roboto:"roboto"},_t={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]},sr={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:[]},At=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],rr={base:{absolute:!0,onlyFiles:!0,ignore:ce.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...ce.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...ce.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:ce.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:ce.globalIgnore}}});import*as I from"node:fs";import"node:fs";import{createRequire as Fo}from"node:module";import{resolve as st,join as Re,dirname as _e,relative as ar,normalize as Mo,sep as lr,extname as Lo}from"node:path";import jo from"fast-glob";function Ie(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="EEXIST"}function cr(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Oe,Y,ur,D,q=xt(()=>{"use strict";J();Oe={getGlobOptionsFor:ot||void 0,SCAN_PATTERNS:ce||void 0,getPatternsFor:ir||void 0,I18N_PATHS:Te||void 0},Y={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};ur={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 n{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._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,n._instance=this}normalizePath(e){if(!e)return"";try{return Mo(e).split(lr).join("/")}catch{return String(e).split(lr).join("/")}}getRelativePath(e){let t=this.getAppRoot(),r=ar(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(_e(e)):""}resolvePackage(e,t=null){try{let r=t||this.getAppRoot(),s=Fo(Re(r,"package.json")).resolve(e);return this.normalizePath(s)}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 i=e.replace("@donotdev/",""),a=this.resolveRepoPath(`packages/${i}`);if(this.pathExists(a))return a;if(["auth","billing","crud","oauth"].includes(i)){let l=this.resolveRepoPath(`packages/features/${i}`);if(this.pathExists(l))return l}if(i==="firebase"){let l=this.resolveRepoPath(`packages/providers/${i}`);if(this.pathExists(l))return l}}let o=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(o))return o;let s=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(s)?s:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),r=st(t,e);return this.normalizePath(r)}resolveRepoPath(e){let t=this.getRepoRoot(),r=this.normalizePath(e),o=st(t,r);return this.normalizePath(o)}resolvePath(e,t){let r=this.normalizePath(t),o=this.normalizePath(e),s=st(r,o);return this.normalizePath(s)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=I.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:Lo(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:r="auto",encoding:o="utf8"}=t,s=this._detectFormat(e,r);try{if(s==="buffer")return await I.promises.readFile(e);let i=await I.promises.readFile(e,o),a=this.stripBom(i);return s==="json"?JSON.parse(a):a}catch(i){return this.options.debug&&Y.warn(`Failed to read file: ${e}`,i),null}}readSync(e,t={}){let{format:r="auto",encoding:o="utf8"}=t,s=this._detectFormat(e,r);try{if(s==="buffer")return I.readFileSync(e);let i=I.readFileSync(e,o),a=this.stripBom(i);return s==="json"?JSON.parse(a):a}catch(i){return this.options.debug&&Y.warn(`Failed to read file: ${e}`,i),null}}async write(e,t,r={}){let{format:o="auto",overwrite:s=!1,dryRun:i=!1,verbose:a=!1}=r,l=this.normalizePath(e),c=this.normalizePath(_e(l)),u=this.pathExists(l);if(u&&!s)return a&&Y.info(`Skipping existing file: ${l}`),!1;if(i)return Y.info(`[DRY RUN] Would write file: ${l}`),!0;try{await I.promises.mkdir(c,{recursive:!0})}catch(f){if(!Ie(f))throw f}let p=this._detectFormat(e,o),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)?
|
|
4
|
-
`)[0];e.push(s)}catch{}let r=[process.env.NVM_DIR,n.resolvePath(".nvm",t)].filter(Boolean);for(let o of r)try{let s=n.resolvePath("versions/node",o),
|
|
5
|
-
`);if(r<0||r>=
|
|
6
|
-
`),{overwrite:!0}),b(e,{ok:!0,line:
|
|
7
|
-
`))
|
|
8
|
-
`;
|
|
9
|
-
`;
|
|
10
|
-
`)),{outDir:"dist",sourcemap:s||i,cacheDir:"node_modules/.vite",target:"baseline-widely-available",minify:i?!1:"esbuild",reportCompressedSize:!1,chunkSizeWarningLimit:2048,assetsInlineLimit:0,esbuild:{format:"esm",drop:i?[]:["console","debugger"],legalComments:"none"},cssMinify:i?!1:"esbuild",cssCodeSplit:!0,rollupOptions:{external:Go(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...u.manualChunks&&{manualChunks:u.manualChunks},compact:!0},onwarn(d,f){d.code!=="MODULE_LEVEL_DIRECTIVE"&&f(d)},plugins:[...i?[]:[Bo({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...a?[(()=>{let d=D.getInstance(),f=d.getAppRoot(),g="dist",w=d.resolveAppPath(`${g}/stats.html`),m=()=>{try{let R=d.resolveAppPath(g);d.pathExists(R)||d.mkdir(R)}catch{}},h=Uo({filename:w,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:s||i,projectRoot:f});if(h.buildStart){let R=h.buildStart.bind(h);h.buildStart=function(...E){m();let S=R.apply(this,E);return S&&typeof S.then=="function"?S.catch(C=>{}):S}}else h.buildStart=function(){m()};let P=["generateBundle","writeBundle","closeBundle"];for(let R of P)if(h[R]){let E=h[R];h[R]=function(...S){try{m();let C=E.apply(this,S);return C&&typeof C.then=="function"?C.catch(k=>{let y=k?.message||k?.toString()||String(k)||"Unknown error";c.warn(`Bundle visualizer warning in ${R}: ${y}`),R==="closeBundle"&&c.warn(`You can manually open ${w} to view the bundle analysis`)}):C}catch(C){let k=C?.message||C?.toString()||String(C)||"Unknown error";c.warn(`Bundle visualizer warning in ${R}: ${k}`),R==="closeBundle"&&c.warn(` You can manually open ${w} to view the bundle analysis`)}}}return h})()]:[]]}}}function Go(n){return n?["firebase-admin","gcp-metadata","google-logging-utils","@google-cloud/firestore",/\.node$/,"esbuild",/@esbuild\/.*/]:["gcp-metadata","google-logging-utils","payload","file-type","firebase-admin","firebase-admin/app","firebase-admin/auth","firebase-admin/firestore","firebase-admin/functions","firebase-admin/credential","@google-cloud/firestore","google-auth-library","google-gax","googleapis-common"]}function Wo(){let n=!1,e=D.getInstance();if((e.pathExists("/.dockerenv")||e.pathExists("/run/.containerenv"))&&(n=!0),!n&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(n=!0),!n&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(n=!0),!n&&process.platform==="linux"&&e.pathExists("/proc/self/cgroup"))try{let o=e.readSync("/proc/self/cgroup");o&&(o.includes("docker")||o.includes("containerd"))&&(n=!0)}catch{}let t=!1;if((process.env.WSL_DISTRO_NAME||process.env.WSLENV)&&(t=!0),!t&&process.platform==="linux"&&e.pathExists("/proc/version"))try{let o=(e.readSync("/proc/version")||"").toLowerCase();t=o.includes("microsoft")||o.includes("wsl")}catch{}if(!t&&process.platform==="linux"&&e.pathExists("/proc/sys/kernel/osrelease"))try{let o=(e.readSync("/proc/sys/kernel/osrelease")||"").toLowerCase()||"";(o.includes("microsoft")||o.includes("wsl"))&&(t=!0)}catch{}if(!t&&process.platform==="win32"){let o=process.cwd();o&&(o.includes("\\wsl$")||o.includes("\\wsl.localhost"))&&(t=!0)}let r=typeof process.versions?.bun=="string";return{isDocker:n,isWSL2:t,isBun:r}}function Vo(n,e){if(n!==void 0)return n;let{isDocker:t,isWSL2:r,isBun:o}=Wo();if(t||r||o){let s=t?"Docker":r?"WSL2":"Bun";return e.info(`Detected ${s} environment - enabling polling mode for file watching`),!0}}function dr(n,e={},t){let r=D.getInstance(),o=r.getRepoRoot(),{watch:s,hmr:i,host:a,...l}=e||{},c=i||{},u=a===!0?"localhost":a||"localhost",p={...c.port&&{port:c.port},...c.clientPort&&{clientPort:c.clientPort},host:c.host??u,...c.protocol&&{protocol:c.protocol},overlay:c.overlay??!0,timeout:c.timeout??5e3},d=a!==void 0?a:!0,f=l.https===!0;return{port:n,host:d,open:e.open!==void 0?e.open:!0,https:f,fs:{allow:[o,r.resolveRepoPath("packages"),r.resolveRepoPath("node_modules")],strict:!1},watch:(()=>{let g=Vo(e?.watch?.usePolling,t);return{usePolling:g,interval:e?.watch?.interval??2e3,...g&&{awaitWriteFinish:{stabilityThreshold:300,pollInterval:100}},...e?.watch||{}}})(),hmr:{...p,...c},headers:{"Cross-Origin-Opener-Policy":"same-origin-allow-popups","Cross-Origin-Embedder-Policy":"unsafe-none"},middlewareMode:!1,...l}}function fr(n={}){let e=n.https===!0;return{...n,https:e}}J();var gr={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 ue={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function Pe(n,e,t,r={}){let{protectedKeys:o=[],onConflict:s}=r;if(e==null)return n;switch(t){case ue.CONCATENATE_DEDUPE:{if(!Array.isArray(n)||!Array.isArray(e))return e;let i=[...n,...e];return[...new Set(i)]}case ue.SHALLOW_MERGE:return typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e)?e:{...n,...e};case ue.DEEP_MERGE:{if(typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e))return e;let i={...n};for(let a in e){if(o.includes(a)){s&&s(a,n[a],e[a]);continue}typeof i[a]=="object"&&typeof e[a]=="object"&&i[a]!==null&&e[a]!==null&&!Array.isArray(i[a])&&!Array.isArray(e[a])?i[a]=Pe(i[a],e[a],ue.DEEP_MERGE,{protectedKeys:o,onConflict:s}):i[a]=e[a]}return i}case ue.REPLACE:default:return e}}function mr(n,e,t=[],r){let o=[...n,...e||[]],s=[...new Set(o)];return[...new Set([...s,...t])]}var Fe={...gr,reactCompiler:!1,base:"/",mode:process.env.NODE_ENV==="production"?"production":"development",logLevel:process.env.NODE_ENV==="production"?"warn":"info",server:{port:3e3,strictPort:!0,host:!0,open:!0,cors:!0,https:!1,hmr:{overlay:!0,timeout:5e3,usePolling:void 0,interval:2e3},watch:{usePolling:void 0,interval:2e3}},build:{sourcemap:!0,target:"es2020",minify:"esbuild",cssMinify:"esbuild",analyze:!1},preview:{port:4173,strictPort:!0,host:!0,open:!1,cors:!0,https:!1},routes:{hmr:!0},themes:{},i18n:{},assets:{},pwa:{enabled:!1},prerender:{routes:"auto"},chunking:{reactCore:[]},pluginFactory:{verbose:!0,disableHmr:!1,hmrSmartDetection:!0,hmrDebounceMs:500,hmrCacheTimeout:3e4},resolve:{alias:{"@":"/src"},preserveSymlinks:!1},define:{__DEV__:JSON.stringify(process.env.NODE_ENV==="development"),__PROD__:JSON.stringify(process.env.NODE_ENV==="production")},optimizeDeps:{include:[...we.mandatoryIncludes],exclude:[...we.buildTools,...Object.values(U)],esbuildOptions:{format:"esm",target:"es2020",platform:"browser",define:{"process.env.NODE_ENV":JSON.stringify(process.env.NODE_ENV||"development")},external:["next","next/*"]}},plugins:[],css:{},envDir:void 0};function hr(n={},e={}){let{onConflict:t}=e,r={...Fe},o=[],s=(i,a,l,c)=>{o.push({key:i,frameworkValue:a,userValue:l,reason:c}),t&&t(i,a,l,c)};if("prerender"in n){let i=n.prerender;i===!1?n.prerender={routes:[]}:i===!0?n.prerender={routes:"auto"}:Array.isArray(i)&&(n.prerender={routes:i})}return Object.keys(n).forEach(i=>{let a=n[i],l=r[i];if(i==="optimizeDeps"&&typeof a=="object"&&a!==null){let c=l?.include||[],u=l?.exclude||[],p=a.include||[],d=a.exclude||[],f=c.filter(P=>!P.startsWith("@donotdev/")),g=d.filter(P=>f.includes(P));if(g.length>0)for(let P of g)s("optimizeDeps.exclude",P,"excluded",`Framework requires ${P} to be included. It will be included despite your exclusion.`);let w=mr(c,p,f),m=Pe(u,d,ue.CONCATENATE_DEDUPE),h=Pe(l?.esbuildOptions||{},a.esbuildOptions||{},ue.DEEP_MERGE,{protectedKeys:["external"],onConflict:P=>s(`optimizeDeps.esbuildOptions.${P}`,l?.esbuildOptions?.[P],a.esbuildOptions?.[P],`Framework requires ${P} to remain as configured.`)});r[i]={...l,include:w,exclude:m,esbuildOptions:h,...Object.fromEntries(Object.entries(a).filter(([P])=>!["include","exclude","esbuildOptions"].includes(P)))};return}if(i==="css"&&typeof a=="object"&&a!==null){r[i]=Pe(l||{},a,ue.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>s("css.postcss","framework PostCSS config",a.postcss,"Framework PostCSS config is required and cannot be overridden. Your postcss config is ignored.")});return}if(i==="define"&&typeof a=="object"&&a!==null){r[i]=Pe(l||{},a,ue.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:c=>s(`define.${c}`,l?.[c],a[c],`Framework requires ${c} to remain as configured.`)});return}if(Array.isArray(a)){Array.isArray(l)?r[i]=Pe(l,a,ue.CONCATENATE_DEDUPE):r[i]=a;return}if(typeof a=="object"&&a!==null&&typeof l=="object"&&l!==null&&!Array.isArray(l)){r[i]=Pe(l,a,ue.SHALLOW_MERGE);return}r[i]=a}),r}function vr(n){let{server:e={},preview:t={},mode:r,build:o={},resolve:s={},routes:i={},themes:a={},i18n:l={},assets:c={},features:u={},seo:p={},prerender:d={},pwa:f={},serverShim:g={},chunking:w={},discovery:m={},pluginFactory:h={},debug:P,verbose:R,base:E,define:S={},optimizeDeps:C={},plugins:k=[],css:y={},envDir:T,reactCompiler:$=!1,...v}=n,G=r==="development",A=P||G,L=r==="production"&&(o.analyze??Fe.build.analyze);return{mode:r,debug:P,verbose:R,isDev:G,isDebug:A,shouldAnalyze:L,serverOptions:e,previewOptions:t,buildOverrides:o,resolveOptions:s,routeOptions:i,themeOptions:a,i18nOptions:l,assetOptions:c,featureOptions:u,seoOptions:p,prerenderOptions:d,pwaOptions:f,serverShimOptions:g,chunkingOptions:w,discoveryOptions:m,pluginFactoryOptions:h,base:E,defineOptions:S,optimizeDepsOptions:C,pluginsOptions:k,cssOptions:y,envDir:T,reactCompiler:$,restOptions:v}}q();import Ho from"autoprefixer";import Jo from"postcss-import";import qo from"postcss-nesting";function yr({postcssImport:n,postcssNesting:e,autoprefixer:t,resolve:r}){return{plugins:[r?n({resolve:r}):n,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function br(n={}){if(n.postcss)return n.postcss;let e=D.getInstance();return yr({postcssImport:Jo,postcssNesting:qo,autoprefixer:Ho,resolve:(r,o)=>{let s=e.resolvePackage(r,o);if(s)return s;if(r.startsWith("@donotdev/")){let i=r.split("/")[0]+"/"+r.split("/")[1],a=r.split("/").slice(2).join("/"),l=e.resolveFrameworkPackage(i,o);if(l&&a){let c=e.resolvePath(a,l);if(e.pathExists(c))return c}}return e.resolvePath(r,o)}})}import Ui from"@vitejs/plugin-basic-ssl";import Gi from"@vitejs/plugin-react";import Wi from"vite-tsconfig-paths";var ne=class{static generateVirtualModule(e,t,r=!1,o=void 0,s=void 0){return t.isEmpty(e)?t.generateEmpty(e,r,o,s):t.generateModule(e,r,s)}static generateInspection(e,t,r,o){return t.generateInspection.length>=3?t.generateInspection(e,r,o):t.generateInspection(e,r)}static wrapVirtualModule(e,t){return`// Virtual module: ${e}
|
|
1
|
+
var hs=Object.defineProperty;var kt=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var vs=(n,e)=>{for(var t in e)hs(n,t,{get:e[t],enumerable:!0})};function Pn(n,e=null){let t=pe[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(r=>`${e}/${r}`)}:t}function at(n){return En[n]||En.base}var Tt,V,re,ve,Me,st,Ot,$e,Fe,pe,Pe,Sn,It,Ft,xn,$n,Mt,En,q=kt(()=>{"use strict";Tt={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"},V={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},re={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},ve={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"}},Me="/og-image.png",st="_shell.html",Ot={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"},pe={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",Me.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/**"]},Pe={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"]},Sn=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"],It=["@donotdev/core/functions","@donotdev/core/server"],Ft={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)/}},xn=["-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"],$n={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:[]},Mt=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],En={base:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...pe.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...pe.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:pe.globalIgnore}}});import*as j from"node:fs";import"node:fs";import{createRequire as $s}from"node:module";import{resolve as it,join as Ae,dirname as De,relative as Rn,normalize as Ps,sep as Cn,extname as Rs}from"node:path";import Cs from"fast-glob";function je(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="EEXIST"}function _n(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Le,ee,An,O,Y=kt(()=>{"use strict";q();Le={getGlobOptionsFor:at||void 0,SCAN_PATTERNS:pe||void 0,getPatternsFor:Pn||void 0,I18N_PATHS:Fe||void 0},ee={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};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"},O=class n{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._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,n._instance=this}normalizePath(e){if(!e)return"";try{return Ps(e).split(Cn).join("/")}catch{return String(e).split(Cn).join("/")}}getRelativePath(e){let t=this.getAppRoot(),r=Rn(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(De(e)):""}resolvePackage(e,t=null){try{let r=t||this.getAppRoot(),s=$s(Ae(r,"package.json")).resolve(e);return this.normalizePath(s)}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 c=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(c))return c}if(a==="firebase"){let c=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(c))return c}}let o=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(o))return o;let s=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(s)?s:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),r=it(t,e);return this.normalizePath(r)}resolveRepoPath(e){let t=this.getRepoRoot(),r=this.normalizePath(e),o=it(t,r);return this.normalizePath(o)}resolvePath(e,t){let r=this.normalizePath(t),o=this.normalizePath(e),s=it(r,o);return this.normalizePath(s)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=j.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:Rs(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:r="auto",encoding:o="utf8"}=t,s=this._detectFormat(e,r);try{if(s==="buffer")return await j.promises.readFile(e);let a=await j.promises.readFile(e,o),i=this.stripBom(a);return s==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&ee.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:r="auto",encoding:o="utf8"}=t,s=this._detectFormat(e,r);try{if(s==="buffer")return j.readFileSync(e);let a=j.readFileSync(e,o),i=this.stripBom(a);return s==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&ee.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,r={}){let{format:o="auto",overwrite:s=!1,dryRun:a=!1,verbose:i=!1}=r,c=this.normalizePath(e),l=this.normalizePath(De(c)),u=this.pathExists(c);if(u&&!s)return i&&ee.info(`Skipping existing file: ${c}`),!1;if(a)return ee.info(`[DRY RUN] Would write file: ${c}`),!0;try{await j.promises.mkdir(l,{recursive:!0})}catch(f){if(!je(f))throw f}let p=this._detectFormat(e,o),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`:d=String(t);try{return await _n(async()=>(Buffer.isBuffer(d)?await j.promises.writeFile(c,d):await j.promises.writeFile(c,d,"utf8"),i&&ee.info(`${u?"Updated":"Created"} file: ${c}`),!0),`Failed to write file: ${c}`)}catch{return!1}}writeSync(e,t,r={}){let{format:o="auto",overwrite:s=!1,dryRun:a=!1,verbose:i=!1}=r,c=this.normalizePath(e),l=this.normalizePath(De(c)),u=this.pathExists(c);if(u&&!s)return i&&ee.info(`Skipping existing file: ${c}`),!1;if(a)return ee.info(`[DRY RUN] Would write file: ${c}`),!0;try{j.mkdirSync(l,{recursive:!0})}catch(f){if(!je(f))throw f}let p=this._detectFormat(e,o),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)?j.writeFileSync(c,d):j.writeFileSync(c,d,"utf8"),this._writtenPaths?.add(c),i&&ee.info(`${u?"Updated":"Created"} file: ${c}`),!0}catch(f){throw new Error(`Failed to write file: ${c}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,r={}){let{overwrite:o=!1,dryRun:s=!1,verbose:a=!1}=r,i=this.normalizePath(t),c=this.pathExists(i);if(c&&!o)return a&&ee.info(`Skipping existing file: ${i}`),!1;if(s)return ee.info(`[DRY RUN] Would copy file: ${i}`),!0;let l=this.normalizePath(De(i));try{await j.promises.mkdir(l,{recursive:!0})}catch(u){if(!je(u))throw u}try{return await _n(async()=>(await j.promises.copyFile(e,i),a&&ee.info(`${c?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,r={}){let{overwrite:o=!1,dryRun:s=!1,verbose:a=!1}=r,i=this.normalizePath(t),c=this.pathExists(i);if(c&&!o)return a&&ee.info(`Skipping existing file: ${i}`),!1;if(s)return ee.info(`[DRY RUN] Would copy file: ${i}`),!0;let l=this.normalizePath(De(i));try{j.mkdirSync(l,{recursive:!0})}catch(u){if(!je(u))throw u}try{return j.copyFileSync(e,i),this._writtenPaths?.add(i),a&&ee.info(`${c?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return j.existsSync(e)}catch(r){return t||ee.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 j.existsSync(t)||j.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return j.readdirSync(e,t)}catch(r){return this.options.debug&&ee.warn(`Failed to read directory: ${e}`,r),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return j.statSync(e)}catch(t){return this.options.debug&&ee.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return j.realpathSync(e)}watch(e,t,r){return j.watch(e,t,r)}lstatSync(e){try{return j.lstatSync(e)}catch(t){return this.options.debug&&ee.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await j.promises.mkdir(e,{recursive:!0})}catch(t){if(!je(t))throw t}}ensureDirSync(e){try{j.mkdirSync(e,{recursive:!0})}catch(t){if(!je(t))throw t}}async remove(e){await j.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){j.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return j.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=Ae(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(it(e)),r=this.getAppRoot(),o=Rn(r,t),s=this.normalizePath(o);return!s.startsWith("../")&&!s.startsWith("/")}async findFiles(e,t,r={}){let o=this.normalizePath(Ae(e,t)),s=this.getAppRoot(),a=this.normalizePath(s),i=o.startsWith(a)?o.slice(a.length+1):o,c={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:Le.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...c,...r})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Le.I18N_PATHS;if(!t)return null;let r=e.replace(t.SOURCE_ROOT+"/",""),o=this.resolveFrameworkPackage("@donotdev/core");if(!o)return null;let s=this.normalizePath(Ae(o,t.PUBLISHED_ROOT,r)),a=s.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),s}async _globWithNormalization(e,t){return(await Cs(e,t)).map(o=>{let s=typeof o=="string"?o:o.path;return this.normalizePath(s)}).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 u of r)if(typeof u!="string"||u.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let o=this.getAppRoot(),s=Le.getGlobOptionsFor?Le.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(o),i=e.framework.map(u=>{let p=this.normalizePath(u);return p.startsWith(a)?p.slice(a.length+1):p}),c=e.consumer.map(u=>{let p=this.normalizePath(u);return p.startsWith(a)?p.slice(a.length+1):p}),l={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o};try{let u=i.length>0?await this._globWithNormalization(i,l):[],p=await this._globWithNormalization(c,l);return{frameworkFiles:u,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!Le.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 o=Le.getPatternsFor(e),s=this.isMonorepo();if(e==="i18n"){let c=o,l={eager:c.eager.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),lazy:c.lazy.map(u=>u.startsWith("!")?"!"+this.resolveAppPath(u.slice(1)):this.resolveAppPath(u)),framework:{eager:s?(c.framework?.eager||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((c.framework?.eager||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean)),lazy:s?(c.framework?.lazy||[]).map(u=>this.resolveRepoPath(u)).filter(Boolean):await Promise.all((c.framework?.lazy||[]).map(u=>this._resolveFrameworkI18nPattern(u))).then(u=>u.filter(Boolean))},all:[]};return l.all=[...l.eager,...l.lazy,...l.framework.eager,...l.framework.lazy],l}let a=o,i={framework:s?(a.framework||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):[],consumer:(a.consumer||[]).map(c=>this.resolveAppPath(c)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),r=0,o=this.options.maxLevels;for(;r<o;){let s=this.normalizePath(Ae(t,An.TOOLING)),a=this.normalizePath(Ae(t,An.CORE));if(this.pathExists(s)&&this.pathExists(a))return t;let i=Ae(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let c=this.normalizePath(Ae(t,"package.json"));if(this.pathExists(c)&&this.normalizePath(De(t))===t)return t;let l=this.normalizePath(De(t));if(l===t)break;t=l,r++}return this.normalizePath(e)}}});var ps={};vs(ps,{createDndevPlugin:()=>qc});import{execSync as Se,execFileSync as Je,spawn as wc}from"node:child_process";function oe(){return O.getInstance()}function le(){return oe().getRepoRoot()}function is(){return oe().resolveRepoPath(".dndev")}function b(n,e,t=200){n.writeHead(t,{"Content-Type":"application/json"}),n.end(JSON.stringify(e))}function _e(n,e=Ec){return new Promise((t,r)=>{let o="",s=0;n.on("data",a=>{if(s+=a.length,s>e){n.destroy(),r(new Error("Request body too large"));return}o+=a.toString()}),n.on("end",()=>t(o)),n.on("error",r)})}function Sc(n){let e=n.lastIndexOf(".");return e===-1?"":n.slice(e).toLowerCase()}function xc(){let n=oe(),e=[],t=process.env.HOME||process.env.USERPROFILE||"";try{let o=process.platform==="win32"?"where node":"which node",s=Se(o,{encoding:"utf8"}).trim().split(`
|
|
4
|
+
`)[0];e.push(s)}catch{}let r=[process.env.NVM_DIR,n.resolvePath(".nvm",t)].filter(Boolean);for(let o of r)try{let s=n.resolvePath("versions/node",o),a=n.readdirSync(s).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/bin/node`,s))}catch{}if(process.env.NVM_BIN&&e.push(n.resolvePath("node",process.env.NVM_BIN)),process.platform==="win32"){e.push("C:\\Program Files\\nodejs\\node.exe");let o=process.env.APPDATA||"";if(o)try{let s=n.resolvePath("nvm",o),a=n.readdirSync(s).filter(i=>i.startsWith("v")).sort().reverse();for(let i of a)e.push(n.resolvePath(`${i}/node.exe`,s))}catch{}}else e.push("/usr/local/bin/node","/usr/bin/node");for(let o of e)try{let s=n.realpathSync(o);if(s.includes("bun")||!n.pathExists(s))continue;return o}catch{continue}return"node"}function cs(n){if(!n||typeof n!="string"||n.includes("\0"))return!1;let e=n.split(/[/\\]/).filter(Boolean);for(let t of e)if(t==="."||t===".."||t==="node_modules"||t===".git"||t.startsWith(".")&&t!==".dndev")return!1;return!0}function $c(n){return n.includes("..")?!1:n.startsWith(".dndev/")||n.startsWith("docs/")||n.startsWith("guides/")}function ls(n){let e=oe(),t=e.getRepoRoot(),r=e.resolvePath(n,t),o=e.normalizePath(t),s=e.normalizePath(r);return!s.startsWith(o+"/")&&s!==o?null:r}async function Rc(n,e){let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!r)return b(e,{error:"path parameter required"},400);if(!cs(r))return b(e,{error:"Access denied"},403);let o=ls(r);if(!o)return b(e,{error:"Access denied"},403);let s=oe();if(!s.pathExists(o))return b(e,{error:"File not found"},404);let a=Sc(o);if(Pc.has(a)){let i=s.readSync(o,{format:"buffer"});return i?(e.writeHead(200,{"Content-Type":us[a]||"application/octet-stream","Content-Length":i.byteLength}),void e.end(Buffer.from(i))):b(e,{error:"Failed to read file"},500)}if(a===".json")try{let i=await s.read(o);return i===null?b(e,{error:"Failed to read file"},500):b(e,{path:r,content:i})}catch{return b(e,{error:"Invalid JSON"},500)}try{let i=await s.read(o,{format:"text"});if(i===null)return b(e,{error:"Failed to read file"},500);b(e,{path:r,content:i})}catch{b(e,{error:"Failed to read file"},500)}}function Cc(n,e){let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("dir"),o=oe(),s=o.getRepoRoot(),a=[],i=new Set(["node_modules",".git","dist","build",".next",".expo"]);function c(u,p){try{let d=o.readdirSync(u,{withFileTypes:!0});for(let f of d){let g=p?`${p}/${f.name}`:f.name;f.isDirectory()&&i.has(f.name)||(f.isDirectory()?(a.push({path:g,name:f.name,isDirectory:!0}),c(o.resolvePath(f.name,u),g)):f.name.endsWith(".md")&&a.push({path:g,name:f.name,isDirectory:!1}))}}catch{}}let l=[".dndev","docs","guides"];if(r){if(r.includes("..")||r.includes("\0"))return b(e,{error:"Access denied"},403);if(!l.includes(r)&&!l.some(f=>r.startsWith(f+"/")))return b(e,{error:"Directory not allowed"},403);let u=o.resolvePath(r,s),p=o.normalizePath(s);if(!o.normalizePath(u).startsWith(p+"/"))return b(e,{error:"Access denied"},403);o.pathExists(u)&&(a.push({path:r,name:o.getBasename(r),isDirectory:!0}),c(u,r))}else{for(let u of l){let p=o.resolveRepoPath(u);o.pathExists(p)&&(a.push({path:u,name:u,isDirectory:!0}),c(p,u))}try{let u=o.readdirSync(s,{withFileTypes:!0});for(let p of u)!p.isDirectory()&&p.name.endsWith(".md")&&a.push({path:p.name,name:p.name,isDirectory:!1})}catch{}}b(e,{entries:a})}async function _c(n,e){let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("path");if(!r)return b(e,{error:"path parameter required"},400);if(!cs(r))return b(e,{error:"Access denied"},403);if(!$c(r))return b(e,{error:"Write not allowed to this path"},403);let o=ls(r);if(!o)return b(e,{error:"Access denied"},403);try{let s=await _e(n),{content:a}=JSON.parse(s);if(a===void 0)return b(e,{error:"content field required"},400);let i=typeof a=="string"?a:JSON.stringify(a,null,2);await oe().write(o,i,{overwrite:!0}),b(e,{ok:!0})}catch{b(e,{error:"Failed to write file"},500)}}async function Ac(n,e){try{let t=await _e(n),{line:r,checked:o}=JSON.parse(t);if(typeof r!="number")return b(e,{error:"line number required"},400);let s=oe(),a=s.resolveRepoPath(".dndev/implementation.md");if(!s.pathExists(a))return b(e,{error:"implementation.md not found"},404);let i=await s.read(a,{format:"text"});if(i===null)return b(e,{error:"Failed to read file"},500);let c=i.split(`
|
|
5
|
+
`);if(r<0||r>=c.length)return b(e,{error:"Line out of range"},400);let l=c[r];c[r]=o?l.replace("- [ ]","- [x]"):l.replace("- [x]","- [ ]"),await s.write(a,c.join(`
|
|
6
|
+
`),{overwrite:!0}),b(e,{ok:!0,line:c[r]})}catch{b(e,{error:"Failed to update progress"},500)}}async function Nc(n,e){try{let t=await _e(n),{id:r,data:o}=JSON.parse(t);if(!r||!o)return b(e,{error:"id and data required"},400);if(!/^[\w-]+$/.test(r))return b(e,{error:"Invalid screenshot ID"},400);let s=oe(),a=s.resolveRepoPath(".dndev/bugs");s.ensureDirSync(a);let i=Buffer.from(o,"base64"),c=s.resolvePath(`${r}.png`,a);await s.write(c,i,{overwrite:!0}),b(e,{ok:!0,path:`.dndev/bugs/${r}.png`})}catch{b(e,{error:"Failed to save screenshot"},500)}}async function kc(n,e){try{let t=await _e(n),{action:r,phase:o}=JSON.parse(t);if(!r||typeof o!="number")return b(e,{error:"action and phase required"},400);let s=oe(),a=is();s.ensureDirSync(a);let i=s.resolvePath("protocol.json",a),c={currentPhase:0,phases:{}};if(s.pathExists(i))try{let l=await s.read(i);l&&(c=l)}catch{}r==="start"?(c.currentPhase=o,c.phases[o]||(c.phases[o]={}),c.phases[o].status="active",c.phases[o].startedAt=new Date().toISOString()):r==="complete"&&(c.phases[o]||(c.phases[o]={}),c.phases[o].status="completed",c.phases[o].completedAt=new Date().toISOString()),await s.write(i,c,{overwrite:!0}),b(e,{ok:!0,protocol:c})}catch{b(e,{error:"Failed to update phase"},500)}}function Dc(n,e){try{let t=le(),r=Se("git rev-parse --short HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),o=Se("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf-8",timeout:5e3}).trim();b(e,{commit:r,branch:o})}catch{b(e,{commit:"unknown",branch:"unknown"})}}async function Tc(n,e){try{let t=await _e(n),r=JSON.parse(t);if(!r.id||!r.type||!r.result)return b(e,{error:"id, type, and result required"},400);let o=oe(),s=is();o.ensureDirSync(s);let a=o.resolvePath("health.json",s),i={actions:[]};if(o.pathExists(a))try{let l=await o.read(a);l&&(i=l)}catch{}Array.isArray(i.actions)||(i.actions=[]);let c=i.actions.findIndex(l=>l.id===r.id);c>=0?i.actions[c]={...i.actions[c],...r}:i.actions.unshift(r),await o.write(a,i,{overwrite:!0}),b(e,{ok:!0})}catch{b(e,{error:"Failed to append action"},500)}}function Oc(n,e){let t=oe(),r=t.resolveRepoPath("apps");try{let s=t.readdirSync(r).filter(a=>{if(a==="dndev")return!1;let i=t.resolvePath(a,r);return t.statSync(i)?.isDirectory()&&t.pathExists(t.resolvePath("package.json",i))}).map(a=>{try{let i=t.resolvePath(`${a}/package.json`,r),c=t.readSync(i);return{name:a,packageName:c?.name||a}}catch{return{name:a,packageName:a}}});b(e,{apps:s})}catch{b(e,{apps:[]})}}function Ic(n,e){try{let t=le(),r=Se("git worktree list --porcelain",{cwd:t,encoding:"utf-8",timeout:5e3}),o=[],s={};for(let a of r.split(`
|
|
7
|
+
`))a.startsWith("worktree ")?(s.path&&o.push(s),s={path:a.slice(9)}):a.startsWith("HEAD ")?s.head=a.slice(5):a.startsWith("branch ")?(s.branch=a.slice(7),s.shortBranch=s.branch.replace("refs/heads/","")):a==="detached"&&(s.detached=!0);s.path&&o.push(s),b(e,{worktrees:o})}catch(t){b(e,{error:t.message},500)}}async function Fc(n,e){try{let t=await _e(n),{branch:r}=JSON.parse(t);if(!r||typeof r!="string")return b(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(r))return b(e,{error:"Invalid branch name"},400);let o=le(),s=oe(),a=s.resolvePath("..",o),i=s.getBasename(o),c=s.resolvePath(`${i}-${r.replace(/\//g,"-")}`,a);Je("git",["worktree","add",c,"-b",r],{cwd:o,encoding:"utf-8",timeout:3e4}),b(e,{ok:!0,path:c,branch:r})}catch(t){b(e,{error:t.message},500)}}async function Mc(n,e){try{let t=await _e(n),{path:r}=JSON.parse(t);if(!r||typeof r!="string")return b(e,{error:"path required"},400);let o=le();Je("git",["worktree","remove",r,"--force"],{cwd:o,encoding:"utf-8",timeout:1e4}),b(e,{ok:!0})}catch(t){b(e,{error:t.message},500)}}function Lc(n,e){try{let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("branch");if(!r)return b(e,{error:"branch required"},400);if(!/^[\w][\w./-]*$/.test(r))return b(e,{error:"Invalid branch name"},400);let o=le(),s=Je("git",["diff",`main...${r}`,"--stat"],{cwd:o,encoding:"utf-8",timeout:1e4}).trim(),a=Je("git",["diff",`main...${r}`],{cwd:o,encoding:"utf-8",timeout:3e4});b(e,{stat:s,diff:a})}catch(t){b(e,{error:t.message},500)}}async function jc(n,e){try{let t=await _e(n),{branch:r,title:o,bodyText:s}=JSON.parse(t);if(!r)return b(e,{error:"branch required"},400);let a=le(),i=["pr","create","--head",r];o&&i.push("--title",o),s&&i.push("--body",s);let c=Je("gh",i,{cwd:a,encoding:"utf-8",timeout:3e4}).trim();b(e,{ok:!0,url:c})}catch(t){b(e,{error:t.message},500)}}function zc(n,e){try{let t=le(),r=Se("git remote get-url origin",{cwd:t,encoding:"utf-8",timeout:5e3}).trim(),o=null;r.includes("github.com")?o="github":r.includes("gitlab")&&(o="gitlab"),b(e,{platform:o,remoteUrl:r})}catch{b(e,{platform:null,remoteUrl:null})}}function Bc(n,e){try{let t=le(),r=Se("gh pr list --json number,title,state,author,headRefName,url,isDraft,reviewDecision,statusCheckRollup --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});b(e,{prs:JSON.parse(r)})}catch(t){b(e,{prs:[],error:t.message})}}function Uc(n,e){try{let t=le(),r=Se("gh issue list --json number,title,state,labels,assignees --limit 50",{cwd:t,encoding:"utf-8",timeout:15e3});b(e,{issues:JSON.parse(r)})}catch(t){b(e,{issues:[],error:t.message})}}function Wc(n,e){try{let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("number");if(!r||!/^\d+$/.test(r))return b(e,{error:"PR number required"},400);let o=le(),s=Se(`gh pr diff ${r}`,{cwd:o,encoding:"utf-8",timeout:3e4});b(e,{diff:s})}catch(t){b(e,{error:t.message},500)}}function Gc(n,e){try{let r=new URL(n.url,`http://${n.headers.host}`).searchParams.get("number");if(!r||!/^\d+$/.test(r))return b(e,{error:"PR number required"},400);let o=le(),s=Se(`gh pr checks ${r} --json name,state,status`,{cwd:o,encoding:"utf-8",timeout:15e3});b(e,{checks:JSON.parse(s)})}catch(t){b(e,{checks:[],error:t.message})}}async function Hc(n,e){try{let t=await _e(n),{number:r,action:o,comment:s}=JSON.parse(t);if(!r||!o)return b(e,{error:"number and action required"},400);let a=["approve","request-changes","comment"];if(!a.includes(o))return b(e,{error:`Invalid action. Use: ${a.join(", ")}`},400);let i=le(),c=["pr","review",String(r),`--${o}`];s&&c.push("--body",s),Je("gh",c,{cwd:i,encoding:"utf-8",timeout:15e3}),b(e,{ok:!0})}catch(t){b(e,{error:t.message},500)}}function Vc(n){if(gn)return;let e=oe(),t=e.normalizePath(n.config.root),r=e.resolvePath("terminal-sidecar.cjs",t);if(!e.pathExists(r))return;try{let i=Se(`fuser ${as}/tcp 2>/dev/null`,{encoding:"utf8"}).trim();i&&process.kill(Number(i),"SIGKILL")}catch{}gn=!0;let o=e.getRepoRoot(),s=xc(),a=wc(s,[r],{cwd:o,stdio:["ignore","inherit","inherit","ipc"],env:{...process.env,TERMINAL_PORT:String(as),TERMINAL_CWD:o}});a.on("message",i=>{i.type}),a.on("exit",i=>{gn=!1}),process.on("exit",()=>{a.kill()})}function Jc(n){let e=oe(),t=e.getRepoRoot(),r=[".dndev","docs","guides"];for(let o of r){let s=e.resolveRepoPath(o);if(!e.pathExists(s))continue;let a=e.watch(s,{recursive:!0},(i,c)=>{if(!c||c==="dashboard.json")return;let l=`${o}/${c}`,u=`change:${l}`;mn.has(u)||(mn.set(u,!0),setTimeout(()=>mn.delete(u),300),n.hot.send("dndev:file-changed",{path:l,timestamp:Date.now()}))});n.httpServer?.on("close",()=>a.close())}}function qc(n={}){return{name:"dndev",configureServer(e){let t=le();n.debug,e.middlewares.use((r,o,s)=>{let a=r.url;if(!a?.startsWith(ss))return s();let c=new URL(a,`http://${r.headers.host}`).pathname.slice(ss.length),l=r.method?.toUpperCase();if(l==="GET")return c==="/file"?void Rc(r,o):c==="/tree"?void Cc(r,o):c==="/git/head"?void Dc(r,o):c==="/apps"?void Oc(r,o):c==="/worktrees"?void Ic(r,o):c==="/worktrees/diff"?void Lc(r,o):c==="/git/platform"?void zc(r,o):c==="/git/prs"?void Bc(r,o):c==="/git/issues"?void Uc(r,o):c==="/git/pr/diff"?void Wc(r,o):c==="/git/pr/checks"?void Gc(r,o):b(o,{error:"Not found"},404);if(l==="POST")return c==="/file"?void _c(r,o):c==="/progress/toggle"?void Ac(r,o):c==="/bugs/screenshot"?void Nc(r,o):c==="/phase"?void kc(r,o):c==="/actions/append"?void Tc(r,o):c==="/worktrees/add"?void Fc(r,o):c==="/worktrees/remove"?void Mc(r,o):c==="/worktrees/pr"?void jc(r,o):c==="/git/pr/review"?void Hc(r,o):b(o,{error:"Not found"},404);b(o,{error:"Method not allowed"},405)}),Vc(e),Jc(e)}}}var ss,Ec,us,Pc,as,gn,mn,ds=kt(()=>{"use strict";Y();ss="/api/dndev";Ec=5*1024*1024;us={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".svg":"image/svg+xml"},Pc=new Set(Object.keys(us));as=24681,gn=!1;mn=new Map});import As from"@rollup/plugin-strip";import{visualizer as Ns}from"rollup-plugin-visualizer";var Dt=["/react/","/react-dom/","/scheduler/","/react-router","/@radix-ui/","/react-hook-form/","/react-i18next/","/clsx/","/class-variance-authority/"],ys={valibot:["/valibot/"],firebase:["/firebase/","/@firebase/"],lucide:["/lucide-react/","/lucide/"],i18n:["/i18next/","/i18next-browser-languagedetector/","/@donotdev/i18n/"],zustand:["/zustand/"],"tanstack-query":["/@tanstack/react-query/","/@tanstack/query-core/"]};function bs(n){let e=n.match(/(?:^|\0)virtual:([^?]+)/);if(e)return e[1]}function yn(n){let e=n.replace(/\\/g,"/");if(e.includes("/node_modules/"))return e.split("?")[0]}function bn(n,e=Dt){return e.some(t=>n.includes(t))}function ws(n){for(let[e,t]of Object.entries(ys))if(t.some(r=>n.includes(r)))return e}function Es(n){let e=bs(n);if(e)return e==="i18n-mapping"?"virtual-i18n-mapping":e.startsWith("i18n-lazy-")?e:"virtual-modules";let t=yn(n);if(!t)return;if(bn(t))return"react-core";let r=ws(t);if(r)return r}function Ss(n=[]){let e=n.filter(r=>!Dt.includes(r)),t=[...Dt,...e];return function(r){let o=yn(r);if(o&&bn(o,t))return"react-core"}}var vn={development:{manualChunks:void 0},production:{manualChunks:Es}};function wn(n,e={}){let t=vn[n]||vn.production,r=e.reactCore||[];return r.length>0?{manualChunks:Ss(r)}:t}Y();import*as ce from"@clack/prompts";var me={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 _s(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function ye(n,e){return _s()?`${e}${n}${me.reset}`:n}function H(n,e,t,r={}){let{logDir:o=".dndev-logs",fileLogging:s=!1}=r,a=O.getInstance(),i=null;if(s){let u=a.resolveAppPath(o);a.pathExists(u)||a.mkdir(u),i=a.resolveAppPath(`${o}/${n.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${n} Log Started at ${new Date().toISOString()} ===
|
|
8
|
+
`;a.writeSync(i,p)}let c=(u,p,d)=>{if(i){let f=new Date().toISOString(),g=d.length>0?" "+d.map(h=>typeof h=="object"?JSON.stringify(h,null,2):String(h)).join(" "):"",v=`${f} [${u}] ${p}${g}
|
|
9
|
+
`;a.appendFile(i,v)}},l=(u,p)=>{if(p.length===0)return u;let d=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${u} ${d}`};return{debug:(u,...p)=>{e&&(s?c("DEBUG",u,p):ce.log.message(ye(l(u,p),me.gray)))},verbose:(u,...p)=>{t&&(s?c("VERBOSE",u,p):ce.log.message(l(u,p)))},info:(u,...p)=>{s?c("INFO",u,p):ce.log.info(ye(l(u,p),me.brightCyan))},warn:(u,...p)=>{e&&s?c("WARN",u,p):ce.log.warn(ye(l(u,p),me.brightYellow))},error:(u,...p)=>{e&&s?c("ERROR",u,p):ce.log.error(ye(l(u,p),me.brightRed))},success:(u,...p)=>{e&&s?c("SUCCESS",u,p):ce.log.success(ye(l(u,p),me.brightGreen))},when:(u,p="debug")=>(d,...f)=>{if(u){let g=l(d,f);switch(p){case"verbose":t&&(ce.log.message(g),c("VERBOSE",d,f));break;case"info":ce.log.info(ye(g,me.brightCyan)),c("INFO",d,f);break;case"warn":ce.log.warn(ye(g,me.brightYellow)),c("WARN",d,f);break;case"error":ce.log.error(ye(g,me.brightRed)),c("ERROR",d,f);break;case"success":ce.log.success(ye(g,me.brightGreen)),c("SUCCESS",d,f);break;default:e&&(ce.log.message(ye(g,me.gray)),c("DEBUG",d,f))}}},getLogFilePath:()=>i}}Y();function Nn(n={}){let{mode:e="development",chunkingOptions:t={},debug:r,verbose:o=!0,isDev:s,isDebug:a,shouldAnalyze:i,build:c={}}=n,l=H("build",r,o),u=wn(e,t);return l.debug("\u{1F41B} DEBUG MODE ENABLED:"),l.debug(" - Minification: DISABLED"),l.debug(" - Sourcemaps: ENABLED"),l.debug(" - Console logs: PRESERVED"),l.debug(" - Debugger statements: PRESERVED"),i&&(l.info("\u{1F4CA} Bundle analysis enabled"),l.info(` Visual treemap will open after build (stats.html)
|
|
10
|
+
`)),{outDir:"dist",sourcemap:s||a,cacheDir:"node_modules/.vite",target:"baseline-widely-available",minify:a?!1:"esbuild",reportCompressedSize:!1,chunkSizeWarningLimit:2048,assetsInlineLimit:0,esbuild:{format:"esm",drop:a?[]:["console","debugger"],legalComments:"none"},cssMinify:a?!1:"esbuild",cssCodeSplit:!0,rollupOptions:{external:ks(),output:{format:"es",entryFileNames:"assets/[name].[hash].js",chunkFileNames:"assets/[name].[hash].js",assetFileNames:"assets/[name].[hash][extname]",...u.manualChunks&&{manualChunks:u.manualChunks},compact:!0},onwarn(d,f){d.code!=="MODULE_LEVEL_DIRECTIVE"&&f(d)},plugins:[...a?[]:[As({include:["**/*.js","**/*.ts","**/*.tsx","**/*.jsx"],functions:["console.*","debugger"],labels:["debug"]})],...i?[(()=>{let d=O.getInstance(),f=d.getAppRoot(),g="dist",v=d.resolveAppPath(`${g}/stats.html`),h=()=>{try{let A=d.resolveAppPath(g);d.pathExists(A)||d.mkdir(A)}catch{}},y=Ns({filename:v,open:!0,gzipSize:!0,brotliSize:!0,template:"treemap",sourcemap:s||a,projectRoot:f});if(y.buildStart){let A=y.buildStart.bind(y);y.buildStart=function(...w){h();let _=A.apply(this,w);return _&&typeof _.then=="function"?_.catch(N=>{}):_}}else y.buildStart=function(){h()};let C=["generateBundle","writeBundle","closeBundle"];for(let A of C)if(y[A]){let w=y[A];y[A]=function(..._){try{h();let N=w.apply(this,_);return N&&typeof N.then=="function"?N.catch(k=>{let x=k?.message||k?.toString()||String(k)||"Unknown error";l.warn(`Bundle visualizer warning in ${A}: ${x}`),A==="closeBundle"&&l.warn(`You can manually open ${v} to view the bundle analysis`)}):N}catch(N){let k=N?.message||N?.toString()||String(N)||"Unknown error";l.warn(`Bundle visualizer warning in ${A}: ${k}`),A==="closeBundle"&&l.warn(` You can manually open ${v} to view the bundle analysis`)}}}return y})()]:[]]}}}function ks(n){return n?["firebase-admin","gcp-metadata","google-logging-utils","@google-cloud/firestore",/\.node$/,"esbuild",/@esbuild\/.*/]:["gcp-metadata","google-logging-utils","payload","file-type","firebase-admin","firebase-admin/app","firebase-admin/auth","firebase-admin/firestore","firebase-admin/functions","firebase-admin/credential","@google-cloud/firestore","google-auth-library","google-gax","googleapis-common"]}function Ds(){let n=!1,e=O.getInstance();if((e.pathExists("/.dockerenv")||e.pathExists("/run/.containerenv"))&&(n=!0),!n&&(process.env.DOCKER_CONTAINER==="true"||process.env.IS_DOCKER==="true"||process.env.DOCKER_BUILDKIT==="1"||process.env.CI==="true"&&process.env.DOCKER==="true")&&(n=!0),!n&&process.env.DOCKER_HOST&&process.env.DOCKER_HOST.includes("docker")&&(n=!0),!n&&process.platform==="linux"&&e.pathExists("/proc/self/cgroup"))try{let o=e.readSync("/proc/self/cgroup");o&&(o.includes("docker")||o.includes("containerd"))&&(n=!0)}catch{}let t=!1;if((process.env.WSL_DISTRO_NAME||process.env.WSLENV)&&(t=!0),!t&&process.platform==="linux"&&e.pathExists("/proc/version"))try{let o=(e.readSync("/proc/version")||"").toLowerCase();t=o.includes("microsoft")||o.includes("wsl")}catch{}if(!t&&process.platform==="linux"&&e.pathExists("/proc/sys/kernel/osrelease"))try{let o=(e.readSync("/proc/sys/kernel/osrelease")||"").toLowerCase()||"";(o.includes("microsoft")||o.includes("wsl"))&&(t=!0)}catch{}if(!t&&process.platform==="win32"){let o=process.cwd();o&&(o.includes("\\wsl$")||o.includes("\\wsl.localhost"))&&(t=!0)}let r=typeof process.versions?.bun=="string";return{isDocker:n,isWSL2:t,isBun:r}}function Ts(n,e){if(n!==void 0)return n;let{isDocker:t,isWSL2:r,isBun:o}=Ds();if(t||r||o){let s=t?"Docker":r?"WSL2":"Bun";return e.info(`Detected ${s} environment - enabling polling mode for file watching`),!0}}function kn(n,e={},t){let r=O.getInstance(),o=r.getRepoRoot(),{watch:s,hmr:a,host:i,...c}=e||{},l=a||{},u=i===!0?"localhost":i||"localhost",p={...l.port&&{port:l.port},...l.clientPort&&{clientPort:l.clientPort},host:l.host??u,...l.protocol&&{protocol:l.protocol},overlay:l.overlay??!0,timeout:l.timeout??5e3},d=i!==void 0?i:!0,f=c.https===!0;return{port:n,host:d,open:e.open!==void 0?e.open:!0,https:f,fs:{allow:[o,r.resolveRepoPath("packages"),r.resolveRepoPath("node_modules")],strict:!1},watch:(()=>{let g=Ts(e?.watch?.usePolling,t);return{usePolling:g,interval:e?.watch?.interval??2e3,...g&&{awaitWriteFinish:{stabilityThreshold:300,pollInterval:100}},...e?.watch||{}}})(),hmr:{...p,...l},headers:{"Cross-Origin-Opener-Policy":"same-origin-allow-popups","Cross-Origin-Embedder-Policy":"unsafe-none"},middlewareMode:!1,...c}}function Dn(n={}){let e=n.https===!0;return{...n,https:e}}q();var Tn={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={CONCATENATE_DEDUPE:"CONCATENATE_DEDUPE",SHALLOW_MERGE:"SHALLOW_MERGE",DEEP_MERGE:"DEEP_MERGE",REPLACE:"REPLACE"};function Ne(n,e,t,r={}){let{protectedKeys:o=[],onConflict:s}=r;if(e==null)return n;switch(t){case de.CONCATENATE_DEDUPE:{if(!Array.isArray(n)||!Array.isArray(e))return e;let a=[...n,...e];return[...new Set(a)]}case de.SHALLOW_MERGE:return typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e)?e:{...n,...e};case de.DEEP_MERGE:{if(typeof n!="object"||typeof e!="object"||n===null||e===null||Array.isArray(n)||Array.isArray(e))return e;let a={...n};for(let i in e){if(o.includes(i)){s&&s(i,n[i],e[i]);continue}typeof a[i]=="object"&&typeof e[i]=="object"&&a[i]!==null&&e[i]!==null&&!Array.isArray(a[i])&&!Array.isArray(e[i])?a[i]=Ne(a[i],e[i],de.DEEP_MERGE,{protectedKeys:o,onConflict:s}):a[i]=e[i]}return a}case de.REPLACE:default:return e}}function On(n,e,t=[],r){let o=[...n,...e||[]],s=[...new Set(o)];return[...new Set([...s,...t])]}var ze={...Tn,reactCompiler:!1,base:"/",mode:process.env.NODE_ENV==="production"?"production":"development",logLevel:process.env.NODE_ENV==="production"?"warn":"info",server:{port:3e3,strictPort:!0,host:!0,open:!0,cors:!0,https:!1,hmr:{overlay:!0,timeout:5e3,usePolling:void 0,interval:2e3},watch:{usePolling:void 0,interval:2e3}},build:{sourcemap:!0,target:"es2020",minify:"esbuild",cssMinify:"esbuild",analyze:!1},preview:{port:4173,strictPort:!0,host:!0,open:!1,cors:!0,https:!1},routes:{hmr:!0},themes:{},i18n:{},assets:{},pwa:{enabled:!1},prerender:{routes:"auto"},chunking:{reactCore:[]},pluginFactory:{verbose:!0,disableHmr:!1,hmrSmartDetection:!0,hmrDebounceMs:500,hmrCacheTimeout:3e4},resolve:{alias:{"@":"/src"},preserveSymlinks:!1},define:{__DEV__:JSON.stringify(process.env.NODE_ENV==="development"),__PROD__:JSON.stringify(process.env.NODE_ENV==="production")},optimizeDeps:{include:[...Pe.mandatoryIncludes],exclude:[...Pe.buildTools,...Object.values(V)],esbuildOptions:{format:"esm",target:"es2020",platform:"browser",define:{"process.env.NODE_ENV":JSON.stringify(process.env.NODE_ENV||"development")},external:["next","next/*"]}},plugins:[],css:{},envDir:void 0};function In(n={},e={}){let{onConflict:t}=e,r={...ze},o=[],s=(a,i,c,l)=>{o.push({key:a,frameworkValue:i,userValue:c,reason:l}),t&&t(a,i,c,l)};if("prerender"in n){let a=n.prerender;a===!1?n.prerender={routes:[]}:a===!0?n.prerender={routes:"auto"}:Array.isArray(a)&&(n.prerender={routes:a})}return Object.keys(n).forEach(a=>{let i=n[a],c=r[a];if(a==="optimizeDeps"&&typeof i=="object"&&i!==null){let l=c?.include||[],u=c?.exclude||[],p=i.include||[],d=i.exclude||[],f=l.filter(C=>!C.startsWith("@donotdev/")),g=d.filter(C=>f.includes(C));if(g.length>0)for(let C of g)s("optimizeDeps.exclude",C,"excluded",`Framework requires ${C} to be included. It will be included despite your exclusion.`);let v=On(l,p,f),h=Ne(u,d,de.CONCATENATE_DEDUPE),y=Ne(c?.esbuildOptions||{},i.esbuildOptions||{},de.DEEP_MERGE,{protectedKeys:["external"],onConflict:C=>s(`optimizeDeps.esbuildOptions.${C}`,c?.esbuildOptions?.[C],i.esbuildOptions?.[C],`Framework requires ${C} to remain as configured.`)});r[a]={...c,include:v,exclude:h,esbuildOptions:y,...Object.fromEntries(Object.entries(i).filter(([C])=>!["include","exclude","esbuildOptions"].includes(C)))};return}if(a==="css"&&typeof i=="object"&&i!==null){r[a]=Ne(c||{},i,de.DEEP_MERGE,{protectedKeys:["postcss"],onConflict:()=>s("css.postcss","framework PostCSS config",i.postcss,"Framework PostCSS config is required and cannot be overridden. Your postcss config is ignored.")});return}if(a==="define"&&typeof i=="object"&&i!==null){r[a]=Ne(c||{},i,de.DEEP_MERGE,{protectedKeys:["__DEV__","__PROD__"],onConflict:l=>s(`define.${l}`,c?.[l],i[l],`Framework requires ${l} to remain as configured.`)});return}if(Array.isArray(i)){Array.isArray(c)?r[a]=Ne(c,i,de.CONCATENATE_DEDUPE):r[a]=i;return}if(typeof i=="object"&&i!==null&&typeof c=="object"&&c!==null&&!Array.isArray(c)){r[a]=Ne(c,i,de.SHALLOW_MERGE);return}r[a]=i}),r}function Fn(n){let{server:e={},preview:t={},mode:r,build:o={},resolve:s={},routes:a={},themes:i={},i18n:c={},assets:l={},features:u={},seo:p={},prerender:d={},pwa:f={},serverShim:g={},chunking:v={},discovery:h={},pluginFactory:y={},debug:C,verbose:A,base:w,define:_={},optimizeDeps:N={},plugins:k=[],css:x={},envDir:D,reactCompiler:R=!1,...m}=n,$=r==="development",U=C||$,E=r==="production"&&(o.analyze??ze.build.analyze);return{mode:r,debug:C,verbose:A,isDev:$,isDebug:U,shouldAnalyze:E,serverOptions:e,previewOptions:t,buildOverrides:o,resolveOptions:s,routeOptions:a,themeOptions:i,i18nOptions:c,assetOptions:l,featureOptions:u,seoOptions:p,prerenderOptions:d,pwaOptions:f,serverShimOptions:g,chunkingOptions:v,discoveryOptions:h,pluginFactoryOptions:y,base:w,defineOptions:_,optimizeDepsOptions:N,pluginsOptions:k,cssOptions:x,envDir:D,reactCompiler:R,restOptions:m}}Y();import Os from"autoprefixer";import Is from"postcss-import";import Fs from"postcss-nesting";function Mn({postcssImport:n,postcssNesting:e,autoprefixer:t,resolve:r}){return{plugins:[r?n({resolve:r}):n,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function Ln(n={}){if(n.postcss)return n.postcss;let e=O.getInstance();return Mn({postcssImport:Is,postcssNesting:Fs,autoprefixer:Os,resolve:(r,o)=>{let s=e.resolvePackage(r,o);if(s)return s;if(r.startsWith("@donotdev/")){let a=r.split("/")[0]+"/"+r.split("/")[1],i=r.split("/").slice(2).join("/"),c=e.resolveFrameworkPackage(a,o);if(c&&i){let l=e.resolvePath(i,c);if(e.pathExists(l))return l}}return e.resolvePath(r,o)}})}import hc from"@vitejs/plugin-basic-ssl";import vc from"@vitejs/plugin-react";import yc from"vite-tsconfig-paths";var ae=class{static generateVirtualModule(e,t,r=!1,o=void 0,s=void 0){return t.isEmpty(e)?t.generateEmpty(e,r,o,s):t.generateModule(e,r,s)}static generateInspection(e,t,r,o){return t.generateInspection.length>=3?t.generateInspection(e,r,o):t.generateInspection(e,r)}static wrapVirtualModule(e,t){return`// Virtual module: ${e}
|
|
11
11
|
// Generated by @donotdev/config discovery
|
|
12
12
|
// Version: 1.0.0
|
|
13
13
|
|
|
@@ -43,16 +43,16 @@ var _o=Object.defineProperty;var xt=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&
|
|
|
43
43
|
`);return`// Helper functions for ${e}
|
|
44
44
|
// Generated by @donotdev/config
|
|
45
45
|
|
|
46
|
-
${r}`}static validateTemplates(e){return["isEmpty","generateModule","generateEmpty","generateInspection"].every(r=>e[r]&&typeof e[r]=="function")}static createTemplateConfig(e,t){let{isEmpty:r=()=>!1,generateModule:o=()=>"",generateEmpty:s=()=>"",generateInspection:
|
|
47
|
-
`)){let o=r.indexOf(":");if(o===-1)continue;let s=r.slice(0,o).trim();if(!s)continue;let
|
|
46
|
+
${r}`}static validateTemplates(e){return["isEmpty","generateModule","generateEmpty","generateInspection"].every(r=>e[r]&&typeof e[r]=="function")}static createTemplateConfig(e,t){let{isEmpty:r=()=>!1,generateModule:o=()=>"",generateEmpty:s=()=>"",generateInspection:a=()=>"",generateManifest:i=()=>({}),logConfig:c=()=>{},logStats:l=()=>{},logManifest:u=()=>{}}=t;return{isEmpty:r,generateModule:o,generateEmpty:s,generateInspection:a,generateManifest:i,logConfig:c,logStats:l,logManifest:u,pluginName:e,version:"1.0.0",createdAt:new Date().toISOString()}}static getEmptyResultWithError(e,t){let r=t?.message||t||"Unknown error";if(e&&typeof e._getEmptyResult=="function")try{let o=e._getEmptyResult();return o.errors&&Array.isArray(o.errors)?o.errors.push(r):o.errors===void 0&&(o.errors=[r]),o.source==="empty"&&(o.source="error"),o}catch{return{errors:[r],source:"error"}}return{errors:[r],source:"error"}}};import{existsSync as js,readdirSync as zs}from"node:fs";import{join as Bs}from"node:path";var Ms=/^---\r?\n([\s\S]*?)\r?\n---/,Ls=/^\r?\n/;function jn(n){let e=n.match(Ms);if(!e)return{meta:{},content:n};let t={};for(let r of(e[1]??"").split(`
|
|
47
|
+
`)){let o=r.indexOf(":");if(o===-1)continue;let s=r.slice(0,o).trim();if(!s)continue;let a=r.slice(o+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[s]=a}return{meta:t,content:n.slice(e[0].length).replace(Ls,"")}}Y();function zn(n){return n.filter(e=>e.endsWith("_en.md")).sort()}function Bn(n){let e=Bs(n,"src","content","blog");try{return js(e)?zn(zs(e)).length>0:!1}catch{return!1}}function ct(n,e){let t=O.getInstance(),r=t.resolvePath("src/content/blog",n);try{if(!t.pathExists(r))return[];let o=zn(t.readdirSync(r));if(o.length===0)return[];let s=[];for(let a of o){let i=t.resolvePath(a,r),c=t.readSync(i,{format:"text"}),l=a.replace(/_en\.md$/,""),{meta:u}=jn(c),p=u.date;if(!p)try{p=t.statSync(i).mtime.toISOString().split("T")[0],e.warn(`Blog post "${l}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],e.warn(`Blog post "${l}" has no date and file stat failed, using today`)}s.push({slug:l,title:u.title||l,description:u.description||"",date:p,tags:u.tags?u.tags.split(",").map(d=>d.trim()):[],image:u.image||null})}return s.sort((a,i)=>i.date.localeCompare(a.date)),e.info(`\u{1F4DD} Discovered ${s.length} blog post(s) in src/content/blog/`),s}catch(o){return e.debug(`Blog content discovery skipped: ${o.message}`),[]}}function B(n,e,t="configuration-error",r={}){let o=`[${n}] ${e}`,s=new Error(o);return s.code=t,s.pluginName=n,s.context=r,s}function be(n){return n instanceof Error&&typeof n.pluginName=="string"}Y();function Un(n,e,t={}){let{blogPath:r="/blog"}=t;return!n.some(s=>{let a=s.path||s;return typeof a=="string"&&a.startsWith(r+"/")&&a.includes(":")})||e.length===0?[]:[{path:r,auth:!1,meta:{namespace:"blog"}},...e.map(s=>({path:`${r}/${s.slug}`,auth:!1,meta:{namespace:"blog",seo:{title:s.title,description:s.description||null,image:s.image,type:"article"}}}))]}function Wn(){let n=null,e,t=new Promise(r=>{e=r});return{set({routes:r,source:o,blogPosts:s}){if(!Array.isArray(s))throw new Error("[dndev] Route manifest: set() needs the build's blogPosts (readBlogPosts).");n={routes:r,errors:[],source:o,blogPosts:s}},useEntityResolver(r){e(r)},entityResolver:()=>t,get(){if(!n)throw new Error("[dndev] Route manifest unavailable: route discovery did not run or failed (see the error above).");return n}}}function Gn(n){return n.filter(e=>{let t=e.path||e;return!(e.auth&&e.auth.required||typeof t=="string"&&t.includes(":"))}).map(e=>e.path||e)}function we(n){let{pluginName:e,icon:t,virtualModuleId:r,DiscoveryClass:o,discoveryMethod:s,filePatterns:a,templates:i,manifestFileName:c,createDiscovery:l,discoveryOptions:u={},configKey:p}=n;return function(f={}){let{debug:g,verbose:v,virtualModuleId:h=r,hmrDebounceMs:y,hmrCacheTimeout:C,hmrSmartDetection:A,disableHmr:w,routeManifest:_,discoveryStore:N,...k}=f;if(!ae.validateTemplates(i))throw new Error(`Invalid templates for plugin ${e}`);let x={...ze.discovery,...u,debug:g,verbose:v,...k},D=p||(()=>{let S=e.match(/dndev-vite-(\w+)-discovery/);return S?S[1]:null})(),R=H(e,g,v,{fileLogging:x.fileLogging,logDir:x.logDir}),m=O.getInstance(),$=()=>{let S=m.getAppRoot(),T=m.getRepoRoot();return S&&S!==T},U=Date.now(),E=l?l(m,x):new o(m,x),M="\0"+h,L="",z=!1,K=null,W=0,Z=!1,P=null,I=!1,F=null,G=!1;typeof global<"u"&&(global.__DNDEV_CLEAR_CACHE__=()=>(E.clearCache(),P=null,R.info("Discovery cache cleared manually"),"Cache cleared"));function Q(S){let J=ae.generateVirtualModule(S,i,g,x,D).replace(/mode:\s*['"]development['"]/g,"mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development'");return!w&&z&&(J+=`
|
|
48
48
|
|
|
49
49
|
// HMR boundary for ${e}
|
|
50
50
|
if (import.meta.hot) {
|
|
51
51
|
import.meta.hot.accept();
|
|
52
52
|
}
|
|
53
|
-
`),Z}function de(x){let N=x.replace(/\\/g,"/");if(E||N.includes("/node_modules/")||N.includes("/.git/")||N.includes("/dist/")||N.includes("/build/")||N.includes("/coverage/")||N.includes("/.vite/")||N.includes("/.turbo/")||N.endsWith(".d.ts")||N.endsWith(".tsbuildinfo")||N.endsWith(".map")||N.endsWith(".css.map")||N.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(N))return!1;let Z=v.getRelativePath(N);if(Z.startsWith("packages/"))return!1;let ge=Z.startsWith("src/")&&/\.(ts|tsx)$/.test(Z);return ge?Array.isArray(i)&&i.length>0?i.some(Q=>typeof Q=="function"?Q(N):typeof Q=="string"?Q.startsWith("**/")?N.endsWith(Q.slice(3)):N.endsWith(Q):!1):ge:!1}function Ce(x){if(E)return $.debug("Virtual modules are static - HMR disabled"),[];let N=Date.now();return O?($.debug("HMR already in progress, skipping update"),[]):N-W<h?(se||(se=!0,X=setTimeout(()=>{se=!1,W=Date.now(),ke(x)},h)),[]):(W=N,ke(x))}function ke(x){let N=Date.now();if(F===x.file&&N-W<100)return $.debug(`Same file processed too recently: ${x.file}`),[];if(!de(x.file))return $.debug(`Skipping irrelevant file change: ${x.file}`),[];$.debug(`Relevant file changed: ${x.file}`),O=!0,F=x.file;try{let Z=Date.now()-(_?.timestamp||0);if(Z<P&&_){$.debug(`Using cached discovery data (age: ${Z}ms)`);let Q=x.server.moduleGraph.getModuleById(j);return Q&&x.server.reloadModule(Q),[]}L.clearCache();let ge=x.server.moduleGraph.getModuleById(j);return ge&&x.server.reloadModule(ge),[]}finally{O=!1,setTimeout(()=>{F===x.file&&(F=null)},200)}}return{name:e,enforce:"pre",configResolved(x){z=x.root,K=x.command==="serve",g&&$.debug(`${t} ${e} initialized`),K&&$.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),a.logConfig&&a.logConfig(y)},config(x){return x.optimizeDeps||(x.optimizeDeps={}),x.optimizeDeps.exclude||(x.optimizeDeps.exclude=[]),x.optimizeDeps.exclude.includes(m)||x.optimizeDeps.exclude.push(m),x},resolveId(x){return x===m?($.debug(`Resolving virtual module: ${x}`),{id:j,moduleSideEffects:!0}):null},async load(x){if(x!==j)return null;if($.debug(`Loading virtual module: ${x}`),!G()){$.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let N=0;for(;!G()&&N<100;)await new Promise(Z=>setTimeout(Z,10)),N++;if(!G())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let N;return _?($.debug("Using cached discovery data for virtual module"),N=_):($.warn(`\u26A0\uFE0F No cached discovery data found for ${e} - running discovery in load() hook. This may indicate buildStart() hook did not run or failed. Performance may be impacted.`),N=await L[s](),_=N,$.debug("Discovery completed for virtual module")),V(N)}catch(N){if(ve(N))throw N;return $.error(`${e} virtual module (${j}) failed to load: ${N.message}`),$.error(`Stack: ${N.stack||"No stack trace available"}`),a.generateEmpty({},g,y,T)}},async buildStart(){if(B=!1,!G()){$.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let x=0;for(;!G()&&x<100;)await new Promise(N=>setTimeout(N,10)),x++;if(!G())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let x=await L[s](!_);if(_=x,p==="routes"&&x?.routes){let N=it(v.getAppRoot(),$),Z=Sr(x.routes,N),ge=[...x.routes.map(Q=>({path:Q.path,auth:Q.auth,meta:Q.meta})),...Z];S?.set({routes:ge,source:x.source||"auto-discovery",blogPosts:N})}a.logStats&&a.logStats(x,t,$)}catch(x){if(ve(x))throw x;$.error(`${e} discovery failed during file scanning: ${x.message}`),$.error(`Stack: ${x.stack||"No stack trace available"}`),_=ne.getEmptyResultWithError(L,x)}finally{B=!0}C?.set(_),p==="routes"&&S?.useEntityResolver(L.getEntityResolver())},configureServer(){B=!0},handleHotUpdate(x){return E?[]:B?Ce(x):($.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!_){$.warn("No cached discovery data for manifest generation - skipping");return}try{let x=ne.generateManifest(_,a.generateManifest);this.emitFile({type:"asset",fileName:l,source:JSON.stringify(x,null,2)}),w&&a.logManifest&&a.logManifest(_,e)}catch(x){$.error(`${e} manifest generation failed: ${x.message}`),$.error(`Stack: ${x.stack||"No stack trace available"}`)}},transform(x,N){return N===j?{code:x,map:null}:null}}}}var ml={generateGlobals:ne.generateGlobals,generateExports:ne.generateExports,generateDefaultExport:ne.generateDefaultExport,wrapVirtualModule:ne.wrapVirtualModule,generateInspectionHeader:ne.generateInspectionHeader,validateTemplates:ne.validateTemplates,createTemplateConfig:ne.createTemplateConfig};J();var pe=class n{constructor(e,t={}){if(this.constructor===n)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=M(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 o=await this._prepareFiles(),s=await this._scanFiles(r),i=await this._processFiles(s,o);this.cache={...i,timestamp:Date.now()};let a=Date.now()-t;return this.logger.debug(`Discovery completed in ${a}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(r){if(ve(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],o=r.split(".")[0],s=r.split(".").pop();return{fileName:r,baseName:o,extension:s,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(ve(r))throw r;return this.logger.debug(`Error processing file ${e}: ${r.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(o=>this._processSingleFile(o,t)))).filter(o=>o!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};J();var wl={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},$r=[{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"}],es={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 ts(){return $r.filter(n=>n.countryCode!==void 0&&n.dialCode!==void 0).map(n=>({code:n.countryCode,dialCode:n.dialCode,flagCode:n.flagCode||n.id,name:n.countryName||es[n.countryCode]||n.name}))}var rs=ts(),qe="/flags";function at(n){return`${n.toLowerCase()}.svg`}function Nt(n){return $r.find(t=>t.id===n)?.flagCode||n}function lt(){return[...new Set(rs.map(n=>n.flagCode))]}var Ae={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},ns="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.",Cr="/manifest.json",Ke=class extends pe{constructor(e,t={}){super(e,{assets:ce.assets.fallback,assetPatterns:ce.assets.patterns,frameworkPackage:Pt.package,assetsPath:Pt.assetsPath,modernFormats:ce.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 a=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(a?[...new Set([...this.flagCodes,...lt()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${qe}/: ${l.join(", ")}`)}let r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn(ns);let s=[],i=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(s=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:s}}async _processFiles(e,{copiedAssets:t,generatedAssets:r}){let o=this.pathResolver.getAppRoot(),{consumerFiles:s}=e,i=await this._processAssetFiles(s),a=this._buildAssetManifest(i,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${Cr}`))}),l=await this._readLogoSvgContent("/logo.svg",o);return{assets:i,manifest:{...a,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(s=>s.path),o=t||this.options.modernFormats;for(let s of o){let i=`/${e}.${s}`;if(r.includes(i))return i}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 o=this.pathResolver.resolveAppPath(Je.public);this.pathResolver.pathExists(o)||(this.pathResolver.mkdir(o),this.logger.debug(`Created public directory: ${o}`));for(let s of this.options.assets)await this._ensureAsset(s,o,r)&&t.push(s);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 o=this.pathResolver.resolveAppPath(`${Je.public}/${e}`);if(this.pathResolver.pathExists(o))return this.logger.debug(`Asset exists: ${e}`),!1;let s=this.pathResolver.normalizePath(`${r}/${e}`);if(this.pathResolver.pathExists(s)){if(await this.pathResolver.copy(s,o))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}/${Te.PUBLISHED_FLAGS}`),o=`${Je.public}${qe}`,s=[];for(let i of e){let a=at(i),l=this.pathResolver.resolveAppPath(`${o}/${a}`);if(this.pathResolver.pathExists(l))continue;let c=`${r}/${a}`;if(!this.pathResolver.pathExists(c)){this.logger.warn(`No flag artwork for "${i}": add ${o}/${a} to the app`);continue}if(!this.pathResolver.copySync(c,l))throw new Error(`Flag copy: cannot copy ${c} to ${l}`);s.push(a)}return s}async _processAssetFiles(e){let t=[];for(let r of e)try{let o=this.pathResolver.getFileInfo(r);if(o&&o.isFile){let s=r.split("/").pop()||r.split("\\").pop(),i=this._analyzeAsset(s,o.size);i&&t.push(i)}}catch(o){this.logger.debug(`Error processing asset file ${r}: ${o.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let r=this._determineAssetType(e),o=this._determineAssetFormat(e);return this.options.assetPatterns.some(i=>this._matchesPattern(e,i))?{path:`/${e}`,name:e,type:r,format:o,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(o)}:(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"],o=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,o)).toFixed(2))+" "+r[o]}_matchesPattern(e,t){let r=t.split("*").map(o=>o.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${r}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let r=e.map(s=>s.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?Cr:null,modernFormats:e.filter(s=>s.isModern).map(s=>s.path),fallbackFormats:e.filter(s=>!s.isModern).map(s=>s.path)}}_getOptimalAsset(e,t,r){for(let o of r){let s=`/${e}.${o}`;if(t.includes(s))return s}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 o=this.pathResolver.normalizePath(`${r}/assets`);return this.pathResolver.pathExists(o)?(this.logger.debug(`Using framework assets from: ${o}`),o):(this.logger.debug(`Assets directory not found: ${o}`),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),o=this.pathResolver.resolveAppPath(`${Je.public}/${r}`);return this.pathResolver.pathExists(o)&&await this.pathResolver.read(o,{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:o}=await e(t).metadata(),s=Math.min(Ae.logoWidth/r,Ae.logoHeight/o),i=await e(t,{density:Math.ceil(72*s)}).resize(Ae.logoWidth,Ae.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:Ae.width,height:Ae.height,channels:4,background:Ae.background}}).composite([{input:i}]).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 o=[{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"}],s=[{name:"favicon.svg",format:"svg"}],i=[],a=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...s,...o].map(u=>u.name),error:"Failed to read logo.svg"};for(let u of s){let p=`${r}/${u.name}`;if(this.pathResolver.pathExists(p)){a.push(u.name);continue}try{await this.pathResolver.write(p,l),i.push(u.name)}catch(d){this.logger.debug(`Failed to copy ${u.name}: ${d.message}`),a.push(u.name)}}let c=await import("sharp").catch(()=>null);if(!c)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),a.push(...o.map(u=>u.name));else{for(let p of o){let d=`${r}/${p.name}`;if(this.pathResolver.pathExists(d)){a.push(p.name);continue}try{let f=c.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),g;p.format==="ico"?g=await f.toFormat("png").toBuffer():g=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(d,g),i.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),a.push(p.name)}}let u=He.slice(1);if(this.pathResolver.pathExists(`${r}/${u}`))a.push(u);else try{let p=await this._renderOgImage(c.default,t);await this.pathResolver.write(`${r}/${u}`,p),i.push(u)}catch(p){this.logger.debug(`Failed to generate ${u}: ${p.message}`),a.push(u)}}return{generated:i,skipped:a,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:[...s,...o].map(c=>c.name),error:l.message}}}};q();var os={isEmpty:n=>!n.manifest||n.assets?.length===0,generateModule:(n,e,t="assets")=>{let{manifest:r,assets:o,copiedAssets:s}=n,i=r.logoSvgContent||null,a={totalAssets:o.length,copiedAssets:s.length,hasLogo:r.logo.optimal!==null,hasFavicon:r.favicon.optimal!==null,hasManifest:r.manifest!==null,timestamp:new Date().toISOString()};return`// ${U.assets} - Generated asset manifest
|
|
53
|
+
`),J}function X(S){let T=S.replace(/\\/g,"/");if(w||T.includes("/node_modules/")||T.includes("/.git/")||T.includes("/dist/")||T.includes("/build/")||T.includes("/coverage/")||T.includes("/.vite/")||T.includes("/.turbo/")||T.endsWith(".d.ts")||T.endsWith(".tsbuildinfo")||T.endsWith(".map")||T.endsWith(".css.map")||T.endsWith(".generated.log")||/\.generated\.[a-z]+$/.test(T))return!1;let J=m.getRelativePath(T);if(J.startsWith("packages/"))return!1;let he=J.startsWith("src/")&&/\.(ts|tsx)$/.test(J);return he?Array.isArray(a)&&a.length>0?a.some(ne=>typeof ne=="function"?ne(T):typeof ne=="string"?ne.startsWith("**/")?T.endsWith(ne.slice(3)):T.endsWith(ne):!1):he:!1}function te(S){if(w)return R.debug("Virtual modules are static - HMR disabled"),[];let T=Date.now();return I?(R.debug("HMR already in progress, skipping update"),[]):T-W<y?(Z||(Z=!0,K=setTimeout(()=>{Z=!1,W=Date.now(),xe(S)},y)),[]):(W=T,xe(S))}function xe(S){let T=Date.now();if(F===S.file&&T-W<100)return R.debug(`Same file processed too recently: ${S.file}`),[];if(!X(S.file))return R.debug(`Skipping irrelevant file change: ${S.file}`),[];R.debug(`Relevant file changed: ${S.file}`),I=!0,F=S.file;try{let J=Date.now()-(P?.timestamp||0);if(J<C&&P){R.debug(`Using cached discovery data (age: ${J}ms)`);let ne=S.server.moduleGraph.getModuleById(M);return ne&&S.server.reloadModule(ne),[]}E.clearCache();let he=S.server.moduleGraph.getModuleById(M);return he&&S.server.reloadModule(he),[]}finally{I=!1,setTimeout(()=>{F===S.file&&(F=null)},200)}}return{name:e,enforce:"pre",configResolved(S){L=S.root,z=S.command==="serve",g&&R.debug(`${t} ${e} initialized`),z&&R.debug("\u{1F4A1} Dev mode: Press 'r' in terminal to restart, or use global.__DNDEV_CLEAR_CACHE__() in console"),i.logConfig&&i.logConfig(x)},config(S){return S.optimizeDeps||(S.optimizeDeps={}),S.optimizeDeps.exclude||(S.optimizeDeps.exclude=[]),S.optimizeDeps.exclude.includes(h)||S.optimizeDeps.exclude.push(h),S},resolveId(S){return S===h?(R.debug(`Resolving virtual module: ${S}`),{id:M,moduleSideEffects:!0}):null},async load(S){if(S!==M)return null;if(R.debug(`Loading virtual module: ${S}`),!$()){R.warn("\u26A0\uFE0F load() called before appRoot is set - waiting for config resolution");let T=0;for(;!$()&&T<100;)await new Promise(J=>setTimeout(J,10)),T++;if(!$())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let T;return P?(R.debug("Using cached discovery data for virtual module"),T=P):(R.warn(`\u26A0\uFE0F No cached discovery data found for ${e} - running discovery in load() hook. This may indicate buildStart() hook did not run or failed. Performance may be impacted.`),T=await E[s](),P=T,R.debug("Discovery completed for virtual module")),Q(T)}catch(T){if(be(T))throw T;return R.error(`${e} virtual module (${M}) failed to load: ${T.message}`),R.error(`Stack: ${T.stack||"No stack trace available"}`),i.generateEmpty({},g,x,D)}},async buildStart(){if(G=!1,!$()){R.warn("\u26A0\uFE0F buildStart() called before appRoot is set - waiting for config resolution");let S=0;for(;!$()&&S<100;)await new Promise(T=>setTimeout(T,10)),S++;if(!$())throw new Error("App root not set before discovery. Ensure configResolved hook has set appRoot.")}try{let S=await E[s](!P);if(P=S,p==="routes"&&S?.routes){let T=ct(m.getAppRoot(),R),J=Un(S.routes,T),he=[...S.routes.map(ne=>({path:ne.path,auth:ne.auth,meta:ne.meta})),...J];_?.set({routes:he,source:S.source||"auto-discovery",blogPosts:T})}i.logStats&&i.logStats(S,t,R)}catch(S){if(be(S))throw S;R.error(`${e} discovery failed during file scanning: ${S.message}`),R.error(`Stack: ${S.stack||"No stack trace available"}`),P=ae.getEmptyResultWithError(E,S)}finally{G=!0}N?.set(P),p==="routes"&&_?.useEntityResolver(E.getEntityResolver())},configureServer(){G=!0},handleHotUpdate(S){return w?[]:G?te(S):(R.debug("HMR disabled - discovery not complete yet"),[])},generateBundle(){if(!P){R.warn("No cached discovery data for manifest generation - skipping");return}try{let S=ae.generateManifest(P,i.generateManifest);this.emitFile({type:"asset",fileName:c,source:JSON.stringify(S,null,2)}),v&&i.logManifest&&i.logManifest(P,e)}catch(S){R.error(`${e} manifest generation failed: ${S.message}`),R.error(`Stack: ${S.stack||"No stack trace available"}`)}},transform(S,T){return T===M?{code:S,map:null}:null}}}}var Wl={generateGlobals:ae.generateGlobals,generateExports:ae.generateExports,generateDefaultExport:ae.generateDefaultExport,wrapVirtualModule:ae.wrapVirtualModule,generateInspectionHeader:ae.generateInspectionHeader,validateTemplates:ae.validateTemplates,createTemplateConfig:ae.createTemplateConfig};q();import{createHash as Hs}from"node:crypto";var fe=class n{constructor(e,t={}){if(this.constructor===n)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=H(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 o=await this._prepareFiles(),s=await this._scanFiles(r),a=await this._processFiles(s,o);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(be(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],o=r.split(".")[0],s=r.split(".").pop();return{fileName:r,baseName:o,extension:s,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(be(r))throw r;return this.logger.debug(`Error processing file ${e}: ${r.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(o=>this._processSingleFile(o,t)))).filter(o=>o!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};q();var ql={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},Hn=[{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"}],Us={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 Ws(){return Hn.filter(n=>n.countryCode!==void 0&&n.dialCode!==void 0).map(n=>({code:n.countryCode,dialCode:n.dialCode,flagCode:n.flagCode||n.id,name:n.countryName||Us[n.countryCode]||n.name}))}var Gs=Ws(),Ke="/flags";function lt(n){return`${n.toLowerCase()}.svg`}function Lt(n){return Hn.find(t=>t.id===n)?.flagCode||n}function ut(){return[...new Set(Gs.map(n=>n.flagCode))]}var Te={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Vn="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.",jt=[{name:"favicon.svg",sharp:!1},{name:"favicon.ico",size:32,sharp:!0},{name:"apple-touch-icon.png",size:180,sharp:!0},{name:"icon-192x192.png",size:192,sharp:!0},{name:"icon-512x512.png",size:512,sharp:!0},{name:Me.slice(1),sharp:!0}],zt=".dndev/icons.json",Vs="sharp is not installed: favicon.ico, apple-touch-icon.png, icon-192x192.png, icon-512x512.png and og-image.png cannot be generated from public/logo.svg or kept in sync with it. Add sharp to the app devDependencies.",Js=new Set(["2b2e767d7d7b8f8775f6f7c3c670f4dba20d5b721da40812b2e76b70efe5bcb2","8a6ee0566fb17bfd659284911fe9e3913fdb6b33b339b0912a68c9f6f825e690"]),Jn=new Set(["2b2e767d7d7b8f8775f6f7c3c670f4dba20d5b721da40812b2e76b70efe5bcb2","74f31fd5ca0d86421b467b2191f650d18ddc8334103142fcd3fc92d3e64a56b9","3ed7374c80df501da384dcbec914e9a2270b2d0af4866061a5f5a61172d68b29","d6f17727836ccdd5dd784e6576bfe3293b4ea8523c25a98aa092be3f30594a59","69970478481c9a5cd9e4c3437c325a315d321e6b4b055a7da29a25d71bcf6b85","c5de4c60c6412ad995ea48f5d4f6204f2874473f28044bc1a21aaf0ee224f6a6","cf96587a25bbe3d259275f34f22fe5212188c2e1c8e74bf0cf7ad6fb72c82ca1","376d735f3903c8320c41df554900b03a93c1659508e91b75e0a9752464238fff","b6c933dcd6d075296cdff68aaa8f7b64287477fb19d666455ac5b94767ec88dd","8a6ee0566fb17bfd659284911fe9e3913fdb6b33b339b0912a68c9f6f825e690","3c38ea7022ee2cc83fb8d4cc2e54f09ab88dd056fc5724ba207b5fde762d879d"]),pt=n=>Hs("sha256").update(n).digest("hex"),qn="/manifest.json",Ye=class extends fe{constructor(e,t={}){super(e,{assets:pe.assets.fallback,assetPatterns:pe.assets.patterns,frameworkPackage:Ot.package,assetsPath:Ot.assetsPath,modernFormats:pe.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"),c=this._ensureFlags(i?[...new Set([...this.flagCodes,...ut()])]:this.flagCodes);c.length>0&&this.logger.debug(`Copied ${c.length} flags to public${Ke}/: ${c.join(", ")}`)}let r=this.pathResolver.resolveAppPath("public/logo.svg");if(!this.pathResolver.pathExists(r)){let i=[];for(let{name:c}of jt){let l=this.pathResolver.resolveAppPath(`public/${c}`);this.pathResolver.pathExists(l)&&Jn.has(pt(await this.pathResolver.read(l,{format:"buffer"})))&&i.push(`public/${c}`)}this.logger.warn(i.length>0?`${Vn} These icons are framework defaults (the DoNotDev logo): ${i.join(", ")}.`:Vn)}let s=[],a=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(s=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:s}}async _processFiles(e,{copiedAssets:t,generatedAssets:r}){let o=this.pathResolver.getAppRoot(),{consumerFiles:s}=e,a=await this._processAssetFiles(s),i=this._buildAssetManifest(a,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${qn}`))}),c=await this._readLogoSvgContent("/logo.svg",o);return{assets:a,manifest:{...i,logoSvgContent:c},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(s=>s.path),o=t||this.options.modernFormats;for(let s of o){let a=`/${e}.${s}`;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 o=this.pathResolver.resolveAppPath($e.public);this.pathResolver.pathExists(o)||(this.pathResolver.mkdir(o),this.logger.debug(`Created public directory: ${o}`));for(let s of this.options.assets)await this._ensureAsset(s,o,r)&&t.push(s);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 o=this.pathResolver.resolveAppPath(`${$e.public}/${e}`);if(this.pathResolver.pathExists(o))return this.logger.debug(`Asset exists: ${e}`),!1;let s=this.pathResolver.normalizePath(`${r}/${e}`);if(this.pathResolver.pathExists(s)){if(await this.pathResolver.copy(s,o))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}`),o=`${$e.public}${Ke}`,s=[];for(let a of e){let i=lt(a),c=this.pathResolver.resolveAppPath(`${o}/${i}`);if(this.pathResolver.pathExists(c))continue;let l=`${r}/${i}`;if(!this.pathResolver.pathExists(l)){this.logger.warn(`No flag artwork for "${a}": add ${o}/${i} to the app`);continue}if(!this.pathResolver.copySync(l,c))throw new Error(`Flag copy: cannot copy ${l} to ${c}`);s.push(i)}return s}async _processAssetFiles(e){let t=[];for(let r of e)try{let o=this.pathResolver.getFileInfo(r);if(o&&o.isFile){let s=r.split("/").pop()||r.split("\\").pop(),a=this._analyzeAsset(s,o.size);a&&t.push(a)}}catch(o){this.logger.debug(`Error processing asset file ${r}: ${o.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let r=this._determineAssetType(e),o=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:r,format:o,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(o)}:(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"],o=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,o)).toFixed(2))+" "+r[o]}_matchesPattern(e,t){let r=t.split("*").map(o=>o.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${r}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let r=e.map(s=>s.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?qn:null,modernFormats:e.filter(s=>s.isModern).map(s=>s.path),fallbackFormats:e.filter(s=>!s.isModern).map(s=>s.path)}}_getOptimalAsset(e,t,r){for(let o of r){let s=`/${e}.${o}`;if(t.includes(s))return s}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 o=this.pathResolver.normalizePath(`${r}/assets`);return this.pathResolver.pathExists(o)?(this.logger.debug(`Using framework assets from: ${o}`),o):(this.logger.debug(`Assets directory not found: ${o}`),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),o=this.pathResolver.resolveAppPath(`${$e.public}/${r}`);return this.pathResolver.pathExists(o)&&await this.pathResolver.read(o,{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:o}=await e(t).metadata(),s=Math.min(Te.logoWidth/r,Te.logoHeight/o),a=await e(t,{density:Math.ceil(72*s)}).resize(Te.logoWidth,Te.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:Te.width,height:Te.height,channels:4,background:Te.background}}).composite([{input:a}]).png().toBuffer()}async _importSharp(){let e=await import("sharp").catch(()=>null);return e?e.default:null}async _renderLogoOutput(e,t,r){return e.name==="favicon.svg"?t:e.name===Me.slice(1)?this._renderOgImage(r,t):r(t).resize(e.size,e.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}).png().toBuffer()}async _readIconState(){let e=this.pathResolver.resolveAppPath(zt);if(!this.pathResolver.pathExists(e))return{};let t=await this.pathResolver.read(e,{format:"text"});try{return JSON.parse(t)}catch(r){throw B("dndev-assets",`${zt} is not valid JSON (${r.message}): fix it, or delete it and the icons generated from public/logo.svg to regenerate both.`,"invalid-configuration")}}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 o=await this.pathResolver.read(t,{format:"buffer"});if(!o)return{generated:[],skipped:jt.map(d=>d.name),error:"Failed to read logo.svg"};let s=pt(o),a=Js.has(s),i=await this._readIconState(),c={},l=await this._importSharp();l||this.logger.warn(Vs);let u=[],p=[];for(let d of jt){let f=`${r}/${d.name}`,g=i[d.name],v=!1;if(this.pathResolver.pathExists(f)){let h=pt(await this.pathResolver.read(f,{format:"buffer"})),y=g?.sha256===h;if(y&&(c[d.name]=g),a){p.push(d.name);continue}if(Jn.has(h))v=!0;else if(y){if(g.logo===s){p.push(d.name);continue}}else{this.logger.debug(`public/${d.name} is the app's own (not generated from logo.svg): left as is`),p.push(d.name);continue}}if(d.sharp&&!l){p.push(d.name);continue}try{let h=await this._renderLogoOutput(d,o,l);if(!await this.pathResolver.write(f,h,{overwrite:!0}))throw new Error(`cannot write ${f}`);c[d.name]={logo:s,sha256:pt(h)},u.push(d.name),v&&this.logger.warn(`replaced framework default public/${d.name}`)}catch(h){this.logger.debug(`Failed to generate ${d.name}: ${h.message}`),p.push(d.name)}}return await this._writeIconState(i,c),{generated:u,skipped:p,error:null}}async _writeIconState(e,t){if(JSON.stringify(e)===JSON.stringify(t))return;let r=this.pathResolver.resolveAppPath(zt);if(Object.keys(t).length===0){await this.pathResolver.remove(r);return}if(!await this.pathResolver.write(r,t,{overwrite:!0}))throw new Error(`Asset generation: cannot write ${r}`)}};Y();var qs={isEmpty:n=>!n.manifest||n.assets?.length===0,generateModule:(n,e,t="assets")=>{let{manifest:r,assets:o,copiedAssets:s}=n,a=r.logoSvgContent||null,i={totalAssets:o.length,copiedAssets:s.length,hasLogo:r.logo.optimal!==null,hasFavicon:r.favicon.optimal!==null,hasManifest:r.manifest!==null,timestamp:new Date().toISOString()};return`// ${V.assets} - Generated asset manifest
|
|
54
54
|
const assetManifest = ${JSON.stringify(r,null,2)};
|
|
55
|
-
const assetStats = ${JSON.stringify(
|
|
55
|
+
const assetStats = ${JSON.stringify(i,null,2)};
|
|
56
56
|
|
|
57
57
|
// Populate unified DnDev config for runtime access
|
|
58
58
|
if (typeof globalThis !== 'undefined') {
|
|
@@ -68,9 +68,9 @@ if (typeof globalThis !== 'undefined') {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
// Populate assets configuration
|
|
71
|
-
globalThis._DNDEV_CONFIG_.${
|
|
71
|
+
globalThis._DNDEV_CONFIG_.${re[t]} = {
|
|
72
72
|
mapping: assetManifest,
|
|
73
|
-
logoSvgContent: ${JSON.stringify(
|
|
73
|
+
logoSvgContent: ${JSON.stringify(a)},
|
|
74
74
|
manifest: {
|
|
75
75
|
totalAssets: ${o.length},
|
|
76
76
|
generatedAt: new Date().toISOString(),
|
|
@@ -120,7 +120,7 @@ export default {
|
|
|
120
120
|
getManifest,
|
|
121
121
|
getAllAssets
|
|
122
122
|
};
|
|
123
|
-
`},generateEmpty:(n,e,t,r="assets")=>{let o={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${
|
|
123
|
+
`},generateEmpty:(n,e,t,r="assets")=>{let o={totalAssets:0,copiedAssets:0,hasLogo:!1,hasFavicon:!1,hasManifest:!1,timestamp:new Date().toISOString()};return`// ${V.assets} - Empty asset manifest
|
|
124
124
|
const assetManifest = {
|
|
125
125
|
logo: { optimal: null, fallback: null },
|
|
126
126
|
favicon: { optimal: null, fallback: null },
|
|
@@ -146,7 +146,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
// Populate empty assets configuration
|
|
149
|
-
globalThis._DNDEV_CONFIG_.${
|
|
149
|
+
globalThis._DNDEV_CONFIG_.${re[r]} = {
|
|
150
150
|
mapping: assetManifest,
|
|
151
151
|
logoSvgContent: null,
|
|
152
152
|
manifest: {
|
|
@@ -219,7 +219,7 @@ export default discoveredAssets;
|
|
|
219
219
|
`:`/**
|
|
220
220
|
* Generated Asset Discovery Results
|
|
221
221
|
* Generated at: ${new Date().toISOString()}
|
|
222
|
-
* Import from '${
|
|
222
|
+
* Import from '${V.assets}'
|
|
223
223
|
*/
|
|
224
224
|
|
|
225
225
|
export const discoveredAssets = ${JSON.stringify(e,null,2)};
|
|
@@ -236,14 +236,14 @@ export const assetStats = {
|
|
|
236
236
|
};
|
|
237
237
|
|
|
238
238
|
export default discoveredAssets;
|
|
239
|
-
`},generateManifest:n=>({assets:n.assets?.length||0,copied:n.copiedAssets?.length||0,timestamp:Date.now(),hasLogo:n.manifest?.logo?.optimal!==null,hasFavicon:n.manifest?.favicon?.optimal!==null}),logConfig:n=>{},logStats:(n,e,t)=>{let r=n.assets?.length||0,o=n.generatedAssets?.length||0;t&&(o>0?t.info(`${e} Assets: ${r} found, ${o} generated`):t.info(`${e} Assets: ${r} found`))}},
|
|
239
|
+
`},generateManifest:n=>({assets:n.assets?.length||0,copied:n.copiedAssets?.length||0,timestamp:Date.now(),hasLogo:n.manifest?.logo?.optimal!==null,hasFavicon:n.manifest?.favicon?.optimal!==null}),logConfig:n=>{},logStats:(n,e,t)=>{let r=n.assets?.length||0,o=n.generatedAssets?.length||0;t&&(o>0?t.info(`${e} Assets: ${r} found, ${o} generated`):t.info(`${e} Assets: ${r} found`))}},Ks=[n=>n.includes("/public/"),n=>n.endsWith(".png")||n.endsWith(".svg")||n.endsWith(".ico"),n=>n.includes("favicon")||n.includes("logo")||n.includes("manifest")];function Kn({i18nStore:n,routeManifest:e,...t}={}){if(!n||!e)throw new Error("[dndev] createViteAssetPlugin: options.i18nStore and options.routeManifest are required (createVitePlugins passes the i18n and route plugins' stores).");let r=null,o=we({pluginName:"dndev-vite-asset-discovery",icon:"\u{1F3AF}",virtualModuleId:V.assets,DiscoveryClass:Ye,createDiscovery:(c,l)=>(r=new Ye(c,l),r),discoveryMethod:"discoverAssets",filePatterns:Ks,templates:qs,manifestFileName:ve.manifests.asset,configKey:"assets"})(t),s=o.buildStart,a=o.configureServer,i=null;return o.configureServer=function(c){return i=c,a.call(this,c)},o.buildStart=async function(...c){let[{flagCodes:l},u]=await Promise.all([n.ready(),e.entityResolver()]);r.useFlagCodes(l,u);let p=O.getInstance(),d=[...new Set([...l??[],...ut()])].map(f=>p.resolveAppPath(`public${Ke}/${lt(f)}`)).filter(f=>!p.pathExists(f));if(await s.apply(this,c),i)for(let f of d)p.pathExists(f)&&i.watcher.emit("add",f)},o}q();var Zn=V.blog,Yn="\0"+Zn;function Xn(){return{name:"dndev-vite-blog",resolveId(n){if(n===Zn)return Yn},load(n){if(n===Yn)return`
|
|
240
240
|
const files = import.meta.glob('/src/content/blog/*.md', {
|
|
241
241
|
query: '?raw',
|
|
242
242
|
import: 'default',
|
|
243
243
|
eager: true,
|
|
244
244
|
});
|
|
245
245
|
export default files;
|
|
246
|
-
`}}}import{loadEnv as
|
|
246
|
+
`}}}import{loadEnv as Ys}from"vite";q();var Qn={isEmpty:n=>!n.env||Object.keys(n.env).length===0,generateModule:(n,e,t="env")=>{let{env:r,mode:o}=n;if(!r||Object.keys(r).length===0)return Qn.generateEmpty(n,e,void 0,t);let s={totalVars:Object.keys(r).length,mode:o,source:n.source,generatedAt:new Date().toISOString()};return`// ${V.env} - Generated environment variables
|
|
247
247
|
|
|
248
248
|
const envData = ${JSON.stringify(r,null,2)};
|
|
249
249
|
const envManifest = ${JSON.stringify(s,null,2)};
|
|
@@ -272,7 +272,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
272
272
|
}
|
|
273
273
|
|
|
274
274
|
// Populate env configuration (frozen to prevent tampering)
|
|
275
|
-
globalThis._DNDEV_CONFIG_.${
|
|
275
|
+
globalThis._DNDEV_CONFIG_.${re[t]} = envData;
|
|
276
276
|
// Only freeze the env property, not the entire config (other plugins need to add properties)
|
|
277
277
|
}
|
|
278
278
|
|
|
@@ -283,7 +283,7 @@ export const source = '${n.source}';
|
|
|
283
283
|
|
|
284
284
|
// Default export
|
|
285
285
|
export default envData;
|
|
286
|
-
`},generateEmpty:(n,e,t,r="env")=>{let o={totalVars:0,mode:n.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${
|
|
286
|
+
`},generateEmpty:(n,e,t,r="env")=>{let o={totalVars:0,mode:n.mode||"development",source:"empty",generatedAt:new Date().toISOString()};return`// ${V.env} - Empty environment data
|
|
287
287
|
|
|
288
288
|
const envData = {};
|
|
289
289
|
const envManifest = ${JSON.stringify(o,null,2)};
|
|
@@ -312,7 +312,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
312
312
|
}
|
|
313
313
|
|
|
314
314
|
// Populate empty env configuration (frozen to prevent tampering)
|
|
315
|
-
globalThis._DNDEV_CONFIG_.${
|
|
315
|
+
globalThis._DNDEV_CONFIG_.${re[r]} = envData;
|
|
316
316
|
// Only freeze the env property, not the entire config (other plugins need to add properties)
|
|
317
317
|
}
|
|
318
318
|
|
|
@@ -322,31 +322,37 @@ export const source = 'empty';
|
|
|
322
322
|
|
|
323
323
|
export default envData;
|
|
324
324
|
`},generateInspection:n=>{let{env:e,mode:t}=n;return["/**"," * Generated Environment Variables",` * Mode: ${t}`,` * Generated at: ${new Date().toISOString()}`,` * Total variables: ${Object.keys(e).length}`," */","","```json",JSON.stringify(e,null,2),"```"].join(`
|
|
325
|
-
`)},generateManifest:n=>({totalVars:Object.keys(n?.env||{}).length,mode:n?.mode||"development",variables:Object.keys(n?.env||{}),timestamp:Date.now()}),logStats:(n,e,t)=>{let r=Object.keys(n.env).length;t&&t.info(`${e} Env: ${r} VITE_* variables`)}},Dt=class{constructor(e,t={}){this.pathResolver=e,this.options=t,this.mode=t.mode||"development",this.appRoot=null}async discoverEnv(){try{let e=this.pathResolver.getAppRoot();if(!e)throw new Error("App root not available in EnvDiscovery");let r={...is(this.mode,e,"VITE_")};return this.mode==="production"&&(delete r.VITE_USE_FIREBASE_EMULATOR,delete r.VITE_FIREBASE_EMULATOR_HOST,delete r.VITE_FIREBASE_AUTH_EMULATOR_HOST,delete r.VITE_FIREBASE_FIRESTORE_EMULATOR_HOST,delete r.VITE_FIREBASE_FUNCTIONS_EMULATOR_PORT),r.MODE=this.mode,r.DEV=this.mode==="development",r.PROD=this.mode==="production",r.SSR=!1,{env:r,mode:this.mode,source:`${e}/.env`,errors:[]}}catch(e){return{env:{},mode:this.mode,source:"error",errors:[e.message]}}}};function Tr(n={}){return ye({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:U.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:kr,manifestFileName:me.manifests.env,configKey:"env",createDiscovery:(e,t)=>new Dt(e,{...t,mode:n.mode||t.mode||"development"})})({...n,disableHmr:!0})}function as(n,e,t,r={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:i}=r;return Array.from({length:t},(a,l)=>{let c=`${e}.${l}`;return n(c)}).filter((a,l)=>{let c=`${e}.${l}`;return!(a===c||s&&a.trim()===""||a.length<o||i&&!i(a,l))})}var Ye=(n,e,t)=>({tag:"meta",attributes:{[n]:e,content:t}});var ls=20,Or={defaultValue:""};function cs(n,e,t){if(n!==null)return n!==void 0?n:t(e,Or)||void 0}function us(n,e){let t=s=>n(s,Or),r=s=>t(`${e}:meta.${s}`)||void 0,o=as(t,`${e}:meta.keywords`,ls);return{fullTitle:r("fullTitle"),image:r("image"),type:r("type"),keywords:o.length>0?o:void 0,author:r("author")}}function Ir(n){let{meta:e,ns:t,defaultNs:r,t:o,siteName:s}=n,i=e.seo;if(!t&&!r)return{title:i?.fullTitle||s};let a=t?cs(i?.title,`${t}:title`,o):i?.title??void 0;return{title:i?.fullTitle||(t?us(o,t).fullTitle:void 0)||(a?`${a} | ${s}`:s),...a&&{pageTitle:a}}}var Fr={enabled:!0,themeColor:"#2563eb",backgroundColor:"#ffffff",includeManifestIcons:!0,includeMSIcons:!1};function Mr(n){let e=t=>n(t)?t:void 0;return{svg:e("/favicon.svg"),ico:e("/favicon.ico"),png16:e("/favicon-16x16.png"),png32:e("/favicon-32x32.png"),apple180:e("/apple-touch-icon.png"),android192:e("/icon-192x192.png"),android512:e("/icon-512x512.png")}}var Me=(n,e,t)=>({tag:"link",attributes:{rel:"icon",type:e,...t&&{sizes:t},href:n}});function Lr(n,e){let{enabled:t,appName:r,themeColor:o,includeManifestIcons:s,includeMSIcons:i}=e;if(t===!1)return[];let a=[];return n.svg&&a.push(Me(n.svg,"image/svg+xml")),n.ico&&a.push(Me(n.ico,"image/x-icon")),n.png16&&a.push(Me(n.png16,"image/png","16x16")),n.png32&&a.push(Me(n.png32,"image/png","32x32")),n.apple180&&(a.push({tag:"link",attributes:{rel:"apple-touch-icon",sizes:"180x180",href:n.apple180}}),r&&a.push(Ye("name","apple-mobile-web-app-title",r))),s&&(n.android192&&a.push(Me(n.android192,"image/png","192x192")),n.android512&&a.push(Me(n.android512,"image/png","512x512"))),i&&n.png32&&(a.push(Ye("name","msapplication-TileImage",n.png32)),o&&a.push(Ye("name","msapplication-TileColor",o))),o&&a.push(Ye("name","theme-color",o)),a.push(Ye("name","color-scheme","light dark")),a}q();function jr({appConfig:n}){let e=n.favicon;return{name:"dndev-favicon",transformIndexHtml(){if(e===!1)return[];let t=D.getInstance();return Lr(Mr(s=>t.pathExists(t.resolveAppPath(`public${s}`))),{...Fr,appName:n.app?.name,...e}).map(({tag:s,attributes:i})=>({tag:s,attrs:i,injectTo:"head"}))}}}J();var ps=["--font-family","--font-headline","--font-mono"],Le=":root",ds=/\/\*[\s\S]*?\*\//g,fs=/([^{}]+)\{([^{}]*)\}/g,gs=/^(?::root|html|:where\(:root\))$/,ms=/^(?::root|html)?\.([a-z][\w-]*)$/i,hs=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/;function Br(n){let e=[],t=0,r="",o=0;for(let s=0;s<n.length;s++){let i=n[s];r?i===r&&(r=""):i==='"'||i==="'"?r=i:i==="("?t++:i===")"?t--:i===","&&t===0&&(e.push(n.slice(o,s)),o=s+1)}return e.push(n.slice(o)),e.map(s=>s.trim())}function vs(n){if(gs.test(n))return Le;let e=ms.exec(n);return e?e[1]:null}function zr(n){let e=new Map,t=n.replace(ds,"");for(let[,r,o]of t.matchAll(fs)){let s=r.split(";").pop(),i=Br(s).map(vs).filter(a=>a!==null);if(i.length!==0)for(let a of o.split(";")){let l=a.indexOf(":");if(l===-1)continue;let c=a.slice(0,l).trim();if(!c.startsWith("--"))continue;let u=a.slice(l+1).replace(/!important\s*$/,"").trim();for(let p of i)e.has(p)||e.set(p,new Map),e.get(p).set(c,u)}}return e}function kt(n,e,t){let r=Br(n)[0];if(!r)return null;let o=hs.exec(r);if(o){let[,s,i]=o;return e.has(s)&&!t.has(s)?kt(e.get(s),e,new Set([...t,s])):i===void 0?null:kt(i,e,t)}return r.replace(/^['"]|['"]$/g,"").trim()}function Ur({frameworkCss:n,appCss:e}){let t=zr(n),r=zr(e.join(`
|
|
326
|
-
`)),o=new Set([Le,...t.keys(),...r.keys()]),s=new Set;for(let i of o){let a=new Map([...t.get(Le)??[],...r.get(Le)??[],...i===Le?[]:t.get(i)??[],...i===Le?[]:r.get(i)??[]]);for(let l of ps){if(!a.has(l))continue;let c=kt(a.get(l),a,new Set([l]));c&&s.add(c)}}return[...s]}var ys=new Map(Object.entries(or).map(([n,e])=>[n.toLowerCase(),e]));function Gr({families:n,locales:e=[]}){if(!Array.isArray(n))throw new Error("resolveFontManifest: families is required (ThemeDiscovery fontFamilies)");let t=new Set;for(let s of n){let i=ys.get(s.toLowerCase());i&&t.add(i)}let r=new Set(["latin"]);for(let s of e)for(let i of sr[s]??[])r.add(i);let o=new Set;for(let s of t)for(let i of r)for(let a of _t[s])o.add(`${s}-${i}-${a}-normal`);return{fontStems:t,subsets:r,stems:o}}function Tt(n){let e=n.split(/[/\\]/).pop().toLowerCase();for(let t of Object.keys(_t)){if(!e.startsWith(`${t}-`))continue;let r=new RegExp(`^${t}-[a-z-]+?-\\d+-(?:normal|italic)`).exec(e);if(r)return r[0]}return null}function Wr(n){return n.replace(/,\s*url\([^)]*\.woff\)\s*format\(['"]woff['"]\)/g,"")}J();J();var je=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:(r,...o)=>{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 r=t.split("-").filter(i=>i.length>0);if(r.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let o=r.map((i,a)=>{let l=i.replace(/[^a-zA-Z0-9]/g,"");return l?a===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!o||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(o)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${o}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(o)?`${o}Var`:o}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,r){let o=[],s,i=this.pathResolver.normalizePath(t),a=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(s=l.exec(a))!==null;){let[,c,u,p]=s;if(!c||!p)continue;let d=u.match(this.patterns.themes.themeIcon),f=u.match(this.patterns.themes.themeIsDark),g={name:c,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:d?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${c} (${p})`),o.push(g),r.themes.set(c,{name:c,displayName:p,isDark:g.isDark,file:i,variables:new Set,meta:g.meta})}return o.length>0&&this._debug(`Extracted ${o.length} themes from ${i}`),o}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(o=>{let s=o.slice(1);s.startsWith("_")||t.classes.add(s)})}extractVariables(e,t,r){(e.match(this.patterns.selectors.variable)||[]).forEach(s=>{s.startsWith("--")&&s.length>2?r==="framework"?t.variables.framework.add(s):t.variables.consumer.add(s):this._debug(`Skipping invalid CSS variable: ${s}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(o=>{let s=o.replace("@keyframes","").trim();s&&t.keyframes.add(s)})}validateCSS(e){let t=[],r=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return r&&r.forEach(s=>{t.push(`Possible malformed CSS variable: ${s}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(s=>{if(!s.includes("--theme-label")&&s.includes("--")){let i=s.match(/\.([a-z][a-z0-9-]+)/)?.[1];i&&t.push(`Theme class "${i}" missing --theme-label`)}}),t}extractAll(e,t,r="consumer"){let o={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},s=this.extractThemes(e,t,o);this.extractClasses(e,o),this.extractVariables(e,o,r),this.extractKeyframes(e,o);let i=this.validateCSS(e);return{themes:s,classes:Array.from(o.classes),variables:{framework:Array.from(o.variables.framework),consumer:Array.from(o.variables.consumer),all:[...Array.from(o.variables.framework),...Array.from(o.variables.consumer)].sort()},keyframes:Array.from(o.keyframes),warnings:i}}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 Vr="@donotdev/components/styles",bs=/@import\s+['"](\.[^'"]+)['"]\s*;/g,Ne=class extends pe{constructor(e,t,r={}){super(t,r),this.cssExtractor=e||new je(t,{debug:r.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:r}=e;this.logger.debug(`Scanning ${t.length} framework + ${r.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",r),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),r.length>0?(this.logger.debug(`Consumer files found: ${r.length}`),this.logger.debug("Consumer files:",r)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t);let o=await this._processConsumerFiles(r),s=this._serializeThemes(),i=Ur({frameworkCss:this._readFrameworkTokenCss(),appCss:o});return this.logger.debug("Theme font families:",i),this.logger.debug(`Discovered ${s.length} themes:`,s.map(a=>a.name)),{themes:s,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort(),fontFamilies:i}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return At.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 r=await this.pathResolver.read(t,{format:"text"}),o=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(r,o,this.discovered),this.cssExtractor.extractClasses(r,this.discovered),this.cssExtractor.extractVariables(r,this.discovered,"framework"),this.cssExtractor.extractKeyframes(r,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(o)}`)}catch(r){this.logger.debug(`Error scanning framework file ${t}: ${r.message}`)}}async _processConsumerFiles(e){let t=[];for(let r of e)try{let o=await this.pathResolver.read(r,{format:"text"});t.push(o);let s=this.pathResolver.normalizePath(r);this.cssExtractor.extractThemes(o,s,this.discovered),this.cssExtractor.extractVariables(o,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(s)}`)}catch(o){this.logger.debug(`Error scanning consumer file ${r}: ${o.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(Vr,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw H("dndev-theme",`cannot resolve ${Vr} (framework font defaults), resolved from @donotdev/ui: check that @donotdev/ui and @donotdev/components are installed`,"missing-required-resource");let t=new Set,r=o=>{if(t.has(o))return"";t.add(o);let s=this.pathResolver.readSync(o,{format:"text"});if(typeof s!="string")throw H("dndev-theme",`cannot read ${o} (framework font defaults)`,"missing-required-resource");let i=this.pathResolver.getDirname(o);return s.replace(bs,(a,l)=>r(this.pathResolver.resolvePath(l,i)))};return r(e)}_addEssentialThemes(){At.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}))}};q();var ws=3,Ot="<!-- DNDEV_FONT_PRELOADS -->",Es=/url\(\s*['"]?([^'")]+)['"]?\s*\)/g;function Hr(n={}){let{debug:e=!1,i18nStore:t}=n;if(!t)throw new Error("[dndev] createViteFontPreloadPlugin: options.i18nStore is required (createVitePlugins passes the i18n plugin's, createI18nStore).");let r=M("font-preload",e,!1),o,s={},i=!1,a=null,l=[];return{name:"vite-font-preload-plugin",enforce:"post",configResolved(c){i=c.command==="build",s={root:c.root,base:c.base&&c.base!=="/"?c.base.replace(/\/$/,""):"",outDir:c.build?.outDir??"dist"};try{o=D.getInstance()}catch(u){r.debug(`Font preload: PathResolver not ready: ${u?.message}`)}},async buildStart(){if(!i||!o||!o.getAppRoot())return;let{supportedLanguages:u}=await t.ready(),p=new Ne(null,o,{debug:e}),{fontFamilies:d}=await p.discoverThemes(),f=Gr({families:d,locales:u});a=f.stems,r.debug(`Font filter: ${f.fontStems.size} font(s) [${[...f.fontStems].join(", ")}], ${f.subsets.size} subset(s), ${a.size} allowed stem(s)`)},generateBundle(c,u){if(!a)return;let p=h=>Tt(h)!==null,d=h=>a.has(Tt(h)),f=0,g=0;for(let h of Object.keys(u))u[h].type!=="asset"||!p(h)||(h.endsWith(".woff")?(delete u[h],f++):h.endsWith(".woff2")&&!d(h)&&(delete u[h],g++));r.debug(`Font filter: deleted ${f} .woff + ${g} .woff2 from bundle`);for(let[h,P]of Object.entries(u)){if(P.type!=="asset"||!h.endsWith(".css")||typeof P.source!="string")continue;let R=P.source,E=R.replace(/@font-face\s*\{[\s\S]*?\}/g,S=>{let C=[...S.matchAll(Es)].map(k=>k[1]);return C.some(p)?C.some(d)?Wr(S):"":S});E!==R&&(P.source=E)}let w=s.base||"",m=[];for(let[h,P]of Object.entries(u)){if(P.type!=="asset"||!h.endsWith(".woff2")||!d(h))continue;let R=w?`${w}/${h}`:`/${h}`;m.push(R)}l=m.slice(0,ws)},writeBundle(){if(!i||!l.length)return;let c=o||D.getInstance(),u=s.root||process.cwd(),p=s.outDir||"dist",d=c.resolvePath(`${p}/index.html`,u);try{if(!c.pathExists(d)){r.debug(`Font preload: index.html not found at ${d}`);return}let f=c.readSync(d,{format:"text"}),g=l.map(w=>`<link rel="preload" as="font" href="${w}" type="font/woff2" crossorigin="anonymous" />`).join(`
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
${g}`+f.slice(m))}c.writeSync(d,f,{overwrite:!0}),r.debug(`Font preload: injected ${l.length} link(s)`)}catch(f){r.debug(`Font preload: write failed: ${f?.message}`)}}}}import{existsSync as Zr,readFileSync as Xr,writeFileSync as xs}from"node:fs";import{join as Qr}from"node:path";var Ss="/(.*)",Ft=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"]),Rs=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'"]}),Jr=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),en=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"]}}),Ps=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=()"}]),$s=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),Cs=31536e3,_s=86400,tn=3600,qr=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(n=>`/assets/:path*.${n}`),"next-export":["/_next/static/:path*"],next:[]}),As=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),Ns=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${tn}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),Kr=Object.freeze(["csp","cache"]);function ct(n,e=!1){return`public, max-age=${n}${e?", immutable":""}`}function It(n,e){return{source:n,headers:[{key:"Cache-Control",value:e}]}}var Yr=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),Ds=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function ks(n,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${n}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!Yr.includes(e)&&!Ds.test(e))throw new Error(`[dndev] appConfig.headers.csp['${n}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${Yr.join(" ")} or a hash like 'sha256-<base64>').`)}function Ts(n){if(n===void 0)return{csp:{},cache:[]};if(!n||typeof n!="object"||Array.isArray(n))throw new Error("[dndev] appConfig.headers must be an object.");for(let r of Object.keys(n))if(!Kr.includes(r))throw new Error(`[dndev] appConfig.headers.${r} is not a header option (allowed: ${Kr.join(", ")}).`);let e=n.csp??{};for(let[r,o]of Object.entries(e)){if(!Ft.includes(r))throw new Error(`[dndev] appConfig.headers.csp['${r}'] is not a CSP directive the framework merges (allowed: ${Ft.join(", ")}).`);if(!Array.isArray(o))throw new Error(`[dndev] appConfig.headers.csp['${r}'] must be an array of sources.`);for(let s of o)ks(r,s)}let t=n.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let r of t){if(typeof r?.source!="string"||!r.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(r?.source)}).`);if(!Number.isInteger(r.maxAge)||r.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${r.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(r.maxAge)}).`)}return{csp:e,cache:t}}function Os({csp:n={},providers:e=[],target:t}){if(!(t in Jr))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...Ft.map(o=>{let s=[...o==="script-src"?Jr[t]:Rs[o]??[],...e.flatMap(l=>en[l]?.[o]??[]),...n[o]??[]],i=[...new Set(s)],a=i.length>1?i.filter(l=>l!=="'none'"):i;return a.length>0?`${o} ${a.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function rn({appConfig:n,target:e,providers:t=[],pwa:r=!1}){if(!(e in qr))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:o,cache:s}=Ts(n?.headers),i=[{key:"Content-Security-Policy",value:Os({csp:o,providers:t,target:e})},...n?.seo===!1?[$s]:[],...Ps].map(a=>({...a}));return[{source:Ss,headers:i},...qr[e].map(a=>It(a,ct(Cs,!0))),...As.map(a=>It(`/:path*.${a}`,ct(_s))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:ct(tn)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...r?Ns.map(a=>({source:a.source,headers:a.headers.map(l=>({...l}))})):[],...s.map(a=>It(a.source,ct(a.maxAge,a.immutable===!0)))]}function nn(n){let e=Qr(n,"package.json");if(!Zr(e))return[];let t=JSON.parse(Xr(e,"utf8")),r={...t.dependencies,...t.devDependencies};return Object.keys(en).filter(o=>!!r[o])}function Is(n){let e=Qr(n,"vercel.json");if(!Zr(e))return null;try{return{path:e,config:JSON.parse(Xr(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function on({appRoot:n,rules:e,ci:t,logger:r}){let o=Is(n);if(!o)return"absent";if(JSON.stringify(o.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${o.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 s=`${JSON.stringify({...o.config,headers:e},null,2)}
|
|
330
|
-
`;return xs(o.path,s),r?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function sn({appConfig:n,pwa:e,debug:t,verbose:r}){let o=M("host-headers",t,r);return{name:"dndev-host-headers",configResolved(s){on({appRoot:s.root,rules:rn({appConfig:n,target:"vite",providers:nn(s.root),pwa:e===!0}),ci:!!(process.env.CI||process.env.VERCEL),logger:o})}}}J();J();q();J();function Fs(n){if(!n)return[];let e=D.getInstance(),t=new Set;try{let r=e.resolvePackage("@donotdev/core",n);if(!r)return[];let o=e.getDirname(e.getDirname(r)),s;try{s=e.readdirSync(o)}catch{return[]}for(let i of s)try{let a=e.resolvePath(`${i}/package.json`,o),l=e.readSync(a,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[c,u]of Object.entries(l.peerDependenciesMeta))u?.optional&&t.add(c)}catch{}}catch{}return Array.from(t)}function Ms(n){if(!n)return[];let e=D.getInstance();try{let t=e.resolvePath("package.json",n),r=e.readSync(t,{format:"json"});if(!r)return[];let o=new Set;if(r.peerDependenciesMeta)for(let[s,i]of Object.entries(r.peerDependenciesMeta))i?.optional&&o.add(s);if(r.optionalDependencies)for(let s of Object.keys(r.optionalDependencies))o.add(s);return Array.from(o)}catch{return[]}}function Ls(n){let e=we.optionalFeatures||[],t=Fs(n),r=Ms(n);return[...new Set([...e,...t,...r])]}function js(n){let e=D.getInstance();try{let t=e.resolvePath("package.json",n),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 zs(n,e,t){if(t.resolvePackage(n,e||void 0))return!0;let r=n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0],o=e;for(let s=0;s<10;s++){let i=t.resolvePath(`node_modules/${r}`,o);if(t.pathExists(i))return!0;let a=t.getDirname(o);if(a===o)break;o=a}return!1}function ut(n){let e=Ls(n),t=[],r=[],o=D.getInstance(),s=js(n);for(let i of e)i.startsWith("@donotdev/")?s.has(i)?r.push(i):t.push(i):s.has(i)&&zs(i,n,o)?r.push(i):t.push(i);return{missing:t,installed:r}}var pt=class extends pe{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,o]of Object.entries(e)){for(let s of Object.keys(o))t.includes(s)||delete o[s];Object.keys(o).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 o=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${o.eager.length}, lazy: ${o.lazy.length}, framework eager: ${o.framework?.eager?.length||0}, framework lazy: ${o.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let s=ot("i18n"),i=o.eager||[],a=o.lazy||[],l=(this.options.additionalPaths||[]).map(_=>{let O=_.endsWith(".json")?_:`${_}/*_*.json`;return this.pathResolver.resolveAppPath(O)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let c=o.framework?.eager||[],u=o.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${i.join(", ")}, lazy: ${a.join(", ")}, framework eager: ${c.join(", ")}, framework lazy: ${u.join(", ")}`),c.length===0&&u.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=(_,O)=>{let F=this.pathResolver.normalizePath(_),B=this.pathResolver.normalizePath(O);return F.startsWith(B)?F.slice(B.length+1):F},g=i.map(_=>f(_,t)),m=[...a,...l].map(_=>f(_,t)),h=c.map(_=>f(_,r)),P=u.map(_=>f(_,r)),R={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},E=await this.pathResolver._globWithNormalization(g,R),S=await this.pathResolver._globWithNormalization(m,R),C={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r,ignore:s.ignore?.filter(_=>_!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${r}, ignore: ${JSON.stringify(C.ignore)}`);let k=await this.pathResolver._globWithNormalization(h,C),y=await this.pathResolver._globWithNormalization(P,C);this.logger.debug(`Found ${E.length} eager, ${S.length} lazy, ${k.length} framework eager, ${y.length} framework lazy files`),k.length>0?this.logger.debug(`Framework eager files (first 3): ${k.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${c.join(", ")}`),y.length>0?this.logger.debug(`Framework lazy files (first 3): ${y.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${u.join(", ")}`);let T=[...new Set([...E,...S,...k,...y])],$=new Set([...E,...k]),v={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:G}=ut(t),A=new Set(G.filter(_=>_.startsWith("@donotdev/")).map(_=>_.replace("@donotdev/","")));A.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...A].join(", ")}] (packages not installed)`);let L=new Map,j=[...k,...y];for(let _ of j){let O=this._processTranslationFile(_,k.includes(_),t);if(O){if(A.has(O.namespace))continue;let F=`${O.namespace}_${O.language}`;L.set(F,O),v.allNamespaces.add(O.namespace),v.supportedLanguages.add(O.language),k.includes(_)&&v.eagerNamespaces.add(O.namespace)}}let z=new Set;for(let _ of T){if(j.includes(_))continue;let O=this._processTranslationFile(_,$.has(_),t);if(O){let{namespace:F,language:B,importPath:V,content:de}=O,Ce=`${O.namespace}_${O.language}`;if(L.has(Ce)){let ke=L.get(Ce);O.content=this._mergeTranslations(ke.content,de)}v.allNamespaces.add(F),v.supportedLanguages.add(B),z.add(B),$.has(_)&&v.eagerNamespaces.add(F),v.mapping[F]||(v.mapping[F]={}),v.mapping[F][B]=V,O.content&&(v.content[F]||(v.content[F]={}),v.content[F][B]=O.content),v.files.push({path:_,relativePath:this.pathResolver.getRelativePath(_),namespace:F,language:B,eager:$.has(_),size:O.content?JSON.stringify(O.content).length:0})}}for(let[_,O]of L){let F=_.lastIndexOf("_"),B=_.slice(0,F),V=_.slice(F+1);z.size>0&&!z.has(V)||(!v.mapping[B]||!v.mapping[B][V])&&(v.mapping[B]||(v.mapping[B]={}),v.mapping[B][V]=O.importPath,v.content[B]||(v.content[B]={}),v.content[B][V]=O.content,v.files.push({path:O.absolutePath,relativePath:this.pathResolver.getRelativePath(O.absolutePath),namespace:B,language:V,eager:v.eagerNamespaces.has(B),size:O.content?JSON.stringify(O.content).length:0}))}let K=z.size>0?[...z].sort():[this.options.fallbackLanguage],X=this._getLanguageAllowlist(),W=K;if(X){let _=K.filter(F=>X.includes(F));W=_.length>0?_:[this.options.fallbackLanguage],this._restrictByLanguage(v.mapping,W),this._restrictByLanguage(v.content,W),v.files=v.files.filter(F=>W.includes(F.language));let O=new Set(Object.keys(v.mapping));v.allNamespaces=new Set([...v.allNamespaces].filter(F=>O.has(F))),v.eagerNamespaces=new Set([...v.eagerNamespaces].filter(F=>O.has(F))),this.logger.debug(`I18n restricted by i18n.only [${X.join(", ")}]: languages [${W.join(", ")}], namespaces ${O.size}`)}let se=[...new Set(W.map(Nt))];return{mapping:v.mapping,content:v.content,eagerNamespaces:[...v.eagerNamespaces].sort(),allNamespaces:[...v.allNamespaces].sort(),supportedLanguages:W,fallbackLanguage:this.options.fallbackLanguage,flagCodes:se,files:v.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 r=await this._processFiles([]);this.cache={...r,timestamp:Date.now()};let o=Date.now()-t;return this.logger.debug(`Discovery completed in ${o}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 o=e.split("/").pop()||e.split("\\").pop()||"",s,i,a=o.match(/^(.+)_([^_.]+)\.json$/);if(!a)return this.logger.debug(`Invalid translation file name format: ${o}`),null;if([,s,i]=a,!s||!i)return this.logger.debug(`Invalid namespace or language in file: ${o}`),null;let c="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),u;try{if(u=this.pathResolver.readSync(e,{format:"json"}),!u)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:s,language:i,importPath:c,absolutePath:e,content:u}}_mergeTranslations(e,t){let r={...e};for(let[o,s]of Object.entries(t))typeof s=="object"&&s!==null&&!Array.isArray(s)?r[o]=this._mergeTranslations(r[o]||{},s):r[o]=s;return r}};var an={isEmpty:n=>!n.mapping||Object.keys(n.mapping).length===0,generateModule:(n,e,t="i18n",r=!1)=>{let{mapping:o,eagerNamespaces:s,supportedLanguages:i,fallbackLanguage:a,stats:l,content:c={},files:u=[]}=n,p=r?Object.keys(c):s,d={};for(let h of p)c[h]&&(d[h]=c[h]);let f=[...new Set([...s,...Object.keys(c)])],g={mapping:o,languages:i,eager:r?f:s,fallback:a,content:d,storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:l?.totalFiles||0,totalNamespaces:l?.totalNamespaces||0,totalLanguages:l?.totalLanguages||0,eagerNamespaces:l?.eagerNamespaces||0,generatedAt:new Date().toISOString()},debug:e},w=[];if(!r)for(let[h,P]of Object.entries(o)){if(s.includes(h))continue;let R=[];for(let E of Object.keys(P))R.push(` '${E}': () => import('virtual:i18n-lazy-${h}-${E}')`);R.length>0&&w.push(` '${h}': {
|
|
331
|
-
${
|
|
325
|
+
`)},generateManifest:n=>({totalVars:Object.keys(n?.env||{}).length,mode:n?.mode||"development",variables:Object.keys(n?.env||{}),timestamp:Date.now()}),logStats:(n,e,t)=>{let r=Object.keys(n.env).length;t&&t.info(`${e} Env: ${r} VITE_* variables`)}},Bt=class{constructor(e,t={}){this.pathResolver=e,this.options=t,this.mode=t.mode||"development",this.appRoot=null}async discoverEnv(){try{let e=this.pathResolver.getAppRoot();if(!e)throw new Error("App root not available in EnvDiscovery");let r={...Ys(this.mode,e,"VITE_")};return this.mode==="production"&&(delete r.VITE_USE_FIREBASE_EMULATOR,delete r.VITE_FIREBASE_EMULATOR_HOST,delete r.VITE_FIREBASE_AUTH_EMULATOR_HOST,delete r.VITE_FIREBASE_FIRESTORE_EMULATOR_HOST,delete r.VITE_FIREBASE_FUNCTIONS_EMULATOR_PORT),r.MODE=this.mode,r.DEV=this.mode==="development",r.PROD=this.mode==="production",r.SSR=!1,{env:r,mode:this.mode,source:`${e}/.env`,errors:[]}}catch(e){return{env:{},mode:this.mode,source:"error",errors:[e.message]}}}};function er(n={}){return we({pluginName:"dndev-vite-env-discovery",icon:"\u{1F510}",virtualModuleId:V.env,discoveryMethod:"discoverEnv",filePatterns:[],templates:Qn,manifestFileName:ve.manifests.env,configKey:"env",createDiscovery:(e,t)=>new Bt(e,{...t,mode:n.mode||t.mode||"development"})})({...n,disableHmr:!0})}function Zs(n,e,t,r={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:t},(i,c)=>{let l=`${e}.${c}`;return n(l)}).filter((i,c)=>{let l=`${e}.${c}`;return!(i===l||s&&i.trim()===""||i.length<o||a&&!a(i,c))})}var Ze=(n,e,t)=>({tag:"meta",attributes:{[n]:e,content:t}});var Xs=20,tr={defaultValue:""};function Qs(n,e,t){if(n!==null)return n!==void 0?n:t(e,tr)||void 0}function ea(n,e){let t=s=>n(s,tr),r=s=>t(`${e}:meta.${s}`)||void 0,o=Zs(t,`${e}:meta.keywords`,Xs);return{fullTitle:r("fullTitle"),image:r("image"),type:r("type"),keywords:o.length>0?o:void 0,author:r("author")}}function nr(n){let{meta:e,ns:t,defaultNs:r,t:o,siteName:s}=n,a=e.seo;if(!t&&!r)return{title:a?.fullTitle||s};let i=t?Qs(a?.title,`${t}:title`,o):a?.title??void 0;return{title:a?.fullTitle||(t?ea(o,t).fullTitle:void 0)||(i?`${i} | ${s}`:s),...i&&{pageTitle:i}}}var rr={enabled:!0,themeColor:"#2563eb",backgroundColor:"#ffffff",includeManifestIcons:!0,includeMSIcons:!1};function or(n){let e=t=>n(t)?t:void 0;return{svg:e("/favicon.svg"),ico:e("/favicon.ico"),png16:e("/favicon-16x16.png"),png32:e("/favicon-32x32.png"),apple180:e("/apple-touch-icon.png"),android192:e("/icon-192x192.png"),android512:e("/icon-512x512.png")}}var Be=(n,e,t)=>({tag:"link",attributes:{rel:"icon",type:e,...t&&{sizes:t},href:n}});function sr(n,e){let{enabled:t,appName:r,themeColor:o,includeManifestIcons:s,includeMSIcons:a}=e;if(t===!1)return[];let i=[];return n.svg&&i.push(Be(n.svg,"image/svg+xml")),n.ico&&i.push(Be(n.ico,"image/x-icon")),n.png16&&i.push(Be(n.png16,"image/png","16x16")),n.png32&&i.push(Be(n.png32,"image/png","32x32")),n.apple180&&(i.push({tag:"link",attributes:{rel:"apple-touch-icon",sizes:"180x180",href:n.apple180}}),r&&i.push(Ze("name","apple-mobile-web-app-title",r))),s&&(n.android192&&i.push(Be(n.android192,"image/png","192x192")),n.android512&&i.push(Be(n.android512,"image/png","512x512"))),a&&n.png32&&(i.push(Ze("name","msapplication-TileImage",n.png32)),o&&i.push(Ze("name","msapplication-TileColor",o))),o&&i.push(Ze("name","theme-color",o)),i.push(Ze("name","color-scheme","light dark")),i}var dt="dndev-fonts";function Ut(n){return n.map(e=>({tag:"link",attributes:{rel:"preload",as:"font",type:"font/woff2",href:e,crossorigin:"anonymous"}}))}Y();function ar({appConfig:n}){let e=n.favicon;return{name:"dndev-favicon",transformIndexHtml(){if(e===!1)return[];let t=O.getInstance();return sr(or(s=>t.pathExists(t.resolveAppPath(`public${s}`))),{...rr,appName:n.app?.name,...e}).map(({tag:s,attributes:a})=>({tag:s,attrs:a,injectTo:"head"}))}}}q();q();var Ue=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:(r,...o)=>{this.options.debug}},this.patterns={selectors:{...Ft.selectors,...this.options.customPatterns?.selectors},themes:{...Ft.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 r=t.split("-").filter(a=>a.length>0);if(r.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let o=r.map((a,i)=>{let c=a.replace(/[^a-zA-Z0-9]/g,"");return c?i===0?c.toLowerCase():c.charAt(0).toUpperCase()+c.slice(1).toLowerCase():null}).filter(Boolean).join("");return!o||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(o)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${o}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(o)?`${o}Var`:o}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,r){let o=[],s,a=this.pathResolver.normalizePath(t),i=this._stripComments(e),c=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(s=c.exec(i))!==null;){let[,l,u,p]=s;if(!l||!p)continue;let d=u.match(this.patterns.themes.themeIcon),f=u.match(this.patterns.themes.themeIsDark),g={name:l,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:d?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${l} (${p})`),o.push(g),r.themes.set(l,{name:l,displayName:p,isDark:g.isDark,file:a,variables:new Set,meta:g.meta})}return o.length>0&&this._debug(`Extracted ${o.length} themes from ${a}`),o}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(o=>{let s=o.slice(1);s.startsWith("_")||t.classes.add(s)})}extractVariables(e,t,r){(e.match(this.patterns.selectors.variable)||[]).forEach(s=>{s.startsWith("--")&&s.length>2?r==="framework"?t.variables.framework.add(s):t.variables.consumer.add(s):this._debug(`Skipping invalid CSS variable: ${s}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(o=>{let s=o.replace("@keyframes","").trim();s&&t.keyframes.add(s)})}validateCSS(e){let t=[],r=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return r&&r.forEach(s=>{t.push(`Possible malformed CSS variable: ${s}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(s=>{if(!s.includes("--theme-label")&&s.includes("--")){let a=s.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,r="consumer"){let o={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},s=this.extractThemes(e,t,o);this.extractClasses(e,o),this.extractVariables(e,o,r),this.extractKeyframes(e,o);let a=this.validateCSS(e);return{themes:s,classes:Array.from(o.classes),variables:{framework:Array.from(o.variables.framework),consumer:Array.from(o.variables.consumer),all:[...Array.from(o.variables.framework),...Array.from(o.variables.consumer)].sort()},keyframes:Array.from(o.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 ir="@donotdev/components/styles",ta=/@import\s+['"](\.[^'"]+)['"]\s*;/g,Oe=class extends fe{constructor(e,t,r={}){super(t,r),this.cssExtractor=e||new Ue(t,{debug:r.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:r}=e;this.logger.debug(`Scanning ${t.length} framework + ${r.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",r),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),r.length>0?(this.logger.debug(`Consumer files found: ${r.length}`),this.logger.debug("Consumer files:",r)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t);let o=await this._processConsumerFiles(r),s=this._serializeThemes(),a={framework:this._readFrameworkTokenCss(),app:o};return this.logger.debug(`Discovered ${s.length} themes:`,s.map(i=>i.name)),{themes:s,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 Mt.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 r=await this.pathResolver.read(t,{format:"text"}),o=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(r,o,this.discovered),this.cssExtractor.extractClasses(r,this.discovered),this.cssExtractor.extractVariables(r,this.discovered,"framework"),this.cssExtractor.extractKeyframes(r,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(o)}`)}catch(r){this.logger.debug(`Error scanning framework file ${t}: ${r.message}`)}}async _processConsumerFiles(e){let t=[];for(let r of e)try{let o=await this.pathResolver.read(r,{format:"text"}),s=this.pathResolver.normalizePath(r);t.push({file:this.pathResolver.getRelativePath(s),css:o}),this.cssExtractor.extractThemes(o,s,this.discovered),this.cssExtractor.extractVariables(o,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(s)}`)}catch(o){this.logger.debug(`Error scanning consumer file ${r}: ${o.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(ir,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw B("dndev-theme",`cannot resolve ${ir} (framework font defaults), resolved from @donotdev/ui: check that @donotdev/ui and @donotdev/components are installed`,"missing-required-resource");let t=new Set,r=o=>{if(t.has(o))return"";t.add(o);let s=this.pathResolver.readSync(o,{format:"text"});if(typeof s!="string")throw B("dndev-theme",`cannot read ${o} (framework font defaults)`,"missing-required-resource");let a=this.pathResolver.getDirname(o);return s.replace(ta,(i,c)=>r(this.pathResolver.resolvePath(c,a)))};return r(e)}_addEssentialThemes(){Mt.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}))}};q();import{createHash as Ia}from"node:crypto";var ur="src/**/*.{ts,tsx,js,jsx,mjs,cjs}",Wt=/\/\*[\s\S]*?\*\//g,na=/(^|\s)\/\/.*$/gm,ra=/<!--[\s\S]*?-->/g,oa=/(?:from\s*|import\s*\(\s*|require\s*\(\s*)['"]next\/font(?:\/[^'"]*)?['"]/g,sa=/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)['"]@fontsource(?:-variable)?\/[^'"]*['"]/g,aa=/@import\s+(?:url\(\s*)?['"]?@fontsource(?:-variable)?\/[^'";)]*/g,cr=/@font-face\b/g,lr="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.",ia={"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). ${lr}`},fontsource:{message:`imports an @fontsource package: the framework ships the fonts the theme names (preloaded, inline @font-face, hashed /fonts/ files). Remove the import. ${lr}`},"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 ca(n,e){let t=n;for(let r of e)t=t.replace(r,(o,s)=>{let a=typeof s=="string"?s:"";return a+o.slice(a.length).replace(/[^\n]/g," ")});return t}var la=(n,e)=>n.slice(0,e).split(`
|
|
326
|
+
`).length;function ua(n){let e=[];for(let{file:t,content:r}of n){if(/\.generated\.[a-z]+$/.test(t))continue;let o=t.endsWith(".css"),s=t.endsWith(".html"),a=ca(r,s?[ra,Wt]:o?[Wt]:[Wt,na]),i=o?[["fontsource",aa],["font-face",cr]]:s?[["font-face",cr]]:[["next-font",oa],["fontsource",sa]];for(let[c,l]of i)for(let u of a.matchAll(l))e.push({file:t,line:la(a,u.index),rule:c})}return e}function pr(n){let e=ua(n);if(e.length===0)return;let t=e.map(({file:r,line:o,rule:s})=>` ${r}:${o} ${ia[s].message}`);throw B("dndev-fonts",`the app loads fonts itself; the framework font plan is the one way:
|
|
327
|
+
${t.join(`
|
|
328
|
+
`)}`,"configuration-error")}import{brotliDecompressSync as pa}from"node:zlib";var dr="aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ",da={"sans-serif":{locals:["Arial","Liberation Sans"],azAvgWidth:934.5116279069767,unitsPerEm:2048},serif:{locals:["Times New Roman","Liberation Serif"],azAvgWidth:854.3953488372093,unitsPerEm:2048}},fa={0:"cmap",1:"head",2:"hhea",3:"hmtx"},ga=63,fr=48,ma=2001684018;function gr(n,e){let t=0;for(let r=0;r<5;r++){let o=n[e+r];if(t=t*128+(o&127),(o&128)===0)return[t,e+r+1]}throw new Error("woff2: invalid UIntBase128")}function ha(n){if(n.length<fr||n.readUInt32BE(0)!==ma)throw new Error("woff2: bad signature");if(n.readUInt32BE(4)===1953784678)throw new Error("woff2: font collections are not supported");let e=n.readUInt16BE(12),t=n.readUInt32BE(20),r=fr,o=[];for(let c=0;c<e;c++){let l=n[r++],u=l&63,p=l>>6,d=fa[u]??`#${u}`;u===ga&&(d=n.toString("latin1",r,r+4),r+=4);let f;[f,r]=gr(n,r);let g=u===10||u===11?p!==3:p!==0,v=f;g&&([v,r]=gr(n,r)),o.push({tag:d,length:v,transformed:g})}let s=pa(n.subarray(r,r+t)),a=new Map,i=0;for(let{tag:c,length:l,transformed:u}of o)a.set(c,{data:s.subarray(i,i+l),transformed:u}),i+=l;return a}function va(n){let e=n.readUInt16BE(2),t=[];for(let u=0;u<e;u++){let p=4+u*8,d=n.readUInt16BE(p),f=n.readUInt16BE(p+2),g=n.readUInt32BE(p+4);(d===0||d===3&&(f===1||f===10))&&t.push({offset:g,format:n.readUInt16BE(g)})}let r=t.find(u=>u.format===12)??t.find(u=>u.format===4);if(!r)throw new Error("font: no Unicode cmap (format 4 or 12)");let o=r.offset;if(r.format===12){let u=n.readUInt32BE(o+12);return p=>{for(let d=0;d<u;d++){let f=o+16+d*12,g=n.readUInt32BE(f),v=n.readUInt32BE(f+4);if(p>=g&&p<=v)return n.readUInt32BE(f+8)+(p-g)}return 0}}let s=n.readUInt16BE(o+6)/2,a=o+14,i=a+s*2+2,c=i+s*2,l=c+s*2;return u=>{for(let p=0;p<s;p++){if(u>n.readUInt16BE(a+p*2))continue;let d=n.readUInt16BE(i+p*2);if(u<d)return 0;let f=n.readInt16BE(c+p*2),g=l+p*2,v=n.readUInt16BE(g);if(v===0)return u+f&65535;let h=n.readUInt16BE(g+v+(u-d)*2);return h===0?0:h+f&65535}return 0}}function hr(n){let e=ha(n);for(let l of["head","hhea","hmtx","cmap"])if(!e.has(l))throw new Error(`font: missing ${l} table`);let t=e.get("head").data,r=e.get("hhea").data,o=e.get("hmtx"),s=r.readUInt16BE(34),a=l=>{let u=Math.min(l,s-1);return o.transformed?o.data.readUInt16BE(1+u*2):o.data.readUInt16BE(u*4)},i=va(e.get("cmap").data),c=0;for(let l of dr){let u=i(l.codePointAt(0));if(u===0)throw new Error(`font: no glyph for '${l}'`);c+=a(u)}return{unitsPerEm:t.readUInt16BE(18),ascent:r.readInt16BE(4),descent:r.readInt16BE(6),lineGap:r.readInt16BE(8),azAvgWidth:c/dr.length}}var mr=n=>`${Math.abs(n*100).toFixed(2)}%`;function ft(n){return`${n} Fallback`}function vr({family:n,category:e,metrics:t}){let r=da[e];if(!r)throw new Error(`font fallback: unknown category '${e}'`);let{unitsPerEm:o,ascent:s,descent:a,lineGap:i,azAvgWidth:c}=t,l=c/o/(r.azAvgWidth/r.unitsPerEm),u=d=>mr(d/(o*l)),p=ft(n);return[`/* ${p}: ${r.locals[0]} size-matched to ${n} */`,"@font-face {",` font-family: '${p}';`,` src: ${r.locals.map(d=>`local('${d}')`).join(", ")};`,` ascent-override: ${u(s)};`,` descent-override: ${u(a)};`,` line-gap-override: ${u(i)};`,` size-adjust: ${mr(l)};`,"}"].join(`
|
|
329
|
+
`)}var ya=2001684018,gt=400;function ht(n){return n.trim().toLowerCase().replace(/\s+/g,"-")}function ba(n){let[e,t=e]=String(n).trim().split(/\s+/).map(Number);return[e,t]}var mt=([n,e],t)=>t>=n&&t<=e;function yr(n,e){if(e.some(s=>mt(s,n)))return n;let t=[...new Set(e.flat())],r=(s=1/0)=>t.filter(a=>a>n&&a<=s).sort((a,i)=>a-i)[0],o=()=>t.filter(s=>s<n).sort((s,a)=>a-s)[0];return n>=400&&n<=500?r(500)??o()??r():n<400?o()??r():r()??o()}function ge(n){return B("dndev-fonts",n,"configuration-error")}function wa(n){return!!(n&&n.length>=4&&n.readUInt32BE(0)===ya)}var Ea=n=>n==="serif"?"serif":"sans-serif";function Sa({family:n,packageName:e,dir:t,pathResolver:r}){let o=r.readSync(r.resolvePath("metadata.json",t),{format:"json"}),s=r.readSync(r.resolvePath("unicode.json",t),{format:"json"});if(!o||!s)throw ge(`${e}: metadata.json or unicode.json missing in ${t} (not a fontsource package?).`);if(String(o.family).toLowerCase()!==n.toLowerCase())throw ge(`${e} is the family '${o.family}', the font stack names '${n}'. Write the family as the package names it.`);let a=e.startsWith("@fontsource-variable/"),i=o.variable?.wght;if(a&&!i)throw ge(`${e} has no wght axis: use @fontsource/${o.id} (static weights).`);let c=a?[Number(i.min),Number(i.max)]:null,l=["normal","italic"].filter(g=>o.styles.includes(g)),u=(g,v,h)=>r.resolvePath(`files/${o.id}-${g}-${a?"wght":v}-${h}.woff2`,t),p=g=>{if(!r.pathExists(g))throw ge(`${e}: font file missing: ${g}`);return g},d=o.subsets.includes("latin")?"latin":o.defSubset,f=o.weights.reduce((g,v)=>Math.abs(v-gt)<Math.abs(g-gt)?v:g);return{family:n,kind:a?"variable":"static",category:Ea(o.category),label:e,provides:g=>a?mt(c,g):o.weights.includes(g),matchWeight:g=>yr(g,a?[c]:o.weights.map(v=>[v,v])),faces({weights:g,subsets:v}){let h=v.filter(A=>o.subsets.includes(A)),y=a?[`${c[0]} ${c[1]}`]:g.map(String),C=[];for(let A of h)for(let w of y)for(let _ of l)C.push({file:p(u(A,w,_)),weight:w,style:_,subset:A,unicodeRange:s[A]??null});return C},metricsFile:p(u(d,f,"normal"))}}function xa({family:n,config:e,pathResolver:t}){let r=`appConfig.fonts['${n}']`;if(e?.category!=="sans-serif"&&e?.category!=="serif")throw ge(`${r}.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 ge(`${r}.faces must list the family's woff2 files ({ file, weight, style?, unicodeRange?, subset? }).`);let o=e.faces.map((l,u)=>{let p=`${r}.faces[${u}]`;if(typeof l?.file!="string"||!l.file.endsWith(".woff2"))throw ge(`${p}.file must be a .woff2 path relative to the app root (e.g. 'src/assets/fonts/brand.woff2').`);let[d,f]=ba(l.weight);if(!Number.isFinite(d)||!Number.isFinite(f)||d>f)throw ge(`${p}.weight must be a weight (400) or a variable range ('300 600'). Got ${JSON.stringify(l.weight)}.`);let g=l.style??"normal";if(g!=="normal"&&g!=="italic")throw ge(`${p}.style must be 'normal' or 'italic'.`);let v=t.resolveAppPath(l.file),h=t.pathExists(v)?t.readSync(v,{format:"buffer"}):null;if(!h)throw ge(`${p}.file: ${l.file} does not exist.`);if(!wa(h))throw ge(`${p}.file: ${l.file} is not a woff2 font.`);return{file:v,weight:d===f?String(d):`${d} ${f}`,range:[d,f],style:g,subset:l.subset??null,unicodeRange:l.unicodeRange??null}}),s=o.filter(l=>l.style==="normal"),a=s.filter(l=>l.unicodeRange===null),i=({range:l})=>mt(l,gt)?0:Math.min(...l.map(u=>Math.abs(u-gt))),c=[...a.length>0?a:s].sort((l,u)=>i(l)-i(u))[0];if(!c)throw ge(`${r}.faces has no normal-style face: the size-matched fallback face is measured on one.`);return{family:n,kind:"local",category:e.category,label:r,provides:l=>s.some(u=>mt(u.range,l)),matchWeight:l=>yr(l,s.map(u=>u.range)),faces:()=>o.map(({range:l,...u})=>u),metricsFile:c.file}}function $a(n,e,t){if(!e)return null;let r=t.resolvePackage(`${n}/package.json`,e);return r?t.getDirname(r):null}function br(n,{appFonts:e={},appRoot:t,uiRoot:r,pathResolver:o}){let s=Object.keys(e).find(i=>i.toLowerCase()===n.toLowerCase());if(s)return xa({family:n,config:e[s],pathResolver:o});let a=ht(n);for(let i of[t,r])for(let c of[`@fontsource-variable/${a}`,`@fontsource/${a}`]){let l=$a(c,i,o);if(l)return Sa({family:n,packageName:c,dir:l,pathResolver:o})}return null}var Vt=Object.freeze({body:"--font-family",headline:"--font-headline",mono:"--font-mono"}),Pa="--font-weight-",Ee=":root",Ra="@donotdev/components/styles",Ca=/\/\*[\s\S]*?\*\//g,_a=/([^{}]+)\{([^{}]*)\}/g,Aa=/^(?::root|html|:where\(:root\))$/,Na=/^(?::root|html)?\.([a-z][\w-]*)$/i,Jt=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/,wr={normal:400,bold:700};function qt(n){let e=[],t=0,r="",o=0;for(let s=0;s<n.length;s++){let a=n[s];r?a===r&&(r=""):a==='"'||a==="'"?r=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(n.slice(o,s)),o=s+1)}return e.push(n.slice(o)),e.map(s=>s.trim()).filter(Boolean)}function ka(n){return n.replace(/^['"]|['"]$/g,"").trim()}function Da(n){if(Aa.test(n))return Ee;let e=Na.exec(n);return e?e[1]:null}function Er(n,e=""){let t=new Map,r=n.replace(Ca,"");for(let[,o,s]of r.matchAll(_a)){let a=o.split(";").pop(),i=qt(a).map(Da).filter(c=>c!==null);if(i.length!==0)for(let c of s.split(";")){let l=c.indexOf(":");if(l===-1)continue;let u=c.slice(0,l).trim();if(!u.startsWith("--"))continue;let p=c.slice(l+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(u,{value:p,source:e,scope:d})}}return t}function Ta(n){let e=new Map;for(let t of n)for(let[r,o]of t){e.has(r)||e.set(r,new Map);for(let[s,a]of o)e.get(r).set(s,a)}return e}function Sr({source:n,scope:e}){return`${n||"CSS"} (${e===Ee?":root":`.${e}`})`}function Gt(n,e,t,r){let o=[];for(let s of qt(e)){let a=Jt.exec(s);if(!a){o.push(ka(s));continue}let[,i,c]=a;if(t.has(i)&&!r.has(i))o.push(...Gt(i,t.get(i).value,t,new Set([...r,i])));else if(c!==void 0)o.push(...Gt(n,c,t,r));else throw B("dndev-fonts",`${n}: ${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. ${n}: Manrope, 'Manrope Fallback', sans-serif; (a next/font or other runtime class variable is not a framework font).`,"configuration-error")}return o}function Oa(n,e){let t=new Set,r=n;for(;e.has(r)&&!t.has(r);){t.add(r);let o=e.get(r),s=qt(o.value),a=s[0]&&Jt.exec(s[0]);if(!a)return{token:r,declaration:o,entries:s};r=a[1]}return null}function Ht(n,e,t=new Set){let{value:r}=e.get(n),o=Jt.exec(r);if(o){let[,a,i]=o;if(e.has(a)&&!t.has(a))return Ht(a,e,new Set([...t,n]));if(i!==void 0)return Ht(n,new Map([[n,{value:i.trim()}]]),t)}if(r in wr)return wr[r];let s=Number(r);if(Number.isFinite(s)&&s>=1&&s<=1e3)return s;throw B("dndev-fonts",`${n}: ${r} 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 xr({frameworkCss:n,appCss:e}){if(typeof n!="string"||!Array.isArray(e))throw new Error("resolveThemeFonts: frameworkCss (string) and appCss ({ file, css }[]) are required (ThemeDiscovery fontCss)");let t=Er(n,Ra),r=Ta(e.map(({file:s,css:a})=>Er(a,s)));return[Ee,...new Set([...t.keys(),...r.keys()])].filter((s,a,i)=>i.indexOf(s)===a).map(s=>{let a=new Map([...t.get(Ee)??[],...r.get(Ee)??[],...s===Ee?[]:t.get(s)??[],...s===Ee?[]:r.get(s)??[]]),i={};for(let[l,u]of Object.entries(Vt))a.has(u)&&(i[l]={stack:Gt(u,a.get(u).value,a,new Set([u])),origin:Oa(u,a)});let c=new Map;for(let l of a.keys())l.startsWith(Pa)&&c.set(l,{weight:Ht(l,a),declaration:a.get(l)});return{scope:s,roles:i,weights:c}})}var Pr="optional",Yt=$e.fonts,Zt=`/${Yt}`,Fa=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),Ma=new Set(xn.map(n=>n.toLowerCase())),La="--font-weight-normal",ja="--font-weight-bold",Kt=n=>B("dndev-fonts",n,"configuration-error");function $r(n){let e=$n[n];return e&&e.length>0?[...e]:["latin"]}var Rr=n=>`'${n.replace(/'/g,"\\'")}'`;function za(n,e){return["@font-face{",`font-family:${Rr(n)};`,`font-style:${e.style};`,`font-weight:${e.weight};`,`font-display:${Pr};`,`src:url(${e.url}) format('woff2');`,e.unicodeRange?`unicode-range:${e.unicodeRange};`:"","}"].join("")}function Ba(n,e){let[t,r=t]=n.split(" ").map(Number);return e>=t&&e<=r}async function Cr({fontCss:n,appFonts:e={},languages:t,publicPath:r="",indexHtml:o=null,pathResolver:s}){if(!n||typeof n.framework!="string"||!Array.isArray(n.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=s.getAppRoot(),i=await s.findFiles(a,ur);pr([...n.app.map(({file:m,css:$})=>({file:m,content:$})),...i.map(m=>({file:s.getRelativePath(m),content:s.readSync(m,{format:"text"})??""})),...o===null?[]:[{file:"index.html",content:o}]]);let c=xr({frameworkCss:n.framework,appCss:n.app}),l=s.resolveFrameworkPackage("@donotdev/ui"),u=new Map,p=m=>{let $=m.toLowerCase();return u.has($)||u.set($,br(m,{appFonts:e,appRoot:a,uiRoot:l,pathResolver:s})),u.get($)},d=new Map,f=new Map,g=new Map,v=new Map,h=new Map;for(let{scope:m,roles:$,weights:U}of c)for(let[E,M]of Object.entries($)){if(!M)continue;let L=Vt[E];M.stack.forEach((z,K)=>{let W=z.toLowerCase();if(Fa.has(W)||Ma.has(W))return;let Z=/^(.+) fallback$/i.exec(z)?.[1];if(Z&&p(Z))return;let P=p(z);if(!P){d.has(W)||d.set(W,{family:z,token:L,scope:m});return}v.has(W)||v.set(W,{source:P,weights:new Set,scopes:new Set});let I=v.get(W);I.scopes.add(m);for(let{weight:J}of U.values())I.weights.add(P.matchWeight(J)),!P.provides(J)&&!g.has(`${W}:${J}`)&&g.set(`${W}:${J}`,`${P.family}: weight ${J} not in source, browser-synthesized`);if(K!==0)return;h.set(W,P);let F=M.origin,G=F?F.entries[1]:M.stack[1],Q=ft(z);if(G&&G.replace(/^['"]|['"]$/g,"").trim().toLowerCase()===Q.toLowerCase())return;let X=F?.declaration??{source:"",scope:m},te=F?.token??L,xe=`${X.source}|${te}|${X.value??z}`;if(f.has(xe))return;let S=F?F.entries:[z],T=`${te}: ${[S[0],Rr(Q),...S.slice(1)].join(", ")};`;f.set(xe,{location:Sr(X),declared:te,family:z,expected:Q,line:T})})}let y=[];for(let{family:m,token:$,scope:U}of d.values())y.push(`${$} (${U===Ee?":root":`.${U}`}) names '${m}', which nothing provides: install @fontsource-variable/${ht(m)} or @fontsource/${ht(m)} in the app, declare its woff2 files in appConfig.fonts['${m}'], or use a system family (SYSTEM_FONT_FAMILIES) or a generic one (sans-serif, serif, monospace, system-ui\u2026).`);for(let{location:m,declared:$,family:U,expected:E,line:M}of f.values())y.push(`${m}: ${$} lacks '${E}' right after '${U}' (the size-matched fallback face: no layout shift, no flicker). Write:
|
|
330
|
+
${M}`);if(y.length>0)throw Kt(`the theme fonts cannot ship:
|
|
331
|
+
- ${y.join(`
|
|
332
|
+
- `)}`);let C=[...new Set(["latin",...t.flatMap($r)])],A=new Map,w=m=>{if(!A.has(m)){let $=s.readSync(m,{format:"buffer"}),U=Ia("sha256").update($).digest("hex").slice(0,8),E=s.getBasename(m).replace(/\.woff2$/,"");A.set(m,`${r}${Zt}/${E}.${U}.woff2`)}return A.get(m)},_=[],N=[];for(let[m,{source:$,weights:U}]of v){let E=$.faces({weights:[...U].sort((M,L)=>M-L),subsets:C}).map(M=>({...M,family:$.family,url:w(M.file)}));N.push(...E),_.push({family:$.family,kind:$.kind,category:$.category,source:$.label,fallback:h.has(m)?ft($.family):null})}let k=[...h.values()].map(m=>{try{return vr({family:m.family,category:m.category,metrics:hr(s.readSync(m.metricsFile,{format:"buffer"}))})}catch($){throw Kt(`'${m.family}' (${m.label}): cannot measure ${m.metricsFile} for its fallback face (${$.message}). Its core file must be a woff2 with the Latin letters a-z.`)}}),x=c.find(({scope:m})=>m===Ee),D=[["body",La],["headline",ja]].flatMap(([m,$])=>{let U=x.roles[m]?.stack[0];if(!U||!v.has(U.toLowerCase()))return[];let E=x.weights.get($)?.weight;if(E===void 0)throw Kt(`${$} is not defined: the framework tokens (@donotdev/components/styles) define it.`);let{source:M}=v.get(U.toLowerCase());return[{family:M.family,weight:M.matchWeight(E)}]}),R={};for(let m of t){let $=$r(m),U=[];for(let{family:E,weight:M}of D)for(let L of N){if(L.family!==E||L.style!=="normal"||!Ba(L.weight,M))continue;(L.subset===null?L.unicodeRange===null:$.includes(L.subset))&&!U.includes(L.url)&&U.push(L.url)}R[m]=U}return{display:Pr,families:_,files:[...A].map(([m,$])=>({source:m,url:$})),css:[...N.map(m=>za(m.family,m)),...k].join(`
|
|
333
|
+
`),preloads:R,notices:[...g.values()]}}function _r(n,{pathResolver:e,publicPath:t=""}){let r=e.resolveAppPath(`public/${Yt}`);e.removeSync(r),e.ensureDirSync(r);let o=`${t}${Zt}/`;for(let{source:s,url:a}of n.files){if(!a.startsWith(o))throw new Error(`[dndev-fonts] writeFontPlan: ${a} is not under ${o}`);e.copySync(s,e.resolvePath(a.slice(o.length),r),{overwrite:!0})}return r}Y();var Ar=/[ \t]*<link rel="preload" as="font"[^>]*>\n?/g,Ua=n=>n.replace(/&/g,"&").replace(/"/g,""");function Nr(n,e){let t=Ut(e).map(({attributes:s})=>` <link ${Object.entries(s).map(([a,i])=>`${a}="${Ua(i)}"`).join(" ")}>
|
|
334
|
+
`).join(""),r=n.search(Ar);if(r===-1){if(e.length===0)return n;let s=n.indexOf(`<style id="${dt}"`);if(s===-1)throw new Error(`[dndev-fonts] Prerender: the SPA shell has no font tags (<style id="${dt}">): keep the font plugin (createVitePlugins) before the prerender.`);let a=n.lastIndexOf(`
|
|
335
|
+
`,s)+1;return n.slice(0,a)+t+n.slice(a)}let o=n.replace(Ar,"");return o.slice(0,r)+t+o.slice(r)}function kr(){let n=null;return{set(e){n=e},get(){if(!n)throw new Error("[dndev-fonts] The font plan is not built yet (the font plugin builds it in buildStart).");return n}}}function Dr({appConfig:n,i18nStore:e,fontPlan:t,debug:r=!1}){if(!e||!t)throw new Error("[dndev] createViteFontPlugin: options.i18nStore and options.fontPlan are required (createVitePlugins passes the i18n plugin's createI18nStore and createFontPlanStore).");let o=H("fonts",r,!1),s="",a=null;async function i(){let c=O.getInstance(),{supportedLanguages:l,fallbackLanguage:u}=await e.ready(),{fontCss:p}=await new Oe(null,c,{debug:r}).discoverThemes(!0),d=c.resolveAppPath("index.html"),f=await Cr({fontCss:p,appFonts:n?.fonts,languages:l,publicPath:s,indexHtml:c.pathExists(d)?c.readSync(d,{format:"text"}):null,pathResolver:c});_r(f,{pathResolver:c,publicPath:s}),t.set(f),a=l.includes(u)?u:l[0],o.debug(`Font plan: ${f.families.map(({family:g})=>g).join(", ")||"system fonts only"} (${f.files.length} files)`);for(let g of f.notices)o.info(`\u{1F524} ${g}`)}return{name:"dndev-fonts",configResolved(c){s=c.base&&c.base!=="/"?c.base.replace(/\/$/,""):""},async buildStart(){await i()},configureServer(c){c.watcher.on("change",async l=>{if(!l.endsWith(".css"))return;let u=t.get();try{await i()}catch(d){c.config.logger.error(d.message),c.ws.send({type:"error",err:{message:d.message,stack:""}});return}let p=t.get();(p.css!==u.css||JSON.stringify(p.preloads)!==JSON.stringify(u.preloads))&&c.ws.send({type:"full-reload"})})},transformIndexHtml:{order:"pre",handler(){let c=t.get();return[...Ut(c.preloads[a]).map(({tag:l,attributes:u})=>({tag:l,attrs:u,injectTo:"head"})),...c.css?[{tag:"style",attrs:{id:dt},children:c.css,injectTo:"head"}]:[]]}}}}q();import{existsSync as Mr,readFileSync as Lr,writeFileSync as Wa}from"node:fs";import{join as jr}from"node:path";var Ga="/(.*)",Qt=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"]),Ha=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'"]}),Tr=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),zr=Object.freeze({"@donotdev/supabase":{"script-src":["https://challenges.cloudflare.com"],"connect-src":["https://*.supabase.co","wss://*.supabase.co"],"frame-src":["https://challenges.cloudflare.com"]},"@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"]}}),Va=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=()"}]),Ja=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),qa=31536e3,Ka=86400,Br=3600,Or=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(n=>`/assets/:path*.${n}`),"next-export":["/_next/static/:path*"],next:[]}),Ya=`/${$e.fonts}/:path*`,Za=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),Xa=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${Br}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),Ir=Object.freeze(["csp","cache"]);function vt(n,e=!1){return`public, max-age=${n}${e?", immutable":""}`}function Xt(n,e){return{source:n,headers:[{key:"Cache-Control",value:e}]}}var Fr=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),Qa=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function ei(n,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${n}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!Fr.includes(e)&&!Qa.test(e))throw new Error(`[dndev] appConfig.headers.csp['${n}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${Fr.join(" ")} or a hash like 'sha256-<base64>').`)}function ti(n){if(n===void 0)return{csp:{},cache:[]};if(!n||typeof n!="object"||Array.isArray(n))throw new Error("[dndev] appConfig.headers must be an object.");for(let r of Object.keys(n))if(!Ir.includes(r))throw new Error(`[dndev] appConfig.headers.${r} is not a header option (allowed: ${Ir.join(", ")}).`);let e=n.csp??{};for(let[r,o]of Object.entries(e)){if(!Qt.includes(r))throw new Error(`[dndev] appConfig.headers.csp['${r}'] is not a CSP directive the framework merges (allowed: ${Qt.join(", ")}).`);if(!Array.isArray(o))throw new Error(`[dndev] appConfig.headers.csp['${r}'] must be an array of sources.`);for(let s of o)ei(r,s)}let t=n.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let r of t){if(typeof r?.source!="string"||!r.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(r?.source)}).`);if(!Number.isInteger(r.maxAge)||r.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${r.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(r.maxAge)}).`)}return{csp:e,cache:t}}function ni({csp:n={},providers:e=[],target:t}){if(!(t in Tr))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...Qt.map(o=>{let s=[...o==="script-src"?Tr[t]:Ha[o]??[],...e.flatMap(c=>zr[c]?.[o]??[]),...n[o]??[]],a=[...new Set(s)],i=a.length>1?a.filter(c=>c!=="'none'"):a;return i.length>0?`${o} ${i.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function Ur({appConfig:n,target:e,providers:t=[],pwa:r=!1}){if(!(e in Or))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:o,cache:s}=ti(n?.headers),a=[{key:"Content-Security-Policy",value:ni({csp:o,providers:t,target:e})},...n?.seo===!1?[Ja]:[],...Va].map(i=>({...i}));return[{source:Ga,headers:a},...[...Or[e],Ya].map(i=>Xt(i,vt(qa,!0))),...Za.map(i=>Xt(`/:path*.${i}`,vt(Ka))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:vt(Br)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...r?Xa.map(i=>({source:i.source,headers:i.headers.map(c=>({...c}))})):[],...s.map(i=>Xt(i.source,vt(i.maxAge,i.immutable===!0)))]}function Wr(n){let e=jr(n,"package.json");if(!Mr(e))return[];let t=JSON.parse(Lr(e,"utf8")),r={...t.dependencies,...t.devDependencies};return Object.keys(zr).filter(o=>!!r[o])}function ri(n){let e=jr(n,"vercel.json");if(!Mr(e))return null;try{return{path:e,config:JSON.parse(Lr(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function Gr({appRoot:n,rules:e,ci:t,logger:r}){let o=ri(n);if(!o)return"absent";if(JSON.stringify(o.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${o.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 s=`${JSON.stringify({...o.config,headers:e},null,2)}
|
|
336
|
+
`;return Wa(o.path,s),r?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function Hr({appConfig:n,pwa:e,debug:t,verbose:r}){let o=H("host-headers",t,r);return{name:"dndev-host-headers",configResolved(s){Gr({appRoot:s.root,rules:Ur({appConfig:n,target:"vite",providers:Wr(s.root),pwa:e===!0}),ci:!!(process.env.CI||process.env.VERCEL),logger:o})}}}q();q();Y();q();function oi(n){if(!n)return[];let e=O.getInstance(),t=new Set;try{let r=e.resolvePackage("@donotdev/core",n);if(!r)return[];let o=e.getDirname(e.getDirname(r)),s;try{s=e.readdirSync(o)}catch{return[]}for(let a of s)try{let i=e.resolvePath(`${a}/package.json`,o),c=e.readSync(i,{format:"json"});if(!c?.peerDependenciesMeta)continue;for(let[l,u]of Object.entries(c.peerDependenciesMeta))u?.optional&&t.add(l)}catch{}}catch{}return Array.from(t)}function si(n){if(!n)return[];let e=O.getInstance();try{let t=e.resolvePath("package.json",n),r=e.readSync(t,{format:"json"});if(!r)return[];let o=new Set;if(r.peerDependenciesMeta)for(let[s,a]of Object.entries(r.peerDependenciesMeta))a?.optional&&o.add(s);if(r.optionalDependencies)for(let s of Object.keys(r.optionalDependencies))o.add(s);return Array.from(o)}catch{return[]}}function ai(n){let e=Pe.optionalFeatures||[],t=oi(n),r=si(n);return[...new Set([...e,...t,...r])]}function ii(n){let e=O.getInstance();try{let t=e.resolvePath("package.json",n),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 ci(n,e,t){let r=new Set,o=t.resolvePackage("@donotdev/core",n);if(!o)return r;let s=t.getDirname(t.getDirname(o));for(let a of e){if(!a.startsWith("@donotdev/"))continue;let i=t.resolvePath(`${a.slice(10)}/package.json`,s);if(!t.pathExists(i))continue;let c=t.readSync(i,{format:"json"});for(let l of Object.keys(c?.dependencies||{}))r.add(l)}return r}function li(n,e,t){if(t.resolvePackage(n,e||void 0))return!0;let r=n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0],o=e;for(let s=0;s<10;s++){let a=t.resolvePath(`node_modules/${r}`,o);if(t.pathExists(a))return!0;let i=t.getDirname(o);if(i===o)break;o=i}return!1}function yt(n){let e=ai(n),t=[],r=[],o=O.getInstance(),s=ii(n),a=ci(n,s,o);for(let i of e)i.startsWith("@donotdev/")?s.has(i)?r.push(i):t.push(i):(s.has(i)||a.has(i))&&li(i,n,o)?r.push(i):t.push(i);return{missing:t,installed:r}}var bt=class extends fe{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,o]of Object.entries(e)){for(let s of Object.keys(o))t.includes(s)||delete o[s];Object.keys(o).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 o=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${o.eager.length}, lazy: ${o.lazy.length}, framework eager: ${o.framework?.eager?.length||0}, framework lazy: ${o.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let s=at("i18n"),a=o.eager||[],i=o.lazy||[],c=(this.options.additionalPaths||[]).map(P=>{let I=P.endsWith(".json")?P:`${P}/*_*.json`;return this.pathResolver.resolveAppPath(I)});c.length>0&&this.logger.debug(`Additional i18n paths configured: ${c.join(", ")}`);let l=o.framework?.eager||[],u=o.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${l.join(", ")}, framework lazy: ${u.join(", ")}`),l.length===0&&u.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=(P,I)=>{let F=this.pathResolver.normalizePath(P),G=this.pathResolver.normalizePath(I);return F.startsWith(G)?F.slice(G.length+1):F},g=a.map(P=>f(P,t)),h=[...i,...c].map(P=>f(P,t)),y=l.map(P=>f(P,r)),C=u.map(P=>f(P,r)),A={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},w=await this.pathResolver._globWithNormalization(g,A),_=await this.pathResolver._globWithNormalization(h,A),N={...s,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:r,ignore:s.ignore?.filter(P=>P!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${r}, ignore: ${JSON.stringify(N.ignore)}`);let k=await this.pathResolver._globWithNormalization(y,N),x=await this.pathResolver._globWithNormalization(C,N);this.logger.debug(`Found ${w.length} eager, ${_.length} lazy, ${k.length} framework eager, ${x.length} framework lazy files`),k.length>0?this.logger.debug(`Framework eager files (first 3): ${k.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${l.join(", ")}`),x.length>0?this.logger.debug(`Framework lazy files (first 3): ${x.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${u.join(", ")}`);let D=[...new Set([...w,..._,...k,...x])],R=new Set([...w,...k]),m={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:$}=yt(t),U=new Set($.filter(P=>P.startsWith("@donotdev/")).map(P=>P.replace("@donotdev/","")));U.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...U].join(", ")}] (packages not installed)`);let E=new Map,M=[...k,...x];for(let P of M){let I=this._processTranslationFile(P,k.includes(P),t);if(I){if(U.has(I.namespace))continue;let F=`${I.namespace}_${I.language}`;E.set(F,I),m.allNamespaces.add(I.namespace),m.supportedLanguages.add(I.language),k.includes(P)&&m.eagerNamespaces.add(I.namespace)}}let L=new Set;for(let P of D){if(M.includes(P))continue;let I=this._processTranslationFile(P,R.has(P),t);if(I){let{namespace:F,language:G,importPath:Q,content:X}=I,te=`${I.namespace}_${I.language}`;if(E.has(te)){let xe=E.get(te);I.content=this._mergeTranslations(xe.content,X)}m.allNamespaces.add(F),m.supportedLanguages.add(G),L.add(G),R.has(P)&&m.eagerNamespaces.add(F),m.mapping[F]||(m.mapping[F]={}),m.mapping[F][G]=Q,I.content&&(m.content[F]||(m.content[F]={}),m.content[F][G]=I.content),m.files.push({path:P,relativePath:this.pathResolver.getRelativePath(P),namespace:F,language:G,eager:R.has(P),size:I.content?JSON.stringify(I.content).length:0})}}for(let[P,I]of E){let F=P.lastIndexOf("_"),G=P.slice(0,F),Q=P.slice(F+1);L.size>0&&!L.has(Q)||(!m.mapping[G]||!m.mapping[G][Q])&&(m.mapping[G]||(m.mapping[G]={}),m.mapping[G][Q]=I.importPath,m.content[G]||(m.content[G]={}),m.content[G][Q]=I.content,m.files.push({path:I.absolutePath,relativePath:this.pathResolver.getRelativePath(I.absolutePath),namespace:G,language:Q,eager:m.eagerNamespaces.has(G),size:I.content?JSON.stringify(I.content).length:0}))}let z=L.size>0?[...L].sort():[this.options.fallbackLanguage],K=this._getLanguageAllowlist(),W=z;if(K){let P=z.filter(F=>K.includes(F));W=P.length>0?P:[this.options.fallbackLanguage],this._restrictByLanguage(m.mapping,W),this._restrictByLanguage(m.content,W),m.files=m.files.filter(F=>W.includes(F.language));let I=new Set(Object.keys(m.mapping));m.allNamespaces=new Set([...m.allNamespaces].filter(F=>I.has(F))),m.eagerNamespaces=new Set([...m.eagerNamespaces].filter(F=>I.has(F))),this.logger.debug(`I18n restricted by i18n.only [${K.join(", ")}]: languages [${W.join(", ")}], namespaces ${I.size}`)}let Z=[...new Set(W.map(Lt))];return{mapping:m.mapping,content:m.content,eagerNamespaces:[...m.eagerNamespaces].sort(),allNamespaces:[...m.allNamespaces].sort(),supportedLanguages:W,fallbackLanguage:this.options.fallbackLanguage,flagCodes:Z,files:m.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[Lt(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 o=Date.now()-t;return this.logger.debug(`Discovery completed in ${o}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 o=e.split("/").pop()||e.split("\\").pop()||"",s,a,i=o.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${o}`),null;if([,s,a]=i,!s||!a)return this.logger.debug(`Invalid namespace or language in file: ${o}`),null;let l="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),u;try{if(u=this.pathResolver.readSync(e,{format:"json"}),!u)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:s,language:a,importPath:l,absolutePath:e,content:u}}_mergeTranslations(e,t){let r={...e};for(let[o,s]of Object.entries(t))typeof s=="object"&&s!==null&&!Array.isArray(s)?r[o]=this._mergeTranslations(r[o]||{},s):r[o]=s;return r}};var Vr={isEmpty:n=>!n.mapping||Object.keys(n.mapping).length===0,generateModule:(n,e,t="i18n",r=!1)=>{let{mapping:o,eagerNamespaces:s,supportedLanguages:a,fallbackLanguage:i,stats:c,content:l={},files:u=[]}=n,p=r?Object.keys(l):s,d={};for(let y of p)l[y]&&(d[y]=l[y]);let f=[...new Set([...s,...Object.keys(l)])],g={mapping:o,languages:a,eager:r?f:s,fallback:i,content:d,storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:c?.totalFiles||0,totalNamespaces:c?.totalNamespaces||0,totalLanguages:c?.totalLanguages||0,eagerNamespaces:c?.eagerNamespaces||0,generatedAt:new Date().toISOString()},debug:e},v=[];if(!r)for(let[y,C]of Object.entries(o)){if(s.includes(y))continue;let A=[];for(let w of Object.keys(C))A.push(` '${w}': () => import('virtual:i18n-lazy-${y}-${w}')`);A.length>0&&v.push(` '${y}': {
|
|
337
|
+
${A.join(`,
|
|
332
338
|
`)}
|
|
333
|
-
}`)}let
|
|
334
|
-
${
|
|
339
|
+
}`)}let h=v.length>0?`{
|
|
340
|
+
${v.join(`,
|
|
335
341
|
`)}
|
|
336
|
-
}`:"{}";return`// ${
|
|
342
|
+
}`:"{}";return`// ${V.i18n} - Generated by @donotdev/config
|
|
337
343
|
// Generated at: ${new Date().toISOString()}
|
|
338
344
|
|
|
339
345
|
// ===== STATIC EXPORTS =====
|
|
340
346
|
export const I18N_CONFIG = ${JSON.stringify(g,null,2)};
|
|
341
|
-
export const LANGUAGES = ${JSON.stringify(
|
|
342
|
-
export const FALLBACK_LANGUAGE = '${
|
|
347
|
+
export const LANGUAGES = ${JSON.stringify(a,null,2)};
|
|
348
|
+
export const FALLBACK_LANGUAGE = '${i}';
|
|
343
349
|
export const EAGER_NAMESPACES = ${JSON.stringify(s,null,2)};
|
|
344
350
|
|
|
345
351
|
const i18nPluginConfig = I18N_CONFIG;
|
|
346
352
|
|
|
347
353
|
// ===== LAZY LOADERS =====
|
|
348
354
|
// Static import() calls \u2014 Vite bundles each JSON as a separate async chunk
|
|
349
|
-
const _lazyLoaders = ${
|
|
355
|
+
const _lazyLoaders = ${h};
|
|
350
356
|
|
|
351
357
|
// ============================================================================
|
|
352
358
|
// INITIALIZE DnDev CONFIG FOUNDATION
|
|
@@ -364,7 +370,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
364
370
|
}
|
|
365
371
|
|
|
366
372
|
// Add i18n plugin configuration + lazy loaders (functions, not serializable)
|
|
367
|
-
globalThis._DNDEV_CONFIG_.${
|
|
373
|
+
globalThis._DNDEV_CONFIG_.${re[t]} = {
|
|
368
374
|
...i18nPluginConfig,
|
|
369
375
|
loaders: _lazyLoaders,
|
|
370
376
|
};
|
|
@@ -458,7 +464,7 @@ export default {
|
|
|
458
464
|
getInlineContent,
|
|
459
465
|
};
|
|
460
466
|
|
|
461
|
-
`},generateEmpty:(n,e,t,r="i18n")=>{let o=t.fallbackLanguage||"en",s={mapping:{},languages:[o],eager:[],fallback:o,content:{},storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:0,totalNamespaces:0,totalLanguages:1,eagerNamespaces:0,generatedAt:new Date().toISOString()},debug:e};return`// ${
|
|
467
|
+
`},generateEmpty:(n,e,t,r="i18n")=>{let o=t.fallbackLanguage||"en",s={mapping:{},languages:[o],eager:[],fallback:o,content:{},storage:{type:"localStorage",prefix:"dndev_i18n_",ttl:1440*60*1e3,encryption:!1,maxSize:5*1024*1024},performance:{cacheSize:1e3,errorCacheTTL:300*1e3},manifest:{totalFiles:0,totalNamespaces:0,totalLanguages:1,eagerNamespaces:0,generatedAt:new Date().toISOString()},debug:e};return`// ${V.i18n} - Empty i18n configuration
|
|
462
468
|
// No translation files found - using fallback configuration
|
|
463
469
|
// Generated at: ${new Date().toISOString()}
|
|
464
470
|
|
|
@@ -476,7 +482,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
476
482
|
};
|
|
477
483
|
}
|
|
478
484
|
|
|
479
|
-
globalThis._DNDEV_CONFIG_.${
|
|
485
|
+
globalThis._DNDEV_CONFIG_.${re[r]} = i18nPluginConfig;
|
|
480
486
|
}
|
|
481
487
|
|
|
482
488
|
// Placeholder functions
|
|
@@ -525,7 +531,7 @@ export default {
|
|
|
525
531
|
getFallbackLanguage,
|
|
526
532
|
getInlineContent,
|
|
527
533
|
};
|
|
528
|
-
`},generateInspection:(n,e,t)=>{let{mapping:r,supportedLanguages:o,eagerNamespaces:s,files:
|
|
534
|
+
`},generateInspection:(n,e,t)=>{let{mapping:r,supportedLanguages:o,eagerNamespaces:s,files:a}=n;return!r||Object.keys(r).length===0?`/**
|
|
529
535
|
* Generated i18n Discovery Results
|
|
530
536
|
* Generated at: ${new Date().toISOString()}
|
|
531
537
|
* Status: No translations found
|
|
@@ -562,7 +568,7 @@ export const supportedLanguages = ${JSON.stringify(o,null,2)};
|
|
|
562
568
|
|
|
563
569
|
export const eagerNamespaces = ${JSON.stringify(s,null,2)};
|
|
564
570
|
|
|
565
|
-
export const translationFiles = ${JSON.stringify(
|
|
571
|
+
export const translationFiles = ${JSON.stringify(a.map(i=>({namespace:i.namespace,language:i.language,path:i.relativePath,eager:i.eager,size:i.size})),null,2)};
|
|
566
572
|
|
|
567
573
|
export const i18nManifest = {
|
|
568
574
|
totalNamespaces: ${n.stats?.totalNamespaces||0},
|
|
@@ -578,37 +584,37 @@ export default {
|
|
|
578
584
|
files: translationFiles,
|
|
579
585
|
manifest: i18nManifest,
|
|
580
586
|
};
|
|
581
|
-
`},generateManifest:n=>({namespaces:n.stats?.totalNamespaces||0,languages:n.stats?.totalLanguages||0,fallbackLanguage:n.fallbackLanguage,eagerNamespaces:n.stats?.eagerNamespaces||0,platform:"vite",timestamp:Date.now()}),logConfig:n=>{},logStats:(n,e,t)=>{let r=n.supportedLanguages||[],o=Object.keys(n.mapping||{}).filter(s=>s!=="default").length||0;t&&t.info(`${e} I18n: ${r.length} languages, ${o} namespaces`)}},
|
|
587
|
+
`},generateManifest:n=>({namespaces:n.stats?.totalNamespaces||0,languages:n.stats?.totalLanguages||0,fallbackLanguage:n.fallbackLanguage,eagerNamespaces:n.stats?.eagerNamespaces||0,platform:"vite",timestamp:Date.now()}),logConfig:n=>{},logStats:(n,e,t)=>{let r=n.supportedLanguages||[],o=Object.keys(n.mapping||{}).filter(s=>s!=="default").length||0;t&&t.info(`${e} I18n: ${r.length} languages, ${o} namespaces`)}},ui=[n=>n.endsWith(".json")&&n.includes("locale"),n=>/[a-z]+_[a-z]{2}\.json$/i.test(n),n=>n.includes("/locales/")&&n.endsWith(".json")];function Jr(){let n=null,e,t=new Promise(r=>{e=r});return{set(r){n=r,e(r)},ready:()=>t,get(){if(!n)throw new Error("[dndev] i18n discovery unavailable: the i18n plugin did not run (see the error above).");return n}}}function pi(n={}){return{...ze.discovery,fallbackLanguage:n.fallbackLanguage||"en",...n}}function qr({i18nStore:n,...e}={}){if(!n)throw new Error("[dndev] createViteI18nPlugin: options.i18nStore is required (createVitePlugins passes it, createI18nStore).");let t=!1,r=new Map;function o(c){r.clear();let{content:l,eagerNamespaces:u}=c;for(let[p,d]of Object.entries(l||{}))if(!u.includes(p))for(let[f,g]of Object.entries(d))r.set(`virtual:i18n-lazy-${p}-${f}`,g)}let s={...Vr,generateModule:(c,l,u)=>(t||o(c),Vr.generateModule(c,l,u,t))};return[we({pluginName:"dndev-vite-i18n-discovery",icon:"\u{1F310}",virtualModuleId:V.i18n,DiscoveryClass:bt,discoveryMethod:"discoverTranslations",filePatterns:ui,templates:s,manifestFileName:ve.manifests.i18n,configKey:"i18n",discoveryOptions:pi(e)})({...e,discoveryStore:n,hmrSmartDetection:!1}),{name:"dndev-i18n-lazy-loader",enforce:"pre",configResolved(c){t=c.command==="serve"},async buildStart(){if(t)return;let c=await n.ready();o(c)},resolveId(c){if(!t&&c.startsWith("virtual:i18n-lazy-"))return"\0"+c},load(c){if(!t&&c.startsWith("\0virtual:i18n-lazy-")){let l=c.slice(1),u=r.get(l);return`export default ${JSON.stringify(u||{})};`}}}]}Y();function Kr(n,e){return e.some(t=>n===t||n.startsWith(t+"/"))}function Yr(n={}){let e=[],t="",r="";return{name:"dndev-optional-dep-resolver",enforce:"pre",config(o){let s={name:"dndev-optional-dep-esbuild",setup(i){i.onResolve({filter:/^[@a-z]/,namespace:"file"},c=>Kr(c.path,e)?{path:r,external:!1}:null)}};return{optimizeDeps:{esbuildOptions:{plugins:[...o.optimizeDeps?.esbuildOptions?.plugins||[],s]}}}},configResolved(o){let s=O.getInstance(),a=s.getAppRoot();if(e=yt(a).missing,t=s.getEmptyModulePath(),r=s.getEmptyCjsModulePath(),e.length>0){let c=o.optimizeDeps?.exclude||[];o.optimizeDeps.exclude=[...c,...e]}n.debug&&e.length>0},resolveId(o){return Kr(o,e)?{id:t,syntheticNamedExports:!0}:null}}}function en(n){return!n||typeof n!="string"?null:n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0]}function di(n){return!n||typeof n!="string"?!1:!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("\\")&&!n.startsWith("\0")}function fi(n,e){if(!n||!e||!e.getRepoRoot())return!1;let r=n;n.startsWith("@fs/")&&(r=n.slice(4));let o=e.resolveRepoPath("packages"),s=e.normalizePath(r);return o&&s.startsWith(o)}function gi(n,e){if(!n||!e)return null;let t=en(n);if(!t)return null;let r=e.resolveAppPath(`node_modules/${t}`);return e.pathExists(r)?e.resolveAppPath(`node_modules/${n}`):null}function Zr(n,e,t){return!di(n)||!fi(e,t)?null:gi(n,t)}Y();function Xr(n={}){let{debug:e=!1,verbose:t=!0}=n,r=H("peer-dependency-resolver",e,t);return{name:"dndev-peer-dependency-resolver",enforce:"pre",configResolved(o){let s=O.getInstance(),a=s.getAppRoot();if(!a){r.warn("App root not set, peer dependency resolution may fail");return}this.pathResolver=s,this.appRoot=a},resolveId(o,s){if(!s||!this.appRoot||!this.pathResolver)return null;if(Zr(o,s,this.pathResolver)){let i=en(o),c=this.pathResolver.resolveAppPath(`node_modules/${o}`),l=this.pathResolver.resolveAppPath(`node_modules/${i}`);return this.pathResolver.pathExists(l)?o===i?((e||t)&&r.debug(`[PeerDeps] Resolving bare import "${o}" from app's node_modules: ${l}`),l):((e||t)&&r.debug(`[PeerDeps] Resolving subpath "${o}" from app's node_modules: ${c}`),c):(e&&r.debug(`[PeerDeps] Package directory not found: ${l}, skipping resolution`),null)}return null}}}Y();Y();function mi(n){return n?String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"):""}function hi(n){return n?String(n).replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"):""}function vi(n){return n.replace(/<meta\s+name="description"[^>]*\/?>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="twitter:[^"]*"[^>]*\/?>\s*/gi,"").replace(/<link\s+rel="canonical"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="robots"[^>]*\/?>\s*/gi,"").replace(/<meta\s+name="keywords"[^>]*\/?>\s*/gi,"")}var yi="data-rh";function Qr({tag:n,attributes:e,text:t}){if(n==="title")return`<title>${mi(t)}</title>`;let r=Object.entries(e).map(([s,a])=>`${s}="${hi(a)}"`).join(" "),o=`<${n} ${r} ${yi}="true"`;return n==="script"?`${o}>${t??""}</script>`:`${o} />`}function eo(n,{tags:e,headScript:t,headElementId:r}){if(!/<title>[^<]*<\/title>/.test(n)||!n.includes("</head>"))throw new Error("[dndev] Prerender: dist/index.html has no <title> or </head>. Keep both in the app's index.html.");let o=e.filter(a=>a.tag==="title").map(Qr),s=e.filter(a=>a.tag!=="title").map(a=>` ${Qr(a)}`);return s.push(` <script type="application/json" id="${r}">${t}</script>`),vi(n).replace(/<title>[^<]*<\/title>/,()=>o.join("")).replace("</head>",()=>`${s.join(`
|
|
582
588
|
`)}
|
|
583
|
-
</head>`)}function
|
|
584
|
-
`];n.description&&
|
|
585
|
-
`);for(let u of r){let p=
|
|
586
|
-
`),
|
|
587
|
-
`),u.date&&
|
|
588
|
-
`),
|
|
589
|
-
`)}import
|
|
590
|
-
`)}function
|
|
591
|
-
`)}discoverBlogPosts(){return this.appRoot?
|
|
592
|
-
<title><![CDATA[${
|
|
593
|
-
<link>${
|
|
594
|
-
<guid>${
|
|
595
|
-
<description><![CDATA[${
|
|
589
|
+
</head>`)}function to(n){if(n==="/")return"/index.html";let e=[];for(let t of n.split("/").slice(1)){let r;try{r=decodeURIComponent(t)}catch{return null}if(!r||r==="."||r===".."||/[/\\\0]/.test(r))return null;e.push(r)}return`/${e.join("/")}.html`}function bi(n){return!n.includes(":")&&!n.includes("*")}var wt=class{constructor(e){this.routes=e.routes||[],this.outDir=e.outDir,this.debug=e.debug||!1,this.logger=e.logger}expandRoutes(e){let{routes:t,errors:r}=e;if(t.length===0)return r.length>0&&this.logger.warn("Route manifest unavailable. Using explicit routes only."),this.routes.filter(s=>!s.includes("*"));let o=new Set;for(let s of this.routes)if(s.includes("*")){let a=s.replace(/\/?\*.*$/,"");for(let i of t){let c=i.path||i;c.startsWith(a)&&bi(c)&&!this.isAuthProtected(i)&&o.add(c)}if(this.debug){let i=[...o].filter(c=>c.startsWith(a));this.logger.debug(` Pattern "${s}" matched ${i.length} route(s)`)}}else{let a=t.find(i=>(i.path||i)===s);a&&this.isAuthProtected(a)?this.logger.warn(` Skipping auth-protected route: ${s}`):(o.add(s),!a&&this.debug&&this.logger.debug(` Route "${s}" not in manifest, including anyway`))}return[...o]}isAuthProtected(e){return typeof e=="string"?!1:e.auth?.required===!0}async writeOutputFile(e,t){let r=O.getInstance(),o=r.resolvePath(e.replace(/^\//,""),this.outDir);if(r.ensureDirSync(r.getDirname(o)),!r.writeSync(o,t,{overwrite:!0}))throw new Error(`writeSync returned false for ${o}`)}};q();function ke(n){return n.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function wi(n,e){let t=e&&Object.hasOwn(e,n.collection)?e[n.collection]:void 0;if(!t)throw new Error(`[dndev] Route "${n.path}" reads "${n.collection}" records but no read schema was given for that collection (entityReadSchemas of the app's entities).`);return t}async function Ei(n,e,t,r){let o=ke(n.path),s=o[0];if(o.length!==1||!n.collection||!s)throw new Error(`[dndev] Cannot list the public URLs of route "${n.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 "${n.path}" lists "${n.collection}" records but no server CRUD reader was given.`);let a=wi(n,r),i;try{i=await e.query(n.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3},a)}catch(l){let u=l?.details?.originalMessage??l?.message??String(l);throw new Error(`[dndev] Route "${n.path}" could not read its public "${n.collection}" records (signed-out visitor: RLS / Security Rules must allow it): ${u}`,{cause:l})}let c=[];for(let l of i.items){let u=l[s];typeof u!="string"&&typeof u!="number"||c.push({param:s,value:String(u),record:l})}return c}async function We(n,e,t,r){let o=[];for(let s of n){if(ke(s.path).length===0){o.push({route:s,path:s.path});continue}for(let{param:a,value:i,record:c}of await Ei(s,e,t,r))o.push({route:s,path:s.path.replace(`:${a}`,encodeURIComponent(i)),record:c})}return o}function no(n,e){return n.startsWith("/")?`${e}${n}`:n}function tn(n){return typeof n=="object"&&n!==null&&"collection"in n&&"fields"in n}function ro(n,e,t){for(let r of Object.values(n))if(tn(r)&&r.collection===e)return r;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 oo(n,e,t){let r=Object.create(null);for(let o of e)!o.collection||Object.hasOwn(r,o.collection)||(r[o.collection]=t(ro(n,o.collection,o.path)).get);return Object.freeze(r)}function so(n,e){let{route:t,value:r,language:o,baseUrl:s,siteName:a,type:i}=e,c=ro(e.entities,t.collection,t.path),l=e.deriveEntitySeo(c,n,{t:e.translate([c.namespace,"crud"]),locale:o}),u=ke(t.path)[0],p=t.path.replace(`:${u}`,encodeURIComponent(r)),d=y=>e.languageUrl(y,o,s,e.routing,e.trailingSlash),f=d(p),g=l.title?`${l.title} | ${a}`:a,v=no(l.image||e.defaultImage,s),h=i==="product"?e.buildProductJsonLd({...l,images:[...new Set(l.images.map(y=>no(y,s)))]},f):null;return{url:f,title:g,...l.description&&{description:l.description},image:v,type:i,jsonLd:h,breadcrumb:l.title?e.buildBreadcrumbJsonLd({pathname:p,routes:e.routes,siteName:a,t:e.translate([e.defaultNamespace]),defaultNs:e.defaultNamespace,pageUrl:d,lastName:l.title}):null}}Y();function ao(n){return(e,t)=>{let r=e.indexOf(":"),o=n[e.slice(0,r)];for(let s of e.slice(r+1).split("."))o=o&&typeof o=="object"&&s in o?o[s]:void 0;return typeof o=="string"?o:t?.defaultValue??e}}var Si="dndev",xi="crud",$i="entity-";function io(n,e,t){return e?n?.[e]?.[t]:void 0}function Re(n){return typeof n=="string"&&n.trim()!==""?n.trim():void 0}function co(n){return n?.metaExport||n?.meta||{}}function Pi(n,{siteName:e,defaultNamespace:t,t:r}){let o=co(n),{title:s,pageTitle:a}=nr({meta:o,ns:o.namespace||null,defaultNs:t,t:r,siteName:e});return a??s}function Ri(n,e,t){let r=co(n),o=r.seo||{};if(o.description===null)return;let s=io(e,r.namespace,t);return Re(o.description)??Re(s?.description)}function lo(n){let{siteName:e,description:t,baseUrl:r,sitemapRoutes:o,routes:s,blogPosts:a=[],blogPath:i="/blog",translations:c,language:l,defaultNamespace:u}=n,p=io(c,Si,l)?.seo,d=Re(p?.llmsPages),f=Re(p?.llmsBlog);if(!d||!f)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${l}".`);if(!u)throw new Error('[dndev] llms.txt: getLlmsTxtSource needs options.defaultNamespace (appConfig.seo.defaultNamespace, else "home").');let g=new Map(s.map(w=>[w.path,w])),v={siteName:e,defaultNamespace:u,t:ao(Object.fromEntries(Object.entries(c||{}).map(([w,_])=>[w,_?.[l]])))},h=new Map(a.map(w=>[`${i}/${w.slug}`,w])),y=o.map(({path:w,collection:_})=>{let N=h.get(w);if(N)return{path:w,title:N.title,...Re(N.description)&&{description:Re(N.description)},section:f};if(_)return{path:w,collection:_};let k=g.get(w);if(!k&&w===i)return{path:w,title:f};let x=Ri(k,c,l);return{path:w,title:Pi(k,v),...x&&{description:x}}}),C={},A={};for(let[w,_]of Object.entries(c||{})){if(w===xi&&_?.[l]&&(A[w]=_[l]),!w.startsWith($i))continue;_?.[l]&&(A[w]=_[l]);let N=Re(_?.[l]?.namePlural);N&&(C[w]=N)}return{name:e,...Re(t)&&{summary:Re(t)},baseUrl:r,pagesHeading:d,routes:y,entityHeadings:C,language:l,translations:A}}function uo(n={}){let{siteName:e,baseUrl:t,blogPosts:r=[],blogPath:o="/blog",appRoot:s,logger:a}=n;if(!e||!t)return null;if(r.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=O.getInstance(),c=s?i.resolvePath("src/content/blog",s):null;if(!c||!i.pathExists(c))return null;let l=[`# ${e}
|
|
590
|
+
`];n.description&&l.push(`> ${n.description}
|
|
591
|
+
`);for(let u of r){let p=i.resolvePath(`${u.slug}_en.md`,c);try{let d=i.readSync(p,{format:"text"});if(!d)continue;let f=d.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),g=`${t}${o}/${u.slug}`;l.push(`## ${u.title}
|
|
592
|
+
`),l.push(`Source: ${g}
|
|
593
|
+
`),u.date&&l.push(`Date: ${u.date}
|
|
594
|
+
`),l.push(f.trim()),l.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${u.slug}`)}}return l.join(`
|
|
595
|
+
`)}import Ci from"i18next";function Xe(n){return n.replace(/\s+/g," ").trim()}function po(n){let e=[`# ${Xe(n.name)}`,""];n.summary&&e.push(`> ${Xe(n.summary)}`,"");for(let t of n.sections)if(t.links.length!==0){e.push(`## ${Xe(t.heading)}`,"");for(let r of t.links){let o=`- [${Xe(r.title)}](${r.url})`;e.push(r.description?`${o}: ${Xe(r.description)}`:o)}e.push("")}return e.join(`
|
|
596
|
+
`)}function _i(n){let e=new Map;for(let t of Object.values(n))tn(t)&&e.set(t.collection,t);return e}function Ai(n,e){let t=Ci.createInstance();return t.init({lng:n,resources:{[n]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),r=>t.getFixedT(n,[r,"crud"])}async function fo(n){let{crud:e,readSchemas:t,deriveEntitySeo:r,hiddenStatuses:o,formatTrailingSlash:s,trailingSlash:a}=n,i=_i(n.entities),c,l=new Map,u=p=>{let d=l.get(p);return d||(d={heading:p,links:[]},l.set(p,d)),d};u(n.pagesHeading);for(let{route:p,path:d,record:f}of await We(n.routes,e,o,t)){let g=`${n.baseUrl}${s(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).`);u(p.section??n.pagesHeading).links.push({title:p.title,url:g,...p.description&&{description:p.description}});continue}let v=i.get(p.collection);if(!v)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 h=p.section??(v.namespace?n.entityHeadings[v.namespace]:void 0);if(!h)throw new Error(`[dndev] llms.txt: no heading for route "${p.path}". Add "namePlural" to the ${v.namespace??`entity-${v.name.toLowerCase()}`} translations.`);if(!c){if(!n.language||!n.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");c=Ai(n.language,n.translations)}let y=r(v,f,{t:c(v.namespace),locale:n.language});u(h).links.push({title:y.title||n.name,url:g,...y.description&&{description:y.description}})}return po({name:n.name,...n.summary&&{summary:n.summary},sections:[...l.values()]})}var go=Object.freeze([{dependency:"@donotdev/supabase",module:"@donotdev/supabase/server",env:["SUPABASE_URL","SUPABASE_PUBLIC_KEY"],create:(n,[e,t])=>new n.SupabasePublicReader(n.createPublicServerClient(e,t))},{dependency:"@donotdev/firebase",module:"@donotdev/firebase/public",env:["FIREBASE_API_KEY","FIREBASE_PROJECT_ID"],create:(n,[e,t])=>new n.FirestorePublicReader(n.createPublicServerFirestore({apiKey:e,projectId:t}))}]);function mo(n){return go.find(({dependency:e})=>n(e))}var ho=go.map(({dependency:n})=>n).join(", ");function ie(n){return n?n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}function vo(n){return n?n.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}function Et(n,e){return(n||e||"").trim().replace(/\/+$/,"")}var wo=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function Ni(n,e){let t;try{let r=new URL(n);if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Error;t=r.hostname}catch{throw new Error(`[dndev] SEO: base URL "${n}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(wo.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: deploy build with base URL "${n}". 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 ki="DNDEV_DEPLOY";function Eo(n=process.env){let e=n.CI;return n[ki]==="1"||n.VERCEL==="1"||e!==void 0&&e!==""&&e!=="false"&&e!=="0"}var yo=new Set;function Qe(n,e,t,r=process.env){if(Eo(r)){if(!n)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 Ni(n,e),n}let o=s=>{yo.has(s)||(yo.add(s),t.warn(s))};return!n||!Di(n)?(o(`[dndev] Local build without a usable ${e}${n?` ("${n}")`:""}: no sitemap.xml, llms.txt, robots.txt, rss.xml, canonical URLs or record pages. Set ${e} to build them.`),null):(Ti(n)||o(`[dndev] Local build: sitemap.xml, llms.txt, canonical URLs and record pages carry ${n} (${e}). A deploy build (dndev deploy, Vercel, CI) needs the production URL.`),n)}async function St(n,e,t,r=process.env){try{return await e(),!0}catch(o){if(be(o))throw o;let s=`${n.join(", ")} not written: ${o.message}`;if(Eo(r))throw B("dndev-seo",`${s}. A deploy build publishes every SEO file.`,"seo-generation-failed",{files:n});return t.warn(`[dndev] Local build: ${s} (a deploy build fails on it).`),!1}}function Di(n){try{let{protocol:e}=new URL(n);return e==="https:"||e==="http:"}catch{return!1}}function Ti(n){let{hostname:e}=new URL(n);return!wo.has(e)&&!e.endsWith(".localhost")}var nn=Object.freeze(["/api"]),bo=new Set(["/404","/not-found","/500","/error"]);function xt(n){return n.auth&&n.auth!==!1||bo.has(n.path)||bo.has(n.meta?.route)?!1:n.meta?.seo?.noindex!==!0}function sn(n){return typeof n.path=="string"&&n.path.split("/").includes("*")}function So(n){if(!(typeof n.path!="string"||!n.path.includes(":"))&&xt(n))return n.meta?.entity||void 0}function xo(n){if(typeof n.path!="string"||n.path.includes("*")||ke(n.path).length!==1)return null;let e=So(n);return e?{path:n.path,collection:e}:null}function Oi(n=[]){return{totalRoutes:n.length,publicRoutes:n.filter(e=>!e.auth||e.auth===!1).length,protectedRoutes:n.filter(e=>e.auth&&e.auth.required).length}}var Ge=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:r=!0,baseUrl:o,siteName:s,crawlDelay:a=1,aiCrawlers:i="recommended",routes:c={},...l}=e;if(!o||!s)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:r,baseUrl:o,siteName:s,crawlDelay:a,aiCrawlers:i,routes:c,blogPath:"/blog",...l},this.appRoot=l.appRoot||null,this.logger=H("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,r){let o={routes:e.routes||[],baseUrl:this.options.baseUrl,siteName:this.options.siteName},s={robotsTxt:null,rss:null,manifest:null};return this.options.generateRobotsTxt&&(s.robotsTxt=await this.generateRobotsTxt(o,t)),r.length>0&&(s.rss=await this.generateRSSFeed(r,t)),s.manifest=await this.generateManifest(o,t),s}async generateRobotsTxt(e,t){let r=this.options.shellPath?[...nn,this.options.shellPath]:nn,o=this.generateRobotsTxtContent({disallowedPaths:r,sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",o),{fileName:"robots.txt",content:o,disallowedPaths:r.length}}getSitemapRoutes(e,t=[]){let{blogPath:r}=this.options,o=[];for(let s of e||[]){if(!xt(s)||typeof s.path!="string"||sn(s))continue;let a=s.path===r||s.path.startsWith(`${r}/`);if(!(t.length>0&&a))if(s.path.includes(":")){if(a)continue;let i=So(s);o.push({path:s.path,...i&&{collection:i}})}else o.push({path:s.path})}if(t.length>0){o.push({path:r,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let s of t)o.push({path:`${r}/${s.slug}`,priority:.6,changeFrequency:"monthly",...s.date&&{lastModified:s.date}})}return o}async generateManifest(e,t){let r={...Oi(e.routes),baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()},o=JSON.stringify(r,null,2);return await t("seo-manifest.json",o),{fileName:"seo-manifest.json",content:o,manifest:r}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:r=nn,sitemap:o,crawlDelay:s}=e,a=l=>l?l==="*"?"*":l.startsWith("/")?l:`/${l}`:"/",i=["User-agent: *",...r.map(l=>`Disallow: ${a(l)}`),...t.map(l=>`Allow: ${a(l)}`)];s&&i.push(`Crawl-delay: ${s}`),o&&i.push(`Sitemap: ${o}`);let c=this.options.aiCrawlers;return c&&c!==!1&&(i.push(""),i.push(...Ii(c))),i.join(`
|
|
597
|
+
`)}discoverBlogPosts(){return this.appRoot?ct(this.appRoot,this.logger):[]}async generateRSSFeed(e,t){let r=e.map(s=>` <item>
|
|
598
|
+
<title><![CDATA[${vo(s.title)}]]></title>
|
|
599
|
+
<link>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}/${ie(s.slug)}</link>
|
|
600
|
+
<guid>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}/${ie(s.slug)}</guid>
|
|
601
|
+
<description><![CDATA[${vo(s.description)}]]></description>
|
|
596
602
|
<pubDate>${s.date?new Date(s.date).toUTCString():""}</pubDate>${s.tags.length?`
|
|
597
|
-
<category>${
|
|
598
|
-
<enclosure url="${
|
|
603
|
+
<category>${ie(s.tags.join(", "))}</category>`:""}${s.image?`
|
|
604
|
+
<enclosure url="${ie(this.options.baseUrl)}${ie(s.image)}" type="image/png" length="0"/>`:""}
|
|
599
605
|
</item>`).join(`
|
|
600
606
|
`),o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
601
607
|
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
602
608
|
<channel>
|
|
603
|
-
<title>${
|
|
604
|
-
<link>${
|
|
605
|
-
<description>${
|
|
609
|
+
<title>${ie(this.options.siteName)}</title>
|
|
610
|
+
<link>${ie(this.options.baseUrl)}${ie(this.options.blogPath)}</link>
|
|
611
|
+
<description>${ie(this.options.siteName)} Blog</description>
|
|
606
612
|
<language>en</language>
|
|
607
|
-
<atom:link href="${
|
|
613
|
+
<atom:link href="${ie(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
608
614
|
${r}
|
|
609
615
|
</channel>
|
|
610
|
-
</rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}},
|
|
611
|
-
`)}var Qe=!1,zn=["react-server","module","node","import","default"];function fi(n){let e=[];for(let t of n){let r=Mn(t);r&&e.push({route:r,type:t.meta?.seo?.type??"website"})}return e}function gi(n,e,t){let r={...n?.dependencies,...n?.devDependencies},o=An(a=>!!r[a]);if(!o)throw new Error(`[dndev] ${t.join(", ")} list published records, but the app's backend provider has no public reader (supported: ${Nn}). Mark these pages \`seo: { noindex: true }\`.`);let s=o.env.map(a=>`VITE_${a}`),i=s.map(a=>e[a]);if(i.some(a=>!a))throw new Error(`[dndev] Set ${s.join(" and ")}: the build lists the published records of ${t.join(", ")} (record pages, sitemap.xml, llms.txt).`);return{module:o.module,create:a=>o.create(a,i)}}function mi(n,e,t=process.env){if(!Xe(n||null,"VITE_APP_URL",e,t))return null;if(n.endsWith("/")||n!==n.trim())throw new Error(`[dndev] VITE_APP_URL "${n}" must have no trailing slash or spaces: the browser builds canonical URLs from it as is.`);return n}function hi(n){let e=new Map;return{query(t,r,o){let s=JSON.stringify([t,r]);return e.has(s)||e.set(s,n.query(t,r,o)),e.get(s)}}}async function vi({staticRoutes:n,records:e,crud:t,readSchemas:r,core:o,entities:s,translate:i,routing:a,baseUrl:l,siteName:c,hreflang:u,defaultNamespace:p,defaultImage:d,shellHtml:f}){let g=u&&o.isMultilingual(a.languages),w=[],m=[],h=new Set,P=(R,E)=>{let S=g?o.languageUrls(R,l,a,Qe):null;for(let C of a.languages){let k=o.localizePath(R,C,a),y=hn(k);if(!y||h.has(y)){m.push(k);continue}h.add(y);let T=o.languageUrl(R,C,l,a,Qe),$=E(C,T),v=[...$.tags,...o.siteHeadTags({url:l?T:null,siteName:c,alternates:S,defaultLanguage:a.defaultLanguage})];w.push({file:y,html:mn(f,{tags:v,headScript:o.jsonScriptText({url:T,...$}),headElementId:o.PRERENDERED_HEAD_ELEMENT_ID})})}};for(let R of n){let E=R.meta??{},S=E.namespace||null;P(R.path,(C,k)=>({tags:o.routeHeadTags(o.routeSeo({meta:E,ns:S,defaultNs:p,t:i([S??p],C),siteName:c,baseUrl:l,url:k,defaultImage:d,authOnly:!!R.auth}),{siteName:c,baseUrl:l}),breadcrumb:!1}))}if(e.length>0){let R=new Map(e.map(({route:S,type:C})=>[S.path,C])),E=await ze(e.map(({route:S})=>S),t,o.HIDDEN_STATUSES,r);for(let{route:S,path:C,record:k}of E){let y=String(k[$e(S.path)[0]]);P(C,T=>{let $=wn(k,{route:S,value:y,language:T,routing:a,baseUrl:l,trailingSlash:Qe,siteName:c,defaultImage:d,type:R.get(S.path),entities:s,translate:v=>i(v,T),deriveEntitySeo:o.deriveEntitySeo,buildProductJsonLd:o.buildProductJsonLd,buildBreadcrumbJsonLd:o.buildBreadcrumbJsonLd,languageUrl:o.languageUrl});return{tags:o.recordHeadTags($),breadcrumb:$.breadcrumb!==null}})}}return{pages:w,skipped:m}}async function yi({routes:n,blogPosts:e,generator:t,crud:r,readSchemas:o,core:s,entities:i,routing:a,baseUrl:l,siteName:c,siteDescription:u,translations:p,defaultNamespace:d,sitemap:f,llmsTxt:g}){let w=t.getSitemapRoutes(n,e),m=[];if(f){let h=await Ln(w,{baseUrl:l,routing:a,trailingSlash:Qe,crud:r,readSchemas:o,languageUrls:s.languageUrls,hiddenStatuses:s.HIDDEN_STATUSES});m.push({file:"/sitemap.xml",content:jn(h)})}if(g){let h=Rn({siteName:c,description:u,baseUrl:l,sitemapRoutes:w,routes:n,blogPosts:e,blogPath:t.options.blogPath,translations:p,language:a.defaultLanguage,defaultNamespace:d});m.push({file:"/llms.txt",content:await Cn({...h,trailingSlash:Qe,formatTrailingSlash:s.formatTrailingSlash,entities:i,crud:r,readSchemas:o,deriveEntitySeo:s.deriveEntitySeo,hiddenStatuses:s.HIDDEN_STATUSES})})}return m}async function vt(n,e,t){try{return await n.import(e)}catch(r){throw new Error(`[dndev] Build pages: cannot load "${e}" (${t}): ${r.message}`,{cause:r})}}async function Bn({appRoot:n,mode:e,manifestRoutes:t,blogPosts:r,staticRoutes:o,prerenderRecords:s,shellHtml:i,seo:a,loadI18n:l,pkg:c,write:u,logger:p}){if(!i)throw new Error("[dndev] Build pages: the build output has no index.html (the SPA shell).");if(await u(`/${nt}`,i),a.disabled)return{pages:0,listings:[]};let{createServer:d,loadEnv:f}=await import("vite"),g=f(e,n,"VITE_"),w=a.siteName,m=a.defaultNamespace||"home",h=Xe(ft(a.baseUrl,g.VITE_APP_URL)||null,"VITE_APP_URL",p)??"",R=(a.generateSitemap!==!1||a.llmsTxt!==!1)&&!!(h&&w),E=fi(t),S=s&&E.length>0?mi(g.VITE_APP_URL,p):null,C=S?E:[],k=E.length>0&&(C.length>0||R);if(o.length===0&&C.length===0&&!R)return{pages:0,listings:[]};if(!w)throw new Error("[dndev] Prerendered page titles end with the site name. Set appConfig.app.name (or appConfig.seo.siteName).");let y=null,T=E.map(({route:j})=>j.path);if(k){if(!{...c?.dependencies,...c?.devDependencies}.entities)throw new Error(`[dndev] ${T.join(", ")}: record pages derive their identity from the entity definition, but the app does not depend on an \`entities\` package. Add the entity to the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`);y=gi(c,g,T)}let $=S??g.VITE_APP_URL??"",v=await l(),G={languages:v.supportedLanguages,defaultLanguage:v.fallbackLanguage},A=await d({root:n,configFile:!1,envFile:!1,logLevel:"error",appType:"custom",server:{middlewareMode:!0,hmr:!1,ws:!1,watch:null},optimizeDeps:{noDiscovery:!0,include:[]},resolve:{conditions:zn},ssr:{resolve:{conditions:zn,externalConditions:["react-server"]}}}),L=globalThis._DNDEV_CONFIG_;globalThis._DNDEV_CONFIG_={...L,i18n:{languages:v.supportedLanguages,eager:v.eagerNamespaces,fallback:v.fallbackLanguage,content:v.content}};try{let j=A.environments.ssr.runner,z=await vt(j,"@donotdev/core/server","SEO helpers"),K=await vt(j,"@donotdev/core/rsc","translations"),X={},W,se;if(y){X=await vt(j,"entities","the entity definitions");let V=await vt(j,y.module,"the public reader");W=hi(y.create(V)),se=bn(X,E.map(({route:de})=>de),z.createSchemas)}let _=(V,de)=>K.useTranslation(V,{language:de}).t,{pages:O,skipped:F}=await vi({staticRoutes:o,records:C,crud:W,readSchemas:se,core:z,entities:X,translate:_,routing:G,baseUrl:$,siteName:w,hreflang:a.hreflang!==!1,defaultNamespace:m,defaultImage:a.defaultImage||He,shellHtml:i});for(let V of O)await u(V.file,V.html);F.length>0&&p.warn(`Pages left to the SPA shell (a static page serves the URL, or no file name can hold it): ${F.join(", ")}`);let B=R?await yi({routes:t,blogPosts:r,generator:new Be({baseUrl:h,siteName:w,appRoot:n}),crud:W,readSchemas:se,core:z,entities:X,routing:G,baseUrl:h,siteName:w,siteDescription:a.siteDescription,translations:v.content,defaultNamespace:m,sitemap:a.generateSitemap!==!1,llmsTxt:a.llmsTxt!==!1}):[];for(let{file:V,content:de}of B)await u(V,de);return{pages:O.length,listings:B.map(({file:V})=>V)}}finally{L===void 0?delete globalThis._DNDEV_CONFIG_:globalThis._DNDEV_CONFIG_=L,await A.close()}}function bi(n=!0){if(typeof n=="boolean")return n;throw new Error(`appConfig.prerenderRecords must be true or false. Got ${JSON.stringify(n)}.`)}function Un(n={}){let{routes:e="auto",prerenderRecords:t,seo:r={},i18nStore:o,debug:s,verbose:i,routeManifest:a}=n;if(!a||!o)throw new Error("[dndev] createVitePrerenderPlugin: options.routeManifest and options.i18nStore are required (createVitePlugins passes the route and i18n plugins', createRouteManifestStore / createI18nStore).");let l=e==="auto"&&bi(t),c=M("Prerender",s,i),u=D.getInstance(),p=null,d=!1,f=!1;return{name:"dndev-prerender",enforce:"post",applyToEnvironment(g){return g.name==="client"},configResolved(g){d=g.command==="build",p={outDir:g.build?.outDir||"dist",mode:g.mode}},buildStart(){f=!1},writeBundle(){f=!0},async closeBundle(){if(!f||!p||!d)return;let g=u.getAppRoot(),w=u.resolveAppPath(p.outDir),m=a.get(),h=m.routes,P=new dt({routes:Array.isArray(e)?e:[],debug:s,outDir:w,logger:c}),R=new Map(h.map(y=>[y.path,y])),S=(e==="auto"?[...new Set(Pr(h).filter(y=>!y.includes("*")))]:P.expandRoutes(m)).map(y=>R.get(y)??{path:y}),{pages:C,listings:k}=await Bn({appRoot:g,mode:p.mode,manifestRoutes:h,blogPosts:m.blogPosts,staticRoutes:S,prerenderRecords:l,shellHtml:u.readSync(u.resolvePath("index.html",w)),seo:r,loadI18n:async()=>o.get(),pkg:u.readSync(u.resolveAppPath("package.json"),{format:"json"}),write:(y,T)=>P.writeOutputFile(y,T),logger:c});C>0&&c.info(`Prerendered: ${C} pages`);for(let y of k)c.info(`\u{1F4C4} ${y.slice(1)}`)}}}import{VitePWA as wi}from"vite-plugin-pwa";var yt=class extends pe{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:r}=e,o=[...t,...r];this.logger.debug(`Processing ${o.length} PWA files`);let s=await this._analyzePWAFiles(o),i=[...s.filter(l=>l.type==="manifest"||l.type==="service-worker"),...s.filter(l=>l.type==="icon")],a=this._generatePWAManifest(i);return{assets:i,manifest:a,totalFiles:o.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 r of e){let o=typeof r=="string"?{absolutePath:r,relativePath:this.pathResolver.getRelativePath(r),fileName:r.split("/").pop()||"",extension:(r.split(".").pop()||"").toLowerCase()}:r,s=await this._analyzePWAAsset(o);s&&t.push(s)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let r=e.relativePath,o=e.fileName;return o==="manifest.json"?this._parseManifestFile(t,r):o.includes("service-worker")||o.includes("sw.")?this._parseServiceWorkerFile(t,r):this._isPWAIcon(o)?this._parseIconFile(e,r):null}_parseManifestFile(e,t){try{let r=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:r,size:typeof e=="string"?e.length:JSON.stringify(r).length}}catch(r){return this.logger.debug(`Failed to parse manifest: ${r.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let r=e.fileName,o=this._extractIconSize(r);return{type:"icon",path:t,size:o,format:e.extension,purpose:this._getIconPurpose(r)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(r=>e.includes(r))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(o=>o.type==="icon"),r=this._getDefaultManifest();return t.length>0&&(r.icons=t.map(o=>this.toManifestIcon(o))),r}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},r=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:r==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[r]||`image/${r}`,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 r=this._getWorkboxDefaults(t),o=t.backgroundSync!==!1&&t.backgroundSync,s=t.precacheManifest||[],i=JSON.stringify(s,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
616
|
+
</rss>`;return await t("rss.xml",o),{fileName:"rss.xml",content:o,postCount:e.length}}},rn=["GPTBot","Google-Extended","CCBot","ClaudeBot"],on=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Ii(n){let e=["# AI Crawler Management"];if(n==="block-all"){for(let t of[...rn,...on])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(n==="allow-all"){for(let t of[...rn,...on])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of rn)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of on)e.push(`User-agent: ${t}`,"Allow: /","");return e}function $t(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function $o(n,{baseUrl:e,routing:t,trailingSlash:r,crud:o,readSchemas:s,languageUrls:a,hiddenStatuses:i}){let c=[],l=(u,p)=>{let d=a(u,e,t,r),f=t.languages.length>1?{alternates:{languages:d}}:{};for(let g of t.languages)c.push({url:d[g],...p,...f})};for(let{route:u,path:p,record:d}of await We(n,o,i,s)){if(!d){l(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??(p==="/"?1:.8),...u.lastModified&&{lastModified:u.lastModified}});continue}let f=d.updatedAt instanceof Date?d.updatedAt.toISOString():d.updatedAt;l(p,{changeFrequency:u.changeFrequency??"weekly",priority:u.priority??.7,...typeof f=="string"&&{lastModified:f}})}return c}function Po(n){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${n.some(r=>r.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let r of n){t.push(" <url>",` <loc>${$t(r.url)}</loc>`);for(let[o,s]of Object.entries(r.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${$t(o)}" href="${$t(s)}" />`);r.lastModified&&t.push(` <lastmod>${$t(r.lastModified)}</lastmod>`),r.changeFrequency&&t.push(` <changefreq>${r.changeFrequency}</changefreq>`),r.priority!==void 0&&t.push(` <priority>${r.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
|
|
617
|
+
`)}var et=!1,Ro=["react-server","module","node","import","default"];function Fi(n){let e=[];for(let t of n){let r=xo(t);r&&e.push({route:r,type:t.meta?.seo?.type??"website"})}return e}function Mi(n,e,t){let r={...n?.dependencies,...n?.devDependencies},o=mo(i=>!!r[i]);if(!o)throw new Error(`[dndev] ${t.join(", ")} list published records, but the app's backend provider has no public reader (supported: ${ho}). Mark these pages \`seo: { noindex: true }\`.`);let s=o.env.map(i=>`VITE_${i}`),a=s.map(i=>e[i]);if(a.some(i=>!i))throw new Error(`[dndev] Set ${s.join(" and ")}: the build lists the published records of ${t.join(", ")} (record pages, sitemap.xml, llms.txt).`);return{module:o.module,create:i=>o.create(i,a)}}function Li(n,e,t=process.env){if(!Qe(n||null,"VITE_APP_URL",e,t))return null;if(n.endsWith("/")||n!==n.trim())throw new Error(`[dndev] VITE_APP_URL "${n}" must have no trailing slash or spaces: the browser builds canonical URLs from it as is.`);return n}function ji(n){let e=new Map;return{query(t,r,o){let s=JSON.stringify([t,r]);return e.has(s)||e.set(s,n.query(t,r,o)),e.get(s)}}}async function zi({staticRoutes:n,records:e,routes:t,crud:r,readSchemas:o,core:s,entities:a,translate:i,routing:c,baseUrl:l,siteName:u,hreflang:p,defaultNamespace:d,defaultImage:f,pageShell:g}){let v=p&&s.isMultilingual(c.languages),h=[],y=[],C=new Set,A=(w,_)=>{let N=v?s.languageUrls(w,l,c,et):null;for(let k of c.languages){let x=s.localizePath(w,k,c),D=to(x);if(!D||C.has(D)){y.push(x);continue}C.add(D);let R=s.languageUrl(w,k,l,c,et),m=_(k,R),$=[...m.tags,...s.siteHeadTags({url:l?R:null,siteName:u,alternates:N,defaultLanguage:c.defaultLanguage})];h.push({file:D,html:eo(g(k),{tags:$,headScript:s.jsonScriptText({url:R,...m}),headElementId:s.PRERENDERED_HEAD_ELEMENT_ID})})}};for(let w of n){let _=w.meta??{},N=_.namespace||null;A(w.path,(k,x)=>({tags:s.routeHeadTags(s.routeSeo({meta:_,ns:N,defaultNs:d,t:i([N??d],k),siteName:u,baseUrl:l,url:x,defaultImage:f,authOnly:!!w.auth}),{siteName:u,baseUrl:l}),breadcrumb:!1}))}if(e.length>0){let w=new Map(e.map(({route:N,type:k})=>[N.path,k])),_=await We(e.map(({route:N})=>N),r,s.HIDDEN_STATUSES,o);for(let{route:N,path:k,record:x}of _){let D=String(x[ke(N.path)[0]]);A(k,R=>{let m=so(x,{route:N,value:D,language:R,routing:c,baseUrl:l,trailingSlash:et,siteName:u,defaultImage:f,type:w.get(N.path),entities:a,translate:$=>i($,R),deriveEntitySeo:s.deriveEntitySeo,buildProductJsonLd:s.buildProductJsonLd,buildBreadcrumbJsonLd:s.buildBreadcrumbJsonLd,languageUrl:s.languageUrl,routes:t,defaultNamespace:d});return{tags:s.recordHeadTags(m),breadcrumb:m.breadcrumb!==null}})}}return{pages:h,skipped:y}}async function Bi({routes:n,blogPosts:e,generator:t,crud:r,readSchemas:o,core:s,entities:a,routing:i,baseUrl:c,siteName:l,siteDescription:u,translations:p,defaultNamespace:d,sitemap:f,llmsTxt:g}){let v=t.getSitemapRoutes(n,e),h=[];if(f){let y=await $o(v,{baseUrl:c,routing:i,trailingSlash:et,crud:r,readSchemas:o,languageUrls:s.languageUrls,hiddenStatuses:s.HIDDEN_STATUSES});h.push({file:"/sitemap.xml",content:Po(y)})}if(g){let y=lo({siteName:l,description:u,baseUrl:c,sitemapRoutes:v,routes:n,blogPosts:e,blogPath:t.options.blogPath,translations:p,language:i.defaultLanguage,defaultNamespace:d});h.push({file:"/llms.txt",content:await fo({...y,trailingSlash:et,formatTrailingSlash:s.formatTrailingSlash,entities:a,crud:r,readSchemas:o,deriveEntitySeo:s.deriveEntitySeo,hiddenStatuses:s.HIDDEN_STATUSES})})}return h}async function Pt(n,e,t){try{return await n.import(e)}catch(r){throw new Error(`[dndev] Build pages: cannot load "${e}" (${t}): ${r.message}`,{cause:r})}}async function Co({appRoot:n,mode:e,manifestRoutes:t,blogPosts:r,staticRoutes:o,prerenderRecords:s,shellHtml:a,pageShell:i,seo:c,loadI18n:l,pkg:u,write:p,logger:d}){if(!a)throw new Error("[dndev] Build pages: the build output has no index.html (the SPA shell).");if(await p(`/${st}`,a),c.disabled)return{pages:0,listings:[]};let{createServer:f,loadEnv:g}=await import("vite"),v=g(e,n,"VITE_"),h=c.siteName,y=c.defaultNamespace||"home",C=Qe(Et(c.baseUrl,v.VITE_APP_URL)||null,"VITE_APP_URL",d)??"",w=(c.generateSitemap!==!1||c.llmsTxt!==!1)&&!!(C&&h),_=Fi(t),N=s&&_.length>0?Li(v.VITE_APP_URL,d):null,k=N?_:[],x=_.length>0&&(k.length>0||w);if(o.length===0&&k.length===0&&!w)return{pages:0,listings:[]};if(!h)throw new Error("[dndev] Prerendered page titles end with the site name. Set appConfig.app.name (or appConfig.seo.siteName).");let D=null,R=_.map(({route:L})=>L.path);if(x){if(!{...u?.dependencies,...u?.devDependencies}.entities)throw new Error(`[dndev] ${R.join(", ")}: record pages derive their identity from the entity definition, but the app does not depend on an \`entities\` package. Add the entity to the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`);D=Mi(u,v,R)}let m=N??v.VITE_APP_URL??"",$=await l(),U={languages:$.supportedLanguages,defaultLanguage:$.fallbackLanguage},E=await f({root:n,configFile:!1,envFile:!1,logLevel:"error",appType:"custom",server:{middlewareMode:!0,hmr:!1,ws:!1,watch:null},optimizeDeps:{noDiscovery:!0,include:[]},resolve:{conditions:Ro},ssr:{resolve:{conditions:Ro,externalConditions:["react-server"]}}}),M=globalThis._DNDEV_CONFIG_;globalThis._DNDEV_CONFIG_={...M,i18n:{languages:$.supportedLanguages,eager:$.eagerNamespaces,fallback:$.fallbackLanguage,content:$.content}};try{let L=E.environments.ssr.runner,z=await Pt(L,"@donotdev/core/server","SEO helpers"),K=await Pt(L,"@donotdev/core/rsc","translations"),W={},Z,P;if(D){W=await Pt(L,"entities","the entity definitions");let X=await Pt(L,D.module,"the public reader");Z=ji(D.create(X)),P=oo(W,_.map(({route:te})=>te),z.createSchemas)}let I=(X,te)=>K.useTranslation(X,{language:te}).t,{pages:F,skipped:G}=await zi({staticRoutes:o,records:k,routes:t,crud:Z,readSchemas:P,core:z,entities:W,translate:I,routing:U,baseUrl:m,siteName:h,hreflang:c.hreflang!==!1,defaultNamespace:y,defaultImage:c.defaultImage||Me,pageShell:i});for(let X of F)await p(X.file,X.html);G.length>0&&d.warn(`Pages left to the SPA shell (a static page serves the URL, or no file name can hold it): ${G.join(", ")}`);let Q=w?await Bi({routes:t,blogPosts:r,generator:new Ge({baseUrl:C,siteName:h,appRoot:n}),crud:Z,readSchemas:P,core:z,entities:W,routing:U,baseUrl:C,siteName:h,siteDescription:c.siteDescription,translations:$.content,defaultNamespace:y,sitemap:c.generateSitemap!==!1,llmsTxt:c.llmsTxt!==!1}):[];for(let{file:X,content:te}of Q)await p(X,te);return{pages:F.length,listings:Q.map(({file:X})=>X)}}finally{M===void 0?delete globalThis._DNDEV_CONFIG_:globalThis._DNDEV_CONFIG_=M,await E.close()}}function Ui(n=!0){if(typeof n=="boolean")return n;throw new Error(`appConfig.prerenderRecords must be true or false. Got ${JSON.stringify(n)}.`)}function _o(n={}){let{routes:e="auto",prerenderRecords:t,seo:r={},i18nStore:o,fontPlan:s,debug:a,verbose:i,routeManifest:c}=n;if(!c||!o||!s)throw new Error("[dndev] createVitePrerenderPlugin: options.routeManifest, options.i18nStore and options.fontPlan are required (createVitePlugins passes the route, i18n and font plugins', createRouteManifestStore / createI18nStore / createFontPlanStore).");let l=e==="auto"&&Ui(t),u=H("Prerender",a,i),p=O.getInstance(),d=null,f=!1,g=!1;return{name:"dndev-prerender",enforce:"post",applyToEnvironment(v){return v.name==="client"},configResolved(v){f=v.command==="build",d={outDir:v.build?.outDir||"dist",mode:v.mode}},buildStart(){g=!1},writeBundle(){g=!0},async closeBundle(){if(!g||!d||!f)return;let v=p.getAppRoot(),h=p.resolveAppPath(d.outDir),y=c.get(),C=y.routes,A=new wt({routes:Array.isArray(e)?e:[],debug:a,outDir:h,logger:u}),w=new Map(C.map(m=>[m.path,m])),N=(e==="auto"?[...new Set(Gn(C).filter(m=>!m.includes("*")))]:A.expandRoutes(y)).map(m=>w.get(m)??{path:m}),k=p.readSync(p.resolvePath("index.html",h)),{preloads:x}=s.get(),{pages:D,listings:R}=await Co({appRoot:v,mode:d.mode,manifestRoutes:C,blogPosts:y.blogPosts,staticRoutes:N,prerenderRecords:l,shellHtml:k,pageShell:m=>Nr(k,x[m]),seo:r,loadI18n:async()=>o.get(),pkg:p.readSync(p.resolveAppPath("package.json"),{format:"json"}),write:(m,$)=>A.writeOutputFile(m,$),logger:u});D>0&&u.info(`Prerendered: ${D} pages`);for(let m of R)u.info(`\u{1F4C4} ${m.slice(1)}`)}}}import{VitePWA as Wi}from"vite-plugin-pwa";var Rt=class extends fe{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:r}=e,o=[...t,...r];this.logger.debug(`Processing ${o.length} PWA files`);let s=await this._analyzePWAFiles(o),a=[...s.filter(c=>c.type==="manifest"||c.type==="service-worker"),...s.filter(c=>c.type==="icon")],i=this._generatePWAManifest(a);return{assets:a,manifest:i,totalFiles:o.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 r of e){let o=typeof r=="string"?{absolutePath:r,relativePath:this.pathResolver.getRelativePath(r),fileName:r.split("/").pop()||"",extension:(r.split(".").pop()||"").toLowerCase()}:r,s=await this._analyzePWAAsset(o);s&&t.push(s)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let r=e.relativePath,o=e.fileName;return o==="manifest.json"?this._parseManifestFile(t,r):o.includes("service-worker")||o.includes("sw.")?this._parseServiceWorkerFile(t,r):this._isPWAIcon(o)?this._parseIconFile(e,r):null}_parseManifestFile(e,t){try{let r=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:r,size:typeof e=="string"?e.length:JSON.stringify(r).length}}catch(r){return this.logger.debug(`Failed to parse manifest: ${r.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let r=e.fileName,o=this._extractIconSize(r);return{type:"icon",path:t,size:o,format:e.extension,purpose:this._getIconPurpose(r)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(r=>e.includes(r))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(o=>o.type==="icon"),r=this._getDefaultManifest();return t.length>0&&(r.icons=t.map(o=>this.toManifestIcon(o))),r}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},r=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:r==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[r]||`image/${r}`,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 r=this._getWorkboxDefaults(t),o=t.backgroundSync!==!1&&t.backgroundSync,s=t.precacheManifest||[],a=JSON.stringify(s,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
612
618
|
// Generated at ${new Date().toISOString()}
|
|
613
619
|
|
|
614
620
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -624,7 +630,7 @@ ${o?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
|
|
|
624
630
|
cleanupOutdatedPrecaches();
|
|
625
631
|
|
|
626
632
|
// Precache static assets
|
|
627
|
-
const precacheManifest = ${
|
|
633
|
+
const precacheManifest = ${a.length>2?a:"self.__WB_MANIFEST || []"};
|
|
628
634
|
precacheAndRoute(precacheManifest);
|
|
629
635
|
|
|
630
636
|
// Runtime caching strategies
|
|
@@ -642,23 +648,23 @@ self.addEventListener('message', (event) => {
|
|
|
642
648
|
self.addEventListener('activate', (event) => {
|
|
643
649
|
event.waitUntil(self.clients.claim());
|
|
644
650
|
});
|
|
645
|
-
`}_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((r,o)=>{let{urlPattern:s,handler:
|
|
646
|
-
maxEntries: ${
|
|
647
|
-
maxAgeSeconds: ${
|
|
648
|
-
})`),
|
|
649
|
-
statuses: ${JSON.stringify(
|
|
650
|
-
})`),
|
|
651
|
-
maxRetentionTime: ${
|
|
652
|
-
})`);let p="";return
|
|
653
|
-
cacheName: '${
|
|
651
|
+
`}_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((r,o)=>{let{urlPattern:s,handler:a,options:i={}}=r,c=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",l;typeof s=="function"?l="({ request }) => request.destination === 'document'":s instanceof RegExp?l=s.toString():l=JSON.stringify(s);let u=[];i.expiration&&u.push(`new ExpirationPlugin({
|
|
652
|
+
maxEntries: ${i.expiration.maxEntries||50},
|
|
653
|
+
maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
|
|
654
|
+
})`),i.cacheableResponse&&u.push(`new CacheableResponsePlugin({
|
|
655
|
+
statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
|
|
656
|
+
})`),i.backgroundSync&&u.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
|
|
657
|
+
maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
|
|
658
|
+
})`);let p="";return i.cacheName&&(p+=`
|
|
659
|
+
cacheName: '${i.cacheName}',`),u.length>0&&(p+=`
|
|
654
660
|
plugins: [
|
|
655
661
|
${u.join(`,
|
|
656
662
|
`)}
|
|
657
|
-
],`),
|
|
658
|
-
networkTimeoutSeconds: ${
|
|
663
|
+
],`),i.networkTimeoutSeconds&&(p+=`
|
|
664
|
+
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${o+1}: ${i.cacheName||"cache-"+o}
|
|
659
665
|
registerRoute(
|
|
660
|
-
${
|
|
661
|
-
new ${
|
|
666
|
+
${l},
|
|
667
|
+
new ${c}({${p}
|
|
662
668
|
})
|
|
663
669
|
);`}).join(`
|
|
664
670
|
|
|
@@ -676,11 +682,11 @@ registerRoute(
|
|
|
676
682
|
}),
|
|
677
683
|
'POST'
|
|
678
684
|
);
|
|
679
|
-
`}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`),r=this.pathResolver.resolveAppPath(`${e}/static/chunks`),o=this.pathResolver.resolveAppPath(`${e}/static/css`),s=[];try{let
|
|
680
|
-
export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,
|
|
681
|
-
${
|
|
685
|
+
`}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`),r=this.pathResolver.resolveAppPath(`${e}/static/chunks`),o=this.pathResolver.resolveAppPath(`${e}/static/css`),s=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${r}/**/*.{js,css}`,`${o}/**/*.css`];for(let i of a){let c=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let l of c){let u=this.pathResolver.getRelativePath(l);if(u.startsWith(`${e}/static/`)){let p=`/_next/${u.replace(`${e}/static/`,"")}`;s.push({url:p,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return s}generatePrecacheManifest(e=[],t=null){let r=e;return t&&typeof t=="function"&&(r=t(r)),r}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};Y();function Ao(n={}){if(!n.enabled)return null;let e=n.app||{},t=[];if(e.name||t.push("name"),e.shortName||t.push("shortName"),e.description||t.push("description"),t.length>0){let l=H("PWA",n.debug,!0);l.warn(`\u26A0\uFE0F PWA is enabled but appConfig.app is missing required fields: ${t.join(", ")}`),l.warn(" Add these to your src/config/app.ts:"),l.warn(" export const appConfig: AppConfig = {"),l.warn(" app: {"),e.name||l.warn(' name: "Your App Name",'),e.shortName||l.warn(' shortName: "App",'),e.description||l.warn(' description: "Your app description",'),l.warn(" },"),l.warn(" // ... rest of config"),l.warn(" };"),l.warn("")}let r=O.getInstance(),o=new Rt(r,n),s=n.devEnabled===!0,a={registerType:n.registerType||"prompt",includeAssets:["favicon.ico","favicon.svg","apple-touch-icon.png"],manifest:async()=>{let l=n.app||{},p=(await o.discoverPWAAssets()).assets.filter(d=>d.type==="icon").map(d=>o.toManifestIcon(d));return{name:l.name,short_name:l.shortName,description:l.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:p.length>0?p:[]}},workbox:{globPatterns:["**/*.{js,css,html,ico,png,svg,woff2}"],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:l})=>l.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:!0,skipWaiting:!0,clientsClaim:!0,maximumFileSizeToCacheInBytes:5*1024*1024,navigateFallback:"/index.html",navigateFallbackDenylist:[/^\/api\/.*/],manifestTransforms:[l=>{let u=l.find(p=>p.url==="/index.html"||p.url==="index.html");return u&&!l.find(p=>p.url==="/")&&l.push({url:"/",revision:u.revision}),{manifest:l,warnings:[]}}]},devOptions:{enabled:s,type:"module"}},c={...a,manifest:async()=>{let l=await a.manifest();if(n.manifest){if(typeof n.manifest=="function"){let u=await n.manifest();return{...l,...u}}return{...l,...n.manifest}}return l},workbox:{...a.workbox,...n.workbox||{},runtimeCaching:[...a.workbox.runtimeCaching,...n.workbox?.runtimeCaching||[]],manifestTransforms:[...a.workbox.manifestTransforms||[],...n.workbox?.manifestTransforms||[]]}};return Wi(c)}q();q();var Gi=/^[A-Za-z_$][\w$]*$/,Hi=/^(?:'[^'\\]*'|"[^"\\]*"|`[^`\\$]*`|-?\d[\w.]*|null|undefined|true|false)$/;function Vi(n,e){let t=0;for(let r=e;r<n.length;r++){let o=n[r];if(o==="'"||o==='"'||o==="`"){for(r++;r<n.length&&n[r]!==o;r++)n[r]==="\\"&&r++;continue}if(t===0&&(o===","||o==="/"&&/[/*]/.test(n[r+1]??"")))return r;if("([{".includes(o))t++;else if(")]}".includes(o)){if(t===0)return r;t--}}return n.length}function Ji(n){let e=/(^|[{,\s])entity\s*:\s*/gm,t="",r=0,o;for(;o=e.exec(n);){let s=o.index+o[0].length,a=Vi(n,s),i=n.slice(s,a).trimEnd();if(!i)continue;let c=Hi.test(i)?i:Gi.test(i)?`{ identifier: '${i}' }`:`{ expression: ${JSON.stringify(i)} }`;t+=n.slice(r,s)+c,r=s+i.length,e.lastIndex=r}return t+n.slice(r)}function qi(n){let e=n instanceof Error?n.message:String(n),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 No(n,e="unknown"){let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,r=n.match(t);if(!r)return null;let o=r[1];o=o.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,c)=>`icon: '${c}'`),o=Ji(o);let s=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;[...n.matchAll(s)].forEach(i=>{let c=i[1],l=i[2];o=o.replace(new RegExp(`\\b${c}\\b`,"g"),`'${l}'`)});try{return Function(`return ${o}`)()}catch(i){throw B("dndev-routes",`${e}: PageMeta cannot be read at build: ${qi(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 ko(n){return/^[ \t]*export\s+(?:(?:async\s+)?function\s*\*?\s*generateMetadata\b|(?:const|let)\s+generateMetadata\b|\{[^}]*\bgenerateMetadata\b[^}]*\})/m.test(n)}import{existsSync as cn,readFileSync as an,realpathSync as Ki}from"node:fs";import{dirname as Do,join as tt,resolve as To}from"node:path";var Ce="dndev-routes",Ct="entities",Yi="@donotdev/core",Oo=[".ts",".tsx",".js",".jsx"],Zi=`import { productEntity } from 'entities';
|
|
686
|
+
export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,Io=null;async function jo(){return Io??=import("@babel/core").then(n=>n.default??n),Io}function zo(n,e,t){let r=/\.[jt]sx$/.test(t);try{return n.parseSync(e,{configFile:!1,babelrc:!1,filename:t,sourceType:"module",parserOpts:{plugins:r?["typescript","jsx"]:["typescript"]}}).program}catch(o){throw B(Ce,`${t} could not be parsed to resolve entities (PageMeta entity, entity field types): ${o.message}. Fix the syntax error.`,"invalid-configuration")}}function Ie(n){return n.type==="StringLiteral"?n.value:n.name}function He(n){let e=n;for(;e&&["TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","ParenthesizedExpression"].includes(e.type);)e=e.expression;return e}function Xi(n,e){for(let t of n.body)if(!(t.type!=="ImportDeclaration"||t.importKind==="type")){for(let r of t.specifiers)if(r.local.name===e)return t.source.value!==Ct||r.type!=="ImportSpecifier"||r.importKind==="type"?null:Ie(r.imported)}return null}function ln(n){let e=null,t=new Map;function r(){let u=tt(n,"package.json"),p=cn(u)?JSON.parse(an(u,"utf8")):null;return!!(p?.dependencies?.[Ct]||p?.devDependencies?.[Ct])}function o(u){if(e)return e;let p=r(),d=n,f=null;for(;p;){let h=tt(d,"node_modules",Ct);if(cn(tt(h,"package.json"))){f=Ki(h);break}let y=Do(d);if(y===d)break;d=y}if(!f)throw B(Ce,`${u}, 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 g=JSON.parse(an(tt(f,"package.json"),"utf8")),v=Lo(To(f,g.main??"./index.ts"));if(!v)throw B(Ce,`The \`entities\` package (${f}) has no entry module (package.json "main": ${JSON.stringify(g.main??"./index.ts")}). Fix: set "main" to its index file (./index.ts).`,"missing-required-resource");return e=v,e}async function s(u){if(!t.has(u)){let p=await jo();t.set(u,zo(p,an(u,"utf8"),u))}return t.get(u)}function a(u,p){return p.startsWith(".")?Lo(To(Do(u),p)):null}async function i(u,p,d){let f=`${u}#${p}`;if(d.has(f))return null;d.add(f);let g=await s(u),v=[];for(let h of g.body)if(h.type==="ExportNamedDeclaration"&&h.exportKind!=="type"){let y=Mo(h.declaration,p);if(y!==void 0)return{init:y,program:g,file:u};for(let C of h.specifiers??[]){if(C.exportKind==="type"||Ie(C.exported)!==p)continue;if(C.type!=="ExportSpecifier")return null;let A=Ie(C.local);if(h.source){let w=a(u,h.source.value);return w?i(w,A,d):null}return c(u,g,A,d)}}else if(h.type==="ExportAllDeclaration"&&h.exportKind!=="type"){let y=a(u,h.source.value);y&&v.push(y)}for(let h of v){let y=await i(h,p,d);if(y)return y}return null}async function c(u,p,d,f){for(let g of p.body){let v=Mo(g,d);if(v!==void 0)return{init:v,program:p,file:u};if(!(g.type!=="ImportDeclaration"||g.importKind==="type"))for(let h of g.specifiers){if(h.local.name!==d||h.type!=="ImportSpecifier")continue;let y=a(u,g.source.value);return y?i(y,Ie(h.imported),f):null}}return null}async function l(u){let p=[u];for(let d=0;d<p.length;d+=1){let f=await s(p[d]);for(let g of f.body){if(!(g.type==="ImportDeclaration"&&g.importKind!=="type"||g.type==="ExportNamedDeclaration"&&g.source&&g.exportKind!=="type"||g.type==="ExportAllDeclaration"&&g.exportKind!=="type"))continue;let h=a(p[d],g.source.value);h&&!p.includes(h)&&p.push(h)}}return p}return{async usesFieldType(u){if(!r())return!1;for(let p of await l(o("The app's package.json lists `entities` (its entity field types are read)")))if(Qi(await s(p),u))return!0;return!1},async collectionOf(u,p){let d=await i(o(`${p} declares a PageMeta entity`),u,new Set);if(!d)throw B(Ce,`${p}: PageMeta entity \`${u}\` 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 { ${u} } from './\u2026').`,"invalid-configuration");return ec(d,u,p)}}}function Bo(n){return n.body.filter(e=>e.type==="ImportDeclaration"&&e.source.value===Yi).flatMap(e=>e.specifiers).find(e=>e.type==="ImportSpecifier"&&Ie(e.imported)==="defineEntity")?.local.name}function Fo(n,e){if(n?.type!=="ObjectExpression")return;let t=n.properties.find(r=>r.type==="ObjectProperty"&&!r.computed&&Ie(r.key)===e);return He(t?.value)}function Qi(n,e){let t=Bo(n);if(!t)return!1;let r=o=>{if(!o||typeof o.type!="string")return!1;if(o.type==="CallExpression"&&o.callee.type==="Identifier"&&o.callee.name===t){let s=Fo(He(o.arguments[0]),"fields");if(s?.type==="ObjectExpression"&&s.properties.some(a=>{let i=Fo(He(a.value),"type");return i?.type==="StringLiteral"&&i.value===e}))return!0}for(let s of Object.keys(o)){if(s==="loc"||s==="leadingComments"||s==="trailingComments")continue;let a=o[s];if(Array.isArray(a)?a.some(r):a&&typeof a=="object"&&r(a))return!0}return!1};return r(n)}function Mo(n,e){if(n?.type==="VariableDeclaration"){for(let t of n.declarations)if(t.id.type==="Identifier"&&t.id.name===e)return t.init??null}}function Lo(n){let e=n.replace(/\.[cm]?js$/,""),t=[n,...Oo.map(r=>`${e}${r}`),...Oo.map(r=>tt(n,`index${r}`))];for(let r of t)if(/\.[cm]?[jt]sx?$/.test(r)&&cn(r))return r;return null}function ec({init:n,program:e,file:t},r,o){let s=He(n),a=Bo(e);if(s?.type!=="CallExpression"||s.callee.type!=="Identifier"||!a||s.callee.name!==a)throw B(Ce,`${o}: PageMeta entity \`${r}\` (${t}) is not a defineEntity definition. The build reads the collection from \`defineEntity({ collection: ... })\` in the entities package. Fix: export const ${r} = defineEntity({ name: '...', collection: '...', fields: { ... } }) with defineEntity imported from '@donotdev/core'.`,"invalid-configuration");let i=He(s.arguments[0]),c=i?.type==="ObjectExpression"?i.properties.find(p=>p.type==="ObjectProperty"&&!p.computed&&Ie(p.key)==="collection"):void 0,l=He(c?.value),u=l?.type==="StringLiteral"?l.value:l?.type==="TemplateLiteral"&&l.expressions.length===0?l.quasis[0].value.cooked:null;if(!u)throw B(Ce,`${o}: PageMeta entity \`${r}\` (${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 u}async function Uo(n,e,t,r){if(!n||n.entity===void 0)return null;let o=n.entity?.identifier,s=n.entity?.expression;if(typeof s=="string"){let c=s.match(/^[A-Za-z_$][\w$]*\s*\??\.\s*([A-Za-z_$][\w$]*)$/)?.[1]??"productEntity";throw B(Ce,`${t}: PageMeta entity \`${s}\` 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 { ${c} } from 'entities'; then entity: ${c}`,"invalid-configuration")}if(typeof o!="string")throw B(Ce,`${t}: PageMeta entity must be the entity definition imported from 'entities' (got ${JSON.stringify(n.entity)}). The build resolves it to the entity's collection. Fix:
|
|
687
|
+
${Zi}`,"invalid-configuration");let a=zo(await jo(),e,t),i=Xi(a,o);if(!i)throw B(Ce,`${t}: PageMeta entity \`${o}\` 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 { ${o} } from 'entities';`,"invalid-configuration");return r.collectionOf(i,t)}var _t=n=>n.split("/").filter(Boolean);function Wo(n){return n==="*"||n.endsWith("/*")}function tc(n){try{return decodeURIComponent(n)}catch{return n}}function Go(n,e){let t={};return n.forEach((r,o)=>{r.startsWith(":")&&e[o]!==void 0&&(t[r.slice(1)]=tc(e[o]))}),t}function nc(n,e){let t=_t(e),r=t.join("/"),o=n.find(i=>typeof i.path=="string"&&_t(i.path).join("/")===r);if(o)return{route:o,params:{}};let s=null;for(let i of n){if(typeof i.path!="string"||!i.path.includes(":")||Wo(i.path))continue;let c=_t(i.path);c.length===t.length&&c.every((l,u)=>l.startsWith(":")||l===t[u])&&(!s||i.path.length>s.route.path.length)&&(s={route:i,pattern:c})}if(s)return{route:s.route,params:Go(s.pattern,t)};let a=null;for(let i of n){if(typeof i.path!="string"||!Wo(i.path))continue;let c=_t(i.path).slice(0,-1);if(t.length<c.length)continue;let l=0,u=!0;for(let d=0;d<c.length;d++){let f=c[d];if(!f.startsWith(":")){if(f!==t[d]){u=!1;break}l++}}if(!u)continue;let p=[c.length,l];(!a||p[0]>a.score[0]||p[0]===a.score[0]&&p[1]>a.score[1])&&(a={route:i,prefix:c,score:p})}return a?{route:a.route,params:Go(a.prefix,t)}:null}function un(n){let e=[],t="";for(let r of n.split("/").filter(Boolean))t+=`/${r}`,e.push(t);return e}var nt=n=>`/${n.split("/").filter(Boolean).join("/")}`,rc=n=>!n.split("/").some(e=>e.startsWith(":")||e==="*");function Ho(n,e){let t=new Map;for(let i of e)typeof i.path=="string"&&rc(i.path)&&t.set(nt(i.path),i);let r=(i,c)=>{let l=un(i).slice(0,-1),u=l.at(-1),p=u===void 0?void 0:t.get(u);if(p)return p;let d=c?.meta?.parent;if(d!==void 0){if(nt(d)==="/")return null;let f=t.get(nt(d));if(!f)throw new Error(`[dndev] ${c?.path}: PageMeta parent ${JSON.stringify(d)} is not a static route path of the app.`);return f}for(let f=l.length-2;f>=0;f--){let g=t.get(l[f]);if(g)return g}return null},o=[],s=new Set([nt(n)]),a=r(n,nc(e,n)?.route);for(;a;){let i=nt(a.path);if(s.has(i))throw new Error(`[dndev] PageMeta parent loop: ${[...s,i].join(" \u2192 ")}. Each page needs one parent chain up to home.`);s.add(i),o.unshift(a),a=r(i,a)}return o}var Ve=null,Vo=null;function oc(n){let t=(n.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function sc(n){let e=n.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw B("dndev-routes",`${n.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]===n.path)throw B("dndev-routes",`${n.file}: PageMeta signedInRedirect points at the page itself (${e}): signed-in visitors would loop. Use another page.`,"invalid-configuration")}}function ac(n,e){let t=n.meta?.parent;if(t===void 0)return;let r=s=>{throw B("dndev-routes",`${n.file}: PageMeta parent ${JSON.stringify(t)} ${s}`,"invalid-configuration")};(typeof t!="string"||!t.startsWith("/")||t.startsWith("//")||/[\\?#*:]/.test(t))&&r("must be the static path of one of the app's pages, starting with '/' (no :param, *, query or hash). Example: export const meta: PageMeta = { parent: '/catalogue' };"),e.some(s=>s.path===t)||r(`is not the path of a page of the app. Use the path of an existing page, e.g. one of: ${e.map(s=>s.path).filter(s=>!/[:*]/.test(s)).slice(0,8).join(", ")}.`),t===n.path&&r("is the page itself. Name the page its visitors come from.");let o=un(n.path).slice(0,-1).at(-1);o&&e.some(s=>s.path===o)&&r(`is never used: the URL prefix ${o} is a page, so it is the parent. Remove parent.`)}function ic(n){for(let e of n)try{Ho(e.path,n)}catch(t){throw B("dndev-routes",`${e.file}: ${t.message.replace(/^\[dndev\] /,"")} Fix the PageMeta parent of one of these pages.`,"invalid-configuration")}}function cc(n,{pageGenerateMetadata:e=!1}={}){if(!n.path.split("/").some(r=>r.startsWith(":"))||sn(n)||!xt(n)||n.meta?.entity||n.metaExport?.namespace==="blog"||e&&n.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 B("dndev-routes",`${n.file}: public dynamic route ${n.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:
|
|
682
688
|
`+t.map((r,o)=>` ${o+1}. ${r}`).join(`
|
|
683
|
-
`),"invalid-configuration")}var
|
|
689
|
+
`),"invalid-configuration")}var At=class extends fe{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(),r=process.env.DNDEV_BUILD_ID;if(Ve&&Vo===r)return this.logger.debug("Using cached route discovery results"),this.routes=Ve.routes,this.errors=Ve.errors,this.source=Ve.source,this.entityResolver=Ve.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 o=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${o} files in ${t}`);let s=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(s)}`)}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/"),Ve={routes:this.routes,errors:this.errors,source:this.source,entityResolver:this.entityResolver},Vo=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??=ln(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:r}=e;this.entityResolver=ln(t);let o=await this._batchProcessFiles(r,l=>this._analyzePageFile(l,t)),s=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(s,l=>this._analyzePageFile(l,t)),i=[...o,...a];this.logger.debug(`Auto-discovering from ${r.length} app + ${s.length} additional files`),this.routes=i.filter(l=>l.path==="home"||l.path==="/home"?(this.logger.debug(`Filtered reserved route: ${l.path} - Use root "/" instead (${l.file})`),!1):!0);let c=new Map;for(let l of this.routes){let u=l.path;if(c.has(u)){let p=c.get(u);throw B("dndev-routes",`${l.file}: route ${u} 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")}c.set(u,l),sc(l),cc(l,{pageGenerateMetadata:this.options.pageGenerateMetadata===!0})}for(let l of this.routes)ac(l,this.routes);ic(this.routes),this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${r.length+s.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(r=>this.pathResolver.resolveAppPath(r));if(t.length===0)return[];try{let{consumerFiles:r}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return r}catch(r){return this.logger.debug(`Error scanning additional patterns: ${r.message}`),[]}}async _analyzePageFile(e,t){let r=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!r)return null;let o=e.relativePath,s="/src/"+o.replace(/\\/g,"/");s=s.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(r,o),i=oc(s),l=i===Tt.HOMEPAGE_COMPONENT?Tt.HOMEPAGE_PATH:this._resolveRoutePath(a,o,e.absolutePath),u=this._extractPageMeta(o),p=await Uo(a,r,o,this.entityResolver),{entity:d,action:f,...g}=a||{};return{path:l,component:i,importPath:s,auth:a?.auth||!1,meta:{...u,...g,...p&&{entity:p},action:u.action},metaExport:a&&{...a,...p&&{entity:p}},exportsGenerateMetadata:ko(r),file:o}}_extractMetaExport(e,t){try{let r=No(e,t);return r?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(r)}`),r):null}catch(r){if(be(r))throw r;return this.logger.debug(`Error parsing meta export from ${t}: ${r.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,r){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let o=e.route.trim();return o==="/"?"/":(o=o.replace(/\/+/g,"/"),o.startsWith("/")||(o="/"+o),o)}if(typeof e.route=="object"&&e.route!==null){let o=this._generateRoutePath(t),s=e.route.params;if(Array.isArray(s)&&s.length>0){let a=s.map(i=>`:${i}`).join("/");return`${o}/${a}`}return o}return this.logger.warn(`Invalid route format in ${r}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${r}`),this._generateRoutePath(t)}_extractPageMeta(e){let t=e.split("/").pop()?.replace(".tsx","")||"",r=t.replace(/Page$/,"");r=r.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let o=e.split("/"),s=null;return o.length>1&&(t.includes("List")?s="list":t.includes("Form")||t.includes("Create")||t.includes("Edit")?s="form":(t.includes("Detail")||t.includes("View"))&&(s="detail")),{title:r,action:s,file:e}}};Y();var lc={isEmpty:n=>!n.routes||n.routes.length===0,generateModule:(n,e,t="routes")=>{let r={totalRoutes:n.routes.length,authRequired:n.routes.filter(s=>s.auth&&s.auth.required).length,publicRoutes:n.routes.filter(s=>!s.auth||s.auth===!1).length,source:n.source,generatedAt:new Date().toISOString(),errors:n.errors.length,hasBlogFeed:Bn(O.getInstance().getAppRoot())},o=n.routes.map(s=>` {
|
|
684
690
|
path: '${s.path}',
|
|
685
691
|
component: () => import('${s.importPath}'),
|
|
686
692
|
auth: ${JSON.stringify(s.auth,null,2).replace(/\n/g,`
|
|
@@ -689,7 +695,7 @@ ${_i}`,"invalid-configuration");let i=eo(await Qn(),e,t),a=Ai(i,o);if(!a)throw H
|
|
|
689
695
|
`)}
|
|
690
696
|
}`).join(`,
|
|
691
697
|
`);return`
|
|
692
|
-
// ${
|
|
698
|
+
// ${V.routes} - Generated route data
|
|
693
699
|
import { lazy } from 'react';
|
|
694
700
|
|
|
695
701
|
const routeData = [
|
|
@@ -711,7 +717,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
711
717
|
}
|
|
712
718
|
|
|
713
719
|
// Include all routes in mapping (navigation store will filter by hideFromMenu)
|
|
714
|
-
globalThis._DNDEV_CONFIG_.${
|
|
720
|
+
globalThis._DNDEV_CONFIG_.${re[t]} = {
|
|
715
721
|
mapping: routeData,
|
|
716
722
|
manifest: {
|
|
717
723
|
totalRoutes: ${n.routes.length},
|
|
@@ -730,7 +736,7 @@ export const source = '${n.source}';
|
|
|
730
736
|
|
|
731
737
|
export default { routes: routeData, manifest: routeManifest, source: '${n.source}' };
|
|
732
738
|
`},generateEmpty:(n,e,t,r="routes")=>{let o={totalRoutes:0,authRequired:0,publicRoutes:0,source:"empty",generatedAt:new Date().toISOString()};return`
|
|
733
|
-
// ${
|
|
739
|
+
// ${V.routes} - Empty route data
|
|
734
740
|
|
|
735
741
|
const routeData = [];
|
|
736
742
|
const routeManifest = ${JSON.stringify(o,null,2)};
|
|
@@ -749,7 +755,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
749
755
|
}
|
|
750
756
|
|
|
751
757
|
// Populate empty routes configuration
|
|
752
|
-
globalThis._DNDEV_CONFIG_.${
|
|
758
|
+
globalThis._DNDEV_CONFIG_.${re[r]} = {
|
|
753
759
|
mapping: [],
|
|
754
760
|
manifest: {
|
|
755
761
|
totalRoutes: 0,
|
|
@@ -794,7 +800,7 @@ export default discoveredRoutes;
|
|
|
794
800
|
* Generated Route Discovery Results
|
|
795
801
|
* Source: ${n.source}
|
|
796
802
|
* Generated at: ${new Date().toISOString()}
|
|
797
|
-
* Import from '${
|
|
803
|
+
* Import from '${V.routes}'
|
|
798
804
|
*/
|
|
799
805
|
|
|
800
806
|
export const discoveredRoutes = [
|
|
@@ -808,10 +814,10 @@ export const routeManifest = {
|
|
|
808
814
|
};
|
|
809
815
|
|
|
810
816
|
export default discoveredRoutes;
|
|
811
|
-
`},generateManifest:n=>({routes:n?.routes?.length||0,source:n?.source||"unknown",timestamp:Date.now(),errors:n?.errors?.length||0}),logConfig:n=>{},logStats:(n,e,t)=>{let r=n.routes||[],o=r.filter(
|
|
812
|
-
`),
|
|
817
|
+
`},generateManifest:n=>({routes:n?.routes?.length||0,source:n?.source||"unknown",timestamp:Date.now(),errors:n?.errors?.length||0}),logConfig:n=>{},logStats:(n,e,t)=>{let r=n.routes||[],o=r.filter(a=>a.auth&&a.auth.required).length,s=r.length;t&&t.info(`${e} Routes: ${s} found${o>0?`, ${o} are authguarded`:""}`)}},uc=[n=>n.endsWith("Page.tsx")];function Jo(n={}){return we({pluginName:"dndev-vite-route-discovery",icon:"\u{1F6E3}\uFE0F",virtualModuleId:V.routes,DiscoveryClass:At,discoveryMethod:"discoverRoutes",filePatterns:uc,templates:lc,manifestFileName:ve.manifests.route,configKey:"routes"})({...n,disableHmr:n?.hmr===!1,hmrSmartDetection:!1})}q();import{loadEnv as pc}from"vite";Y();var dc=`/${st.replace(/\.html$/,"")}`;function qo(n={}){let{disabled:e=!1,debug:t,generateRobotsTxt:r,generateSitemap:o,routes:s={},baseUrl:a,siteName:i,siteDescription:c,crawlDelay:l,aiCrawlers:u,llmsTxt:p=!0,redirects:d,isDev:f,routeManifest:g,...v}=n;if(e)return{name:"seo-disabled"};if(!g)throw new Error("[dndev] createViteSEOPlugin: options.routeManifest is required (createVitePlugins passes the route plugin's, createRouteManifestStore).");let h=H("SEO Plugin",t,!0),y=O.getInstance(),C=null,A=null,w=!1;return{name:"vite-seo-plugin",enforce:"pre",applyToEnvironment(_){return _.name==="client"},configResolved(_){let N=y.getAppRoot(),k=_.mode||"production",D=pc(k,N,"VITE_").VITE_APP_URL||process.env.VITE_APP_URL||null;D&&t&&h.debug(`Using app URL from VITE_APP_URL: ${D}`),C=i||null;let R=Et(a,D)||null;if(A=f?R:Qe(R,"VITE_APP_URL",h),!f&&!A){w=!0;return}h.verbose(`Name: ${C||"Not found"}`),h.verbose(`URL: ${A||"Not found"}
|
|
818
|
+
`),C&&h.debug(` - Site name from appConfig: "${C}"`);let m=[];if(A||m.push("baseUrl (VITE_APP_URL in .env)"),C||m.push("siteName (APP_NAME in src/config/app.ts)"),m.length>0){w=!0,h.warn("\u26A0\uFE0F SEO Plugin disabled - missing required configuration:"),m.forEach($=>h.warn(` - ${$}`)),h.warn(""),h.warn(" To fix:"),A||h.warn(" 1. Add VITE_APP_URL=https://yourdomain.com to your .env file"),C||(h.warn(" 2. Add APP_NAME export to src/config/app.ts:"),h.warn(' export const APP_NAME = "Your App Name";')),h.warn(""),h.warn(" robots.txt and sitemap.xml will NOT be generated."),h.warn("");return}h.debug(`Generate robots.txt: ${r}`),h.debug(`Generate sitemap: ${o}`)},async generateBundle(){if(w)return;let _=new Ge({debug:t,generateRobotsTxt:r,shellPath:dc,baseUrl:A,siteName:C,crawlDelay:l,aiCrawlers:u,routes:s,appRoot:y.getAppRoot(),...v}),N=g.get(),{blogPosts:k}=N,x=async(D,R)=>{this.emitFile({type:"asset",fileName:D,source:R})};await St(["robots.txt","rss.xml","seo-manifest.json"],async()=>{let D=await _.generateSEOFiles(N,x,k);D.robotsTxt&&!D.robotsTxt.skipped&&h.info(`\u{1F916} robots.txt: ${D.robotsTxt.disallowedPaths||0} disallowed paths`),D.rss&&!D.rss.skipped&&h.info(`\u{1F4E1} rss.xml: ${D.rss.postCount||0} blog posts`),D.manifest&&!D.manifest.skipped&&h.info("\u{1F4C4} seo-manifest.json")},h),p&&k.length>0&&await St(["llms-full.txt"],async()=>{let D=uo({siteName:C,baseUrl:A,description:c,appRoot:y.getAppRoot(),blogPosts:k,logger:h});D&&(await x("llms-full.txt",D),h.info("\u{1F4C4} llms-full.txt"))},h),d?.length>0&&await St(["_redirects"],async()=>{let D=new Set,R=[];for(let{from:m,to:$,permanent:U}of d){let E=m.replace(/\/+$/,"")||"/",M=$.replace(/\/+$/,"")||"/";if(E===M){h.warn(`Redirect loop detected: ${m} \u2192 ${$} (skipped)`);continue}if(!m.startsWith("/")){h.warn(`Redirect source must start with /: "${m}" (skipped)`);continue}if(D.has(E)){h.warn(`Duplicate redirect source: "${m}" (skipped)`);continue}D.add(E),R.push(`${m} ${$} ${U===!1?302:301}`)}R.length>0&&(await x("_redirects",R.join(`
|
|
813
819
|
`)+`
|
|
814
|
-
`),
|
|
820
|
+
`),h.info(`\u{1F4CE} _redirects: ${R.length} redirect${R.length>1?"s":""}`))},h)}}}q();function Ko(n={}){let{debug:e}=n;return{name:"dndev-server-shim",enforce:"pre",resolveId(t,r){return t.startsWith("node:")?(H("server-shim",e,!0).warn(`Blocking Node.js built-in module import: ${t}${r?` from ${r}`:""}`),"\0virtual:empty-server-module"):It.includes(t)||It.some(o=>t.startsWith(`${o}/`))?(H("server-shim",e,!0).warn(`Blocking server-only subpath import: ${t}${r?` from ${r}`:""}`),"\0virtual:empty-server-module"):Sn.includes(t)?(H("server-shim",e,!0).warn(`Blocking server-only import: ${t}${r?` from ${r}`:""}`),"\0virtual:empty-server-module"):null},load(t){return t==="\0virtual:empty-server-module"?`
|
|
815
821
|
// Node.js built-in modules shims for browser compatibility
|
|
816
822
|
export const URL = globalThis.URL;
|
|
817
823
|
export const URLSearchParams = globalThis.URLSearchParams;
|
|
@@ -1090,11 +1096,11 @@ export default discoveredRoutes;
|
|
|
1090
1096
|
// Google Logging Utils shims
|
|
1091
1097
|
export const LoggingWinston = class LoggingWinston {};
|
|
1092
1098
|
export const LoggingBunyan = class LoggingBunyan {};
|
|
1093
|
-
`:null}}}
|
|
1094
|
-
`}function
|
|
1099
|
+
`:null}}}q();import{createRequire as fc}from"node:module";var gc=fc(import.meta.url),Zo="ThemeIcon_",Yo;function mc(){return Yo??=new Set(Object.keys(gc("lucide-react"))),Yo}function pn(n,e){let t=mc(),r=new Set;for(let o of n){let s=o.meta?.icon;if(!s)continue;let a=String(s).replace(/['"]/g,"").trim();/^[A-Za-z][A-Za-z0-9]*$/.test(a)&&t.has(a)?r.add(a):e.warn(`\u{1F3A8} Theme "${o.name}": --theme-icon '${a}' is not a lucide-react icon name (theme toggle shows the Palette icon)`)}return[...r].sort()}function dn(n){return n.length===0?"":`import { ${n.map(t=>`${t} as ${Zo}${t}`).join(", ")} } from 'lucide-react';
|
|
1100
|
+
`}function fn(n){return`{ ${n.map(t=>`${JSON.stringify(t)}: ${Zo}${t}`).join(", ")} }`}var Xo=H("theme-plugin"),Qo={isEmpty:n=>!n.themes||n.themes.length===0,generateModule:(n,e,t="themes")=>{let{themes:r}=n;if(!r||r.length===0)return Qo.generateEmpty(n,e,void 0,t);let o=r.find(i=>i.essential&&i.name==="light")||r[0],s={totalThemes:r.length,defaultTheme:o?.name||"light",hasCustomThemes:r.some(i=>!i.essential),timestamp:new Date().toISOString()},a=pn(r,Xo);return`// Virtual module: ${V.themes}
|
|
1095
1101
|
// \u{1F680} STATIC INJECTION PATTERN - Zero Runtime Loading
|
|
1096
1102
|
// Generated by @donotdev/config at ${new Date().toISOString()}
|
|
1097
|
-
${
|
|
1103
|
+
${dn(a)}
|
|
1098
1104
|
// ===== STATIC EXPORTS - IMMEDIATE AVAILABILITY =====
|
|
1099
1105
|
export const THEMES = ${JSON.stringify(r,null,2)};
|
|
1100
1106
|
export const THEME_MANIFEST = ${JSON.stringify(s,null,2)};
|
|
@@ -1119,14 +1125,14 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1119
1125
|
}
|
|
1120
1126
|
|
|
1121
1127
|
// Populate themes configuration
|
|
1122
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1128
|
+
globalThis._DNDEV_CONFIG_.${re[t]} = {
|
|
1123
1129
|
discovered: themeData,
|
|
1124
1130
|
mapping: themeData.reduce((acc, theme) => {
|
|
1125
1131
|
acc[theme.name] = theme;
|
|
1126
1132
|
return acc;
|
|
1127
1133
|
}, {}),
|
|
1128
1134
|
// Theme icons (--theme-icon), imported by name: rendered without the lucide namespace
|
|
1129
|
-
icons: ${
|
|
1135
|
+
icons: ${fn(a)},
|
|
1130
1136
|
variables: {},
|
|
1131
1137
|
manifest: {
|
|
1132
1138
|
totalThemes: ${r.length},
|
|
@@ -1168,11 +1174,11 @@ export default {
|
|
|
1168
1174
|
getAllThemes,
|
|
1169
1175
|
getThemeNames
|
|
1170
1176
|
};
|
|
1171
|
-
`},generateEmpty:(n,e,t,r="themes")=>{let o=n.themes&&n.themes.length>0?n.themes:[{name:"light",displayName:"Light",meta:{icon:"Sun",category:"light"},essential:!0,isDark:!1,source:"built-in",variableCount:0}],s=o.find(
|
|
1177
|
+
`},generateEmpty:(n,e,t,r="themes")=>{let o=n.themes&&n.themes.length>0?n.themes:[{name:"light",displayName:"Light",meta:{icon:"Sun",category:"light"},essential:!0,isDark:!1,source:"built-in",variableCount:0}],s=o.find(c=>c.essential&&c.name==="light")||o[0],a={totalThemes:o.length,defaultTheme:s?.name||"light",hasCustomThemes:o.some(c=>!c.essential),timestamp:new Date().toISOString()},i=pn(o,Xo);return`// ${V.themes} - Using framework essential themes (fallback)
|
|
1172
1178
|
// Generated by @donotdev/config at ${new Date().toISOString()}
|
|
1173
|
-
${
|
|
1179
|
+
${dn(i)}
|
|
1174
1180
|
export const THEMES = ${JSON.stringify(o,null,2)};
|
|
1175
|
-
export const THEME_MANIFEST = ${JSON.stringify(
|
|
1181
|
+
export const THEME_MANIFEST = ${JSON.stringify(a,null,2)};
|
|
1176
1182
|
export const THEME_COUNT = ${o.length};
|
|
1177
1183
|
export const DEFAULT_THEME = '${s?.name||"light"}';
|
|
1178
1184
|
|
|
@@ -1192,13 +1198,13 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1192
1198
|
};
|
|
1193
1199
|
}
|
|
1194
1200
|
|
|
1195
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1201
|
+
globalThis._DNDEV_CONFIG_.${re[r]} = {
|
|
1196
1202
|
discovered: themeData,
|
|
1197
1203
|
mapping: themeData.reduce((acc, theme) => {
|
|
1198
1204
|
acc[theme.name] = theme;
|
|
1199
1205
|
return acc;
|
|
1200
1206
|
}, {}),
|
|
1201
|
-
icons: ${
|
|
1207
|
+
icons: ${fn(i)},
|
|
1202
1208
|
variables: {},
|
|
1203
1209
|
manifest: {
|
|
1204
1210
|
totalThemes: ${o.length},
|
|
@@ -1255,7 +1261,7 @@ export default discoveredThemes;
|
|
|
1255
1261
|
`;let r=t.find(o=>o.essential&&o.name==="light")||t[0];return`/**
|
|
1256
1262
|
* Generated Theme Discovery Results
|
|
1257
1263
|
* Generated at: ${new Date().toISOString()}
|
|
1258
|
-
* Import from '${
|
|
1264
|
+
* Import from '${V.themes}'
|
|
1259
1265
|
*/
|
|
1260
1266
|
|
|
1261
1267
|
export const discoveredThemes = ${JSON.stringify(t,null,2)};
|
|
@@ -1270,9 +1276,9 @@ export const themeManifest = {
|
|
|
1270
1276
|
};
|
|
1271
1277
|
|
|
1272
1278
|
export default discoveredThemes;
|
|
1273
|
-
`},generateManifest:n=>({themes:n.themes?.length||0,timestamp:Date.now(),hasCustomThemes:n.themes?.some(e=>!e.essential)||!1}),logConfig:n=>{},logStats:(n,e,t)=>{let r=n.themes||[],o=r.filter(
|
|
1274
|
-
Build output: ${z.length} JS, ${K.length} CSS, ${
|
|
1275
|
-
Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof
|
|
1276
|
-
\u{1F3D7}\uFE0F DnDev Framework - ${
|
|
1277
|
-
`);let
|
|
1278
|
-
${s}`:""}`);throw
|
|
1279
|
+
`},generateManifest:n=>({themes:n.themes?.length||0,timestamp:Date.now(),hasCustomThemes:n.themes?.some(e=>!e.essential)||!1}),logConfig:n=>{},logStats:(n,e,t)=>{let r=n.themes||[],o=r.filter(a=>!a.essential).length,s=r.length;t&&(s===0?t.warn(`${e} No themes discovered - using framework essential themes fallback`):t.info(`${e} Themes: ${s} discovered${o>0?` (${o} custom)`:""}`))}};function es(n={}){let e=Date.now();return H("theme-plugin",n.debug,n.verbose).debug("\u{1F3A8} Creating theme discovery plugin..."),we({pluginName:"dndev-theme",icon:"\u{1F3A8}",virtualModuleId:V.themes,DiscoveryClass:Oe,discoveryMethod:"discoverThemes",filePatterns:["**/*.css"],templates:Qo,manifestFileName:ve.manifests.theme,configKey:"themes",createDiscovery:(o,s)=>{let a=new Ue(o,{debug:s.debug,logger:H("css-extractor",s.debug,s.verbose)});return new Oe(a,o,s)}})(n)}q();Y();var Nt=new Set(["@donotdev/functions"]);function ts(){try{let n=O.getInstance(),e=n.resolveAppPath("package.json"),t=n.readSync(e,{format:"json"});if(!t)return[];let r={...t.dependencies,...t.devDependencies};return Object.keys(r).filter(o=>o.startsWith("@donotdev/")).filter(o=>!Pe.buildTimePackages.includes(o)).filter(o=>!Nt.has(o)).sort()}catch{return[]}}Y();function ns(n={}){let e=H("vite-plugins",n.debug,n.verbose);try{let{mode:t,debug:r,verbose:o,isDev:s,isPreview:a=!1,server:i={},routes:c={},themes:l={},i18n:u={},assets:p={},seo:d={},prerender:f={},pwa:g={},serverShim:v={},pluginFactory:h={},reactCompiler:y=!1,appConfig:C}=n,A=c.debug??r,w=l.debug??r,_=u.debug??r,N=p.debug??r,k=v.debug??r,x=[];x.push(Ko({...v,debug:k}));let D;try{D=O.getInstance()}catch(E){throw new Error(`Failed to initialize PathResolver: ${E.message||E}`)}x.push({name:"dndev-file-watcher-fix",enforce:"pre",configResolved(E){if(r){e.debug("\u{1F4CB} Vite resolved config (configResolved):");let z={root:E.root,mode:E.mode,envDir:E.envDir,base:E.base,build:E.build?{outDir:E.build.outDir,minify:E.build.minify}:void 0,server:E.server?{port:E.server.port,host:E.server.host}:void 0,plugins:E.plugins?{count:E.plugins.length,names:E.plugins.map(K=>K?.name||"unnamed").filter(Boolean)}:void 0};e.debug(JSON.stringify(z,null,2))}D.setAppRoot(E.root);let M=D.getAppRoot(),L=ts();if(L.length>0){let z=E.optimizeDeps?.include||[];E.optimizeDeps.include=[...new Set([...z,...L])],e.verbose(`optimizeDeps: added ${L.length} @donotdev packages`)}if(Nt.size>0){let z=E.optimizeDeps?.exclude||[],K=[...Nt];E.optimizeDeps.exclude=[...new Set([...z,...K])],e.verbose(`optimizeDeps: excluded ${K.length} server-only packages`)}if(s&&E.server?.port){let z=E.server.https?"https":"http";process.env.VITE_APP_URL=`${z}://localhost:${E.server.port}`,(r||o)&&e.debug(`VITE_APP_URL set: ${process.env.VITE_APP_URL}`)}else s&&e.warn("VITE_APP_URL not set in dev mode. Server port not available.");try{let z=D.getRepoRoot();e.verbose(`Repo: ${z}`),e.verbose(`App: ${M}`)}catch(z){e.debug(`Could not log PathResolver values: ${z.message}`)}if(E.server&&!a){let z=W=>{let Z=W.replace(/\\/g,"/"),P=M.replace(/\\/g,"/");return!Z.startsWith(P)};E.server.watch||(E.server.watch={});let K=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.turbo/**","**/.vite/**","**/functions/**","**/.generated/**"];E.server.watch={...E.server.watch,ignored:[...E.server.watch.ignored||[],...K,z]},e.verbose(`Fixed file watcher to use app root: ${M}`)}}}),x.push(Hr({appConfig:C,pwa:g.enabled,debug:r,verbose:o})),x.push(Xr({debug:r,verbose:o})),x.push(Yr({debug:r})),x.push(vc({fastRefresh:!0,jsxRuntime:"automatic",...y?{babel:{plugins:[["babel-plugin-react-compiler",{target:"19"}]]}}:{}})),x.push(yc({ignoreConfigErrors:!0})),i.https===!0&&x.push(hc());let R=Wn(),m=Jr(),$=kr();x.push(Jo({...h,...c,debug:A,routeManifest:R})),x.push(es({...h,...l,debug:w})),x.push(...qr({...h,...u,debug:_,i18nStore:m})),x.push(Kn({...h,...p,debug:N,i18nStore:m,routeManifest:R})),x.push(ar({appConfig:C})),x.push(er({...h,mode:t,debug:r,verbose:o})),x.push(qo({...d,routeManifest:R,debug:r,isDev:s})),g.enabled&&x.push(Ao({...g,debug:r})),x.push(Dr({appConfig:C,debug:r,i18nStore:m,fontPlan:$})),x.push(Xn());let U=!1;return x.push({name:"dndev-build-summary",enforce:"post",configResolved(E){U=E.command==="build"},closeBundle(){if(!U)return;let E=D,M=E.resolveAppPath("dist/assets");if(E.pathExists(M))try{let L=E.readdirSync(M),z=L.filter(Z=>Z.endsWith(".js")),K=L.filter(Z=>Z.endsWith(".css")),W=L.length-z.length-K.length;e.info(`
|
|
1280
|
+
Build output: ${z.length} JS, ${K.length} CSS, ${W} other \u2014 ${L.length} files total`)}catch{}}}),x.push(_o({...f,routeManifest:R,prerenderRecords:C?.prerenderRecords,seo:d,i18nStore:m,fontPlan:$,debug:r,verbose:o})),x}catch(t){throw H("vite-plugins",!1,!0).error(`Failed to create Vite plugins: ${t.message}`),t}}q();function bc(n){if(!n)return{};let e={};return Array.isArray(n)?n.forEach(({find:t,replacement:r})=>{typeof t=="string"&&(e[t]=r)}):typeof n=="object"&&Object.assign(e,n),e}function rs(n={}){let{alias:e,...t}=n,{conditions:r,...o}=t;return{alias:{"@":"/src",...bc(e)},dedupe:["react","react-dom","react-router-dom"],preserveSymlinks:!1,conditions:["browser","module","import","vite-app",...r||[]],...o}}function os(n={}){let{include:e=[],exclude:t=[],esbuildOptions:r={},...o}=n,s=[...e,...Pe.optionalFeatures],a=[...new Set(s)],i=[...new Set(t)];return{include:a,exclude:i,esbuildOptions:r,...o}}function Kc(n={}){return n==null&&(n={}),async(e={})=>{e==null&&(e={});try{let t=process.env.CI==="true";process.env.DNDEV_BUILD_ID||(process.env.DNDEV_BUILD_ID=t?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9));let r=e.command,o=e.mode,s=e.isPreview??!1,{appConfig:a,dndev:i,...c}=n;if(!a)throw new Error(`appConfig is required. Import appConfig from src/config/app.ts and pass it to defineViteConfig({ appConfig, ... })
|
|
1281
|
+
Make sure the import statement in vite.config.ts is: import { appConfig } from "./src/config/app";`);if(typeof a!="object"||a===null)throw new Error(`appConfig must be an object, but got ${typeof a}. Make sure you are exporting appConfig from src/config/app.ts correctly.`);let l=a?.features?{debug:a.features.debug}:void 0,u=a?.seo===!1?{disabled:!0}:a?.seo&&typeof a.seo!="boolean"?{...a.seo,siteName:a.seo.siteName||a.app?.name,siteDescription:a.app?.description}:a?.app?.name?{siteName:a.app.name,siteDescription:a.app.description}:void 0,{features:p,seo:d,...f}=c,g=a?.app?{name:a.app.name,shortName:a.app.shortName,description:a.app.description}:void 0,{pwa:v={},...h}=f,y={...v,app:v.app||g},C={...l?{features:l}:{},...u?{seo:u}:{},...Object.keys(y).length>0?{pwa:y}:{},...h,mode:o},A;try{A=In(C)}catch(se){throw new Error(`mergeOptions failed: ${se?.message||se||"Unknown error"}`)}let w;try{w=Fn(A)}catch(se){throw new Error(`normalizeOptions failed: ${se?.message||se||"Unknown error"}`)}if(!w)throw new Error("normalizeOptions returned undefined");let{mode:_,debug:N,verbose:k,isDev:x,isDebug:D,shouldAnalyze:R,serverOptions:m,previewOptions:$,buildOverrides:U,resolveOptions:E,routeOptions:M,themeOptions:L,i18nOptions:z,assetOptions:K,featureOptions:W,seoOptions:Z,prerenderOptions:P,pwaOptions:I,serverShimOptions:F,chunkingOptions:G,pluginFactoryOptions:Q,reactCompiler:X,base:te,defineOptions:xe,optimizeDepsOptions:S,pluginsOptions:T,cssOptions:J,envDir:he,restOptions:ne}=w,rt=H("vite-config",N,k);rt.debug(`Mode: ${_}, Dev: ${x}`);let hn=process.env.DNDEV_BUILD_ID,qe;r==="build"?qe=`Building for ${_}`:s?qe=`Preview server (serving ${_} build)`:r==="serve"?qe=`Development server (${_})`:qe=`Running ${r} (${_})`,rt.info(`
|
|
1282
|
+
\u{1F3D7}\uFE0F DnDev Framework - ${qe}${hn?` [build:${hn}]`:""}`),rt.info(` Platform: Vite | Command: ${r} | Mode: ${_}
|
|
1283
|
+
`);let ot=ns({appConfig:a,mode:_,debug:N,verbose:k,isDev:x,isPreview:s,routes:M,themes:L,i18n:z,assets:K,features:W,seo:Z,prerender:P,pwa:I,serverShim:F,chunkingOptions:G,pluginFactory:Q,reactCompiler:X});if(!Array.isArray(ot))throw new Error(`createVitePlugins returned ${typeof ot}, expected array. Value: ${ot}`);let fs=Nn({mode:_,chunkingOptions:G,debug:N,isDev:x,isDebug:D,shouldAnalyze:R}),gs=s?void 0:kn(m.port||3e3,m,rt),ms=s?Dn($):void 0;if(i)try{let{createDndevPlugin:se}=await Promise.resolve().then(()=>(ds(),ps));T.push(se(typeof i=="object"?i:{}))}catch{}return{...te&&{base:te},plugins:[...ot,...T],appType:"spa",assetsInclude:["**/*.woff","**/*.woff2","**/*.ttf","**/*.otf","**/*.eot"],..._==="production"&&{build:fs},...r==="serve"&&!s&&{server:gs},...s&&{preview:ms},...he&&{envDir:he},customLogger:_==="production"&&!N?(()=>{let se={hasWarned:!1,_shouldSuppress(ue){return ue.includes("dist/")||ue.includes("kB")||ue.includes("\u2502")||ue.includes("gzip:")||ue.includes("\u2713 built in")||ue.match(/built in \d+\.\d+s/)},info(ue){se._shouldSuppress(ue)},warn(ue){se._shouldSuppress(ue)},error(ue){},warnOnce(ue){se.hasWarned||(se.hasWarned=!0)},clearScreen(){},hasErrorLogged(){return!1}};return se})():void 0,css:{postcss:Ln(J),...J},optimizeDeps:os(S),resolve:rs(E),define:{...xe,"process.env.NODE_ENV":JSON.stringify(o),__DEV__:JSON.stringify(x),__PROD__:JSON.stringify(!x)},...ne}}catch(t){let r=t||new Error("Unknown error occurred"),o=r?.message||r?.toString()||String(r)||"Unknown error",s=r?.stack||"",a=new Error(`Failed to create Vite config: ${o}${s?`
|
|
1284
|
+
${s}`:""}`);throw a.stack=s||a.stack,a}}}export{Kc as defineViteConfig};
|