@donotdev/core 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/functions/index.d.ts +99 -10
- package/functions/index.js +20 -18
- package/i18n/flags/af.svg +1 -0
- package/i18n/flags/al.svg +1 -0
- package/i18n/flags/am.svg +1 -0
- package/i18n/flags/ar.svg +1 -0
- package/i18n/flags/at.svg +1 -0
- package/i18n/flags/au.svg +1 -0
- package/i18n/flags/az.svg +1 -0
- package/i18n/flags/ba.svg +1 -0
- package/i18n/flags/bd.svg +1 -0
- package/i18n/flags/be.svg +1 -0
- package/i18n/flags/bg.svg +1 -0
- package/i18n/flags/bn.svg +1 -0
- package/i18n/flags/br.svg +1 -0
- package/i18n/flags/bs.svg +1 -0
- package/i18n/flags/by.svg +1 -0
- package/i18n/flags/bzh.svg +1 -0
- package/i18n/flags/ca.svg +1 -0
- package/i18n/flags/ch.svg +1 -0
- package/i18n/flags/co.svg +1 -0
- package/i18n/flags/cs.svg +1 -0
- package/i18n/flags/cy.svg +1 -0
- package/i18n/flags/da.svg +1 -0
- package/i18n/flags/de.svg +1 -0
- package/i18n/flags/dz.svg +1 -0
- package/i18n/flags/ee.svg +1 -0
- package/i18n/flags/el.svg +1 -0
- package/i18n/flags/en.svg +1 -0
- package/i18n/flags/es.svg +1 -0
- package/i18n/flags/et.svg +1 -0
- package/i18n/flags/eu.svg +1 -0
- package/i18n/flags/fa.svg +1 -0
- package/i18n/flags/fi.svg +1 -0
- package/i18n/flags/fr-cor.svg +1 -0
- package/i18n/flags/fr.svg +1 -0
- package/i18n/flags/ga.svg +1 -0
- package/i18n/flags/gb-sct.svg +1 -0
- package/i18n/flags/gb.svg +1 -0
- package/i18n/flags/gd.svg +1 -0
- package/i18n/flags/ge.svg +1 -0
- package/i18n/flags/gl.svg +1 -0
- package/i18n/flags/gu.svg +1 -0
- package/i18n/flags/he.svg +1 -0
- package/i18n/flags/hi.svg +1 -0
- package/i18n/flags/hr.svg +1 -0
- package/i18n/flags/hu.svg +1 -0
- package/i18n/flags/hy.svg +1 -0
- package/i18n/flags/id.svg +1 -0
- package/i18n/flags/ie.svg +1 -0
- package/i18n/flags/in.svg +1 -0
- package/i18n/flags/ir.svg +1 -0
- package/i18n/flags/is.svg +1 -0
- package/i18n/flags/it.svg +1 -0
- package/i18n/flags/ja.svg +1 -0
- package/i18n/flags/ke.svg +1 -0
- package/i18n/flags/kg.svg +1 -0
- package/i18n/flags/kh.svg +1 -0
- package/i18n/flags/kk.svg +1 -0
- package/i18n/flags/km.svg +1 -0
- package/i18n/flags/kn.svg +1 -0
- package/i18n/flags/ko.svg +1 -0
- package/i18n/flags/kz.svg +1 -0
- package/i18n/flags/la.svg +1 -0
- package/i18n/flags/lb.svg +1 -0
- package/i18n/flags/lk.svg +1 -0
- package/i18n/flags/lt.svg +1 -0
- package/i18n/flags/lv.svg +1 -0
- package/i18n/flags/ly.svg +1 -0
- package/i18n/flags/ma.svg +1 -0
- package/i18n/flags/md.svg +1 -0
- package/i18n/flags/mk.svg +1 -0
- package/i18n/flags/ml.svg +1 -0
- package/i18n/flags/mm.svg +1 -0
- package/i18n/flags/mn.svg +1 -0
- package/i18n/flags/mr.svg +1 -0
- package/i18n/flags/ms.svg +1 -0
- package/i18n/flags/mt.svg +1 -0
- package/i18n/flags/mx.svg +1 -0
- package/i18n/flags/my.svg +1 -0
- package/i18n/flags/ne.svg +1 -0
- package/i18n/flags/nl.svg +1 -0
- package/i18n/flags/no.svg +1 -0
- package/i18n/flags/np.svg +1 -0
- package/i18n/flags/oc.svg +1 -0
- package/i18n/flags/pa.svg +1 -0
- package/i18n/flags/pk.svg +1 -0
- package/i18n/flags/pl.svg +1 -0
- package/i18n/flags/ps.svg +1 -0
- package/i18n/flags/pt.svg +1 -0
- package/i18n/flags/rm.svg +1 -0
- package/i18n/flags/ro.svg +1 -0
- package/i18n/flags/ru.svg +1 -0
- package/i18n/flags/sa.svg +1 -0
- package/i18n/flags/si.svg +1 -0
- package/i18n/flags/sk.svg +1 -0
- package/i18n/flags/sl.svg +1 -0
- package/i18n/flags/sr.svg +1 -0
- package/i18n/flags/sv.svg +1 -0
- package/i18n/flags/sw.svg +1 -0
- package/i18n/flags/ta.svg +1 -0
- package/i18n/flags/te.svg +1 -0
- package/i18n/flags/th.svg +1 -0
- package/i18n/flags/tj.svg +1 -0
- package/i18n/flags/tl.svg +1 -0
- package/i18n/flags/tn.svg +1 -0
- package/i18n/flags/tr.svg +1 -0
- package/i18n/flags/ua.svg +1 -0
- package/i18n/flags/ur.svg +1 -0
- package/i18n/flags/us.svg +1 -0
- package/i18n/flags/uz.svg +1 -0
- package/i18n/flags/vi.svg +1 -0
- package/i18n/flags/za.svg +1 -0
- package/i18n/flags/zh.svg +1 -0
- package/i18n/locales/eager/dndev_ar.json +2 -1
- package/i18n/locales/eager/dndev_da.json +2 -1
- package/i18n/locales/eager/dndev_de.json +2 -1
- package/i18n/locales/eager/dndev_en.json +2 -1
- package/i18n/locales/eager/dndev_es.json +2 -1
- package/i18n/locales/eager/dndev_fr.json +2 -1
- package/i18n/locales/eager/dndev_it.json +2 -1
- package/i18n/locales/eager/dndev_ja.json +2 -1
- package/i18n/locales/eager/dndev_ko.json +2 -1
- package/i18n/locales/eager/dndev_nl.json +2 -1
- package/i18n/locales/eager/dndev_pl.json +2 -1
- package/i18n/locales/eager/dndev_pt.json +2 -1
- package/i18n/locales/eager/dndev_zh.json +2 -1
- package/i18n/locales/lazy/auth_ar.json +19 -2
- package/i18n/locales/lazy/auth_da.json +22 -2
- package/i18n/locales/lazy/auth_de.json +19 -2
- package/i18n/locales/lazy/auth_en.json +19 -2
- package/i18n/locales/lazy/auth_es.json +19 -2
- package/i18n/locales/lazy/auth_fr.json +19 -2
- package/i18n/locales/lazy/auth_it.json +19 -2
- package/i18n/locales/lazy/auth_ja.json +19 -2
- package/i18n/locales/lazy/auth_ko.json +19 -2
- package/i18n/locales/lazy/auth_nl.json +22 -2
- package/i18n/locales/lazy/auth_pl.json +19 -2
- package/i18n/locales/lazy/auth_pt.json +19 -2
- package/i18n/locales/lazy/auth_zh.json +19 -2
- package/i18n/locales/lazy/crud_ar.json +3 -1
- package/i18n/locales/lazy/crud_da.json +3 -1
- package/i18n/locales/lazy/crud_de.json +3 -1
- package/i18n/locales/lazy/crud_en.json +3 -1
- package/i18n/locales/lazy/crud_es.json +3 -1
- package/i18n/locales/lazy/crud_fr.json +3 -1
- package/i18n/locales/lazy/crud_it.json +3 -1
- package/i18n/locales/lazy/crud_ja.json +3 -1
- package/i18n/locales/lazy/crud_ko.json +3 -1
- package/i18n/locales/lazy/crud_nl.json +3 -1
- package/i18n/locales/lazy/crud_pl.json +3 -1
- package/i18n/locales/lazy/crud_pt.json +3 -1
- package/i18n/locales/lazy/crud_zh.json +3 -1
- package/index.d.ts +6927 -6153
- package/index.js +3 -3
- package/next/index.d.ts +250 -23
- package/next/index.js +556 -594
- package/next/runtime.js +3 -3
- package/package.json +4 -3
- package/server.d.ts +6950 -6153
- package/shared.js +2 -1
- package/symbol-index.json +1 -1
- package/vite/index.d.ts +85 -10
- package/vite/index.js +152 -152
- package/chunks/FlagBase-IQILJTOA.js +0 -1
- package/chunks/chunk-I6HT4XNS.js +0 -1
- package/chunks/chunk-PX544BGJ.js +0 -1
- package/chunks/flagAF-JHV34XMS.js +0 -1
- package/chunks/flagAL-UH6NKHXO.js +0 -1
- package/chunks/flagAM-7XYXA6G6.js +0 -1
- package/chunks/flagAR-LO3YLUZF.js +0 -1
- package/chunks/flagAT-6SWWBNVY.js +0 -1
- package/chunks/flagAU-FIJG7J4T.js +0 -1
- package/chunks/flagAZ-6AIO4DNL.js +0 -1
- package/chunks/flagBA-PIQRWY42.js +0 -1
- package/chunks/flagBD-7PXOE6GM.js +0 -1
- package/chunks/flagBE-2ZP6HCIM.js +0 -1
- package/chunks/flagBG-4XSHCVYH.js +0 -1
- package/chunks/flagBN-OF5XRA5N.js +0 -1
- package/chunks/flagBR-Y2266PSZ.js +0 -1
- package/chunks/flagBS-UV5PVKWJ.js +0 -1
- package/chunks/flagBY-MNAFXBA6.js +0 -1
- package/chunks/flagBZH-AOCZVEVI.js +0 -1
- package/chunks/flagCA-VR6MSBTS.js +0 -1
- package/chunks/flagCH-Q7MV5SPV.js +0 -1
- package/chunks/flagCO-C2YBOMO2.js +0 -1
- package/chunks/flagCS-5BC7NJX6.js +0 -1
- package/chunks/flagCY-PPAUTJGB.js +0 -1
- package/chunks/flagDA-LPI2JRTO.js +0 -1
- package/chunks/flagDE-MQDJAEWL.js +0 -1
- package/chunks/flagDZ-M6NVCF3D.js +0 -1
- package/chunks/flagEE-LY2JJ44X.js +0 -1
- package/chunks/flagEL-PP2HZIV7.js +0 -1
- package/chunks/flagEN-TGFHJYK7.js +0 -1
- package/chunks/flagES-C3H6SSSI.js +0 -1
- package/chunks/flagET-GEZLWRTF.js +0 -1
- package/chunks/flagEU-YJF5577W.js +0 -1
- package/chunks/flagFA-QCQKNEUZ.js +0 -1
- package/chunks/flagFI-LN5ICHNF.js +0 -1
- package/chunks/flagFR-5JPZSUVS.js +0 -1
- package/chunks/flagFR-COR-KPRNU2U6.js +0 -1
- package/chunks/flagGA-PUAQ7VY3.js +0 -1
- package/chunks/flagGB-SCT-RJGHRDJP.js +0 -1
- package/chunks/flagGB-XD2JB7EC.js +0 -1
- package/chunks/flagGD-ABOZBNKE.js +0 -1
- package/chunks/flagGE-N7C2KHVA.js +0 -1
- package/chunks/flagGL-AO2LC4XU.js +0 -1
- package/chunks/flagGU-RNGQ3TIY.js +0 -1
- package/chunks/flagHE-QUAWLF43.js +0 -1
- package/chunks/flagHI-JOOJFNKB.js +0 -1
- package/chunks/flagHR-2U7YEA7P.js +0 -1
- package/chunks/flagHU-6SPEV3OO.js +0 -1
- package/chunks/flagHY-L62LW6BP.js +0 -1
- package/chunks/flagID-LV75M4R3.js +0 -1
- package/chunks/flagIE-LBTC7LCK.js +0 -1
- package/chunks/flagIN-3UWOJ2S3.js +0 -1
- package/chunks/flagIR-44N33GFX.js +0 -1
- package/chunks/flagIS-VCPTXPLZ.js +0 -1
- package/chunks/flagIT-KB4NWTBO.js +0 -1
- package/chunks/flagJA-KLHM6VYH.js +0 -1
- package/chunks/flagKE-MZONPGAJ.js +0 -1
- package/chunks/flagKG-VF3T4E3E.js +0 -1
- package/chunks/flagKH-K5ZXX3DS.js +0 -1
- package/chunks/flagKK-ZZTJKPMR.js +0 -1
- package/chunks/flagKM-Y3XA6HXW.js +0 -1
- package/chunks/flagKN-OMVHGIUS.js +0 -1
- package/chunks/flagKO-UBLOXGRF.js +0 -1
- package/chunks/flagKZ-PYOALOB6.js +0 -1
- package/chunks/flagLA-4ONTEYIB.js +0 -1
- package/chunks/flagLB-FGOBUCL4.js +0 -1
- package/chunks/flagLK-BEVYO56P.js +0 -1
- package/chunks/flagLT-TYWQGIIQ.js +0 -1
- package/chunks/flagLV-S34SVWJJ.js +0 -1
- package/chunks/flagLY-AVR5B6N3.js +0 -1
- package/chunks/flagMA-KHTPMDTL.js +0 -1
- package/chunks/flagMD-TQMYMRQI.js +0 -1
- package/chunks/flagMK-C4CIIAUH.js +0 -1
- package/chunks/flagML-JEE5UGDD.js +0 -1
- package/chunks/flagMM-M72A7CHZ.js +0 -1
- package/chunks/flagMN-34CH7Q43.js +0 -1
- package/chunks/flagMR-KIJ2BPCC.js +0 -1
- package/chunks/flagMS-6COZCDLY.js +0 -1
- package/chunks/flagMT-HDBP7BED.js +0 -1
- package/chunks/flagMX-3XBPZTP5.js +0 -1
- package/chunks/flagMY-Y7C3QGRG.js +0 -1
- package/chunks/flagNE-LCWCYEQW.js +0 -1
- package/chunks/flagNL-3RFQSLLH.js +0 -1
- package/chunks/flagNO-RNDXHKBT.js +0 -1
- package/chunks/flagNP-IKVTRWFR.js +0 -1
- package/chunks/flagOC-JWCST6MI.js +0 -1
- package/chunks/flagPA-5SGZJRNZ.js +0 -1
- package/chunks/flagPK-KQ674PEZ.js +0 -1
- package/chunks/flagPL-V2ITOKFK.js +0 -1
- package/chunks/flagPS-WBOKI4MV.js +0 -1
- package/chunks/flagPT-PFIUVBWR.js +0 -1
- package/chunks/flagRM-MEV6U4AJ.js +0 -1
- package/chunks/flagRO-JPMXEGLK.js +0 -1
- package/chunks/flagRU-3BBKEK34.js +0 -1
- package/chunks/flagSA-N7OI2M6Y.js +0 -1
- package/chunks/flagSI-UTODFLQZ.js +0 -1
- package/chunks/flagSK-EV5JZ2DI.js +0 -1
- package/chunks/flagSL-Y4LHIV2J.js +0 -1
- package/chunks/flagSR-MTRWQPJ5.js +0 -1
- package/chunks/flagSV-LYVDSSJ4.js +0 -1
- package/chunks/flagSW-GJO5P4HE.js +0 -1
- package/chunks/flagTA-CDT3KYEB.js +0 -1
- package/chunks/flagTE-5EXMXH6E.js +0 -1
- package/chunks/flagTH-ODJA4CWB.js +0 -1
- package/chunks/flagTJ-CE5SV6V4.js +0 -1
- package/chunks/flagTL-TRVUF3XO.js +0 -1
- package/chunks/flagTN-G6ERYSZ3.js +0 -1
- package/chunks/flagTR-33VFGL2S.js +0 -1
- package/chunks/flagUA-HESNDKQJ.js +0 -1
- package/chunks/flagUR-ECIZZCDG.js +0 -1
- package/chunks/flagUS-M7R4WRRU.js +0 -1
- package/chunks/flagUZ-YW54WCES.js +0 -1
- package/chunks/flagVI-K3DF2THA.js +0 -1
- package/chunks/flagZA-5UIOKDJH.js +0 -1
- package/chunks/flagZH-5IE3RZVQ.js +0 -1
package/next/index.js
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
|
-
import*as R from"node:fs";import"node:fs";import{createRequire as Or}from"node:module";import{resolve as Re,join as oe,dirname as ae,relative as Tt,normalize as Fr,sep as Dt,extname as Ir}from"node:path";import{fileURLToPath as Lr}from"node:url";import Ur from"fast-glob";var ye={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var He={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},J={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},Z={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},F={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"}},ce="/og-image.png",qe={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},be={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},_e={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},V={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${_e.SOURCE_EAGER}/*_*.json`],lazy:[`${_e.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},ke={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"]},_t=["firebase-admin","gcp-metadata","google-logging-utils","payload","undici","@fastify/busboy","image-size","@donotdev/tooling","fs","path","crypto","net","tls","http","https","child_process","os","util","stream","buffer","events","querystring","url","zlib","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","cluster","dgram","dns","http2","inspector","module","perf_hooks","process","readline","repl","trace_events","v8","wasi"];var Ve={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)/}},we={Inter:"inter","Space Grotesk":"space-grotesk","Playfair Display":"playfair-display","Press Start 2P":"press-start-2p",Roboto:"roboto"},ue={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]},kt={inter:"sans-serif","playfair-display":"serif",roboto:"sans-serif","space-grotesk":"sans-serif","press-start-2p":"sans-serif"},Nt={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:[]},Je=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],At={base:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...V.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...V.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:V.globalIgnore}};function Ct(o,e=null){let t=V[o];if(!t)throw new Error(`Unknown pattern type: ${o}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Ne(o){return At[o]||At.base}var he={getGlobOptionsFor:Ne||void 0,SCAN_PATTERNS:V||void 0,getPatternsFor:Ct||void 0,I18N_PATHS:_e||void 0},L={error:(o,e)=>{},warn:(o,e)=>{},info:o=>{}};function ge(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="EEXIST"}function Ot(o,e){return o().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var Ft={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},$=class o{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return o._instance||(o._instance=new o(e)),o._instance}static _reset(){o._instance=null}constructor(e={}){if(o._instance)return o._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,o._instance=this}normalizePath(e){if(!e)return"";try{return Fr(e).split(Dt).join("/")}catch{return String(e).split(Dt).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=Tt(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(ae(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),n=Or(oe(s,"package.json")).resolve(e);return this.normalizePath(n)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let r=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(r))return r;let n=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(n)?n:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=Re(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),r=Re(t,s);return this.normalizePath(r)}resolvePath(e,t){let s=this.normalizePath(t),r=this.normalizePath(e),n=Re(s,r);return this.normalizePath(n)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=R.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:Ir(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return await R.promises.readFile(e);let a=await R.promises.readFile(e,r),i=this.stripBom(a);return n==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&L.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:s="auto",encoding:r="utf8"}=t,n=this._detectFormat(e,s);try{if(n==="buffer")return R.readFileSync(e);let a=R.readFileSync(e,r),i=this.stripBom(a);return n==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&L.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,s={}){let{format:r="auto",overwrite:n=!1,dryRun:a=!1,verbose:i=!1}=s,l=this.normalizePath(e),p=this.normalizePath(ae(l)),c=this.pathExists(l);if(c&&!n)return i&&L.info(`Skipping existing file: ${l}`),!1;if(a)return L.info(`[DRY RUN] Would write file: ${l}`),!0;try{await R.promises.mkdir(p,{recursive:!0})}catch(g){if(!ge(g))throw g}let u=this._detectFormat(e,r),h;Buffer.isBuffer(t)?h=t:u==="json"&&typeof t=="object"?h=`${JSON.stringify(t,null,2)}
|
|
2
|
-
`:
|
|
3
|
-
`:
|
|
4
|
-
|
|
5
|
-
`;a.appendFile(i,f)}},p=(c,u)=>{if(u.length===0)return c;let h=u.map(g=>typeof g=="object"?JSON.stringify(g,null,2):String(g)).join(" ");return`${c} ${h}`};return{debug:(c,...u)=>{e&&(n?l("DEBUG",c,u):W.log.message(Q(p(c,u),Y.gray)))},verbose:(c,...u)=>{t&&(n?l("VERBOSE",c,u):W.log.message(p(c,u)))},info:(c,...u)=>{n?l("INFO",c,u):W.log.info(Q(p(c,u),Y.brightCyan))},warn:(c,...u)=>{e&&n?l("WARN",c,u):W.log.warn(Q(p(c,u),Y.brightYellow))},error:(c,...u)=>{e&&n?l("ERROR",c,u):W.log.error(Q(p(c,u),Y.brightRed))},success:(c,...u)=>{e&&n?l("SUCCESS",c,u):W.log.success(Q(p(c,u),Y.brightGreen))},when:(c,u="debug")=>(h,...g)=>{if(c){let d=p(h,g);switch(u){case"verbose":t&&(W.log.message(d),l("VERBOSE",h,g));break;case"info":W.log.info(Q(d,Y.brightCyan)),l("INFO",h,g);break;case"warn":W.log.warn(Q(d,Y.brightYellow)),l("WARN",h,g);break;case"error":W.log.error(Q(d,Y.brightRed)),l("ERROR",h,g);break;case"success":W.log.success(Q(d,Y.brightGreen)),l("SUCCESS",h,g);break;default:e&&(W.log.message(Q(d,Y.gray)),l("DEBUG",h,g))}}},getLogFilePath:()=>i}}var Lt=jr(import.meta.url),Xe;function Gr(){return Xe===void 0&&(Xe=[[Lt.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],Lt.resolve("@babel/plugin-transform-parameters")]),Xe}function Ut({logger:o=B("lower-destructuring-next",!1,!1),debug:e=!1}={}){return{apply(t){let{webpack:s}=t,{Compilation:r,sources:n}=s,{RawSource:a}=n;t.hooks.thisCompilation.tap("DndevLowerDestructuring",i=>{i.compiler.isChild()||i.compiler.name?.includes("server")||i.options.mode==="production"&&i.hooks.processAssets.tapPromise({name:"DndevLowerDestructuring",stage:r.PROCESS_ASSETS_STAGE_REPORT},async l=>{let p,c;try{p=(await import("@babel/core")).default,c=Gr()}catch(h){o.warn(`Safari destructuring fix skipped \u2014 Babel not resolvable: ${h?.message}`);return}let u=0;for(let h of Object.keys(l)){if(!h.endsWith(".js"))continue;let g=i.getAsset(h).source.source(),d=typeof g=="string"?g:g.toString("utf8"),f;try{f=p.transformSync(d,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:c})}catch(w){throw new Error(`[lower-destructuring] failed to transform ${h}: ${w.message}`)}f?.code&&f.code!==d&&(i.updateAsset(h,new a(f.code)),u++)}e&&o.debug(`Safari destructuring fix: lowered ${u} client chunks`)})})}}}function Mt({postcssImport:o,postcssNesting:e,autoprefixer:t,resolve:s}){return{plugins:[s?o({resolve:s}):o,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}var jt={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function Br(o){return(e,t)=>{jt[e]&&(e=jt[e]);let s=o.resolvePackage(e,t);if(s)return s;if(e.startsWith("@donotdev/")){let r=e.split("/")[0]+"/"+e.split("/")[1],n=e.split("/").slice(2).join("/"),a=o.resolveFrameworkPackage(r,t);if(a){if(n){let l=o.resolvePath(n,a);if(o.pathExists(l))return l;let p=l+".css";if(o.pathExists(p))return p}let i=o.resolvePath("index.css",a);if(o.pathExists(i))return i}}return o.resolvePath(e,t)}}async function zr(){let[o,e,t]=await Promise.all([import("postcss-import").then(r=>r.default),import("postcss-nesting").then(r=>r.default),import("autoprefixer").then(r=>r.default)]),s=$.getInstance();return Mt({postcssImport:o,postcssNesting:e,autoprefixer:t,resolve:Br(s)})}import{renameSync as Wr}from"node:fs";import{basename as Gt,dirname as Hr,join as Ye,relative as qr}from"node:path";var ie="next",Vr=["tsx","ts","jsx","js"],Bt=Vr.map(o=>`${ie}.${o}`);function I(o,e){return`${o}.${ie}.${e}`}var Jr=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],Xr=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],Kr=["proxy","middleware","instrumentation"],Yr="// Generated by @donotdev/config";function Ke(o,e){let t=o.match(new RegExp(`^(.+?)(\\.${ie})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,s,r,n]=t;return e.includes(s)?{name:s,extension:n,marked:!!r}:null}function Zr(o){let e=[],t=o.resolveAppPath("src/app"),s=r=>{for(let n of o.readdirSync(r,{withFileTypes:!0})){let a=Ye(r,n.name);if(n.isDirectory()){s(a);continue}if(!n.isFile())continue;let i=Ke(n.name,Jr);i&&e.push({file:a,...i,metadata:!1});let l=Ke(n.name,Xr);l&&e.push({file:a,...l,metadata:!0})}};o.pathExists(t)&&s(t);for(let r of[o.resolveAppPath("src"),o.getAppRoot()])if(o.pathExists(r))for(let n of o.readdirSync(r,{withFileTypes:!0})){let a=n.isFile()&&Ke(n.name,Kr);a&&e.push({file:Ye(r,n.name),...a,metadata:!1})}return e}function zt({pathResolver:o,logger:e,isCI:t}){let s=o.getAppRoot(),r=p=>qr(s,p),n=[],a=[],i=[],l=[];for(let p of Zr(o)){let c=o.readSync(p.file,{format:"text"})||"";if(!p.marked&&c.startsWith(Yr)){o.removeSync(p.file),a.push(r(p.file));continue}p.metadata?l.push(r(p.file)):p.marked||i.push(p)}if(l.length>0)throw new Error(`[dndev] Next ignores code metadata files with the framework's file marker: ${l.join(", ")}. Serve each as a route handler (e.g. src/app/robots.txt/${I("route","ts")}) or a static file (icon.png, opengraph-image.png). The sitemap and llms.txt are generated by the framework.`);if(t&&i.length>0)throw new Error(`[dndev] Next files must carry the .${ie}. marker (src/pages is never a Next route). Rename: `+i.map(({file:p,name:c,extension:u})=>`${r(p)} \u2192 ${I(c,u)}`).join(", ")+". Running the app once in development renames them.");for(let{file:p,name:c,extension:u}of i){let h=Ye(Hr(p),I(c,u));if(o.pathExists(h))throw new Error(`[dndev] Both ${r(p)} and ${r(h)} exist. Next only reads *.${ie}.* files: merge ${Gt(p)} into ${Gt(h)} and delete it.`);Wr(p,h),n.push(r(p))}return n.length>0&&e.warn(`Next files renamed to *.${ie}.* (src/pages is never a Next route): ${n.join(", ")}. Commit the renames.`),a.length>0&&e.debug(`Removed generated Next files without marker: ${a.join(", ")}`),{renamed:n,removed:a}}function se(o){return o&&typeof o=="object"&&!Array.isArray(o)}var Ht={"@donotdev/ui/dndev.css":"@donotdev/ui/dndev-next.css"};function qt({originalWebpack:o,unusedFeaturePackages:e,usedFeaturePackages:t,missingOptionalDeps:s=[],flagCodes:r=[],logger:n,debug:a}){return(i,l)=>{let{dev:p,isServer:c,webpack:u}=l;p&&!c&&(i.infrastructureLogging={level:"error"},i.stats={...i.stats,logging:"error",loggingTrace:!1},i.ignoreWarnings=[...i.ignoreWarnings||[],/WebSocket connection to/,/WebSocket closed without opened/,/failed to connect to websocket/,/WebSocket error/]);let h=i.module?.rules?.find(g=>g.test?.test?.(".svg"));h&&(h.exclude=/\.svg$/i),i.module=i.module||{},i.module.rules=i.module.rules||[],i.module.rules.push({test:/\.svg$/i,type:"asset/resource",generator:{filename:"static/media/[name].[hash][ext]"}}),i.module.rules.push({test:/\.md$/,type:"asset/source"}),i.resolve=i.resolve||{},i.resolve.alias=i.resolve.alias||{};try{let g=$.getInstance(),d=g.resolveAppPath(F.next.blogContent);i.resolve.alias[He.blog]=Wt.existsSync(d)?d:g.getEmptyCjsModulePath()}catch(g){n.debug(`Blog content alias fallback to empty stub: ${g?.message}`)}if(i.resolve=i.resolve||{},i.resolve.alias={...i.resolve.alias,...Ht},u?.IgnorePlugin&&i.plugins.push(new u.IgnorePlugin({resourceRegExp:/^(vite|@vitejs|vite-tsconfig-paths)$/})),!c)try{i.plugins.push(Ut({logger:n,debug:a}))}catch(g){n.debug(`Lower-destructuring webpack plugin skipped: ${g?.message}`)}if(e.length>0)if(n.info(`\u{1F6AB} Excluding unused features: ${e.join(", ")}`),n.info(`\u2705 Including features: ${t.join(", ")}`),i.externals=i.externals||[],Array.isArray(i.externals))i.externals.push(...e);else{let g=i.externals;i.externals=(d,f,w)=>e.includes(f)?w(null,"commonjs "+f):typeof g=="function"?g(d,f,w):w()}if(s.length>0&&u?.NormalModuleReplacementPlugin){let d=$.getInstance().getEmptyCjsModulePath(),f=s.map(y=>y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),w=new RegExp(`^(${f.join("|")})(\\/|$)`);i.plugins.push(new u.NormalModuleReplacementPlugin(w,d)),a&&n.debug(`Aliased ${s.length} missing optional deps to empty module`)}if(r.length>0&&u?.NormalModuleReplacementPlugin){let d=$.getInstance().getEmptyFlagModulePath(),f=new Set(r.map(w=>w.toUpperCase()));i.plugins.push(new u.NormalModuleReplacementPlugin(/flags\/raw\/flag([A-Z][A-Z0-9_-]*)\./,w=>{let y=w.request.match(/flag([A-Z][A-Z0-9_-]*)\./i);y&&y[1].toUpperCase()!=="BASE"&&!f.has(y[1].toUpperCase())&&(w.request=d)})),a&&n.debug(`Flag filter: allowing ${f.size} flags, aliasing rest to empty component`)}return o?o(i,l):i}}function Vt({originalRewrites:o,handlers:e,logger:t}){return async function(){try{let s=o?await o():[],n=e.filter(i=>i?.getAPIRewrites).map(i=>i.getAPIRewrites()).reduce((i,l)=>(l?.beforeFiles&&i.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&i.afterFiles.push(...l.afterFiles),l?.fallback&&i.fallback.push(...l.fallback),i),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(s)?[]:s?.beforeFiles||[],...n.beforeFiles],afterFiles:[...Array.isArray(s)?s:s?.afterFiles||[],...n.afterFiles],fallback:[...Array.isArray(s)?[]:s?.fallback||[],...n.fallback]}}catch(s){return t.error(`Next.js config failed to merge rewrites: ${s.message}`),t.error(`Stack: ${s.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function Jt({originalRedirects:o,seoRedirects:e,logger:t}){return async function(){try{let s=o?await o():[],r=(e||[]).map(({from:l,to:p,permanent:c})=>({source:l,destination:p,permanent:c!==!1})),n=[],a=new Set;for(let l of r){let p=l.source.replace(/\/+$/,"")||"/",c=l.destination.replace(/\/+$/,"")||"/";if(p===c){t.warn(`Redirect loop detected: ${l.source} \u2192 ${l.destination} (skipped)`);continue}if(!l.source.startsWith("/")){t.warn(`Redirect source must start with /: "${l.source}" (skipped)`);continue}if(a.has(p)){t.warn(`Duplicate redirect source: "${l.source}" (skipped)`);continue}a.add(p),n.push(l)}let i=[...Array.isArray(s)?s:[],...n];return i.length===0?[]:(t.info(` \u{1F4CE} ${i.length} redirect${i.length>1?"s":""} configured`),i)}catch(s){return t.error(`Failed to merge redirects: ${s.message}`),[]}}}function Xt({policyRules:o,originalHeaders:e}){if(e!==void 0&&typeof e!="function")throw new Error("[dndev] next.config headers must be a function returning an array (Next headers() contract).");return async function(){let s=e?await e():[];if(!Array.isArray(s))throw new Error(`[dndev] next.config headers() must return an array (got ${typeof s}).`);return[...o,...s]}}function Kt({routeResult:o,themeResult:e,i18nResult:t,assetResult:s,seoResult:r,pwaResult:n,serverShimResult:a,restNextConfig:i,discoveredPackages:l,reactCompiler:p=!1,routingMode:c,webpackConfig:u,rewritesConfig:h,redirectsConfig:g,headersConfig:d,missingOptionalDeps:f,flagCodes:w=[],pathResolver:y,env:A,logger:m}){let E=i?.output==="export";if(c==="app"&&i?.pageExtensions)throw new Error("[dndev] pageExtensions is set by the framework (Next files carry the .next. marker so src/pages is never a route). Remove it from next.config.");let k=i?.distDir||".next";return{transpilePackages:[...l,...f||[]],...p?{reactCompiler:p}:{},...se(i)?i:(m.warn("restNextConfig is not a plain object:",i),{}),...c==="app"&&{pageExtensions:Bt},...c==="app"&&{experimental:{...i?.experimental,globalNotFound:!0}},serverExternalPackages:(i?.serverExternalPackages||i?.serverComponentsExternalPackages||[]).filter(T=>!T.startsWith("@donotdev/")&&!f?.includes(T)),turbopack:{...i?.turbopack||{},root:i?.turbopack?.root||y.getRepoRoot(),resolveAlias:{...i?.turbopack?.resolveAlias||{},...Ht,[He.blog]:(()=>{try{let T=y.resolveAppPath(F.next.blogContent);if(Wt.existsSync(T))return"./"+F.next.blogContent}catch{}return"@donotdev/core/empty"})(),...f?.length>0?Object.fromEntries(f.flatMap(T=>[[T,"@donotdev/core/empty"],[`${T}/*`,"@donotdev/core/empty"]])):{}}},distDir:k,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},...se(o)?o:(m.error(`Route handler config invalid (got ${typeof o}):`,o),{}),...se(e)?e:(m.error(`Theme handler config invalid (got ${typeof e}):`,e),{}),...se(t)?t:(m.error(`I18n handler config invalid (got ${typeof t}):`,t),{}),...se(s)?s:(m.error(`Asset handler config invalid (got ${typeof s}):`,s),{}),...se(r)?r:(m.error(`SEO handler config invalid (got ${typeof r}):`,r),{}),...se(n)?n:(m.error(`PWA handler config invalid (got ${typeof n}):`,n),{}),...se(a)?a:(m.warn("serverShimConfig returned non-object:",a),{}),webpack:u,...E?{}:{rewrites:h,...g?{redirects:g}:{},...d?{headers:d}:{}},env:A,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}import{brotliDecompressSync as Qr}from"node:zlib";var Yt="aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ",en={"sans-serif":{locals:["Arial","Liberation Sans"],azAvgWidth:934.5116279069767,unitsPerEm:2048},serif:{locals:["Times New Roman","Liberation Serif"],azAvgWidth:854.3953488372093,unitsPerEm:2048}},tn={0:"cmap",1:"head",2:"hhea",3:"hmtx"},sn=63,Zt=48,rn=2001684018;function Qt(o,e){let t=0;for(let s=0;s<5;s++){let r=o[e+s];if(t=t*128+(r&127),(r&128)===0)return[t,e+s+1]}throw new Error("woff2: invalid UIntBase128")}function nn(o){if(o.length<Zt||o.readUInt32BE(0)!==rn)throw new Error("woff2: bad signature");if(o.readUInt32BE(4)===1953784678)throw new Error("woff2: font collections are not supported");let e=o.readUInt16BE(12),t=o.readUInt32BE(20),s=Zt,r=[];for(let l=0;l<e;l++){let p=o[s++],c=p&63,u=p>>6,h=tn[c]??`#${c}`;c===sn&&(h=o.toString("latin1",s,s+4),s+=4);let g;[g,s]=Qt(o,s);let d=c===10||c===11?u!==3:u!==0,f=g;d&&([f,s]=Qt(o,s)),r.push({tag:h,length:f,transformed:d})}let n=Qr(o.subarray(s,s+t)),a=new Map,i=0;for(let{tag:l,length:p,transformed:c}of r)a.set(l,{data:n.subarray(i,i+p),transformed:c}),i+=p;return a}function on(o){let e=o.readUInt16BE(2),t=[];for(let c=0;c<e;c++){let u=4+c*8,h=o.readUInt16BE(u),g=o.readUInt16BE(u+2),d=o.readUInt32BE(u+4);(h===0||h===3&&(g===1||g===10))&&t.push({offset:d,format:o.readUInt16BE(d)})}let s=t.find(c=>c.format===12)??t.find(c=>c.format===4);if(!s)throw new Error("font: no Unicode cmap (format 4 or 12)");let r=s.offset;if(s.format===12){let c=o.readUInt32BE(r+12);return u=>{for(let h=0;h<c;h++){let g=r+16+h*12,d=o.readUInt32BE(g),f=o.readUInt32BE(g+4);if(u>=d&&u<=f)return o.readUInt32BE(g+8)+(u-d)}return 0}}let n=o.readUInt16BE(r+6)/2,a=r+14,i=a+n*2+2,l=i+n*2,p=l+n*2;return c=>{for(let u=0;u<n;u++){if(c>o.readUInt16BE(a+u*2))continue;let h=o.readUInt16BE(i+u*2);if(c<h)return 0;let g=o.readInt16BE(l+u*2),d=p+u*2,f=o.readUInt16BE(d);if(f===0)return c+g&65535;let w=o.readUInt16BE(d+f+(c-h)*2);return w===0?0:w+g&65535}return 0}}function ts(o){let e=nn(o);for(let p of["head","hhea","hmtx","cmap"])if(!e.has(p))throw new Error(`font: missing ${p} table`);let t=e.get("head").data,s=e.get("hhea").data,r=e.get("hmtx"),n=s.readUInt16BE(34),a=p=>{let c=Math.min(p,n-1);return r.transformed?r.data.readUInt16BE(1+c*2):r.data.readUInt16BE(c*4)},i=on(e.get("cmap").data),l=0;for(let p of Yt){let c=i(p.codePointAt(0));if(c===0)throw new Error(`font: no glyph for '${p}'`);l+=a(c)}return{unitsPerEm:t.readUInt16BE(18),ascent:s.readInt16BE(4),descent:s.readInt16BE(6),lineGap:s.readInt16BE(8),azAvgWidth:l/Yt.length}}var es=o=>`${Math.abs(o*100).toFixed(2)}%`;function an(o){return`${o} Fallback`}function ss({family:o,category:e,metrics:t}){let s=en[e];if(!s)throw new Error(`font fallback: unknown category '${e}'`);let{unitsPerEm:r,ascent:n,descent:a,lineGap:i,azAvgWidth:l}=t,p=l/r/(s.azAvgWidth/s.unitsPerEm),c=h=>es(h/(r*p)),u=an(o);return[`/* ${u}: ${s.locals[0]} size-matched to ${o} */`,"@font-face {",` font-family: '${u}';`,` src: ${s.locals.map(h=>`local('${h}')`).join(", ")};`,` ascent-override: ${c(n)};`,` descent-override: ${c(a)};`,` line-gap-override: ${c(i)};`,` size-adjust: ${es(p)};`,"}"].join(`
|
|
6
|
-
|
|
7
|
-
`)),
|
|
8
|
-
`],u=new Set;for(let h of a.fontStems){for(let g of ue[h]){let d=`@fontsource/${h}/${g}.css`,f=n.resolvePackage(d,l);if(!f)throw new Error(`Font copy: cannot resolve ${d}`);let w=n.readSync(f,{format:"text"}),y=n.resolvePath("files",n.getDirname(f));for(let A of w.match(mn)??[]){let m=is(yn.exec(A)?.[1]??"");if(!m||!a.stems.has(m))continue;let E=ls(A).replace(vn,(O,k)=>{let D=n.resolvePath(k,y);if(!n.pathExists(D))throw new Error(`Font copy: font file missing: ${D}`);return u.has(k)||(n.copySync(D,n.resolvePath(k,p),{overwrite:!0}),u.add(k)),`url(/${Qe}/${k})`});c.push(E)}}c.push(bn(h,l,n))}n.writeSync(i,c.join(`
|
|
9
|
-
|
|
1
|
+
import*as $ from"node:fs";import"node:fs";import{createRequire as Ls}from"node:module";import{resolve as Ue,join as fe,dirname as ye,relative as rn,normalize as Ms,sep as sn,extname as Us}from"node:path";import js from"fast-glob";var Ae={HOMEPAGE_FILE:"HomePage.tsx",HOMEPAGE_PATH:"/",HOMEPAGE_COMPONENT:"HomePage"};var Qt={routes:"virtual:routes",themes:"virtual:themes",i18n:"virtual:i18n-mapping",assets:"virtual:assets",env:"virtual:env",blog:"@donotdev/blog-content"},Y={routes:"routes",themes:"themes",i18n:"i18n",assets:"assets",env:"env"},Z={siteGroup:"(site)",sessionSegment:"dndev-session",languageHeader:"x-dndev-language",revalidateSeconds:3600},L={next:{proxy:"src/proxy.next.ts",revalidateRoute:"src/app/api/dndev/revalidate/route.next.ts",routeManifest:"public/route-manifest.json",assetManifest:"public/asset-manifest.json",utilities:"src/styles/utilities.generated.css",appPages:"src/app",appLayout:"src/app/layout.next.tsx",appDocument:"src/app/AppDocument.tsx",configRoute:"src/config/dndev-config-route.js",configTheme:"src/config/dndev-config-theme.js",configI18n:"src/config/dndev-config-i18n.js",configPwa:"src/config/dndev-config-pwa.js",configAsset:"src/config/dndev-config-asset.js",configSeo:"src/config/dndev-config-seo.js",configEnv:"src/config/dndev-config-env.js",configServer:"src/config/dndev-config-server.js",blogContent:"src/content/blog/blog-content.generated.ts",fonts:"src/app/fonts.generated.ts"},manifests:{route:"route-manifest.json",theme:"theme-manifest.json",i18n:"i18n-manifest.json",asset:"asset-manifest.json",feature:"feature-manifest.json",env:"env-manifest.json"}},Ne="/og-image.png";var lt={package:"@donotdev/ui",assetsPath:"packages/ui/assets",browserTargets:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"]},le={public:"public",fonts:"fonts",nodeModules:"node_modules",packages:"packages",core:"core",ui:"ui"},we={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy",PUBLISHED_FLAGS:"i18n/flags"},X={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json","../../entities/locales/*_*.json"],additional:[],framework:{eager:[`${we.SOURCE_EAGER}/*_*.json`],lazy:[`${we.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","icon-*x*.png",Ne.slice(1)],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},Le={mandatoryIncludes:["react","react-dom","react-router-dom","zustand","zustand/middleware","lucide-react","valibot","i18next","i18next-browser-languagedetector","react-i18next","@tanstack/react-query","react-helmet-async"],optionalFeatures:[],coreBundled:["@donotdev/types","@donotdev/utils","@donotdev/stores","@donotdev/schemas","@donotdev/hooks","@donotdev/i18n","@donotdev/config"],componentsBundled:["class-variance-authority","clsx","lucide-react","react-day-picker"],radixUIPattern:"@radix-ui/",buildTools:["esbuild","@esbuild/win32-x64","@esbuild/darwin-x64","@esbuild/linux-x64","@esbuild/darwin-arm64","@esbuild/linux-arm64","vite","rollup","rollup-plugin-visualizer","@vitejs/plugin-react","vite-tsconfig-paths","vite-plugin-pwa","vite-plugin-compression2","vite-plugin-node-polyfills","fsevents","postcss","postcss-import","postcss-nesting","autoprefixer"],buildTimePackages:[],largeOptional:["@sentry/react","framer-motion","stripe","@tanstack/react-query","shiki","@tiptap/react","@tiptap/starter-kit","@tiptap/extension-placeholder","sharp","semver","file-type"]};var ct={selectors:{class:/\.([a-zA-Z0-9-]+)/g,variable:/--[a-zA-Z0-9-]+/g,keyframe:/@keyframes\s+([a-zA-Z0-9-]+)/g},themes:{themeClass:/(?::root\.|\.)([a-z][a-z0-9-]+)\s*\{([\s\S]*?)\}/gim,themeLabel:/--theme-label\s*:\s*['"]([^'"]+)['"]/,themeIcon:/--theme-icon\s*:\s*['"]([^'"]+)['"]/,themeIsDark:/--theme-is-dark\s*:\s*(0|1)/}},en=["-apple-system","BlinkMacSystemFont","SF Pro","SF Pro Text","SF Pro Display","SF Mono","Helvetica Neue","Helvetica","Menlo","Monaco","Apple SD Gothic Neo","Hiragino Sans","Hiragino Kaku Gothic ProN","PingFang SC","PingFang TC","Apple Color Emoji","Segoe UI","Segoe UI Emoji","Segoe UI Symbol","Cascadia Code","Cascadia Mono","Consolas","Arial","Georgia","Times New Roman","Times","Courier New","Courier","Verdana","Tahoma","Trebuchet MS","Malgun Gothic","Yu Gothic","Meiryo","Microsoft YaHei","Microsoft JhengHei","Liberation Sans","Liberation Serif","Liberation Mono","DejaVu Sans","DejaVu Serif","DejaVu Sans Mono","Ubuntu","Cantarell","Noto Sans","Noto Serif","Noto Color Emoji","Droid Sans","Droid Sans Mono"],tn={en:["latin"],fr:["latin"],es:["latin"],de:["latin"],it:["latin"],pt:["latin"],nl:["latin"],da:["latin"],sv:["latin"],nb:["latin"],fi:["latin"],pl:["latin","latin-ext"],cs:["latin","latin-ext"],sk:["latin","latin-ext"],hr:["latin","latin-ext"],sl:["latin","latin-ext"],hu:["latin","latin-ext"],ro:["latin","latin-ext"],et:["latin","latin-ext"],lv:["latin","latin-ext"],lt:["latin","latin-ext"],mt:["latin","latin-ext"],ga:["latin"],ca:["latin"],eu:["latin"],gl:["latin"],af:["latin"],sw:["latin"],tr:["latin","latin-ext"],id:["latin"],ms:["latin"],tl:["latin"],vi:["latin","vietnamese"],ru:["latin","cyrillic"],bg:["latin","cyrillic"],uk:["latin","cyrillic"],sr:["latin","latin-ext","cyrillic"],mk:["latin","cyrillic"],be:["latin","cyrillic"],el:["latin","greek"],zh:[],ja:[],ko:[],ar:[],he:[],th:[],hi:[],bn:[],ta:[]},ut=[{name:"light",displayName:"Light",icon:"Sun",isDark:!1}],Zt={base:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...X.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...X.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:X.globalIgnore}};function nn(r,e=null){let t=X[r];if(!t)throw new Error(`Unknown pattern type: ${r}`);return e&&t.framework?{...t,framework:t.framework.map(n=>`${e}/${n}`)}:t}function Me(r){return Zt[r]||Zt.base}var Se={getGlobOptionsFor:Me||void 0,SCAN_PATTERNS:X||void 0,getPatternsFor:nn||void 0,I18N_PATHS:we||void 0},z={error:(r,e)=>{},warn:(r,e)=>{},info:r=>{}};function Ee(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="EEXIST"}function on(r,e){return r().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var an={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},D=class r{static _instance=null;options;_repoRoot;_appRoot=null;_writtenPaths=null;static getInstance(e={}){return r._instance||(r._instance=new r(e)),r._instance}static _reset(){r._instance=null}constructor(e={}){if(r._instance)return r._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=process.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${process.cwd()}`)}this._appRoot=null,r._instance=this}normalizePath(e){if(!e)return"";try{return Ms(e).split(sn).join("/")}catch{return String(e).split(sn).join("/")}}getRelativePath(e){let t=this.getAppRoot(),n=rn(t,e);return this.normalizePath(n)}getBasename(e){if(!e)return"";let n=this.normalizePath(e).split("/");return n[n.length-1]||""}getDirname(e){return e?this.normalizePath(ye(e)):""}resolvePackage(e,t=null){try{let n=t||this.getAppRoot(),o=Ls(fe(n,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let n=this.resolvePackage(`${e}/package.json`,t);if(n)return this.getDirname(n);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let a=e.replace("@donotdev/",""),i=this.resolveRepoPath(`packages/${a}`);if(this.pathExists(i))return i;if(["auth","billing","crud","oauth"].includes(a)){let l=this.resolveRepoPath(`packages/features/${a}`);if(this.pathExists(l))return l}if(a==="firebase"){let l=this.resolveRepoPath(`packages/providers/${a}`);if(this.pathExists(l))return l}}let s=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(s))return s;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),n=Ue(t,e);return this.normalizePath(n)}resolveRepoPath(e){let t=this.getRepoRoot(),n=this.normalizePath(e),s=Ue(t,n);return this.normalizePath(s)}resolvePath(e,t){let n=this.normalizePath(t),s=this.normalizePath(e),o=Ue(n,s);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=$.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:Us(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:n="auto",encoding:s="utf8"}=t,o=this._detectFormat(e,n);try{if(o==="buffer")return await $.promises.readFile(e);let a=await $.promises.readFile(e,s),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&z.warn(`Failed to read file: ${e}`,a),null}}readSync(e,t={}){let{format:n="auto",encoding:s="utf8"}=t,o=this._detectFormat(e,n);try{if(o==="buffer")return $.readFileSync(e);let a=$.readFileSync(e,s),i=this.stripBom(a);return o==="json"?JSON.parse(i):i}catch(a){return this.options.debug&&z.warn(`Failed to read file: ${e}`,a),null}}async write(e,t,n={}){let{format:s="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),u=this.normalizePath(ye(l)),c=this.pathExists(l);if(c&&!o)return i&&z.info(`Skipping existing file: ${l}`),!1;if(a)return z.info(`[DRY RUN] Would write file: ${l}`),!0;try{await $.promises.mkdir(u,{recursive:!0})}catch(f){if(!Ee(f))throw f}let p=this._detectFormat(e,s),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`:d=String(t);try{return await on(async()=>(Buffer.isBuffer(d)?await $.promises.writeFile(l,d):await $.promises.writeFile(l,d,"utf8"),i&&z.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,n={}){let{format:s="auto",overwrite:o=!1,dryRun:a=!1,verbose:i=!1}=n,l=this.normalizePath(e),u=this.normalizePath(ye(l)),c=this.pathExists(l);if(c&&!o)return i&&z.info(`Skipping existing file: ${l}`),!1;if(a)return z.info(`[DRY RUN] Would write file: ${l}`),!0;try{$.mkdirSync(u,{recursive:!0})}catch(f){if(!Ee(f))throw f}let p=this._detectFormat(e,s),d;Buffer.isBuffer(t)?d=t:p==="json"&&typeof t=="object"?d=`${JSON.stringify(t,null,2)}
|
|
3
|
+
`:d=String(t);try{return Buffer.isBuffer(d)?$.writeFileSync(l,d):$.writeFileSync(l,d,"utf8"),this._writtenPaths?.add(l),i&&z.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(f){throw new Error(`Failed to write file: ${l}: ${f instanceof Error?f.message:String(f)}`)}}async copy(e,t,n={}){let{overwrite:s=!1,dryRun:o=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!s)return a&&z.info(`Skipping existing file: ${i}`),!1;if(o)return z.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(ye(i));try{await $.promises.mkdir(u,{recursive:!0})}catch(c){if(!Ee(c))throw c}try{return await on(async()=>(await $.promises.copyFile(e,i),a&&z.info(`${l?"Updated":"Created"} file: ${i}`),!0),`Failed to copy file from ${e} to ${i}`)}catch{return!1}}copySync(e,t,n={}){let{overwrite:s=!1,dryRun:o=!1,verbose:a=!1}=n,i=this.normalizePath(t),l=this.pathExists(i);if(l&&!s)return a&&z.info(`Skipping existing file: ${i}`),!1;if(o)return z.info(`[DRY RUN] Would copy file: ${i}`),!0;let u=this.normalizePath(ye(i));try{$.mkdirSync(u,{recursive:!0})}catch(c){if(!Ee(c))throw c}try{return $.copyFileSync(e,i),this._writtenPaths?.add(i),a&&z.info(`${l?"Updated":"Created"} file: ${i}`),!0}catch{return!1}}pathExists(e,t=!1){try{return $.existsSync(e)}catch(n){return t||z.error(`Error checking path existence: ${e}`,n),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return $.existsSync(t)||$.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return $.readdirSync(e,t)}catch(n){return this.options.debug&&z.warn(`Failed to read directory: ${e}`,n),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return $.statSync(e)}catch(t){return this.options.debug&&z.warn(`Failed to stat file: ${e}`,t),null}}realpathSync(e){return $.realpathSync(e)}watch(e,t,n){return $.watch(e,t,n)}lstatSync(e){try{return $.lstatSync(e)}catch(t){return this.options.debug&&z.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await $.promises.mkdir(e,{recursive:!0})}catch(t){if(!Ee(t))throw t}}ensureDirSync(e){try{$.mkdirSync(e,{recursive:!0})}catch(t){if(!Ee(t))throw t}}async remove(e){await $.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){$.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return $.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||process.cwd()}startWriteRecording(){this._writtenPaths=new Set}stopWriteRecording(){if(!this._writtenPaths)throw new Error("stopWriteRecording() called without startWriteRecording()");let e=this._writtenPaths;return this._writtenPaths=null,e}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=fe(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(Ue(e)),n=this.getAppRoot(),s=rn(n,t),o=this.normalizePath(s);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,n={}){let s=this.normalizePath(fe(e,t)),o=this.getAppRoot(),a=this.normalizePath(o),i=s.startsWith(a)?s.slice(a.length+1):s,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:Se.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([i],{...l,...n})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=Se.I18N_PATHS;if(!t)return null;let n=e.replace(t.SOURCE_ROOT+"/",""),s=this.resolveFrameworkPackage("@donotdev/core");if(!s)return null;let o=this.normalizePath(fe(s,t.PUBLISHED_ROOT,n)),a=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(a),o}async _globWithNormalization(e,t){return(await js(e,t)).map(s=>{let o=typeof s=="string"?s:s.path;return this.normalizePath(o)}).sort()}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let n=[...e.framework,...e.consumer];for(let c of n)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let s=this.getAppRoot(),o=Se.getGlobOptionsFor?Se.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},a=this.normalizePath(s),i=e.framework.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),l=e.consumer.map(c=>{let p=this.normalizePath(c);return p.startsWith(a)?p.slice(a.length+1):p}),u={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s};try{let c=i.length>0?await this._globWithNormalization(i,u):[],p=await this._globWithNormalization(l,u);return{frameworkFiles:c,consumerFiles:p}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!Se.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),n=this.getRepoRoot();if(e==="i18n"&&(!t||t===n))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${n}). Ensure configResolved hook has run before discovery.`);let s=Se.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=s,u={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return u.all=[...u.eager,...u.lazy,...u.framework.eager,...u.framework.lazy],u}let a=s,i={framework:o?(a.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(a.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return i.all=[...i.consumer,...i.framework],i}getEmptyModulePath(){return this.getEmptyCjsModulePath().replace(/\.cjs$/,".js")}getEmptyCjsModulePath(){let e=this.resolvePackage("@donotdev/core/empty");if(!e)throw new Error("Cannot resolve @donotdev/core/empty \u2014 package setup is broken");return e}_findRepoRoot(e){let t=this.normalizePath(e),n=0,s=this.options.maxLevels;for(;n<s;){let o=this.normalizePath(fe(t,an.TOOLING)),a=this.normalizePath(fe(t,an.CORE));if(this.pathExists(o)&&this.pathExists(a))return t;let i=fe(t,"apps");if(this.pathExists(i)&&this.statSync(i)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(fe(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(ye(t))===t)return t;let u=this.normalizePath(ye(t));if(u===t)break;t=u,n++}return this.normalizePath(e)}};function ln({logger:r,debug:e=!1}={}){let t=D.getInstance(),n=!1,s=null;if(process.env.DNDEV_APP_ROOT?(s=t.normalizePath(process.env.DNDEV_APP_ROOT),t.pathExists(s)?(t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root set from DNDEV_APP_ROOT: ${s}`)):r&&r.warn(`DNDEV_APP_ROOT path does not exist: ${s}`)):e&&r&&r.debug("DNDEV_APP_ROOT env var not set"),!n){if(t.getRepoRoot()){let a=t.resolveRepoPath("apps");if(t.pathExists(a))try{let i=process.cwd(),l=t.normalizePath(i);if(l.includes("/apps/")){let u=l.indexOf("/apps/"),p=l.substring(u+6).split("/")[0];if(p){let d=t.resolveRepoPath(`apps/${p}`),f=t.resolveRepoPath(`apps/${p}/next.config.js`);t.pathExists(f)&&(s=d,t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root detected from process.cwd(): ${s}`))}}}catch{}}!n&&!s&&(s=process.cwd(),t.setAppRoot(s),n=!0,e&&r&&r.debug(`App root fallback to process.cwd(): ${s}`))}return{appRoot:s,appRootSet:n}}import oo from"node:fs";import{readdirSync as Bs,readFileSync as Gs,writeFileSync as zs}from"node:fs";import{createRequire as Hs}from"node:module";import{join as dt,resolve as Ws}from"node:path";var je=Hs(import.meta.url),pt=[14,1];function cn(r){if(!r)return!1;let[e,t=0]=String(r).split(".").map(Number);return e<pt[0]||e===pt[0]&&t<pt[1]}function qs(r){let e=je("@babel/core"),{targets:t}=e.loadPartialConfig({cwd:r,root:r,babelrc:!1,configFile:!1,filename:dt(r,"index.js")}).options;return cn(t?.safari)||cn(t?.ios)}function*un(r){for(let e of Bs(r,{withFileTypes:!0})){let t=dt(r,e.name);e.isDirectory()?yield*un(t):e.name.endsWith(".js")&&(yield t)}}function Js(){return{pre(r){r.metadata.script=r.path.node.sourceType==="script";let e=Object.keys(r.scope.bindings);if(r.metadata.script&&e.length>0)throw new Error(`declares top-level ${e.join(", ")}, which its own function scope would hide from the other chunks`)}}}async function pn({distDir:r,projectDir:e}){if(!qs(e))return 0;let t=je("@babel/core"),n=[Js,[je.resolve("@babel/plugin-transform-destructuring"),{loose:!0}],je.resolve("@babel/plugin-transform-parameters")],s=0;for(let o of un(dt(Ws(e,r),"static"))){let a=Gs(o,"utf8"),i;try{i=t.transformSync(a,{babelrc:!1,configFile:!1,compact:!0,comments:!1,sourceMaps:!1,parserOpts:{sourceType:"unambiguous",allowReturnOutsideFunction:!0},plugins:n})}catch(l){throw new Error(`[dndev] Safari destructuring fix: cannot transform ${o}: ${l.message}`)}i?.code&&i.code!==a&&(zs(o,i.metadata.script?`(function(){${i.code}
|
|
4
|
+
}).call(this);`:i.code),s++)}return s}function dn({postcssImport:r,postcssNesting:e,autoprefixer:t,resolve:n}){return{plugins:[n?r({resolve:n}):r,e,t({overrideBrowserslist:["> 1%","last 2 versions","Firefox ESR","not dead","not op_mini all"],grid:"autoplace"})]}}function Vs(r){return(e,t)=>{let n=r.resolvePackage(e,t);if(n)return n;if(e.startsWith("@donotdev/")){let s=e.split("/")[0]+"/"+e.split("/")[1],o=e.split("/").slice(2).join("/"),a=r.resolveFrameworkPackage(s,t);if(a){if(o){let l=r.resolvePath(o,a);if(r.pathExists(l))return l;let u=l+".css";if(r.pathExists(u))return u}let i=r.resolvePath("index.css",a);if(r.pathExists(i))return i}}return r.resolvePath(e,t)}}async function Ks(){let[r,e,t]=await Promise.all([import("postcss-import").then(s=>s.default),import("postcss-nesting").then(s=>s.default),import("autoprefixer").then(s=>s.default)]),n=D.getInstance();return dn({postcssImport:r,postcssNesting:e,autoprefixer:t,resolve:Vs(n)})}import{renameSync as Xs}from"node:fs";import{basename as fn,dirname as Ys,join as ht,relative as Zs}from"node:path";var he="next",Qs=["tsx","ts","jsx","js"],hn=Qs.map(r=>`${he}.${r}`);function U(r,e){return`${r}.${he}.${e}`}var eo=["page","route","layout","template","default","loading","error","global-error","not-found","global-not-found","forbidden","unauthorized"],to=["sitemap","robots","manifest","icon","apple-icon","opengraph-image","twitter-image"],no=["proxy","middleware","instrumentation"],ro="// Generated by @donotdev/config";function ft(r,e){let t=r.match(new RegExp(`^(.+?)(\\.${he})?\\.(tsx|ts|jsx|js)$`));if(!t)return null;let[,n,s,o]=t;return e.includes(n)?{name:n,extension:o,marked:!!s}:null}function so(r){let e=[],t=r.resolveAppPath("src/app"),n=s=>{for(let o of r.readdirSync(s,{withFileTypes:!0})){let a=ht(s,o.name);if(o.isDirectory()){n(a);continue}if(!o.isFile())continue;let i=ft(o.name,eo);i&&e.push({file:a,...i,metadata:!1});let l=ft(o.name,to);l&&e.push({file:a,...l,metadata:!0})}};r.pathExists(t)&&n(t);for(let s of[r.resolveAppPath("src"),r.getAppRoot()])if(r.pathExists(s))for(let o of r.readdirSync(s,{withFileTypes:!0})){let a=o.isFile()&&ft(o.name,no);a&&e.push({file:ht(s,o.name),...a,metadata:!1})}return e}function gn({pathResolver:r,logger:e,isCI:t}){let n=r.getAppRoot(),s=u=>Zs(n,u),o=[],a=[],i=[],l=[];for(let u of so(r)){let c=r.readSync(u.file,{format:"text"})||"";if(!u.marked&&c.startsWith(ro)){r.removeSync(u.file),a.push(s(u.file));continue}u.metadata?l.push(s(u.file)):u.marked||i.push(u)}if(l.length>0)throw new Error(`[dndev] Next ignores code metadata files with the framework's file marker: ${l.join(", ")}. Serve each as a route handler (e.g. src/app/robots.txt/${U("route","ts")}) or a static file (icon.png, opengraph-image.png). The sitemap and llms.txt are generated by the framework.`);if(t&&i.length>0)throw new Error(`[dndev] Next files must carry the .${he}. marker (src/pages is never a Next route). Rename: `+i.map(({file:u,name:c,extension:p})=>`${s(u)} \u2192 ${U(c,p)}`).join(", ")+". Running the app once in development renames them.");for(let{file:u,name:c,extension:p}of i){let d=ht(Ys(u),U(c,p));if(r.pathExists(d))throw new Error(`[dndev] Both ${s(u)} and ${s(d)} exist. Next only reads *.${he}.* files: merge ${fn(u)} into ${fn(d)} and delete it.`);Xs(u,d),o.push(s(u))}return o.length>0&&e.warn(`Next files renamed to *.${he}.* (src/pages is never a Next route): ${o.join(", ")}. Commit the renames.`),a.length>0&&e.debug(`Removed generated Next files without marker: ${a.join(", ")}`),{renamed:o,removed:a}}function mn(r){return r&&typeof r=="object"&&!Array.isArray(r)}function yn({originalRewrites:r,handlers:e,logger:t}){return async function(){try{let n=r?await r():[],o=e.filter(i=>i?.getAPIRewrites).map(i=>i.getAPIRewrites()).reduce((i,l)=>(l?.beforeFiles&&i.beforeFiles.push(...l.beforeFiles),l?.afterFiles&&i.afterFiles.push(...l.afterFiles),l?.fallback&&i.fallback.push(...l.fallback),i),{beforeFiles:[],afterFiles:[],fallback:[]});return{beforeFiles:[...Array.isArray(n)?[]:n?.beforeFiles||[],...o.beforeFiles],afterFiles:[...Array.isArray(n)?n:n?.afterFiles||[],...o.afterFiles],fallback:[...Array.isArray(n)?[]:n?.fallback||[],...o.fallback]}}catch(n){return t.error(`Next.js config failed to merge rewrites: ${n.message}`),t.error(`Stack: ${n.stack||"No stack trace available"}`),{beforeFiles:[],afterFiles:[],fallback:[]}}}}function vn({originalRedirects:r,seoRedirects:e,logger:t}){return async function(){try{let n=r?await r():[],s=(e||[]).map(({from:l,to:u,permanent:c})=>({source:l,destination:u,permanent:c!==!1})),o=[],a=new Set;for(let l of s){let u=l.source.replace(/\/+$/,"")||"/",c=l.destination.replace(/\/+$/,"")||"/";if(u===c){t.warn(`Redirect loop detected: ${l.source} \u2192 ${l.destination} (skipped)`);continue}if(!l.source.startsWith("/")){t.warn(`Redirect source must start with /: "${l.source}" (skipped)`);continue}if(a.has(u)){t.warn(`Duplicate redirect source: "${l.source}" (skipped)`);continue}a.add(u),o.push(l)}let i=[...Array.isArray(n)?n:[],...o];return i.length===0?[]:(t.info(` \u{1F4CE} ${i.length} redirect${i.length>1?"s":""} configured`),i)}catch(n){return t.error(`Failed to merge redirects: ${n.message}`),[]}}}function bn({policyRules:r,originalHeaders:e}){if(e!==void 0&&typeof e!="function")throw new Error("[dndev] next.config headers must be a function returning an array (Next headers() contract).");return async function(){let n=e?await e():[];if(!Array.isArray(n))throw new Error(`[dndev] next.config headers() must return an array (got ${typeof n}).`);return[...r,...n]}}function wn({restNextConfig:r,discoveredPackages:e,reactCompiler:t=!1,routingMode:n,rewritesConfig:s,redirectsConfig:o,headersConfig:a,missingOptionalDeps:i,pathResolver:l,env:u,logger:c}){let p=r?.output==="export";if(n==="app"&&r?.pageExtensions)throw new Error("[dndev] pageExtensions is set by the framework (Next files carry the .next. marker so src/pages is never a route). Remove it from next.config.");let f=r?.distDir||".next";return{transpilePackages:[...e,...i||[]],...t?{reactCompiler:t}:{},...mn(r)?r:(c.warn("restNextConfig is not a plain object:",r),{}),...n==="app"&&{pageExtensions:hn},...n==="app"&&{experimental:{...r?.experimental,globalNotFound:!0}},serverExternalPackages:(r?.serverExternalPackages||r?.serverComponentsExternalPackages||[]).filter(m=>!m.startsWith("@donotdev/")&&!i?.includes(m)),turbopack:{...r?.turbopack||{},root:r?.turbopack?.root||l.getRepoRoot(),resolveAlias:{...r?.turbopack?.resolveAlias||{},[Qt.blog]:(()=>{try{let m=l.resolveAppPath(L.next.blogContent);if(oo.existsSync(m))return"./"+L.next.blogContent}catch{}return"@donotdev/core/empty"})(),...i?.length>0?Object.fromEntries(i.flatMap(m=>[[m,"@donotdev/core/empty"],[`${m}/*`,"@donotdev/core/empty"]])):{}}},distDir:f,...process.env.NODE_ENV==="development"&&{devIndicators:{position:"bottom-right"},onDemandEntries:{maxInactiveAge:60*1e3,pagesBufferLength:5}},compiler:{...r?.compiler,runAfterProductionCompile:async m=>{let y=await pn(m);y>0&&c.info(`Safari < 14.1 destructuring fix: ${y} client chunks lowered`),await r?.compiler?.runAfterProductionCompile?.(m)}},...p?{}:{rewrites:s,...o?{redirects:o}:{},...a?{headers:a}:{}},env:u,...process.env.NODE_ENV==="production"&&{logging:{fetches:{fullUrl:!1}}}}}import{createHash as jo}from"node:crypto";function C(r,e,t="configuration-error",n={}){let s=`[${r}] ${e}`,o=new Error(s);return o.code=t,o.pluginName=r,o.context=n,o}function ce(r){return r instanceof Error&&typeof r.pluginName=="string"}function Sn(r,e,t,n={}){return C(r,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},n))}var $n="src/**/*.{ts,tsx,js,jsx,mjs,cjs}",gt=/\/\*[\s\S]*?\*\//g,ao=/(^|\s)\/\/.*$/gm,io=/<!--[\s\S]*?-->/g,lo=/(?:from\s*|import\s*\(\s*|require\s*\(\s*)['"]next\/font(?:\/[^'"]*)?['"]/g,co=/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)['"]@fontsource(?:-variable)?\/[^'"]*['"]/g,uo=/@import\s+(?:url\(\s*)?['"]?@fontsource(?:-variable)?\/[^'";)]*/g,En=/@font-face\b/g,Rn="Name the family in src/themes.css (e.g. --font-sans: Manrope, 'Manrope Fallback', sans-serif;) and keep @fontsource-variable/<slug> or @fontsource/<slug> in package.json, or declare its woff2 files in appConfig.fonts.",po={"next-font":{message:`imports next/font: its preload cannot work in a framework app (page files carry the \`.next.\` marker, Next's font manifest is keyed without it) and it is a second font pipeline. The framework ships the theme's fonts (preloaded, inline @font-face, size-matched fallback). ${Rn}`},fontsource:{message:`imports an @fontsource package: the framework ships the fonts the theme names (preloaded, inline @font-face, hashed /fonts/ files). Remove the import. ${Rn}`},"font-face":{message:"declares @font-face: the framework writes every @font-face of the app (one place, preloaded, hashed files). Declare the woff2 files in appConfig.fonts (src/config/app.ts: { category, faces: [{ file, weight, unicodeRange? }] }) and name the family in src/themes.css."}};function fo(r,e){let t=r;for(let n of e)t=t.replace(n,(s,o)=>{let a=typeof o=="string"?o:"";return a+s.slice(a.length).replace(/[^\n]/g," ")});return t}var ho=(r,e)=>r.slice(0,e).split(`
|
|
5
|
+
`).length;function go(r){let e=[];for(let{file:t,content:n}of r){if(/\.generated\.[a-z]+$/.test(t))continue;let s=t.endsWith(".css"),o=t.endsWith(".html"),a=fo(n,o?[io,gt]:s?[gt]:[gt,ao]),i=s?[["fontsource",uo],["font-face",En]]:o?[["font-face",En]]:[["next-font",lo],["fontsource",co]];for(let[l,u]of i)for(let c of a.matchAll(u))e.push({file:t,line:ho(a,c.index),rule:l})}return e}function xn(r){let e=go(r);if(e.length===0)return;let t=e.map(({file:n,line:s,rule:o})=>` ${n}:${s} ${po[o].message}`);throw C("dndev-fonts",`the app loads fonts itself; the framework font plan is the one way:
|
|
6
|
+
${t.join(`
|
|
7
|
+
`)}`,"configuration-error")}import{brotliDecompressSync as mo}from"node:zlib";var Pn="aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ",yo={"sans-serif":{locals:["Arial","Liberation Sans"],azAvgWidth:934.5116279069767,unitsPerEm:2048},serif:{locals:["Times New Roman","Liberation Serif"],azAvgWidth:854.3953488372093,unitsPerEm:2048}},vo={0:"cmap",1:"head",2:"hhea",3:"hmtx"},bo=63,Cn=48,wo=2001684018;function An(r,e){let t=0;for(let n=0;n<5;n++){let s=r[e+n];if(t=t*128+(s&127),(s&128)===0)return[t,e+n+1]}throw new Error("woff2: invalid UIntBase128")}function So(r){if(r.length<Cn||r.readUInt32BE(0)!==wo)throw new Error("woff2: bad signature");if(r.readUInt32BE(4)===1953784678)throw new Error("woff2: font collections are not supported");let e=r.readUInt16BE(12),t=r.readUInt32BE(20),n=Cn,s=[];for(let l=0;l<e;l++){let u=r[n++],c=u&63,p=u>>6,d=vo[c]??`#${c}`;c===bo&&(d=r.toString("latin1",n,n+4),n+=4);let f;[f,n]=An(r,n);let h=c===10||c===11?p!==3:p!==0,m=f;h&&([m,n]=An(r,n)),s.push({tag:d,length:m,transformed:h})}let o=mo(r.subarray(n,n+t)),a=new Map,i=0;for(let{tag:l,length:u,transformed:c}of s)a.set(l,{data:o.subarray(i,i+u),transformed:c}),i+=u;return a}function Eo(r){let e=r.readUInt16BE(2),t=[];for(let c=0;c<e;c++){let p=4+c*8,d=r.readUInt16BE(p),f=r.readUInt16BE(p+2),h=r.readUInt32BE(p+4);(d===0||d===3&&(f===1||f===10))&&t.push({offset:h,format:r.readUInt16BE(h)})}let n=t.find(c=>c.format===12)??t.find(c=>c.format===4);if(!n)throw new Error("font: no Unicode cmap (format 4 or 12)");let s=n.offset;if(n.format===12){let c=r.readUInt32BE(s+12);return p=>{for(let d=0;d<c;d++){let f=s+16+d*12,h=r.readUInt32BE(f),m=r.readUInt32BE(f+4);if(p>=h&&p<=m)return r.readUInt32BE(f+8)+(p-h)}return 0}}let o=r.readUInt16BE(s+6)/2,a=s+14,i=a+o*2+2,l=i+o*2,u=l+o*2;return c=>{for(let p=0;p<o;p++){if(c>r.readUInt16BE(a+p*2))continue;let d=r.readUInt16BE(i+p*2);if(c<d)return 0;let f=r.readInt16BE(l+p*2),h=u+p*2,m=r.readUInt16BE(h);if(m===0)return c+f&65535;let y=r.readUInt16BE(h+m+(c-d)*2);return y===0?0:y+f&65535}return 0}}function _n(r){let e=So(r);for(let u of["head","hhea","hmtx","cmap"])if(!e.has(u))throw new Error(`font: missing ${u} table`);let t=e.get("head").data,n=e.get("hhea").data,s=e.get("hmtx"),o=n.readUInt16BE(34),a=u=>{let c=Math.min(u,o-1);return s.transformed?s.data.readUInt16BE(1+c*2):s.data.readUInt16BE(c*4)},i=Eo(e.get("cmap").data),l=0;for(let u of Pn){let c=i(u.codePointAt(0));if(c===0)throw new Error(`font: no glyph for '${u}'`);l+=a(c)}return{unitsPerEm:t.readUInt16BE(18),ascent:n.readInt16BE(4),descent:n.readInt16BE(6),lineGap:n.readInt16BE(8),azAvgWidth:l/Pn.length}}var Nn=r=>`${Math.abs(r*100).toFixed(2)}%`;function Be(r){return`${r} Fallback`}function kn({family:r,category:e,metrics:t}){let n=yo[e];if(!n)throw new Error(`font fallback: unknown category '${e}'`);let{unitsPerEm:s,ascent:o,descent:a,lineGap:i,azAvgWidth:l}=t,u=l/s/(n.azAvgWidth/n.unitsPerEm),c=d=>Nn(d/(s*u)),p=Be(r);return[`/* ${p}: ${n.locals[0]} size-matched to ${r} */`,"@font-face {",` font-family: '${p}';`,` src: ${n.locals.map(d=>`local('${d}')`).join(", ")};`,` ascent-override: ${c(o)};`,` descent-override: ${c(a)};`,` line-gap-override: ${c(i)};`,` size-adjust: ${Nn(u)};`,"}"].join(`
|
|
8
|
+
`)}var Ro=2001684018,Ge=400;function He(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function $o(r){let[e,t=e]=String(r).trim().split(/\s+/).map(Number);return[e,t]}var ze=([r,e],t)=>t>=r&&t<=e;function Dn(r,e){if(e.some(o=>ze(o,r)))return r;let t=[...new Set(e.flat())],n=(o=1/0)=>t.filter(a=>a>r&&a<=o).sort((a,i)=>a-i)[0],s=()=>t.filter(o=>o<r).sort((o,a)=>a-o)[0];return r>=400&&r<=500?n(500)??s()??n():r<400?s()??n():n()??s()}function Q(r){return C("dndev-fonts",r,"configuration-error")}function xo(r){return!!(r&&r.length>=4&&r.readUInt32BE(0)===Ro)}var Po=r=>r==="serif"?"serif":"sans-serif";function Co({family:r,packageName:e,dir:t,pathResolver:n}){let s=n.readSync(n.resolvePath("metadata.json",t),{format:"json"}),o=n.readSync(n.resolvePath("unicode.json",t),{format:"json"});if(!s||!o)throw Q(`${e}: metadata.json or unicode.json missing in ${t} (not a fontsource package?).`);if(String(s.family).toLowerCase()!==r.toLowerCase())throw Q(`${e} is the family '${s.family}', the font stack names '${r}'. Write the family as the package names it.`);let a=e.startsWith("@fontsource-variable/"),i=s.variable?.wght;if(a&&!i)throw Q(`${e} has no wght axis: use @fontsource/${s.id} (static weights).`);let l=a?[Number(i.min),Number(i.max)]:null,u=["normal","italic"].filter(h=>s.styles.includes(h)),c=(h,m,y)=>n.resolvePath(`files/${s.id}-${h}-${a?"wght":m}-${y}.woff2`,t),p=h=>{if(!n.pathExists(h))throw Q(`${e}: font file missing: ${h}`);return h},d=s.subsets.includes("latin")?"latin":s.defSubset,f=s.weights.reduce((h,m)=>Math.abs(m-Ge)<Math.abs(h-Ge)?m:h);return{family:r,kind:a?"variable":"static",category:Po(s.category),label:e,provides:h=>a?ze(l,h):s.weights.includes(h),matchWeight:h=>Dn(h,a?[l]:s.weights.map(m=>[m,m])),faces({weights:h,subsets:m}){let y=m.filter(R=>s.subsets.includes(R)),S=a?[`${l[0]} ${l[1]}`]:h.map(String),T=[];for(let R of y)for(let v of S)for(let x of u)T.push({file:p(c(R,v,x)),weight:v,style:x,subset:R,unicodeRange:o[R]??null});return T},metricsFile:p(c(d,f,"normal"))}}function Ao({family:r,config:e,pathResolver:t}){let n=`appConfig.fonts['${r}']`;if(e?.category!=="sans-serif"&&e?.category!=="serif")throw Q(`${n}.category must be 'sans-serif' or 'serif' (picks the size-matched fallback face's system font).`);if(!Array.isArray(e.faces)||e.faces.length===0)throw Q(`${n}.faces must list the family's woff2 files ({ file, weight, style?, unicodeRange?, subset? }).`);let s=e.faces.map((u,c)=>{let p=`${n}.faces[${c}]`;if(typeof u?.file!="string"||!u.file.endsWith(".woff2"))throw Q(`${p}.file must be a .woff2 path relative to the app root (e.g. 'src/assets/fonts/brand.woff2').`);let[d,f]=$o(u.weight);if(!Number.isFinite(d)||!Number.isFinite(f)||d>f)throw Q(`${p}.weight must be a weight (400) or a variable range ('300 600'). Got ${JSON.stringify(u.weight)}.`);let h=u.style??"normal";if(h!=="normal"&&h!=="italic")throw Q(`${p}.style must be 'normal' or 'italic'.`);let m=t.resolveAppPath(u.file),y=t.pathExists(m)?t.readSync(m,{format:"buffer"}):null;if(!y)throw Q(`${p}.file: ${u.file} does not exist.`);if(!xo(y))throw Q(`${p}.file: ${u.file} is not a woff2 font.`);return{file:m,weight:d===f?String(d):`${d} ${f}`,range:[d,f],style:h,subset:u.subset??null,unicodeRange:u.unicodeRange??null}}),o=s.filter(u=>u.style==="normal"),a=o.filter(u=>u.unicodeRange===null),i=({range:u})=>ze(u,Ge)?0:Math.min(...u.map(c=>Math.abs(c-Ge))),l=[...a.length>0?a:o].sort((u,c)=>i(u)-i(c))[0];if(!l)throw Q(`${n}.faces has no normal-style face: the size-matched fallback face is measured on one.`);return{family:r,kind:"local",category:e.category,label:n,provides:u=>o.some(c=>ze(c.range,u)),matchWeight:u=>Dn(u,o.map(c=>c.range)),faces:()=>s.map(({range:u,...c})=>c),metricsFile:l.file}}function No(r,e,t){if(!e)return null;let n=t.resolvePackage(`${r}/package.json`,e);return n?t.getDirname(n):null}function Tn(r,{appFonts:e={},appRoot:t,uiRoot:n,pathResolver:s}){let o=Object.keys(e).find(i=>i.toLowerCase()===r.toLowerCase());if(o)return Ao({family:r,config:e[o],pathResolver:s});let a=He(r);for(let i of[t,n])for(let l of[`@fontsource-variable/${a}`,`@fontsource/${a}`]){let u=No(l,i,s);if(u)return Co({family:r,packageName:l,dir:u,pathResolver:s})}return null}var vt=Object.freeze({body:"--font-family",headline:"--font-headline",mono:"--font-mono"}),_o="--font-weight-",se=":root",ko="@donotdev/components/styles",Do=/\/\*[\s\S]*?\*\//g,To=/([^{}]+)\{([^{}]*)\}/g,Oo=/^(?::root|html|:where\(:root\))$/,Fo=/^(?::root|html)?\.([a-z][\w-]*)$/i,bt=/^var\(\s*(--[\w-]+)\s*(?:,([\s\S]*))?\)$/,On={normal:400,bold:700};function wt(r){let e=[],t=0,n="",s=0;for(let o=0;o<r.length;o++){let a=r[o];n?a===n&&(n=""):a==='"'||a==="'"?n=a:a==="("?t++:a===")"?t--:a===","&&t===0&&(e.push(r.slice(s,o)),s=o+1)}return e.push(r.slice(s)),e.map(o=>o.trim()).filter(Boolean)}function Io(r){return r.replace(/^['"]|['"]$/g,"").trim()}function Lo(r){if(Oo.test(r))return se;let e=Fo.exec(r);return e?e[1]:null}function Fn(r,e=""){let t=new Map,n=r.replace(Do,"");for(let[,s,o]of n.matchAll(To)){let a=s.split(";").pop(),i=wt(a).map(Lo).filter(l=>l!==null);if(i.length!==0)for(let l of o.split(";")){let u=l.indexOf(":");if(u===-1)continue;let c=l.slice(0,u).trim();if(!c.startsWith("--"))continue;let p=l.slice(u+1).replace(/!important\s*$/,"").replace(/\s+/g," ").trim();for(let d of i)t.has(d)||t.set(d,new Map),t.get(d).set(c,{value:p,source:e,scope:d})}}return t}function Mo(r){let e=new Map;for(let t of r)for(let[n,s]of t){e.has(n)||e.set(n,new Map);for(let[o,a]of s)e.get(n).set(o,a)}return e}function In({source:r,scope:e}){return`${r||"CSS"} (${e===se?":root":`.${e}`})`}function mt(r,e,t,n){let s=[];for(let o of wt(e)){let a=bt.exec(o);if(!a){s.push(Io(o));continue}let[,i,l]=a;if(t.has(i)&&!n.has(i))s.push(...mt(i,t.get(i).value,t,new Set([...n,i])));else if(l!==void 0)s.push(...mt(r,l,t,n));else throw C("dndev-fonts",`${r}: ${e} uses var(${i}), which no theme CSS defines (src/**/*.css and the framework tokens). Name the font family in the stack itself, e.g. ${r}: Manrope, 'Manrope Fallback', sans-serif; (a next/font or other runtime class variable is not a framework font).`,"configuration-error")}return s}function Uo(r,e){let t=new Set,n=r;for(;e.has(n)&&!t.has(n);){t.add(n);let s=e.get(n),o=wt(s.value),a=o[0]&&bt.exec(o[0]);if(!a)return{token:n,declaration:s,entries:o};n=a[1]}return null}function yt(r,e,t=new Set){let{value:n}=e.get(r),s=bt.exec(n);if(s){let[,a,i]=s;if(e.has(a)&&!t.has(a))return yt(a,e,new Set([...t,r]));if(i!==void 0)return yt(r,new Map([[r,{value:i.trim()}]]),t)}if(n in On)return On[n];let o=Number(n);if(Number.isFinite(o)&&o>=1&&o<=1e3)return o;throw C("dndev-fonts",`${r}: ${n} is not a font weight (a number from 1 to 1000, normal or bold): the font plan ships the weights the --font-weight-* tokens name.`,"configuration-error")}function Ln({frameworkCss:r,appCss:e}){if(typeof r!="string"||!Array.isArray(e))throw new Error("resolveThemeFonts: frameworkCss (string) and appCss ({ file, css }[]) are required (ThemeDiscovery fontCss)");let t=Fn(r,ko),n=Mo(e.map(({file:o,css:a})=>Fn(a,o)));return[se,...new Set([...t.keys(),...n.keys()])].filter((o,a,i)=>i.indexOf(o)===a).map(o=>{let a=new Map([...t.get(se)??[],...n.get(se)??[],...o===se?[]:t.get(o)??[],...o===se?[]:n.get(o)??[]]),i={};for(let[u,c]of Object.entries(vt))a.has(c)&&(i[u]={stack:mt(c,a.get(c).value,a,new Set([c])),origin:Uo(c,a)});let l=new Map;for(let u of a.keys())u.startsWith(_o)&&l.set(u,{weight:yt(u,a),declaration:a.get(u)});return{scope:o,roles:i,weights:l}})}var Un="optional",Et=le.fonts,Rt=`/${Et}`,Bo=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),Go=new Set(en.map(r=>r.toLowerCase())),zo="--font-weight-normal",Ho="--font-weight-bold",St=r=>C("dndev-fonts",r,"configuration-error");function Mn(r){let e=tn[r];return e&&e.length>0?[...e]:["latin"]}var jn=r=>`'${r.replace(/'/g,"\\'")}'`;function Wo(r,e){return["@font-face{",`font-family:${jn(r)};`,`font-style:${e.style};`,`font-weight:${e.weight};`,`font-display:${Un};`,`src:url(${e.url}) format('woff2');`,e.unicodeRange?`unicode-range:${e.unicodeRange};`:"","}"].join("")}function qo(r,e){let[t,n=t]=r.split(" ").map(Number);return e>=t&&e<=n}async function Bn({fontCss:r,appFonts:e={},languages:t,publicPath:n="",indexHtml:s=null,pathResolver:o}){if(!r||typeof r.framework!="string"||!Array.isArray(r.app))throw new Error("[dndev-fonts] buildFontPlan: fontCss is required (ThemeDiscovery fontCss: theme discovery failed?)");if(!Array.isArray(t)||t.length===0)throw new Error("[dndev-fonts] buildFontPlan: languages is required (i18n discovery supportedLanguages)");let a=o.getAppRoot(),i=await o.findFiles(a,$n);xn([...r.app.map(({file:g,css:b})=>({file:g,content:b})),...i.map(g=>({file:o.getRelativePath(g),content:o.readSync(g,{format:"text"})??""})),...s===null?[]:[{file:"index.html",content:s}]]);let l=Ln({frameworkCss:r.framework,appCss:r.app}),u=o.resolveFrameworkPackage("@donotdev/ui"),c=new Map,p=g=>{let b=g.toLowerCase();return c.has(b)||c.set(b,Tn(g,{appFonts:e,appRoot:a,uiRoot:u,pathResolver:o})),c.get(b)},d=new Map,f=new Map,h=new Map,m=new Map,y=new Map;for(let{scope:g,roles:b,weights:k}of l)for(let[N,_]of Object.entries(b)){if(!_)continue;let F=vt[N];_.stack.forEach((A,G)=>{let j=A.toLowerCase();if(Bo.has(j)||Go.has(j))return;let re=/^(.+) fallback$/i.exec(A)?.[1];if(re&&p(re))return;let w=p(A);if(!w){d.has(j)||d.set(j,{family:A,token:F,scope:g});return}m.has(j)||m.set(j,{source:w,weights:new Set,scopes:new Set});let E=m.get(j);E.scopes.add(g);for(let{weight:ie}of k.values())E.weights.add(w.matchWeight(ie)),!w.provides(ie)&&!h.has(`${j}:${ie}`)&&h.set(`${j}:${ie}`,`${w.family}: weight ${ie} not in source, browser-synthesized`);if(G!==0)return;y.set(j,w);let P=_.origin,I=P?P.entries[1]:_.stack[1],V=Be(A);if(I&&I.replace(/^['"]|['"]$/g,"").trim().toLowerCase()===V.toLowerCase())return;let ge=P?.declaration??{source:"",scope:g},de=P?.token??F,me=`${ge.source}|${de}|${ge.value??A}`;if(f.has(me))return;let Ie=P?P.entries:[A],it=`${de}: ${[Ie[0],jn(V),...Ie.slice(1)].join(", ")};`;f.set(me,{location:In(ge),declared:de,family:A,expected:V,line:it})})}let S=[];for(let{family:g,token:b,scope:k}of d.values())S.push(`${b} (${k===se?":root":`.${k}`}) names '${g}', which nothing provides: install @fontsource-variable/${He(g)} or @fontsource/${He(g)} in the app, declare its woff2 files in appConfig.fonts['${g}'], or use a system family (SYSTEM_FONT_FAMILIES) or a generic one (sans-serif, serif, monospace, system-ui\u2026).`);for(let{location:g,declared:b,family:k,expected:N,line:_}of f.values())S.push(`${g}: ${b} lacks '${N}' right after '${k}' (the size-matched fallback face: no layout shift, no flicker). Write:
|
|
9
|
+
${_}`);if(S.length>0)throw St(`the theme fonts cannot ship:
|
|
10
|
+
- ${S.join(`
|
|
11
|
+
- `)}`);let T=[...new Set(["latin",...t.flatMap(Mn)])],R=new Map,v=g=>{if(!R.has(g)){let b=o.readSync(g,{format:"buffer"}),k=jo("sha256").update(b).digest("hex").slice(0,8),N=o.getBasename(g).replace(/\.woff2$/,"");R.set(g,`${n}${Rt}/${N}.${k}.woff2`)}return R.get(g)},x=[],O=[];for(let[g,{source:b,weights:k}]of m){let N=b.faces({weights:[...k].sort((_,F)=>_-F),subsets:T}).map(_=>({..._,family:b.family,url:v(_.file)}));O.push(...N),x.push({family:b.family,kind:b.kind,category:b.category,source:b.label,fallback:y.has(g)?Be(b.family):null})}let B=[...y.values()].map(g=>{try{return kn({family:g.family,category:g.category,metrics:_n(o.readSync(g.metricsFile,{format:"buffer"}))})}catch(b){throw St(`'${g.family}' (${g.label}): cannot measure ${g.metricsFile} for its fallback face (${b.message}). Its core file must be a woff2 with the Latin letters a-z.`)}}),M=l.find(({scope:g})=>g===se),te=[["body",zo],["headline",Ho]].flatMap(([g,b])=>{let k=M.roles[g]?.stack[0];if(!k||!m.has(k.toLowerCase()))return[];let N=M.weights.get(b)?.weight;if(N===void 0)throw St(`${b} is not defined: the framework tokens (@donotdev/components/styles) define it.`);let{source:_}=m.get(k.toLowerCase());return[{family:_.family,weight:_.matchWeight(N)}]}),W={};for(let g of t){let b=Mn(g),k=[];for(let{family:N,weight:_}of te)for(let F of O){if(F.family!==N||F.style!=="normal"||!qo(F.weight,_))continue;(F.subset===null?F.unicodeRange===null:b.includes(F.subset))&&!k.includes(F.url)&&k.push(F.url)}W[g]=k}return{display:Un,families:x,files:[...R].map(([g,b])=>({source:g,url:b})),css:[...O.map(g=>Wo(g.family,g)),...B].join(`
|
|
12
|
+
`),preloads:W,notices:[...h.values()]}}function Gn(r,{pathResolver:e,publicPath:t=""}){let n=e.resolveAppPath(`public/${Et}`);e.removeSync(n),e.ensureDirSync(n);let s=`${t}${Rt}/`;for(let{source:o,url:a}of r.files){if(!a.startsWith(s))throw new Error(`[dndev-fonts] writeFontPlan: ${a} is not under ${s}`);e.copySync(o,e.resolvePath(a.slice(s.length),n),{overwrite:!0})}return n}import{existsSync as xt,readFileSync as $t,realpathSync as Jo}from"node:fs";import{dirname as zn,join as _e,resolve as Hn}from"node:path";var ue="dndev-routes",We="entities",Vo="@donotdev/core",Wn=[".ts",".tsx",".js",".jsx"],Ko=`import { productEntity } from 'entities';
|
|
13
|
+
export const meta: PageMeta = { entity: productEntity, route: { params: ['slug'] } };`,qn=null;async function Xn(){return qn??=import("@babel/core").then(r=>r.default??r),qn}function Yn(r,e,t){let n=/\.[jt]sx$/.test(t);try{return r.parseSync(e,{configFile:!1,babelrc:!1,filename:t,sourceType:"module",parserOpts:{plugins:n?["typescript","jsx"]:["typescript"]}}).program}catch(s){throw C(ue,`${t} could not be parsed to resolve entities (PageMeta entity, entity field types): ${s.message}. Fix the syntax error.`,"invalid-configuration")}}function ve(r){return r.type==="StringLiteral"?r.value:r.name}function Re(r){let e=r;for(;e&&["TSAsExpression","TSSatisfiesExpression","TSNonNullExpression","ParenthesizedExpression"].includes(e.type);)e=e.expression;return e}function Xo(r,e){for(let t of r.body)if(!(t.type!=="ImportDeclaration"||t.importKind==="type")){for(let n of t.specifiers)if(n.local.name===e)return t.source.value!==We||n.type!=="ImportSpecifier"||n.importKind==="type"?null:ve(n.imported)}return null}function ke(r){let e=null,t=new Map;function n(){let c=_e(r,"package.json"),p=xt(c)?JSON.parse($t(c,"utf8")):null;return!!(p?.dependencies?.[We]||p?.devDependencies?.[We])}function s(c){if(e)return e;let p=n(),d=r,f=null;for(;p;){let y=_e(d,"node_modules",We);if(xt(_e(y,"package.json"))){f=Jo(y);break}let S=zn(d);if(S===d)break;d=S}if(!f)throw C(ue,`${c}, but the app has no \`entities\` package (${p?"not installed: run bun install":"not in the dependencies of its package.json"}). The entity is read from the app's defineEntity definitions. Fix: add \`"entities": "workspace:*"\` to the app's dependencies and export the entity from the entities package.`,"missing-required-resource");let h=JSON.parse($t(_e(f,"package.json"),"utf8")),m=Kn(Hn(f,h.main??"./index.ts"));if(!m)throw C(ue,`The \`entities\` package (${f}) has no entry module (package.json "main": ${JSON.stringify(h.main??"./index.ts")}). Fix: set "main" to its index file (./index.ts).`,"missing-required-resource");return e=m,e}async function o(c){if(!t.has(c)){let p=await Xn();t.set(c,Yn(p,$t(c,"utf8"),c))}return t.get(c)}function a(c,p){return p.startsWith(".")?Kn(Hn(zn(c),p)):null}async function i(c,p,d){let f=`${c}#${p}`;if(d.has(f))return null;d.add(f);let h=await o(c),m=[];for(let y of h.body)if(y.type==="ExportNamedDeclaration"&&y.exportKind!=="type"){let S=Vn(y.declaration,p);if(S!==void 0)return{init:S,program:h,file:c};for(let T of y.specifiers??[]){if(T.exportKind==="type"||ve(T.exported)!==p)continue;if(T.type!=="ExportSpecifier")return null;let R=ve(T.local);if(y.source){let v=a(c,y.source.value);return v?i(v,R,d):null}return l(c,h,R,d)}}else if(y.type==="ExportAllDeclaration"&&y.exportKind!=="type"){let S=a(c,y.source.value);S&&m.push(S)}for(let y of m){let S=await i(y,p,d);if(S)return S}return null}async function l(c,p,d,f){for(let h of p.body){let m=Vn(h,d);if(m!==void 0)return{init:m,program:p,file:c};if(!(h.type!=="ImportDeclaration"||h.importKind==="type"))for(let y of h.specifiers){if(y.local.name!==d||y.type!=="ImportSpecifier")continue;let S=a(c,h.source.value);return S?i(S,ve(y.imported),f):null}}return null}async function u(c){let p=[c];for(let d=0;d<p.length;d+=1){let f=await o(p[d]);for(let h of f.body){if(!(h.type==="ImportDeclaration"&&h.importKind!=="type"||h.type==="ExportNamedDeclaration"&&h.source&&h.exportKind!=="type"||h.type==="ExportAllDeclaration"&&h.exportKind!=="type"))continue;let y=a(p[d],h.source.value);y&&!p.includes(y)&&p.push(y)}}return p}return{async usesFieldType(c){if(!n())return!1;for(let p of await u(s("The app's package.json lists `entities` (its entity field types are read)")))if(Yo(await o(p),c))return!0;return!1},async collectionOf(c,p){let d=await i(s(`${p} declares a PageMeta entity`),c,new Set);if(!d)throw C(ue,`${p}: PageMeta entity \`${c}\` is not exported by the \`entities\` package. The page names the entity definition it shows a record of. Fix: export it from the entities package index (export { ${c} } from './\u2026').`,"invalid-configuration");return Zo(d,c,p)}}}function Zn(r){return r.body.filter(e=>e.type==="ImportDeclaration"&&e.source.value===Vo).flatMap(e=>e.specifiers).find(e=>e.type==="ImportSpecifier"&&ve(e.imported)==="defineEntity")?.local.name}function Jn(r,e){if(r?.type!=="ObjectExpression")return;let t=r.properties.find(n=>n.type==="ObjectProperty"&&!n.computed&&ve(n.key)===e);return Re(t?.value)}function Yo(r,e){let t=Zn(r);if(!t)return!1;let n=s=>{if(!s||typeof s.type!="string")return!1;if(s.type==="CallExpression"&&s.callee.type==="Identifier"&&s.callee.name===t){let o=Jn(Re(s.arguments[0]),"fields");if(o?.type==="ObjectExpression"&&o.properties.some(a=>{let i=Jn(Re(a.value),"type");return i?.type==="StringLiteral"&&i.value===e}))return!0}for(let o of Object.keys(s)){if(o==="loc"||o==="leadingComments"||o==="trailingComments")continue;let a=s[o];if(Array.isArray(a)?a.some(n):a&&typeof a=="object"&&n(a))return!0}return!1};return n(r)}function Vn(r,e){if(r?.type==="VariableDeclaration"){for(let t of r.declarations)if(t.id.type==="Identifier"&&t.id.name===e)return t.init??null}}function Kn(r){let e=r.replace(/\.[cm]?js$/,""),t=[r,...Wn.map(n=>`${e}${n}`),...Wn.map(n=>_e(r,`index${n}`))];for(let n of t)if(/\.[cm]?[jt]sx?$/.test(n)&&xt(n))return n;return null}function Zo({init:r,program:e,file:t},n,s){let o=Re(r),a=Zn(e);if(o?.type!=="CallExpression"||o.callee.type!=="Identifier"||!a||o.callee.name!==a)throw C(ue,`${s}: PageMeta entity \`${n}\` (${t}) is not a defineEntity definition. The build reads the collection from \`defineEntity({ collection: ... })\` in the entities package. Fix: export const ${n} = defineEntity({ name: '...', collection: '...', fields: { ... } }) with defineEntity imported from '@donotdev/core'.`,"invalid-configuration");let i=Re(o.arguments[0]),l=i?.type==="ObjectExpression"?i.properties.find(p=>p.type==="ObjectProperty"&&!p.computed&&ve(p.key)==="collection"):void 0,u=Re(l?.value),c=u?.type==="StringLiteral"?u.value:u?.type==="TemplateLiteral"&&u.expressions.length===0?u.quasis[0].value.cooked:null;if(!c)throw C(ue,`${s}: PageMeta entity \`${n}\` (${t}) has no literal \`collection\` in its defineEntity options. The page's records (sitemap, prerender, server metadata) are read from it. Fix: set collection: 'products' (a string literal) in the defineEntity call.`,"invalid-configuration");return c}async function Qn(r,e,t,n){if(!r||r.entity===void 0)return null;let s=r.entity?.identifier,o=r.entity?.expression;if(typeof o=="string"){let l=o.match(/^[A-Za-z_$][\w$]*\s*\??\.\s*([A-Za-z_$][\w$]*)$/)?.[1]??"productEntity";throw C(ue,`${t}: PageMeta entity \`${o}\` is not a bare identifier. The build reads the entity statically: only a defineEntity definition named-imported from 'entities' resolves to its collection (no namespace import, member access or call). Fix: import { ${l} } from 'entities'; then entity: ${l}`,"invalid-configuration")}if(typeof s!="string")throw C(ue,`${t}: PageMeta entity must be the entity definition imported from 'entities' (got ${JSON.stringify(r.entity)}). The build resolves it to the entity's collection. Fix:
|
|
14
|
+
${Ko}`,"invalid-configuration");let a=Yn(await Xn(),e,t),i=Xo(a,s);if(!i)throw C(ue,`${t}: PageMeta entity \`${s}\` is not imported from 'entities'. The page's entity must be a defineEntity definition of the app's \`entities\` package (one source for its collection). Fix: import { ${s} } from 'entities';`,"invalid-configuration");return n.collectionOf(i,t)}var Qo=["public/route-manifest.json","public/theme-manifest.json","public/i18n-manifest.json","public/asset-manifest.json","public/seo-manifest.json","public/pwa-manifest.json","public/dndev-fonts.css","public/robots.txt","public/sitemap.xml","public/rss.xml","public/llms.txt","public/llms-full.txt",L.next.revalidateRoute],ea="dndev-config-",er=".dndev-build";function Pt(r){if(!r)return!1;let e=D.getInstance(),t=e.resolveAppPath(er),n=process.env.DNDEV_BUILD_ID;try{return(e.readSync(t,{format:"text"})||"").trim()===n}catch{return!1}}function ta(r){if(!r)return;let e=D.getInstance(),t=e.resolveAppPath(er),n=process.env.DNDEV_BUILD_ID;try{e.writeSync(t,n,{overwrite:!0})}catch{}}function na(r,e,t){if(!r)return;let n=D.getInstance(),s=(a,i)=>{let l=n.normalizePath(a);if(!(t.has(l)||!n.pathExists(l)))try{n.removeSync(a),e.debug(`Removed stale: ${i}`)}catch{}};for(let a of Qo)s(n.resolveAppPath(a),a);let o=n.resolveAppPath("src/config");for(let a of n.readdirSync(o))a.startsWith(ea)&&a.endsWith(".js")&&s(n.resolvePath(a,o),`src/config/${a}`)}async function tr({routeHandler:r,themeHandler:e,i18nHandler:t,assetHandler:n,seoHandler:s,pwaHandler:o,blogContentHandler:a},i,{appFonts:l}={}){let u=r?.pathResolver;if(!u)throw new Error("PathResolver not available - handlers must be initialized with PathResolver");let c=u.getAppRoot(),p=u.getRepoRoot();if(!c||c===p){i.warn("\u26A0\uFE0F App root not properly set before discovery - waiting for appRoot resolution"),await new Promise(y=>setTimeout(y,0));let m=u.getAppRoot();if(!m||m===p)throw new Error("App root not set before discovery. Ensure resolveAppRoot() is called before runDiscoveries().")}if(Pt(c)){i.debug("Discoveries already completed this build, skipping");return}ta(c);let d=Date.now();u.startWriteRecording();let f;try{let m=await t.getDiscoveryData(),y={languages:m.supportedLanguages,defaultLanguage:m.fallbackLanguage};s.useLanguages(y),s.useTranslations(m.content);let{fontCss:S}=e?await e.getDiscoveryData():{},T=await Bn({fontCss:S,appFonts:l,languages:m.supportedLanguages,pathResolver:u});Gn(T,{pathResolver:u}),i.debug(`Font plan: ${T.families.map(({family:v})=>v).join(", ")||"system fonts only"} (${T.files.length} files)`);for(let v of T.notices)i.info(`\u{1F524} ${v}`);if(r)try{r.useLanguages(y),r.useI18n(m),r.useFonts(T),i.info("\u{1F50D} Starting route discovery...");let v=await r.generateFiles();s.useRoutes(v);let x=v?.routes?.length||0;i.info(`\u2705 Routes generated: ${x} routes found`),x===0&&i.error("\u274C NO ROUTES FOUND! Check that pages exist in src/pages/")}catch(v){throw i.error(`\u274C Route generation failed: ${v.message}`),v.stack&&i.error(`Stack: ${v.stack}`),v}else i.warn("\u26A0\uFE0F Route handler is disabled - no routes will be discovered");n.useFlagCodes(m.flagCodes,r?r.getEntityResolver():ke(c));let R=[{name:"Theme",handler:e},{name:"I18n",handler:t},{name:"Asset",handler:n},{name:"SEO",handler:s},{name:"PWA",handler:o},{name:"BlogContent",handler:a}];for(let{name:v,handler:x}of R)try{await x.generateFiles()}catch(O){if(ce(O))throw O;i.debug(`${v} generation failed: ${O.message}`)}try{ra(u,i)}catch(v){i.debug(`Env config generation failed (non-critical): ${v.message}`)}}finally{f=u.stopWriteRecording()}na(c,i,f);let h=Date.now()-d;i.verbose?.(`\u2705 All discoveries completed in ${h}ms - Next.js can now compile`)}function ra(r,e){let t={};for(let[a,i]of Object.entries(process.env))a.startsWith("NEXT_PUBLIC_")&&i!==void 0&&(t[a]=i);let n=`// Auto-generated DnDev env config by @donotdev/config
|
|
10
15
|
// Generated at: ${new Date().toISOString()}
|
|
11
16
|
// Populates _DNDEV_CONFIG_.env with NEXT_PUBLIC_* environment variables
|
|
12
17
|
|
|
@@ -23,38 +28,34 @@ if (typeof globalThis !== 'undefined') {
|
|
|
23
28
|
timestamp: Date.now(),
|
|
24
29
|
};
|
|
25
30
|
}
|
|
26
|
-
globalThis._DNDEV_CONFIG_.${
|
|
31
|
+
globalThis._DNDEV_CONFIG_.${Y.env} = envConfig;
|
|
27
32
|
}
|
|
28
33
|
|
|
29
34
|
// Export for compatibility
|
|
30
35
|
export default envConfig;
|
|
31
|
-
`,r
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
|
35
|
-
const SUPABASE_PUBLIC_KEY = process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY;
|
|
36
|
-
if (!SUPABASE_URL || !SUPABASE_PUBLIC_KEY) {
|
|
37
|
-
throw new Error(
|
|
38
|
-
'[dndev] Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLIC_KEY: ${t}.'
|
|
39
|
-
);
|
|
40
|
-
}
|
|
41
|
-
const CRUD = new SupabaseCrudAdapter(
|
|
36
|
+
`,s=r.resolveAppPath(L.next.configEnv);r.writeSync(s,n,{overwrite:!0});let o=Object.keys(t).length;e.debug(`Generated env config: ${o} NEXT_PUBLIC_* vars`)}var nr={debug:!1,verbose:process.env.CI!=="true",seo:{disabled:!1,generateRobotsTxt:!0,generateSitemap:!0,crawlDelay:1,aiCrawlers:"recommended",llmsTxt:!0,speculationRules:!0,hreflang:!0,breadcrumbSchema:!0,websiteSchema:!0,organizationSchema:!0},serverShim:{enabled:!0},discovery:{verbose:!0,cacheTimeout:6e4,fileLogging:!1,logDir:".dndev-logs"},features:{}};var De={...nr,generateManifest:!0,reactCompiler:!1,routes:{disabled:!1,routingMode:"app",generateMiddleware:!0},themes:{},i18n:{fallbackLanguage:"en"},assets:{},pwa:{}};function rr(r,e){let t={...r};return e&&Object.keys(e).forEach(n=>{e[n]&&typeof e[n]=="object"&&!Array.isArray(e[n])?t[n]=rr(r[n]||{},e[n]):t[n]=e[n]}),t}function sr(r={}){return rr(De,r)}function or(r){let{features:e={},routes:t={},themes:n={},i18n:s={},assets:o={},pwa:a={},seo:i={},serverShim:l,discovery:u={},generateManifest:c,debug:p,verbose:d,...f}=r,h=process.env.NODE_ENV==="production"?"production":"development";return{generateManifest:c,debug:p,verbose:d,mode:h,isDev:h==="development",routeOptions:t,themeOptions:n,i18nOptions:s,assetOptions:o,featureOptions:e,pwaOptions:a,seoOptions:i,discoveryOptions:u,nextConfigOptions:f}}import*as K from"@clack/prompts";var ne={reset:"\x1B[0m",green:"\x1B[32m",brightGreen:"\x1B[92m",red:"\x1B[31m",brightRed:"\x1B[91m",yellow:"\x1B[33m",brightYellow:"\x1B[93m",blue:"\x1B[34m",cyan:"\x1B[36m",brightCyan:"\x1B[96m",gray:"\x1B[90m",white:"\x1B[37m"};function sa(){return process.env.NO_COLOR?!1:process.platform==="win32"?!0:process.stdout.isTTY===!0}function oe(r,e){return sa()?`${e}${r}${ne.reset}`:r}function ae(r,e,t,n={}){let{logDir:s=".dndev-logs",fileLogging:o=!1}=n,a=D.getInstance(),i=null;if(o){let c=a.resolveAppPath(s);a.pathExists(c)||a.mkdir(c),i=a.resolveAppPath(`${s}/${r.replace(/[^a-zA-Z0-9]/g,"-")}.log`);let p=`=== ${r} Log Started at ${new Date().toISOString()} ===
|
|
37
|
+
`;a.writeSync(i,p)}let l=(c,p,d)=>{if(i){let f=new Date().toISOString(),h=d.length>0?" "+d.map(y=>typeof y=="object"?JSON.stringify(y,null,2):String(y)).join(" "):"",m=`${f} [${c}] ${p}${h}
|
|
38
|
+
`;a.appendFile(i,m)}},u=(c,p)=>{if(p.length===0)return c;let d=p.map(f=>typeof f=="object"?JSON.stringify(f,null,2):String(f)).join(" ");return`${c} ${d}`};return{debug:(c,...p)=>{e&&(o?l("DEBUG",c,p):K.log.message(oe(u(c,p),ne.gray)))},verbose:(c,...p)=>{t&&(o?l("VERBOSE",c,p):K.log.message(u(c,p)))},info:(c,...p)=>{o?l("INFO",c,p):K.log.info(oe(u(c,p),ne.brightCyan))},warn:(c,...p)=>{e&&o?l("WARN",c,p):K.log.warn(oe(u(c,p),ne.brightYellow))},error:(c,...p)=>{e&&o?l("ERROR",c,p):K.log.error(oe(u(c,p),ne.brightRed))},success:(c,...p)=>{e&&o?l("SUCCESS",c,p):K.log.success(oe(u(c,p),ne.brightGreen))},when:(c,p="debug")=>(d,...f)=>{if(c){let h=u(d,f);switch(p){case"verbose":t&&(K.log.message(h),l("VERBOSE",d,f));break;case"info":K.log.info(oe(h,ne.brightCyan)),l("INFO",d,f);break;case"warn":K.log.warn(oe(h,ne.brightYellow)),l("WARN",d,f);break;case"error":K.log.error(oe(h,ne.brightRed)),l("ERROR",d,f);break;case"success":K.log.success(oe(h,ne.brightGreen)),l("SUCCESS",d,f);break;default:e&&(K.log.message(oe(h,ne.gray)),l("DEBUG",d,f))}}},getLogFilePath:()=>i}}var ar=Object.freeze([{dependency:"@donotdev/supabase",module:"@donotdev/supabase/server",env:["SUPABASE_URL","SUPABASE_PUBLIC_KEY"],create:(r,[e,t])=>new r.SupabasePublicReader(r.createPublicServerClient(e,t))},{dependency:"@donotdev/firebase",module:"@donotdev/firebase/public",env:["FIREBASE_API_KEY","FIREBASE_PROJECT_ID"],create:(r,[e,t])=>new r.FirestorePublicReader(r.createPublicServerFirestore({apiKey:e,projectId:t}))}]);function ir(r){return ar.find(({dependency:e})=>r(e))}var lr=ar.map(({dependency:r})=>r).join(", ");var Ct=Object.freeze({pageGenerateMetadata:!0}),oa=Object.freeze({"@donotdev/supabase":{exports:"createPublicServerClient, SupabasePublicReader",comment:"RLS returns what a signed-out visitor can read.",construct:`new SupabasePublicReader(
|
|
42
39
|
createPublicServerClient(SUPABASE_URL, SUPABASE_PUBLIC_KEY)
|
|
43
|
-
)
|
|
44
|
-
|
|
40
|
+
)`},"@donotdev/firebase":{exports:"createPublicServerFirestore, FirestorePublicReader",comment:"Security Rules return what a signed-out visitor can read.",construct:`new FirestorePublicReader(
|
|
41
|
+
createPublicServerFirestore({ apiKey: FIREBASE_API_KEY, projectId: FIREBASE_PROJECT_ID })
|
|
42
|
+
)`}}),H=class{constructor(e,t={}){this.options={...this.getHandlerDefaults(),...t},this.logger=ae(`Next${this.getHandlerName()}Handler`,this.options.debug,this.options.verbose),this.pathResolver=D.getInstance(),this.configRoot=this.pathResolver.getAppRoot(),this.discovery=this.createDiscovery(e),this.initialize()}revalidate(){let e=this.options.revalidate??Z.revalidateSeconds;if(e===!1||Number.isInteger(e)&&e>0)return e;throw new Error(`appConfig.revalidate must be a whole number of seconds above 0, or false (kept until the next deploy). Got ${JSON.stringify(e)}.`)}revalidateLabel(){let e=this.revalidate();return e===!1?"kept until the next deploy":`re-rendered at most every ${e}s`}appDependsOn(e){let t=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"),{format:"json"});return!!(t?.dependencies?.[e]||t?.devDependencies?.[e])}serverCrudReader(e,t="the sitemap and llms.txt list published records",n="Mark these pages `seo: { noindex: true }`."){let s=e.filter(d=>d.collection);if(s.length===0)return{imports:"",setup:"",expr:null,schemas:null,named:{}};let o=s.map(d=>d.path).join(", "),a=ir(d=>this.appDependsOn(d));if(!a)throw new Error(`[dndev] ${o} list published records, but the app's backend provider has no server reader (supported: ${lr}). ${n}`);if(!this.appDependsOn("entities")){let d=[...new Set(s.map(f=>f.collection))];throw C("dndev-routes",`${o} ${s.length===1?"lists":"list"} published ${d.map(f=>`"${f}"`).join(", ")} records, read with their entity definition's read schema, but the app does not depend on an \`entities\` package. Add the app's \`entities\` package (exporting the defineEntity definition) to its dependencies. `+n,"missing-entities-package",{routes:s.map(f=>f.path),collections:d})}let{exports:i,comment:l,construct:u}=oa[a.dependency],c=a.env,p=s.map(({path:d,collection:f})=>({path:d,collection:f}));return{imports:`import { ${i} } from '${a.module}';
|
|
43
|
+
import * as entities from 'entities';
|
|
45
44
|
`,setup:`
|
|
46
|
-
// Public (anonymous) reader:
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
if (
|
|
45
|
+
// Public (anonymous) reader: ${l}
|
|
46
|
+
${c.map(d=>`const ${d} = process.env.NEXT_PUBLIC_${d};`).join(`
|
|
47
|
+
`)}
|
|
48
|
+
if (${c.map(d=>`!${d}`).join(" || ")}) {
|
|
50
49
|
throw new Error(
|
|
51
|
-
'[dndev] Set
|
|
50
|
+
'[dndev] Set ${c.map(d=>`NEXT_PUBLIC_${d}`).join(" and ")}: ${t}.'
|
|
52
51
|
);
|
|
53
52
|
}
|
|
54
|
-
const CRUD =
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
53
|
+
const CRUD = ${u};
|
|
54
|
+
|
|
55
|
+
// Records are read with their entity's read schema: keyed by the entity's field names
|
|
56
|
+
// (RLS / Security Rules decide what a signed-out visitor reads)
|
|
57
|
+
const READ_SCHEMAS = entityReadSchemas(entities, ${JSON.stringify(p)}, createSchemas);
|
|
58
|
+
`,expr:"CRUD",schemas:"READ_SCHEMAS",named:{"@donotdev/core/server":["createSchemas"],"@donotdev/core/next":["entityReadSchemas"]}}}getHandlerDefaults(){return{}}logDiscoveryResults(e){}createDiscovery(e){let t={...De.discovery,...this.options,...Ct};return new e(this.pathResolver,t)}initialize(){}setAppRoot(e){this.configRoot=e,this.pathResolver.setAppRoot(e)}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateConfigFile(e),this.options.generateManifest&&await this.generateManifest(e),await this.generateSpecificFiles(e),this.getHandlerName()==="Route"&&await this.generateNextEnvTypes(),this.logger.debug(`Generated ${this.getHandlerName()}: ${this.getGenerationSummary(e)}`),e}catch(e){throw this.logger.error(`${this.getHandlerName()} handler failed to generate files: ${e.message}`),this.logger.error(`Stack: ${e.stack||"No stack trace available"}`),e}}async generateConfigFile(e){let t=this.getHandlerName().toLowerCase(),n=L.next[`config${t.charAt(0).toUpperCase()}${t.slice(1)}`];if(!n)throw new Error(`No config path defined for ${t} handler. Add config${t.charAt(0).toUpperCase()}${t.slice(1)} to GENERATED_PATHS.next in constants.js`);let s=this.generateConfigContent(e);this.writeGeneratedFile(n,s,`DnDev ${t} config`)}generateConfigContent(e){let t=this.getHandlerName().toLowerCase(),n=Y[t]||t;return`// Auto-generated DnDev config by @donotdev/config
|
|
58
59
|
// Generated at: ${new Date().toISOString()}
|
|
59
60
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
60
61
|
|
|
@@ -71,12 +72,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
71
72
|
timestamp: Date.now(),
|
|
72
73
|
};
|
|
73
74
|
}
|
|
74
|
-
globalThis._DNDEV_CONFIG_.${
|
|
75
|
+
globalThis._DNDEV_CONFIG_.${n} = ${t}Config;
|
|
75
76
|
}
|
|
76
77
|
|
|
77
78
|
// Export for compatibility
|
|
78
79
|
export default ${t}Config;
|
|
79
|
-
`}writeGeneratedFile(e,t,s="file"){let r=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(r,t,{overwrite:!0}),this.logger.debug(`Generated ${s}: ${r}`),r}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}applyViteIgnorePlugin(e,t){return e.plugins=e.plugins||[],e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^vite$/})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/^@vitejs\//})),e.plugins.push(new t.IgnorePlugin({resourceRegExp:/vite/,contextRegExp:/node_modules/})),e}mergeRewrites(e,t){let s={beforeFiles:t?.beforeFiles||[],afterFiles:t?.afterFiles||[],fallback:t?.fallback||[]};return{beforeFiles:[...Array.isArray(e)?[]:e?.beforeFiles||[],...s.beforeFiles],afterFiles:[...Array.isArray(e)?e:e?.afterFiles||[],...s.afterFiles],fallback:[...Array.isArray(e)?[]:e?.fallback||[],...s.fallback]}}async _generateFiles(){return this.generateFiles()}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}async generateAPIHandler(e){return Promise.resolve()}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}formatAPIResponse(e){throw new Error("formatAPIResponse() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var X=class o{constructor(e,t={}){if(this.constructor===o)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=B(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._getPatterns();this.options.verbose&&s&&(typeof s=="object"&&s.pattern?this.logger.verbose(`Pattern: ${s.pattern}`):typeof s=="string"&&this.logger.verbose(`Pattern: ${s}`),s.dirs&&this.logger.verbose(`Search directories: ${s.dirs.slice(0,3).join(", ")}${s.dirs.length>3?` (${s.dirs.length} total)`:""}`));let r=await this._scanFiles(s),n=await this._processFiles(r);this.cache={...n,timestamp:Date.now()};let a=Date.now()-t;return this.logger.debug(`Discovery completed in ${a}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _processFiles(e){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),s=t[t.length-1],r=s.split(".")[0],n=s.split(".").pop();return{fileName:s,baseName:r,extension:n,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let s=this.pathResolver.getFileInfo(e);return s?await t(s):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(s){return this.logger.debug(`Error processing file ${e}: ${s.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(r=>this._processSingleFile(r,t)))).filter(r=>r!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var pe={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},Ce=class extends X{constructor(e,t={}){super(e,{assets:V.assets.fallback,assetPatterns:V.assets.patterns,frameworkPackage:qe.package,assetsPath:qe.assetsPath,modernFormats:V.assets.modern,...t}),this.hasRunForSession=!1}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=await this._ensureDefaultAssets(t),r=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(r)||this.logger.warn("logo.svg not found in public/. Add your logo.svg to generate PWA assets, or copy from node_modules/@donotdev/ui/assets/logo.svg");let a=[],i=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(i)&&this.options.generateAssets!==!1&&(a=(await this._generateMissingAssets(t))?.generated||[]);let{consumerFiles:l}=e,p=await this._processAssetFiles(l),c=this._buildAssetManifest(p),u=await this._readLogoSvgContent("/logo.svg",t);return{assets:p,manifest:{...c,logoSvgContent:u},copiedAssets:s,generatedAssets:a,pwaIcons:this._extractPWAIcons(p)}}_extractPWAIcons(e){let t=[/icon-(\d+)x(\d+)\.(png|jpg|jpeg|webp|svg)/i,/apple-touch-icon/i,/android-chrome/i,/favicon\.(ico|svg)/i];return e.filter(s=>{let r=s.path.split("/").pop()||"";return t.some(n=>n.test(r))}).map(s=>{let r=s.path.split("/").pop()||"",n=r.match(/(\d+)x(\d+)/),a=n?{width:parseInt(n[1]),height:parseInt(n[2])}:this._getDefaultIconSize(r);return{type:"icon",path:s.path.replace(/^\/?public\//,""),size:a,format:s.format||this._getFormatFromPath(s.path),purpose:this._getIconPurpose(r)}})}_getDefaultIconSize(e){return e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("favicon")?{width:32,height:32}:{width:192,height:192}}_getFormatFromPath(e){return e.split(".").pop()?.toLowerCase()||"png"}_getIconPurpose(e){return e.includes("maskable")||e.includes("mask")?"maskable":"any"}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let s=this.getAssets().map(n=>n.path),r=t||this.options.modernFormats;for(let n of r){let a=`/${e}.${n}`;if(s.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let s=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${s}`),!s)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let r=this.pathResolver.resolveAppPath(be.public);this.pathResolver.pathExists(r)||(this.pathResolver.mkdir(r),this.logger.debug(`Created public directory: ${r}`));for(let n of this.options.assets)await this._ensureAsset(n,r,s)&&t.push(n);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(s){this.logger.debug(`Failed to ensure default assets: ${s.message}`)}return t}async _ensureAsset(e,t,s){let r=this.pathResolver.resolveAppPath(`${be.public}/${e}`);if(this.pathResolver.pathExists(r))return this.logger.debug(`Asset exists: ${e}`),!1;let n=this.pathResolver.normalizePath(`${s}/${e}`);if(this.pathResolver.pathExists(n)){if(await this.pathResolver.copy(n,r))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}async _processAssetFiles(e){let t=[];for(let s of e)try{let r=this.pathResolver.getFileInfo(s);if(r&&r.isFile){let n=s.split("/").pop()||s.split("\\").pop(),a=this._analyzeAsset(n,r.size);a&&t.push(a)}}catch(r){this.logger.debug(`Error processing asset file ${s}: ${r.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let s=this._determineAssetType(e),r=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:s,format:r,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(r)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let s=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(s)?"image":["woff2","woff","ttf","otf"].includes(s)?"font":["json"].includes(s)?"json":["ico"].includes(s)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,s=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+s[r]}_matchesPattern(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s.includes(r.replace("*",""))}_buildAssetManifest(e){let t=e.map(r=>r.path);return{logo:{optimal:this._getOptimalAsset("logo",t,this.options.modernFormats),fallback:this._getOptimalAsset("logo",t,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",t,["svg","ico"]),fallback:this._getOptimalAsset("favicon",t,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",t,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",t,["png"]),512:this._getOptimalAsset("android-chrome-512x512",t,["png"])},manifest:t.find(r=>r.includes("manifest.json"))||null,modernFormats:e.filter(r=>r.isModern).map(r=>r.path),fallbackFormats:e.filter(r=>!r.isModern).map(r=>r.path)}}_getOptimalAsset(e,t,s){for(let r of s){let n=`/${e}.${r}`;if(t.includes(n))return n}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),s=await this._resolvePackage("@donotdev/ui",t);if(!s)return this.logger.debug("@donotdev/ui package not found"),null;let r=this.pathResolver.normalizePath(`${s}/assets`);return this.pathResolver.pathExists(r)?(this.logger.debug(`Using framework assets from: ${r}`),r):(this.logger.debug(`Assets directory not found: ${r}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let s=this.pathResolver.resolveFrameworkPackage(e,t);return s?(this.logger.debug(`Found package: ${s}`),s):(this.logger.debug(`Package ${e} not found`),null)}catch(s){return this.logger.debug(`Error resolving package ${e}: ${s.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let s=e.slice(1),r=this.pathResolver.resolveAppPath(`${be.public}/${s}`);return this.pathResolver.pathExists(r)&&await this.pathResolver.read(r,{format:"text"})||null}catch(s){return this.logger.debug(`Failed to read logo SVG content: ${s.message}`),null}}async _copyFrameworkLogo(e){try{let t=await this._resolveFrameworkAssetsDir(e);if(!t)return this.logger.debug("Framework assets directory not found"),!1;let s=this.pathResolver.normalizePath(`${t}/logo.svg`);if(!this.pathResolver.pathExists(s))return this.logger.debug("Framework logo.svg not found"),!1;let r=this.pathResolver.resolveAppPath(be.public);this.pathResolver.pathExists(r)||this.pathResolver.mkdir(r);let n=this.pathResolver.resolveAppPath("public/logo.svg");return await this.pathResolver.copy(s,n)}catch(t){return this.logger.debug(`Failed to copy framework logo: ${t.message}`),!1}}async _renderOgImage(e,t){let{width:s,height:r}=await e(t).metadata(),n=Math.min(pe.logoWidth/s,pe.logoHeight/r),a=await e(t,{density:Math.ceil(72*n)}).resize(pe.logoWidth,pe.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:pe.width,height:pe.height,channels:4,background:pe.background}}).composite([{input:a}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),s=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let r=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],n=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...n,...r].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of n){let u=`${s}/${c.name}`;if(this.pathResolver.pathExists(u)){i.push(c.name);continue}try{await this.pathResolver.write(`public/${c.name}`,l),a.push(c.name)}catch(h){this.logger.debug(`Failed to copy ${c.name}: ${h.message}`),i.push(c.name)}}let p=await import("sharp").catch(()=>null);if(!p)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...r.map(c=>c.name));else{for(let u of r){let h=`${s}/${u.name}`;if(this.pathResolver.pathExists(h)){i.push(u.name);continue}try{let g=p.default(t).resize(u.size,u.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),d;u.format==="ico"?d=await g.toFormat("png").toBuffer():d=await g.toFormat(u.format).toBuffer(),await this.pathResolver.write(`public/${u.name}`,d),a.push(u.name)}catch(g){this.logger.debug(`Failed to generate ${u.name}: ${g.message}`),i.push(u.name)}}let c=ce.slice(1);if(this.pathResolver.pathExists(`${s}/${c}`))i.push(c);else try{let u=await this._renderOgImage(p.default,t);await this.pathResolver.write(`public/${c}`,u),a.push(c)}catch(u){this.logger.debug(`Failed to generate ${c}: ${u.message}`),i.push(c)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:requiredAssets.map(p=>p.name),error:l.message}}}};var rt={data:null},st=class extends G{constructor(e={}){super(Ce,e)}getHandlerDefaults(){return{manifestPath:F.next.assetManifest,generateManifest:!0,optimizeImages:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
80
|
+
`}writeGeneratedFile(e,t,n="file"){let s=this.pathResolver.resolveAppPath(e);return this.pathResolver.writeSync(s,t,{overwrite:!0}),this.logger.debug(`Generated ${n}: ${s}`),s}async generateManifest(e){let t=this.createManifestContent(e);this.writeGeneratedFile(this.options.manifestPath,JSON.stringify(t,null,2),`${this.getHandlerName().toLowerCase()} manifest`)}async generateNextEnvTypes(){try{let e=this.pathResolver.resolveAppPath("next-env.d.ts"),t=this.pathResolver.readSync(e,{format:"text"});t&&(this.writeGeneratedFile("next-env.d.ts",t,"Next.js environment types"),this.logger.debug("Generated Next.js environment types"))}catch(e){this.logger.debug(`Could not generate Next.js environment types: ${e.message}`)}}getHandlerName(){throw new Error("getHandlerName() must be implemented by subclass")}async getDiscoveryData(){throw new Error("getDiscoveryData() must be implemented by subclass")}async generateSpecificFiles(e){throw new Error("generateSpecificFiles() must be implemented by subclass")}getAPIRewrites(){throw new Error("getAPIRewrites() must be implemented by subclass")}createManifestContent(e){throw new Error("createManifestContent() must be implemented by subclass")}getGenerationSummary(e){throw new Error("getGenerationSummary() must be implemented by subclass")}};var ee=class r{constructor(e,t={}){if(this.constructor===r)throw new Error("BaseDiscovery is abstract and cannot be instantiated directly");this.pathResolver=e,this.options={...t},process.env.NODE_ENV==="development"&&(this.options.cacheTimeout=Math.max(this.options.cacheTimeout||6e4,3e5)),this.logger=ae(this._getDiscoveryType(),this.options.debug,this.options.verbose,{fileLogging:this.options.fileLogging,logDir:this.options.logDir}),this.cache=null,this._lastDiscoveryTime=0}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let n=await this._getPatterns();this.options.verbose&&n&&(typeof n=="object"&&n.pattern?this.logger.verbose(`Pattern: ${n.pattern}`):typeof n=="string"&&this.logger.verbose(`Pattern: ${n}`),n.dirs&&this.logger.verbose(`Search directories: ${n.dirs.slice(0,3).join(", ")}${n.dirs.length>3?` (${n.dirs.length} total)`:""}`));let s=await this._prepareFiles(),o=await this._scanFiles(n),a=await this._processFiles(o,s);this.cache={...a,timestamp:Date.now()};let i=Date.now()-t;return this.logger.debug(`Discovery completed in ${i}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){if(ce(n))throw n;return this.logger.error(`${this._getDiscoveryType()} discovery failed during file scanning: ${n.message}`),this.logger.error(`Stack: ${n.stack||"No stack trace available"}`),this._getEmptyResult()}}clearCache(){this.cache=null,this._lastDiscoveryTime=0,this.logger.debug("Cache cleared")}getCachedResults(){return this.cache}_getDiscoveryType(){throw new Error("_getDiscoveryType must be implemented by subclass")}_getPatterns(){throw new Error("_getPatterns must be implemented by subclass")}_getPatternType(){throw new Error("_getPatternType must be implemented by subclass")}async _prepareFiles(){return{}}async _processFiles(e,t){throw new Error("_processFiles must be implemented by subclass")}_getEmptyResult(){throw new Error("_getEmptyResult must be implemented by subclass")}_getDiscoverySummary(){throw new Error("_getDiscoverySummary must be implemented by subclass")}async _scanFiles(e){let t=this._getPatternType();return await this.pathResolver.resolveFiles(e,t)}_extractFileNameInfo(e){let t=e.split("/"),n=t[t.length-1],s=n.split(".")[0],o=n.split(".").pop();return{fileName:n,baseName:s,extension:o,directory:t.slice(0,-1).join("/")}}async _processSingleFile(e,t){try{let n=this.pathResolver.getFileInfo(e);return n?await t(n):(this.logger.debug(`Could not get file info: ${e}`),null)}catch(n){if(ce(n))throw n;return this.logger.debug(`Error processing file ${e}: ${n.message}`),null}}async _batchProcessFiles(e,t){return(await Promise.all(e.map(s=>this._processSingleFile(s,t)))).filter(s=>s!==null)}_isCacheValid(){return this.cache?Date.now()-this.cache.timestamp<this.options.cacheTimeout:!1}};var tc={isDevelopment:typeof window<"u"?window.location.hostname==="localhost":!1},cr=[{id:"en",name:"English",nativeName:"English",flagCode:"gb"},{id:"us",name:"English (US)",nativeName:"English (US)",countryCode:"US",dialCode:"+1"},{id:"gb",name:"English (UK)",nativeName:"English (UK)",countryCode:"GB",dialCode:"+44"},{id:"en-ca",name:"English (Canada)",nativeName:"English (Canada)",flagCode:"ca",countryCode:"CA",dialCode:"+1"},{id:"au",name:"English (Australia)",nativeName:"English (Australia)",countryCode:"AU",dialCode:"+61"},{id:"ie",name:"English (Ireland)",nativeName:"English (Ireland)",countryCode:"IE",dialCode:"+353"},{id:"es",name:"Spanish",nativeName:"Espa\xF1ol",countryCode:"ES",dialCode:"+34"},{id:"mx",name:"Spanish (Mexico)",nativeName:"Espa\xF1ol (M\xE9xico)",countryCode:"MX",dialCode:"+52"},{id:"es-ar",name:"Spanish (Argentina)",nativeName:"Espa\xF1ol (Argentina)",flagCode:"ar",countryCode:"AR",dialCode:"+54"},{id:"fr",name:"French",nativeName:"Fran\xE7ais",flagCode:"fr",countryCode:"FR",dialCode:"+33"},{id:"fr-be",name:"French (Belgium)",nativeName:"Fran\xE7ais (Belgique)",flagCode:"be",countryCode:"BE",dialCode:"+32"},{id:"ch",name:"French (Switzerland)",nativeName:"Fran\xE7ais (Suisse)",countryCode:"CH",dialCode:"+41"},{id:"de",name:"German",nativeName:"Deutsch",countryCode:"DE",dialCode:"+49"},{id:"at",name:"German (Austria)",nativeName:"Deutsch (\xD6sterreich)",countryCode:"AT",dialCode:"+43"},{id:"it",name:"Italian",nativeName:"Italiano",countryCode:"IT",dialCode:"+39"},{id:"pt",name:"Portuguese",nativeName:"Portugu\xEAs",countryCode:"PT",dialCode:"+351"},{id:"br",name:"Portuguese (Brazil)",nativeName:"Portugu\xEAs (Brasil)",flagCode:"br",countryCode:"BR",dialCode:"+55"},{id:"ru",name:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",countryCode:"RU",dialCode:"+7"},{id:"ja",name:"Japanese",nativeName:"\u65E5\u672C\u8A9E",countryCode:"JP",dialCode:"+81"},{id:"ko",name:"Korean",nativeName:"\uD55C\uAD6D\uC5B4",countryCode:"KR",dialCode:"+82"},{id:"zh",name:"Chinese",nativeName:"\u4E2D\u6587",countryCode:"CN",dialCode:"+86"},{id:"ar",name:"Arabic",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flagCode:"sa",countryCode:"SA",dialCode:"+966"},{id:"ar-ma",name:"Arabic (Morocco)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u0645\u063A\u0631\u0628)",flagCode:"ma",countryCode:"MA",dialCode:"+212"},{id:"ar-dz",name:"Arabic (Algeria)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0627\u0644\u062C\u0632\u0627\u0626\u0631)",flagCode:"dz",countryCode:"DZ",dialCode:"+213"},{id:"ar-tn",name:"Arabic (Tunisia)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u062A\u0648\u0646\u0633)",flagCode:"tn",countryCode:"TN",dialCode:"+216"},{id:"ar-ly",name:"Arabic (Libya)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0644\u064A\u0628\u064A\u0627)",flagCode:"ly",countryCode:"LY",dialCode:"+218"},{id:"ar-mr",name:"Arabic (Mauritania)",nativeName:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629 (\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627)",flagCode:"mr",countryCode:"MR",dialCode:"+222"},{id:"hi",name:"Hindi",nativeName:"\u0939\u093F\u0928\u094D\u0926\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"nl",name:"Dutch",nativeName:"Nederlands",countryCode:"NL",dialCode:"+31"},{id:"sv",name:"Swedish",nativeName:"Svenska",countryCode:"SE",dialCode:"+46"},{id:"da",name:"Danish",nativeName:"Dansk",countryCode:"DK",dialCode:"+45"},{id:"no",name:"Norwegian",nativeName:"Norsk",countryCode:"NO",dialCode:"+47"},{id:"fi",name:"Finnish",nativeName:"Suomi",countryCode:"FI",dialCode:"+358"},{id:"pl",name:"Polish",nativeName:"Polski",countryCode:"PL",dialCode:"+48"},{id:"tr",name:"Turkish",nativeName:"T\xFCrk\xE7e",countryCode:"TR",dialCode:"+90"},{id:"th",name:"Thai",nativeName:"\u0E44\u0E17\u0E22",countryCode:"TH",dialCode:"+66"},{id:"vi",name:"Vietnamese",nativeName:"Ti\u1EBFng Vi\u1EC7t",countryCode:"VN",dialCode:"+84"},{id:"id",name:"Indonesian",nativeName:"Bahasa Indonesia",countryCode:"ID",dialCode:"+62"},{id:"ms",name:"Malay",nativeName:"Bahasa Melayu",flagCode:"my",countryCode:"MY",dialCode:"+60"},{id:"tl",name:"Filipino",nativeName:"Tagalog",countryCode:"PH",dialCode:"+63"},{id:"bg",name:"Bulgarian",nativeName:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",countryCode:"BG",dialCode:"+359"},{id:"cs",name:"Czech",nativeName:"\u010Ce\u0161tina",countryCode:"CZ",dialCode:"+420"},{id:"el",name:"Greek",nativeName:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",countryCode:"GR",dialCode:"+30"},{id:"he",name:"Hebrew",nativeName:"\u05E2\u05D1\u05E8\u05D9\u05EA",countryCode:"IL",dialCode:"+972"},{id:"hu",name:"Hungarian",nativeName:"Magyar",countryCode:"HU",dialCode:"+36"},{id:"is",name:"Icelandic",nativeName:"\xCDslenska",countryCode:"IS",dialCode:"+354"},{id:"lt",name:"Lithuanian",nativeName:"Lietuvi\u0173",countryCode:"LT",dialCode:"+370"},{id:"lv",name:"Latvian",nativeName:"Latvie\u0161u",countryCode:"LV",dialCode:"+371"},{id:"mt",name:"Maltese",nativeName:"Malti",countryCode:"MT",dialCode:"+356"},{id:"ro",name:"Romanian",nativeName:"Rom\xE2n\u0103",countryCode:"RO",dialCode:"+40"},{id:"sk",name:"Slovak",nativeName:"Sloven\u010Dina",countryCode:"SK",dialCode:"+421"},{id:"sl",name:"Slovenian",nativeName:"Sloven\u0161\u010Dina",flagCode:"si",countryCode:"SI",dialCode:"+386"},{id:"uk",name:"Ukrainian",nativeName:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flagCode:"ua",countryCode:"UA",dialCode:"+380"},{id:"et",name:"Estonian",nativeName:"Eesti",countryCode:"EE",dialCode:"+372"},{id:"ca",name:"Catalan",nativeName:"Catal\xE0",countryCode:"ES",dialCode:"+34"},{id:"eu",name:"Basque",nativeName:"Euskara",countryCode:"ES",dialCode:"+34"},{id:"gl",name:"Galician",nativeName:"Galego",countryCode:"ES",dialCode:"+34"},{id:"cy",name:"Welsh",nativeName:"Cymraeg",countryCode:"GB",dialCode:"+44"},{id:"ga",name:"Irish",nativeName:"Gaeilge",flagCode:"ie",countryCode:"IE",dialCode:"+353"},{id:"gd",name:"Scottish Gaelic",nativeName:"G\xE0idhlig",flagCode:"gb-sct",countryCode:"GB",dialCode:"+44"},{id:"br-fr",name:"Breton",nativeName:"Brezhoneg",flagCode:"bzh",countryCode:"FR",dialCode:"+33"},{id:"co",name:"Corsican",nativeName:"Corsu",flagCode:"fr-cor",countryCode:"FR",dialCode:"+33"},{id:"oc",name:"Occitan",nativeName:"Occitan",countryCode:"FR",dialCode:"+33"},{id:"rm",name:"Romansh",nativeName:"Rumantsch",countryCode:"CH",dialCode:"+41"},{id:"lb",name:"Luxembourgish",nativeName:"L\xEBtzebuergesch",countryCode:"LU",dialCode:"+352"},{id:"af",name:"Afrikaans",nativeName:"Afrikaans",countryCode:"ZA",dialCode:"+27"},{id:"sw",name:"Swahili",nativeName:"Kiswahili",countryCode:"KE",dialCode:"+254"},{id:"am",name:"Amharic",nativeName:"\u12A0\u121B\u122D\u129B",flagCode:"et",countryCode:"ET",dialCode:"+251"},{id:"bn",name:"Bengali",nativeName:"\u09AC\u09BE\u0982\u09B2\u09BE",flagCode:"bd",countryCode:"BD",dialCode:"+880"},{id:"gu",name:"Gujarati",nativeName:"\u0A97\u0AC1\u0A9C\u0AB0\u0ABE\u0AA4\u0AC0",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"kn",name:"Kannada",nativeName:"\u0C95\u0CA8\u0CCD\u0CA8\u0CA1",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ml",name:"Malayalam",nativeName:"\u0D2E\u0D32\u0D2F\u0D3E\u0D33\u0D02",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"mr",name:"Marathi",nativeName:"\u092E\u0930\u093E\u0920\u0940",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ne",name:"Nepali",nativeName:"\u0928\u0947\u092A\u093E\u0932\u0940",flagCode:"np",countryCode:"NP",dialCode:"+977"},{id:"pa",name:"Punjabi",nativeName:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"si",name:"Sinhala",nativeName:"\u0DC3\u0DD2\u0D82\u0DC4\u0DBD",countryCode:"LK",dialCode:"+94"},{id:"ta",name:"Tamil",nativeName:"\u0BA4\u0BAE\u0BBF\u0BB4\u0BCD",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"te",name:"Telugu",nativeName:"\u0C24\u0C46\u0C32\u0C41\u0C17\u0C41",flagCode:"in",countryCode:"IN",dialCode:"+91"},{id:"ur",name:"Urdu",nativeName:"\u0627\u0631\u062F\u0648",flagCode:"pk",countryCode:"PK",dialCode:"+92"},{id:"fa",name:"Persian",nativeName:"\u0641\u0627\u0631\u0633\u06CC",flagCode:"ir",countryCode:"IR",dialCode:"+98"},{id:"ps",name:"Pashto",nativeName:"\u067E\u069A\u062A\u0648",countryCode:"AF",dialCode:"+93"},{id:"uz",name:"Uzbek",nativeName:"O\u02BBzbek",countryCode:"UZ",dialCode:"+998"},{id:"kk",name:"Kazakh",nativeName:"\u049A\u0430\u0437\u0430\u049B",flagCode:"kz",countryCode:"KZ",dialCode:"+7"},{id:"ky",name:"Kyrgyz",nativeName:"\u041A\u044B\u0440\u0433\u044B\u0437\u0447\u0430",flagCode:"kg",countryCode:"KG",dialCode:"+996"},{id:"tg",name:"Tajik",nativeName:"\u0422\u043E\u04B7\u0438\u043A\u04E3",flagCode:"tj",countryCode:"TJ",dialCode:"+992"},{id:"mn",name:"Mongolian",nativeName:"\u041C\u043E\u043D\u0433\u043E\u043B",countryCode:"MN",dialCode:"+976"},{id:"my",name:"Burmese",nativeName:"\u1019\u103C\u1014\u103A\u1019\u102C",flagCode:"mm",countryCode:"MM",dialCode:"+95"},{id:"km",name:"Khmer",nativeName:"\u1781\u17D2\u1798\u17C2\u179A",flagCode:"kh",countryCode:"KH",dialCode:"+855"},{id:"lo",name:"Lao",nativeName:"\u0EA5\u0EB2\u0EA7",flagCode:"la",countryCode:"LA",dialCode:"+856"},{id:"ka",name:"Georgian",nativeName:"\u10E5\u10D0\u10E0\u10D7\u10E3\u10DA\u10D8",flagCode:"ge",countryCode:"GE",dialCode:"+995"},{id:"hy",name:"Armenian",nativeName:"\u0540\u0561\u0575\u0565\u0580\u0565\u0576",flagCode:"am",countryCode:"AM",dialCode:"+374"},{id:"az",name:"Azerbaijani",nativeName:"Az\u0259rbaycan",countryCode:"AZ",dialCode:"+994"},{id:"be",name:"Belarusian",nativeName:"\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0430\u044F",flagCode:"by",countryCode:"BY",dialCode:"+375"},{id:"mk",name:"Macedonian",nativeName:"\u041C\u0430\u043A\u0435\u0434\u043E\u043D\u0441\u043A\u0438",countryCode:"MK",dialCode:"+389"},{id:"sr",name:"Serbian",nativeName:"\u0421\u0440\u043F\u0441\u043A\u0438",countryCode:"RS",dialCode:"+381"},{id:"bs",name:"Bosnian",nativeName:"Bosanski",flagCode:"ba",countryCode:"BA",dialCode:"+387"},{id:"hr",name:"Croatian",nativeName:"Hrvatski",countryCode:"HR",dialCode:"+385"},{id:"sq",name:"Albanian",nativeName:"Shqip",flagCode:"al",countryCode:"AL",dialCode:"+355"},{id:"md",name:"Moldovan",nativeName:"Moldoveneasc\u0103",countryCode:"MD",dialCode:"+373"}],aa={US:"United States",GB:"United Kingdom",CA:"Canada",AU:"Australia",IE:"Ireland",FR:"France",BE:"Belgium",CH:"Switzerland",DE:"Germany",AT:"Austria",IT:"Italy",PT:"Portugal",BR:"Brazil",ES:"Spain",MX:"Mexico",AR:"Argentina",RU:"Russia",JP:"Japan",KR:"South Korea",CN:"China",SE:"Sweden",NO:"Norway",DK:"Denmark",FI:"Finland",NL:"Netherlands",PL:"Poland",CZ:"Czech Republic",HU:"Hungary",RO:"Romania",BG:"Bulgaria",GR:"Greece",TR:"Turkey",IL:"Israel",IN:"India",ZA:"South Africa"};function ia(){return cr.filter(r=>r.countryCode!==void 0&&r.dialCode!==void 0).map(r=>({code:r.countryCode,dialCode:r.dialCode,flagCode:r.flagCode||r.id,name:r.countryName||aa[r.countryCode]||r.name}))}var la=ia(),At="/flags";function ur(r){return`${r.toLowerCase()}.svg`}function Nt(r){return cr.find(t=>t.id===r)?.flagCode||r}function pr(){return[...new Set(la.map(r=>r.flagCode))]}var be={width:1200,height:630,logoWidth:720,logoHeight:360,background:"#ffffff"},ca="public/logo.svg is missing: it is the site logo (Organization / publisher logo in the JSON-LD, the default logo) and the source of the favicon, PWA icons and og-image.png. Add public/logo.svg.",dr="/manifest.json",qe=class extends ee{constructor(e,t={}){super(e,{assets:X.assets.fallback,assetPatterns:X.assets.patterns,frameworkPackage:lt.package,assetsPath:lt.assetsPath,modernFormats:X.assets.modern,...t}),this.hasRunForSession=!1,this.flagCodes=null,this.entityResolver=null}_getDiscoveryType(){return"Asset"}async _getPatterns(){return await this.pathResolver.resolvePatterns("assets")}_getPatternType(){return"assets"}async _prepareFiles(){let e=this.pathResolver.getAppRoot(),t=await this._ensureDefaultAssets(e);if(this.flagCodes){let i=await this.entityResolver.usesFieldType("tel"),l=this._ensureFlags(i?[...new Set([...this.flagCodes,...pr()])]:this.flagCodes);l.length>0&&this.logger.debug(`Copied ${l.length} flags to public${At}/: ${l.join(", ")}`)}let n=this.pathResolver.resolveAppPath("public/logo.svg");this.pathResolver.pathExists(n)||this.logger.warn(ca);let o=[],a=this.pathResolver.resolveAppPath("public/logo.svg");return this.pathResolver.pathExists(a)&&this.options.generateAssets!==!1&&(o=(await this._generateMissingAssets(e))?.generated||[]),{copiedAssets:t,generatedAssets:o}}async _processFiles(e,{copiedAssets:t,generatedAssets:n}){let s=this.pathResolver.getAppRoot(),{consumerFiles:o}=e,a=await this._processAssetFiles(o),i=this._buildAssetManifest(a,{webAppManifest:this.pathResolver.pathExists(this.pathResolver.resolveAppPath(`public${dr}`))}),l=await this._readLogoSvgContent("/logo.svg",s);return{assets:a,manifest:{...i,logoSvgContent:l},copiedAssets:t,generatedAssets:n}}_getEmptyResult(){return{assets:[],manifest:this._getEmptyManifest(),copiedAssets:[],timestamp:Date.now()}}_getDiscoverySummary(){let e=this.cache?.assets?.length||0,t=this.cache?.copiedAssets?.length||0;return`${e} assets, ${t} copied`}useFlagCodes(e,t){this.flagCodes=e,this.entityResolver=t}async discoverAssets(e=!1){return await this.discover(e)}getAssets(){return this.cache?.assets||[]}getManifest(){return this.cache?.manifest||this._getEmptyManifest()}getOptimalAsset(e,t){let n=this.getAssets().map(o=>o.path),s=t||this.options.modernFormats;for(let o of s){let a=`/${e}.${o}`;if(n.includes(a))return a}return null}async _ensureDefaultAssets(e){this.logger.debug("Ensuring default assets with modern format support...");let t=[];try{let n=await this._resolveFrameworkAssetsDir(e);if(this.logger.debug(`Framework assets directory resolved to: ${n}`),!n)return this.logger.debug("Framework assets directory not found, skipping defaults"),t;let s=this.pathResolver.resolveAppPath(le.public);this.pathResolver.pathExists(s)||(this.pathResolver.mkdir(s),this.logger.debug(`Created public directory: ${s}`));for(let o of this.options.assets)await this._ensureAsset(o,s,n)&&t.push(o);t.length>0&&this.logger.debug(`Added ${t.length} default assets from DNDev framework`)}catch(n){this.logger.debug(`Failed to ensure default assets: ${n.message}`)}return t}async _ensureAsset(e,t,n){let s=this.pathResolver.resolveAppPath(`${le.public}/${e}`);if(this.pathResolver.pathExists(s))return this.logger.debug(`Asset exists: ${e}`),!1;let o=this.pathResolver.normalizePath(`${n}/${e}`);if(this.pathResolver.pathExists(o)){if(await this.pathResolver.copy(o,s))return this.logger.debug(`Copied framework asset: ${e}`),!0;this.logger.debug(`Failed to copy framework asset: ${e}`)}return!1}_ensureFlags(e){let t=this.pathResolver.resolveFrameworkPackage("@donotdev/core");if(!t)throw new Error("Flag copy: @donotdev/core not found");let n=this.pathResolver.normalizePath(`${t}/${we.PUBLISHED_FLAGS}`),s=`${le.public}${At}`,o=[];for(let a of e){let i=ur(a),l=this.pathResolver.resolveAppPath(`${s}/${i}`);if(this.pathResolver.pathExists(l))continue;let u=`${n}/${i}`;if(!this.pathResolver.pathExists(u)){this.logger.warn(`No flag artwork for "${a}": add ${s}/${i} to the app`);continue}if(!this.pathResolver.copySync(u,l))throw new Error(`Flag copy: cannot copy ${u} to ${l}`);o.push(i)}return o}async _processAssetFiles(e){let t=[];for(let n of e)try{let s=this.pathResolver.getFileInfo(n);if(s&&s.isFile){let o=n.split("/").pop()||n.split("\\").pop(),a=this._analyzeAsset(o,s.size);a&&t.push(a)}}catch(s){this.logger.debug(`Error processing asset file ${n}: ${s.message}`)}return this.logger.debug(`Processed ${t.length} assets from ${e.length} files`),t}_analyzeAsset(e,t){let n=this._determineAssetType(e),s=this._determineAssetFormat(e);return this.options.assetPatterns.some(a=>this._matchesPattern(e,a))?{path:`/${e}`,name:e,type:n,format:s,size:t,sizeFormatted:this._formatBytes(t),isModern:this.options.modernFormats.includes(s)}:(this.logger.debug(`Asset ${e} does not match any pattern, skipping`),null)}_determineAssetType(e){let t=e.toLowerCase();if(t.includes("favicon"))return"favicon";if(t.includes("logo"))return"logo";if(t.includes("icon"))return"icon";if(t.includes("apple-touch"))return"apple-touch-icon";if(t.includes("android-chrome"))return"android-icon";if(t.includes("manifest"))return"manifest";let n=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","avif","svg"].includes(n)?"image":["woff2","woff","ttf","otf"].includes(n)?"font":["json"].includes(n)?"json":["ico"].includes(n)?"icon":"unknown"}_determineAssetFormat(e){return e.split(".").pop()?.toLowerCase()||"unknown"}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,n=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+n[s]}_matchesPattern(e,t){let n=t.split("*").map(s=>s.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${n}$`,"i").test(e)}_buildAssetManifest(e,{webAppManifest:t}){let n=e.map(o=>o.path);return{logo:{optimal:this._getOptimalAsset("logo",n,this.options.modernFormats),fallback:this._getOptimalAsset("logo",n,["png","jpg","jpeg"])},favicon:{optimal:this._getOptimalAsset("favicon",n,["svg","ico"]),fallback:this._getOptimalAsset("favicon",n,["ico"])},appleTouchIcon:this._getOptimalAsset("apple-touch-icon",n,["png"]),androidChrome:{192:this._getOptimalAsset("android-chrome-192x192",n,["png"]),512:this._getOptimalAsset("android-chrome-512x512",n,["png"])},manifest:t?dr:null,modernFormats:e.filter(o=>o.isModern).map(o=>o.path),fallbackFormats:e.filter(o=>!o.isModern).map(o=>o.path)}}_getOptimalAsset(e,t,n){for(let s of n){let o=`/${e}.${s}`;if(t.includes(o))return o}return null}async _resolveFrameworkAssetsDir(e){try{let t=this.pathResolver.getRepoRoot(),n=await this._resolvePackage("@donotdev/ui",t);if(!n)return this.logger.debug("@donotdev/ui package not found"),null;let s=this.pathResolver.normalizePath(`${n}/assets`);return this.pathResolver.pathExists(s)?(this.logger.debug(`Using framework assets from: ${s}`),s):(this.logger.debug(`Assets directory not found: ${s}`),null)}catch(t){return this.logger.debug(`Error resolving framework assets directory: ${t.message}`),null}}async _resolvePackage(e,t){try{let n=this.pathResolver.resolveFrameworkPackage(e,t);return n?(this.logger.debug(`Found package: ${n}`),n):(this.logger.debug(`Package ${e} not found`),null)}catch(n){return this.logger.debug(`Error resolving package ${e}: ${n.message}`),null}}_getEmptyManifest(){return{logo:{optimal:null,fallback:null},favicon:{optimal:null,fallback:null},appleTouchIcon:null,androidChrome:{192:null,512:null},manifest:null,modernFormats:[],fallbackFormats:[],logoSvgContent:null}}async _readLogoSvgContent(e,t){if(!e||!e.endsWith(".svg"))return null;try{let n=e.slice(1),s=this.pathResolver.resolveAppPath(`${le.public}/${n}`);return this.pathResolver.pathExists(s)&&await this.pathResolver.read(s,{format:"text"})||null}catch(n){return this.logger.debug(`Failed to read logo SVG content: ${n.message}`),null}}async _renderOgImage(e,t){let{width:n,height:s}=await e(t).metadata(),o=Math.min(be.logoWidth/n,be.logoHeight/s),a=await e(t,{density:Math.ceil(72*o)}).resize(be.logoWidth,be.logoHeight,{fit:"inside"}).png().toBuffer();return e({create:{width:be.width,height:be.height,channels:4,background:be.background}}).composite([{input:a}]).png().toBuffer()}async _generateMissingAssets(e){let t=this.pathResolver.resolveAppPath("public/logo.svg"),n=this.pathResolver.resolveAppPath("public");if(!this.pathResolver.pathExists(t))return this.logger.debug("logo.svg not found in public/, skipping asset generation"),{generated:[],skipped:[],error:"logo.svg not found in public/"};let s=[{name:"favicon.ico",size:32,format:"ico"},{name:"apple-touch-icon.png",size:180,format:"png"},{name:"icon-192x192.png",size:192,format:"png"},{name:"icon-512x512.png",size:512,format:"png"}],o=[{name:"favicon.svg",format:"svg"}],a=[],i=[];try{let l=await this.pathResolver.read(t,{format:"text"});if(!l)return{generated:[],skipped:[...o,...s].map(c=>c.name),error:"Failed to read logo.svg"};for(let c of o){let p=`${n}/${c.name}`;if(this.pathResolver.pathExists(p)){i.push(c.name);continue}try{await this.pathResolver.write(p,l),a.push(c.name)}catch(d){this.logger.debug(`Failed to copy ${c.name}: ${d.message}`),i.push(c.name)}}let u=await import("sharp").catch(()=>null);if(!u)this.logger.debug("sharp not installed, skipping PNG/ICO generation"),i.push(...s.map(c=>c.name));else{for(let p of s){let d=`${n}/${p.name}`;if(this.pathResolver.pathExists(d)){i.push(p.name);continue}try{let f=u.default(t).resize(p.size,p.size,{fit:"contain",background:{r:255,g:255,b:255,alpha:0}}),h;p.format==="ico"?h=await f.toFormat("png").toBuffer():h=await f.toFormat(p.format).toBuffer(),await this.pathResolver.write(d,h),a.push(p.name)}catch(f){this.logger.debug(`Failed to generate ${p.name}: ${f.message}`),i.push(p.name)}}let c=Ne.slice(1);if(this.pathResolver.pathExists(`${n}/${c}`))i.push(c);else try{let p=await this._renderOgImage(u.default,t);await this.pathResolver.write(`${n}/${c}`,p),a.push(c)}catch(p){this.logger.debug(`Failed to generate ${c}: ${p.message}`),i.push(c)}}return{generated:a,skipped:i,error:null}}catch(l){return this.logger.debug(`Asset generation failed: ${l.message}`),{generated:[],skipped:[...o,...s].map(u=>u.name),error:l.message}}}};var _t=class extends H{constructor(e={}){super(qe,e)}getHandlerDefaults(){return{manifestPath:L.next.assetManifest,generateManifest:!0,modernFormats:["webp","avif","png","jpg","jpeg"]}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Asset"}generateConfigContent(e){let t=e.manifest?.logoSvgContent||null;return`// Auto-generated DnDev config by @donotdev/config
|
|
80
81
|
// Generated at: ${new Date().toISOString()}
|
|
81
82
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
82
83
|
|
|
@@ -93,7 +94,7 @@ if (typeof globalThis !== 'undefined') {
|
|
|
93
94
|
timestamp: Date.now(),
|
|
94
95
|
};
|
|
95
96
|
}
|
|
96
|
-
globalThis._DNDEV_CONFIG_.${
|
|
97
|
+
globalThis._DNDEV_CONFIG_.${Y.assets} = {
|
|
97
98
|
mapping: assetConfig.manifest,
|
|
98
99
|
logoSvgContent: ${JSON.stringify(t)},
|
|
99
100
|
manifest: {
|
|
@@ -105,15 +106,15 @@ if (typeof globalThis !== 'undefined') {
|
|
|
105
106
|
|
|
106
107
|
// Export for compatibility
|
|
107
108
|
export default assetConfig;
|
|
108
|
-
`}logDiscoveryResults(e){let t=e.assets?.length||0,
|
|
109
|
-
path: '${
|
|
110
|
-
type: '${
|
|
111
|
-
format: '${
|
|
112
|
-
size: ${
|
|
113
|
-
optimized: ${
|
|
109
|
+
`}logDiscoveryResults(e){let t=e.assets?.length||0,n=e.generatedAssets?.length||0;n>0?this.logger.info(`\u{1F3AF} Assets: ${t} found, ${n} generated`):this.logger.info(`\u{1F3AF} Assets: ${t} found`)}useFlagCodes(e,t){this.discovery.useFlagCodes(e,t)}async getDiscoveryData(){return await this.discovery.discoverAssets()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/assets",destination:"/api/assets/asset"}],fallback:[]}}createManifestContent(e){return{assets:e.assets.map(t=>({path:t.path,type:t.type,format:t.format,size:t.size,optimized:t.optimized})),manifest:e.manifest,copiedAssets:e.copiedAssets,source:e.source,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} assets, ${e.copiedAssets.length} copied from framework`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateAssetManifest(e)}async generateAssetManifest(e){let t=this.generateAssetManifestContent(e);this.writeGeneratedFile("src/app/assets.generated.ts",t,"asset manifest")}generateAssetManifestContent(e){let t=e.assets.map(o=>` {
|
|
110
|
+
path: '${o.path}',
|
|
111
|
+
type: '${o.type}',
|
|
112
|
+
format: '${o.format}',
|
|
113
|
+
size: ${o.size},
|
|
114
|
+
optimized: ${o.optimized||!1}
|
|
114
115
|
}`).join(`,
|
|
115
|
-
`),
|
|
116
|
-
`),
|
|
116
|
+
`),n=Object.entries(e.manifest).map(([o,a])=>` ${o}: ${JSON.stringify(a)}`).join(`,
|
|
117
|
+
`),s=e.manifest.logoSvgContent||null;return`// Auto-generated asset manifest by @donotdev/config
|
|
117
118
|
// Generated at ${new Date().toISOString()}
|
|
118
119
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
119
120
|
|
|
@@ -122,7 +123,7 @@ ${t}
|
|
|
122
123
|
];
|
|
123
124
|
|
|
124
125
|
export const assetManifest = {
|
|
125
|
-
${
|
|
126
|
+
${n}
|
|
126
127
|
};
|
|
127
128
|
|
|
128
129
|
export const copiedAssets = ${JSON.stringify(e.copiedAssets,null,2)};
|
|
@@ -135,41 +136,24 @@ export const assetStats = {
|
|
|
135
136
|
};
|
|
136
137
|
|
|
137
138
|
export default assets;
|
|
138
|
-
`}
|
|
139
|
-
src: '${s.path}',
|
|
140
|
-
alt: '${r}',
|
|
141
|
-
width: ${s.width||"auto"},
|
|
142
|
-
height: ${s.height||"auto"},
|
|
143
|
-
priority: false
|
|
144
|
-
}`}).join(`,
|
|
145
|
-
`);return`// Auto-generated image optimization config by @donotdev/config
|
|
146
|
-
// Generated at ${new Date().toISOString()}
|
|
147
|
-
|
|
148
|
-
export const imageConfigs = {
|
|
149
|
-
${t}
|
|
150
|
-
};
|
|
151
|
-
|
|
152
|
-
export const imageAssets = ${JSON.stringify(e.map(s=>s.path),null,2)};
|
|
153
|
-
|
|
154
|
-
export default imageConfigs;
|
|
155
|
-
`}};function bs(o={}){return new st(o)}import nt from"node:fs";import En from"node:path";var ot=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!nt.existsSync(e))return{blogDir:e,files:[]};let t;try{t=nt.readdirSync(e)}catch{return{blogDir:e,files:[]}}let s=t.filter(r=>r.endsWith(".md")&&!r.startsWith(".")).sort();return{blogDir:e,files:s}}},at=class extends G{constructor(e={}){super(ot,e)}getHandlerDefaults(){return{outputPath:F.next.blogContent}}getHandlerName(){return"BlogContent"}createDiscovery(e){return new e(this.pathResolver)}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateSpecificFiles(e),this.logger.debug(`Generated BlogContent: ${this.getGenerationSummary(e)}`),e}catch(e){return this.logger.debug(`BlogContent generation failed (non-critical): ${e.message}`),{blogDir:"",files:[]}}}async getDiscoveryData(){return this.discovery.discoverBlogFiles()}logDiscoveryResults(e){this.logger.info(`\u{1F4DD} Blog: ${e.files.length} .md file(s) found`)}getGenerationSummary(e){return`${e.files.length} blog file(s)`}async generateSpecificFiles(e){let{blogDir:t,files:s}=e;if(s.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let r=this._buildGeneratedContent(t,s);this.writeGeneratedFile(this.options.outputPath,r,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
139
|
+
`}};function fr(r={}){return new _t(r)}import kt from"node:fs";import ua from"node:path";var Dt=class{constructor(e){this.pathResolver=e}discoverBlogFiles(){let e=this.pathResolver.resolveAppPath("src/content/blog");if(!kt.existsSync(e))return{blogDir:e,files:[]};let t;try{t=kt.readdirSync(e)}catch{return{blogDir:e,files:[]}}let n=t.filter(s=>s.endsWith(".md")&&!s.startsWith(".")).sort();return{blogDir:e,files:n}}},Tt=class extends H{constructor(e={}){super(Dt,e)}getHandlerDefaults(){return{outputPath:L.next.blogContent}}getHandlerName(){return"BlogContent"}createDiscovery(e){return new e(this.pathResolver)}async generateFiles(){try{let e=await this.getDiscoveryData();return this.options.verbose&&this.logDiscoveryResults(e),await this.generateSpecificFiles(e),this.logger.debug(`Generated BlogContent: ${this.getGenerationSummary(e)}`),e}catch(e){return this.logger.debug(`BlogContent generation failed (non-critical): ${e.message}`),{blogDir:"",files:[]}}}async getDiscoveryData(){return this.discovery.discoverBlogFiles()}logDiscoveryResults(e){this.logger.info(`\u{1F4DD} Blog: ${e.files.length} .md file(s) found`)}getGenerationSummary(e){return`${e.files.length} blog file(s)`}async generateSpecificFiles(e){let{blogDir:t,files:n}=e;if(n.length===0){this.logger.debug("No .md files in src/content/blog/ \u2014 skipping blog-content.generated.ts");return}let s=this._buildGeneratedContent(t,n);this.writeGeneratedFile(this.options.outputPath,s,"blog content manifest")}_buildGeneratedContent(e,t){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
156
140
|
// Regenerated when src/content/blog/*.md files change
|
|
157
141
|
|
|
158
142
|
const blogContent: Record<string, string> = {
|
|
159
|
-
${t.map(
|
|
143
|
+
${t.map(s=>{let o=kt.readFileSync(ua.join(e,s),"utf8");return` './${s}': ${JSON.stringify(o)},`}).join(`
|
|
160
144
|
`)}
|
|
161
145
|
};
|
|
162
146
|
|
|
163
147
|
export default blogContent;
|
|
164
|
-
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return e}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function ws(o={}){return new at(o)}function xn(o){if(!o)return[];let e=$.getInstance(),t=new Set;try{let s=e.resolvePackage("@donotdev/core",o);if(!s)return[];let r=e.getDirname(e.getDirname(s)),n;try{n=e.readdirSync(r)}catch{return[]}for(let a of n)try{let i=e.resolvePath(`${a}/package.json`,r),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[p,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(p)}catch{}}catch{}return Array.from(t)}function An(o){if(!o)return[];let e=$.getInstance();try{let t=e.resolvePath("package.json",o),s=e.readSync(t,{format:"json"});if(!s)return[];let r=new Set;if(s.peerDependenciesMeta)for(let[n,a]of Object.entries(s.peerDependenciesMeta))a?.optional&&r.add(n);if(s.optionalDependencies)for(let n of Object.keys(s.optionalDependencies))r.add(n);return Array.from(r)}catch{return[]}}function _n(o){let e=ke.optionalFeatures||[],t=xn(o),s=An(o);return[...new Set([...e,...t,...s])]}function kn(o){let e=$.getInstance();try{let t=e.resolvePath("package.json",o),s=e.readSync(t,{format:"json"});return s?new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.devDependencies||{})]):new Set}catch{return new Set}}function Nn(o,e,t){if(t.resolvePackage(o,e||void 0))return!0;let s=o.startsWith("@")?o.split("/").slice(0,2).join("/"):o.split("/")[0],r=e;for(let n=0;n<10;n++){let a=t.resolvePath(`node_modules/${s}`,r);if(t.pathExists(a))return!0;let i=t.getDirname(r);if(i===r)break;r=i}return!1}function Te(o){let e=_n(o),t=[],s=[],r=$.getInstance(),n=kn(o);for(let a of e)a.startsWith("@donotdev/")?n.has(a)?s.push(a):t.push(a):n.has(a)&&Nn(a,o,r)?s.push(a):t.push(a);return{missing:t,installed:s}}var De=class o extends X{static LANGUAGE_FLAG_OVERRIDES={en:"gb","en-ca":"ca","es-ar":"ar","fr-be":"be",ar:"sa","ar-ma":"ma","ar-dz":"dz","ar-tn":"tn","ar-ly":"ly","ar-mr":"mr",hi:"in",sl:"si",uk:"ua",ga:"ie",gd:"gb-sct",br:"bzh",co:"fr-cor",am:"et",bn:"bd",gu:"in",kn:"in",ml:"in",mr:"in",ne:"np",pa:"pk",ta:"in",te:"in",ur:"pk",fa:"ir",kk:"kz",ky:"kg",tg:"tj",my:"mm",km:"kh",lo:"la",ka:"ge",hy:"am",be:"by",bs:"ba",sq:"al",ms:"my"};constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[s,r]of Object.entries(e)){for(let n of Object.keys(r))t.includes(n)||delete r[n];Object.keys(r).length===0&&delete e[s]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=this.pathResolver.getRepoRoot();if(!t||t===s)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${s})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${s}`);let r=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${r.eager.length}, lazy: ${r.lazy.length}, framework eager: ${r.framework?.eager?.length||0}, framework lazy: ${r.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let n=Ne("i18n"),a=r.eager||[],i=r.lazy||[],l=(this.options.additionalPaths||[]).map(b=>{let S=b.endsWith(".json")?b:`${b}/*_*.json`;return this.pathResolver.resolveAppPath(S)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let p=r.framework?.eager||[],c=r.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${p.join(", ")}, framework lazy: ${c.join(", ")}`),p.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let u=this.pathResolver.normalizePath(t),h=this.pathResolver.normalizePath(s),g=(b,S)=>{let P=this.pathResolver.normalizePath(b),C=this.pathResolver.normalizePath(S);return P.startsWith(C)?P.slice(C.length+1):P},d=a.map(b=>g(b,t)),w=[...i,...l].map(b=>g(b,t)),y=p.map(b=>g(b,s)),A=c.map(b=>g(b,s)),m={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},E=await this.pathResolver._globWithNormalization(d,m),O=await this.pathResolver._globWithNormalization(w,m),k={...n,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:s,ignore:n.ignore?.filter(b=>b!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${s}, ignore: ${JSON.stringify(k.ignore)}`);let D=await this.pathResolver._globWithNormalization(y,k),T=await this.pathResolver._globWithNormalization(A,k);this.logger.debug(`Found ${E.length} eager, ${O.length} lazy, ${D.length} framework eager, ${T.length} framework lazy files`),D.length>0?this.logger.debug(`Framework eager files (first 3): ${D.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${p.join(", ")}`),T.length>0?this.logger.debug(`Framework lazy files (first 3): ${T.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let re=[...new Set([...E,...O,...D,...T])],ee=new Set([...E,...D]),v={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:ne}=Te(t),x=new Set(ne.filter(b=>b.startsWith("@donotdev/")).map(b=>b.replace("@donotdev/","")));x.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...x].join(", ")}] (packages not installed)`);let K=new Map,M=[...D,...T];for(let b of M){let S=this._processTranslationFile(b,D.includes(b),t);if(S){if(x.has(S.namespace))continue;let P=`${S.namespace}_${S.language}`;K.set(P,S),v.allNamespaces.add(S.namespace),v.supportedLanguages.add(S.language),D.includes(b)&&v.eagerNamespaces.add(S.namespace)}}let j=new Set;for(let b of re){if(M.includes(b))continue;let S=this._processTranslationFile(b,ee.has(b),t);if(S){let{namespace:P,language:C,importPath:z,content:Be}=S,Ae=`${S.namespace}_${S.language}`;if(K.has(Ae)){let ze=K.get(Ae);S.content=this._mergeTranslations(ze.content,Be)}v.allNamespaces.add(P),v.supportedLanguages.add(C),j.add(C),ee.has(b)&&v.eagerNamespaces.add(P),v.mapping[P]||(v.mapping[P]={}),v.mapping[P][C]=z,S.content&&(v.content[P]||(v.content[P]={}),v.content[P][C]=S.content),v.files.push({path:b,relativePath:this.pathResolver.getRelativePath(b),namespace:P,language:C,eager:ee.has(b),size:S.content?JSON.stringify(S.content).length:0})}}for(let[b,S]of K){let P=b.lastIndexOf("_"),C=b.slice(0,P),z=b.slice(P+1);j.size>0&&!j.has(z)||(!v.mapping[C]||!v.mapping[C][z])&&(v.mapping[C]||(v.mapping[C]={}),v.mapping[C][z]=S.importPath,v.content[C]||(v.content[C]={}),v.content[C][z]=S.content,v.files.push({path:S.absolutePath,relativePath:this.pathResolver.getRelativePath(S.absolutePath),namespace:C,language:z,eager:v.eagerNamespaces.has(C),size:S.content?JSON.stringify(S.content).length:0}))}let q=j.size>0?[...j].sort():[this.options.fallbackLanguage],N=this._getLanguageAllowlist(),_=q;if(N){let b=q.filter(P=>N.includes(P));_=b.length>0?b:[this.options.fallbackLanguage],this._restrictByLanguage(v.mapping,_),this._restrictByLanguage(v.content,_),v.files=v.files.filter(P=>_.includes(P.language));let S=new Set(Object.keys(v.mapping));v.allNamespaces=new Set([...v.allNamespaces].filter(P=>S.has(P))),v.eagerNamespaces=new Set([...v.eagerNamespaces].filter(P=>S.has(P))),this.logger.debug(`I18n restricted by i18n.only [${N.join(", ")}]: languages [${_.join(", ")}], namespaces ${S.size}`)}let te=[...new Set(_.map(b=>o.LANGUAGE_FLAG_OVERRIDES[b]||b))];return{mapping:v.mapping,content:v.content,eagerNamespaces:[...v.eagerNamespaces].sort(),allNamespaces:[...v.allNamespaces].sort(),supportedLanguages:_,fallbackLanguage:this.options.fallbackLanguage,flagCodes:te,files:v.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[o.LANGUAGE_FLAG_OVERRIDES[this.options.fallbackLanguage]||this.options.fallbackLanguage],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let s=await this._processFiles([]);this.cache={...s,timestamp:Date.now()};let r=Date.now()-t;return this.logger.debug(`Discovery completed in ${r}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(s){throw this.logger.error(`I18n discovery failed: ${s.message}`),s}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,s){let r=e.split("/").pop()||e.split("\\").pop()||"",n,a,i=r.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${r}`),null;if([,n,a]=i,!n||!a)return this.logger.debug(`Invalid namespace or language in file: ${r}`),null;let p="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(u){return this.logger.debug(`Error parsing JSON from ${e}: ${u.message}`),null}return{namespace:n,language:a,importPath:p,absolutePath:e,content:c}}_mergeTranslations(e,t){let s={...e};for(let[r,n]of Object.entries(t))typeof n=="object"&&n!==null&&!Array.isArray(n)?s[r]=this._mergeTranslations(s[r]||{},n):s[r]=n;return s}};var it=class extends G{constructor(e={}){super(De,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...Se.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],s=Object.keys(e.mapping||{}).filter(r=>r!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${s} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}formatAPIResponse(e){return{mapping:e.mapping,languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,timestamp:e.timestamp}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},s=t.totalNamespaces||0,r=t.totalLanguages||0;return`${s} namespaces, ${r} languages`}async generateSpecificFiles(e){this.options.generateManifest&&await this.generateManifest(e),await this.generateAPIHandler(e)}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:s,eagerNamespaces:r,fallbackLanguage:n,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
148
|
+
`}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}createManifestContent(e){return{files:e.files,generatedAt:new Date().toISOString()}}};function hr(r={}){return new Tt(r)}function pa(r){if(!r)return[];let e=D.getInstance(),t=new Set;try{let n=e.resolvePackage("@donotdev/core",r);if(!n)return[];let s=e.getDirname(e.getDirname(n)),o;try{o=e.readdirSync(s)}catch{return[]}for(let a of o)try{let i=e.resolvePath(`${a}/package.json`,s),l=e.readSync(i,{format:"json"});if(!l?.peerDependenciesMeta)continue;for(let[u,c]of Object.entries(l.peerDependenciesMeta))c?.optional&&t.add(u)}catch{}}catch{}return Array.from(t)}function da(r){if(!r)return[];let e=D.getInstance();try{let t=e.resolvePath("package.json",r),n=e.readSync(t,{format:"json"});if(!n)return[];let s=new Set;if(n.peerDependenciesMeta)for(let[o,a]of Object.entries(n.peerDependenciesMeta))a?.optional&&s.add(o);if(n.optionalDependencies)for(let o of Object.keys(n.optionalDependencies))s.add(o);return Array.from(s)}catch{return[]}}function fa(r){let e=Le.optionalFeatures||[],t=pa(r),n=da(r);return[...new Set([...e,...t,...n])]}function ha(r){let e=D.getInstance();try{let t=e.resolvePath("package.json",r),n=e.readSync(t,{format:"json"});return n?new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{})]):new Set}catch{return new Set}}function ga(r,e,t){let n=new Set,s=t.resolvePackage("@donotdev/core",r);if(!s)return n;let o=t.getDirname(t.getDirname(s));for(let a of e){if(!a.startsWith("@donotdev/"))continue;let i=t.resolvePath(`${a.slice(10)}/package.json`,o);if(!t.pathExists(i))continue;let l=t.readSync(i,{format:"json"});for(let u of Object.keys(l?.dependencies||{}))n.add(u)}return n}function ma(r,e,t){if(t.resolvePackage(r,e||void 0))return!0;let n=r.startsWith("@")?r.split("/").slice(0,2).join("/"):r.split("/")[0],s=e;for(let o=0;o<10;o++){let a=t.resolvePath(`node_modules/${n}`,s);if(t.pathExists(a))return!0;let i=t.getDirname(s);if(i===s)break;s=i}return!1}function Je(r){let e=fa(r),t=[],n=[],s=D.getInstance(),o=ha(r),a=ga(r,o,s);for(let i of e)i.startsWith("@donotdev/")?o.has(i)?n.push(i):t.push(i):(o.has(i)||a.has(i))&&ma(i,r,s)?n.push(i):t.push(i);return{missing:t,installed:n}}var Ve=class extends ee{constructor(e,t={}){super(e,{fallbackLanguage:"en",additionalPaths:[],only:null,...t})}_getLanguageAllowlist(){let e=this.options.only;return Array.isArray(e)&&e.length>0?e:null}_restrictByLanguage(e,t){for(let[n,s]of Object.entries(e)){for(let o of Object.keys(s))t.includes(o)||delete s[o];Object.keys(s).length===0&&delete e[n]}}_getDiscoveryType(){return"I18n"}async _getPatterns(){return await this.pathResolver.resolvePatterns("i18n")}_getPatternType(){return"i18n"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),n=this.pathResolver.getRepoRoot();if(!t||t===n)throw this.logger.error(`I18n discovery: appRoot not properly set (appRoot: ${t}, repoRoot: ${n})`),new Error("App root not set before i18n discovery. Ensure configResolved hook has run.");this.logger.debug(`I18n discovery: appRoot=${t}, repoRoot=${n}`);let s=await this._getPatterns();this.logger.debug(`I18n patterns - eager: ${s.eager.length}, lazy: ${s.lazy.length}, framework eager: ${s.framework?.eager?.length||0}, framework lazy: ${s.framework?.lazy?.length||0}`),this.logger.debug(`isMonorepo: ${this.pathResolver.isMonorepo()}, repoRoot: ${this.pathResolver.getRepoRoot()}`);let o=Me("i18n"),a=s.eager||[],i=s.lazy||[],l=(this.options.additionalPaths||[]).map(w=>{let E=w.endsWith(".json")?w:`${w}/*_*.json`;return this.pathResolver.resolveAppPath(E)});l.length>0&&this.logger.debug(`Additional i18n paths configured: ${l.join(", ")}`);let u=s.framework?.eager||[],c=s.framework?.lazy||[];this.logger.debug(`Resolved patterns - eager: ${a.join(", ")}, lazy: ${i.join(", ")}, framework eager: ${u.join(", ")}, framework lazy: ${c.join(", ")}`),u.length===0&&c.length===0&&this.logger.error(`\u26A0\uFE0F Framework i18n patterns are EMPTY! isMonorepo=${this.pathResolver.isMonorepo()}, repoRoot=${this.pathResolver.getRepoRoot()}`);let p=this.pathResolver.normalizePath(t),d=this.pathResolver.normalizePath(n),f=(w,E)=>{let P=this.pathResolver.normalizePath(w),I=this.pathResolver.normalizePath(E);return P.startsWith(I)?P.slice(I.length+1):P},h=a.map(w=>f(w,t)),y=[...i,...l].map(w=>f(w,t)),S=u.map(w=>f(w,n)),T=c.map(w=>f(w,n)),R={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:t},v=await this.pathResolver._globWithNormalization(h,R),x=await this.pathResolver._globWithNormalization(y,R),O={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:n,ignore:o.ignore?.filter(w=>w!=="**/node_modules/**")||[]};this.logger.debug(`\u{1F50D} Searching framework patterns with cwd: ${n}, ignore: ${JSON.stringify(O.ignore)}`);let B=await this.pathResolver._globWithNormalization(S,O),M=await this.pathResolver._globWithNormalization(T,O);this.logger.debug(`Found ${v.length} eager, ${x.length} lazy, ${B.length} framework eager, ${M.length} framework lazy files`),B.length>0?this.logger.debug(`Framework eager files (first 3): ${B.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework eager files found! Patterns were: ${u.join(", ")}`),M.length>0?this.logger.debug(`Framework lazy files (first 3): ${M.slice(0,3).join(", ")}`):this.logger.error(`\u274C NO framework lazy files found! Patterns were: ${c.join(", ")}`);let te=[...new Set([...v,...x,...B,...M])],W=new Set([...v,...B]),g={mapping:{},content:{},eagerNamespaces:new Set,allNamespaces:new Set,supportedLanguages:new Set,files:[]},{missing:b}=Je(t),k=new Set(b.filter(w=>w.startsWith("@donotdev/")).map(w=>w.replace("@donotdev/","")));k.size>0&&this.logger.debug(`I18n namespace filter: excluding [${[...k].join(", ")}] (packages not installed)`);let N=new Map,_=[...B,...M];for(let w of _){let E=this._processTranslationFile(w,B.includes(w),t);if(E){if(k.has(E.namespace))continue;let P=`${E.namespace}_${E.language}`;N.set(P,E),g.allNamespaces.add(E.namespace),g.supportedLanguages.add(E.language),B.includes(w)&&g.eagerNamespaces.add(E.namespace)}}let F=new Set;for(let w of te){if(_.includes(w))continue;let E=this._processTranslationFile(w,W.has(w),t);if(E){let{namespace:P,language:I,importPath:V,content:ge}=E,de=`${E.namespace}_${E.language}`;if(N.has(de)){let me=N.get(de);E.content=this._mergeTranslations(me.content,ge)}g.allNamespaces.add(P),g.supportedLanguages.add(I),F.add(I),W.has(w)&&g.eagerNamespaces.add(P),g.mapping[P]||(g.mapping[P]={}),g.mapping[P][I]=V,E.content&&(g.content[P]||(g.content[P]={}),g.content[P][I]=E.content),g.files.push({path:w,relativePath:this.pathResolver.getRelativePath(w),namespace:P,language:I,eager:W.has(w),size:E.content?JSON.stringify(E.content).length:0})}}for(let[w,E]of N){let P=w.lastIndexOf("_"),I=w.slice(0,P),V=w.slice(P+1);F.size>0&&!F.has(V)||(!g.mapping[I]||!g.mapping[I][V])&&(g.mapping[I]||(g.mapping[I]={}),g.mapping[I][V]=E.importPath,g.content[I]||(g.content[I]={}),g.content[I][V]=E.content,g.files.push({path:E.absolutePath,relativePath:this.pathResolver.getRelativePath(E.absolutePath),namespace:I,language:V,eager:g.eagerNamespaces.has(I),size:E.content?JSON.stringify(E.content).length:0}))}let A=F.size>0?[...F].sort():[this.options.fallbackLanguage],G=this._getLanguageAllowlist(),j=A;if(G){let w=A.filter(P=>G.includes(P));j=w.length>0?w:[this.options.fallbackLanguage],this._restrictByLanguage(g.mapping,j),this._restrictByLanguage(g.content,j),g.files=g.files.filter(P=>j.includes(P.language));let E=new Set(Object.keys(g.mapping));g.allNamespaces=new Set([...g.allNamespaces].filter(P=>E.has(P))),g.eagerNamespaces=new Set([...g.eagerNamespaces].filter(P=>E.has(P))),this.logger.debug(`I18n restricted by i18n.only [${G.join(", ")}]: languages [${j.join(", ")}], namespaces ${E.size}`)}let re=[...new Set(j.map(Nt))];return{mapping:g.mapping,content:g.content,eagerNamespaces:[...g.eagerNamespaces].sort(),allNamespaces:[...g.allNamespaces].sort(),supportedLanguages:j,fallbackLanguage:this.options.fallbackLanguage,flagCodes:re,files:g.files}}_getEmptyResult(){return{mapping:{},content:{},eagerNamespaces:[],allNamespaces:["common"],supportedLanguages:[this.options.fallbackLanguage],fallbackLanguage:this.options.fallbackLanguage,flagCodes:[Nt(this.options.fallbackLanguage)],files:[],timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.allNamespaces?.length||0} namespaces, ${this.cache?.supportedLanguages?.length||0} languages`}async discover(e=!1){if(!e&&this._isCacheValid())return this.logger.debug("Using cached results"),this.cache;let t=Date.now();try{let n=await this._processFiles([]);this.cache={...n,timestamp:Date.now()};let s=Date.now()-t;return this.logger.debug(`Discovery completed in ${s}ms`),this._lastDiscoveryTime=Date.now(),this.cache}catch(n){throw this.logger.error(`I18n discovery failed: ${n.message}`),n}}async discoverTranslations(e=!1){return await this.discover(e)}getMapping(){return this.cache?.mapping||{}}getLanguages(){return this.cache?.supportedLanguages||[this.options.fallbackLanguage]}getNamespaces(){return this.cache?.allNamespaces||["common"]}getEagerNamespaces(){return this.cache?.eagerNamespaces||[]}_processTranslationFile(e,t,n){let s=e.split("/").pop()||e.split("\\").pop()||"",o,a,i=s.match(/^(.+)_([^_.]+)\.json$/);if(!i)return this.logger.debug(`Invalid translation file name format: ${s}`),null;if([,o,a]=i,!o||!a)return this.logger.debug(`Invalid namespace or language in file: ${s}`),null;let u="./"+this.pathResolver.getRelativePath(e).replace(/\\/g,"/"),c;try{if(c=this.pathResolver.readSync(e,{format:"json"}),!c)return this.logger.debug(`Could not read file: ${e}`),null}catch(p){return this.logger.debug(`Error parsing JSON from ${e}: ${p.message}`),null}return{namespace:o,language:a,importPath:u,absolutePath:e,content:c}}_mergeTranslations(e,t){let n={...e};for(let[s,o]of Object.entries(t))typeof o=="object"&&o!==null&&!Array.isArray(o)?n[s]=this._mergeTranslations(n[s]||{},o):n[s]=o;return n}};var Ot=class extends H{constructor(e={}){super(Ve,e)}getHandlerDefaults(){return{generateI18nProvider:!1,generateTranslationHooks:!1,manifestPath:"public/i18n-manifest.json",fallbackLanguage:"en"}}createDiscovery(e){let t={...De.discovery,...this.options,fallbackLanguage:this.options.fallbackLanguage};return new e(this.pathResolver,t)}getHandlerName(){return"I18n"}logDiscoveryResults(e){let t=e.supportedLanguages||[],n=Object.keys(e.mapping||{}).filter(s=>s!=="default").length||0;this.logger.info(`\u{1F310} I18n: ${t.length} languages, ${n} namespaces`)}async getDiscoveryData(){return await this.discovery.discoverTranslations()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/i18n",destination:"/api/i18n/route"},{source:"/api/translations/:namespace/:language",destination:"/api/translations/[namespace]/[language]/route"}],fallback:[]}}createManifestContent(e){return{languages:e.supportedLanguages,namespaces:e.allNamespaces,eagerNamespaces:e.eagerNamespaces,fallbackLanguage:e.fallbackLanguage,stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){let t=e.stats||{},n=t.totalNamespaces||0,s=t.totalLanguages||0;return`${n} namespaces, ${s} languages`}async generateSpecificFiles(){}async generateI18n(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{mapping:t,supportedLanguages:n,eagerNamespaces:s,fallbackLanguage:o,content:a}=e;return`// Auto-generated DnDev config by @donotdev/config
|
|
165
149
|
// Generated at: ${new Date().toISOString()}
|
|
166
150
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
167
151
|
|
|
168
152
|
const i18nConfig = {
|
|
169
153
|
mapping: ${JSON.stringify(t,null,2)},
|
|
170
|
-
languages: ${JSON.stringify(
|
|
171
|
-
eager: ${JSON.stringify(
|
|
172
|
-
fallback: '${
|
|
154
|
+
languages: ${JSON.stringify(n,null,2)},
|
|
155
|
+
eager: ${JSON.stringify(s,null,2)},
|
|
156
|
+
fallback: '${o}',
|
|
173
157
|
content: ${JSON.stringify(a||{},null,2)},
|
|
174
158
|
storage: {
|
|
175
159
|
type: 'localStorage',
|
|
@@ -185,8 +169,8 @@ const i18nConfig = {
|
|
|
185
169
|
manifest: {
|
|
186
170
|
totalFiles: ${Object.keys(t).length},
|
|
187
171
|
totalNamespaces: ${Object.keys(t).length},
|
|
188
|
-
totalLanguages: ${
|
|
189
|
-
eagerNamespaces: ${
|
|
172
|
+
totalLanguages: ${n.length},
|
|
173
|
+
eagerNamespaces: ${s.length},
|
|
190
174
|
generatedAt: new Date().toISOString(),
|
|
191
175
|
},
|
|
192
176
|
debug: ${this.options.debug},
|
|
@@ -203,12 +187,12 @@ if (typeof globalThis !== 'undefined') {
|
|
|
203
187
|
timestamp: Date.now(),
|
|
204
188
|
};
|
|
205
189
|
}
|
|
206
|
-
globalThis._DNDEV_CONFIG_.${
|
|
190
|
+
globalThis._DNDEV_CONFIG_.${Y.i18n} = i18nConfig;
|
|
207
191
|
}
|
|
208
192
|
|
|
209
193
|
// Export for compatibility
|
|
210
194
|
export default i18nConfig;
|
|
211
|
-
`}};function
|
|
195
|
+
`}};function gr(r={}){return new Ot(r)}var Ke=class extends ee{constructor(e,t={}){super(e,{...t})}_getDiscoveryType(){return"PWA"}async _getPatterns(){return await this.pathResolver.resolvePatterns("pwa")}_getPatternType(){return"pwa"}async _processFiles(e){let{frameworkFiles:t,consumerFiles:n}=e,s=[...t,...n];this.logger.debug(`Processing ${s.length} PWA files`);let o=await this._analyzePWAFiles(s),a=[...o.filter(l=>l.type==="manifest"||l.type==="service-worker"),...o.filter(l=>l.type==="icon")],i=this._generatePWAManifest(a);return{assets:a,manifest:i,totalFiles:s.length,timestamp:Date.now()}}_getEmptyResult(){return{assets:[],manifest:this._getDefaultManifest(),totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.assets?.length||0} PWA assets discovered`}async _analyzePWAFiles(e){let t=[];for(let n of e){let s=typeof n=="string"?{absolutePath:n,relativePath:this.pathResolver.getRelativePath(n),fileName:n.split("/").pop()||"",extension:(n.split(".").pop()||"").toLowerCase()}:n,o=await this._analyzePWAAsset(s);o&&t.push(o)}return t}async _analyzePWAAsset(e){let t=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!t)return null;let n=e.relativePath,s=e.fileName;return s==="manifest.json"?this._parseManifestFile(t,n):s.includes("service-worker")||s.includes("sw.")?this._parseServiceWorkerFile(t,n):this._isPWAIcon(s)?this._parseIconFile(e,n):null}_parseManifestFile(e,t){try{let n=typeof e=="string"?JSON.parse(e):e;return{type:"manifest",path:t,content:n,size:typeof e=="string"?e.length:JSON.stringify(n).length}}catch(n){return this.logger.debug(`Failed to parse manifest: ${n.message}`),null}}_parseServiceWorkerFile(e,t){return{type:"service-worker",path:t,size:e.length,hasWorkbox:e.includes("workbox")}}_parseIconFile(e,t){let n=e.fileName,s=this._extractIconSize(n);return{type:"icon",path:t,size:s,format:e.extension,purpose:this._getIconPurpose(n)}}_isPWAIcon(e){return["icon","logo","apple-touch-icon","android-chrome","favicon"].some(n=>e.includes(n))}_extractIconSize(e){let t=e.match(/(\d+)x(\d+)/);return t?{width:parseInt(t[1]),height:parseInt(t[2])}:e.includes("favicon")?{width:32,height:32}:e.includes("apple-touch-icon")?{width:180,height:180}:e.includes("icon-192")?{width:192,height:192}:e.includes("icon-512")?{width:512,height:512}:{width:192,height:192}}_getIconPurpose(e){return e.includes("maskable")?"maskable":e.includes("apple-touch")?"apple-touch":e.includes("android-chrome")?"android":"any"}_generatePWAManifest(e){let t=e.filter(s=>s.type==="icon"),n=this._getDefaultManifest();return t.length>0&&(n.icons=t.map(s=>this.toManifestIcon(s))),n}toManifestIcon(e){let t={ico:"image/x-icon",svg:"image/svg+xml",jpg:"image/jpeg",jpeg:"image/jpeg"},n=(e.format||"").toLowerCase();return{src:`/${e.path.replace(/^\/?public\//,"")}`,sizes:n==="svg"?"any":`${e.size.width}x${e.size.height}`,type:t[n]||`image/${n}`,purpose:e.purpose==="maskable"?"maskable":"any"}}_getDefaultManifest(){let e=this.options?.app||{};return{name:e.name,short_name:e.shortName,description:e.description,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:"#000000",icons:[]}}generateManifestContent(e){let t=e.manifest||this._getDefaultManifest();return JSON.stringify(t,null,2)}generateServiceWorkerContent(e,t={}){let n=this._getWorkboxDefaults(t),s=t.backgroundSync!==!1&&t.backgroundSync,o=t.precacheManifest||[],a=JSON.stringify(o,null,2);return`// Generated by @donotdev/config - PWA Service Worker with Workbox
|
|
212
196
|
// Generated at ${new Date().toISOString()}
|
|
213
197
|
|
|
214
198
|
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.0.0/workbox-sw.js');
|
|
@@ -218,7 +202,7 @@ const { registerRoute } = workbox.routing;
|
|
|
218
202
|
const { CacheFirst, NetworkFirst, StaleWhileRevalidate } = workbox.strategies;
|
|
219
203
|
const { ExpirationPlugin } = workbox.expiration;
|
|
220
204
|
const { CacheableResponsePlugin } = workbox.cacheableResponse;
|
|
221
|
-
${
|
|
205
|
+
${s?"const { BackgroundSyncPlugin } = workbox.backgroundSync;":""}
|
|
222
206
|
|
|
223
207
|
// Clean up outdated caches
|
|
224
208
|
cleanupOutdatedPrecaches();
|
|
@@ -228,9 +212,9 @@ const precacheManifest = ${a.length>2?a:"self.__WB_MANIFEST || []"};
|
|
|
228
212
|
precacheAndRoute(precacheManifest);
|
|
229
213
|
|
|
230
214
|
// Runtime caching strategies
|
|
231
|
-
${this._generateWorkboxRuntimeCaching(
|
|
215
|
+
${this._generateWorkboxRuntimeCaching(n.runtimeCaching,t)}
|
|
232
216
|
|
|
233
|
-
${
|
|
217
|
+
${s?this._generateBackgroundSync(t.backgroundSync):""}
|
|
234
218
|
|
|
235
219
|
// Skip waiting and claim clients
|
|
236
220
|
self.addEventListener('message', (event) => {
|
|
@@ -242,101 +226,41 @@ self.addEventListener('message', (event) => {
|
|
|
242
226
|
self.addEventListener('activate', (event) => {
|
|
243
227
|
event.waitUntil(self.clients.claim());
|
|
244
228
|
});
|
|
245
|
-
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((s
|
|
229
|
+
`}_getWorkboxDefaults(e={}){return{globPatterns:e.globPatterns||["**/*.{js,css,html,ico,png,svg,woff2}"],runtimeCaching:e.runtimeCaching||[{urlPattern:/^https:\/\/fonts\.googleapis\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"google-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/^https:\/\/fonts\.gstatic\.com\/.*/i,handler:"CacheFirst",options:{cacheName:"gstatic-fonts-cache",expiration:{maxEntries:10,maxAgeSeconds:3600*24*365},cacheableResponse:{statuses:[0,200]}}},{urlPattern:/\.(?:png|jpg|jpeg|svg|gif|webp|avif)$/,handler:"StaleWhileRevalidate",options:{cacheName:"images-cache",expiration:{maxEntries:60,maxAgeSeconds:3600*24*30}}},{urlPattern:/\/api\/.*/i,handler:"NetworkFirst",options:{cacheName:"api-cache",expiration:{maxEntries:50,maxAgeSeconds:300},networkTimeoutSeconds:10}},{urlPattern:({request:t})=>t.destination==="document",handler:"NetworkFirst",options:{cacheName:"pages-cache",expiration:{maxEntries:32,maxAgeSeconds:3600*24},networkTimeoutSeconds:10}}],cleanupOutdatedCaches:e.cleanupOutdatedCaches!==!1,skipWaiting:e.skipWaiting!==!1,clientsClaim:e.clientsClaim!==!1,maximumFileSizeToCacheInBytes:e.maximumFileSizeToCacheInBytes||5*1024*1024,navigateFallback:e.navigateFallback||"/",navigateFallbackDenylist:e.navigateFallbackDenylist||[/^\/api\/.*/]}}_generateWorkboxRuntimeCaching(e,t={}){return e.map((n,s)=>{let{urlPattern:o,handler:a,options:i={}}=n,l=a==="CacheFirst"?"CacheFirst":a==="NetworkFirst"?"NetworkFirst":a==="StaleWhileRevalidate"?"StaleWhileRevalidate":"NetworkFirst",u;typeof o=="function"?u="({ request }) => request.destination === 'document'":o instanceof RegExp?u=o.toString():u=JSON.stringify(o);let c=[];i.expiration&&c.push(`new ExpirationPlugin({
|
|
246
230
|
maxEntries: ${i.expiration.maxEntries||50},
|
|
247
231
|
maxAgeSeconds: ${i.expiration.maxAgeSeconds||3600*24},
|
|
248
232
|
})`),i.cacheableResponse&&c.push(`new CacheableResponsePlugin({
|
|
249
233
|
statuses: ${JSON.stringify(i.cacheableResponse.statuses||[0,200])},
|
|
250
234
|
})`),i.backgroundSync&&c.push(`new BackgroundSyncPlugin('${i.backgroundSync.queueName||"background-sync-queue"}', {
|
|
251
235
|
maxRetentionTime: ${i.backgroundSync.maxRetentionTime||1440},
|
|
252
|
-
})`);let
|
|
253
|
-
cacheName: '${i.cacheName}',`),c.length>0&&(
|
|
236
|
+
})`);let p="";return i.cacheName&&(p+=`
|
|
237
|
+
cacheName: '${i.cacheName}',`),c.length>0&&(p+=`
|
|
254
238
|
plugins: [
|
|
255
239
|
${c.join(`,
|
|
256
240
|
`)}
|
|
257
|
-
],`),i.networkTimeoutSeconds&&(
|
|
258
|
-
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${
|
|
241
|
+
],`),i.networkTimeoutSeconds&&(p+=`
|
|
242
|
+
networkTimeoutSeconds: ${i.networkTimeoutSeconds},`),`// Runtime cache ${s+1}: ${i.cacheName||"cache-"+s}
|
|
259
243
|
registerRoute(
|
|
260
|
-
${
|
|
261
|
-
new ${l}({${
|
|
244
|
+
${u},
|
|
245
|
+
new ${l}({${p}
|
|
262
246
|
})
|
|
263
247
|
);`}).join(`
|
|
264
248
|
|
|
265
|
-
`)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",
|
|
249
|
+
`)}_generateBackgroundSync(e){if(!e||e===!1)return"";let t=e.queueName||"background-sync-queue",n=e.maxRetentionTime||1440,s=e.urlPattern||/\/api\/.*/i,o;return typeof s=="function"||s instanceof RegExp?o=s.toString():o=JSON.stringify(s),`
|
|
266
250
|
// Background sync for offline actions
|
|
267
251
|
const { NetworkOnly } = workbox.strategies;
|
|
268
252
|
registerRoute(
|
|
269
|
-
${
|
|
253
|
+
${o},
|
|
270
254
|
new NetworkOnly({
|
|
271
255
|
plugins: [
|
|
272
256
|
new BackgroundSyncPlugin('${t}', {
|
|
273
|
-
maxRetentionTime: ${
|
|
257
|
+
maxRetentionTime: ${n},
|
|
274
258
|
}),
|
|
275
259
|
],
|
|
276
260
|
}),
|
|
277
261
|
'POST'
|
|
278
262
|
);
|
|
279
|
-
`}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),s=this.pathResolver.resolveAppPath(`${e}/static/chunks`),r=this.pathResolver.resolveAppPath(`${e}/static/css`),n=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${s}/**/*.{js,css}`,`${r}/**/*.css`];for(let i of a){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let p of l){let c=this.pathResolver.getRelativePath(p);if(c.startsWith(`${e}/static/`)){let u=`/_next/${c.replace(`${e}/static/`,"")}`;n.push({url:u,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return n}generatePrecacheManifest(e=[],t=null){let s=e;return t&&typeof t=="function"&&(s=t(s)),s}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var lt=class extends G{constructor(e={}){super(Oe,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/pwa-manifest.json",webManifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){let t=this.options.assetData||rt.data;return new e(this.pathResolver,{...this.options,assetData:t})}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}formatAPIResponse(e){return{assets:e.assets,manifest:e.manifest,totalAssets:e.assets.length,timestamp:e.timestamp}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(this.options.generateManifest&&await this.generatePWAManifest(e),!this.options.enabled){this.logger.debug("PWA disabled, skipping service worker generation");return}this.options.generateServiceWorker&&await this.generateServiceWorker(e),await this.generateAPIHandler(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.webManifestPath,t,"web app manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},s=[];if(this.options.discoverBuildAssets!==!1){let n=await this.discovery.discoverNextBuildAssets(".next");s=this.discovery.generatePrecacheManifest(n,t.manifestTransform)}let r=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:s});this.writeGeneratedFile(this.options.serviceWorkerPath,r,"service worker")}createNextConfig(){return this.options.enabled?(e={})=>(this.logger.debug("Initializing Next.js PWA handler"),{...e,webpack:(t,s)=>{let{dev:r,isServer:n,webpack:a}=s;return this.applyViteIgnorePlugin(t,a),!r&&!n&&this._generateFiles(),e.webpack?e.webpack(t,s):t}}):()=>({})}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function Ss(o={}){return new lt(o)}import{createRequire as Vn}from"node:module";function $s(o,e="unknown"){try{let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,s=o.match(t);if(!s)return null;let r=s[1];r=r.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(l,p)=>`icon: '${p}'`);let n=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;return[...o.matchAll(n)].forEach(l=>{let p=l[1],c=l[2];r=r.replace(new RegExp(`\\b${p}\\b`,"g"),`'${c}'`)}),Function(`return ${r}`)()}catch{return null}}var $e=null,Ps=null;function Cn(o){let t=(o.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Tn(o){let e=o.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw new Error(`PageMeta signedInRedirect in ${o.file} must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`);if(e.split(/[?#]/)[0]===o.path)throw new Error(`PageMeta signedInRedirect in ${o.file} points at the page itself (${e}): signed-in visitors would loop. Use another page.`)}}var fe=class extends X{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),s=process.env.DNDEV_BUILD_ID;if($e&&Ps===s)return this.logger.debug("Using cached route discovery results"),this.routes=$e.routes,this.errors=$e.errors,this.source=$e.source,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let r=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${r} files in ${t}`);let n=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(n)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),$e={routes:this.routes,errors:this.errors,source:this.source},Ps=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:s}=e,r=await this._batchProcessFiles(s,p=>this._analyzePageFile(p,t)),n=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(n,p=>this._analyzePageFile(p,t)),i=[...r,...a];this.logger.debug(`Auto-discovering from ${s.length} app + ${n.length} additional files`),this.routes=i.filter(p=>p.path==="home"||p.path==="/home"?(this.logger.debug(`Filtered reserved route: ${p.path} - Use root "/" instead (${p.file})`),!1):!0);let l=new Map;for(let p of this.routes){let c=p.path;if(l.has(c)){let u=l.get(c);throw new Error(`Route conflict: Multiple routes found for path '${c}'. Routes: ${u.file} and ${p.file}. Use PageMeta route override to specify unique paths. Example: export const meta: PageMeta = { route: '/custom-path' };`)}l.set(c,p),Tn(p)}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${s.length+n.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(s=>this.pathResolver.resolveAppPath(s));if(t.length===0)return[];try{let{consumerFiles:s}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return s}catch(s){return this.logger.debug(`Error scanning additional patterns: ${s.message}`),[]}}async _analyzePageFile(e,t){let s=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!s)return null;let r=e.relativePath,n="/src/"+r.replace(/\\/g,"/");n=n.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(s,e.absolutePath),i=Cn(n),p=i===ye.HOMEPAGE_COMPONENT?ye.HOMEPAGE_PATH:this._resolveRoutePath(a,r,e.absolutePath),c=this._extractPageMeta(r,s),{entity:u,action:h,...g}=a||{};return{path:p,component:i,importPath:n,auth:a?.auth||!1,meta:{...c,...g,entity:c.entity,action:c.action},metaExport:a,file:r}}_extractMetaExport(e,t){try{let s=$s(e,t);return s?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(s)}`),s):null}catch(s){return this.logger.debug(`Error parsing meta export from ${t}: ${s.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,s){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let r=e.route.trim();return r==="/"?"/":(r=r.replace(/\/+/g,"/"),r.startsWith("/")||(r="/"+r),r)}if(typeof e.route=="object"&&e.route!==null){let r=this._generateRoutePath(t),n=e.route.params;if(Array.isArray(n)&&n.length>0){let a=n.map(i=>`:${i}`).join("/");return`${r}/${a}`}return r}return this.logger.warn(`Invalid route format in ${s}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${s}`),this._generateRoutePath(t)}_extractPageMeta(e,t){let s=e.split("/").pop()?.replace(".tsx","")||"",r=s.replace(/Page$/,"");r=r.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),r=r.charAt(0).toUpperCase()+r.slice(1);let n=e.split("/"),a=null,i=null;return n.length>1&&(a=n[n.length-2],s.includes("List")?i="list":s.includes("Form")||s.includes("Create")||s.includes("Edit")?i="form":(s.includes("Detail")||s.includes("View"))&&(i="detail")),{title:r,entity:a,action:i,file:e}}};import{existsSync as Dn,readdirSync as On}from"node:fs";import{join as Fn}from"node:path";function Es(o){let e=Fn(o,"src","content","blog");try{return Dn(e)?On(e).some(t=>t.endsWith("_en.md")):!1}catch{return!1}}function In(o,e,t="configuration-error",s={}){let r=`[${o}] ${e}`,n=new Error(r);return n.code=t,n.pluginName=o,n.context=s,n}function xs(o,e,t,s={}){return In(o,`Required resource missing: ${e}. ${t}`,"missing-required-resource",Object.assign({resourceName:e},s))}function U(o){return o?o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}function As(o){return o?o.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Ln=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function ks(o,e){let t;try{let s=new URL(o);if(s.protocol!=="https:"&&s.protocol!=="http:")throw new Error;t=s.hostname}catch{throw new Error(`[dndev] SEO: base URL "${o}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(Ln.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: production build with base URL "${o}". 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 _s=new Set(["/404","/not-found","/500","/error"]);function ut(o){return o.auth&&o.auth!==!1||_s.has(o.path)||_s.has(o.meta?.route)?!1:o.meta?.seo?.noindex!==!0}function ht(o){if(!(typeof o.path!="string"||!o.path.includes(":"))&&ut(o))return o.meta?.entity||void 0}var Fe=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:s=!0,generateSitemap:r=!0,baseUrl:n,siteName:a,crawlDelay:i=1,aiCrawlers:l="recommended",routes:p={},...c}=e;if(!n||!a)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:s,generateSitemap:r,baseUrl:n,siteName:a,crawlDelay:i,aiCrawlers:l,routes:p,defaultImage:ce,twitterHandle:"@donotdev",defaultAuthor:"DNDev Team",defaultLanguage:"en",blogPath:"/blog",staticTags:{},...c},this.appRoot=c.appRoot||null,this.logger=B("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t){try{let s=this.generateRouteMetaTags(e.routes||[]),r={routes:e.routes||[],routeMetaTags:s,baseUrl:this.options.baseUrl,siteName:this.options.siteName},n=this.discoverBlogPosts(),a={robotsTxt:null,sitemap:null,rss:null,manifest:null,totalRoutes:r.routes.length,publicRoutes:r.routes.filter(i=>!i.auth||i.auth===!1).length,protectedRoutes:r.routes.filter(i=>i.auth&&i.auth.required).length,blogPosts:n.length};return this.options.generateRobotsTxt&&(a.robotsTxt=await this.generateRobotsTxt(r,t)),this.options.generateSitemap&&(a.sitemap=await this.generateSitemap(r,t,n)),n.length>0&&(a.rss=await this.generateRSSFeed(n,t)),a.manifest=await this.generateManifest(r,t),a}catch(s){throw this.logger.error(`SEO generator failed to create files (robots.txt/sitemap.xml/manifest): ${s.message}`),this.logger.error(`Stack: ${s.stack||"No stack trace available"}`),s}}async generateRobotsTxt(e,t){let s=[];(e.routes||[]).forEach(n=>{if(n.auth&&n.auth.required){let a=n.path.startsWith("/")?n.path:`/${n.path}`;s.push(a)}}),s.push("/admin","/api");let r=this.generateRobotsTxtContent({disallowedPaths:[...new Set(s)],sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",r),{fileName:"robots.txt",content:r,disallowedPaths:s.length}}async generateSitemap(e,t,s=[]){let n=(e.routes||[]).filter(i=>!(!ut(i)||typeof i.path=="string"&&i.path.includes(":")||s.length>0&&i.path===this.options.blogPath)).map(i=>({url:i.path,lastmod:new Date().toISOString().split("T")[0],changefreq:"weekly",priority:i.path==="/"?"1.0":"0.8"}));if(s.length>0){n.push({url:this.options.blogPath,lastmod:s[0]?.date||new Date().toISOString().split("T")[0],changefreq:"weekly",priority:"0.7"});for(let i of s)n.push({url:`${this.options.blogPath}/${i.slug}`,lastmod:i.date,changefreq:"monthly",priority:"0.6",image:i.image||null})}let a=this.generateSitemapContent(n);return await t("sitemap.xml",a),{fileName:"sitemap.xml",content:a,publicRoutes:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:s}=this.options,r=[];for(let n of e||[]){if(!ut(n)||typeof n.path!="string")continue;let a=n.path===s||n.path.startsWith(`${s}/`);if(!(t.length>0&&a))if(n.path.includes(":")){if(a)continue;let i=ht(n);r.push({path:n.path,...i&&{collection:i}})}else r.push({path:n.path})}if(t.length>0){r.push({path:s,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let n of t)r.push({path:`${s}/${n.slug}`,priority:.6,changeFrequency:"monthly",...n.date&&{lastModified:n.date}})}return r}async generateManifest(e,t){let s={totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,protectedRoutes:e.routes?.filter(n=>n.auth&&n.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString(),routeMetaTags:e.routeMetaTags||[]},r=JSON.stringify(s,null,2);return await t("seo-manifest.json",r),{fileName:"seo-manifest.json",content:r,manifest:s}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:s=["/admin","/api"],sitemap:r,crawlDelay:n}=e,a=p=>p?p==="*"?"*":p.startsWith("/")?p:`/${p}`:"/",i=["User-agent: *",...s.map(p=>`Disallow: ${a(p)}`),...t.map(p=>`Allow: ${a(p)}`)];n&&i.push(`Crawl-delay: ${n}`),r&&i.push(`Sitemap: ${r}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Un(l))),i.join(`
|
|
280
|
-
`)}generateSitemapContent(e){let t=e.some(r=>r.image),s=e.map(({url:r,lastmod:n,changefreq:a,priority:i,image:l})=>{let p=[` <loc>${U(this.options.baseUrl)}${U(r)}</loc>`];return n&&p.push(` <lastmod>${n}</lastmod>`),a&&p.push(` <changefreq>${a}</changefreq>`),i&&p.push(` <priority>${i}</priority>`),l&&p.push(` <image:image>
|
|
281
|
-
<image:loc>${U(this.options.baseUrl)}${U(l)}</image:loc>
|
|
282
|
-
</image:image>`),` <url>
|
|
283
|
-
${p.join(`
|
|
284
|
-
`)}
|
|
285
|
-
</url>`}).join(`
|
|
286
|
-
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
287
|
-
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${t?`
|
|
288
|
-
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"`:""}>
|
|
289
|
-
${s}
|
|
290
|
-
</urlset>`}generateRouteMetaTags(e){return e.map(t=>{let s=this.options.siteName;if(t.meta?.title)s=`${t.meta.title} - ${this.options.siteName}`;else if(t.path!=="/"){let n=t.path.split("/").filter(Boolean);n.length>0&&(s=`${n[n.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ")} - ${this.options.siteName}`)}let r=`Welcome to ${this.options.siteName}`;if(t.meta?.description)r=t.meta.description;else if(t.meta?.entity&&t.meta?.action)r=`${t.meta.action} ${t.meta.entity} on ${this.options.siteName}`;else if(t.path!=="/"){let n=t.path.split("/").filter(Boolean);n.length>0&&(r=`Explore ${n[n.length-1].split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ").toLowerCase()} on ${this.options.siteName}`)}return{path:t.path,meta:{title:s,description:r,canonical:`${this.options.baseUrl}${t.path}`,robots:t.auth&&t.auth.required?"noindex, nofollow":"index, follow"}}})}discoverBlogPosts(){if(!this.appRoot)return[];let e=$.getInstance(),t=e.resolvePath("src/content/blog",this.appRoot);try{if(!e.pathExists(t))return[];let s=e.readdirSync(t).filter(n=>n.endsWith("_en.md"));if(s.length===0)return[];let r=[];for(let n of s){let a=e.resolvePath(n,t),i=e.readSync(a,{format:"text"}),l=n.replace(/_en\.md$/,""),p=i.match(/^---\r?\n([\s\S]*?)\r?\n---/),c={};if(p)for(let h of p[1].split(`
|
|
291
|
-
`)){let g=h.indexOf(":");g!==-1&&(c[h.slice(0,g).trim()]=h.slice(g+1).trim())}let u=c.date;if(!u)try{u=e.statSync(a).mtime.toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no frontmatter date, using file mtime (${u})`)}catch{u=new Date().toISOString().split("T")[0],this.logger.warn(`Blog post "${l}" has no date and file stat failed, using today`)}r.push({slug:l,title:c.title||l,description:c.description||"",date:u,tags:c.tags?c.tags.split(",").map(h=>h.trim()):[],image:c.image||null})}return r.sort((n,a)=>a.date.localeCompare(n.date)),this.logger.info(`\u{1F4DD} Discovered ${r.length} blog post(s) in src/content/blog/`),r}catch(s){return this.logger.debug(`Blog content discovery skipped: ${s.message}`),[]}}async generateRSSFeed(e,t){let s=e.map(n=>` <item>
|
|
292
|
-
<title><![CDATA[${As(n.title)}]]></title>
|
|
293
|
-
<link>${U(this.options.baseUrl)}${U(this.options.blogPath)}/${U(n.slug)}</link>
|
|
294
|
-
<guid>${U(this.options.baseUrl)}${U(this.options.blogPath)}/${U(n.slug)}</guid>
|
|
295
|
-
<description><![CDATA[${As(n.description)}]]></description>
|
|
296
|
-
<pubDate>${n.date?new Date(n.date).toUTCString():""}</pubDate>${n.tags.length?`
|
|
297
|
-
<category>${U(n.tags.join(", "))}</category>`:""}${n.image?`
|
|
298
|
-
<enclosure url="${U(this.options.baseUrl)}${U(n.image)}" type="image/png" length="0"/>`:""}
|
|
299
|
-
</item>`).join(`
|
|
300
|
-
`),r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
301
|
-
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
302
|
-
<channel>
|
|
303
|
-
<title>${U(this.options.siteName)}</title>
|
|
304
|
-
<link>${U(this.options.baseUrl)}${U(this.options.blogPath)}</link>
|
|
305
|
-
<description>${U(this.options.siteName)} Blog</description>
|
|
306
|
-
<language>en</language>
|
|
307
|
-
<atom:link href="${U(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
308
|
-
${s}
|
|
309
|
-
</channel>
|
|
310
|
-
</rss>`;return await t("rss.xml",r),{fileName:"rss.xml",content:r,postCount:e.length}}getGenerationSummary(e){let t=e.routes?.length||0,s=e.routes?.filter(n=>!n.auth||n.auth===!1).length||0,r=e.routes?.filter(n=>n.auth&&n.auth.required).length||0;return`${t} routes (${s} public, ${r} protected)`}formatAPIResponse(e){return{totalRoutes:e.routes?.length||0,publicRoutes:e.routes?.filter(t=>!t.auth||t.auth===!1).length||0,protectedRoutes:e.routes?.filter(t=>t.auth&&t.auth.required).length||0,baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()}}},ct=["GPTBot","Google-Extended","CCBot","ClaudeBot"],pt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Un(o){let e=["# AI Crawler Management"];if(o==="block-all"){for(let t of[...ct,...pt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(o==="allow-all"){for(let t of[...ct,...pt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of ct)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of pt)e.push(`User-agent: ${t}`,"Allow: /","");return e}import{createHash as jn,timingSafeEqual as Gn}from"node:crypto";function Ie(o){return o.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}async function Ns(o,e,t){let s=Ie(o.path),r=s[0];if(s.length!==1||!o.collection||!r)throw new Error(`[dndev] Cannot list the public URLs of route "${o.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 "${o.path}" lists "${o.collection}" records but no server CRUD reader was given.`);let n;try{n=await e.query(o.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3})}catch(i){let l=i?.details?.originalMessage??i?.message??String(i);throw new Error(`[dndev] Route "${o.path}" could not read its public "${o.collection}" records (signed-out visitor: RLS / Security Rules must allow it): ${l}`,{cause:i})}let a=[];for(let i of n.items){let l=i[r];typeof l!="string"&&typeof l!="number"||a.push({param:r,value:String(l),record:i})}return a}async function Le(o,e,t){let s=[];for(let r of o){if(Ie(r.path).length===0){s.push({route:r,path:r.path});continue}for(let{param:n,value:a,record:i}of await Ns(r,e,t))s.push({route:r,path:r.path.replace(`:${n}`,encodeURIComponent(a)),record:i})}return s}async function Mn(o,e,t){return(await Ns(o,e,t)).map(({param:s,value:r})=>({[s]:r}))}var Pe="DNDEV_REVALIDATE_SECRET",Ds="/api/dndev/revalidate",Cs=32,Ts="public",Bn=["/sitemap.xml","/llms.txt"];function zn(o){return o.replace(/[/#?\\]|%(2f|23|3f|5c)/gi,e=>encodeURIComponent(e))}function Wn(o,e){return e.languages.length<2?[o]:e.languages.map(t=>`/${t}${o==="/"?"":o}`)}function Os(o,e,t){let s=new Set,r=new Set;for(let n of o){let a=Ie(n.path);if(a.length===0){s.add(n.path);continue}let[i]=a;if(!(a.length!==1||!i||n.collection!==e.table)){for(let l of[e.record,e.oldRecord]){let p=l?.[i];typeof p!="string"&&typeof p!="number"||s.add(n.path.replace(`:${i}`,zn(String(p))))}for(let l of Bn)r.add(l)}}for(let n of s)for(let a of Wn(n,t))r.add(a);return[...r].sort()}function Hn(o,e){let t=/^Bearer (.+)$/.exec(o??"");if(!t)return!1;let s=r=>jn("sha256").update(r).digest();return Gn(s(t[1]),s(e))}async function qn(o,{secret:e,routes:t,routing:s,readChange:r,revalidatePath:n}){if(!e||e.length<Cs)throw new Error(`[dndev] Set ${Pe} to a random secret of at least ${Cs} characters: the revalidation webhook (${Ds}) authenticates with it.`);if(!Hn(o.headers.get("authorization"),e))return Response.json({error:"Unauthorized"},{status:401});let a;try{a=r(await o.json())}catch(l){if(!(l instanceof Error))throw l;return Response.json({error:l.message},{status:400})}if(a.schema!==Ts)return Response.json({error:`Table "${a.schema}.${a.table}" is not in the "${Ts}" schema: only public content tables are revalidated.`},{status:400});let i=Os(t,a,s);for(let l of i)n(l);return Response.json({revalidated:i})}function gt(o,e,t,s){try{if(t?.content?.[o]?.[e])return t.content[o][e];let r=t?.mapping?.[o]?.[e];if(!r)return null;let n=s.resolveAppPath(r),a=s.readSync(n,{format:"text"});return a?JSON.parse(a):null}catch{return null}}function Ue(o,e){if(!o||!e)return;let t=e.split("."),s=o;for(let r of t)if(s&&typeof s=="object"&&r in s)s=s[r];else return;return s}function dt(o){return o?.languages||o?.supportedLanguages||["en"]}function ft(o){return o?.fallback||o?.fallbackLanguage||"en"}var mt=class extends G{constructor(e={}){super(fe,e),this.rendersSessionTree=!1,this.appRouteSegments=[]}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,proxyPath:F.next.proxy,manifestPath:F.next.routeManifest,languages:[],defaultLanguage:null}}useLanguages({languages:e,defaultLanguage:t}){if(e.length>1&&!e.includes(t))throw new Error(`i18n fallbackLanguage "${t}" has no translations among [${e.join(", ")}]: it is the language served at the root URL. Add its locale files or set i18n.fallbackLanguage to one of them.`);this.options.languages=e,this.options.defaultLanguage=t}isMultilingual(){return this.options.languages.length>1}rootDir(){return this.isMultilingual()?"/[lang]":""}treeDir(e="site"){return`${this.rootDir()}/${e==="session"?Z.sessionSegment:Z.siteGroup}`}appDirFor(e,t="site"){return`${this.treeDir(t)}${this.convertRouteToAppPath(e)}`}appImport(e,t){let s=e.split("/").filter(Boolean).length;return s===0?`./${t}`:`${"../".repeat(s)}${t}`}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],s=t.filter(n=>n.auth&&n.auth.required).length,r=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${r} found${s>0?`, ${s} are authguarded`:""}`)}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}formatAPIResponse(e){return{routes:e.routes,source:e.source,totalRoutes:e.routes.length,timestamp:e.timestamp}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[],s={totalRoutes:t.length,authRequired:t.filter(r=>r.auth&&r.auth.required).length,publicRoutes:t.filter(r=>!r.auth||r.auth===!1).length,source:e.source,hasBlogFeed:Es(this.pathResolver.getAppRoot()),generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
311
|
-
// Generated at: ${new Date().toISOString()}
|
|
312
|
-
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
313
|
-
|
|
314
|
-
const routeMapping = ${JSON.stringify(t,null,2)};
|
|
315
|
-
|
|
316
|
-
const routeManifest = ${JSON.stringify(s,null,2)};
|
|
317
|
-
|
|
318
|
-
// Populate unified DnDev config for runtime access (universal CSR/SSR)
|
|
319
|
-
if (typeof globalThis !== 'undefined') {
|
|
320
|
-
if (!globalThis._DNDEV_CONFIG_) {
|
|
321
|
-
globalThis._DNDEV_CONFIG_ = {
|
|
322
|
-
platform: 'nextjs',
|
|
323
|
-
mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development',
|
|
324
|
-
version: '1.0.0',
|
|
325
|
-
context: typeof window !== 'undefined' ? 'client' : 'server',
|
|
326
|
-
timestamp: Date.now(),
|
|
327
|
-
};
|
|
328
|
-
}
|
|
329
|
-
globalThis._DNDEV_CONFIG_.${J.routes} = {
|
|
330
|
-
mapping: routeMapping,
|
|
331
|
-
manifest: routeManifest,
|
|
332
|
-
};
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// Export for compatibility
|
|
336
|
-
export const routes = routeMapping;
|
|
337
|
-
export const manifest = routeManifest;
|
|
338
|
-
export default { routes: routeMapping, manifest: routeManifest };
|
|
339
|
-
`}async generateSpecificFiles(e){await this.assertAppDocument(),this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&(await this.generateAppPageFiles(e),this.generateRevalidationRoute(e)),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e),await this.generateAPIHandler(e)}async generateMetadataManifest(e){let t=this.loadI18nConfig(),s=dt(t),r=ft(t),n=process.env.NEXT_PUBLIC_SITE_NAME||"";if(!n)try{let l=this.pathResolver.resolveAppPath("public/seo-manifest.json");this.pathResolver.pathExists(l)&&(n=this.pathResolver.readSync(l,{format:"json"})?.siteName||"")}catch{}let a={};for(let l of e.routes){let p=l.metaExport?.namespace,c=l.metaExport?.seo||{},u={};for(let h of s){let g=p&&t&>(p,h,t,this.pathResolver)||gt(p,r,t,this.pathResolver),d=Ue(g,"meta")||{},f=Ue(g,"title"),w=Ue(g,"description"),y;d.fullTitle?y=d.fullTitle:c.fullTitle?y=c.fullTitle:f?y=n?`${f} | ${n}`:f:c.title?y=n?`${c.title} | ${n}`:c.title:c.title===null?y=n:y=n||"";let A;c.description===null?A=void 0:c.description?A=c.description:w&&(A=w);let m=c.image||d.image||ce,E=c.type||d.type||"website",O=c.keywords||d.keywords,k=c.noindex||!1;u[h]={title:y,...A&&{description:A},image:m,type:E,...O&&{keywords:O},...k&&{noindex:k}}}a[l.path]={locales:u,defaultLocale:r}}let i=JSON.stringify(a,null,2);this.writeGeneratedFile("public/metadata-manifest.json",i,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(a).length} routes`)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles(),this.generateRootLayout(),this.generateNotFoundPages();let t=this.rendersSessionTree?["site","session"]:["site"];for(let r of t)await this.generateTreeLayout(r);let s=0;for(let r of e.routes){let n=this.isSessionOnlyRoute(r)?"session":"site",a=await this.generateSingleAppPage(r,n);a&&s++,a&&n==="site"&&this.rendersSessionTree&&this.generateSessionPage(r)}this.logger.debug(`Successfully generated ${s}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}requestDocumentParts(e){return[[/<ClientLayout\b/,"renders <ClientLayout>"],[/from\s+['"]next\/headers['"]/,"imports next/headers"],[/export\s+const\s+dynamic\b/,"exports `dynamic`"]].filter(([t])=>t.test(e)).map(([,t])=>t)}async assertAppDocument(){let e=F.next.appDocument,t=`${e} exports \`metadata\` (site-level: metadataBase) and \`AppDocument({ lang, children })\`, which renders <html lang={lang}>, the <head> links (favicon, <FontPreloadLinks />), imports the global CSS and puts {children} in <body> (see the @donotdev/cli app-next template)`,s=[];for(let a of this.frameworkRootFiles()){let i=this.pathResolver.resolveAppPath(a);this.pathResolver.pathExists(i)&&!await this.hasGenerationMarker(i)&&s.push(a)}if(s.length>0)throw new Error(`[dndev] ${s.join(", ")}: the framework generates the root layout and the 404 pages, so every page's HTML carries its language (<html lang>). Move the HTML shell into ${e}: ${t}. Then delete ${s.join(", ")}.`);let r=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(r))throw new Error(`[dndev] ${e} is missing: ${t}.`);let n=this.requestDocumentParts(await this.pathResolver.read(r,{format:"text"}));if(n.length!==0)throw new Error(`[dndev] ${e} ${n.join(", ")}. It must be the HTML shell: render {children} in <body>, drop the ClientLayout / headers() wrapper and \`export const dynamic\`. The generated layouts render ClientLayout: cached pages for guests, per-request pages for visitors with an auth cookie.`)}frameworkRootFiles(){let e=I("layout","tsx"),t=I("not-found","tsx");return[F.next.appLayout,`src/app/[lang]/${e}`,`src/app/${t}`,`src/app/[lang]/${t}`,`src/app/${I("global-not-found","tsx")}`]}async generateTreeLayout(e){let t=`src/app${this.treeDir(e)}/${I("layout","tsx")}`,s=this.pathResolver.resolveAppPath(t);if(this.pathResolver.pathExists(s)&&!await this.hasGenerationMarker(s)){this.logger.debug(`Skipping ${t} - user-created file detected`);return}this.writeGeneratedFile(t,e==="session"?this.generateSessionLayoutContent():this.generateSiteLayoutContent(),`${e} layout`)}generateSiteLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
263
|
+
`}getPWARewrites(){return{beforeFiles:[],afterFiles:[{source:"/sw.js",destination:"/sw.js"},{source:"/workbox-:path*",destination:"/workbox-:path*"}],fallback:[]}}async discoverNextBuildAssets(e=".next"){let t=this.pathResolver.resolveAppPath(`${e}/static`),n=this.pathResolver.resolveAppPath(`${e}/static/chunks`),s=this.pathResolver.resolveAppPath(`${e}/static/css`),o=[];try{let a=[`${t}/**/*.{js,css,woff2,woff,ttf,eot}`,`${n}/**/*.{js,css}`,`${s}/**/*.css`];for(let i of a){let l=await this.pathResolver.findFiles(this.pathResolver.getAppRoot(),i.replace(this.pathResolver.getAppRoot(),""),{onlyFiles:!0});for(let u of l){let c=this.pathResolver.getRelativePath(u);if(c.startsWith(`${e}/static/`)){let p=`/_next/${c.replace(`${e}/static/`,"")}`;o.push({url:p,revision:null})}}}}catch(a){this.logger?.warn(`Failed to discover Next.js build assets: ${a.message}`)}return o}generatePrecacheManifest(e=[],t=null){let n=e;return t&&typeof t=="function"&&(n=t(n)),n}async discoverPWAAssets(e=!1){return await this.discover(e)}getPWAAssets(){return this.cache?.assets||[]}getPWAManifest(){return this.cache?.manifest||this._getDefaultManifest()}};var Ft=class extends H{constructor(e={}){super(Ke,e)}getHandlerDefaults(){return{enabled:!1,manifestPath:"public/pwa-manifest.json",webManifestPath:"public/manifest.json",serviceWorkerPath:"public/sw.js",workboxPath:"public/workbox-*.js",generateServiceWorker:!0,generateManifest:!0}}createDiscovery(e){return new e(this.pathResolver,this.options)}getHandlerName(){return"PWA"}async getDiscoveryData(){return await this.discovery.discoverPWAAssets()}getAPIRewrites(){return this.options.enabled?this.discovery.getPWARewrites():{beforeFiles:[],afterFiles:[],fallback:[]}}createManifestContent(e){return{assets:e.assets.map(t=>({type:t.type,path:t.path,size:t.size})),manifest:e.manifest,totalAssets:e.assets.length,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.assets.length} PWA assets for Next.js`}async generateSpecificFiles(e){if(this.options.generateManifest&&await this.generatePWAManifest(e),!this.options.enabled){this.logger.debug("PWA disabled, skipping service worker generation");return}this.options.generateServiceWorker&&await this.generateServiceWorker(e)}async generatePWAManifest(e){let t=this.discovery.generateManifestContent(e);this.writeGeneratedFile(this.options.webManifestPath,t,"web app manifest")}async generateServiceWorker(e){let t=this.options.workbox||{},n=[];if(this.options.discoverBuildAssets!==!1){let o=await this.discovery.discoverNextBuildAssets(".next");n=this.discovery.generatePrecacheManifest(o,t.manifestTransform)}let s=this.discovery.generateServiceWorkerContent(e,{...t,precacheManifest:n});this.writeGeneratedFile(this.options.serviceWorkerPath,s,"service worker")}async generatePWA(){return this.generateFiles()}createPWAAPIHandler(){return this.createAPIHandler()}};function mr(r={}){return new Ft(r)}var yr={requestDocumentParts(r){return[[/<ClientLayout\b/,"renders <ClientLayout>"],[/from\s+['"]next\/headers['"]/,"imports next/headers"],[/export\s+const\s+dynamic\b/,"exports `dynamic`"]].filter(([e])=>e.test(r)).map(([,e])=>e)},async assertAppDocument(){let r=L.next.appDocument,e=`${r} exports \`metadata\` (site-level: metadataBase) and \`AppDocument({ lang, children })\`, which renders <html lang={lang}>, the <head> links the app needs (the framework renders the favicon and font tags), imports the global CSS and puts {children} in <body> (see the @donotdev/cli app-next template)`,t=[];for(let o of this.frameworkRootFiles()){let a=this.pathResolver.resolveAppPath(o);this.pathResolver.pathExists(a)&&!await this.hasGenerationMarker(a)&&t.push(o)}if(t.length>0)throw new Error(`[dndev] ${t.join(", ")}: the framework generates the root layout and the 404 pages, so every page's HTML carries its language (<html lang>). Move the HTML shell into ${r}: ${e}. Then delete ${t.join(", ")}.`);let n=this.pathResolver.resolveAppPath(r);if(!this.pathResolver.pathExists(n))throw new Error(`[dndev] ${r} is missing: ${e}.`);let s=this.requestDocumentParts(await this.pathResolver.read(n,{format:"text"}));if(s.length!==0)throw new Error(`[dndev] ${r} ${s.join(", ")}. It must be the HTML shell: render {children} in <body>, drop the ClientLayout / headers() wrapper and \`export const dynamic\`. The generated layouts render ClientLayout: cached pages for guests, per-request pages for visitors with an auth cookie.`)},frameworkRootFiles(){let r=U("layout","tsx"),e=U("not-found","tsx");return[L.next.appLayout,`src/app/[lang]/${r}`,`src/app/${e}`,`src/app/[lang]/${e}`,`src/app/${U("global-not-found","tsx")}`]},async generateTreeLayout(r){let e=`src/app${this.treeDir(r)}/${U("layout","tsx")}`,t=this.pathResolver.resolveAppPath(e);if(this.pathResolver.pathExists(t)&&!await this.hasGenerationMarker(t)){this.logger.debug(`Skipping ${e} - user-created file detected`);return}this.writeGeneratedFile(e,r==="session"?this.generateSessionLayoutContent():this.generateSiteLayoutContent(),`${r} layout`)},generateSiteLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
340
264
|
// Cached pages: rendered without request data (no cookies, no headers), served from the
|
|
341
265
|
// cache and ${this.revalidateLabel()} (appConfig.revalidate). One entry per URL (page and language).
|
|
342
266
|
|
|
@@ -353,7 +277,7 @@ export default function SiteLayout({ children }: { children: ReactNode }) {
|
|
|
353
277
|
</ClientLayout>
|
|
354
278
|
);
|
|
355
279
|
}
|
|
356
|
-
`}generateSessionLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
280
|
+
`},generateSessionLayoutContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
357
281
|
// Per-request pages for visitors with an auth cookie (the proxy rewrites them here; a
|
|
358
282
|
// direct hit is a 404): the providers read the request cookies, so the server render
|
|
359
283
|
// shows the visitor's signed-in state and data. Never cached.
|
|
@@ -374,17 +298,29 @@ export default async function SessionLayout({ children }: { children: ReactNode
|
|
|
374
298
|
</ClientLayout>
|
|
375
299
|
);
|
|
376
300
|
}
|
|
377
|
-
`}generateRootLayout(){this.writeGeneratedFile(`src/app${this.rootDir()}/${
|
|
378
|
-
//
|
|
301
|
+
`},generateRootLayout(){this.writeGeneratedFile(L.next.fonts,this.generateFontsContent(),"font plan"),this.writeGeneratedFile(`src/app${this.rootDir()}/${U("layout","tsx")}`,this.generateRootLayoutContent(),"root layout")},generateFontsContent(){if(!this.fonts)throw new Error("[dndev] NextRouteHandler: the font plan is not set (runDiscoveries calls useFonts before generating routes).");let r={css:this.fonts.css,preloads:this.fonts.preloads};return`// Generated by @donotdev/config - DO NOT EDIT
|
|
302
|
+
// The app's font plan (@donotdev/core config fonts/buildFontPlan.js, from the theme font tokens
|
|
303
|
+
// and appConfig.fonts): inline @font-face rules and each language's font preloads, rendered
|
|
304
|
+
// by FontHead in the root layout and the global 404. Files: public/fonts/ (content-hashed).
|
|
305
|
+
|
|
306
|
+
import type { FontHeadData } from '@donotdev/ui/next';
|
|
307
|
+
|
|
308
|
+
export const FONTS: FontHeadData = ${JSON.stringify(r,null,2)};
|
|
309
|
+
`},generateRootLayoutContent(){let r=this.appImport(this.rootDir(),"AppDocument"),e=this.appImport(this.rootDir(),"fonts.generated");return this.isMultilingual()?`// Generated by @donotdev/config - DO NOT EDIT
|
|
310
|
+
// Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the URL's language, with
|
|
311
|
+
// the framework's font tags (FontHead: the language's font preloads + inline @font-face).
|
|
379
312
|
// One URL per language: the default language (${this.options.defaultLanguage}) at the root, served here by
|
|
380
313
|
// the proxy's rewrite; the others under their prefix. Any other first segment is a 404.
|
|
381
314
|
|
|
382
315
|
import { notFound } from 'next/navigation';
|
|
383
316
|
import type { ReactNode } from 'react';
|
|
384
317
|
|
|
385
|
-
import {
|
|
318
|
+
import { FontHead } from '@donotdev/ui/next';
|
|
319
|
+
|
|
320
|
+
import { AppDocument } from '${r}';
|
|
321
|
+
import { FONTS } from '${e}';
|
|
386
322
|
|
|
387
|
-
export { metadata } from '${
|
|
323
|
+
export { metadata } from '${r}';
|
|
388
324
|
|
|
389
325
|
const LANGUAGES: readonly string[] = ${JSON.stringify(this.options.languages)};
|
|
390
326
|
|
|
@@ -401,21 +337,37 @@ export default async function RootLayout({
|
|
|
401
337
|
}) {
|
|
402
338
|
const { lang } = await params;
|
|
403
339
|
if (!LANGUAGES.includes(lang)) notFound();
|
|
404
|
-
return
|
|
340
|
+
return (
|
|
341
|
+
<AppDocument lang={lang}>
|
|
342
|
+
<FontHead fonts={FONTS} lang={lang} />
|
|
343
|
+
{children}
|
|
344
|
+
</AppDocument>
|
|
345
|
+
);
|
|
405
346
|
}
|
|
406
347
|
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
407
|
-
// Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the app's language
|
|
348
|
+
// Root layout: the app's AppDocument (src/app/AppDocument.tsx) in the app's language, with
|
|
349
|
+
// the framework's font tags (FontHead: font preloads + inline @font-face, hoisted to <head>).
|
|
408
350
|
|
|
409
351
|
import type { ReactNode } from 'react';
|
|
410
352
|
|
|
411
|
-
import {
|
|
353
|
+
import { FontHead } from '@donotdev/ui/next';
|
|
412
354
|
|
|
413
|
-
|
|
355
|
+
import { AppDocument } from '${r}';
|
|
356
|
+
import { FONTS } from '${e}';
|
|
357
|
+
|
|
358
|
+
export { metadata } from '${r}';
|
|
359
|
+
|
|
360
|
+
const lang = ${JSON.stringify(this.options.defaultLanguage)};
|
|
414
361
|
|
|
415
362
|
export default function RootLayout({ children }: { children: ReactNode }) {
|
|
416
|
-
return
|
|
363
|
+
return (
|
|
364
|
+
<AppDocument lang={lang}>
|
|
365
|
+
<FontHead fonts={FONTS} lang={lang} />
|
|
366
|
+
{children}
|
|
367
|
+
</AppDocument>
|
|
368
|
+
);
|
|
417
369
|
}
|
|
418
|
-
`}generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${
|
|
370
|
+
`},generateNotFoundPages(){this.writeGeneratedFile(`src/app${this.rootDir()}/${U("not-found","tsx")}`,this.generateNotFoundContent(),"404 page"),this.writeGeneratedFile(`src/app/${U("global-not-found","tsx")}`,this.generateGlobalNotFoundContent(),"global 404 page")},generateNotFoundContent(){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
419
371
|
// 404 page: the app's providers without request data (static, like every cached page).
|
|
420
372
|
// Shared fallback content must not expose the pathname captured during prerendering:
|
|
421
373
|
// NotFoundDocument drops URL-derived output (canonical, JSON-LD, breadcrumbs).
|
|
@@ -438,8 +390,9 @@ export default function NotFound() {
|
|
|
438
390
|
</NotFoundDocument>
|
|
439
391
|
);
|
|
440
392
|
}
|
|
441
|
-
`}generateGlobalNotFoundContent(){let
|
|
393
|
+
`},generateGlobalNotFoundContent(){let r=`
|
|
442
394
|
<AppDocument lang={lang}>
|
|
395
|
+
<FontHead fonts={FONTS} lang={lang} />
|
|
443
396
|
<NotFoundDocument>
|
|
444
397
|
<ClientLayout serverCookies="" acceptLanguage={null}>
|
|
445
398
|
<Suspense fallback={null}>
|
|
@@ -456,9 +409,11 @@ import { headers } from 'next/headers';
|
|
|
456
409
|
import { Suspense } from 'react';
|
|
457
410
|
|
|
458
411
|
import { NotFoundDocument, NotFoundPage } from '@donotdev/ui';
|
|
412
|
+
import { FontHead } from '@donotdev/ui/next';
|
|
459
413
|
|
|
460
414
|
import { AppDocument } from './AppDocument';
|
|
461
415
|
import { ClientLayout } from './ClientLayout';
|
|
416
|
+
import { FONTS } from './fonts.generated';
|
|
462
417
|
|
|
463
418
|
export { metadata } from './AppDocument';
|
|
464
419
|
|
|
@@ -468,7 +423,7 @@ export default async function GlobalNotFound() {
|
|
|
468
423
|
const requested = (await headers()).get(${JSON.stringify(Z.languageHeader)});
|
|
469
424
|
const lang =
|
|
470
425
|
requested && LANGUAGES.includes(requested) ? requested : ${JSON.stringify(this.options.defaultLanguage)};
|
|
471
|
-
return (${
|
|
426
|
+
return (${r}
|
|
472
427
|
);
|
|
473
428
|
}
|
|
474
429
|
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
@@ -477,186 +432,196 @@ export default async function GlobalNotFound() {
|
|
|
477
432
|
import { Suspense } from 'react';
|
|
478
433
|
|
|
479
434
|
import { NotFoundDocument, NotFoundPage } from '@donotdev/ui';
|
|
435
|
+
import { FontHead } from '@donotdev/ui/next';
|
|
480
436
|
|
|
481
437
|
import { AppDocument } from './AppDocument';
|
|
482
438
|
import { ClientLayout } from './ClientLayout';
|
|
439
|
+
import { FONTS } from './fonts.generated';
|
|
483
440
|
|
|
484
441
|
export { metadata } from './AppDocument';
|
|
485
442
|
|
|
486
443
|
const lang = ${JSON.stringify(this.options.defaultLanguage)};
|
|
487
444
|
|
|
488
445
|
export default function GlobalNotFound() {
|
|
489
|
-
return (${
|
|
446
|
+
return (${r}
|
|
490
447
|
);
|
|
491
448
|
}
|
|
492
|
-
`}
|
|
493
|
-
// Per-request render of ${e.path} (visitors with an auth cookie): same page as the cached one.
|
|
494
|
-
|
|
495
|
-
export { ${n.join(", ")} } from '${r}';
|
|
496
|
-
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${I("page","tsx")}`,`src/app/**/${I("layout","tsx")}`,`src/app/**/${I("not-found","tsx")}`,`src/app/${I("global-not-found","tsx")}`,"src/app/**/*PageClient.tsx"],s=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),r=0;for(let n of s)if(await this.hasGenerationMarker(n))try{await this.pathResolver.remove(n),r++,this.logger.debug(`Cleaned generated file: ${n}`)}catch(a){this.logger.debug(`Could not clean file ${n}: ${a.message}`)}r>0&&this.logger.debug(`Cleaned ${r} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e,t="site"){try{let s=this.appDirFor(e.path,t),r=`src/app${s}/${I("page","tsx")}`,n=this.pathResolver.resolveAppPath(r);if(this.pathResolver.pathExists(n)&&!await this.hasGenerationMarker(n))return this.logger.debug(`Skipping ${r} - user-created file detected (no generation marker)`),!1;let a={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},i=this.generatePageFileContent(a,t);this.writeGeneratedFile(r,i,`app page: ${s}`);let l=this.extractComponentName(a.filePath),p=this.calculateRelativeImportPath(a.relativePath,a.path);return a.metaExport?.namespace==="blog"&&this.hasDynamicSegment(a.path)?this.writeGeneratedFile(`src/app${s}/BlogPostClient.tsx`,this.generateBlogPostClientContent(l,p),`app blog client: ${s}`):this.isClientComponent(a.filePath)&&this.writeGeneratedFile(`src/app${s}/${l}Client.tsx`,this.generateMountedClientContent(l,p),`app client wrapper: ${s}`),!0}catch(s){return this.logger.debug(`Error generating page for route ${e.path}: ${s.message}`),!1}}convertRouteToAppPath(e){if(e===ye.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(s=>s.startsWith(":")?`[${s.slice(1)}]`:s==="*"?"[...slug]":s).join("/")}loadI18nConfig(){try{let e=this.pathResolver.resolveAppPath("src/config/dndev-config-i18n.js");if(!this.pathResolver.pathExists(e))return this.logger.debug("I18n config file not found, skipping metadata generation"),null;if(typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?.i18n)return globalThis._DNDEV_CONFIG_.i18n;try{let t=this.pathResolver.getAppRoot(),s=Vn(t),r=s.resolve(e);delete s.cache[r];let n=s(r);return n.default||n.i18nConfig||n}catch(t){return this.logger.debug(`Failed to require i18n config: ${t.message}`),null}}catch(e){return this.logger.debug(`Failed to load i18n config: ${e.message}`),null}}generatePageFileContent(e,t="site"){let s=this.extractComponentName(e.filePath),r=e.relativePath||e.file,n=this.calculateRelativeImportPath(r,e.path);if(e.metaExport?.namespace==="blog"&&this.hasDynamicSegment(e.path))return this.generateBlogPostRSCContent(e,s,n);let a=this.isClientComponent(e.filePath),i=this.normalizeAuth(e.auth)?e.auth:null,l=e.meta?.signedInRedirect??null,p=[...i?["AuthGuard"]:[],...l?["SignedInRedirect"]:[]],c=p.length?`import { ${p.join(", ")} } from '@donotdev/ui';
|
|
497
|
-
`:"",u=t==="site"?this.staticParamsExport(e):{imports:"",code:""},h=g=>{let d=l?`<SignedInRedirect to={${JSON.stringify(l)}}>${g}</SignedInRedirect>`:g;return i?`<AuthGuard auth={${JSON.stringify(i===!0?{required:!0}:i)}}>${d}</AuthGuard>`:d};return a?`// Generated by @donotdev/config - DO NOT EDIT
|
|
449
|
+
`}};var vr={isBlogPostRoute(r){return r.metaExport?.namespace==="blog"&&this.hasDynamicSegment(r.path)},extractDynamicParam(r){let e=r.match(/:([a-zA-Z0-9_]+)/);if(e)return e[1];let t=r.match(/\[([^\]]+)\]/);return t?t[1]:"slug"},generateBlogPostClientContent(r,e){return`// Generated by @donotdev/config - DO NOT EDIT
|
|
498
450
|
// This file will be regenerated when src/pages changes
|
|
499
|
-
|
|
451
|
+
'use client';
|
|
500
452
|
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
453
|
+
import { useEffect, useState } from 'react';
|
|
454
|
+
|
|
455
|
+
import ${r} from '${e}';
|
|
456
|
+
|
|
457
|
+
export default function BlogPostClient() {
|
|
458
|
+
const [mounted, setMounted] = useState(false);
|
|
459
|
+
|
|
460
|
+
useEffect(() => {
|
|
461
|
+
document.documentElement.dataset.dndevBlogClientReady = 'true';
|
|
462
|
+
setMounted(true);
|
|
463
|
+
return () => {
|
|
464
|
+
delete document.documentElement.dataset.dndevBlogClientReady;
|
|
465
|
+
};
|
|
466
|
+
}, []);
|
|
509
467
|
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
export default function ${s}Route(props: Record<string, unknown>) {
|
|
513
|
-
return ${h(`<${s} {...props} />`)};
|
|
468
|
+
if (!mounted) return null;
|
|
469
|
+
return <${r} />;
|
|
514
470
|
}
|
|
515
|
-
|
|
471
|
+
`},calculateBlogContentImportPath(r){let t=this.appDirFor(r).split("/").filter(Boolean);return`${"../".repeat(t.length+1)}content/blog/blog-content.generated`},generateBlogPostRSCContent(r,e,t){let n=this.extractDynamicParam(r.path);return`// Generated by @donotdev/config - DO NOT EDIT
|
|
516
472
|
// This file will be regenerated when src/pages changes
|
|
517
|
-
// To customize: edit ${
|
|
473
|
+
// To customize: edit ${r.filePath} or create manual app/** files
|
|
518
474
|
|
|
519
|
-
${u.imports}import ${s} from '${n}';
|
|
520
|
-
${u.code}
|
|
521
|
-
export default ${s};
|
|
522
|
-
`}generateMetadataFunction(e,t,s){let r=dt(s),n=ft(s),a="`",i=r.map(l=>` '${l}': { href: ${a}\${baseUrl}\${currentPath}${a} }`).join(`,
|
|
523
|
-
`);return`
|
|
524
475
|
import type { Metadata } from 'next';
|
|
525
|
-
|
|
526
|
-
import {
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
return null;
|
|
541
|
-
}
|
|
476
|
+
|
|
477
|
+
import { parseBlogFrontmatter } from '@donotdev/core/server';
|
|
478
|
+
|
|
479
|
+
import BlogPostClient from './BlogPostClient';
|
|
480
|
+
import blogContent from '${this.calculateBlogContentImportPath(r.path)}';
|
|
481
|
+
|
|
482
|
+
type Params = Promise<{ ${n}: string }>;
|
|
483
|
+
|
|
484
|
+
interface BlogMeta {
|
|
485
|
+
title: string;
|
|
486
|
+
description: string;
|
|
487
|
+
date: string;
|
|
488
|
+
tags?: string;
|
|
489
|
+
image?: string;
|
|
490
|
+
[key: string]: string | undefined;
|
|
542
491
|
}
|
|
543
492
|
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
493
|
+
interface BlogPost {
|
|
494
|
+
slug: string;
|
|
495
|
+
meta: BlogMeta;
|
|
496
|
+
content: string;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function parseFrontmatter(raw: string): { meta: BlogMeta; content: string } {
|
|
500
|
+
const { meta, content } = parseBlogFrontmatter(raw);
|
|
501
|
+
return { meta: { title: '', description: '', date: '', ...meta }, content };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function parseFilePath(path: string): { slug: string; lang: string } | null {
|
|
505
|
+
const filename = path.split('/').pop()?.replace(new RegExp('\\\\.md$'), '');
|
|
506
|
+
if (filename === undefined) return null;
|
|
507
|
+
|
|
508
|
+
const lastUnderscore = filename.lastIndexOf('_');
|
|
509
|
+
if (lastUnderscore === -1) return { slug: filename, lang: 'en' };
|
|
510
|
+
|
|
511
|
+
const lang = filename.slice(lastUnderscore + 1);
|
|
512
|
+
const slug = filename.slice(0, lastUnderscore);
|
|
513
|
+
if (lang.length < 2 || lang.length > 5 || !/^[a-zA-Z]{2,5}$/.test(lang)) {
|
|
514
|
+
return { slug: filename, lang: 'en' };
|
|
554
515
|
}
|
|
555
|
-
return
|
|
516
|
+
return { slug, lang };
|
|
556
517
|
}
|
|
557
518
|
|
|
558
|
-
|
|
559
|
-
const
|
|
560
|
-
const
|
|
561
|
-
const
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
// For Next.js App Router, locale can come from [locale] segment or headers
|
|
566
|
-
const locale = (params?.locale as string) || fallbackLocale;
|
|
567
|
-
const effectiveLocale = supportedLocales.includes(locale) ? locale : fallbackLocale;
|
|
568
|
-
|
|
569
|
-
// Get base URL from environment or construct from request
|
|
570
|
-
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ||
|
|
571
|
-
(typeof process !== 'undefined' && process.env.VERCEL_URL
|
|
572
|
-
? ${a}https://\${process.env.VERCEL_URL}${a}
|
|
573
|
-
: '');
|
|
574
|
-
const currentPath = '${e.path}';
|
|
575
|
-
|
|
576
|
-
// Read translation for current locale
|
|
577
|
-
const translation = readTranslation('${t}', effectiveLocale, i18nConfig) ||
|
|
578
|
-
readTranslation('${t}', fallbackLocale, i18nConfig);
|
|
579
|
-
|
|
580
|
-
// Extract metadata from translation
|
|
581
|
-
const title = getTranslationValue(translation, 'title') || '${e.metaExport?.title||""}';
|
|
582
|
-
const description = getTranslationValue(translation, 'description') || '${e.metaExport?.description||""}';
|
|
583
|
-
const metaObject = getTranslationValue(translation, 'meta') || {};
|
|
584
|
-
|
|
585
|
-
// Read site name from SEO manifest or env var
|
|
586
|
-
let siteName = process.env.NEXT_PUBLIC_SITE_NAME;
|
|
587
|
-
if (!siteName) {
|
|
588
|
-
try {
|
|
589
|
-
const seoManifestPath = join(process.cwd(), 'public', 'seo-manifest.json');
|
|
590
|
-
const seoManifest = JSON.parse(readFileSync(seoManifestPath, 'utf-8'));
|
|
591
|
-
siteName = seoManifest?.siteName || 'Site';
|
|
592
|
-
} catch {
|
|
593
|
-
siteName = 'Site';
|
|
594
|
-
}
|
|
519
|
+
function getEnglishPosts(): BlogPost[] {
|
|
520
|
+
const posts: BlogPost[] = [];
|
|
521
|
+
for (const [path, raw] of Object.entries(blogContent)) {
|
|
522
|
+
const parsed = parseFilePath(path);
|
|
523
|
+
if (parsed === null || parsed.lang !== 'en') continue;
|
|
524
|
+
const post = parseFrontmatter(raw);
|
|
525
|
+
posts.push({ slug: parsed.slug, meta: post.meta, content: post.content });
|
|
595
526
|
}
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
527
|
+
return posts;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
const englishPosts = getEnglishPosts();
|
|
531
|
+
|
|
532
|
+
export async function generateStaticParams() {
|
|
533
|
+
return englishPosts.map((post) => ({ ${n}: post.slug }));
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export async function generateMetadata({
|
|
537
|
+
params,
|
|
538
|
+
}: {
|
|
539
|
+
params: Params;
|
|
540
|
+
}): Promise<Metadata> {
|
|
541
|
+
const { ${n} } = await params;
|
|
542
|
+
const post = englishPosts.find((item) => item.slug === ${n}) ?? null;
|
|
543
|
+
if (!post) return { title: 'Post not found' };
|
|
544
|
+
const appUrl = process.env.NEXT_PUBLIC_APP_URL;
|
|
545
|
+
return {
|
|
546
|
+
title: post.meta.title,
|
|
547
|
+
...(post.meta.description ? { description: post.meta.description } : {}),
|
|
548
|
+
...(appUrl ? { metadataBase: new URL(appUrl) } : {}),
|
|
612
549
|
openGraph: {
|
|
613
|
-
title:
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
...(pageImage && { images: [pageImage] }),
|
|
618
|
-
siteName: siteName,
|
|
550
|
+
title: post.meta.title,
|
|
551
|
+
type: 'article',
|
|
552
|
+
...(post.meta.description ? { description: post.meta.description } : {}),
|
|
553
|
+
...(post.meta.image ? { images: [post.meta.image] } : {}),
|
|
619
554
|
},
|
|
620
555
|
twitter: {
|
|
621
556
|
card: 'summary_large_image',
|
|
622
|
-
title:
|
|
623
|
-
...(
|
|
624
|
-
...(
|
|
625
|
-
},
|
|
626
|
-
alternates: {
|
|
627
|
-
languages: {
|
|
628
|
-
${i}
|
|
629
|
-
},
|
|
557
|
+
title: post.meta.title,
|
|
558
|
+
...(post.meta.description ? { description: post.meta.description } : {}),
|
|
559
|
+
...(post.meta.image ? { images: [post.meta.image] } : {}),
|
|
630
560
|
},
|
|
631
561
|
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function escapeHtml(value: string): string {
|
|
565
|
+
return value
|
|
566
|
+
.replace(/&/g, '&')
|
|
567
|
+
.replace(/</g, '<')
|
|
568
|
+
.replace(/>/g, '>')
|
|
569
|
+
.replace(/"/g, '"')
|
|
570
|
+
.replace(/'/g, ''');
|
|
571
|
+
}
|
|
632
572
|
|
|
633
|
-
|
|
573
|
+
export default async function BlogPostRoute({ params }: { params: Params }) {
|
|
574
|
+
const { ${n} } = await params;
|
|
575
|
+
const post = englishPosts.find((item) => item.slug === ${n}) ?? null;
|
|
576
|
+
|
|
577
|
+
return (
|
|
578
|
+
<>
|
|
579
|
+
<style
|
|
580
|
+
dangerouslySetInnerHTML={{
|
|
581
|
+
__html:
|
|
582
|
+
'html[data-dndev-blog-client-ready="true"] .dndev-blog-seo-fallback{display:none}',
|
|
583
|
+
}}
|
|
584
|
+
/>
|
|
585
|
+
{post && (
|
|
586
|
+
<article className="dndev-blog-seo-fallback prose">
|
|
587
|
+
<h1>{post.meta.title}</h1>
|
|
588
|
+
{post.meta.description && <p>{post.meta.description}</p>}
|
|
589
|
+
{post.meta.date && <p>{post.meta.date}</p>}
|
|
590
|
+
<pre
|
|
591
|
+
style={{ whiteSpace: 'pre-wrap', font: 'inherit' }}
|
|
592
|
+
dangerouslySetInnerHTML={{ __html: escapeHtml(post.content) }}
|
|
593
|
+
/>
|
|
594
|
+
</article>
|
|
595
|
+
)}
|
|
596
|
+
<BlogPostClient />
|
|
597
|
+
</>
|
|
598
|
+
);
|
|
634
599
|
}
|
|
635
|
-
`}
|
|
636
|
-
`),
|
|
637
|
-
`),
|
|
638
|
-
`),
|
|
639
|
-
session: SupabaseProxySession['session']`:"",
|
|
640
|
-
language: string`:"",
|
|
641
|
-
// Request gate (Next 16 proxy)${
|
|
642
|
-
// root, the others under their prefix (resolveLanguageRoute in @donotdev/core)`:""}.${
|
|
600
|
+
`}};function It(r,e,t,n){try{if(t?.content?.[r]?.[e])return t.content[r][e];let s=t?.mapping?.[r]?.[e];if(!s)return null;let o=n.resolveAppPath(s),a=n.readSync(o,{format:"text"});return a?JSON.parse(a):null}catch{return null}}function br(r){return r?.languages||r?.supportedLanguages||["en"]}function wr(r){return r?.fallback||r?.fallbackLanguage||"en"}function ya(r,e,t,n={}){let{minLength:s=0,excludeEmpty:o=!0,customFilter:a}=n;return Array.from({length:t},(i,l)=>{let u=`${e}.${l}`;return r(u)}).filter((i,l)=>{let u=`${e}.${l}`;return!(i===u||o&&i.trim()===""||i.length<s||a&&!a(i,l))})}var va=20,Sr={defaultValue:""};function Er(r,e,t){if(r!==null)return r!==void 0?r:t(e,Sr)||void 0}function Rr(r,e){let t=o=>r(o,Sr),n=o=>t(`${e}:meta.${o}`)||void 0,s=ya(t,`${e}:meta.keywords`,va);return{fullTitle:n("fullTitle"),image:n("image"),type:n("type"),keywords:s.length>0?s:void 0,author:n("author")}}function ba(r,e){return r===!0?"noindex, nofollow":r===!1?null:e?"noindex":null}function Lt(r){let{meta:e,ns:t,defaultNs:n,t:s,siteName:o}=r,a=e.seo;if(!t&&!n)return{title:a?.fullTitle||o};let i=t?Er(a?.title,`${t}:title`,s):a?.title??void 0;return{title:a?.fullTitle||(t?Rr(s,t).fullTitle:void 0)||(i?`${i} | ${o}`:o),...i&&{pageTitle:i}}}function $r(r){let{meta:e,ns:t,defaultNs:n,t:s,siteName:o,baseUrl:a,url:i,defaultImage:l}=r,u=e.seo,c=t??n,p=c?Rr(s,c):null,{title:d}=Lt({meta:e,ns:t,defaultNs:n,t:s,siteName:o}),f=c?Er(u?.description,`${c}:description`,s):void 0,h=u?.image||p?.image||l||void 0,m=u?.keywords||p?.keywords,y=e.author||p?.author;return{title:d,...f&&{description:f},...h&&{image:h.startsWith("http")?h:`${a}${h}`},url:i,type:u?.type||p?.type||"website",robots:ba(u?.noindex??e.noindex,r.authOnly),...m&&{keywords:m},...y&&{author:y},...e.publishDate&&{publishDate:e.publishDate},...e.modifiedDate&&{modifiedDate:e.modifiedDate}}}function Xe(r){return(e,t)=>{let n=e.indexOf(":"),s=r[e.slice(0,n)];for(let o of e.slice(n+1).split("."))s=s&&typeof s=="object"&&o in s?s[o]:void 0;return typeof s=="string"?s:t?.defaultValue??e}}var xr={async generateMetadataManifest(r){let e=this.i18n;if(!e)throw new Error("Route handler: translations not set before the metadata manifest (runDiscoveries calls useI18n)");let t=br(e),n=wr(e),s=this.options.siteName||"",o={};for(let i of r.routes){let l=i.metaExport?.namespace||null,u=this.defaultNamespace(),c=l||u,p={};for(let d of t){let f=It(c,d,e,this.pathResolver)||It(c,n,e,this.pathResolver),h=$r({meta:i.metaExport||{},ns:l,defaultNs:u,t:Xe({[c]:f}),siteName:s,baseUrl:"",url:null,defaultImage:this.defaultImage(),authOnly:!!i.auth});p[d]={title:h.title,...h.description&&{description:h.description},image:h.image,type:h.type,...h.keywords&&{keywords:h.keywords},...h.robots&&{robots:h.robots}}}o[i.path]={locales:p,defaultLocale:n}}let a=JSON.stringify(o,null,2);this.writeGeneratedFile("public/metadata-manifest.json",a,"metadata manifest"),this.logger.debug(`Generated metadata manifest for ${Object.keys(o).length} routes`)}};var Pr={async generateMiddleware(r){this.removeLegacyMiddleware(),this.rendersSessionTree=!1;let e=r.routes.filter(l=>!!this.normalizeAuth(l.auth)),t=r.routes.filter(l=>l.meta?.signedInRedirect),n=this.usesCookieSession();(e.length>0||t.length>0)&&!n&&this.logger.debug("Auth session not in cookies (no Supabase createBrowserClient): pages use the client AuthGuard / SignedInRedirect only, no proxy auth redirects");let s=n?e:[],o=n?t:[],a=this.pathResolver.resolveAppPath(this.options.proxyPath),i=this.pathResolver.pathExists(a)&&!await this.hasGenerationMarker(a);if(!this.isMultilingual()&&!n){this.logger.debug("One language and no cookie session: no proxy.next.ts"),this.pathResolver.pathExists(a)&&!i&&await this.pathResolver.remove(a);return}if(i){this.logger.warn(`${this.options.proxyPath} is hand-written: not generating language routing / session refresh / auth redirects / per-request pages (add them to your proxy; every visitor gets the cached pages)`);return}this.isMultilingual()&&(this.appRouteSegments=await this.findAppRouteSegments()),this.writeGeneratedFile(this.options.proxyPath,this.generateMiddlewareContent(s,r.routes,o,n),"proxy"),this.rendersSessionTree=n},async findAppRouteSegments(){let r=this.pathResolver.getAppRoot(),e=this.pathResolver.resolveAppPath(L.next.appPages),t=await this.pathResolver._globWithNormalization([`${L.next.appPages}/**/{route,page}.${he}.{ts,tsx,js,jsx}`],{cwd:r,absolute:!0,onlyFiles:!0,braceExpansion:!0}),n=new Set;for(let s of t){if(await this.hasGenerationMarker(s))continue;let[o]=s.slice(e.length+1).split("/").slice(0,-1).filter(a=>!/^\(.*\)$/.test(a));o&&o!=="[lang]"&&n.add(o)}return[...n].sort()},routePattern(r){return"^"+r.split("/").map(e=>e==="*"?".*":e.startsWith(":")?"[^/]+":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("/")+"$"},generateMiddlewareContent(r,e=[],t=[],n=!1){let s=this.isMultilingual(),o=r.length>0,a=t.length>0,i=o||a,l=n||i,u=this.options.auth??{},c=r.map(A=>{let{role:G}=this.normalizeAuth(A.auth);return` { pattern: new RegExp(${JSON.stringify(this.routePattern(A.path))})${G?`, role: ${JSON.stringify(G)}`:""} },`}).join(`
|
|
601
|
+
`),p=t.map(A=>` { pattern: new RegExp(${JSON.stringify(this.routePattern(A.path))}), to: ${JSON.stringify(A.meta.signedInRedirect)} },`).join(`
|
|
602
|
+
`),d=[...new Set(e.map(A=>A.path))].map(A=>` new RegExp(${JSON.stringify(this.routePattern(A))}),`).join(`
|
|
603
|
+
`),f=` ${JSON.stringify("/((?!api|_next|.*\\..*).*)")},`,h=[...o?["hasRoleAccess"]:[],...s?["LANGUAGE_COOKIE",...i?["localizePath"]:[],"parseAcceptLanguage","readCookieValue","resolveLanguageRoute","splitLanguagePath"]:[]],m=["hasSupabaseSessionCookie","refreshSupabaseSession",...i?["type SupabaseProxySession"]:[]],y=i?`,
|
|
604
|
+
session: SupabaseProxySession['session']`:"",S=s?`,
|
|
605
|
+
language: string`:"",T=l?"{ request }":"",R=`/${Z.sessionSegment}`,v=`// Generated by @donotdev/config - DO NOT EDIT
|
|
606
|
+
// Request gate (Next 16 proxy)${s?`: one URL per language, the default language (${this.options.defaultLanguage}) at the
|
|
607
|
+
// root, the others under their prefix (resolveLanguageRoute in @donotdev/core)`:""}.${l?`
|
|
643
608
|
// Session: the Supabase cookie (createBrowserClient). No auth cookie: signed out, the
|
|
644
609
|
// page comes from the cache (src/app${this.treeDir("site")}, static). With one: verified and refreshed
|
|
645
610
|
// when expired (refreshSupabaseSession: Auth getUser() for documents, local getClaims()
|
|
646
611
|
// for RSC soft navigations and prefetches), then rendered per request with the refreshed
|
|
647
|
-
// cookies (src/app${this.rootDir()}${
|
|
648
|
-
// gets the refreshed cookies on the response.`:""}${
|
|
612
|
+
// cookies (src/app${this.rootDir()}${R}, an internal path: a direct hit is a 404); the browser
|
|
613
|
+
// gets the refreshed cookies on the response.`:""}${o?`
|
|
649
614
|
// Auth redirects for pages whose PageMeta sets \`auth\`, on the verified session.
|
|
650
615
|
// Redirect gate only: data access stays enforced by RLS, and the page's AuthGuard still
|
|
651
616
|
// runs on the client. Those pages have no cached copy: rendered per request for every
|
|
652
|
-
// visitor that is not redirected.`:""}${
|
|
617
|
+
// visitor that is not redirected.`:""}${a?"\n// Signed-in redirects for pages whose PageMeta sets `signedInRedirect` (verified\n// session); the page's SignedInRedirect still runs on the client.":""}
|
|
653
618
|
|
|
654
619
|
import { NextResponse } from 'next/server';
|
|
655
620
|
import type { NextRequest } from 'next/server';
|
|
656
621
|
|
|
657
|
-
${
|
|
658
|
-
`:""}${
|
|
659
|
-
`:""}`,
|
|
622
|
+
${h.length?`import { ${h.join(", ")} } from '@donotdev/core/server';
|
|
623
|
+
`:""}${l?`import { ${m.join(", ")} } from '@donotdev/supabase/server';
|
|
624
|
+
`:""}`,x=l?`
|
|
660
625
|
/** Supabase project of the cookie session (same env as src/config/providers.ts) */
|
|
661
626
|
const SUPABASE = supabaseProject(
|
|
662
627
|
process.env.NEXT_PUBLIC_SUPABASE_URL,
|
|
@@ -671,23 +636,23 @@ function supabaseProject(url: string | undefined, publicKey: string | undefined)
|
|
|
671
636
|
}
|
|
672
637
|
return { url, publicKey };
|
|
673
638
|
}
|
|
674
|
-
${
|
|
675
|
-
/** Internal tree of the per-request pages (src/app/[lang]${
|
|
639
|
+
${s?`
|
|
640
|
+
/** Internal tree of the per-request pages (src/app/[lang]${R}), after the language: never a public URL */
|
|
676
641
|
const SESSION_SEGMENT = ${JSON.stringify(Z.sessionSegment)};
|
|
677
642
|
|
|
678
|
-
/** Internal URL path of a page rendered per request: \`/fr/compte\` \u2192 \`/fr${
|
|
643
|
+
/** Internal URL path of a page rendered per request: \`/fr/compte\` \u2192 \`/fr${R}/compte\` */
|
|
679
644
|
function sessionPath(path: string): string {
|
|
680
645
|
const [, language, ...rest] = path.split('/');
|
|
681
646
|
return ['', language, SESSION_SEGMENT, ...rest].join('/');
|
|
682
647
|
}
|
|
683
648
|
|
|
684
|
-
/** A direct request for the internal tree (\`/fr${
|
|
649
|
+
/** A direct request for the internal tree (\`/fr${R}/\u2026\`) */
|
|
685
650
|
function isSessionTreePath(pathname: string): boolean {
|
|
686
651
|
return pathname.split('/').slice(1, 3).includes(SESSION_SEGMENT);
|
|
687
652
|
}
|
|
688
653
|
`:`
|
|
689
|
-
/** Internal tree of the per-request pages (src/app${
|
|
690
|
-
const SESSION_TREE = ${JSON.stringify(
|
|
654
|
+
/** Internal tree of the per-request pages (src/app${R}): never a public URL */
|
|
655
|
+
const SESSION_TREE = ${JSON.stringify(R)};
|
|
691
656
|
|
|
692
657
|
/** Internal URL path of a page rendered per request */
|
|
693
658
|
function sessionPath(path: string): string {
|
|
@@ -698,17 +663,17 @@ function sessionPath(path: string): string {
|
|
|
698
663
|
function isSessionTreePath(pathname: string): boolean {
|
|
699
664
|
return pathname === SESSION_TREE || pathname.startsWith(\`\${SESSION_TREE}/\`);
|
|
700
665
|
}
|
|
701
|
-
`}${
|
|
666
|
+
`}${i?`
|
|
702
667
|
/** Session of a request without an auth cookie: signed out, nothing to verify */
|
|
703
668
|
const SIGNED_OUT: SupabaseProxySession['session'] = { user: null };
|
|
704
|
-
`:""}`:"",
|
|
669
|
+
`:""}`:"",O=o?`
|
|
705
670
|
/** appConfig.auth.authRoute: where a signed-out visitor goes (null: page fallback) */
|
|
706
|
-
const AUTH_ROUTE: string | null = ${JSON.stringify(
|
|
671
|
+
const AUTH_ROUTE: string | null = ${JSON.stringify(u.authRoute??null)};
|
|
707
672
|
/** appConfig.auth.roleRoute: where a visitor without the role goes (null: page fallback) */
|
|
708
|
-
const ROLE_ROUTE: string | null = ${JSON.stringify(
|
|
673
|
+
const ROLE_ROUTE: string | null = ${JSON.stringify(u.roleRoute??null)};
|
|
709
674
|
|
|
710
675
|
const protectedRoutes: Array<{ pattern: RegExp; role?: string }> = [
|
|
711
|
-
${
|
|
676
|
+
${c}
|
|
712
677
|
];
|
|
713
678
|
|
|
714
679
|
/** Protected pages exist only in the per-request tree (no cached copy) */
|
|
@@ -719,7 +684,7 @@ function isProtectedRoute(routePath: string): boolean {
|
|
|
719
684
|
/** Redirect of a protected route, or null to let the page render. */
|
|
720
685
|
function authRedirect(
|
|
721
686
|
request: NextRequest${y},
|
|
722
|
-
routePath: string${
|
|
687
|
+
routePath: string${S}
|
|
723
688
|
): NextResponse | null {
|
|
724
689
|
const route = protectedRoutes.find((r) => r.pattern.test(routePath));
|
|
725
690
|
if (!route) return null;
|
|
@@ -728,26 +693,26 @@ function authRedirect(
|
|
|
728
693
|
|
|
729
694
|
if (!session.user) {
|
|
730
695
|
if (!AUTH_ROUTE) return null;
|
|
731
|
-
const url = new URL(${
|
|
696
|
+
const url = new URL(${s?"localizePath(AUTH_ROUTE, language, LANGUAGE_ROUTING)":"AUTH_ROUTE"}, request.url);
|
|
732
697
|
url.searchParams.set('returnTo', request.nextUrl.pathname + request.nextUrl.search);
|
|
733
698
|
return NextResponse.redirect(url);
|
|
734
699
|
}
|
|
735
700
|
if (route.role && !hasRoleAccess(session.user.role, route.role)) {
|
|
736
701
|
if (!ROLE_ROUTE) return null;
|
|
737
|
-
return NextResponse.redirect(new URL(${
|
|
702
|
+
return NextResponse.redirect(new URL(${s?"localizePath(ROLE_ROUTE, language, LANGUAGE_ROUTING)":"ROLE_ROUTE"}, request.url));
|
|
738
703
|
}
|
|
739
704
|
return null;
|
|
740
705
|
}
|
|
741
|
-
`:"",
|
|
706
|
+
`:"",B=a?`
|
|
742
707
|
/** PageMeta \`signedInRedirect\`: where a signed-in visitor of the page goes */
|
|
743
708
|
const signedInRoutes: Array<{ pattern: RegExp; to: string }> = [
|
|
744
|
-
${
|
|
709
|
+
${p}
|
|
745
710
|
];
|
|
746
711
|
|
|
747
712
|
/** Redirect of a signed-in visitor, or null to let the page render. */
|
|
748
713
|
function signedInRedirect(
|
|
749
714
|
request: NextRequest${y},
|
|
750
|
-
routePath: string${
|
|
715
|
+
routePath: string${S}
|
|
751
716
|
): NextResponse | null {
|
|
752
717
|
const route = signedInRoutes.find((r) => r.pattern.test(routePath));
|
|
753
718
|
if (!route) return null;
|
|
@@ -755,9 +720,9 @@ function signedInRedirect(
|
|
|
755
720
|
if (request.nextUrl.searchParams.has('returnTo')) return null;
|
|
756
721
|
// Signed out, or cannot tell: the page renders (its SignedInRedirect decides on the client)
|
|
757
722
|
if (!session?.user) return null;
|
|
758
|
-
return NextResponse.redirect(new URL(${
|
|
723
|
+
return NextResponse.redirect(new URL(${s?"localizePath(route.to, language, LANGUAGE_ROUTING)":"route.to"}, request.url));
|
|
759
724
|
}
|
|
760
|
-
`:"",
|
|
725
|
+
`:"",M=s?`
|
|
761
726
|
const LANGUAGE_ROUTING = {
|
|
762
727
|
languages: ${JSON.stringify(this.options.languages)},
|
|
763
728
|
defaultLanguage: ${JSON.stringify(this.options.defaultLanguage)},
|
|
@@ -768,29 +733,29 @@ const LANGUAGE_HEADER = ${JSON.stringify(Z.languageHeader)};
|
|
|
768
733
|
|
|
769
734
|
/** First URL segments of the app's hand-written routes outside src/app/[lang] (route handlers) */
|
|
770
735
|
const APP_ROUTE_SEGMENTS: readonly string[] = ${JSON.stringify(this.appRouteSegments)};
|
|
771
|
-
`:"",
|
|
736
|
+
`:"",te=s||l?`
|
|
772
737
|
/** App pages (src/pages): API routes, files and hand-written app routes pass untouched */
|
|
773
738
|
const pageRoutes: RegExp[] = [
|
|
774
|
-
${
|
|
739
|
+
${d}
|
|
775
740
|
];
|
|
776
|
-
`:"",
|
|
777
|
-
request: NextRequest${y}${
|
|
741
|
+
`:"",W=i?"session, ":"",g=" // Verified session, refreshed when expired: the redirects and the server render\n // (refreshed cookies forwarded with `request`) see the same signed-in state\n const auth = await refreshSupabaseSession(request, SUPABASE.url, SUPABASE.publicKey);",b=`
|
|
742
|
+
request: NextRequest${y}${l?`,
|
|
778
743
|
personal: boolean`:""}
|
|
779
|
-
`,
|
|
780
|
-
const redirect = authRedirect(request, ${
|
|
744
|
+
`,k=(A,G)=>`${o?`
|
|
745
|
+
const redirect = authRedirect(request, ${W}${A}${G});
|
|
781
746
|
if (redirect) return redirect;
|
|
782
|
-
`:""}${
|
|
783
|
-
const signedIn = signedInRedirect(request, ${
|
|
747
|
+
`:""}${a?`
|
|
748
|
+
const signedIn = signedInRedirect(request, ${W}${A}${G});
|
|
784
749
|
if (signedIn) return signedIn;
|
|
785
|
-
`:""}`,
|
|
786
|
-
// Auth cookie: rendered per request with the visitor's cookies${
|
|
750
|
+
`:""}`,N=(A,G)=>l?`
|
|
751
|
+
// Auth cookie: rendered per request with the visitor's cookies${o?`. Protected pages
|
|
787
752
|
// have no cached copy: per request for every visitor`:""}
|
|
788
|
-
if (personal${
|
|
789
|
-
const page = ${
|
|
790
|
-
return NextResponse.rewrite(new URL(sessionPath(${
|
|
791
|
-
}`:"",
|
|
753
|
+
if (personal${o?` || isProtectedRoute(${G})`:""}) {${A==="pathname"?"":`
|
|
754
|
+
const page = ${A};`}
|
|
755
|
+
return NextResponse.rewrite(new URL(sessionPath(${A==="pathname"?"pathname":"page"}) + search, request.url), { request });
|
|
756
|
+
}`:"",_;s?_=`
|
|
792
757
|
/** Language routing, redirects and render tree of a page request. */
|
|
793
|
-
function route(${
|
|
758
|
+
function route(${b}): NextResponse {
|
|
794
759
|
const { pathname, search } = request.nextUrl;
|
|
795
760
|
const decision = resolveLanguageRoute(
|
|
796
761
|
pathname,
|
|
@@ -823,23 +788,23 @@ function route(${x}): NextResponse {
|
|
|
823
788
|
decision.permanent ? 308 : 307
|
|
824
789
|
);
|
|
825
790
|
}
|
|
826
|
-
${
|
|
791
|
+
${k("decision.path",", decision.language")}${N("decision.type === 'rewrite' ? decision.destination : pathname","decision.path")}
|
|
827
792
|
if (decision.type === 'rewrite') {
|
|
828
|
-
return NextResponse.rewrite(new URL(decision.destination + search, request.url)${
|
|
793
|
+
return NextResponse.rewrite(new URL(decision.destination + search, request.url)${l?", { request }":""});
|
|
829
794
|
}
|
|
830
|
-
return NextResponse.next(${
|
|
795
|
+
return NextResponse.next(${T});
|
|
831
796
|
}
|
|
832
|
-
`:
|
|
797
|
+
`:_=`
|
|
833
798
|
/** Redirects and render tree of a page request. */
|
|
834
|
-
function route(${
|
|
835
|
-
const { ${
|
|
799
|
+
function route(${b}): NextResponse {
|
|
800
|
+
const { ${l?"pathname, search":"pathname"} } = request.nextUrl;
|
|
836
801
|
if (!pageRoutes.some((pattern) => pattern.test(pathname))) {
|
|
837
802
|
return NextResponse.next({ request });
|
|
838
803
|
}
|
|
839
|
-
${
|
|
804
|
+
${k("pathname","")}${N("pathname","pathname")}
|
|
840
805
|
return NextResponse.next({ request });
|
|
841
806
|
}
|
|
842
|
-
`;let
|
|
807
|
+
`;let F;return l?F=`
|
|
843
808
|
export async function proxy(request: NextRequest) {
|
|
844
809
|
if (isSessionTreePath(request.nextUrl.pathname)) {
|
|
845
810
|
return new NextResponse(null, { status: 404 });
|
|
@@ -847,136 +812,267 @@ export async function proxy(request: NextRequest) {
|
|
|
847
812
|
// No auth cookie: signed out. Nothing to verify or refresh, no cookie written: the
|
|
848
813
|
// page is served from the cache.
|
|
849
814
|
if (!hasSupabaseSessionCookie(request)) {
|
|
850
|
-
return route(request${
|
|
815
|
+
return route(request${i?", SIGNED_OUT":""}, false);
|
|
851
816
|
}
|
|
852
817
|
|
|
853
|
-
${
|
|
818
|
+
${g}
|
|
854
819
|
// Signed in, or cannot tell (Supabase unreachable): per-request render. Signed out
|
|
855
820
|
// (refresh failed, session revoked): the cached page, with the cleared cookies.
|
|
856
|
-
return auth.apply(route(request, ${
|
|
821
|
+
return auth.apply(route(request, ${i?"auth.session, ":""}auth.session?.user !== null));
|
|
857
822
|
}
|
|
858
|
-
${
|
|
823
|
+
${_}`:F=`
|
|
859
824
|
export function proxy(request: NextRequest) {
|
|
860
825
|
return route(request);
|
|
861
826
|
}
|
|
862
|
-
${
|
|
827
|
+
${_}`,`${v}${x}${M}${te}${O}${B}${F}
|
|
863
828
|
export const config = {
|
|
864
829
|
matcher: [
|
|
865
|
-
${
|
|
830
|
+
${f}
|
|
866
831
|
],
|
|
867
832
|
};
|
|
868
|
-
`}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
833
|
+
`},usesCookieSession(){try{let r=this.pathResolver.readSync(this.pathResolver.resolveAppPath("package.json"));if(!{...r.dependencies,...r.devDependencies}["@donotdev/supabase"])return!1;let t=this.pathResolver.resolveAppPath("src/config/providers.ts");return this.pathResolver.pathExists(t)?this.pathResolver.readSync(t).includes("createBrowserClient("):!1}catch(r){return this.logger.debug(`Cookie session detection failed: ${r.message}`),!1}},removeLegacyMiddleware(){for(let r of["middleware.ts","src/middleware.ts"]){let e=this.pathResolver.resolveAppPath(r);try{this.pathResolver.pathExists(e)&&this.pathResolver.readSync(e).startsWith("// Auto-generated middleware by @donotdev/config")&&(this.pathResolver.removeSync(e),this.logger.debug(`Removed legacy generated ${r}`))}catch(t){this.logger.debug(`Could not remove legacy ${r}: ${t.message}`)}}}};function q(r){return r.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function Mt(r,e){let t=e&&Object.hasOwn(e,r.collection)?e[r.collection]:void 0;if(!t)throw new Error(`[dndev] Route "${r.path}" reads "${r.collection}" records but no read schema was given for that collection (entityReadSchemas of the app's entities).`);return t}async function Cr(r,e,t,n){let s=q(r.path),o=s[0];if(s.length!==1||!r.collection||!o)throw new Error(`[dndev] Cannot list the public URLs of route "${r.path}". Only single-param routes of an entity collection are expanded. Mark the page \`seo: { noindex: true }\` to keep it out of the sitemap and llms.txt.`);if(!e)throw new Error(`[dndev] Route "${r.path}" lists "${r.collection}" records but no server CRUD reader was given.`);let a=Mt(r,n),i;try{i=await e.query(r.collection,{where:[{field:"status",operator:"not-in",value:[...t]}],limit:1e3},a)}catch(u){let c=u?.details?.originalMessage??u?.message??String(u);throw new Error(`[dndev] Route "${r.path}" could not read its public "${r.collection}" records (signed-out visitor: RLS / Security Rules must allow it): ${c}`,{cause:u})}let l=[];for(let u of i.items){let c=u[o];typeof c!="string"&&typeof c!="number"||l.push({param:o,value:String(c),record:u})}return l}async function Ye(r,e,t,n){let s=[];for(let o of r){if(q(o.path).length===0){s.push({route:o,path:o.path});continue}for(let{param:a,value:i,record:l}of await Cr(o,e,t,n))s.push({route:o,path:o.path.replace(`:${a}`,encodeURIComponent(i)),record:l})}return s}async function wa(r,e,t,n){return(await Cr(r,e,t,n)).map(({param:s,value:o})=>({[s]:o}))}import{createHash as Sa,timingSafeEqual as Ea}from"node:crypto";var Te="DNDEV_REVALIDATE_SECRET",_r="/api/dndev/revalidate",Ar=32,Nr="public",Ra=["/sitemap.xml","/llms.txt"];function $a(r){return r.replace(/[/#?\\]|%(2f|23|3f|5c)/gi,e=>encodeURIComponent(e))}function xa(r,e){return e.languages.length<2?[r]:e.languages.map(t=>`/${t}${r==="/"?"":r}`)}function kr(r,e,t){let n=new Set,s=new Set;for(let o of r){let a=q(o.path);if(a.length===0){n.add(o.path);continue}let[i]=a;if(!(a.length!==1||!i||o.collection!==e.table)){for(let l of[e.record,e.oldRecord]){let u=l?.[i];typeof u!="string"&&typeof u!="number"||n.add(o.path.replace(`:${i}`,$a(String(u))))}for(let l of Ra)s.add(l)}}for(let o of n)for(let a of xa(o,t))s.add(a);return[...s].sort()}function Pa(r,e){let t=/^Bearer (.+)$/.exec(r??"");if(!t)return!1;let n=s=>Sa("sha256").update(s).digest();return Ea(n(t[1]),n(e))}async function Ca(r,{secret:e,routes:t,routing:n,readChange:s,revalidatePath:o}){if(!e||e.length<Ar)throw new Error(`[dndev] Set ${Te} to a random secret of at least ${Ar} characters: the revalidation webhook (${_r}) authenticates with it.`);if(!Pa(r.headers.get("authorization"),e))return Response.json({error:"Unauthorized"},{status:401});let a;try{a=s(await r.json())}catch(l){if(!(l instanceof Error))throw l;return Response.json({error:l.message},{status:400})}if(a.schema!==Nr)return Response.json({error:`Table "${a.schema}.${a.table}" is not in the "${Nr}" schema: only public content tables are revalidated.`},{status:400});let i=kr(t,a,n);for(let l of i)o(l);return Response.json({revalidated:i})}var Dr={revalidationRoute(r){if(this.isSessionOnlyRoute(r)||r.path.includes("*"))return null;let e=q(r.path);if(e.length===0)return{path:r.path};let t=r.meta?.entity;return e.length===1&&t?{path:r.path,collection:t}:null},generateRevalidationContent(r){let e=r.routes.map(n=>this.revalidationRoute(n)).filter(Boolean),t={languages:this.options.languages,defaultLanguage:this.options.defaultLanguage};return`// Generated by @donotdev/config - DO NOT EDIT
|
|
834
|
+
// Regenerated on every build from src/pages (PageMeta).
|
|
835
|
+
// On-demand revalidation: a Supabase database webhook POSTs each row change here
|
|
836
|
+
// (Authorization: Bearer $${Te}). The cached pages showing the row (its entity
|
|
837
|
+
// pages in every language, the static pages, sitemap.xml, llms.txt) are invalidated and
|
|
838
|
+
// re-rendered on their next visit. Secret unset or under 32 characters: every call fails
|
|
839
|
+
// (500), loudly. Watch public content tables only: each call invalidates every static page.
|
|
840
|
+
|
|
841
|
+
import { revalidatePath } from 'next/cache';
|
|
842
|
+
|
|
843
|
+
import type { LanguageRouting } from '@donotdev/core/server';
|
|
844
|
+
import { handleRevalidationWebhook } from '@donotdev/core/next';
|
|
845
|
+
import type { PublicRoute } from '@donotdev/core/next';
|
|
846
|
+
import { readDatabaseWebhook } from '@donotdev/supabase/server';
|
|
847
|
+
|
|
848
|
+
const LANGUAGE_ROUTING: LanguageRouting = ${JSON.stringify(t)};
|
|
849
|
+
|
|
850
|
+
/** Cached pages: static ones, entity ones with the table that fills their param */
|
|
851
|
+
const ROUTES: PublicRoute[] = ${JSON.stringify(e,null,2)};
|
|
852
|
+
|
|
853
|
+
export async function POST(request: Request): Promise<Response> {
|
|
854
|
+
return handleRevalidationWebhook(request, {
|
|
855
|
+
secret: process.env.${Te},
|
|
856
|
+
routes: ROUTES,
|
|
857
|
+
routing: LANGUAGE_ROUTING,
|
|
858
|
+
readChange: readDatabaseWebhook,
|
|
859
|
+
revalidatePath,
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
`},generateRevalidationRoute(r){this.options.routingMode==="app"&&this.appDependsOn("@donotdev/supabase")&&this.writeGeneratedFile(L.next.revalidateRoute,this.generateRevalidationContent(r),"revalidation route")}};var Tr={async generateAppRoutes(r){let e=this.generateAppRoutesContent(r.routes);this.writeGeneratedFile("src/app/routes.generated.ts",e,"app routes index")},generateAppRoutesContent(r){let e=r.map(t=>{let n=t.componentName||this.pathToComponentName(t.path),s=t.relativePath||t.file;if(!s)return this.logger.warn(`Route ${t.path} missing file path, skipping`),null;let o=s.replace(/\.tsx$/,"").replace(/^src\//,"../");return` {
|
|
863
|
+
path: '${t.path}',
|
|
864
|
+
component: lazy(() => import('${o}')),
|
|
865
|
+
auth: ${JSON.stringify(t.auth)},
|
|
866
|
+
meta: ${JSON.stringify(t.meta)}
|
|
867
|
+
}`}).filter(t=>t!==null).join(`,
|
|
874
868
|
`);return`// Auto-generated app routes by @donotdev/config
|
|
875
869
|
// Generated at ${new Date().toISOString()}
|
|
876
870
|
|
|
877
871
|
import { lazy } from 'react';
|
|
878
872
|
|
|
879
873
|
export const appRoutes = [
|
|
880
|
-
${
|
|
874
|
+
${e}
|
|
881
875
|
];
|
|
882
876
|
|
|
883
877
|
export const routeManifest = {
|
|
884
|
-
totalRoutes: ${
|
|
878
|
+
totalRoutes: ${r.length},
|
|
885
879
|
routingMode: 'app',
|
|
886
880
|
generatedAt: '${new Date().toISOString()}'
|
|
887
881
|
};
|
|
888
882
|
|
|
889
883
|
export default appRoutes;
|
|
890
|
-
`}async generatePagesRoutes(
|
|
891
|
-
auth: ${JSON.stringify(
|
|
892
|
-
meta: ${JSON.stringify(
|
|
893
|
-
file: '${
|
|
884
|
+
`},async generatePagesRoutes(r){let e=this.generatePagesRoutesContent(r.routes);this.writeGeneratedFile("src/pages/routes.generated.ts",e,"pages routes index")},generatePagesRoutesContent(r){let e=r.map(t=>` '${t.path}': {
|
|
885
|
+
auth: ${JSON.stringify(t.auth)},
|
|
886
|
+
meta: ${JSON.stringify(t.meta)},
|
|
887
|
+
file: '${t.file}'
|
|
894
888
|
}`).join(`,
|
|
895
889
|
`);return`// Auto-generated pages routes by @donotdev/config
|
|
896
890
|
// Generated at ${new Date().toISOString()}
|
|
897
891
|
|
|
898
892
|
export const pageRoutes = {
|
|
899
|
-
${
|
|
893
|
+
${e}
|
|
900
894
|
};
|
|
901
895
|
|
|
902
896
|
export const routeManifest = {
|
|
903
|
-
totalRoutes: ${
|
|
897
|
+
totalRoutes: ${r.length},
|
|
904
898
|
routingMode: 'pages',
|
|
905
899
|
generatedAt: '${new Date().toISOString()}'
|
|
906
900
|
};
|
|
907
901
|
|
|
908
902
|
export default pageRoutes;
|
|
909
|
-
`}pathToComponentName(
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
}
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
903
|
+
`},pathToComponentName(r){return r.split("/").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")+"Page"}};import{existsSync as _a,readdirSync as ka}from"node:fs";import{join as Da}from"node:path";var Aa=/^---\r?\n([\s\S]*?)\r?\n---/,Na=/^\r?\n/;function Or(r){let e=r.match(Aa);if(!e)return{meta:{},content:r};let t={};for(let n of(e[1]??"").split(`
|
|
904
|
+
`)){let s=n.indexOf(":");if(s===-1)continue;let o=n.slice(0,s).trim();if(!o)continue;let a=n.slice(s+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),t[o]=a}return{meta:t,content:r.slice(e[0].length).replace(Na,"")}}function Fr(r){return r.filter(e=>e.endsWith("_en.md")).sort()}function Ir(r){let e=Da(r,"src","content","blog");try{return _a(e)?Fr(ka(e)).length>0:!1}catch{return!1}}function Lr(r,e){let t=D.getInstance(),n=t.resolvePath("src/content/blog",r);try{if(!t.pathExists(n))return[];let s=Fr(t.readdirSync(n));if(s.length===0)return[];let o=[];for(let a of s){let i=t.resolvePath(a,n),l=t.readSync(i,{format:"text"}),u=a.replace(/_en\.md$/,""),{meta:c}=Or(l),p=c.date;if(!p)try{p=t.statSync(i).mtime.toISOString().split("T")[0],e.warn(`Blog post "${u}" has no frontmatter date, using file mtime (${p})`)}catch{p=new Date().toISOString().split("T")[0],e.warn(`Blog post "${u}" has no date and file stat failed, using today`)}o.push({slug:u,title:c.title||u,description:c.description||"",date:p,tags:c.tags?c.tags.split(",").map(d=>d.trim()):[],image:c.image||null})}return o.sort((a,i)=>i.date.localeCompare(a.date)),e.info(`\u{1F4DD} Discovered ${o.length} blog post(s) in src/content/blog/`),o}catch(s){return e.debug(`Blog content discovery skipped: ${s.message}`),[]}}function J(r){return r?r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}function Mr(r){return r?r.replace(/\]\]>/g,"]]]]><![CDATA[>"):""}var Br=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]"]);function Ta(r,e){let t;try{let n=new URL(r);if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error;t=n.hostname}catch{throw new Error(`[dndev] SEO: base URL "${r}" is not an absolute http(s) URL. Set ${e} (or seo.baseUrl) to the production URL.`)}if(Br.has(t)||t.endsWith(".localhost"))throw new Error(`[dndev] SEO: deploy build with base URL "${r}". The sitemap, robots.txt and llms.txt would publish local URLs. Set ${e} (or seo.baseUrl) to the production URL in the build environment.`)}var Oa="DNDEV_DEPLOY";function Qe(r=process.env){let e=r.CI;return r[Oa]==="1"||r.VERCEL==="1"||e!==void 0&&e!==""&&e!=="false"&&e!=="0"}var Ur=new Set;function Gr(r,e,t,n=process.env){if(Qe(n)){if(!r)throw new Error(`[dndev] SEO: deploy build without ${e}. The sitemap, robots.txt, llms.txt and canonical URLs need the production URL: set ${e} (or seo.baseUrl) in the build environment.`);return Ta(r,e),r}let s=o=>{Ur.has(o)||(Ur.add(o),t.warn(o))};return!r||!Fa(r)?(s(`[dndev] Local build without a usable ${e}${r?` ("${r}")`:""}: no sitemap.xml, llms.txt, robots.txt, rss.xml, canonical URLs or record pages. Set ${e} to build them.`),null):(Ia(r)||s(`[dndev] Local build: sitemap.xml, llms.txt, canonical URLs and record pages carry ${r} (${e}). A deploy build (dndev deploy, Vercel, CI) needs the production URL.`),r)}async function $e(r,e,t,n=process.env){try{return await e(),!0}catch(s){if(ce(s))throw s;let o=`${r.join(", ")} not written: ${s.message}`;if(Qe(n))throw C("dndev-seo",`${o}. A deploy build publishes every SEO file.`,"seo-generation-failed",{files:r});return t.warn(`[dndev] Local build: ${o} (a deploy build fails on it).`),!1}}function Fa(r){try{let{protocol:e}=new URL(r);return e==="https:"||e==="http:"}catch{return!1}}function Ia(r){let{hostname:e}=new URL(r);return!Br.has(e)&&!e.endsWith(".localhost")}var Ut=Object.freeze(["/api"]),jr=new Set(["/404","/not-found","/500","/error"]);function et(r){return r.auth&&r.auth!==!1||jr.has(r.path)||jr.has(r.meta?.route)?!1:r.meta?.seo?.noindex!==!0}function Gt(r){return typeof r.path=="string"&&r.path.split("/").includes("*")}function zr(r){if(!(typeof r.path!="string"||!r.path.includes(":"))&&et(r))return r.meta?.entity||void 0}function tt(r){if(typeof r.path!="string"||r.path.includes("*")||q(r.path).length!==1)return null;let e=zr(r);return e?{path:r.path,collection:e}:null}function La(r=[]){return{totalRoutes:r.length,publicRoutes:r.filter(e=>!e.auth||e.auth===!1).length,protectedRoutes:r.filter(e=>e.auth&&e.auth.required).length}}var Ze=class{constructor(e={}){let{debug:t=!1,generateRobotsTxt:n=!0,baseUrl:s,siteName:o,crawlDelay:a=1,aiCrawlers:i="recommended",routes:l={},...u}=e;if(!s||!o)throw new Error("SEOGenerator requires baseUrl and siteName options");this.options={debug:t,generateRobotsTxt:n,baseUrl:s,siteName:o,crawlDelay:a,aiCrawlers:i,routes:l,blogPath:"/blog",...u},this.appRoot=u.appRoot||null,this.logger=ae("SEO Generator",e.debug,e.verbose)}async generateSEOFiles(e,t,n){let s={routes:e.routes||[],baseUrl:this.options.baseUrl,siteName:this.options.siteName},o={robotsTxt:null,rss:null,manifest:null};return this.options.generateRobotsTxt&&(o.robotsTxt=await this.generateRobotsTxt(s,t)),n.length>0&&(o.rss=await this.generateRSSFeed(n,t)),o.manifest=await this.generateManifest(s,t),o}async generateRobotsTxt(e,t){let n=this.options.shellPath?[...Ut,this.options.shellPath]:Ut,s=this.generateRobotsTxtContent({disallowedPaths:n,sitemap:`${this.options.baseUrl}/sitemap.xml`,crawlDelay:this.options.crawlDelay});return await t("robots.txt",s),{fileName:"robots.txt",content:s,disallowedPaths:n.length}}getSitemapRoutes(e,t=[]){let{blogPath:n}=this.options,s=[];for(let o of e||[]){if(!et(o)||typeof o.path!="string"||Gt(o))continue;let a=o.path===n||o.path.startsWith(`${n}/`);if(!(t.length>0&&a))if(o.path.includes(":")){if(a)continue;let i=zr(o);s.push({path:o.path,...i&&{collection:i}})}else s.push({path:o.path})}if(t.length>0){s.push({path:n,priority:.7,...t[0]?.date&&{lastModified:t[0].date}});for(let o of t)s.push({path:`${n}/${o.slug}`,priority:.6,changeFrequency:"monthly",...o.date&&{lastModified:o.date}})}return s}async generateManifest(e,t){let n={...La(e.routes),baseUrl:this.options.baseUrl,siteName:this.options.siteName,generatedAt:new Date().toISOString()},s=JSON.stringify(n,null,2);return await t("seo-manifest.json",s),{fileName:"seo-manifest.json",content:s,manifest:n}}generateRobotsTxtContent(e={}){let{allowedPaths:t=["/"],disallowedPaths:n=Ut,sitemap:s,crawlDelay:o}=e,a=u=>u?u==="*"?"*":u.startsWith("/")?u:`/${u}`:"/",i=["User-agent: *",...n.map(u=>`Disallow: ${a(u)}`),...t.map(u=>`Allow: ${a(u)}`)];o&&i.push(`Crawl-delay: ${o}`),s&&i.push(`Sitemap: ${s}`);let l=this.options.aiCrawlers;return l&&l!==!1&&(i.push(""),i.push(...Ma(l))),i.join(`
|
|
905
|
+
`)}discoverBlogPosts(){return this.appRoot?Lr(this.appRoot,this.logger):[]}async generateRSSFeed(e,t){let n=e.map(o=>` <item>
|
|
906
|
+
<title><![CDATA[${Mr(o.title)}]]></title>
|
|
907
|
+
<link>${J(this.options.baseUrl)}${J(this.options.blogPath)}/${J(o.slug)}</link>
|
|
908
|
+
<guid>${J(this.options.baseUrl)}${J(this.options.blogPath)}/${J(o.slug)}</guid>
|
|
909
|
+
<description><![CDATA[${Mr(o.description)}]]></description>
|
|
910
|
+
<pubDate>${o.date?new Date(o.date).toUTCString():""}</pubDate>${o.tags.length?`
|
|
911
|
+
<category>${J(o.tags.join(", "))}</category>`:""}${o.image?`
|
|
912
|
+
<enclosure url="${J(this.options.baseUrl)}${J(o.image)}" type="image/png" length="0"/>`:""}
|
|
913
|
+
</item>`).join(`
|
|
914
|
+
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
915
|
+
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
|
916
|
+
<channel>
|
|
917
|
+
<title>${J(this.options.siteName)}</title>
|
|
918
|
+
<link>${J(this.options.baseUrl)}${J(this.options.blogPath)}</link>
|
|
919
|
+
<description>${J(this.options.siteName)} Blog</description>
|
|
920
|
+
<language>en</language>
|
|
921
|
+
<atom:link href="${J(this.options.baseUrl)}/rss.xml" rel="self" type="application/rss+xml"/>
|
|
922
|
+
${n}
|
|
923
|
+
</channel>
|
|
924
|
+
</rss>`;return await t("rss.xml",s),{fileName:"rss.xml",content:s,postCount:e.length}}},jt=["GPTBot","Google-Extended","CCBot","ClaudeBot"],Bt=["OAI-SearchBot","ChatGPT-User","Claude-SearchBot","Claude-User","PerplexityBot"];function Ma(r){let e=["# AI Crawler Management"];if(r==="block-all"){for(let t of[...jt,...Bt])e.push(`User-agent: ${t}`,"Disallow: /","");return e}if(r==="allow-all"){for(let t of[...jt,...Bt])e.push(`User-agent: ${t}`,"Allow: /","");return e}for(let t of jt)e.push(`User-agent: ${t}`,"Disallow: /","");for(let t of Bt)e.push(`User-agent: ${t}`,"Allow: /","");return e}var Hr={prerendersRecords(){let r=this.options.prerenderRecords??!0;if(typeof r=="boolean")return r;throw new Error(`appConfig.prerenderRecords must be true or false. Got ${JSON.stringify(r)}.`)},prerenderedRecordsRoute(r){return this.prerendersRecords()?tt(r):null},serverMetadataSource(r){return r.exportsGenerateMetadata?"page":this.isBlogPostRoute(r)?"blog":tt(r)?"entity":null},entityMetadataRoute(r){return this.serverMetadataSource(r)==="entity"?tt(r):null},assertServerMetadata(r){for(let e of r){if(e.exportsGenerateMetadata){if(this.isBlogPostRoute(e))throw new Error(`[dndev] ${e.file} exports \`generateMetadata\`, but blog post pages get theirs generated from the post's frontmatter (a second one would conflict). Remove it from the page.`);if(this.isClientComponent(e.file))throw new Error(`[dndev] ${e.file} exports \`generateMetadata\` but is a client module ('use client'). Next reads generateMetadata only from server modules, so the page would ship without its title and description. Keep the page module a server component (no 'use client') that exports generateMetadata and renders a 'use client' component, or remove generateMetadata.`);continue}let t=this.entityMetadataRoute(e);if(t){if(!this.appDependsOn("entities"))throw new Error(`[dndev] ${e.path} is an entity page ("${t.collection}" records): its metadata derives from the entity definition, but the app does not depend on an \`entities\` package. Add the entity to the app's \`entities\` package, mark the page \`seo: { noindex: true }\`, or export \`generateMetadata\` from a server page module.`);this.entityMetadataExport(e,this.entityPageReader(e,"site"))}}},entityPageReader(r,e){let t=e==="site"?this.prerenderedRecordsRoute(r):null,n=this.entityMetadataRoute(r),s=n??t;if(!s)return{imports:"",setup:"",expr:null,schemas:null,named:{}};let o=[n&&"entity pages read their record on the server (metadata, JSON-LD, 404)",t&&"entity pages prerender their published records at build"].filter(Boolean).join("; "),a=n?"Mark the page `seo: { noindex: true }`, or export `generateMetadata` from a server page module and set `appConfig.prerenderRecords: false`.":"Set `appConfig.prerenderRecords: false` to render them on their first request.";return this.serverCrudReader([s],o,a)},staticParamsExport(r,e){if(!this.convertRouteToAppPath(r.path).includes("["))return{named:{},code:""};let t=this.prerenderedRecordsRoute(r);return t?{named:{"@donotdev/core/next":["listStaticParams"]},code:`
|
|
917
925
|
// Every published "${t.collection}" record is prerendered at build (the sitemap's records,
|
|
918
926
|
// public reader). A record published later renders on its first request. All are cached
|
|
919
927
|
// like the static pages (ISR). Opt out: appConfig.prerenderRecords = false.
|
|
920
928
|
export async function generateStaticParams() {
|
|
921
|
-
return listStaticParams(${JSON.stringify(t)}, ${
|
|
929
|
+
return listStaticParams(${JSON.stringify(t)}, ${e.expr}, HIDDEN_STATUSES, ${e.schemas});
|
|
922
930
|
}
|
|
923
|
-
`}
|
|
924
|
-
//
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
931
|
+
`}:{named:{},code:`
|
|
932
|
+
// Each URL renders on its first request, then is cached like the static pages (ISR)
|
|
933
|
+
export function generateStaticParams() {
|
|
934
|
+
return [];
|
|
935
|
+
}
|
|
936
|
+
`}},entityMetadataExport(r,e){let t=this.entityMetadataRoute(r);if(!t)return null;let{defaultLanguage:n,languages:s}=this.options;if(!n)throw new Error("Route handler: languages not set before page generation (runDiscoveries calls useLanguages)");let[o]=q(t.path),a=this.isMultilingual(),i=r.meta?.seo?.type??"website",l=this.calculateRelativeImportPath("src/config/dndev-config-i18n.js",r.path),u=this.options.siteName;if(!u)throw new Error(`[dndev] ${r.path}: entity page titles end with the site name. Set appConfig.app.name (or appConfig.seo.siteName).`);return{vendorImports:`import type { Metadata } from 'next';
|
|
937
|
+
import { notFound } from 'next/navigation';
|
|
938
|
+
import { cache } from 'react';
|
|
939
|
+
`,named:{"@donotdev/core/server":["buildBreadcrumbJsonLd","buildProductJsonLd","deriveEntitySeo","languageUrl"],"@donotdev/core/next":["appBaseUrl","entityPageSeo","jsonLdScript","readEntityPageRecord"],"@donotdev/core/rsc":["useTranslation"]},typeImports:`import type { LanguageRouting } from '@donotdev/core/server';
|
|
940
|
+
`,appImports:`// Server graph: the translations the server useTranslation reads
|
|
941
|
+
import '${l}';
|
|
942
|
+
`,code:`
|
|
943
|
+
// Page identity from the "${t.collection}" record of this URL (server, no app code): title,
|
|
944
|
+
// description, Open Graph, Twitter card, ${i==="product"?"Product JSON-LD, ":""}in the URL's language. Canonical, og:url
|
|
945
|
+
// and hreflang come from AutoMetaTags. No public record (missing, hidden status): HTTP 404.
|
|
946
|
+
const ROUTE = ${JSON.stringify(t)};
|
|
947
|
+
|
|
948
|
+
const LANGUAGE_ROUTING: LanguageRouting = ${JSON.stringify({languages:s,defaultLanguage:n})};
|
|
949
|
+
|
|
950
|
+
// next.config trailingSlash: page URLs end with \`/\` when true
|
|
951
|
+
const TRAILING_SLASH = ${JSON.stringify(this.options.trailingSlash)};
|
|
952
|
+
|
|
953
|
+
type Params = Promise<{ ${a?"lang: string; ":""}${o}: string }>;
|
|
954
|
+
|
|
955
|
+
// One read per request: generateMetadata and the page share it (React cache)
|
|
956
|
+
const pageSeo = cache(async (language: string, value: string) => {
|
|
957
|
+
const record = await readEntityPageRecord(ROUTE, value, ${e.expr}, HIDDEN_STATUSES, ${e.schemas});
|
|
958
|
+
if (!record) return null;
|
|
959
|
+
return entityPageSeo(record, {
|
|
960
|
+
route: ROUTE,
|
|
961
|
+
value,
|
|
962
|
+
language,
|
|
963
|
+
routing: LANGUAGE_ROUTING,
|
|
964
|
+
baseUrl: appBaseUrl(process.env.NEXT_PUBLIC_APP_URL),
|
|
965
|
+
trailingSlash: TRAILING_SLASH,
|
|
966
|
+
siteName: ${JSON.stringify(u)},
|
|
967
|
+
defaultImage: ${JSON.stringify(this.defaultImage())},
|
|
968
|
+
type: ${JSON.stringify(i)},
|
|
969
|
+
entities,
|
|
970
|
+
translate: (namespaces) => useTranslation(namespaces, { language }).t,
|
|
971
|
+
deriveEntitySeo,
|
|
972
|
+
buildProductJsonLd,
|
|
973
|
+
languageUrl,
|
|
974
|
+
buildBreadcrumbJsonLd,
|
|
975
|
+
});
|
|
976
|
+
});
|
|
930
977
|
|
|
931
|
-
|
|
978
|
+
/** The URL's page identity; \`notFound()\` (HTTP 404) when no public record matches. */
|
|
979
|
+
async function requireSeo(params: Params) {
|
|
980
|
+
const { ${a?"lang, ":""}${o} } = await params;
|
|
981
|
+
const seo = await pageSeo(${a?"lang":JSON.stringify(n)}, ${o});
|
|
982
|
+
if (!seo) notFound();
|
|
983
|
+
return seo;
|
|
984
|
+
}
|
|
932
985
|
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
986
|
+
export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
|
|
987
|
+
return (await requireSeo(params)).metadata;
|
|
988
|
+
}
|
|
989
|
+
`,render:`const seo = await requireSeo(props.params);
|
|
990
|
+
return (
|
|
991
|
+
<>
|
|
992
|
+
{PAGE}
|
|
993
|
+
{seo.ogType && <meta property="og:type" content={seo.ogType} />}
|
|
994
|
+
{seo.jsonLd && (
|
|
995
|
+
<script
|
|
996
|
+
type="application/ld+json"
|
|
997
|
+
dangerouslySetInnerHTML={{ __html: jsonLdScript(seo.jsonLd) }}
|
|
998
|
+
/>
|
|
999
|
+
)}
|
|
1000
|
+
{seo.breadcrumb && (
|
|
1001
|
+
<script
|
|
1002
|
+
type="application/ld+json"
|
|
1003
|
+
dangerouslySetInnerHTML={{ __html: jsonLdScript(seo.breadcrumb) }}
|
|
1004
|
+
/>
|
|
1005
|
+
)}
|
|
1006
|
+
</>
|
|
1007
|
+
);`}}};var Ua=/^[A-Za-z_$][\w$]*$/,ja=/^(?:'[^'\\]*'|"[^"\\]*"|`[^`\\$]*`|-?\d[\w.]*|null|undefined|true|false)$/;function Ba(r,e){let t=0;for(let n=e;n<r.length;n++){let s=r[n];if(s==="'"||s==='"'||s==="`"){for(n++;n<r.length&&r[n]!==s;n++)r[n]==="\\"&&n++;continue}if(t===0&&(s===","||s==="/"&&/[/*]/.test(r[n+1]??"")))return n;if("([{".includes(s))t++;else if(")]}".includes(s)){if(t===0)return n;t--}}return r.length}function Ga(r){let e=/(^|[{,\s])entity\s*:\s*/gm,t="",n=0,s;for(;s=e.exec(r);){let o=s.index+s[0].length,a=Ba(r,o),i=r.slice(o,a).trimEnd();if(!i)continue;let l=ja.test(i)?i:Ua.test(i)?`{ identifier: '${i}' }`:`{ expression: ${JSON.stringify(i)} }`;t+=r.slice(n,o)+l,n=o+i.length,e.lastIndex=n}return t+r.slice(n)}function za(r){let e=r instanceof Error?r.message:String(r),t=/^(\S+) is not defined$/.exec(e)?.[1];return t?`\`${t}\` is not a literal value (an import, a variable or a call)`:`it is not a plain object literal (${e})`}function Wr(r,e="unknown"){let t=/export\s+const\s+meta\s*[^=]*=\s*(\{[\s\S]*?\});/,n=r.match(t);if(!n)return null;let s=n[1];s=s.replace(/icon:\s*<(\w+)[\s\/][^>]*\/?>/g,(i,l)=>`icon: '${l}'`),s=Ga(s);let o=/(?:export\s+)?const\s+(\w+)\s*=\s*['"]([^'"]+)['"]/g;[...r.matchAll(o)].forEach(i=>{let l=i[1],u=i[2];s=s.replace(new RegExp(`\\b${l}\\b`,"g"),`'${u}'`)});try{return Function(`return ${s}`)()}catch(i){throw C("dndev-routes",`${e}: PageMeta cannot be read at build: ${za(i)}. Without it the page would lose its route, auth and seo. The build reads PageMeta statically: write every value as a literal in the object (strings, numbers, booleans, null, arrays and objects of those, icon: <Icon />, a string constant declared in the page file: const NAMESPACE = 'home'), except entity, the defineEntity identifier imported from 'entities'. Example: auth: { required: true, role: 'admin' } instead of auth: ADMIN_ONLY.`,"invalid-configuration")}}function qr(r){return/^[ \t]*export\s+(?:(?:async\s+)?function\s*\*?\s*generateMetadata\b|(?:const|let)\s+generateMetadata\b|\{[^}]*\bgenerateMetadata\b[^}]*\})/m.test(r)}var xe=null,Jr=null;function Ha(r){let t=(r.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return t.charAt(0).toUpperCase()+t.slice(1)}function Wa(r){let e=r.meta?.signedInRedirect;if(e!==void 0){if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//")||e.startsWith("/\\"))throw C("dndev-routes",`${r.file}: PageMeta signedInRedirect must be an app path starting with '/' (got ${JSON.stringify(e)}). Example: export const meta: PageMeta = { signedInRedirect: '/catalogue' };`,"invalid-configuration");if(e.split(/[?#]/)[0]===r.path)throw C("dndev-routes",`${r.file}: PageMeta signedInRedirect points at the page itself (${e}): signed-in visitors would loop. Use another page.`,"invalid-configuration")}}function qa(r,{pageGenerateMetadata:e=!1}={}){if(!r.path.split("/").some(n=>n.startsWith(":"))||Gt(r)||!et(r)||r.meta?.entity||r.metaExport?.namespace==="blog"||e&&r.exportsGenerateMetadata)return;let t=["declare the record entity it shows: import { productEntity } from 'entities'; then entity: productEntity in its PageMeta (title, description and image from the record)",...e?["export Next's generateMetadata from the page module (a server module, no 'use client')"]:[],"keep it out of search engines: seo: { noindex: true } in its PageMeta"];throw C("dndev-routes",`${r.file}: public dynamic route ${r.path} has no per-URL SEO: every URL would get the same title and description (PageMeta + i18n), duplicate pages for search engines. Fix, one of:
|
|
1008
|
+
`+t.map((n,s)=>` ${s+1}. ${n}`).join(`
|
|
1009
|
+
`),"invalid-configuration")}var Pe=class extends ee{constructor(e,t={}){super(e,{additionalPatterns:[],...t}),this.routes=[],this.errors=[],this.source="auto-discovery"}_getDiscoveryType(){return"Route"}async _getPatterns(){return await this.pathResolver.resolvePatterns("routes")}_getPatternType(){return"routes"}async _processFiles(e){let t=this.pathResolver.getAppRoot(),n=process.env.DNDEV_BUILD_ID;if(xe&&Jr===n)return this.logger.debug("Using cached route discovery results"),this.routes=xe.routes,this.errors=xe.errors,this.source=xe.source,this.entityResolver=xe.entityResolver,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length};if(this.logger.debug("Route discovery mode: AUTO-DISCOVERY"),this.logger.debug(`App root: ${t}`),this.options.debug){let s=e?.consumerFiles?.length||0;this.logger.debug(`\u{1F50D} Route discovery: Scanning ${s} files in ${t}`);let o=await this._getPatterns();this.logger.debug(`Patterns: ${JSON.stringify(o)}`)}return await this._performAutoDiscovery(e,t),this.options.debug&&this.logger.debug(`\u{1F50D} Route discovery: Found ${this.routes.length} routes`),this.routes.length===0&&this.logger.warn("\u26A0\uFE0F No routes discovered! Check that pages exist in src/pages/"),xe={routes:this.routes,errors:this.errors,source:this.source,entityResolver:this.entityResolver},Jr=process.env.DNDEV_BUILD_ID,{routes:this.routes,errors:this.errors,source:this.source,totalFiles:this.routes.length}}_getEmptyResult(){return{routes:[],errors:[],source:"empty",totalFiles:0,timestamp:Date.now()}}_getDiscoverySummary(){return`${this.cache?.routes?.length||0} routes discovered via ${this.cache?.source||"unknown"}`}getEntityResolver(){return this.entityResolver??=ke(this.pathResolver.getAppRoot()),this.entityResolver}async discoverRoutes(e=!1){return await this.discover(e)}getRoutes(){return this.cache?.routes||[]}async _performAutoDiscovery(e,t){let{consumerFiles:n}=e;this.entityResolver=ke(t);let s=await this._batchProcessFiles(n,u=>this._analyzePageFile(u,t)),o=await this._scanAdditionalPatterns(t),a=await this._batchProcessFiles(o,u=>this._analyzePageFile(u,t)),i=[...s,...a];this.logger.debug(`Auto-discovering from ${n.length} app + ${o.length} additional files`),this.routes=i.filter(u=>u.path==="home"||u.path==="/home"?(this.logger.debug(`Filtered reserved route: ${u.path} - Use root "/" instead (${u.file})`),!1):!0);let l=new Map;for(let u of this.routes){let c=u.path;if(l.has(c)){let p=l.get(c);throw C("dndev-routes",`${u.file}: route ${c} is also the route of ${p.file}: two pages cannot share a URL. Give one of them another path with a PageMeta route override, e.g. export const meta: PageMeta = { route: '/custom-path' };`,"invalid-configuration")}l.set(c,u),Wa(u),qa(u,{pageGenerateMetadata:this.options.pageGenerateMetadata===!0})}this.logger.debug(`Auto-discovered ${this.routes.length} routes from ${n.length+o.length} files`)}async _scanAdditionalPatterns(e){let t=this.options.additionalPatterns.map(n=>this.pathResolver.resolveAppPath(n));if(t.length===0)return[];try{let{consumerFiles:n}=await this.pathResolver.resolveFiles({consumer:t,framework:[]},"routes");return n}catch(n){return this.logger.debug(`Error scanning additional patterns: ${n.message}`),[]}}async _analyzePageFile(e,t){let n=await this.pathResolver.read(e.absolutePath,{format:"text"});if(!n)return null;let s=e.relativePath,o="/src/"+s.replace(/\\/g,"/");o=o.replace(/src\/src\//g,"src/").replace(/src\/src\//g,"src/");let a=this._extractMetaExport(n,s),i=Ha(o),u=i===Ae.HOMEPAGE_COMPONENT?Ae.HOMEPAGE_PATH:this._resolveRoutePath(a,s,e.absolutePath),c=this._extractPageMeta(s),p=await Qn(a,n,s,this.entityResolver),{entity:d,action:f,...h}=a||{};return{path:u,component:i,importPath:o,auth:a?.auth||!1,meta:{...c,...h,...p&&{entity:p},action:c.action},metaExport:a&&{...a,...p&&{entity:p}},exportsGenerateMetadata:qr(n),file:s}}_extractMetaExport(e,t){try{let n=Wr(e,t);return n?(this.logger.debug(`Extracted meta export from ${t}: ${JSON.stringify(n)}`),n):null}catch(n){if(ce(n))throw n;return this.logger.debug(`Error parsing meta export from ${t}: ${n.message}`),null}}_generateRoutePath(e){let t=e.replace(/\.tsx$/,"").replace(/Page$/,"").replace(/^src\//,"").replace(/^pages\//,"").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return(t.endsWith("/index")||t==="index")&&(t=t.replace(/\/index$/,"")||"/"),t==="/"?"/":"/"+t.replace(/\/+/g,"/")}_resolveRoutePath(e,t,n){if(!e?.route)return this._generateRoutePath(t);if(typeof e.route=="string"){let s=e.route.trim();return s==="/"?"/":(s=s.replace(/\/+/g,"/"),s.startsWith("/")||(s="/"+s),s)}if(typeof e.route=="object"&&e.route!==null){let s=this._generateRoutePath(t),o=e.route.params;if(Array.isArray(o)&&o.length>0){let a=o.map(i=>`:${i}`).join("/");return`${s}/${a}`}return s}return this.logger.warn(`Invalid route format in ${n}. Use string format: route: "/path/:param" or object format: route: { params: ['id'] }`),this.logger.debug(`Falling back to auto-generated path for ${n}`),this._generateRoutePath(t)}_extractPageMeta(e){let t=e.split("/").pop()?.replace(".tsx","")||"",n=t.replace(/Page$/,"");n=n.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z])([A-Z])/g,"$1 $2").trim(),n=n.charAt(0).toUpperCase()+n.slice(1);let s=e.split("/"),o=null;return s.length>1&&(t.includes("List")?o="list":t.includes("Form")||t.includes("Create")||t.includes("Edit")?o="form":(t.includes("Detail")||t.includes("View"))&&(o="detail")),{title:n,action:o,file:e}}};var nt=class extends H{constructor(e={}){super(Pe,e),this.rendersSessionTree=!1,this.appRouteSegments=[],this.i18n=null,this.fonts=null}getHandlerDefaults(){return{routingMode:"app",generateMiddleware:!0,generateAppPages:!0,proxyPath:L.next.proxy,manifestPath:L.next.routeManifest,languages:[],defaultLanguage:null,trailingSlash:!1,siteName:null,defaultImage:void 0,defaultNamespace:void 0}}useLanguages({languages:e,defaultLanguage:t}){if(e.length>1&&!e.includes(t))throw new Error(`i18n fallbackLanguage "${t}" has no translations among [${e.join(", ")}]: it is the language served at the root URL. Add its locale files or set i18n.fallbackLanguage to one of them.`);this.options.languages=e,this.options.defaultLanguage=t}useI18n(e){this.i18n=e}useFonts(e){this.fonts=e}isMultilingual(){return this.options.languages.length>1}defaultImage(){return this.options.defaultImage||Ne}defaultNamespace(){return this.options.defaultNamespace||"home"}rootDir(){return this.isMultilingual()?"/[lang]":""}treeDir(e="site"){return`${this.rootDir()}/${e==="session"?Z.sessionSegment:Z.siteGroup}`}appDirFor(e,t="site"){return`${this.treeDir(t)}${this.convertRouteToAppPath(e)}`}appImport(e,t){let n=e.split("/").filter(Boolean).length;return n===0?`./${t}`:`${"../".repeat(n)}${t}`}createDiscovery(e){return new e(this.pathResolver,{...this.options,...Ct})}getHandlerName(){return"Route"}logDiscoveryResults(e){let t=e.routes||[],n=t.filter(o=>o.auth&&o.auth.required).length,s=t.length;this.logger.info(`\u{1F6E3}\uFE0F Routes: ${s} found${n>0?`, ${n} are authguarded`:""}`)}getEntityResolver(){return this.discovery.getEntityResolver()}async getDiscoveryData(){return await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/routes",destination:"/api/routes/route"}],fallback:[]}}createManifestContent(e){return{routes:e.routes.map(t=>({path:t.path,auth:t.auth,meta:t.meta})),source:e.source,totalRoutes:e.routes.length,generatedAt:new Date().toISOString(),routingMode:this.options.routingMode}}getGenerationSummary(e){return`${e.routes.length} routes for Next.js ${this.options.routingMode} router`}generateConfigContent(e){let t=e.routes||[];this.options.generateAppPages&&this.assertServerMetadata(t);let n={totalRoutes:t.length,authRequired:t.filter(s=>s.auth&&s.auth.required).length,publicRoutes:t.filter(s=>!s.auth||s.auth===!1).length,source:e.source,hasBlogFeed:Ir(this.pathResolver.getAppRoot()),trailingSlash:this.options.trailingSlash,serverMetadataPaths:this.options.generateAppPages?t.filter(s=>this.serverMetadataSource(s)).map(s=>s.path):[],recordBreadcrumbPaths:this.options.generateAppPages?t.filter(s=>this.entityMetadataRoute(s)).map(s=>s.path):[],generatedAt:new Date().toISOString()};return`// Auto-generated DnDev config by @donotdev/config
|
|
1010
|
+
// Generated at: ${new Date().toISOString()}
|
|
1011
|
+
// Populates _DNDEV_CONFIG_.routes with discovery results
|
|
937
1012
|
|
|
938
|
-
const
|
|
1013
|
+
const routeMapping = ${JSON.stringify(t,null,2)};
|
|
939
1014
|
|
|
940
|
-
|
|
941
|
-
const ROUTES: PublicRoute[] = ${JSON.stringify(t,null,2)};
|
|
1015
|
+
const routeManifest = ${JSON.stringify(n,null,2)};
|
|
942
1016
|
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
1017
|
+
// Populate unified DnDev config for runtime access (universal CSR/SSR)
|
|
1018
|
+
if (typeof globalThis !== 'undefined') {
|
|
1019
|
+
if (!globalThis._DNDEV_CONFIG_) {
|
|
1020
|
+
globalThis._DNDEV_CONFIG_ = {
|
|
1021
|
+
platform: 'nextjs',
|
|
1022
|
+
mode: typeof process !== 'undefined' && process.env.NODE_ENV === 'production' ? 'production' : 'development',
|
|
1023
|
+
version: '1.0.0',
|
|
1024
|
+
context: typeof window !== 'undefined' ? 'client' : 'server',
|
|
1025
|
+
timestamp: Date.now(),
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
globalThis._DNDEV_CONFIG_.${Y.routes} = {
|
|
1029
|
+
mapping: routeMapping,
|
|
1030
|
+
manifest: routeManifest,
|
|
1031
|
+
};
|
|
951
1032
|
}
|
|
952
|
-
`}generateRevalidationRoute(e){this.options.routingMode==="app"&&this.appDependsOn("@donotdev/supabase")&&this.writeGeneratedFile(F.next.revalidateRoute,this.generateRevalidationContent(e),"revalidation route")}hasDynamicSegment(e){return e.includes(":")||e.includes("[")}extractDynamicParam(e){let t=e.match(/:([a-zA-Z0-9_]+)/);if(t)return t[1];let s=e.match(/\[([^\]]+)\]/);return s?s[1]:"slug"}generateMountedClientContent(e,t){return this.options.ssr?`// Generated by @donotdev/config - DO NOT EDIT
|
|
953
|
-
// This file will be regenerated when src/pages changes
|
|
954
|
-
'use client';
|
|
955
1033
|
|
|
956
|
-
|
|
1034
|
+
// Export for compatibility
|
|
1035
|
+
export const routes = routeMapping;
|
|
1036
|
+
export const manifest = routeManifest;
|
|
1037
|
+
export default { routes: routeMapping, manifest: routeManifest };
|
|
1038
|
+
`}async generateSpecificFiles(e){await this.assertAppDocument(),this.options.generateMiddleware&&await this.generateMiddleware(e),await this.generateMetadataManifest(e),this.options.generateAppPages&&(await this.generateAppPageFiles(e),this.generateRevalidationRoute(e)),this.options.routingMode==="app"?await this.generateAppRoutes(e):await this.generatePagesRoutes(e)}async generateAppPageFiles(e){this.logger.debug("Starting app/** page file generation");try{await this.cleanGeneratedPageFiles(),this.generateRootLayout(),this.generateNotFoundPages();let t=this.rendersSessionTree?["site","session"]:["site"];for(let s of t)await this.generateTreeLayout(s);let n=0;for(let s of e.routes){let o=this.isSessionOnlyRoute(s)?"session":"site",a=await this.generateSingleAppPage(s,o);a&&n++,a&&o==="site"&&this.rendersSessionTree&&this.generateSessionPage(s)}this.logger.debug(`Successfully generated ${n}/${e.routes.length} app/** page files`)}catch(t){throw this.logger.error(`Failed to generate app/** files: ${t.message}`),t}}isSessionOnlyRoute(e){return this.rendersSessionTree&&!!this.normalizeAuth(e.auth)}generateSessionPage(e){let t=this.appDirFor(e.path,"session"),s=`${"../".repeat(t.split("/").filter(Boolean).length)}${this.appDirFor(e.path).slice(1)}/${U("page","tsx").replace(/\.tsx$/,"")}`,o=["default"];this.serverMetadataSource(e)&&o.push("generateMetadata"),this.writeGeneratedFile(`src/app${t}/${U("page","tsx")}`,`// Generated by @donotdev/config - DO NOT EDIT
|
|
1039
|
+
// Per-request render of ${e.path} (visitors with an auth cookie): same page as the cached one.
|
|
957
1040
|
|
|
958
|
-
export
|
|
959
|
-
|
|
1041
|
+
export { ${o.join(", ")} } from '${s}';
|
|
1042
|
+
`,`session page: ${t}`)}async cleanGeneratedPageFiles(){try{let e=this.pathResolver.getAppRoot(),t=[`src/app/**/${U("page","tsx")}`,`src/app/**/${U("layout","tsx")}`,`src/app/**/${U("not-found","tsx")}`,`src/app/${U("global-not-found","tsx")}`,"src/app/**/*PageClient.tsx"],n=await this.pathResolver._globWithNormalization(t,{cwd:e,absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0}),s=0;for(let o of n)if(await this.hasGenerationMarker(o))try{await this.pathResolver.remove(o),s++,this.logger.debug(`Cleaned generated file: ${o}`)}catch(a){this.logger.debug(`Could not clean file ${o}: ${a.message}`)}s>0&&this.logger.debug(`Cleaned ${s} existing generated page files`)}catch(e){this.logger.debug(`Error during cleanup: ${e.message}`)}}async generateSingleAppPage(e,t="site"){try{let n=this.appDirFor(e.path,t),s=`src/app${n}/${U("page","tsx")}`,o=this.pathResolver.resolveAppPath(s);if(this.pathResolver.pathExists(o)&&!await this.hasGenerationMarker(o))return this.logger.debug(`Skipping ${s} - user-created file detected (no generation marker)`),!1;let a={...e,filePath:e.file||e.filePath||this.pathResolver.resolveAppPath(e.file),relativePath:e.file||e.relativePath},i=this.generatePageFileContent(a,t);this.writeGeneratedFile(s,i,`app page: ${n}`);let l=this.extractComponentName(a.filePath),u=this.calculateRelativeImportPath(a.relativePath,a.path);return this.isBlogPostRoute(a)?this.writeGeneratedFile(`src/app${n}/BlogPostClient.tsx`,this.generateBlogPostClientContent(l,u),`app blog client: ${n}`):this.isClientComponent(a.filePath)&&this.writeGeneratedFile(`src/app${n}/${l}Client.tsx`,this.generateMountedClientContent(l,u),`app client wrapper: ${n}`),!0}catch(n){return this.logger.debug(`Error generating page for route ${e.path}: ${n.message}`),!1}}convertRouteToAppPath(e){if(e===Ae.HOMEPAGE_PATH)return"";let t=e;return t.startsWith("/")||(t="/"+t),t=t.replace(/\/+/g,"/"),t.split("/").map(n=>n.startsWith(":")?`[${n.slice(1)}]`:n==="*"?"[...slug]":n).join("/")}generatePageFileContent(e,t="site"){let n=this.extractComponentName(e.filePath),s=e.relativePath||e.file,o=this.calculateRelativeImportPath(s,e.path);if(this.isBlogPostRoute(e))return this.generateBlogPostRSCContent(e,n,o);let a=this.isClientComponent(e.filePath),i=this.normalizeAuth(e.auth)?e.auth:null,l=e.meta?.signedInRedirect??null,u=[...i?["AuthGuard"]:[],...l?["SignedInRedirect"]:[]],c=u.length?`import { ${u.join(", ")} } from '@donotdev/ui';
|
|
1043
|
+
`:"",p=this.entityPageReader(e,t),d=t==="site"?this.staticParamsExport(e,p):{named:{},code:""},f=this.entityMetadataExport(e,p),h={"@donotdev/core/server":p.expr?["HIDDEN_STATUSES"]:[],"@donotdev/core/next":[],"@donotdev/core/rsc":[]};for(let v of[d.named,f?.named??{},p.named])for(let[x,O]of Object.entries(v))h[x].push(...O);let m=Object.entries(h).filter(([,v])=>v.length>0).map(([v,x])=>`import { ${x.join(", ")} } from '${v}';
|
|
1044
|
+
`).join(""),y=this.serverMetadataSource(e)==="page"?`
|
|
1045
|
+
// The page module's own Next metadata
|
|
1046
|
+
export { generateMetadata } from '${o}';
|
|
1047
|
+
`:"",S=v=>{let x=l?`<SignedInRedirect to={${JSON.stringify(l)}}>${v}</SignedInRedirect>`:v;return i?`<AuthGuard auth={${JSON.stringify(i===!0?{required:!0}:i)}}>${x}</AuthGuard>`:x},T=a?`import ${n}Client from './${n}Client';`:`import ${n} from '${o}';`,R=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1048
|
+
// This file will be regenerated when src/pages changes
|
|
1049
|
+
// To customize: edit ${e.filePath} or create manual app/** files
|
|
1050
|
+
|
|
1051
|
+
${f?.vendorImports??""}${m}${f?.typeImports??""}${c}${p.imports}${f?.appImports??""}${T}
|
|
1052
|
+
${p.setup}${d.code}${f?f.code:""}${y}`;if(f){let v=a?`<${n}Client />`:`<${n} {...props} />`;return`${R}
|
|
1053
|
+
export default async function ${n}Route(props: { params: Params }) {
|
|
1054
|
+
${f.render.replace("{PAGE}",S(v))}
|
|
960
1055
|
}
|
|
961
|
-
|
|
1056
|
+
`}return a?`${R}
|
|
1057
|
+
export default function ${n}Route() {
|
|
1058
|
+
return ${S(`<${n}Client />`)};
|
|
1059
|
+
}
|
|
1060
|
+
`:u.length?`${R}
|
|
1061
|
+
export default function ${n}Route(props: Record<string, unknown>) {
|
|
1062
|
+
return ${S(`<${n} {...props} />`)};
|
|
1063
|
+
}
|
|
1064
|
+
`:`${R}
|
|
1065
|
+
export default ${n};
|
|
1066
|
+
`}extractComponentName(e){let n=(e.split("/").pop()?.replace(/\.tsx?$/,"")||"Component").replace(/[^a-zA-Z0-9]/g,"");return n.charAt(0).toUpperCase()+n.slice(1)}async hasGenerationMarker(e){try{let t=await this.pathResolver.read(e,{format:"text"});return t&&t.includes("// Generated by @donotdev/config")}catch{return!1}}normalizeAuth(e){return e===!0?{}:!e||typeof e!="object"||!e.required&&!e.role&&!e.tier?null:{role:e.role,tier:e.tier}}calculateRelativeImportPath(e,t){if(!e)throw new Error("relativePath is required for import path calculation");let s=e.replace(/\.tsx$/,"").replace(/^src\//,""),o=this.appDirFor(t).split("/").filter(Boolean).length;return`${"../".repeat(o+1)}${s}`}hasDynamicSegment(e){return e.includes(":")||e.includes("[")}generateMountedClientContent(e,t){return this.options.ssr?`// Generated by @donotdev/config - DO NOT EDIT
|
|
962
1067
|
// This file will be regenerated when src/pages changes
|
|
963
1068
|
'use client';
|
|
964
1069
|
|
|
965
|
-
import { useEffect, useState } from 'react';
|
|
966
|
-
|
|
967
1070
|
import ${e} from '${t}';
|
|
968
1071
|
|
|
969
1072
|
export default function ${e}Client() {
|
|
970
|
-
const [mounted, setMounted] = useState(false);
|
|
971
|
-
|
|
972
|
-
useEffect(() => {
|
|
973
|
-
setMounted(true);
|
|
974
|
-
}, []);
|
|
975
|
-
|
|
976
|
-
if (!mounted) return null;
|
|
977
1073
|
return <${e} />;
|
|
978
1074
|
}
|
|
979
|
-
|
|
1075
|
+
`:`// Generated by @donotdev/config - DO NOT EDIT
|
|
980
1076
|
// This file will be regenerated when src/pages changes
|
|
981
1077
|
'use client';
|
|
982
1078
|
|
|
@@ -984,178 +1080,33 @@ import { useEffect, useState } from 'react';
|
|
|
984
1080
|
|
|
985
1081
|
import ${e} from '${t}';
|
|
986
1082
|
|
|
987
|
-
export default function
|
|
1083
|
+
export default function ${e}Client() {
|
|
988
1084
|
const [mounted, setMounted] = useState(false);
|
|
989
1085
|
|
|
990
1086
|
useEffect(() => {
|
|
991
|
-
document.documentElement.dataset.dndevBlogClientReady = 'true';
|
|
992
1087
|
setMounted(true);
|
|
993
|
-
return () => {
|
|
994
|
-
delete document.documentElement.dataset.dndevBlogClientReady;
|
|
995
|
-
};
|
|
996
1088
|
}, []);
|
|
997
1089
|
|
|
998
1090
|
if (!mounted) return null;
|
|
999
1091
|
return <${e} />;
|
|
1000
1092
|
}
|
|
1001
|
-
`}
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
import
|
|
1009
|
-
|
|
1010
|
-
type Params = Promise<{ ${r}: string }>;
|
|
1011
|
-
|
|
1012
|
-
interface BlogMeta {
|
|
1013
|
-
title: string;
|
|
1014
|
-
description: string;
|
|
1015
|
-
date: string;
|
|
1016
|
-
tags?: string;
|
|
1017
|
-
image?: string;
|
|
1018
|
-
[key: string]: string | undefined;
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
interface BlogPost {
|
|
1022
|
-
slug: string;
|
|
1023
|
-
meta: BlogMeta;
|
|
1024
|
-
content: string;
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
function parseFrontmatter(raw: string): { meta: BlogMeta; content: string } {
|
|
1028
|
-
const match = raw.match(new RegExp('^---\\\\r?\\\\n([\\\\s\\\\S]*?)\\\\r?\\\\n---\\\\r?\\\\n'));
|
|
1029
|
-
if (match === null) {
|
|
1030
|
-
return { meta: { title: '', description: '', date: '' }, content: raw };
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
const meta: BlogMeta = { title: '', description: '', date: '' };
|
|
1034
|
-
const frontmatter = match[1] ?? '';
|
|
1035
|
-
for (const line of frontmatter.split('\\n')) {
|
|
1036
|
-
const colonIndex = line.indexOf(':');
|
|
1037
|
-
if (colonIndex === -1) continue;
|
|
1038
|
-
const key = line.slice(0, colonIndex).trim();
|
|
1039
|
-
const value = line.slice(colonIndex + 1).trim();
|
|
1040
|
-
if (key) meta[key] = value;
|
|
1041
|
-
}
|
|
1042
|
-
return { meta, content: raw.slice(match[0].length) };
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
function parseFilePath(path: string): { slug: string; lang: string } | null {
|
|
1046
|
-
const filename = path.split('/').pop()?.replace(new RegExp('\\\\.md$'), '');
|
|
1047
|
-
if (filename === undefined) return null;
|
|
1048
|
-
|
|
1049
|
-
const lastUnderscore = filename.lastIndexOf('_');
|
|
1050
|
-
if (lastUnderscore === -1) return { slug: filename, lang: 'en' };
|
|
1051
|
-
|
|
1052
|
-
const lang = filename.slice(lastUnderscore + 1);
|
|
1053
|
-
const slug = filename.slice(0, lastUnderscore);
|
|
1054
|
-
if (lang.length < 2 || lang.length > 5 || !/^[a-zA-Z]{2,5}$/.test(lang)) {
|
|
1055
|
-
return { slug: filename, lang: 'en' };
|
|
1056
|
-
}
|
|
1057
|
-
return { slug, lang };
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
function getEnglishPosts(): BlogPost[] {
|
|
1061
|
-
const posts: BlogPost[] = [];
|
|
1062
|
-
for (const [path, raw] of Object.entries(blogContent)) {
|
|
1063
|
-
const parsed = parseFilePath(path);
|
|
1064
|
-
if (parsed === null || parsed.lang !== 'en') continue;
|
|
1065
|
-
const post = parseFrontmatter(raw);
|
|
1066
|
-
posts.push({ slug: parsed.slug, meta: post.meta, content: post.content });
|
|
1067
|
-
}
|
|
1068
|
-
return posts;
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
const englishPosts = getEnglishPosts();
|
|
1072
|
-
|
|
1073
|
-
export async function generateStaticParams() {
|
|
1074
|
-
return englishPosts.map((post) => ({ ${r}: post.slug }));
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
export async function generateMetadata({
|
|
1078
|
-
params,
|
|
1079
|
-
}: {
|
|
1080
|
-
params: Params;
|
|
1081
|
-
}): Promise<Metadata> {
|
|
1082
|
-
const { ${r} } = await params;
|
|
1083
|
-
const post = englishPosts.find((item) => item.slug === ${r}) ?? null;
|
|
1084
|
-
if (!post) return { title: 'Post not found' };
|
|
1085
|
-
const appUrl = process.env.NEXT_PUBLIC_APP_URL;
|
|
1086
|
-
return {
|
|
1087
|
-
title: post.meta.title,
|
|
1088
|
-
...(post.meta.description ? { description: post.meta.description } : {}),
|
|
1089
|
-
...(appUrl ? { metadataBase: new URL(appUrl) } : {}),
|
|
1090
|
-
openGraph: {
|
|
1091
|
-
title: post.meta.title,
|
|
1092
|
-
type: 'article',
|
|
1093
|
-
...(post.meta.description ? { description: post.meta.description } : {}),
|
|
1094
|
-
...(post.meta.image ? { images: [post.meta.image] } : {}),
|
|
1095
|
-
},
|
|
1096
|
-
twitter: {
|
|
1097
|
-
card: 'summary_large_image',
|
|
1098
|
-
title: post.meta.title,
|
|
1099
|
-
...(post.meta.description ? { description: post.meta.description } : {}),
|
|
1100
|
-
...(post.meta.image ? { images: [post.meta.image] } : {}),
|
|
1101
|
-
},
|
|
1102
|
-
};
|
|
1103
|
-
}
|
|
1104
|
-
|
|
1105
|
-
function escapeHtml(value: string): string {
|
|
1106
|
-
return value
|
|
1107
|
-
.replace(/&/g, '&')
|
|
1108
|
-
.replace(/</g, '<')
|
|
1109
|
-
.replace(/>/g, '>')
|
|
1110
|
-
.replace(/"/g, '"')
|
|
1111
|
-
.replace(/'/g, ''');
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
export default async function BlogPostRoute({ params }: { params: Params }) {
|
|
1115
|
-
const { ${r} } = await params;
|
|
1116
|
-
const post = englishPosts.find((item) => item.slug === ${r}) ?? null;
|
|
1117
|
-
|
|
1118
|
-
return (
|
|
1119
|
-
<>
|
|
1120
|
-
<style
|
|
1121
|
-
dangerouslySetInnerHTML={{
|
|
1122
|
-
__html:
|
|
1123
|
-
'html[data-dndev-blog-client-ready="true"] .dndev-blog-seo-fallback{display:none}',
|
|
1124
|
-
}}
|
|
1125
|
-
/>
|
|
1126
|
-
{post && (
|
|
1127
|
-
<article className="dndev-blog-seo-fallback prose">
|
|
1128
|
-
<h1>{post.meta.title}</h1>
|
|
1129
|
-
{post.meta.description && <p>{post.meta.description}</p>}
|
|
1130
|
-
{post.meta.date && <p>{post.meta.date}</p>}
|
|
1131
|
-
<pre
|
|
1132
|
-
style={{ whiteSpace: 'pre-wrap', font: 'inherit' }}
|
|
1133
|
-
dangerouslySetInnerHTML={{ __html: escapeHtml(post.content) }}
|
|
1134
|
-
/>
|
|
1135
|
-
</article>
|
|
1136
|
-
)}
|
|
1137
|
-
<BlogPostClient />
|
|
1138
|
-
</>
|
|
1139
|
-
);
|
|
1140
|
-
}
|
|
1141
|
-
`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let s=this.pathResolver.readSync(t);return s?s.split(`
|
|
1142
|
-
`).slice(0,50).some(n=>n.trim()==="'use client';"||n.trim()==='"use client";'):!1}catch{return!1}}};function Fs(o={}){return new mt(o)}function Ee(o){return o.replace(/\s+/g," ").trim()}function Is(o){let e=[`# ${Ee(o.name)}`,""];o.summary&&e.push(`> ${Ee(o.summary)}`,"");for(let t of o.sections)if(t.links.length!==0){e.push(`## ${Ee(t.heading)}`,"");for(let s of t.links){let r=`- [${Ee(s.title)}](${s.url})`;e.push(s.description?`${r}: ${Ee(s.description)}`:r)}e.push("")}return e.join(`
|
|
1143
|
-
`)}var Jn="dndev",Xn="crud",Kn="entity-";function Ls(o,e,t){return e?o?.[e]?.[t]:void 0}function H(o){return typeof o=="string"&&o.trim()!==""?o.trim():void 0}function Yn(o,e,t){let s=o.metaExport||o.meta||{},r=s.seo||{},n=Ls(e,s.namespace,t),a=H(n?.title)??H(r.title)??H(n?.meta?.fullTitle)??H(r.fullTitle),i=r.description===null?void 0:H(r.description)??H(n?.description);return{...a&&{title:a},...i&&{description:i}}}function Us(o){let{siteName:e,description:t,baseUrl:s,sitemapRoutes:r,routes:n,blogPosts:a=[],blogPath:i="/blog",translations:l,language:p}=o,c=Ls(l,Jn,p)?.seo,u=H(c?.llmsPages),h=H(c?.llmsBlog);if(!u||!h)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${p}".`);let g=new Map(n.map(m=>[m.path,m])),d=new Map(a.map(m=>[`${i}/${m.slug}`,m])),f=r.map(({path:m,collection:E})=>{let O=d.get(m);if(O)return{path:m,title:O.title,...H(O.description)&&{description:H(O.description)},section:h};if(E)return{path:m,collection:E};let k=w(m);if(m===i&&!k.title)return{path:m,...k,title:h};if(!k.title){let D=g.get(m),T=(D?.metaExport||D?.meta)?.namespace;throw new Error(`[dndev] llms.txt: page "${m}" has no title in "${p}". Add "title" to `+(T?`${T}_${p}.json`:"its translations")+" or `seo: { title }` to its PageMeta.")}return{path:m,...k}});function w(m){let E=g.get(m);return E?Yn(E,l,p):{}}let y={},A={};for(let[m,E]of Object.entries(l||{})){if(m===Xn&&E?.[p]&&(A[m]=E[p]),!m.startsWith(Kn))continue;E?.[p]&&(A[m]=E[p]);let O=H(E?.[p]?.namePlural);O&&(y[m]=O)}return{name:e,...H(t)&&{summary:H(t)},baseUrl:s,pagesHeading:u,routes:f,entityHeadings:y,language:p,translations:A}}function Ms(o={}){let{siteName:e,baseUrl:t,blogPosts:s=[],blogPath:r="/blog",appRoot:n,logger:a}=o;if(!e||!t)return null;if(s.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=$.getInstance(),l=n?i.resolvePath("src/content/blog",n):null;if(!l||!i.pathExists(l))return null;let p=[`# ${e}
|
|
1144
|
-
`];o.description&&p.push(`> ${o.description}
|
|
1145
|
-
`);for(let c of s){let u=i.resolvePath(`${c.slug}_en.md`,l);try{let h=i.readSync(u,{format:"text"});if(!h)continue;let g=h.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),d=`${t}${r}/${c.slug}`;p.push(`## ${c.title}
|
|
1146
|
-
`),p.push(`Source: ${d}
|
|
1147
|
-
`),c.date&&p.push(`Date: ${c.date}
|
|
1148
|
-
`),p.push(g.trim()),p.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${c.slug}`)}}return p.join(`
|
|
1149
|
-
`)}function vt(o){let e=(o??"").trim().replace(/\/+$/,"");return e?/^https?:\/\//i.test(e)?e:`https://${e}`:null}function Zn(o){let e=vt(o);if(!e)throw new Error("[dndev] Set NEXT_PUBLIC_APP_URL: the sitemap and llms.txt publish absolute URLs.");return e}var js=`src/app/sitemap.xml/${I("route","ts")}`,Gs=`src/app/llms.txt/${I("route","ts")}`;function Bs(o){let e=o.filter(r=>r.path.includes(":")),t=`${o.length-e.length} static + ${e.length} dynamic`;if(e.length===0)return t;let s=e.map(r=>`${r.path} \u2192 ${r.collection??"no collection"}`);return`${t} (${s.join(", ")})`}var yt=class extends G{constructor(e={}){super(fe,e);let t=$.getInstance(),s=B("SEO Handler",this.options.debug,this.options.verbose),r=process.env.NEXT_PUBLIC_APP_URL||null;r&&this.options.debug&&s.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${r}`);let n=e.baseUrl;!n&&r&&(n=vt(r)),this._baseUrlExpr=e.baseUrl?`appBaseUrl(${JSON.stringify(e.baseUrl)})`:"appBaseUrl(process.env.NEXT_PUBLIC_APP_URL)",n?s.debug(`Found app URL: ${n}`):s.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let a=e.siteName||null;if(s.verbose(`Name: ${a||"Not found"}`),s.verbose(`URL: ${n||"Not found"}`),a&&s.debug(` - Site name from appConfig: "${a}"`),e.disabled===!0){s.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}let i=[];if(n||i.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),a||i.push("siteName (APP_NAME in src/config/app.ts)"),i.length>0){s.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),i.forEach(l=>s.warn(` - ${l}`)),s.warn(""),s.warn(" To fix:"),n||s.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),a||(s.warn(" 2. Add APP_NAME export to src/config/app.ts:"),s.warn(' export const APP_NAME = "Your App Name";')),s.warn(""),s.warn(" robots.txt and sitemap.xml will NOT be generated."),s.warn(""),this.disabled=!0;return}this.options.isDev||ks(n,"NEXT_PUBLIC_APP_URL"),this._baseUrl=n,this._siteName=a,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this._sitemapEnabled=this.options.generateSitemap!==!1,this.seoGenerator=new Fe({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,baseUrl:n,siteName:a,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e,generateSitemap:!1})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json"}}createNextConfig(){return this.disabled?()=>({}):super.createNextConfig()}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:await this.discovery.discoverRoutes()}getAPIRewrites(){return this.disabled?{beforeFiles:[],afterFiles:[],fallback:[]}:{beforeFiles:[],afterFiles:[],fallback:[]}}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(!this.disabled){if(!e||!e.routes)try{let t=this.pathResolver.resolveAppPath("public/route-manifest.json");if(this.pathResolver.pathExists(t))e=await this.pathResolver.read(t,{format:"json"});else{this.logger.debug("Route manifest not found, skipping SEO file generation");return}}catch(t){this.logger.debug(`Could not load route manifest for SEO: ${t.message}`);return}try{let t=async(r,n)=>{if(!r){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${r}`,n,r)},s=await this.seoGenerator.generateSEOFiles(e,t);if(this._sitemapEnabled&&await this.generateSitemapRoute(e.routes||[]),s.robotsTxt&&!s.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${s.robotsTxt.disallowedPaths||0} disallowed paths`),s.sitemap&&!s.sitemap.skipped&&this.logger.info(`\u{1F5FA}\uFE0F sitemap.xml: ${s.sitemap.publicRoutes||0} routes`),s.rss&&!s.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${s.rss.postCount||0} blog posts`),s.manifest&&!s.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json"),this._llmsTxtEnabled){let r=this.seoGenerator.discoverBlogPosts(),n=this.pathResolver.getAppRoot();if(await this.generateLlmsTxtRoute(e.routes||[],r),r.length>0){let a=Ms({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:n,blogPosts:r,logger:this.logger});a&&(this.writeGeneratedFile("public/llms-full.txt",a,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))}}}catch(t){this.logger.error(`SEO handler failed to generate files (robots.txt/sitemap.xml): ${t.message}`),this.logger.error(`Stack: ${t.stack||"No stack trace available"}`)}}}useLanguages(e){this._languageRouting=e}async generateSitemapRoute(e){if(!this._languageRouting)throw new Error("SEO handler: languages not set before sitemap generation (runDiscoveries calls useLanguages)");let t=this.seoGenerator.getSitemapRoutes(e,this.seoGenerator.discoverBlogPosts()),s=this.serverCrudReader(t),r=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1093
|
+
`}isClientComponent(e){try{let t=this.pathResolver.resolveAppPath(e);if(!this.pathResolver.pathExists(t))return!1;let n=this.pathResolver.readSync(t);return n?n.split(`
|
|
1094
|
+
`).slice(0,50).some(o=>o.trim()==="'use client';"||o.trim()==='"use client";'):!1}catch{return!1}}};Object.assign(nt.prototype,yr,xr,Pr,Tr,Hr,Dr,vr);function Vr(r={}){return new nt(r)}var Ja="dndev",Va="crud",Ka="entity-";function Kr(r,e,t){return e?r?.[e]?.[t]:void 0}function pe(r){return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function Xr(r){return r?.metaExport||r?.meta||{}}function Xa(r,{siteName:e,defaultNamespace:t,t:n}){let s=Xr(r),{title:o,pageTitle:a}=Lt({meta:s,ns:s.namespace||null,defaultNs:t,t:n,siteName:e});return a??o}function Ya(r,e,t){let n=Xr(r),s=n.seo||{};if(s.description===null)return;let o=Kr(e,n.namespace,t);return pe(s.description)??pe(o?.description)}function Yr(r){let{siteName:e,description:t,baseUrl:n,sitemapRoutes:s,routes:o,blogPosts:a=[],blogPath:i="/blog",translations:l,language:u,defaultNamespace:c}=r,p=Kr(l,Ja,u)?.seo,d=pe(p?.llmsPages),f=pe(p?.llmsBlog);if(!d||!f)throw new Error(`[dndev] llms.txt: framework labels seo.llmsPages / seo.llmsBlog missing for language "${u}".`);if(!c)throw new Error('[dndev] llms.txt: getLlmsTxtSource needs options.defaultNamespace (appConfig.seo.defaultNamespace, else "home").');let h=new Map(o.map(v=>[v.path,v])),m={siteName:e,defaultNamespace:c,t:Xe(Object.fromEntries(Object.entries(l||{}).map(([v,x])=>[v,x?.[u]])))},y=new Map(a.map(v=>[`${i}/${v.slug}`,v])),S=s.map(({path:v,collection:x})=>{let O=y.get(v);if(O)return{path:v,title:O.title,...pe(O.description)&&{description:pe(O.description)},section:f};if(x)return{path:v,collection:x};let B=h.get(v);if(!B&&v===i)return{path:v,title:f};let M=Ya(B,l,u);return{path:v,title:Xa(B,m),...M&&{description:M}}}),T={},R={};for(let[v,x]of Object.entries(l||{})){if(v===Va&&x?.[u]&&(R[v]=x[u]),!v.startsWith(Ka))continue;x?.[u]&&(R[v]=x[u]);let O=pe(x?.[u]?.namePlural);O&&(T[v]=O)}return{name:e,...pe(t)&&{summary:pe(t)},baseUrl:n,pagesHeading:d,routes:S,entityHeadings:T,language:u,translations:R}}function Zr(r={}){let{siteName:e,baseUrl:t,blogPosts:n=[],blogPath:s="/blog",appRoot:o,logger:a}=r;if(!e||!t)return null;if(n.length===0)return a?.debug?.("llms-full.txt skipped: no blog posts"),null;let i=D.getInstance(),l=o?i.resolvePath("src/content/blog",o):null;if(!l||!i.pathExists(l))return null;let u=[`# ${e}
|
|
1095
|
+
`];r.description&&u.push(`> ${r.description}
|
|
1096
|
+
`);for(let c of n){let p=i.resolvePath(`${c.slug}_en.md`,l);try{let d=i.readSync(p,{format:"text"});if(!d)continue;let f=d.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,""),h=`${t}${s}/${c.slug}`;u.push(`## ${c.title}
|
|
1097
|
+
`),u.push(`Source: ${h}
|
|
1098
|
+
`),c.date&&u.push(`Date: ${c.date}
|
|
1099
|
+
`),u.push(f.trim()),u.push("")}catch{a?.debug?.(`llms-full.txt: could not read ${c.slug}`)}}return u.join(`
|
|
1100
|
+
`)}function zt(r){let e=(r??"").trim().replace(/\/+$/,"");return e?/^https?:\/\//i.test(e)?e:`https://${e}`:null}function Za(r){let e=zt(r);if(!e)throw new Error("[dndev] Set NEXT_PUBLIC_APP_URL: the sitemap and llms.txt publish absolute URLs.");return e}var Qr=`src/app/sitemap.xml/${U("route","ts")}`,es=`src/app/llms.txt/${U("route","ts")}`;function ts(r){let e=r.filter(s=>s.path.includes(":")),t=`${r.length-e.length} static + ${e.length} dynamic`;if(e.length===0)return t;let n=e.map(s=>`${s.path} \u2192 ${s.collection??"no collection"}`);return`${t} (${n.join(", ")})`}function rt(r,e,t){return`import { ${[...e,...t.named[r]??[]].join(", ")} } from '${r}';`}var Ht=class extends H{constructor(e={}){super(Pe,e);let t=D.getInstance(),n=ae("SEO Handler",this.options.debug,this.options.verbose),s=process.env.NEXT_PUBLIC_APP_URL||null;s&&this.options.debug&&n.debug(`Using app URL from NEXT_PUBLIC_APP_URL: ${s}`);let o=e.baseUrl;!o&&s&&(o=zt(s)),this._baseUrlExpr=e.baseUrl?`appBaseUrl(${JSON.stringify(e.baseUrl)})`:"appBaseUrl(process.env.NEXT_PUBLIC_APP_URL)",o?n.debug(`Found app URL: ${o}`):n.warn("Missing app URL. Set NEXT_PUBLIC_APP_URL in .env file.");let a=e.siteName||null;if(n.verbose(`Name: ${a||"Not found"}`),n.verbose(`URL: ${o||"Not found"}`),a&&n.debug(` - Site name from appConfig: "${a}"`),e.disabled===!0){n.info("SEO generation disabled (disabled: true)"),this.disabled=!0;return}if(!this.options.isDev&&(o=Gr(o||null,"NEXT_PUBLIC_APP_URL",n),!o)){this.disabled=!0;return}let i=[];if(o||i.push("baseUrl (NEXT_PUBLIC_APP_URL in .env)"),a||i.push("siteName (APP_NAME in src/config/app.ts)"),i.length>0){n.warn("\u26A0\uFE0F SEO Handler disabled - missing required configuration:"),i.forEach(l=>n.warn(` - ${l}`)),n.warn(""),n.warn(" To fix:"),o||n.warn(" 1. Add NEXT_PUBLIC_APP_URL=https://yourdomain.com to your .env file"),a||(n.warn(" 2. Add APP_NAME export to src/config/app.ts:"),n.warn(' export const APP_NAME = "Your App Name";')),n.warn(""),n.warn(" robots.txt and sitemap.xml will NOT be generated."),n.warn(""),this.disabled=!0;return}this._baseUrl=o,this._siteName=a,this._siteDescription=e.siteDescription||null,this._llmsTxtEnabled=this.options.llmsTxt!==!1,this._sitemapEnabled=this.options.generateSitemap!==!1,this.seoGenerator=new Ze({debug:this.options.debug,generateRobotsTxt:this.options.generateRobotsTxt,baseUrl:o,siteName:a,crawlDelay:this.options.crawlDelay,aiCrawlers:this.options.aiCrawlers,appRoot:t.getAppRoot(),...e})}getHandlerDefaults(){return{manifestPath:"public/seo-manifest.json",trailingSlash:!1}}useRoutes(e){this._routeData=e}async getDiscoveryData(){return this.disabled?{routes:[],errors:[],source:"disabled"}:this._routeData??await this.discovery.discoverRoutes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[],fallback:[]}}async generateManifest(e){this.disabled&&await super.generateManifest(e)}getHandlerName(){return"SEO"}async generateSpecificFiles(e){if(this.disabled)return;let t=async(i,l)=>{if(!i){this.logger.debug("Skipping SEO file write - fileName is undefined");return}this.writeGeneratedFile(`public/${i}`,l,i)},n=e.routes,s,o;await $e(["robots.txt","rss.xml","seo-manifest.json","sitemap.xml","llms.txt","llms-full.txt"],()=>{s=this.seoGenerator.discoverBlogPosts(),o=this.seoGenerator.getSitemapRoutes(n,s)},this.logger)&&(await $e(["robots.txt","rss.xml","seo-manifest.json"],async()=>{let i=await this.seoGenerator.generateSEOFiles(e,t,s);i.robotsTxt&&!i.robotsTxt.skipped&&this.logger.info(`\u{1F916} robots.txt: ${i.robotsTxt.disallowedPaths||0} disallowed paths`),i.rss&&!i.rss.skipped&&this.logger.info(`\u{1F4E1} rss.xml: ${i.rss.postCount||0} blog posts`),i.manifest&&!i.manifest.skipped&&this.logger.info("\u{1F4C4} seo-manifest.json")},this.logger),this._sitemapEnabled&&await $e(["sitemap.xml"],()=>this.generateSitemapRoute(o),this.logger),this._llmsTxtEnabled&&(await $e(["llms.txt"],()=>this.generateLlmsTxtRoute(n,s,o),this.logger),s.length>0&&await $e(["llms-full.txt"],()=>{let i=Zr({siteName:this._siteName,baseUrl:this._baseUrl,description:this._siteDescription,appRoot:this.pathResolver.getAppRoot(),blogPosts:s,logger:this.logger});i&&(this.writeGeneratedFile("public/llms-full.txt",i,"llms-full.txt"),this.logger.info("\u{1F4C4} llms-full.txt"))},this.logger)))}useLanguages(e){this._languageRouting=e}async generateSitemapRoute(e){if(!this._languageRouting)throw new Error("SEO handler: languages not set before sitemap generation (runDiscoveries calls useLanguages)");let t=this.serverCrudReader(e),n=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1150
1101
|
// Regenerated on every build from src/pages (PageMeta) and appConfig.
|
|
1151
1102
|
// Public routes + one URL per published record of each dynamic route's entity
|
|
1152
1103
|
// (read with the public role). Keep a page out with \`seo: { noindex: true }\`.
|
|
1153
1104
|
|
|
1154
|
-
|
|
1105
|
+
${rt("@donotdev/core/server",["HIDDEN_STATUSES","languageUrls"],t)}
|
|
1155
1106
|
import type { LanguageRouting } from '@donotdev/core/server';
|
|
1156
|
-
|
|
1107
|
+
${rt("@donotdev/core/next",["appBaseUrl","buildSitemap","formatSitemapXml"],t)}
|
|
1157
1108
|
import type { SitemapRoute } from '@donotdev/core/next';
|
|
1158
|
-
${
|
|
1109
|
+
${t.imports}
|
|
1159
1110
|
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
1160
1111
|
export const revalidate = ${this.revalidate()};
|
|
1161
1112
|
|
|
@@ -1163,70 +1114,80 @@ const BASE_URL = ${this._baseUrlExpr};
|
|
|
1163
1114
|
|
|
1164
1115
|
const LANGUAGE_ROUTING: LanguageRouting = ${JSON.stringify(this._languageRouting)};
|
|
1165
1116
|
|
|
1166
|
-
|
|
1167
|
-
${
|
|
1117
|
+
// next.config trailingSlash: page URLs end with \`/\` when true
|
|
1118
|
+
const TRAILING_SLASH = ${JSON.stringify(this.options.trailingSlash)};
|
|
1119
|
+
|
|
1120
|
+
const ROUTES: SitemapRoute[] = ${JSON.stringify(e,null,2)};
|
|
1121
|
+
${t.setup}
|
|
1168
1122
|
export async function GET(): Promise<Response> {
|
|
1169
1123
|
const entries = await buildSitemap(ROUTES, {
|
|
1170
1124
|
baseUrl: BASE_URL,
|
|
1171
1125
|
routing: LANGUAGE_ROUTING,
|
|
1126
|
+
trailingSlash: TRAILING_SLASH,
|
|
1172
1127
|
languageUrls,
|
|
1173
|
-
hiddenStatuses: HIDDEN_STATUSES,${
|
|
1174
|
-
crud: ${
|
|
1128
|
+
hiddenStatuses: HIDDEN_STATUSES,${t.expr?`
|
|
1129
|
+
crud: ${t.expr},
|
|
1130
|
+
readSchemas: ${t.schemas},`:""}
|
|
1175
1131
|
});
|
|
1176
1132
|
return new Response(formatSitemapXml(entries), {
|
|
1177
1133
|
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
|
|
1178
1134
|
});
|
|
1179
1135
|
}
|
|
1180
|
-
`;this.writeGeneratedFile(
|
|
1136
|
+
`;this.writeGeneratedFile(Qr,n,"sitemap route");let s=this.pathResolver.resolveAppPath("public/sitemap.xml");this.pathResolver.pathExists(s)&&await this.pathResolver.remove(s),this.logger.info(`\u{1F5FA}\uFE0F sitemap: ${ts(e)} (${Qr}); URL count printed by dndev build`)}useTranslations(e){this._translations=e}async generateLlmsTxtRoute(e,t,n){if(!this._languageRouting||!this._translations)throw new Error("SEO handler: languages/translations not set before llms.txt generation (runDiscoveries calls useLanguages and useTranslations)");let s=Yr({siteName:this._siteName,description:this._siteDescription,baseUrl:this._baseUrl,sitemapRoutes:n,routes:e,blogPosts:t,blogPath:this.seoGenerator.options.blogPath,translations:this._translations,language:this._languageRouting.defaultLanguage,defaultNamespace:this.options.defaultNamespace||"home"}),{baseUrl:o,...a}=s,i=this.serverCrudReader(s.routes),l=`// Generated by @donotdev/config - DO NOT EDIT
|
|
1181
1137
|
// Regenerated on every build from src/pages (PageMeta), translations and appConfig.
|
|
1182
1138
|
// Same URLs as app/sitemap.xml: public pages + one link per published record of each
|
|
1183
1139
|
// dynamic route's entity. Keep a page out with \`seo: { noindex: true }\`.
|
|
1184
1140
|
|
|
1185
|
-
|
|
1186
|
-
|
|
1141
|
+
${rt("@donotdev/core/server",["HIDDEN_STATUSES","deriveEntitySeo","formatTrailingSlash"],i)}
|
|
1142
|
+
${rt("@donotdev/core/next",["appBaseUrl","buildLlmsTxt"],i)}
|
|
1187
1143
|
import type { LlmsTxtSource } from '@donotdev/core/next';
|
|
1188
|
-
${i
|
|
1189
|
-
`:""}${a.imports}
|
|
1144
|
+
${i.imports}
|
|
1190
1145
|
// Published records: ${this.revalidateLabel()} (appConfig.revalidate, same as the pages).
|
|
1191
1146
|
export const revalidate = ${this.revalidate()};
|
|
1192
1147
|
|
|
1193
1148
|
const BASE_URL = ${this._baseUrlExpr};
|
|
1194
1149
|
|
|
1195
|
-
const SOURCE: Omit<LlmsTxtSource, 'baseUrl'> = ${JSON.stringify(
|
|
1196
|
-
|
|
1150
|
+
const SOURCE: Omit<LlmsTxtSource, 'baseUrl'> = ${JSON.stringify(a,null,2)};
|
|
1151
|
+
|
|
1152
|
+
// next.config trailingSlash: page URLs end with \`/\` when true
|
|
1153
|
+
const TRAILING_SLASH = ${JSON.stringify(this.options.trailingSlash)};
|
|
1154
|
+
${i.setup}
|
|
1197
1155
|
export async function GET(): Promise<Response> {
|
|
1198
1156
|
const body = await buildLlmsTxt({
|
|
1199
1157
|
...SOURCE,
|
|
1200
1158
|
baseUrl: BASE_URL,
|
|
1201
|
-
|
|
1159
|
+
trailingSlash: TRAILING_SLASH,
|
|
1160
|
+
formatTrailingSlash,
|
|
1161
|
+
entities: ${i.expr?"entities":"{}"},
|
|
1202
1162
|
deriveEntitySeo,
|
|
1203
|
-
hiddenStatuses: HIDDEN_STATUSES,${
|
|
1204
|
-
crud: ${
|
|
1163
|
+
hiddenStatuses: HIDDEN_STATUSES,${i.expr?`
|
|
1164
|
+
crud: ${i.expr},
|
|
1165
|
+
readSchemas: ${i.schemas},`:""}
|
|
1205
1166
|
});
|
|
1206
1167
|
return new Response(body, {
|
|
1207
1168
|
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
1208
1169
|
});
|
|
1209
1170
|
}
|
|
1210
|
-
`;this.writeGeneratedFile(
|
|
1211
|
-
`}function
|
|
1171
|
+
`;this.writeGeneratedFile(es,l,"llms.txt route"),this.logger.info(`\u{1F4C4} llms.txt: ${ts(s.routes)} (${es})`)}createManifestContent(){return{}}getGenerationSummary(e){return this.disabled?"SEO disabled":`${(e?.routes||[]).length} routes processed for SEO`}};function ns(r={}){return new Ht(r)}var Ce=class{constructor(e,t={}){if(!e)throw new Error("CSSExtractor requires PathResolver instance");this.pathResolver=e,this.options={debug:!1,customPatterns:{},...t},this.logger=t.logger||{debug:(n,...s)=>{this.options.debug}},this.patterns={selectors:{...ct.selectors,...this.options.customPatterns?.selectors},themes:{...ct.themes,...this.options.customPatterns?.themes}}}cssVarToJsIdentifier(e){if(!e||typeof e!="string")return this._debug(`Invalid CSS variable: ${e}`),null;let t=e.replace(/^--/,"");if(!t)return this._debug(`Empty CSS variable after removing --: ${e}`),null;let n=t.split("-").filter(a=>a.length>0);if(n.length===0)return this._debug(`No valid parts in CSS variable: ${e}`),null;let s=n.map((a,i)=>{let l=a.replace(/[^a-zA-Z0-9]/g,"");return l?i===0?l.toLowerCase():l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():null}).filter(Boolean).join("");return!s||!/^[a-zA-Z][a-zA-Z0-9]*$/.test(s)?(this._debug(`Invalid JavaScript identifier generated from ${e}: ${s}`),null):["const","let","var","function","class","export","import","default","if","else","for","while"].includes(s)?`${s}Var`:s}_stripComments(e){return e.replace(/\/\*[\s\S]*?\*\//g,"")}extractThemes(e,t,n){let s=[],o,a=this.pathResolver.normalizePath(t),i=this._stripComments(e),l=/(?::root\.|\.)([a-z][a-z0-9-]*)\s*\{([^}]*--theme-label\s*:\s*['"]([^'"]+)['"][^}]*)\}/gim;for(;(o=l.exec(i))!==null;){let[,u,c,p]=o;if(!u||!p)continue;let d=c.match(this.patterns.themes.themeIcon),f=c.match(this.patterns.themes.themeIsDark),h={name:u,displayName:p,isDark:f?f[1]==="1":!1,meta:{icon:d?.[1]},source:this.pathResolver.getBasename(t)};this._debug(`Discovered theme: ${u} (${p})`),s.push(h),n.themes.set(u,{name:u,displayName:p,isDark:h.isDark,file:a,variables:new Set,meta:h.meta})}return s.length>0&&this._debug(`Extracted ${s.length} themes from ${a}`),s}extractClasses(e,t){(e.match(this.patterns.selectors.class)||[]).forEach(s=>{let o=s.slice(1);o.startsWith("_")||t.classes.add(o)})}extractVariables(e,t,n){(e.match(this.patterns.selectors.variable)||[]).forEach(o=>{o.startsWith("--")&&o.length>2?n==="framework"?t.variables.framework.add(o):t.variables.consumer.add(o):this._debug(`Skipping invalid CSS variable: ${o}`)})}extractKeyframes(e,t){(e.match(this.patterns.selectors.keyframe)||[]).forEach(s=>{let o=s.replace("@keyframes","").trim();o&&t.keyframes.add(o)})}validateCSS(e){let t=[],n=e.match(/--[a-zA-Z0-9-_]*[^a-zA-Z0-9-_:;\s]/g);return n&&n.forEach(o=>{t.push(`Possible malformed CSS variable: ${o}`)}),(e.match(/\.[a-z][a-z0-9-]+\s*\{[^}]*\}/gi)||[]).forEach(o=>{if(!o.includes("--theme-label")&&o.includes("--")){let a=o.match(/\.([a-z][a-z0-9-]+)/)?.[1];a&&t.push(`Theme class "${a}" missing --theme-label`)}}),t}extractAll(e,t,n="consumer"){let s={themes:new Map,classes:new Set,variables:{framework:new Set,consumer:new Set},keyframes:new Set},o=this.extractThemes(e,t,s);this.extractClasses(e,s),this.extractVariables(e,s,n),this.extractKeyframes(e,s);let a=this.validateCSS(e);return{themes:o,classes:Array.from(s.classes),variables:{framework:Array.from(s.variables.framework),consumer:Array.from(s.variables.consumer),all:[...Array.from(s.variables.framework),...Array.from(s.variables.consumer)].sort()},keyframes:Array.from(s.keyframes),warnings:a}}getPatterns(){return{...this.patterns}}setPatterns(e){this.patterns={...this.patterns,...e,selectors:{...this.patterns.selectors,...e.selectors},themes:{...this.patterns.themes,...e.themes}}}_debug(e,t){this.logger.debug(e,t||"")}};var rs="@donotdev/components/styles",Qa=/@import\s+['"](\.[^'"]+)['"]\s*;/g,st=class extends ee{constructor(e,t,n={}){super(t,n),this.cssExtractor=e||new Ce(t,{debug:n.debug,logger:this.logger}),this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes()}_getDiscoveryType(){return"Theme"}async _getPatterns(){return await this.pathResolver.resolvePatterns("css")}_getPatternType(){return"css"}async _processFiles(e){this.discovered={themes:new Map,variables:{framework:new Set,consumer:new Set},classes:new Set,keyframes:new Set},this._addEssentialThemes();let{frameworkFiles:t,consumerFiles:n}=e;this.logger.debug(`Scanning ${t.length} framework + ${n.length} consumer CSS files`),this.logger.debug("\u{1F50D} FILES DISCOVERED:"),this.logger.debug("Framework files:",t),this.logger.debug("Consumer files:",n),t.length>0?(this.logger.debug(`Framework files found: ${t.length}`),this.logger.debug("Framework files:",t)):this.logger.debug("No framework files found"),n.length>0?(this.logger.debug(`Consumer files found: ${n.length}`),this.logger.debug("Consumer files:",n)):this.logger.debug("No consumer files found"),await this._processFrameworkFiles(t);let s=await this._processConsumerFiles(n),o=this._serializeThemes(),a={framework:this._readFrameworkTokenCss(),app:s};return this.logger.debug(`Discovered ${o.length} themes:`,o.map(i=>i.name)),{themes:o,variables:{framework:Array.from(this.discovered.variables.framework).sort(),consumer:Array.from(this.discovered.variables.consumer).sort(),all:[...Array.from(this.discovered.variables.framework),...Array.from(this.discovered.variables.consumer)].sort()},classes:Array.from(this.discovered.classes).sort(),keyframes:Array.from(this.discovered.keyframes).sort(),fontCss:a}}_getEmptyResult(){let e=this._serializeThemes();return{themes:e.length>0?e:this._getEssentialThemesFallback(),variables:{framework:[],consumer:[],all:[]},classes:[],keyframes:[],timestamp:Date.now()}}_getEssentialThemesFallback(){return ut.map(e=>({name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variableCount:0}))}_getDiscoverySummary(){return""}async discoverThemes(e=!1){return await this.discover(e)}getThemes(){return this.cache?.themes||[]}getVariables(){return this.cache?.variables||{framework:[],consumer:[],all:[]}}getClasses(){return this.cache?.classes||[]}async _processFrameworkFiles(e){for(let t of e)try{let n=await this.pathResolver.read(t,{format:"text"}),s=this.pathResolver.normalizePath(t);this.cssExtractor.extractThemes(n,s,this.discovered),this.cssExtractor.extractClasses(n,this.discovered),this.cssExtractor.extractVariables(n,this.discovered,"framework"),this.cssExtractor.extractKeyframes(n,this.discovered),this.logger.debug(`\u2705 Processed framework: ${this.pathResolver.getRelativePath(s)}`)}catch(n){this.logger.debug(`Error scanning framework file ${t}: ${n.message}`)}}async _processConsumerFiles(e){let t=[];for(let n of e)try{let s=await this.pathResolver.read(n,{format:"text"}),o=this.pathResolver.normalizePath(n);t.push({file:this.pathResolver.getRelativePath(o),css:s}),this.cssExtractor.extractThemes(s,o,this.discovered),this.cssExtractor.extractVariables(s,this.discovered,"consumer"),this.logger.debug(`\u2705 Processed consumer: ${this.pathResolver.getRelativePath(o)}`)}catch(s){this.logger.debug(`Error scanning consumer file ${n}: ${s.message}`)}return t}_readFrameworkTokenCss(){let e=this.pathResolver.resolvePackage(rs,this.pathResolver.resolveFrameworkPackage("@donotdev/ui"));if(!e)throw C("dndev-theme",`cannot resolve ${rs} (framework font defaults), resolved from @donotdev/ui: check that @donotdev/ui and @donotdev/components are installed`,"missing-required-resource");let t=new Set,n=s=>{if(t.has(s))return"";t.add(s);let o=this.pathResolver.readSync(s,{format:"text"});if(typeof o!="string")throw C("dndev-theme",`cannot read ${s} (framework font defaults)`,"missing-required-resource");let a=this.pathResolver.getDirname(s);return o.replace(Qa,(i,l)=>n(this.pathResolver.resolvePath(l,a)))};return n(e)}_addEssentialThemes(){ut.forEach(e=>{this.discovered.themes.set(e.name,{name:e.name,displayName:e.displayName,meta:{icon:e.icon,category:e.isDark?"dark":"light"},essential:!0,isDark:e.isDark,source:"built-in",variables:new Set})})}_serializeThemes(){return Array.from(this.discovered.themes.values()).map(e=>({name:e.name,displayName:e.displayName,meta:e.meta,source:e.source,essential:e.essential||!1,isDark:e.isDark||!1,variableCount:e.variables?.size||0}))}};import{createRequire as ei}from"node:module";var ti=ei(import.meta.url),os="ThemeIcon_",ss;function ni(){return ss??=new Set(Object.keys(ti("lucide-react"))),ss}function as(r,e){let t=ni(),n=new Set;for(let s of r){let o=s.meta?.icon;if(!o)continue;let a=String(o).replace(/['"]/g,"").trim();/^[A-Za-z][A-Za-z0-9]*$/.test(a)&&t.has(a)?n.add(a):e.warn(`\u{1F3A8} Theme "${s.name}": --theme-icon '${a}' is not a lucide-react icon name (theme toggle shows the Palette icon)`)}return[...n].sort()}function is(r){return r.length===0?"":`import { ${r.map(t=>`${t} as ${os}${t}`).join(", ")} } from 'lucide-react';
|
|
1172
|
+
`}function ls(r){return`{ ${r.map(t=>`${JSON.stringify(t)}: ${os}${t}`).join(", ")} }`}var Wt=class extends H{constructor(e={}){super(st,e)}getHandlerDefaults(){return{generateThemeProvider:!1,manifestPath:"public/theme-manifest.json"}}createDiscovery(e){return this.cssExtractor=new Ce(this.pathResolver,{debug:this.options.debug}),new e(this.cssExtractor,this.pathResolver,this.options)}getHandlerName(){return"Theme"}logDiscoveryResults(e){let t=e.themes||[],n=t.filter(o=>!o.essential).length,s=t.length;if(s===0)throw Sn("dndev-theme","themes","Framework requires at least one theme. Ensure CSS files with theme definitions exist in your project. Check that @donotdev/components/styles are imported.");this.logger.info(`\u{1F3A8} Themes: ${s} discovered${n>0?` (${n} custom)`:""}`)}async getDiscoveryData(){return await this.discovery.discoverThemes()}getAPIRewrites(){return{beforeFiles:[],afterFiles:[{source:"/api/themes",destination:"/api/themes/route"}],fallback:[]}}createManifestContent(e){return{themes:e.themes,variables:{total:e.variables.all.length,framework:e.variables.framework.length,consumer:e.variables.consumer.length},stats:e.stats,generatedAt:new Date().toISOString()}}getGenerationSummary(e){return`${e.themes.length} themes, ${e.variables.all.length} variables`}async generateSpecificFiles(){}async generateThemes(){let e=await this.getDiscoveryData();await this.generateConfigFile(e)}async generateConfigFile(e){return super.generateConfigFile(e)}generateConfigContent(e){let{themes:t,variables:n}=e,s=as(t,this.logger);return`// Auto-generated DnDev config by @donotdev/config
|
|
1212
1173
|
// Generated at: ${new Date().toISOString()}
|
|
1213
1174
|
// Populates _DNDEV_CONFIG_ with discovery results
|
|
1214
|
-
${
|
|
1175
|
+
${is(s)}
|
|
1215
1176
|
const themeConfig = {
|
|
1216
1177
|
discovered: ${JSON.stringify(t,null,2)},
|
|
1217
1178
|
// Theme icons (--theme-icon), imported by name: server-rendered without the lucide namespace
|
|
1218
|
-
icons: ${
|
|
1219
|
-
variables: ${JSON.stringify(
|
|
1179
|
+
icons: ${ls(s)},
|
|
1180
|
+
variables: ${JSON.stringify(n,null,2)},
|
|
1220
1181
|
utilities: {
|
|
1221
|
-
framework: ${JSON.stringify(
|
|
1222
|
-
consumer: ${JSON.stringify(
|
|
1223
|
-
all: ${JSON.stringify(
|
|
1182
|
+
framework: ${JSON.stringify(n.framework,null,2)},
|
|
1183
|
+
consumer: ${JSON.stringify(n.consumer,null,2)},
|
|
1184
|
+
all: ${JSON.stringify(n.all,null,2)},
|
|
1224
1185
|
},
|
|
1225
1186
|
manifest: {
|
|
1226
1187
|
totalThemes: ${t.length},
|
|
1227
|
-
totalVariables: ${
|
|
1228
|
-
frameworkVariables: ${
|
|
1229
|
-
consumerVariables: ${
|
|
1188
|
+
totalVariables: ${n.all.length},
|
|
1189
|
+
frameworkVariables: ${n.framework.length},
|
|
1190
|
+
consumerVariables: ${n.consumer.length},
|
|
1230
1191
|
generatedAt: new Date().toISOString(),
|
|
1231
1192
|
},
|
|
1232
1193
|
};
|
|
@@ -1242,13 +1203,14 @@ if (typeof globalThis !== 'undefined') {
|
|
|
1242
1203
|
timestamp: Date.now(),
|
|
1243
1204
|
};
|
|
1244
1205
|
}
|
|
1245
|
-
globalThis._DNDEV_CONFIG_.${
|
|
1206
|
+
globalThis._DNDEV_CONFIG_.${Y.themes} = themeConfig;
|
|
1246
1207
|
}
|
|
1247
1208
|
|
|
1248
1209
|
// Export for compatibility
|
|
1249
1210
|
export default themeConfig;
|
|
1250
|
-
`}};function
|
|
1251
|
-
`;return
|
|
1252
|
-
\u{1F3D7}\uFE0F DnDev Framework - Building for ${
|
|
1253
|
-
`)),
|
|
1254
|
-
`)}import
|
|
1211
|
+
`}};function cs(r={}){return new Wt(r)}function us({debug:r,verbose:e,generateManifest:t,routeOptions:n,themeOptions:s,i18nOptions:o,assetOptions:a,seoOptions:i,pwaOptions:l,appUrl:u,isDev:c,logger:p}){let d=n.debug??r,f=s.debug??r,h=o.debug??r,m=a.debug??r,y=i.debug??r,S=l.debug??r,T=n.verbose??e,R=s.verbose??e,v=o.verbose??e,x=a.verbose??e,O=i.verbose??e,B=l.verbose??e,M={debug:r,verbose:e,generateManifest:t},te=n.disabled?null:Vr({...M,...n,debug:d,verbose:T});r&&p.debug(`Route handler created: ${te?"enabled":"disabled"} (debug: ${d})`);let W=cs({...M,...s,debug:f,verbose:R}),g=gr({...M,...o,debug:h,verbose:v}),b=fr({...M,...a,debug:m,verbose:x}),k=ns({...M,...i,debug:y,verbose:O,appUrl:u,isDev:c}),N=mr({...M,...l,debug:S,verbose:B}),_=hr({debug:r,verbose:e});return{routeHandler:te,themeHandler:W,i18nHandler:g,assetHandler:b,seoHandler:k,pwaHandler:N,blogContentHandler:_}}import{existsSync as gs,readFileSync as ms,writeFileSync as ri}from"node:fs";import{join as ys}from"node:path";var si="/(.*)",Jt=Object.freeze(["default-src","script-src","style-src","img-src","font-src","connect-src","media-src","worker-src","manifest-src","frame-src","object-src","base-uri","form-action","frame-ancestors"]),oi=Object.freeze({"default-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"frame-src":["'none'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"]}),ps=Object.freeze({next:["'self'","'unsafe-inline'"],"next-export":["'self'","'unsafe-inline'"],vite:["'self'"]}),vs=Object.freeze({"@donotdev/supabase":{"connect-src":["https://*.supabase.co","wss://*.supabase.co"]},"@donotdev/firebase":{"script-src":["https://accounts.google.com","https://apis.google.com"],"connect-src":["https://identitytoolkit.googleapis.com","https://securetoken.googleapis.com","https://www.googleapis.com","https://*.googleapis.com","https://*.firebaseio.com"],"frame-src":["https://accounts.google.com"]}}),ai=Object.freeze([{key:"X-Content-Type-Options",value:"nosniff"},{key:"X-Frame-Options",value:"DENY"},{key:"X-XSS-Protection",value:"1; mode=block"},{key:"Referrer-Policy",value:"strict-origin-when-cross-origin"},{key:"Permissions-Policy",value:"geolocation=(), microphone=(), camera=()"}]),ii=Object.freeze({key:"X-Robots-Tag",value:"noindex, nofollow, noarchive, nosnippet, noimageindex"}),li=31536e3,ci=86400,bs=3600,ds=Object.freeze({vite:["woff","woff2","ttf","eot","js","css"].map(r=>`/assets/:path*.${r}`),"next-export":["/_next/static/:path*"],next:[]}),ui=`/${le.fonts}/:path*`,pi=Object.freeze(["jpg","jpeg","png","svg","webp","ico"]),di=Object.freeze([{source:"/manifest.json",headers:[{key:"Content-Type",value:"application/manifest+json"},{key:"Cache-Control",value:`public, max-age=${bs}`}]},{source:"/sw.js",headers:[{key:"Content-Type",value:"application/javascript"},{key:"Cache-Control",value:"no-cache"}]}]),fs=Object.freeze(["csp","cache"]);function ot(r,e=!1){return`public, max-age=${r}${e?", immutable":""}`}function qt(r,e){return{source:r,headers:[{key:"Cache-Control",value:e}]}}var hs=Object.freeze(["'self'","'none'","'unsafe-inline'","'unsafe-eval'","'unsafe-hashes'","'wasm-unsafe-eval'","'strict-dynamic'","'report-sample'"]),fi=/^'sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2}'$/;function hi(r,e){if(typeof e!="string"||e===""||/[\s;,]/.test(e))throw new Error(`[dndev] appConfig.headers.csp['${r}']: invalid source ${JSON.stringify(e)} (one origin, keyword or hash per entry, no spaces, ';' or ',').`);if(e.includes("'")&&!hs.includes(e)&&!fi.test(e))throw new Error(`[dndev] appConfig.headers.csp['${r}']: invalid quoted source ${JSON.stringify(e)} (allowed: ${hs.join(" ")} or a hash like 'sha256-<base64>').`)}function gi(r){if(r===void 0)return{csp:{},cache:[]};if(!r||typeof r!="object"||Array.isArray(r))throw new Error("[dndev] appConfig.headers must be an object.");for(let n of Object.keys(r))if(!fs.includes(n))throw new Error(`[dndev] appConfig.headers.${n} is not a header option (allowed: ${fs.join(", ")}).`);let e=r.csp??{};for(let[n,s]of Object.entries(e)){if(!Jt.includes(n))throw new Error(`[dndev] appConfig.headers.csp['${n}'] is not a CSP directive the framework merges (allowed: ${Jt.join(", ")}).`);if(!Array.isArray(s))throw new Error(`[dndev] appConfig.headers.csp['${n}'] must be an array of sources.`);for(let o of s)hi(n,o)}let t=r.cache??[];if(!Array.isArray(t))throw new Error("[dndev] appConfig.headers.cache must be an array.");for(let n of t){if(typeof n?.source!="string"||!n.source.startsWith("/"))throw new Error(`[dndev] appConfig.headers.cache: source must be a path starting with '/' (got ${JSON.stringify(n?.source)}).`);if(!Number.isInteger(n.maxAge)||n.maxAge<0)throw new Error(`[dndev] appConfig.headers.cache '${n.source}': maxAge must be a whole number of seconds (got ${JSON.stringify(n.maxAge)}).`)}return{csp:e,cache:t}}function mi({csp:r={},providers:e=[],target:t}){if(!(t in ps))throw new Error(`[dndev] Unknown header target '${t}' (expected next, next-export or vite).`);return[...Jt.map(s=>{let o=[...s==="script-src"?ps[t]:oi[s]??[],...e.flatMap(l=>vs[l]?.[s]??[]),...r[s]??[]],a=[...new Set(o)],i=a.length>1?a.filter(l=>l!=="'none'"):a;return i.length>0?`${s} ${i.join(" ")}`:null}).filter(Boolean),"upgrade-insecure-requests"].join("; ")}function ws({appConfig:r,target:e,providers:t=[],pwa:n=!1}){if(!(e in ds))throw new Error(`[dndev] Unknown header target '${e}' (expected next, next-export or vite).`);let{csp:s,cache:o}=gi(r?.headers),a=[{key:"Content-Security-Policy",value:mi({csp:s,providers:t,target:e})},...r?.seo===!1?[ii]:[],...ai].map(i=>({...i}));return[{source:si,headers:a},...[...ds[e],ui].map(i=>qt(i,ot(li,!0))),...pi.map(i=>qt(`/:path*.${i}`,ot(ci))),{source:"/:path*.json",headers:[{key:"Cache-Control",value:ot(bs)},{key:"Content-Type",value:"application/json; charset=utf-8"}]},...n?di.map(i=>({source:i.source,headers:i.headers.map(l=>({...l}))})):[],...o.map(i=>qt(i.source,ot(i.maxAge,i.immutable===!0)))]}function Ss(r){let e=ys(r,"package.json");if(!gs(e))return[];let t=JSON.parse(ms(e,"utf8")),n={...t.dependencies,...t.devDependencies};return Object.keys(vs).filter(s=>!!n[s])}function Es(r){let e=ys(r,"vercel.json");if(!gs(e))return null;try{return{path:e,config:JSON.parse(ms(e,"utf8"))}}catch(t){throw new Error(`[dndev] ${e} is not valid JSON: ${t.message}`)}}function Rs({appRoot:r,rules:e,ci:t,logger:n}){let s=Es(r);if(!s)return"absent";if(JSON.stringify(s.config.headers)===JSON.stringify(e))return"unchanged";if(t)throw new Error(`[dndev] ${s.path}: "headers" differ from the framework header policy (appConfig.headers, appConfig.seo). The host reads the committed file, so this deploy would serve stale headers. Run the app locally (dev or build) to regenerate vercel.json, then commit it.`);let o=`${JSON.stringify({...s.config,headers:e},null,2)}
|
|
1212
|
+
`;return ri(s.path,o),n?.info(`vercel.json headers regenerated from the header policy (${e.length} rules)`),"written"}function $s(r){let e=Es(r);if(e&&"headers"in e.config)throw new Error(`[dndev] ${e.path} has "headers": Next serves the framework header policy from next.config headers(). Remove the "headers" key; declare app deltas (CSP sources, cache overrides) in appConfig.headers.`)}var yi=new Set(["@donotdev/functions"]);function xs(){try{let r=D.getInstance(),e=r.resolveAppPath("package.json"),t=r.readSync(e,{format:"json"});if(!t)return[];let n={...t.dependencies,...t.devDependencies};return Object.keys(n).filter(s=>s.startsWith("@donotdev/")).filter(s=>!Le.buildTimePackages.includes(s)).filter(s=>!yi.has(s)).sort()}catch{return[]}}var Vt=new Map;function vi(r={}){let{port:e,...t}=r;if(e&&process.env.NODE_ENV!=="production"&&(process.env.PORT=String(e)),!process.env.DNDEV_BUILD_ID){let re=process.env.CI==="true";process.env.DNDEV_BUILD_ID=re?`ci-${Math.random().toString(36).slice(2,9)}`:Math.random().toString(36).slice(2,9)}let n=process.env.DNDEV_BUILD_ID;if(n&&Vt.has(n))return Vt.get(n).configFn;let{appConfig:s,...o}=t;if(!s)throw new Error("appConfig is required. Import appConfig from src/config/app.ts and pass it to defineNextConfig({ appConfig, ... })");let a=s?.features?{debug:s.features.debug}:void 0,i=s?.seo===!1?{disabled:!0}:s?.seo&&typeof s.seo!="boolean"?{...s.seo,siteName:s.seo.siteName||s.app?.name,siteDescription:s.app?.description}:s?.app?.name?{siteName:s.app.name,siteDescription:s.app.description}:void 0,l=s?.app?{name:s.app.name,shortName:s.app.shortName,description:s.app.description}:void 0,{features:u,seo:c,...p}=o,d={...a?{features:a}:{},...i?{seo:i}:{},...p},f=sr(d),h=or(f);if(!h)throw new Error("normalizeOptions returned undefined");let{generateManifest:m,debug:y,verbose:S,mode:T,isDev:R,routeOptions:v,themeOptions:x,i18nOptions:O,assetOptions:B,pwaOptions:M,seoOptions:te,nextConfigOptions:W,reactCompiler:g}=h,b=ae("next-config",y,S),{appRoot:k,appRootSet:N}=ln({logger:b,debug:y}),_=v?.routingMode||"app",F=N&&Pt(k);if(F||(b.info(`
|
|
1213
|
+
\u{1F3D7}\uFE0F DnDev Framework - Building for ${T}${n?` [build:${n}]`:""}`),b.info(` Platform: Next.js | Routing: ${_}
|
|
1214
|
+
`)),R){let re=process.env.PORT||3e3;process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${re}`,y&&(b.debug(`NEXT_PUBLIC_APP_URL: ${process.env.NEXT_PUBLIC_APP_URL}`),e&&b.debug(`Port configured: ${re} (set PORT env var)`))}else!process.env.NEXT_PUBLIC_APP_URL&&!Qe()&&(process.env.NEXT_PUBLIC_APP_URL=`http://localhost:${process.env.PORT||3e3}`);let A=W.trailingSlash===!0,G=us({debug:y,verbose:S,generateManifest:m,routeOptions:{...v,ssr:s?.ssr!==!1,auth:s?.auth,revalidate:s?.revalidate,prerenderRecords:s?.prerenderRecords,trailingSlash:A,siteName:s?.seo?.siteName||s?.app?.name,defaultImage:s?.seo?.defaultImage,defaultNamespace:s?.seo?.defaultNamespace},themeOptions:x,i18nOptions:O,assetOptions:B,seoOptions:{...te,revalidate:s?.revalidate,trailingSlash:A},pwaOptions:{...M,app:l},isDev:R,logger:b}),j=async function(){let w=D.getInstance(),E=N?xs():[];y&&E.length>0&&b.debug(`Discovered ${E.length} packages: ${E.join(", ")}`);let{missing:P}=Je(w.getAppRoot());y&&P.length>0&&b.debug(`Missing optional deps (will alias to empty): ${P.join(", ")}`),N&&(_==="app"&&gn({pathResolver:w,logger:b,isCI:!!(process.env.CI||process.env.VERCEL)}),await tr(G,b,{appFonts:s?.fonts}));let I=W,{rewrites:V,redirects:ge,headers:de,...me}=I,Ie=yn({originalRewrites:V,handlers:[G.routeHandler,G.themeHandler,G.i18nHandler,G.assetHandler,G.pwaHandler],logger:b}),it=vn({originalRedirects:ge,seoRedirects:te?.redirects||[],logger:b}),ie=me.output==="export",Yt=N?ws({appConfig:s,target:ie?"next-export":"next",providers:Ss(w.getAppRoot()),pwa:M?.enabled===!0}):[];N&&ie?Rs({appRoot:w.getAppRoot(),rules:Yt,ci:!!(process.env.CI||process.env.VERCEL),logger:b}):N&&$s(w.getAppRoot());let Ds=ie?null:bn({policyRules:R?[]:Yt,originalHeaders:de}),Ts={_DNDEV_CONFIG_:JSON.stringify({platform:"nextjs",mode:process.env.NODE_ENV||"development",context:"build",timestamp:Date.now()})},Os=wn({restNextConfig:me,discoveredPackages:E,reactCompiler:g,routingMode:_,rewritesConfig:Ie,redirectsConfig:it,headersConfig:Ds,missingOptionalDeps:P,pathResolver:w,env:Ts,logger:b});if(b.debug("Next.js config generated"),N&&!F){let Fs=l?.name||"app";b.info(`Name: ${Fs}`),b.info(`URL: ${process.env.NEXT_PUBLIC_APP_URL||"http://localhost:3000"}`),b.info(`App root (final): ${w.getAppRoot()}`)}return Os};return n&&Vt.set(n,{configFn:j}),j}var Ps=vi;import{readFileSync as bi,existsSync as wi}from"node:fs";import{join as Si}from"node:path";var Oe=null,Kt=0,Ei=6e4;function Ri(){let r=Date.now();if(Oe&&r-Kt<Ei)return Oe;try{let e=Si(process.cwd(),"public","metadata-manifest.json");if(!wi(e))return null;let t=bi(e,"utf-8");return Oe=JSON.parse(t),Kt=r,Oe}catch{return null}}function $i(r,e,t){let n=Ri(),s={title:t?.siteName||"Site"};if(!n)return s;let o=r.startsWith("/")?r:`/${r}`,a=n[o];if(!a)return s;let i=e||a.defaultLocale||"en",l=a.locales[i]||a.locales[a.defaultLocale]||Object.values(a.locales)[0];if(!l)return s;let u=process.env.NEXT_PUBLIC_APP_URL,c={title:l.title,...u&&{metadataBase:new URL(u)}};return l.description&&(c.description=l.description),l.keywords&&(c.keywords=l.keywords),c.openGraph={title:l.title,type:l.type||"website",...l.description&&{description:l.description},...l.image&&{images:[l.image]},...t?.siteName&&{siteName:t.siteName}},c.twitter={card:"summary_large_image",title:l.title,...l.description&&{description:l.description},...l.image&&{images:[l.image]}},l.robots&&(c.robots={index:!1,...l.robots==="noindex, nofollow"&&{follow:!1}}),c}function xi(){Oe=null,Kt=0}function at(r){return String(r).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function Pi(r,{baseUrl:e,routing:t,trailingSlash:n,crud:s,readSchemas:o,languageUrls:a,hiddenStatuses:i}){let l=[],u=(c,p)=>{let d=a(c,e,t,n),f=t.languages.length>1?{alternates:{languages:d}}:{};for(let h of t.languages)l.push({url:d[h],...p,...f})};for(let{route:c,path:p,record:d}of await Ye(r,s,i,o)){if(!d){u(p,{changeFrequency:c.changeFrequency??"weekly",priority:c.priority??(p==="/"?1:.8),...c.lastModified&&{lastModified:c.lastModified}});continue}let f=d.updatedAt instanceof Date?d.updatedAt.toISOString():d.updatedAt;u(p,{changeFrequency:c.changeFrequency??"weekly",priority:c.priority??.7,...typeof f=="string"&&{lastModified:f}})}return l}function Ci(r){let t=['<?xml version="1.0" encoding="UTF-8"?>',`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${r.some(n=>n.alternates)?' xmlns:xhtml="http://www.w3.org/1999/xhtml"':""}>`];for(let n of r){t.push(" <url>",` <loc>${at(n.url)}</loc>`);for(let[s,o]of Object.entries(n.alternates?.languages??{}))t.push(` <xhtml:link rel="alternate" hreflang="${at(s)}" href="${at(o)}" />`);n.lastModified&&t.push(` <lastmod>${at(n.lastModified)}</lastmod>`),n.changeFrequency&&t.push(` <changefreq>${n.changeFrequency}</changefreq>`),n.priority!==void 0&&t.push(` <priority>${n.priority}</priority>`),t.push(" </url>")}return t.push("</urlset>",""),t.join(`
|
|
1215
|
+
`)}import Ni from"i18next";function Cs(r,e){return r.startsWith("/")?`${e}${r}`:r}function Xt(r){return typeof r=="object"&&r!==null&&"collection"in r&&"fields"in r}function As(r,e,t){for(let n of Object.values(r))if(Xt(n)&&n.collection===e)return n;throw new Error(`[dndev] Entity page "${t}": no entity definition for collection "${e}". Export it from the app's \`entities\` package, or mark the page \`seo: { noindex: true }\`.`)}function Ai(r,e,t){let n=Object.create(null);for(let s of e)!s.collection||Object.hasOwn(n,s.collection)||(n[s.collection]=t(As(r,s.collection,s.path)).get);return Object.freeze(n)}function Ns(r,e){let{route:t,value:n,language:s,baseUrl:o,siteName:a,type:i}=e,l=As(e.entities,t.collection,t.path),u=e.deriveEntitySeo(l,r,{t:e.translate([l.namespace,"crud"]),locale:s}),c=q(t.path)[0],p=t.path.replace(`:${c}`,encodeURIComponent(n)),d=S=>e.languageUrl(S,s,o,e.routing,e.trailingSlash),f=d(p),h=u.title?`${u.title} | ${a}`:a,m=Cs(u.image||e.defaultImage,o),y=i==="product"?e.buildProductJsonLd({...u,images:[...new Set(u.images.map(S=>Cs(S,o)))]},f):null;return{url:f,title:h,...u.description&&{description:u.description},image:m,type:i,jsonLd:y,breadcrumb:u.title?e.buildBreadcrumbJsonLd(p,a,d,u.title):null}}function Fe(r){return r.replace(/\s+/g," ").trim()}function _s(r){let e=[`# ${Fe(r.name)}`,""];r.summary&&e.push(`> ${Fe(r.summary)}`,"");for(let t of r.sections)if(t.links.length!==0){e.push(`## ${Fe(t.heading)}`,"");for(let n of t.links){let s=`- [${Fe(n.title)}](${n.url})`;e.push(n.description?`${s}: ${Fe(n.description)}`:s)}e.push("")}return e.join(`
|
|
1216
|
+
`)}function _i(r){let e=new Map;for(let t of Object.values(r))Xt(t)&&e.set(t.collection,t);return e}function ki(r,e){let t=Ni.createInstance();return t.init({lng:r,resources:{[r]:e},ns:Object.keys(e),interpolation:{escapeValue:!1},initAsync:!1}),n=>t.getFixedT(r,[n,"crud"])}async function Di(r){let{crud:e,readSchemas:t,deriveEntitySeo:n,hiddenStatuses:s,formatTrailingSlash:o,trailingSlash:a}=r,i=_i(r.entities),l,u=new Map,c=p=>{let d=u.get(p);return d||(d={heading:p,links:[]},u.set(p,d)),d};c(r.pagesHeading);for(let{route:p,path:d,record:f}of await Ye(r.routes,e,s,t)){let h=`${r.baseUrl}${o(d,a)}`;if(!f){if(!p.title)throw new Error(`[dndev] llms.txt: source route "${p.path}" has no title (getLlmsTxtSource gives every static page one).`);c(p.section??r.pagesHeading).links.push({title:p.title,url:h,...p.description&&{description:p.description}});continue}let m=i.get(p.collection);if(!m)throw new Error(`[dndev] llms.txt: no entity definition for collection "${p.collection}" (route "${p.path}"). Export it from the app's \`entities\` package.`);let y=p.section??(m.namespace?r.entityHeadings[m.namespace]:void 0);if(!y)throw new Error(`[dndev] llms.txt: no heading for route "${p.path}". Add "namePlural" to the ${m.namespace??`entity-${m.name.toLowerCase()}`} translations.`);if(!l){if(!r.language||!r.translations)throw new Error("[dndev] llms.txt: source has no language/translations (getLlmsTxtSource writes them).");l=ki(r.language,r.translations)}let S=n(m,f,{t:l(m.namespace),locale:r.language});c(y).links.push({title:S.title||r.name,url:h,...S.description&&{description:S.description}})}return _s({name:r.name,...r.summary&&{summary:r.summary},sections:[...u.values()]})}var ks=new Set(["website","article"]);async function Ti(r,e,t,n,s){let o=q(r.path),a=o[0];if(o.length!==1||!r.collection||!a)throw new Error(`[dndev] Entity page "${r.path}": only single-param routes of an entity collection read a record.`);if(!t)throw new Error(`[dndev] Entity page "${r.path}" reads a "${r.collection}" record but no server CRUD reader was given.`);let i=Mt(r,s),l;try{l=await t.query(r.collection,{where:[{field:a,operator:"==",value:e},{field:"status",operator:"not-in",value:[...n]}],limit:1},i)}catch(u){let c=u?.details?.originalMessage??u?.message??String(u);throw new Error(`[dndev] Entity page "${r.path}" could not read its public "${r.collection}" record (signed-out visitor: RLS / Security Rules must allow it): ${c}`,{cause:u})}return l.items[0]??null}function Oi(r,e){let{title:t,description:n,image:s,type:o,jsonLd:a,breadcrumb:i}=Ns(r,e);return{metadata:{title:{absolute:t},...n&&{description:n},openGraph:{title:{absolute:t},...n&&{description:n},...ks.has(o)&&{type:o},images:[s]},twitter:{card:"summary_large_image",title:{absolute:t},...n&&{description:n},images:[s]}},ogType:ks.has(o)?null:o,jsonLd:a,breadcrumb:i}}function Fi(r){return JSON.stringify(r).replace(/</g,"\\u003c")}export{_r as REVALIDATE_ROUTE_PATH,Te as REVALIDATE_SECRET_ENV,Za as appBaseUrl,Di as buildLlmsTxt,Pi as buildSitemap,xi as clearMetadataCache,Ps as default,Ps as defineNextConfig,Ks as definePostCSSConfig,Oi as entityPageSeo,Ai as entityReadSchemas,Ci as formatSitemapXml,$i as getMetadataForPath,Ca as handleRevalidationWebhook,Fi as jsonLdScript,wa as listStaticParams,Ti as readEntityPageRecord,kr as revalidationPaths};
|