@teispace/next-maker 4.0.0 → 4.0.2
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/CHANGELOG.md +14 -0
- package/dist/index.js +172 -164
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,30 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Na=Object.defineProperty;var Ge=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var Rr=(e,t)=>{for(var r in t)Na(e,r,{get:t[r],enumerable:!0})};import{existsSync as br}from"node:fs";import Ie from"node:fs/promises";import Ui from"node:path";var g,h,b,C,v,_,l,w=Ge(()=>{"use strict";g=async e=>Ie.readFile(e,"utf-8"),h=async(e,t)=>{await Ie.mkdir(Ui.dirname(e),{recursive:!0}),await Ie.writeFile(e,t,"utf-8")},b=async(e,t)=>{await Ie.mkdir(Ui.dirname(t),{recursive:!0}),await Ie.copyFile(e,t)},C=async e=>{br(e)&&await Ie.unlink(e)},v=async e=>{br(e)&&await Ie.rm(e,{recursive:!0,force:!0})},_=async(e,t)=>{let r=await g(e),i=JSON.parse(r),n=t(i);await h(e,JSON.stringify(n,null,2))},l=e=>br(e)});var Xi={};Rr(Xi,{PROJECT_PATHS:()=>a});var a,P=Ge(()=>{"use strict";a={NEXT_CONFIG:"next.config.ts",POSTCSS_CONFIG:"postcss.config.mjs",BIOME_CONFIG:"biome.json",VITEST_CONFIG:"vitest.config.ts",TEST_DIR:"test",TS_CONFIG:"tsconfig.json",PACKAGE_JSON:"package.json",ENV_EXAMPLE:".env.example",GITIGNORE:".gitignore",README:"README.md",LICENSE:"LICENSE",CHANGELOG:"CHANGELOG.md",NVM_RC:".nvmrc",NPM_RC:".npmrc",AGENTS_MD:"AGENTS.md",CLAUDE_MD:"CLAUDE.md",SRC:"src",APP:"src/app",COMPONENTS:"src/components",LIB:"src/lib",PROVIDERS:"src/providers",STYLES:"src/styles",TYPES:"src/types",UTILS:"src/lib/utils",HOOKS:"src/hooks",SERVICES:"src/services",STORE:"src/store",I18N:"src/i18n",GLOBALS_CSS:"src/styles/globals.css",ROOT_LAYOUT:"src/app/layout.tsx",ROOT_PAGE:"src/app/page.tsx",ROOT_PROVIDER:"src/providers/RootProvider.tsx",PROVIDERS_INDEX:"src/providers/index.ts",COMPONENTS_INDEX:"src/components/index.ts",TYPES_INDEX:"src/types/index.ts",UTILS_INDEX:"src/lib/utils/index.ts",CONFIG_INDEX:"src/lib/config/index.ts",CONSTANTS:"src/lib/config/constants.ts",APP_LOCALES:"src/lib/config/app-locales.ts",SEO_FILE:"src/lib/config/seo.ts",SITEMAP_FILE:"src/app/sitemap.ts",MIDDLEWARE:"src/middleware.ts",PROXY:"src/proxy.ts",I18N_TYPES:"src/types/i18n.ts",HTTP_UTILS:"src/lib/utils/http",HTTP_SHARED:"src/lib/utils/http/shared",HTTP_SERVER_FILE:"src/lib/utils/http/server.ts",HTTP_BUNDLE_SENTINEL_DIR:"src/lib/utils/http/__bundle-sentinel__",HTTP_BUNDLE_SENTINEL_FILE:"src/lib/utils/http/__bundle-sentinel__/client-bundle-sentinel.tsx",WS_UTILS:"src/lib/utils/ws",WS_SLICE_FILE:"src/store/slices/ws.slice.ts",WS_SLICE_TEST_FILE:"src/store/slices/ws.slice.test.ts",ROOT_REDUCER:"src/store/rootReducer.ts",TEST_SETUP_FILE:"test/setup.ts",AXIOS_CLIENT:"src/lib/utils/http/axios-client",FETCH_CLIENT:"src/lib/utils/http/fetch-client",AXIOS_CLIENT_FILE:"src/lib/utils/http/axios-client/index.ts",FETCH_CLIENT_FILE:"src/lib/utils/http/fetch-client/index.ts",CLIENT_UTILS:"src/lib/utils/http/client-utils.ts",APP_APIS:"src/lib/config/app-apis.ts",API_URL_FILE:"src/lib/config/api-url.ts",STORAGE_SERVICE:"src/services/storage",COUNTER_FEATURE:"src/features/counter",I18N_DIR:"src/i18n",LOCALE_DIR:"src/app/[locale]",ERRORS_DIR:"src/lib/errors",UTILITY_TYPES_DIR:"src/types/utility",COMMON_TYPES_DIR:"src/types/common",HTTP_TYPES:"src/types/common/http.types.ts",GITHUB_DIR:".github",HUSKY_DIR:".husky",STORE_PROVIDER:"src/providers/StoreProvider.tsx",THEME_PROVIDER:"src/providers/CustomThemeProvider.tsx",COUNTER_COMPONENT:"src/features/counter/components/Counter.tsx",LOCALE_PAGE:"src/app/[locale]/page.tsx",LOCALE_LAYOUT:"src/app/[locale]/layout.tsx",COMMITLINT_CONFIG:"commitlint.config.mjs",LINTSTAGED_RC:".lintstagedrc.mjs",CZRC:".czrc",DOCKERIGNORE:".dockerignore",DOCKERFILE:"Dockerfile",DOCKER_COMPOSE:"docker-compose.yml",GITHUB_WORKFLOWS:".github/workflows",GITHUB_ISSUE_TEMPLATE:"ISSUE_TEMPLATE",GITHUB_PR_TEMPLATE:"PULL_REQUEST_TEMPLATE.md",CODE_OF_CONDUCT:"CODE_OF_CONDUCT.md",CONTRIBUTING:"CONTRIBUTING.md",SECURITY:"SECURITY.md",SCRIPTS_DIR:"scripts",DOCS_DIR:"docs",CLAUDE_DIR:".claude",VSCODE_DIR:".vscode"}});var nn={};Rr(nn,{cleanupHttpTypes:()=>Ue,injectBundleSentinel:()=>rn,installBundleSentinelMount:()=>tt,isFileUsed:()=>dc,isStringUsed:()=>uc,migrateClientUsages:()=>jr,removeBundleSentinelMount:()=>rt,removeHttpExports:()=>Mr,resolveBundleSentinelLayoutPath:()=>Lr,rewriteSentinelImports:()=>we,rewriteServerEntryImports:()=>Pe,stripBundleSentinel:()=>_t,stripSaveAuthTokens:()=>Dr,updateConfigIndex:()=>Or,updateHttpIndex:()=>Ar,updateTypesIndex:()=>Fr,updateUtilsIndex:()=>_r});import{execFile as cc}from"node:child_process";import D from"node:path";import{promisify as pc}from"node:util";async function Nr(e,t,r){try{let{stdout:i}=await lc("grep",[...r,"--include=*.ts","--include=*.tsx",e,t]);return i}catch(i){if(i.code===1)return"";throw i}}var lc,Ar,_r,Fr,Or,Ue,Dr,jr,Lr,mc,Qi,en,rn,_t,tt,rt,Mr,dc,uc,we,Pe,tn,Be=Ge(()=>{"use strict";P();w();lc=pc(cc);Ar=async(e,t)=>{let r=D.join(e,a.HTTP_UTILS,"index.ts");if(l(r)){let i=await g(r);i=i.replace(/export .* from '\.\/axios-client';?\n?/g,""),i=i.replace(/export .* from '\.\/fetch-client';?\n?/g,""),t.includes("fetch")&&!i.includes("fetch-client")&&(i+=`export * from './fetch-client';
|
|
3
3
|
`),t.includes("axios")&&!i.includes("axios-client")&&(i+=`export * from './axios-client';
|
|
4
|
-
`),await h(r,i)}},
|
|
5
|
-
`,await h(t,r))}},
|
|
4
|
+
`),await h(r,i)}},_r=async e=>{let t=D.join(e,a.UTILS_INDEX);if(l(t)){let r=await g(t);r.includes("./http")||(r+=`export * from './http';
|
|
5
|
+
`,await h(t,r))}},Fr=async e=>{let t=D.join(e,a.TYPES_INDEX);if(l(t)){let r=await g(t);r.includes("./common")||(r+=`export * from './common';
|
|
6
6
|
`),r.includes("./utility")||(r+=`export * from './utility';
|
|
7
|
-
`),await h(t,r)}},
|
|
8
|
-
`,await h(t,r))}},
|
|
7
|
+
`),await h(t,r)}},Or=async e=>{let t=D.join(e,a.CONFIG_INDEX);if(l(t)){let r=await g(t);r.includes("./app-apis")||(r+=`export * from './app-apis';
|
|
8
|
+
`,await h(t,r))}},Ue=async(e,t)=>{let r=D.join(e,a.HTTP_TYPES);if(l(r)){let i=await g(r);t.includes("axios")||(i=i.replace(/declare module 'axios'\s*\{\s*export interface AxiosRequestConfig\s*\{[\s\S]*?\}\s*\}/g,""),i=`${i.replace(/\n\s*\n/g,`
|
|
9
9
|
|
|
10
10
|
`).trim()}
|
|
11
|
-
`,await h(r,i))}},
|
|
12
|
-
`).filter(d=>d);for(let d of u){if(!l(d))continue;let f=await g(d),
|
|
13
|
-
${
|
|
11
|
+
`,await h(r,i))}},Dr=e=>{let t=e;return t=t.replace(/\/\*\*(?:[^*]|\*(?!\/))*?\*\/\n(?=(?:export\s+)?const\s+BEARER_ALLOWED_ENVS\b)/,""),t=t.replace(/^(?:export\s+)?const\s+BEARER_ALLOWED_ENVS\s*=[\s\S]*?;\n?/m,""),t=t.replace(/^export const SAVE_AUTH_TOKENS\s*=.*;\n?/m,""),t},jr=async(e,t,r)=>{if(t===r)return;let i=t==="fetch"?"fetchClient":"axiosClient",n=r==="fetch"?"fetchClient":"axiosClient",o=t==="fetch"?"fetch-client":"axios-client",s=r==="fetch"?"fetch-client":"axios-client",c=D.join(e,"src");try{let p=await Nr(i,c,["-r","-l"]);if(!p.trim())return;let u=p.trim().split(`
|
|
12
|
+
`).filter(d=>d);for(let d of u){if(!l(d))continue;let f=await g(d),x=!1,I=new RegExp(`(import\\s*\\{[^}]*?)\\b${i}\\b([^}]*?\\}\\s*from\\s*['"][^'"]*?/http['"])`,"g");I.test(f)&&(f=f.replace(I,`$1${n}$2`),x=!0);let H=new RegExp(`import\\s+${i}\\s+from\\s+['"]([^'"]*?)/${o}['"]`,"g");H.test(f)&&(f=f.replace(H,`import ${n} from '$1/${s}'`),x=!0);let k=new RegExp(`\\b${i}\\b(?=\\.)`,"g");k.test(f)&&(f=f.replace(k,n),x=!0);let Z=new RegExp(`\\b${i}\\b(?![.\\w])`,"g");Z.test(f)&&(f=f.replace(Z,n),x=!0),x&&await h(d,f)}}catch(p){console.warn("Warning: Could not scan for HTTP client usages:",p)}},Lr=e=>{let t=D.join(e,a.LOCALE_LAYOUT);if(l(t))return t;let r=D.join(e,a.ROOT_LAYOUT);return l(r)?r:null},mc="// Regression sentinel \u2014 see file comment for what this guards.",Qi="import { HttpClientBundleSentinel } from '@/lib/utils/http/__bundle-sentinel__/client-bundle-sentinel';",en="<HttpClientBundleSentinel />",rn=e=>{if(e.includes(en))return e;let t=e;if(!t.includes(Qi)){let o=/(^import\s[^\n]*\n)+/m,s=t.match(o);if(!s)throw new Error("injectBundleSentinel: no `import` lines found \u2014 expected a layout file with at least one import.");let c=t.slice(0,(s.index??0)+s[0].length),p=t.slice((s.index??0)+s[0].length);t=`${c}${mc}
|
|
13
|
+
${Qi}
|
|
14
14
|
${p}`}let r=/(<RootProvider\b[^>]*>)\n([ \t]*)/,i=t.match(r);if(!i)throw new Error("injectBundleSentinel: could not locate `<RootProvider \u2026>` opening tag \u2014 layout shape unexpected.");let n=i[2];return t=t.replace(r,`$1
|
|
15
|
-
${n}${
|
|
16
|
-
${n}`),t},
|
|
17
|
-
`).filter(u=>{let[d]=u.split(":"),f=
|
|
18
|
-
`).filter(c=>{let[p]=c.split(":"),u=
|
|
15
|
+
${n}${en}
|
|
16
|
+
${n}`),t},_t=e=>{let t=e,r=/@\/lib\/utils\/http\/__bundle-sentinel__\/client-bundle-sentinel/,i=new RegExp(`(?:^[ \\t]*//[^\\n]*\\n)?^[ \\t]*import[^\\n]*${r.source}[^\\n]*\\n`,"m");return t=t.replace(i,""),t=t.replace(/[ \t]*<HttpClientBundleSentinel\s*\/>\s*\n/,""),t},tt=async e=>{let t=Lr(e);if(!t)return;let r=await g(t),i=rn(r);i!==r&&await h(t,i)},rt=async e=>{let t=Lr(e);if(!t)return;let r=await g(t),i=_t(r);i!==r&&await h(t,i)},Mr=async e=>{let t=D.join(e,a.UTILS_INDEX);if(l(t)){let i=await g(t);i=i.replace(/^\s*export\s+\*\s+from\s+['"]\.\/http['"];?.*$/gm,""),await h(t,i)}let r=D.join(e,a.TYPES_INDEX);if(l(r)){let i=await g(r),n=D.join(e,a.COMMON_TYPES_DIR);if(!l(n))i=i.replace(/^\s*export\s+\*\s+from\s+['"]\.\/common['"];?.*$/gm,"");else{let o=D.join(n,"index.ts");if(l(o)){let s=await g(o);s=s.replace(/^\s*export\s+\*\s+from\s+['"]\.\/http\.types['"];?.*$/gm,""),await h(o,s)}}l(D.join(e,a.UTILITY_TYPES_DIR))||(i=i.replace(/^\s*export\s+\*\s+from\s+['"]\.\/utility['"];?.*$/gm,"")),await h(r,i)}},dc=async(e,t,r=[])=>{let i=D.join(e,"src"),o=`from ['"].*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}.*['"]`;try{let s=await Nr(o,i,["-r","-E"]);return s.trim()?s.trim().split(`
|
|
17
|
+
`).filter(u=>{let[d]=u.split(":"),f=D.resolve(e,d);return!r.some(x=>!!(f===x||f.startsWith(x+D.sep)))}).length>0:!1}catch(s){return console.warn(`Warning: Failed to check usage for ${t}:`,s),!0}},uc=async(e,t,r=[])=>{let i=D.join(e,"src");try{let n=await Nr(t,i,["-r","-F"]);return n.trim()?n.trim().split(`
|
|
18
|
+
`).filter(c=>{let[p]=c.split(":"),u=D.resolve(e,p);return!r.some(d=>!!(u===d||u.startsWith(d+D.sep)))}).length>0:!1}catch(n){return console.warn(`Warning: Failed to check usage for string ${t}:`,n),!0}},we=async(e,t)=>{let r=D.join(e,a.HTTP_BUNDLE_SENTINEL_FILE);if(!l(r))return;let i=await g(r),n=["toSearchParams"];if(t.includes("axios")&&n.unshift("axiosClient","createAxiosClient"),t.includes("fetch")){let c=n.indexOf("toSearchParams");n.splice(c,0,"createFetchClient","fetchClient")}n.sort();let o=`import {
|
|
19
19
|
${n.join(`,
|
|
20
20
|
`)},
|
|
21
21
|
} from '@/lib/utils/http';`;i=i.replace(/import\s*\{[^}]*\}\s*from\s*['"]@\/lib\/utils\/http['"];/,o);let s=n.map(c=>` ${c},`).join(`
|
|
22
22
|
`);i=i.replace(/const __sentinel__ = \{[\s\S]*?\};/,`const __sentinel__ = {
|
|
23
23
|
${s}
|
|
24
|
-
};`),await h(r,i)},
|
|
25
|
-
|
|
26
|
-
`),await h(r,i)},
|
|
27
|
-
`})}});import{existsSync as Zc}from"node:fs";import{access as Qc}from"node:fs/promises";import $n from"node:path";var ve,Ht,kn=Me(()=>{"use strict";ve=async(e,t,r)=>{try{return await Qc($n.join(e,r,t)),!0}catch{return!1}},Ht=(e,t,r)=>Zc($n.join(e,t,r))});import{access as Gt,readFile as ep}from"node:fs/promises";import ot from"node:path";var M,Nn=Me(()=>{"use strict";M=async e=>{try{let t=ot.join(e,"package.json"),r=await ep(t,"utf-8"),i=JSON.parse(r),n={...i.dependencies,...i.devDependencies},o=!!(n["@reduxjs/toolkit"]&&n["react-redux"]),s=!!n["next-intl"],c=!!n.axios,p=!1,u=ot.join(e,"src","lib","utils","http","axios-client");try{await Gt(u)}catch{c=!1}let d=ot.join(e,"src","lib","utils","http","fetch-client");try{await Gt(d),p=!0}catch{p=!1}let f;c&&p?f="both":c?f="axios":p?f="fetch":f="none";let y=!!n.vitest;if(!y)try{await Gt(ot.join(e,"vitest.config.ts")),y=!0}catch{}let I="none";if(n["socket.io-client"])try{await Gt(ot.join(e,"src","lib","utils","ws")),I="present"}catch{}return{hasRedux:o,httpClient:f,hasI18n:s,hasTests:y,ws:I}}catch(t){throw new Error(`Failed to detect project setup: ${t}`,{cause:t})}}});var st={};Cr(st,{detectProjectSetup:()=>M,directoryExists:()=>ve,fileExistsAt:()=>Ht});var W=Me(()=>{"use strict";kn();Nn()});import{Command as Cd}from"commander";var Oi={name:"@teispace/next-maker",version:"4.0.0",description:"Create a new Teispace Next.js application with interactive setup.",keywords:["nextjs","react","typescript","tailwindcss","starter","template","redux"],type:"module",homepage:"https://github.com/teispace/npm-packages/tree/main/packages/next-maker#readme",bugs:{url:"https://github.com/teispace/npm-packages/issues"},license:"MIT",author:"Teispace",files:["dist","README.md","LICENSE","CHANGELOG.md"],bin:"dist/index.js",repository:{type:"git",url:"git+https://github.com/teispace/npm-packages.git",directory:"packages/next-maker"},scripts:{build:"tsx build.ts",start:"node dist/index.js",dev:"tsx --watch src/index.ts",test:"vitest run","test:watch":"vitest","test:cov":"vitest run --coverage","type-check":"tsc --noEmit",clean:"rm -rf dist",prepublishOnly:"yarn clean && yarn build"},dependencies:{commander:"^15.0.0",degit:"^3.8.0",enquirer:"^2.4.1",ora:"^9.4.1",picocolors:"^1.1.1","png-to-ico":"^3.0.2",sharp:"^0.35.3"},devDependencies:{"@types/degit":"^2.8.6","@types/node":"^26.2.0",esbuild:"^0.28.2",tsx:"^4.23.12",typescript:"^6.0.3",vitest:"^4.1.11"},engines:{node:">=24.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"}};import Hr from"node:path";import Q from"picocolors";var Ye=new Set;function ji(e){return Ye.add(e),()=>Ye.delete(e)}function Di(e){let{logger:t=p=>console.error(p),exitOnCancel:r=process.env.NODE_ENV!=="test"}=e??{},i=!1,n=async()=>{let p=[...Ye];Ye.clear();for(let u of p)try{await u()}catch(d){t(`Cleanup failed: ${d instanceof Error?d.message:String(d)}`)}},o=()=>{if(i){r&&process.exit(130);return}i=!0;let p=Ye.size>0;n().then(()=>{console.log(""),t("Setup cancelled by user"),console.log(""),r&&process.exit(p?130:0)})},s=p=>{if(p!==null&&typeof p=="object"&&"code"in p&&p.code==="ERR_USE_AFTER_CLOSE"){o();return}if(p instanceof Error){t(`Uncaught exception: ${p.message}`);return}t(`Uncaught exception: ${String(p)}`)},c=p=>{if(p instanceof Error){t(`Unhandled promise rejection: ${p.message}`);return}t(`Unhandled promise rejection: ${String(p)}`)};return process.on("SIGINT",o),process.on("SIGTERM",o),process.on("uncaughtException",s),process.on("unhandledRejection",c),()=>{process.off("SIGINT",o),process.off("SIGTERM",o),process.off("uncaughtException",s),process.off("unhandledRejection",c)}}import se from"picocolors";var Ia={reset:e=>e,red:se.red,green:se.green,yellow:se.yellow,blue:se.blue,cyan:se.cyan,magenta:se.magenta,white:se.white,gray:se.gray,bright:se.bold,dim:se.dim};function ye(e,t="reset"){let r=Ia[t]??(i=>i);console.log(r(e))}function $t(e){ye(`\u2716 ${e}`,"red")}var E=$t;function Li(e){ye(`\u26A0 ${e}`,"yellow")}function m(e){ye(e)}function Mi(){console.log(""),ye("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557","cyan"),ye("\u2551 \u2551","cyan"),ye("\u2551 \u{1F680} Create Teispace Next.js App \u{1F680} \u2551","cyan"),ye("\u2551 \u2551","cyan"),ye("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D","cyan"),console.log("")}import $a from"ora";function S(e="",t){let r=$a({text:e,...t});return r.start(),r}var ka=e=>e.charAt(0).toUpperCase()+e.slice(1),H=e=>e.replace(/-([a-z])/g,(t,r)=>r.toUpperCase()),N=e=>ka(H(e));import Na from"ora";var x=Na();w();import{execFile as Aa}from"node:child_process";import{promisify as Fa}from"node:util";var _a=Fa(Aa),de=(e,t)=>_a("git",e,t?{cwd:t}:void 0);function Oa(e){let t=e.trim();if(!t||t.startsWith("-"))throw new Error(`Invalid git remote "${e}".`);if(!(/^https?:\/\/\S+$/.test(t)||/^git@[\w.-]+:\S+$/.test(t)||/^ssh:\/\/\S+$/.test(t)||/^[\w.-]+\/[\w.-]+$/.test(t)))throw new Error(`Invalid git remote "${e}". Expected an https/ssh URL or "owner/repo".`)}var Gi=async(e,t,r)=>{try{if(await de(["init"],e),await de(["add","."],e),await de(["commit","-m","Initial commit from @teispace/next-maker"],e),t&&(Oa(t),await de(["remote","add","origin",t],e),r)){await de(["fetch","origin"],e);let i="main";try{await de(["show-branch","origin/main"],e)}catch{try{await de(["show-branch","origin/master"],e),i="master"}catch{i="main"}}await de(["merge",`origin/${i}`,"--allow-unrelated-histories","-X","ours"],e),await de(["push","origin",`HEAD:${i}`],e)}}catch(i){console.warn("Failed to initialize git repository",i)}};import{execFile as ja}from"node:child_process";import{promisify as Da}from"node:util";var La=Da(ja),Ke=(e,t,r)=>La(e,t,{cwd:r}),Ui=async(e,t)=>{try{await Ke(t,["install"],e)}catch(r){throw new Error(`Failed to install dependencies with ${t}: ${r}`,{cause:r})}},Y=async(e,t,r)=>{let i=t==="npm"?["run",r]:[r];try{await Ke(t,i,e)}catch(n){console.warn(`Warning: Failed to run script '${r}': ${n}`)}},Ma=()=>{let e=process.env.npm_config_user_agent;if(e){if(e.startsWith("yarn"))return"yarn";if(e.startsWith("pnpm"))return"pnpm";if(e.startsWith("bun"))return"bun"}return"npm"},A=async e=>{let{existsSync:t}=await import("node:fs"),r=await import("node:path");return t(r.join(e,"pnpm-lock.yaml"))?"pnpm":t(r.join(e,"yarn.lock"))?"yarn":t(r.join(e,"bun.lockb"))?"bun":t(r.join(e,"package-lock.json"))?"npm":Ma()},br=async(e,t,r)=>{if(r.length!==0)try{await Ke(t,[...Bi(t),...r],e)}catch(i){throw new Error(`Failed to install packages with ${t}: ${i}`,{cause:i})}},Bi=e=>{switch(e){case"npm":return["install"];case"yarn":return["add"];case"pnpm":return["add"];case"bun":return["add"];default:return["install"]}},z=async(e,t)=>{let r=await A(e);await br(e,r,[t])},Ha=e=>{switch(e){case"npm":return"--save-dev";case"yarn":case"pnpm":case"bun":return"-D";default:return"--save-dev"}},ue=async(e,t,r)=>{if(r.length!==0)try{await Ke(t,[...Bi(t),Ha(t),...r],e)}catch(i){throw new Error(`Failed to install dev packages with ${t}: ${i}`,{cause:i})}},kt=async(e,t)=>{let r=await A(e);await ue(e,r,[t])},Ir=async(e,t,r)=>{if(r.length!==0)try{await Ke(t,[...Ga(t),...r],e)}catch(i){throw new Error(`Failed to uninstall packages with ${t}: ${i}`,{cause:i})}},Ga=e=>{switch(e){case"npm":return["uninstall"];case"yarn":return["remove"];case"pnpm":return["remove"];case"bun":return["remove"];default:return["uninstall"]}},He=async(e,t)=>{let r=await A(e);await Ir(e,r,[t])};import Ua from"enquirer";var Ba=/^[a-z0-9-_]+$/,za=/^\d+\.\d+\.\d+$/,zi=e=>Ba.test(e),Va=e=>za.test(e),Vi=(e,t={})=>{let r=t.projectName??e??"my-app";if(!zi(r))throw new Error(`Invalid project name "${r}". Use lowercase letters, digits, hyphens, and underscores only.`);let i=t.version??"0.1.0";if(!Va(i))throw new Error(`Invalid version "${i}". Expected semver (e.g. 0.1.0).`);let n=t.author??"Teispace",o=t.company??n;return{projectName:r,description:t.description??"A Next.js application",author:n,version:i,packageManager:t.packageManager??"yarn",gitRemote:t.gitRemote??"",pushToRemote:t.pushToRemote??!1,gitIssues:t.gitIssues??"",gitHomepage:t.gitHomepage??"",httpClient:t.httpClient??"fetch",reactSecureStorage:t.reactSecureStorage??!0,email:t.email??"support@example.com",company:o,keepTemplates:t.keepTemplates??!1,darkMode:t.darkMode??!0,redux:t.redux??!0,ws:(t.redux??!0)&&(t.ws??!1),i18n:t.i18n??!0,communityFiles:t.communityFiles??[],readme:t.readme??!0,docker:t.docker??!1,containerName:t.containerName,imageName:t.imageName,imageTag:t.imageTag,ci:t.ci??!1,preCommitHooks:t.preCommitHooks??!0,commitizen:t.commitizen??!0,copyEnv:t.copyEnv??!0,tests:t.tests??!0,reactCompiler:t.reactCompiler??!0,bundleAnalyzer:t.bundleAnalyzer??!1}},{prompt:Ja}=Ua,Ji=async e=>{if(e!==void 0&&!zi(e))throw new Error(`Invalid project name "${e}". Use lowercase letters, digits, hyphens, and underscores only \u2014 no slashes, "..", or absolute paths.`);let t=await Ja([{type:"input",name:"projectName",message:"What is the project name?",initial:e||"my-app",skip:!!e,validate:r=>/^[a-z0-9-_]+$/.test(r)?!0:"Project name must be lowercase and contain only alphanumeric characters, hyphens, and underscores."},{type:"input",name:"description",message:"Project description:",initial:"A Next.js application"},{type:"input",name:"author",message:"Author:",initial:"Teispace"},{type:"input",name:"version",message:"Version:",initial:"0.1.0",validate:r=>/^\d+\.\d+\.\d+$/.test(r)?!0:"Version must be a valid semantic version (x.y.z)."},{type:"input",name:"email",message:"Support email:",initial:"support@example.com",validate:r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)?!0:"Please enter a valid email address."},{type:"select",name:"packageManager",message:"Which package manager would you like to use?",choices:["npm","yarn","pnpm","bun"],initial:1},{type:"input",name:"gitRemote",message:"GitHub repository URL (optional):",initial:""},{type:"confirm",name:"pushToRemote",message:"Would you like to push the changes to the remote repository?",initial:!0,skip:function(){return!this.state?.answers?.gitRemote}},{type:"input",name:"gitIssues",message:"GitHub issues URL (optional):",initial:"",skip:function(){return!this.state?.answers?.gitRemote},validate:r=>r?/^https:\/\/github\.com\/[\w-]+\/[\w.-]+\/issues$/.test(r)?!0:"Please enter a valid GitHub issues URL (e.g., https://github.com/user/repo/issues)":!0},{type:"input",name:"gitHomepage",message:"GitHub homepage URL (optional):",initial:"",skip:function(){return!this.state?.answers?.gitRemote},validate:r=>r?/^https:\/\/github\.com\/[\w-]+\/[\w.-]+#readme$/.test(r)?!0:"Please enter a valid GitHub homepage URL (e.g., https://github.com/user/repo#readme)":!0},{type:"confirm",name:"keepTemplates",message:"Do you want to keep GitHub issue and pull request templates?",initial:!1},{type:"select",name:"httpClient",message:"Which HTTP client do you want to use?",choices:["axios","fetch","both","none"],initial:1},{type:"confirm",name:"reactSecureStorage",message:"Do you want to include react-secure-storage?",initial:!0,skip:function(){let r=this.state?.answers??this.enquirer?.answers??{};return!!(r.httpClient&&r.httpClient!=="none")}},{type:"confirm",name:"darkMode",message:"Do you want to include Dark Mode (Tailwind + @teispace/next-themes)?",initial:!0},{type:"confirm",name:"redux",message:"Do you want to include Redux Toolkit?",initial:!0},{type:"confirm",name:"ws",message:"Do you want to include WebSocket support (socket.io-client + Redux bridge)?",initial:!1,skip:function(){return!(this.state?.answers??this.enquirer?.answers??{}).redux}},{type:"confirm",name:"i18n",message:"Do you want to include Internationalization (next-intl)?",initial:!0},{type:"confirm",name:"tests",message:"Do you want to include testing setup (Vitest + React Testing Library)?",initial:!0},{type:"confirm",name:"reactCompiler",message:"Do you want to enable the React Compiler?",initial:!0},{type:"confirm",name:"bundleAnalyzer",message:"Do you want to include @next/bundle-analyzer?",initial:!1},{type:"multiselect",name:"communityFiles",message:"Select community files to include:",choices:[{name:"CODE_OF_CONDUCT.md",value:"CODE_OF_CONDUCT.md"},{name:"CONTRIBUTING.md",value:"CONTRIBUTING.md"},{name:"SECURITY.md",value:"SECURITY.md"}],initial:[]},{type:"confirm",name:"readme",message:"Do you want to create a README.md?",initial:!0},{type:"confirm",name:"docker",message:"Do you want to include Docker configuration?",initial:!1},{type:"input",name:"containerName",message:"Docker Container Name:",initial:"next-app",skip:function(){return!(this.state?.answers??this.enquirer?.answers??{}).docker},validate:r=>/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(r)?!0:"Invalid Docker container name."},{type:"input",name:"imageName",message:"Docker Image Name:",initial:"nextjs-starter",skip:function(){return!(this.state?.answers??this.enquirer?.answers??{}).docker},validate:r=>/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(r)?!0:"Invalid Docker image name (must be lowercase)."},{type:"input",name:"imageTag",message:"Docker Image Tag:",initial:"latest",skip:function(){return!(this.state?.answers??this.enquirer?.answers??{}).docker},validate:r=>/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/.test(r)?!0:"Invalid Docker image tag."},{type:"confirm",name:"ci",message:"Do you want to include GitHub Actions (CI/CD)?",initial:!1},{type:"confirm",name:"preCommitHooks",message:"Do you want to setup pre-commit hooks (Husky, Commitlint, Lint-staged)?",initial:!0},{type:"confirm",name:"commitizen",message:"Do you want to setup Commitizen?",initial:!0},{type:"confirm",name:"copyEnv",message:"Want to copy .env.example to .env?",initial:!0}]);if(t.company=t.author,t.ws=!!t.redux&&!!t.ws,t.gitRemote&&!t.gitHomepage){let r=t.gitRemote.replace("git@github.com:","https://github.com/").replace(/\.git$/,"");t.gitHomepage=`${r}#readme`,t.gitIssues=`${r}/issues`}return t};w();import Wa from"node:path";var ae=async(e,t)=>{let r=qa(t);await h(Wa.join(e,"test/test-utils.tsx"),r)},qa=({redux:e,i18n:t})=>e&&t?Xa:e?Ya:t?Ka:Za,Xa=`import { type RenderOptions, render } from '@testing-library/react';
|
|
24
|
+
};`),await h(r,i)},Pe=async(e,t)=>{let r=D.join(e,a.HTTP_SERVER_FILE);if(!l(r)||t.length===0)return;let i=await g(r),n=o=>{i=i.replace(o,"")};t.includes("axios")||(n(/^import\s*\{\s*createAxiosClient\s*\}\s*from\s*['"]\.\/axios-client['"];\n?/m),n(/export const axiosClient = createAxiosClient\(\{[\s\S]*?\}\);\n?\n?/),i=tn(i,"createAxiosClient")),t.includes("fetch")||(n(/^import\s*\{\s*createFetchClient\s*\}\s*from\s*['"]\.\/fetch-client['"];\n?/m),n(/export const fetchClient = createFetchClient\(\{[\s\S]*?\}\);\n?\n?/),i=tn(i,"createFetchClient")),i=i.replace(/\n{3,}/g,`
|
|
25
|
+
|
|
26
|
+
`),await h(r,i)},tn=(e,t)=>{let r=/^export\s*\{([^}]*)\};\n?/m;return e.replace(r,(i,n)=>{let o=n.split(",").map(s=>s.trim()).filter(s=>s.length>0&&s!==t);return o.length===0?"":`export { ${o.join(", ")} };
|
|
27
|
+
`})}});import{existsSync as op}from"node:fs";import{access as sp}from"node:fs/promises";import Fn from"node:path";var Se,Ht,On=Ge(()=>{"use strict";Se=async(e,t,r)=>{try{return await sp(Fn.join(e,r,t)),!0}catch{return!1}},Ht=(e,t,r)=>op(Fn.join(e,t,r))});import{access as Ut,readFile as ap}from"node:fs/promises";import at from"node:path";var M,Dn=Ge(()=>{"use strict";M=async e=>{try{let t=at.join(e,"package.json"),r=await ap(t,"utf-8"),i=JSON.parse(r),n={...i.dependencies,...i.devDependencies},o=!!(n["@reduxjs/toolkit"]&&n["react-redux"]),s=!!n["next-intl"],c=!!n.axios,p=!1,u=at.join(e,"src","lib","utils","http","axios-client");try{await Ut(u)}catch{c=!1}let d=at.join(e,"src","lib","utils","http","fetch-client");try{await Ut(d),p=!0}catch{p=!1}let f;c&&p?f="both":c?f="axios":p?f="fetch":f="none";let x=!!n.vitest;if(!x)try{await Ut(at.join(e,"vitest.config.ts")),x=!0}catch{}let I="none";if(n["socket.io-client"])try{await Ut(at.join(e,"src","lib","utils","ws")),I="present"}catch{}return{hasRedux:o,httpClient:f,hasI18n:s,hasTests:x,ws:I}}catch(t){throw new Error(`Failed to detect project setup: ${t}`,{cause:t})}}});var ct={};Rr(ct,{detectProjectSetup:()=>M,directoryExists:()=>Se,fileExistsAt:()=>Ht});var q=Ge(()=>{"use strict";On();Dn()});import{Command as Cd}from"commander";var ji={name:"@teispace/next-maker",version:"4.0.2",description:"Create a new Teispace Next.js application with interactive setup.",keywords:["nextjs","react","typescript","tailwindcss","starter","template","redux"],type:"module",homepage:"https://github.com/teispace/npm-packages/tree/main/packages/next-maker#readme",bugs:{url:"https://github.com/teispace/npm-packages/issues"},license:"MIT",author:"Teispace",files:["dist","README.md","LICENSE","CHANGELOG.md"],bin:"dist/index.js",repository:{type:"git",url:"git+https://github.com/teispace/npm-packages.git",directory:"packages/next-maker"},scripts:{build:"tsx build.ts",start:"node dist/index.js",dev:"tsx --watch src/index.ts",test:"vitest run","test:watch":"vitest","test:cov":"vitest run --coverage","type-check":"tsc --noEmit",clean:"rm -rf dist",prepublishOnly:"yarn clean && yarn build"},dependencies:{commander:"^15.0.0",degit:"^3.8.0",enquirer:"^2.4.1",ora:"^9.4.1",picocolors:"^1.1.1","png-to-ico":"^3.0.2",sharp:"^0.35.3"},devDependencies:{"@types/degit":"^2.8.6","@types/node":"^26.2.0",esbuild:"^0.28.2",tsx:"^4.23.12",typescript:"^6.0.3",vitest:"^4.1.11"},engines:{node:">=24.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"}};import Ur from"node:path";import ee from"picocolors";var Ze=new Set;function Li(e){return Ze.add(e),()=>Ze.delete(e)}function Mi(e){let{logger:t=p=>console.error(p),exitOnCancel:r=process.env.NODE_ENV!=="test"}=e??{},i=!1,n=async()=>{let p=[...Ze];Ze.clear();for(let u of p)try{await u()}catch(d){t(`Cleanup failed: ${d instanceof Error?d.message:String(d)}`)}},o=()=>{if(i){r&&process.exit(130);return}i=!0;let p=Ze.size>0;n().then(()=>{console.log(""),t("Setup cancelled by user"),console.log(""),r&&process.exit(p?130:0)})},s=p=>{if(p!==null&&typeof p=="object"&&"code"in p&&p.code==="ERR_USE_AFTER_CLOSE"){o();return}if(p instanceof Error){t(`Uncaught exception: ${p.message}`);return}t(`Uncaught exception: ${String(p)}`)},c=p=>{if(p instanceof Error){t(`Unhandled promise rejection: ${p.message}`);return}t(`Unhandled promise rejection: ${String(p)}`)};return process.on("SIGINT",o),process.on("SIGTERM",o),process.on("uncaughtException",s),process.on("unhandledRejection",c),()=>{process.off("SIGINT",o),process.off("SIGTERM",o),process.off("uncaughtException",s),process.off("unhandledRejection",c)}}import ae from"picocolors";var _a={reset:e=>e,red:ae.red,green:ae.green,yellow:ae.yellow,blue:ae.blue,cyan:ae.cyan,magenta:ae.magenta,white:ae.white,gray:ae.gray,bright:ae.bold,dim:ae.dim};function xe(e,t="reset"){let r=_a[t]??(i=>i);console.log(r(e))}function Nt(e){xe(`\u2716 ${e}`,"red")}var E=Nt;function Gi(e){xe(`\u26A0 ${e}`,"yellow")}function m(e){xe(e)}function Hi(){console.log(""),xe("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557","cyan"),xe("\u2551 \u2551","cyan"),xe("\u2551 \u{1F680} Create Teispace Next.js App \u{1F680} \u2551","cyan"),xe("\u2551 \u2551","cyan"),xe("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D","cyan"),console.log("")}import Fa from"ora";function S(e="",t){let r=Fa({text:e,...t});return r.start(),r}var Oa=e=>e.charAt(0).toUpperCase()+e.slice(1),G=e=>e.replace(/-([a-z])/g,(t,r)=>r.toUpperCase()),N=e=>Oa(G(e));import Da from"ora";var y=Da();w();import{execFile as ja}from"node:child_process";import{promisify as La}from"node:util";var Ma=La(ja),ue=(e,t)=>Ma("git",e,t?{cwd:t}:void 0);function Ga(e){let t=e.trim();if(!t||t.startsWith("-"))throw new Error(`Invalid git remote "${e}".`);if(!(/^https?:\/\/\S+$/.test(t)||/^git@[\w.-]+:\S+$/.test(t)||/^ssh:\/\/\S+$/.test(t)||/^[\w.-]+\/[\w.-]+$/.test(t)))throw new Error(`Invalid git remote "${e}". Expected an https/ssh URL or "owner/repo".`)}var Bi=async(e,t,r)=>{try{if(await ue(["init"],e),await ue(["add","."],e),await ue(["commit","-m","Initial commit from @teispace/next-maker"],e),t&&(Ga(t),await ue(["remote","add","origin",t],e),r)){await ue(["fetch","origin"],e);let i="main";try{await ue(["show-branch","origin/main"],e)}catch{try{await ue(["show-branch","origin/master"],e),i="master"}catch{i="main"}}await ue(["merge",`origin/${i}`,"--allow-unrelated-histories","-X","ours"],e),await ue(["push","origin",`HEAD:${i}`],e)}}catch(i){console.warn("Failed to initialize git repository",i)}};import{execFile as Ha}from"node:child_process";import{promisify as Ua}from"node:util";var Ba=Ua(Ha),Qe=(e,t,r)=>Ba(e,t,{cwd:r,maxBuffer:64*1024*1024}),Ir=e=>{let t=e;return(`${t.stdout??""}
|
|
28
|
+
${t.stderr??""}`.trim()||(t.message??String(e))).split(`
|
|
29
|
+
`).filter(Boolean).slice(-12).join(`
|
|
30
|
+
`)},zi=async(e,t)=>{try{await Qe(t,["install"],e)}catch(r){throw new Error(`Failed to install dependencies with ${t}:
|
|
31
|
+
${Ir(r)}`,{cause:r})}},K=async(e,t,r)=>{let i=t==="npm"?["run",r]:[r];try{await Qe(t,i,e)}catch(n){console.warn(`Warning: Failed to run script '${r}': ${n}`)}},za=()=>{let e=process.env.npm_config_user_agent;if(e){if(e.startsWith("yarn"))return"yarn";if(e.startsWith("pnpm"))return"pnpm";if(e.startsWith("bun"))return"bun"}return"npm"},A=async e=>{let{existsSync:t}=await import("node:fs"),r=await import("node:path");return t(r.join(e,"pnpm-lock.yaml"))?"pnpm":t(r.join(e,"yarn.lock"))?"yarn":t(r.join(e,"bun.lockb"))?"bun":t(r.join(e,"package-lock.json"))?"npm":za()},$r=async(e,t,r)=>{if(r.length!==0)try{await Qe(t,[...Vi(t),...r],e)}catch(i){throw new Error(`Failed to install packages with ${t}:
|
|
32
|
+
${Ir(i)}`,{cause:i})}},Vi=e=>{switch(e){case"npm":return["install"];case"yarn":return["add"];case"pnpm":return["add"];case"bun":return["add"];default:return["install"]}},z=async(e,t)=>{let r=await A(e);await $r(e,r,[t])},Va=e=>{switch(e){case"npm":return"--save-dev";case"yarn":case"pnpm":case"bun":return"-D";default:return"--save-dev"}},fe=async(e,t,r)=>{if(r.length!==0)try{await Qe(t,[...Vi(t),Va(t),...r],e)}catch(i){throw new Error(`Failed to install dev packages with ${t}:
|
|
33
|
+
${Ir(i)}`,{cause:i})}},At=async(e,t)=>{let r=await A(e);await fe(e,r,[t])},kr=async(e,t,r)=>{if(r.length!==0)try{await Qe(t,[...Ja(t),...r],e)}catch(i){throw new Error(`Failed to uninstall packages with ${t}: ${i}`,{cause:i})}},Ja=e=>{switch(e){case"npm":return["uninstall"];case"yarn":return["remove"];case"pnpm":return["remove"];case"bun":return["remove"];default:return["uninstall"]}},He=async(e,t)=>{let r=await A(e);await kr(e,r,[t])};import Wa from"enquirer";var qa=/^[a-z0-9-_]+$/,Xa=/^\d+\.\d+\.\d+$/,Ji=e=>qa.test(e),Ya=e=>Xa.test(e),Wi=(e,t={})=>{let r=t.projectName??e??"my-app";if(!Ji(r))throw new Error(`Invalid project name "${r}". Use lowercase letters, digits, hyphens, and underscores only.`);let i=t.version??"0.1.0";if(!Ya(i))throw new Error(`Invalid version "${i}". Expected semver (e.g. 0.1.0).`);let n=t.author??"Teispace",o=t.company??n;return{projectName:r,description:t.description??"A Next.js application",author:n,version:i,packageManager:t.packageManager??"yarn",gitRemote:t.gitRemote??"",pushToRemote:t.pushToRemote??!1,gitIssues:t.gitIssues??"",gitHomepage:t.gitHomepage??"",httpClient:t.httpClient??"fetch",reactSecureStorage:t.reactSecureStorage??!0,email:t.email??"support@example.com",company:o,keepTemplates:t.keepTemplates??!1,darkMode:t.darkMode??!0,redux:t.redux??!0,ws:(t.redux??!0)&&(t.ws??!1),i18n:t.i18n??!0,communityFiles:t.communityFiles??[],readme:t.readme??!0,docker:t.docker??!1,containerName:t.containerName,imageName:t.imageName,imageTag:t.imageTag,ci:t.ci??!1,preCommitHooks:t.preCommitHooks??!0,commitizen:t.commitizen??!0,copyEnv:t.copyEnv??!0,tests:t.tests??!0,reactCompiler:t.reactCompiler??!0,bundleAnalyzer:t.bundleAnalyzer??!1}},{prompt:Ka}=Wa,qi=async e=>{if(e!==void 0&&!Ji(e))throw new Error(`Invalid project name "${e}". Use lowercase letters, digits, hyphens, and underscores only \u2014 no slashes, "..", or absolute paths.`);let t=await Ka([{type:"input",name:"projectName",message:"What is the project name?",initial:e||"my-app",skip:!!e,validate:r=>/^[a-z0-9-_]+$/.test(r)?!0:"Project name must be lowercase and contain only alphanumeric characters, hyphens, and underscores."},{type:"input",name:"description",message:"Project description:",initial:"A Next.js application"},{type:"input",name:"author",message:"Author:",initial:"Teispace"},{type:"input",name:"version",message:"Version:",initial:"0.1.0",validate:r=>/^\d+\.\d+\.\d+$/.test(r)?!0:"Version must be a valid semantic version (x.y.z)."},{type:"input",name:"email",message:"Support email:",initial:"support@example.com",validate:r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)?!0:"Please enter a valid email address."},{type:"select",name:"packageManager",message:"Which package manager would you like to use?",choices:["npm","yarn","pnpm","bun"],initial:1},{type:"input",name:"gitRemote",message:"GitHub repository URL (optional):",initial:""},{type:"confirm",name:"pushToRemote",message:"Would you like to push the changes to the remote repository?",initial:!0,skip:function(){return!this.state?.answers?.gitRemote}},{type:"input",name:"gitIssues",message:"GitHub issues URL (optional):",initial:"",skip:function(){return!this.state?.answers?.gitRemote},validate:r=>r?/^https:\/\/github\.com\/[\w-]+\/[\w.-]+\/issues$/.test(r)?!0:"Please enter a valid GitHub issues URL (e.g., https://github.com/user/repo/issues)":!0},{type:"input",name:"gitHomepage",message:"GitHub homepage URL (optional):",initial:"",skip:function(){return!this.state?.answers?.gitRemote},validate:r=>r?/^https:\/\/github\.com\/[\w-]+\/[\w.-]+#readme$/.test(r)?!0:"Please enter a valid GitHub homepage URL (e.g., https://github.com/user/repo#readme)":!0},{type:"confirm",name:"keepTemplates",message:"Do you want to keep GitHub issue and pull request templates?",initial:!1},{type:"select",name:"httpClient",message:"Which HTTP client do you want to use?",choices:["axios","fetch","both","none"],initial:1},{type:"confirm",name:"reactSecureStorage",message:"Do you want to include react-secure-storage?",initial:!0,skip:function(){let r=this.state?.answers??this.enquirer?.answers??{};return!!(r.httpClient&&r.httpClient!=="none")}},{type:"confirm",name:"darkMode",message:"Do you want to include Dark Mode (Tailwind + @teispace/next-themes)?",initial:!0},{type:"confirm",name:"redux",message:"Do you want to include Redux Toolkit?",initial:!0},{type:"confirm",name:"ws",message:"Do you want to include WebSocket support (socket.io-client + Redux bridge)?",initial:!1,skip:function(){return!(this.state?.answers??this.enquirer?.answers??{}).redux}},{type:"confirm",name:"i18n",message:"Do you want to include Internationalization (next-intl)?",initial:!0},{type:"confirm",name:"tests",message:"Do you want to include testing setup (Vitest + React Testing Library)?",initial:!0},{type:"confirm",name:"reactCompiler",message:"Do you want to enable the React Compiler?",initial:!0},{type:"confirm",name:"bundleAnalyzer",message:"Do you want to include @next/bundle-analyzer?",initial:!1},{type:"multiselect",name:"communityFiles",message:"Select community files to include:",choices:[{name:"CODE_OF_CONDUCT.md",value:"CODE_OF_CONDUCT.md"},{name:"CONTRIBUTING.md",value:"CONTRIBUTING.md"},{name:"SECURITY.md",value:"SECURITY.md"}],initial:[]},{type:"confirm",name:"readme",message:"Do you want to create a README.md?",initial:!0},{type:"confirm",name:"docker",message:"Do you want to include Docker configuration?",initial:!1},{type:"input",name:"containerName",message:"Docker Container Name:",initial:"next-app",skip:function(){return!(this.state?.answers??this.enquirer?.answers??{}).docker},validate:r=>/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(r)?!0:"Invalid Docker container name."},{type:"input",name:"imageName",message:"Docker Image Name:",initial:"nextjs-starter",skip:function(){return!(this.state?.answers??this.enquirer?.answers??{}).docker},validate:r=>/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(r)?!0:"Invalid Docker image name (must be lowercase)."},{type:"input",name:"imageTag",message:"Docker Image Tag:",initial:"latest",skip:function(){return!(this.state?.answers??this.enquirer?.answers??{}).docker},validate:r=>/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/.test(r)?!0:"Invalid Docker image tag."},{type:"confirm",name:"ci",message:"Do you want to include GitHub Actions (CI/CD)?",initial:!1},{type:"confirm",name:"preCommitHooks",message:"Do you want to setup pre-commit hooks (Husky, Commitlint, Lint-staged)?",initial:!0},{type:"confirm",name:"commitizen",message:"Do you want to setup Commitizen?",initial:!0},{type:"confirm",name:"copyEnv",message:"Want to copy .env.example to .env?",initial:!0}]);if(t.company=t.author,t.ws=!!t.redux&&!!t.ws,t.gitRemote&&!t.gitHomepage){let r=t.gitRemote.replace("git@github.com:","https://github.com/").replace(/\.git$/,"");t.gitHomepage=`${r}#readme`,t.gitIssues=`${r}/issues`}return t};w();import Za from"node:path";var ce=async(e,t)=>{let r=Qa(t);await h(Za.join(e,"test/test-utils.tsx"),r)},Qa=({redux:e,i18n:t})=>e&&t?ec:e?tc:t?rc:ic,ec=`import { type RenderOptions, render } from '@testing-library/react';
|
|
28
34
|
import { NextIntlClientProvider } from 'next-intl';
|
|
29
35
|
import type { ReactElement, ReactNode } from 'react';
|
|
30
36
|
import { Provider } from 'react-redux';
|
|
@@ -85,7 +91,7 @@ export function renderWithProviders(
|
|
|
85
91
|
|
|
86
92
|
export * from '@testing-library/react';
|
|
87
93
|
export { default as userEvent } from '@testing-library/user-event';
|
|
88
|
-
`,
|
|
94
|
+
`,tc=`import { type RenderOptions, render } from '@testing-library/react';
|
|
89
95
|
import type { ReactElement, ReactNode } from 'react';
|
|
90
96
|
import { Provider } from 'react-redux';
|
|
91
97
|
import { type AppState, type AppStore, makeStore } from '@/store';
|
|
@@ -124,7 +130,7 @@ export function renderWithProviders(
|
|
|
124
130
|
|
|
125
131
|
export * from '@testing-library/react';
|
|
126
132
|
export { default as userEvent } from '@testing-library/user-event';
|
|
127
|
-
`,
|
|
133
|
+
`,rc=`import { type RenderOptions, render } from '@testing-library/react';
|
|
128
134
|
import { NextIntlClientProvider } from 'next-intl';
|
|
129
135
|
import type { ReactElement, ReactNode } from 'react';
|
|
130
136
|
import type { SupportedLocale } from '@/types/i18n';
|
|
@@ -164,7 +170,7 @@ export function renderWithProviders(
|
|
|
164
170
|
|
|
165
171
|
export * from '@testing-library/react';
|
|
166
172
|
export { default as userEvent } from '@testing-library/user-event';
|
|
167
|
-
`,
|
|
173
|
+
`,ic=`import { type RenderOptions, render } from '@testing-library/react';
|
|
168
174
|
import type { ReactElement, ReactNode } from 'react';
|
|
169
175
|
|
|
170
176
|
type TestProvidersProps = {
|
|
@@ -186,13 +192,15 @@ export function renderWithProviders(ui: ReactElement, options: ExtendedRenderOpt
|
|
|
186
192
|
|
|
187
193
|
export * from '@testing-library/react';
|
|
188
194
|
export { default as userEvent } from '@testing-library/user-event';
|
|
189
|
-
`;import
|
|
190
|
-
`),await C(
|
|
195
|
+
`;import Yi from"node:path";var R={REDUX_TOOLKIT:"@reduxjs/toolkit",REACT_REDUX:"react-redux",REDUX:"redux",REDUX_PERSIST:"redux-persist",REACT_SECURE_STORAGE:"react-secure-storage",NEXT_INTL:"next-intl",NEXT_THEMES:"@teispace/next-themes",AXIOS:"axios",HUSKY:"husky",COMMITLINT_CLI:"@commitlint/cli",COMMITLINT_CONFIG:"@commitlint/config-conventional",LINT_STAGED:"lint-staged",COMMITIZEN:"commitizen",CZ_CONVENTIONAL_CHANGELOG:"cz-conventional-changelog",VITEST:"vitest",JSDOM:"jsdom",VITE_PLUGIN_REACT:"@vitejs/plugin-react",TESTING_LIBRARY_DOM:"@testing-library/dom",TESTING_LIBRARY_JEST_DOM:"@testing-library/jest-dom",TESTING_LIBRARY_REACT:"@testing-library/react",TESTING_LIBRARY_USER_EVENT:"@testing-library/user-event",REACT_COMPILER_BABEL:"babel-plugin-react-compiler",NEXT_BUNDLE_ANALYZER:"@next/bundle-analyzer"};P();w();var Ki=async(e,t)=>{if(t.bundleAnalyzer)return;let r=Yi.join(e,a.NEXT_CONFIG);if(l(r)){let i=await g(r);i=i.replace(/import\s+withBundleAnalyzer\s+from\s+'@next\/bundle-analyzer';\n/,""),i=i.replace(/const\s+bundleAnalyzer\s*=\s*withBundleAnalyzer\(\{[\s\S]*?\}\);\n+/,""),i=i.replace(/bundleAnalyzer\(([^)]*)\)/,"$1"),await h(r,i)}await _(Yi.join(e,a.PACKAGE_JSON),i=>(i.devDependencies&&delete i.devDependencies[R.NEXT_BUNDLE_ANALYZER],i.scripts&&delete i.scripts.analyze,i))};P();w();import et from"node:path";var Zi=async(e,t)=>{t.darkMode||(await C(et.join(e,a.THEME_PROVIDER)),await nc(e),await oc(e),await ac(e))},nc=async e=>{let t=et.join(e,a.PROVIDERS_INDEX),r=await g(t);r=r.replace(/export \* from '\.\/CustomThemeProvider';\n/,""),await h(t,r)},oc=async e=>{let t=et.join(e,a.GLOBALS_CSS);if(l(t)){let r=await g(t);r=r.replace(/@custom-variant dark \(.*?\);\n\n/,""),r=r.replace(/@theme \{[\s\S]*?\}\n/,""),await h(t,r)}},sc=e=>e.replace(/\bbg-light\b\s?/g,"").replace(/\bdark:bg-dark\b\s?/g,"").replace(/\s{2,}/g," ").replace(/suppressHydrationWarning=\{true\}/g,""),ac=async e=>{let t=[et.join(e,a.ROOT_LAYOUT),et.join(e,"src/app/[locale]/layout.tsx")];for(let r of t)if(l(r)){let i=await g(r),n=sc(i);n!==i&&await h(r,n)}};P();w();Be();import j from"node:path";var on=async(e,t)=>{let r=j.join(e,a.HTTP_UTILS),i=t.httpClient!=="none"||!!t.reactSecureStorage;t.httpClient==="none"?(await rt(e),await fc(e,r,i)):t.httpClient==="axios"?(await gc(e,r),await we(e,["axios"]),await Pe(e,["axios"])):t.httpClient==="fetch"?(await hc(e,r),await we(e,["fetch"]),await Pe(e,["fetch"])):t.httpClient},fc=async(e,t,r)=>{await v(j.join(e,a.AXIOS_CLIENT)),await v(j.join(e,a.FETCH_CLIENT)),r?(await h(j.join(t,"index.ts"),`export * from './token-store';
|
|
196
|
+
`),await C(j.join(e,a.CLIENT_UTILS)),await Ue(e,[])):(await v(t),await yc(e),await C(j.join(e,a.APP_APIS)),await xc(e)),await wc(e),await v(j.join(e,a.ERRORS_DIR)),r||(await v(j.join(e,a.COMMON_TYPES_DIR)),await v(j.join(e,a.UTILITY_TYPES_DIR)),await Pc(e))},gc=async(e,t)=>{await v(j.join(e,a.FETCH_CLIENT));let r=await g(j.join(t,"index.ts"));r=r.replace(/export .* from '\.\/fetch-client';\n/g,""),await h(j.join(t,"index.ts"),r);let i=j.join(e,a.HTTP_TYPES);if(l(i)){let n=await g(i);n=n.replace(/export interface FetchClientOptions \{[\s\S]*?\}\n\n/,""),n=n.replace(/export interface ExtendedRequestInit extends RequestInit \{[\s\S]*?\}\n\n/,""),await h(i,n)}},hc=async(e,t)=>{await v(j.join(e,a.AXIOS_CLIENT));let r=await g(j.join(t,"index.ts"));r=r.replace(/export .* from '\.\/axios-client';\n/g,""),await h(j.join(t,"index.ts"),r),await Ue(e,["fetch"]);let i=j.join(e,a.HTTP_TYPES);if(l(i)){let n=await g(i);n=n.replace(/export interface AxiosClientOptions \{[\s\S]*?\}\n\n/,""),await h(i,n)}},yc=async e=>{let t=j.join(e,a.UTILS_INDEX);if(l(t)){let r=await g(t);r=r.replace(/export \* from '\.\/http';\n/,""),await h(t,r)}},xc=async e=>{let t=j.join(e,a.CONFIG_INDEX);if(l(t)){let r=await g(t);r=r.replace(/export \* from '\.\/app-apis';\n/,""),await h(t,r)}},wc=async e=>{let t=j.join(e,a.CONSTANTS);if(l(t)){let r=await g(t);r=r.replace(/export const API_RESPONSE_DATA_KEY = 'data';\n/,""),r=Dr(r),await h(t,r)}},Pc=async e=>{let t=j.join(e,a.TYPES_INDEX);if(l(t)){let r=await g(t);r=r.replace(/export \* from '\.\/utility';\n/,""),r=r.replace(/export \* from '\.\/common';\n/,""),await h(t,r)}};P();w();import Q from"node:path";var sn=async(e,t)=>{t.i18n||(await Sc(e),await Ec(e),await Tc(e),await Cc(e),await vc(e))},vc=async e=>{let t=Q.join(e,a.ENV_EXAMPLE);if(!l(t))return;let r=await g(t);r=r.replace(/#[^\n]*IANA time zone[\s\S]*?DEFAULT_TIMEZONE=[^\n]*\n?/,""),r=r.replace(/#[^\n]*Fallback locale[\s\S]*?DEFAULT_LOCALE=[^\n]*\n?/,""),r=r.replace(/^DEFAULT_TIMEZONE=.*\n?/m,""),r=r.replace(/^DEFAULT_LOCALE=.*\n?/m,""),await h(t,r)},Sc=async e=>{await v(Q.join(e,a.I18N_DIR)),await v(Q.join(e,a.LOCALE_DIR)),await C(Q.join(e,a.PROXY)),await C(Q.join(e,a.MIDDLEWARE)),await C(Q.join(e,a.I18N_TYPES)),await C(Q.join(e,a.APP_LOCALES))},Ec=async e=>{let t=Q.join(e,a.TYPES_INDEX);if(l(t)){let i=await g(t);i=i.replace(/export \* from '\.\/i18n';\n/,""),await h(t,i)}let r=Q.join(e,a.CONFIG_INDEX);if(l(r)){let i=await g(r);i=i.replace(/export \* from '\.\/app-locales';\n/,""),await h(r,i)}},Tc=async e=>{let t=Q.join(e,a.NEXT_CONFIG);if(l(t)){let r=await g(t);r=r.replace(/import createNextIntlPlugin from 'next-intl\/plugin';\n/,""),r=r.replace(/const withNextIntl = createNextIntlPlugin\(\);\n+/,""),r=r.replace(/withNextIntl\(([^)]+)\)/,"$1"),await h(t,r)}},Cc=async e=>{let t=Q.join(e,a.COUNTER_COMPONENT);if(l(t)){let n=await g(t);n=n.replace(/import\s+\{\s*useTranslations\s*\}\s+from\s+['"]next-intl['"];\n/,""),n=n.replace(/\s*const\s+t\s*=\s*useTranslations\(['"]Count['"]\);\n/,""),n=n.replace(/\{t\('currentCount',\s*\{\s*count:\s*value\s*\}\)\}/g,"Current Count: {value}"),n=n.replace(/\{t\(['"]increment['"]\)\}/g,"Increment"),n=n.replace(/\{t\(['"]decrement['"]\)\}/g,"Decrement"),n=n.replace(/\{t\(['"]reset['"]\)\}/g,"Reset"),await h(t,n)}let r=Q.join(e,"src/features/counter/components/Counter.test.tsx"),i=Q.join(e,"test/test-utils.tsx");await C(r),await C(i)};P();w();import ve from"node:path";var an=async(e,t)=>{t.httpClient!=="none"||t.reactSecureStorage||await v(ve.join(e,a.STORAGE_SERVICE))},cn=async e=>{await C(ve.join(e,a.LICENSE))},pn=async e=>{await C(ve.join(e,a.CHANGELOG))},ln=async e=>{await C(ve.join(e,a.NVM_RC)),await C(ve.join(e,a.NPM_RC))},mn=async e=>{await v(ve.join(e,a.CLAUDE_DIR)),await v(ve.join(e,a.DOCS_DIR)),await v(ve.join(e,a.VSCODE_DIR))};import dn from"node:path";P();w();var un=async(e,t)=>{if(t.reactCompiler)return;let r=dn.join(e,a.NEXT_CONFIG);if(l(r)){let i=await g(r);i=i.replace(/^\s*reactCompiler:\s*true,?\n/m,""),await h(r,i)}await _(dn.join(e,a.PACKAGE_JSON),i=>(i.devDependencies&&delete i.devDependencies[R.REACT_COMPILER_BABEL],i))};P();w();import $e from"node:path";var fn=async(e,t)=>{t.redux||(await v($e.join(e,a.STORE)),await v($e.join(e,a.COUNTER_FEATURE)),await C($e.join(e,a.STORE_PROVIDER)),await C($e.join(e,"test/test-utils.tsx")),await Rc(e),await bc(e))},Rc=async e=>{let t=$e.join(e,a.PROVIDERS_INDEX),r=await g(t);r=r.replace(/export \* from '\.\/StoreProvider';\n/,""),await h(t,r)},bc=async e=>{let t=[$e.join(e,a.ROOT_PAGE),$e.join(e,a.LOCALE_PAGE)];for(let r of t)if(l(r)){let i=await g(r);i=i.replace(/import\s+\{\s*Counter\s*\}\s+from\s+['"]@\/features\/counter['"];\n?/,""),i=i.replace(/<Counter\s*\/>\n?/g,""),await h(r,i)}};P();w();import gn from"node:path";var hn=async(e,t)=>{if(t.i18n)return;let r=gn.join(e,a.SEO_FILE);l(r)&&await h(r,Ic);let i=gn.join(e,a.SITEMAP_FILE);l(i)&&await h(i,$c)},Ic=`import type { Metadata } from 'next';
|
|
191
197
|
|
|
192
198
|
import { env } from '@/lib/env';
|
|
193
199
|
|
|
194
200
|
const APP_URL = env.NEXT_PUBLIC_APP_URL;
|
|
195
201
|
const APP_NAME = 'Nextjs Starter';
|
|
202
|
+
/** Route served by \`src/app/opengraph-image.tsx\`; relative so \`metadataBase\` resolves it. */
|
|
203
|
+
const DEFAULT_OG_IMAGE_PATH = '/opengraph-image';
|
|
196
204
|
|
|
197
205
|
type SEOParams = {
|
|
198
206
|
title: string;
|
|
@@ -210,7 +218,7 @@ export function generateSEOMetadata({
|
|
|
210
218
|
noIndex = false,
|
|
211
219
|
}: SEOParams): Metadata {
|
|
212
220
|
const url = \`\${APP_URL}\${path}\`;
|
|
213
|
-
const ogImage = image
|
|
221
|
+
const ogImage = image ?? DEFAULT_OG_IMAGE_PATH;
|
|
214
222
|
|
|
215
223
|
return {
|
|
216
224
|
title,
|
|
@@ -253,8 +261,8 @@ export function generateSEOMetadata({
|
|
|
253
261
|
};
|
|
254
262
|
}
|
|
255
263
|
|
|
256
|
-
export { APP_NAME, APP_URL };
|
|
257
|
-
|
|
264
|
+
export { APP_NAME, APP_URL, DEFAULT_OG_IMAGE_PATH };
|
|
265
|
+
`,$c=`import type { MetadataRoute } from 'next';
|
|
258
266
|
|
|
259
267
|
import { env } from '@/lib/env';
|
|
260
268
|
|
|
@@ -270,13 +278,13 @@ export default function sitemap(): MetadataRoute.Sitemap {
|
|
|
270
278
|
priority: path === '/' ? 1 : 0.8,
|
|
271
279
|
}));
|
|
272
280
|
}
|
|
273
|
-
`;import
|
|
281
|
+
`;import kc from"node:fs/promises";import it from"node:path";P();w();var Nc=[R.VITEST,R.JSDOM,R.VITE_PLUGIN_REACT,R.TESTING_LIBRARY_DOM,R.TESTING_LIBRARY_JEST_DOM,R.TESTING_LIBRARY_REACT,R.TESTING_LIBRARY_USER_EVENT],yn=async e=>{let t;try{t=await kc.readdir(e,{withFileTypes:!0})}catch{return}for(let r of t){let i=it.join(e,r.name);if(r.isDirectory()){if(r.name==="__test-utils__"||r.name==="__tests__"){await v(i);continue}await yn(i)}else r.isFile()&&/\.(test|spec)\.tsx?$/.test(r.name)&&await C(i)}},xn=async(e,t)=>{t.tests||(await C(it.join(e,a.VITEST_CONFIG)),await v(it.join(e,a.TEST_DIR)),await yn(it.join(e,a.SRC)),await _(it.join(e,a.PACKAGE_JSON),r=>{if(r.devDependencies)for(let i of Nc)delete r.devDependencies[i];return r.scripts&&(delete r.scripts.test,delete r.scripts["test:watch"],delete r.scripts["test:coverage"],typeof r.scripts.validate=="string"&&(r.scripts.validate=r.scripts.validate.replace(/\s*&&\s*yarn\s+test(?![:\w])/,"").replace(/\byarn\s+test(?![:\w])\s*&&\s*/,""))),r}))};P();w();import ze from"node:path";P();w();import wn from"node:path";import{readFile as Ac,writeFile as _c}from"node:fs/promises";import Fc from"node:path";var nt=(e,t)=>{let r=/import\s+.*\s+from\s+['"].*['"];?\n/g,i=e.match(r);if(i&&i.length>0){let n=i[i.length-1],o=e.lastIndexOf(n);return e.slice(0,o+n.length)+t+`
|
|
274
282
|
`+e.slice(o+n.length)}return`${t}
|
|
275
|
-
${e}`},
|
|
283
|
+
${e}`},Gr=(e,t,r)=>{let i=/combineReducers\(\{([^}]*)\}\)/s,n=e.match(i);if(!n)throw new Error("Could not find combineReducers in rootReducer.ts");let o=n[1],s=`
|
|
276
284
|
${t}: ${r},`,c=o.trimEnd()+s;return e.replace(i,`combineReducers({${c}
|
|
277
|
-
})`)},
|
|
285
|
+
})`)},ot=(e,t)=>{let r=e.lastIndexOf("} as const;");if(r===-1)throw new Error("Could not find closing brace of AppApis object");let i=e.substring(0,r),n=e.substring(r);return`${i.trimEnd()}
|
|
278
286
|
${t}
|
|
279
|
-
${n}`};var
|
|
287
|
+
${n}`};var ke=async e=>{let{projectPath:t,name:r,persist:i,importPath:n}=e,o=Fc.join(t,"src","store","rootReducer.ts");try{let s=await Ac(o,"utf-8"),c=G(r),p=`${c}Reducer`,u=`${c}PersistConfig`,d=n.replace(/^src\//,"@/"),f=i?`import { ${p}, ${u} } from '${d}';`:`import { ${p} } from '${d}';`;s=nt(s,f);let x=i?`persistReducer(${u}, ${p})`:p;s=Gr(s,c,x),await _c(o,s)}catch(s){throw new Error(`Failed to register reducer '${r}' in rootReducer: ${s}`,{cause:s})}};var Pn="import { attachWsBridge, wsClient } from '@/lib/utils/ws';",Oc=`
|
|
280
288
|
// Bridge the WS client's lifecycle into the Redux slice exactly once per
|
|
281
289
|
// store instance. The bridge does not open a connection \u2014 that happens
|
|
282
290
|
// lazily on first \`useWsEvent\` subscription or an explicit \`connect()\`.
|
|
@@ -286,12 +294,12 @@ ${n}`};var $e=async e=>{let{projectPath:t,name:r,persist:i,importPath:n}=e,o=Ic.
|
|
|
286
294
|
if (!store) return;
|
|
287
295
|
return attachWsBridge(wsClient, store.dispatch);
|
|
288
296
|
}, []);
|
|
289
|
-
`,Ft=async e=>{await
|
|
290
|
-
${t.slice(n)}`,t=
|
|
291
|
-
${
|
|
292
|
-
`),t},
|
|
293
|
-
`),/\buseEffect\s*\(/.test(t)||(t=
|
|
294
|
-
`;return e.replace(t,n)},
|
|
297
|
+
`,Ft=async e=>{await ke({projectPath:e,name:"ws",persist:!1,importPath:"src/store/slices/ws.slice"})},Dc=e=>{if(e.includes("from '@/lib/utils/ws'"))return e;let t=e,r=/(^import\s[^\n]*\n)+/m,i=t.match(r);if(!i)throw new Error("injectBridgeMount: no `import` lines found \u2014 expected a StoreProvider with imports.");let n=(i.index??0)+i[0].length;t=`${t.slice(0,n)}${Pn}
|
|
298
|
+
${t.slice(n)}`,t=Gc(t);let o=/(if\s*\(\s*!storeRef\.current\s*\)\s*\{[\s\S]*?\n\s*\})/;if(!t.match(o))throw new Error("injectBridgeMount: could not locate `if (!storeRef.current) { ... }` initializer \u2014 StoreProvider shape unexpected.");return t=t.replace(o,`$1
|
|
299
|
+
${Oc.trimEnd()}
|
|
300
|
+
`),t},Ot=e=>{let t=e;return t=t.replace(new RegExp(`${Hc(Pn)}\\n?`),""),t=t.replace(/\n(?:[ \t]*\/\/[^\n]*\n)*[ \t]*useEffect\(\(\)\s*=>\s*\{[\s\S]*?attachWsBridge\(wsClient,\s*store\.dispatch\)[\s\S]*?\},\s*\[\]\);\n?/,`
|
|
301
|
+
`),/\buseEffect\s*\(/.test(t)||(t=jc(t)),t},jc=e=>{let t=/import\s*\{([^}]*)\}\s*from\s*['"]react['"];\n?/,r=e.match(t);if(!r)return e;let i=r[1].split(",").map(o=>o.trim()).filter(o=>o.length>0&&o!=="useEffect");if(i.length===0)return e.replace(t,"");let n=`import { ${i.join(", ")} } from 'react';
|
|
302
|
+
`;return e.replace(t,n)},Dt=async e=>{let t=wn.join(e,a.STORE_PROVIDER);if(!l(t))return;let r=await g(t),i=Dc(r);i!==r&&await h(t,i)};var jt=async e=>{let t=wn.join(e,a.TEST_SETUP_FILE);if(!l(t))return;let r=await g(t),i=!1;r.includes("vi.mock('react-secure-storage'")||(r+=Lc,i=!0),r.includes("vi.mock('server-only'")||(r+=Mc,i=!0),i&&await h(t,r)},Lc=`
|
|
295
303
|
// \`react-secure-storage\` constructs an \`EncryptionService\` at module load
|
|
296
304
|
// that fingerprints the browser via \`<canvas>.getContext\`. jsdom doesn't
|
|
297
305
|
// implement canvas, so the import explodes anywhere it's pulled in
|
|
@@ -308,15 +316,15 @@ vi.mock('react-secure-storage', () => {
|
|
|
308
316
|
},
|
|
309
317
|
};
|
|
310
318
|
});
|
|
311
|
-
`,
|
|
319
|
+
`,Mc=`
|
|
312
320
|
// \`server-only\` throws at module load outside a Next.js server bundle \u2014
|
|
313
321
|
// the package relies on bundler-level redirect to a no-op file in server
|
|
314
322
|
// environments. Vitest doesn't do that redirect, so we stub it as a no-op
|
|
315
323
|
// to let unit tests reach the server-side modules. Production builds are
|
|
316
324
|
// unaffected; Next.js still routes \`server-only\` to its real implementation.
|
|
317
325
|
vi.mock('server-only', () => ({}));
|
|
318
|
-
`,
|
|
319
|
-
`};n("CONTAINER_NAME",t.containerName||"next-app"),n("IMAGE_NAME",t.imageName||"nextjs-starter"),n("IMAGE_TAG",t.imageTag||"latest"),await h(r,i)}}else{await C(L.join(e,a.DOCKERFILE)),await C(L.join(e,a.DOCKER_COMPOSE)),await C(L.join(e,a.DOCKERIGNORE));let r=L.join(e,a.ENV_EXAMPLE);if(l(r)){let i=await g(r);i=i.replace(/# Docker Compose Configuration\n/,""),i=i.replace(/CONTAINER_NAME=.*\n/,""),i=i.replace(/IMAGE_NAME=.*\n/,""),i=i.replace(/IMAGE_TAG=.*\n/,""),await h(r,i)}}},
|
|
326
|
+
`,Gc=e=>{let t=/import\s*\{([^}]*)\}\s*from\s*['"]react['"];/,r=e.match(t);if(!r)return e;let i=r[1];if(/\buseEffect\b/.test(i))return e;let n=i.split(",").map(s=>s.trim()).filter(Boolean);n.push("useEffect"),n.sort();let o=`import { ${n.join(", ")} } from 'react';`;return e.replace(t,o)},Hc=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Lt=e=>{let t=e;return t=t.replace(/^import\s*\{\s*wsReducer\s*\}\s*from\s*['"][^'"]*ws\.slice['"];\n?/m,""),t=t.replace(/^\s*ws:\s*wsReducer,?\n/m,""),t=t.replace(/\/\*\*[^*]*(?:\*(?!\/)[^*]*)*\bws\b[^*]*(?:\*(?!\/)[^*]*)*\bpersistReducer\b[\s\S]*?\*\/\n?/,""),t};var vn=async(e,t)=>{t.ws||(await v(ze.join(e,a.WS_UTILS)),await C(ze.join(e,a.WS_SLICE_FILE)),await C(ze.join(e,a.WS_SLICE_TEST_FILE)),t.redux&&(await Uc(e),await Bc(e)),await zc(e))},Uc=async e=>{let t=ze.join(e,a.ROOT_REDUCER);if(!l(t))return;let r=await g(t),i=Lt(r);i!==r&&await h(t,i)},Bc=async e=>{let t=ze.join(e,a.STORE_PROVIDER);if(!l(t))return;let r=await g(t),i=Ot(r);i!==r&&await h(t,i)},zc=async e=>{let t=ze.join(e,a.PACKAGE_JSON);if(!l(t))return;let r=JSON.parse(await g(t));({...r.dependencies,...r.devDependencies})["socket.io-client"]&&await He(e,"socket.io-client")};var Sn=async(e,t)=>{let r=S("Customizing features...");try{await on(e,t),await an(e,t),await vn(e,t),await fn(e,t),await Zi(e,t),await Ki(e,t),await sn(e,t),await hn(e,t),await un(e,t),await xn(e,t),await cn(e),await pn(e),await ln(e),await mn(e),t.tests&&await ce(e,{redux:t.redux,i18n:t.i18n}),r.succeed("Features customized.")}catch(i){throw r.fail("Failed to customize features."),i}};import Vc from"node:path";P();w();var En=async(e,t)=>{let r=S("Configuring package.json...");try{let i=t.gitRemote,n=t.gitHomepage,o=t.gitIssues;t.gitRemote&&(t.gitRemote.startsWith("git@github.com:")&&(i=t.gitRemote.replace("git@github.com:","https://github.com/").replace(/\.git$/,"")),n||(n=`${i.replace(/\.git$/,"")}#readme`),o||(o=`${i.replace(/\.git$/,"")}/issues`),i.endsWith(".git")||(i=`${i}.git`)),await _(Vc.join(e,a.PACKAGE_JSON),s=>(s.name=t.projectName,s.version=t.version,s.description=t.description,s.author=t.author,delete s.packageManager,t.gitRemote?(n&&(s.homepage=n),o&&(s.bugs={url:o}),i&&(s.repository={type:"git",url:i})):(delete s.homepage,delete s.bugs,delete s.repository),t.redux||(delete s.dependencies[R.REDUX_TOOLKIT],delete s.dependencies[R.REACT_REDUX],delete s.dependencies[R.REDUX],delete s.dependencies[R.REDUX_PERSIST]),t.httpClient!=="none"||t.reactSecureStorage||delete s.dependencies[R.REACT_SECURE_STORAGE],t.i18n||delete s.dependencies[R.NEXT_INTL],t.darkMode||delete s.dependencies[R.NEXT_THEMES],t.httpClient==="none"?delete s.dependencies[R.AXIOS]:t.httpClient==="fetch"&&delete s.dependencies[R.AXIOS],s)),r.succeed("package.json configured.")}catch(i){throw r.fail("Failed to configure package.json."),i}};import{readdir as Tn}from"node:fs/promises";import L from"node:path";P();w();var Cn=async(e,t)=>{await Jc(e,t),await Wc(e,t),await qc(e,t),await Xc(e,t),await Yc(e,t),await Kc(e,t),await Zc(e,t)},Jc=async(e,t)=>{t.preCommitHooks||(await v(L.join(e,a.HUSKY_DIR)),await C(L.join(e,a.COMMITLINT_CONFIG)),await C(L.join(e,a.LINTSTAGED_RC)),await _(L.join(e,a.PACKAGE_JSON),r=>(delete r.devDependencies[R.HUSKY],delete r.devDependencies[R.COMMITLINT_CLI],delete r.devDependencies[R.COMMITLINT_CONFIG],delete r.devDependencies[R.LINT_STAGED],delete r.scripts.prepare,delete r.scripts.postinstall,delete r.commitlint,delete r["lint-staged"],r)))},Wc=async(e,t)=>{t.commitizen||(await C(L.join(e,a.CZRC)),await _(L.join(e,a.PACKAGE_JSON),r=>(delete r.devDependencies[R.COMMITIZEN],delete r.devDependencies[R.CZ_CONVENTIONAL_CHANGELOG],delete r.config?.commitizen,r.config&&Object.keys(r.config).length===0&&delete r.config,delete r.scripts.commit,r)))},qc=async(e,t)=>{t.ci||await v(L.join(e,a.GITHUB_WORKFLOWS))},Xc=async(e,t)=>{let r=L.join(e,a.GITHUB_DIR);if(!t.keepTemplates)await v(L.join(r,a.GITHUB_ISSUE_TEMPLATE)),await C(L.join(r,a.GITHUB_PR_TEMPLATE));else{let i=L.join(r,a.GITHUB_ISSUE_TEMPLATE),n=L.join(r,a.GITHUB_PR_TEMPLATE),o=s=>s.replace(/Teispace/g,t.company).replace(/support@teispace\.com/g,t.email).replace(/Next\.js Starter/g,t.projectName).replace(/\[AUTHOR\]/g,t.author).replace(/\[COMPANY\]/g,t.company).replace(/\[EMAIL\]/g,t.email);if(l(n)){let s=await g(n);s=o(s),await h(n,s)}try{if(l(i)){let s=await Tn(i);for(let c of s){let p=L.join(i,c),u=await g(p);u=o(u),await h(p,u)}}}catch{}}},Yc=async(e,t)=>{let r=[a.CODE_OF_CONDUCT,a.CONTRIBUTING,a.SECURITY];for(let i of r)t.communityFiles.includes(i)||await C(L.join(e,i))},Kc=async(e,t)=>{if(t.docker){let r=L.join(e,a.ENV_EXAMPLE);if(l(r)){let i=await g(r),n=(o,s)=>{let c=new RegExp(`${o}=.*`);c.test(i)?i=i.replace(c,`${o}=${s}`):i+=`${o}=${s}
|
|
327
|
+
`};n("CONTAINER_NAME",t.containerName||"next-app"),n("IMAGE_NAME",t.imageName||"nextjs-starter"),n("IMAGE_TAG",t.imageTag||"latest"),await h(r,i)}}else{await C(L.join(e,a.DOCKERFILE)),await C(L.join(e,a.DOCKER_COMPOSE)),await C(L.join(e,a.DOCKERIGNORE));let r=L.join(e,a.ENV_EXAMPLE);if(l(r)){let i=await g(r);i=i.replace(/# Docker Compose Configuration\n/,""),i=i.replace(/CONTAINER_NAME=.*\n/,""),i=i.replace(/IMAGE_NAME=.*\n/,""),i=i.replace(/IMAGE_TAG=.*\n/,""),await h(r,i)}}},Zc=async(e,t)=>{let r=async o=>{let s=await Tn(o,{withFileTypes:!0}),c=[];for(let p of s){let u=L.join(o,p.name);p.isDirectory()&&p.name!=="node_modules"&&p.name!==".git"?c.push(...await r(u)):p.isFile()&&p.name.toLowerCase()==="readme.md"&&c.push(u)}return c},i=await r(e),n=L.join(e,a.README);for(let o of i)o!==n&&await C(o);if(t.readme){let o=`# ${t.projectName}
|
|
320
328
|
|
|
321
329
|
${t.description}
|
|
322
330
|
|
|
@@ -329,7 +337,7 @@ ${t.packageManager==="npm"?"npm run dev":`${t.packageManager} dev`}
|
|
|
329
337
|
\`\`\`
|
|
330
338
|
|
|
331
339
|
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
|
332
|
-
`;await h(n,o)}else await C(n)};P();w();import
|
|
340
|
+
`;await h(n,o)}else await C(n)};P();w();import Hr from"node:path";var Rn=async(e,t)=>{let r=[];t.i18n&&r.push("import { type AbstractIntlMessages, NextIntlClientProvider } from 'next-intl';"),t.darkMode&&r.push("import { CustomThemeProvider } from '@/providers';"),t.redux&&r.push("import type { AppState } from '@/store';"),t.i18n&&r.push("import type { SupportedLocale } from '@/types/i18n';"),t.redux&&r.push("import { StoreProvider } from './StoreProvider';");let i=["children: React.ReactNode;"],n=["children"];t.i18n&&(i.push("locale: SupportedLocale;"),i.push("messages: AbstractIntlMessages;"),i.push("timeZone: string;"),n.push("locale","messages","timeZone")),t.redux&&(i.push("preloadedState?: Partial<AppState>;"),n.push("preloadedState"));let o="{children}";t.i18n&&(o=`<NextIntlClientProvider locale={locale} messages={messages} timeZone={timeZone}>
|
|
333
341
|
${o}
|
|
334
342
|
</NextIntlClientProvider>`),t.darkMode&&(o=`<CustomThemeProvider>
|
|
335
343
|
${o}
|
|
@@ -349,7 +357,7 @@ export const RootProvider = ({ ${n.join(", ")} }: RootProviderProps) => {
|
|
|
349
357
|
${o}
|
|
350
358
|
);
|
|
351
359
|
};
|
|
352
|
-
`;await h(
|
|
360
|
+
`;await h(Hr.join(e,a.ROOT_PROVIDER),c)},bn=async(e,t)=>{if(t.i18n)return;let r=`\`\${livvic.variable} ${t.darkMode?"bg-light antialiased dark:bg-dark":"antialiased"}\``,i=(t.redux,""),n=t.httpClient!=="none",o=n?`// Regression sentinel \u2014 see file comment for what this guards.
|
|
353
361
|
import { HttpClientBundleSentinel } from '@/lib/utils/http/__bundle-sentinel__/client-bundle-sentinel';
|
|
354
362
|
`:"",s=n?`
|
|
355
363
|
<HttpClientBundleSentinel />`:"",c=`import type { Metadata } from 'next';
|
|
@@ -384,7 +392,7 @@ export default function RootLayout({
|
|
|
384
392
|
</html>
|
|
385
393
|
);
|
|
386
394
|
}
|
|
387
|
-
`;await h(
|
|
395
|
+
`;await h(Hr.join(e,a.ROOT_LAYOUT),c);let p=t.redux?`import { Counter } from '@/features/counter';
|
|
388
396
|
|
|
389
397
|
`:"",u=t.redux?`
|
|
390
398
|
<Counter />`:"",d=`${p}export default function Home() {
|
|
@@ -395,13 +403,13 @@ export default function RootLayout({
|
|
|
395
403
|
</div>
|
|
396
404
|
);
|
|
397
405
|
}
|
|
398
|
-
`;await h(
|
|
399
|
-
Cleaning up: Deleting directory ${r.projectName}...`));try{await v(i),console.log(
|
|
400
|
-
Process interrupted. Cleaning up...`)),await o()});try{if(await
|
|
401
|
-
`)},
|
|
402
|
-
`;var
|
|
403
|
-
`);let c=
|
|
404
|
-
`;t.includes(r.trim())||(t+=r,await h(e,t))};import{writeFile as
|
|
406
|
+
`;await h(Hr.join(e,a.ROOT_PAGE),d)};import Qc from"degit";var In="teispace/nextjs-starter",$n="v1.1.1",ep=()=>$n==="main"?In:`${In}#${$n}`,J=async(e,t={})=>{await Qc(ep(),{cache:!1,force:!0,verbose:t.verbose??!1}).clone(e)};var kn=async e=>{let t=S("Downloading template...");try{await J(e,{verbose:!0}),t.succeed("Template downloaded successfully.")}catch(r){throw t.fail("Failed to download template."),r}};var Br=["npm","yarn","pnpm","bun"],tp=e=>{if(e!==void 0){if(!Br.includes(e))throw new Error(`Invalid --package-manager "${e}". Valid: ${Br.join(", ")}.`);return e}},Nn=e=>{e.command("init").description("Initialize a new Next.js project").argument("[name]","Project name").option("-y, --yes","Skip all prompts and use the recommended production defaults").option("--package-manager <pm>",`Override the package manager (one of: ${Br.join(", ")})`).action(async(t,r)=>{try{let i=tp(r.packageManager);await ip(t,{yes:r.yes??!1,packageManager:i})}catch(i){E(`${i instanceof Error?i.message:i}`),process.exit(1)}})},st=async(e,t,r,i)=>{let n=S(e);i.current=n;try{let o=await r();return n.succeed(t),o}finally{i.current===n&&(i.current=null)}},rp=e=>{let t=[];e.darkMode&&t.push("dark mode"),e.redux&&t.push("redux"),e.i18n&&t.push("i18n"),e.tests&&t.push("tests"),e.reactCompiler&&t.push("react-compiler"),e.preCommitHooks&&t.push("pre-commit hooks"),e.commitizen&&t.push("commitizen"),e.httpClient!=="none"&&t.push(`http (${e.httpClient})`),m(ee.dim("Defaults applied (run `next-maker remove <feature>` to undo any of them):")),m(ee.dim(` package manager : ${e.packageManager}`)),m(ee.dim(` features : ${t.join(", ")}`)),m("")},ip=async(e,t)=>{Hi();let r;t.yes?(r=Wi(e,{packageManager:t.packageManager}),m(ee.cyan(`\u2728 Bootstrapping ${r.projectName} with the recommended defaults`)),m(""),rp(r)):(m("Welcome to the Teispace Next.js App Creator!"),m(""),r=await qi(e),t.packageManager&&(r={...r,packageManager:t.packageManager}));let i=Ur.resolve(process.cwd(),r.projectName);l(i)&&(console.error(ee.red(`Error: Directory ${r.projectName} already exists.`)),process.exit(1));let n={current:null},o=async()=>{if(l(i)){n.current?.stop(),n.current=null,console.log(ee.yellow(`
|
|
407
|
+
Cleaning up: Deleting directory ${r.projectName}...`));try{await v(i),console.log(ee.green("Cleanup successful."))}catch(c){console.error(ee.red(`Failed to clean up directory ${r.projectName}:`),c)}}},s=Li(async()=>{console.log(ee.red(`
|
|
408
|
+
Process interrupted. Cleaning up...`)),await o()});try{if(await kn(i),await En(i,r),await Sn(i,r),await st("Generating providers and layout...","Providers and layout generated.",async()=>{await Rn(i,r),await bn(i,r)},n),await st("Setting up developer tools...","Developer tools configured.",()=>Cn(i,r),n),await st("Initializing Git...","Git initialized.",()=>Bi(i,r.gitRemote,r.pushToRemote),n),await st("Installing dependencies...","Dependencies installed.",()=>zi(i,r.packageManager),n),await st("Formatting and linting...","Formatted.",()=>K(i,r.packageManager,"lint:fix"),n),r.copyEnv){let c=Ur.join(i,".env.example"),p=Ur.join(i,".env");l(c)&&await(await import("node:fs/promises")).copyFile(c,p)}s(),m(""),m(ee.green(`\u2728 Project ${r.projectName} created successfully!`)),m(""),m("To get started:"),m(ee.cyan(` cd ${r.projectName}`)),m(ee.cyan(` ${r.packageManager==="npm"?"npm run dev":`${r.packageManager} dev`}`)),m("")}catch(c){s(),n.current?.fail("Failed to create project."),n.current=null,console.error(c),await o(),process.exit(1)}};import ii from"node:path";import le from"picocolors";import Mt from"node:path";var An=/^[A-Za-z][A-Za-z0-9-]*$/,np=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;function _n(e){return np.test(e)}function W(e,t="name"){let r=e?.trim();if(!r)throw new Error(`A ${t} is required.`);if(!An.test(r))throw new Error(`Invalid ${t} "${e}". Use letters, digits, and hyphens only \u2014 no slashes, spaces, "..", or absolute paths.`);if(_n(r))throw new Error(`Invalid ${t} "${e}". That is a reserved name on Windows.`);return r}function pe(e,t="path"){let r=e?.trim();if(!r)throw new Error(`A ${t} is required.`);let i=r.replace(/^\.\//,"");if(i.startsWith("/")||/^[a-zA-Z]:/.test(i))throw new Error(`Invalid ${t} "${e}". Must be a relative path inside the project (no leading "/" or drive letter).`);for(let n of i.split("/")){if(!An.test(n))throw new Error(`Invalid ${t} "${e}". Each segment must be kebab/camel-case (letters, digits, hyphens), separated by "/" \u2014 no "..", dots, or empty segments.`);if(_n(n))throw new Error(`Invalid ${t} "${e}". Segment "${n}" is reserved on Windows.`)}return i}function Gt(e,...t){let r=Mt.resolve(e),i=Mt.resolve(r,...t),n=Mt.relative(r,i);if(n===""||n===".")return i;if(n.startsWith("..")||Mt.isAbsolute(n))throw new Error(`Refusing to write outside the project directory (resolved path escapes "${r}").`);return i}q();import{mkdir as Ln,writeFile as Vr}from"node:fs/promises";import Ne from"node:path";w();var zr=e=>{let{componentName:t,isClient:r,hasI18n:i}=e,n=e.translationNamespace||t,o=[];return(r||i)&&o.push("'use client';"),i&&o.push("import { useTranslations } from 'next-intl';"),o.push(""),o.push(`export function ${t}() {`),i?(o.push(` const t = useTranslations('${n}');`),o.push(""),o.push(" return ("),o.push(" <div>"),o.push(" <h2>{t('title')}</h2>"),o.push(" </div>"),o.push(" );")):(o.push(" return ("),o.push(" <div>"),o.push(` <h2>${t}</h2>`),o.push(" </div>"),o.push(" );")),o.push("}"),o.push(""),o.join(`
|
|
409
|
+
`)},jn=e=>`export { ${e.componentName} } from './${e.componentName}';
|
|
410
|
+
`;var Jr=async e=>{let{name:t,projectPath:r,isClient:i,hasI18n:n,featurePath:o}=e,s=N(t);o?await cp(s,r,o,i,n):await pp(s,t,r,i,n)},cp=async(e,t,r,i,n)=>{let o=Ne.join(t,r,"components");await Ln(o,{recursive:!0}),await Vr(Ne.join(o,`${e}.tsx`),zr({componentName:e,isClient:i,hasI18n:n}))},pp=async(e,t,r,i,n)=>{let o=Ne.join(r,"src","components","common",e);await Ln(o,{recursive:!0}),await Vr(Ne.join(o,`${e}.tsx`),zr({componentName:e,isClient:i,hasI18n:n})),await Vr(Ne.join(o,"index.ts"),jn({componentName:e}));let s=Ne.join(r,"src","components","common","index.ts");await lp(s,`export { ${e} } from './${e}';
|
|
411
|
+
`);let c=Ne.join(r,"src","components","index.ts");await mp(c)},lp=async(e,t)=>{let r="";l(e)&&(r=await g(e)),r.includes(t.trim())||(r+=t,await h(e,r))},mp=async e=>{let t="";l(e)&&(t=await g(e));let r=`export * from './common';
|
|
412
|
+
`;t.includes(r.trim())||(t+=r,await h(e,t))};import{writeFile as dp}from"node:fs/promises";import up from"node:path";var Mn=e=>{let{camelName:t,pascalName:r,httpClient:i}=e,n=i==="axios"?"import { axiosClient } from '@/lib/utils/http';":"import { fetchClient } from '@/lib/utils/http';",o=i==="axios"?"axiosClient":"fetchClient";return`import { AppApis } from '@/lib/config';
|
|
405
413
|
${n}
|
|
406
414
|
import type { ResultAsync } from '@/types';
|
|
407
415
|
|
|
@@ -449,14 +457,14 @@ export const ${t}Service = {
|
|
|
449
457
|
return ${o}.delete<void>(AppApis.${t}.delete(id));
|
|
450
458
|
},
|
|
451
459
|
};
|
|
452
|
-
`},
|
|
460
|
+
`},Gn=e=>{let{camelName:t,kebabName:r}=e;return` ${t}: {
|
|
453
461
|
base: '/${r}',
|
|
454
462
|
getAll: '/${r}',
|
|
455
463
|
getById: (id: string) => \`/${r}/\${id}\`,
|
|
456
464
|
create: '/${r}',
|
|
457
465
|
update: (id: string) => \`/${r}/\${id}\`,
|
|
458
466
|
delete: (id: string) => \`/${r}/\${id}\`,
|
|
459
|
-
},`};var
|
|
467
|
+
},`};var Wr=async e=>{let{name:t,outputPath:r,httpClient:i}=e,n=G(t),o=N(t);await dp(up.join(r,`${t}.service.ts`),Mn({camelName:n,pascalName:o,httpClient:i}))};import{mkdir as yp,writeFile as zt}from"node:fs/promises";import ie from"node:path";import{writeFile as fp}from"node:fs/promises";import gp from"node:path";var Hn=e=>{let{camelName:t,httpClient:r}=e;return`import { AppApis } from '@/lib/config';
|
|
460
468
|
${r==="axios"?"import { axiosClient } from '@/lib/utils/http';":"import { fetchClient } from '@/lib/utils/http';"}
|
|
461
469
|
import type { ResultAsync } from '@/types';
|
|
462
470
|
|
|
@@ -465,16 +473,16 @@ export const ${t}Service = {
|
|
|
465
473
|
return ${r==="axios"?"axiosClient":"fetchClient"}.get<string>(AppApis.${t}.getAll);
|
|
466
474
|
},
|
|
467
475
|
};
|
|
468
|
-
`};var
|
|
476
|
+
`};var pt=async e=>{let{name:t,outputPath:r,httpClient:i}=e,n=G(t);await fp(gp.join(r,`${t}.service.ts`),Hn({camelName:n,httpClient:i}))};import{mkdir as hp,writeFile as lt}from"node:fs/promises";import mt from"node:path";var Un=e=>{let{sliceName:t,withPersist:r}=e;return`export * from './${t}.slice';
|
|
469
477
|
export * from './${t}.selectors';
|
|
470
478
|
export * from './${t}.types';${r?`
|
|
471
479
|
export * from './persist';`:""}
|
|
472
|
-
`},
|
|
480
|
+
`},Bn=e=>{let{featureName:t,componentName:r,hookName:i,withStore:n,withService:o}=e;return`export { default as ${r} } from './components/${r}';
|
|
473
481
|
export { ${i} } from './hooks/${i}';
|
|
474
482
|
export * from './types/${t}.types';${n?`
|
|
475
483
|
export * from './store';`:""}${o?`
|
|
476
484
|
export * from './services/${t}.service';`:""}
|
|
477
|
-
`};var
|
|
485
|
+
`};var zn=e=>{let{componentName:t,camelName:r,typesImportPath:i}=e,n=`${r.toUpperCase()}_PERSIST_VERSION`;return`import { createMigrate, type PersistConfig, type PersistedState } from 'redux-persist';
|
|
478
486
|
import storage from '@/store/storage';
|
|
479
487
|
import type { ${t}State } from '${i}';
|
|
480
488
|
|
|
@@ -494,11 +502,11 @@ export const ${r}PersistConfig: PersistConfig<${t}State> = {
|
|
|
494
502
|
// whitelist: ['someField'], // Specify which fields to persist
|
|
495
503
|
migrate: createMigrate(migrations, { debug: false }),
|
|
496
504
|
};
|
|
497
|
-
`};var
|
|
505
|
+
`};var Vn=e=>{let{componentName:t,camelName:r,sliceName:i}=e;return`import { RootState } from '@/store/rootReducer';
|
|
498
506
|
|
|
499
507
|
export const select${t}State = (state: RootState) => state.${r};
|
|
500
508
|
export { setLoading, setError, resetState } from './${i}.slice';
|
|
501
|
-
`};var
|
|
509
|
+
`};var Jn=e=>{let{componentName:t,camelName:r,typesImportPath:i}=e;return`import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
|
|
502
510
|
import type { ${t}State } from '${i}';
|
|
503
511
|
|
|
504
512
|
const initialState: ${t}State = {
|
|
@@ -527,13 +535,13 @@ export const ${r}Slice = createSlice({
|
|
|
527
535
|
export const { setLoading, setError, resetState } = ${r}Slice.actions;
|
|
528
536
|
|
|
529
537
|
export const ${r}Reducer = ${r}Slice.reducer;
|
|
530
|
-
`};var
|
|
538
|
+
`};var Bt=e=>{let{componentName:t,withStore:r}=e;return`export interface ${t}State {
|
|
531
539
|
${r?`loading: boolean;
|
|
532
540
|
error: string | null;
|
|
533
541
|
// Add your state properties here`:`// Add your state properties here
|
|
534
542
|
// example: value: string;`}
|
|
535
543
|
}
|
|
536
|
-
`};var
|
|
544
|
+
`};var dt=async e=>{let{name:t,outputPath:r,persist:i,typesImportPath:n=`./${t}.types`}=e;await hp(r,{recursive:!0});let o=N(t),s=G(t);await Promise.all([lt(mt.join(r,`${t}.types.ts`),Bt({componentName:o,withStore:!0})),lt(mt.join(r,`${t}.slice.ts`),Jn({componentName:o,camelName:s,typesImportPath:n})),lt(mt.join(r,`${t}.selectors.ts`),Vn({componentName:o,camelName:s,sliceName:t})),...i?[lt(mt.join(r,"persist.ts"),zn({componentName:o,camelName:s,typesImportPath:n}))]:[],lt(mt.join(r,"index.ts"),Un({sliceName:t,withPersist:i}))])};var Wn=e=>{let{componentName:t,hookName:r}=e;return`'use client';
|
|
537
545
|
import { ${r} } from '../hooks/${r}';
|
|
538
546
|
|
|
539
547
|
export function ${t}() {
|
|
@@ -548,7 +556,7 @@ export function ${t}() {
|
|
|
548
556
|
}
|
|
549
557
|
|
|
550
558
|
export default ${t};
|
|
551
|
-
`};var
|
|
559
|
+
`};var qn=e=>{let{hookName:t,componentName:r,featureName:i}=e;return`'use client';
|
|
552
560
|
import { useAppDispatch, useAppSelector } from '@/store/hooks';
|
|
553
561
|
import { select${r}State, setLoading, setError } from '../store/${i}.selectors';
|
|
554
562
|
|
|
@@ -570,7 +578,7 @@ export const ${t} = () => {
|
|
|
570
578
|
setError: handleSetError,
|
|
571
579
|
} as const;
|
|
572
580
|
};
|
|
573
|
-
`},
|
|
581
|
+
`},Xn=e=>{let{hookName:t}=e;return`'use client';
|
|
574
582
|
import { useState } from 'react';
|
|
575
583
|
|
|
576
584
|
export const ${t} = () => {
|
|
@@ -582,8 +590,8 @@ export const ${t} = () => {
|
|
|
582
590
|
// Add your methods here
|
|
583
591
|
} as const;
|
|
584
592
|
};
|
|
585
|
-
`};var
|
|
586
|
-
`)};var
|
|
593
|
+
`};var qr=async e=>{let{name:t,outputPath:r,createStore:i,persistStore:n,createService:o,httpClient:s}=e,c=N(t),p=`use${c}`,u=[ie.join(r,"components"),ie.join(r,"hooks"),ie.join(r,"types"),...i?[ie.join(r,"store")]:[],...o?[ie.join(r,"services")]:[]];await Promise.all(u.map(d=>yp(d,{recursive:!0}))),await Promise.all([zt(ie.join(r,"components",`${c}.tsx`),Wn({componentName:c,hookName:p})),zt(ie.join(r,"hooks",`${p}.ts`),i?qn({hookName:p,componentName:c,featureName:t}):Xn({hookName:p})),zt(ie.join(r,"types",`${t}.types.ts`),Bt({componentName:c,withStore:i})),zt(ie.join(r,"index.ts"),Bn({featureName:t,componentName:c,hookName:p,withStore:i,withService:o}))]),i&&await dt({name:t,outputPath:ie.join(r,"store"),persist:n,typesImportPath:`../types/${t}.types`}),o&&s&&await pt({name:t,outputPath:ie.join(r,"services"),httpClient:s})};import{mkdir as xp,writeFile as wp}from"node:fs/promises";import Xr from"node:path";var Yn=e=>{let{hookName:t,isClient:r}=e,i=[];return r&&i.push("'use client';"),i.push("import { useState, useCallback } from 'react';"),i.push(""),i.push(`export const ${t} = () => {`),i.push(" const [loading, setLoading] = useState(false);"),i.push(" const [error, setError] = useState<string | null>(null);"),i.push(""),i.push(" const execute = useCallback(async () => {"),i.push(" setLoading(true);"),i.push(" setError(null);"),i.push(" try {"),i.push(" // Add your logic here"),i.push(" } catch (err) {"),i.push(" setError(err instanceof Error ? err.message : 'An error occurred');"),i.push(" } finally {"),i.push(" setLoading(false);"),i.push(" }"),i.push(" }, []);"),i.push(""),i.push(" return {"),i.push(" loading,"),i.push(" error,"),i.push(" execute,"),i.push(" } as const;"),i.push("};"),i.push(""),i.join(`
|
|
594
|
+
`)};var Yr=async e=>{let{name:t,projectPath:r,isClient:i,featurePath:n}=e,s=`use${N(t)}`,c;n?c=Xr.join(r,n,"hooks"):c=Xr.join(r,"src","hooks"),await xp(c,{recursive:!0}),await wp(Xr.join(c,`${s}.ts`),Yn({hookName:s,isClient:i}))};import{mkdir as Sp}from"node:fs/promises";import Vt from"node:path";w();var Pp=e=>`import { setRequestLocale } from 'next-intl/server';
|
|
587
595
|
import type { SupportedLocale } from '@/types/i18n';
|
|
588
596
|
|
|
589
597
|
type Props = {
|
|
@@ -597,21 +605,21 @@ export default async function ${e}({ children, params }: Props) {
|
|
|
597
605
|
|
|
598
606
|
return <>{children}</>;
|
|
599
607
|
}
|
|
600
|
-
`,
|
|
608
|
+
`,vp=e=>`type Props = {
|
|
601
609
|
children: React.ReactNode;
|
|
602
610
|
};
|
|
603
611
|
|
|
604
612
|
export default function ${e}({ children }: Props) {
|
|
605
613
|
return <>{children}</>;
|
|
606
614
|
}
|
|
607
|
-
`,
|
|
608
|
-
`)}},
|
|
615
|
+
`,Kn=({componentName:e,hasI18n:t})=>t?Pp(e):vp(e);var Ep=/^[a-z][a-z0-9-]*$/,Tp=/^[a-z][a-z0-9-]*(\/[a-z][a-z0-9-]*)*$/,Cp=e=>{if(!Ep.test(e))throw new Error(`Invalid layout segment "${e}". Use kebab-case letters, digits, and hyphens. For route groups pass --group instead of wrapping in parens.`)},Rp=e=>{if(!Tp.test(e))throw new Error(`Invalid --at path "${e}". Use kebab-case segments separated by "/", e.g. "dashboard/settings".`)},Kr=async e=>{let{segment:t,at:r,projectPath:i,hasI18n:n,withGroup:o}=e;Cp(t),r&&Rp(r);let s=`${N(t)}Layout`,c=o?`(${t})`:t,p=["src","app"];n&&p.push("[locale]"),r&&p.push(...r.split("/")),p.push(c);let u=Vt.join(i,...p),d=Vt.join(u,"layout.tsx");if(l(d))throw new Error(`Layout already exists at ${Vt.relative(i,d)}.`);return await Sp(u,{recursive:!0}),await h(d,Kn({componentName:s,hasI18n:n})),{layoutFile:d,displayPath:Vt.relative(i,d),componentName:s}};w();import{copyFile as bp,readFile as Ip,writeFile as $p}from"node:fs/promises";import ut from"node:path";var Zr=async e=>{let{code:t,name:r,country:i,flag:n,projectPath:o,copyTranslations:s}=e;await kp(o,t,s),await Np(o,t),await Ap(o,t,r,i,n)},kp=async(e,t,r)=>{let i=ut.join(e,"src","i18n","translations"),n=ut.join(i,"en.json"),o=ut.join(i,`${t}.json`);if(r)await bp(n,o);else{let s=await Ip(n,"utf-8"),c=JSON.parse(s),p=Zn(c);await $p(o,`${JSON.stringify(p,null,2)}
|
|
616
|
+
`)}},Zn=e=>{let t={};for(let[r,i]of Object.entries(e))typeof i=="object"&&i!==null?t[r]=Zn(i):t[r]="";return t},Np=async(e,t)=>{let r=ut.join(e,"src","types","i18n.ts");if(!l(r))return;let i=await g(r),n=/export type SupportedLocale = (.*);/,o=i.match(n);if(o&&!o[1].includes(`'${t}'`)){let s=`${o[1]} | '${t}'`;i=i.replace(n,`export type SupportedLocale = ${s};`),await h(r,i)}},Ap=async(e,t,r,i,n)=>{let o=ut.join(e,"src","lib","config","app-locales.ts");if(!l(o))return;let s=await g(o);if(s.includes(`locale: '${t}'`))return;let c=s.lastIndexOf("];");if(c===-1)return;let p=` {
|
|
609
617
|
name: '${r}',
|
|
610
618
|
locale: '${t}',
|
|
611
619
|
flag: '${n}',
|
|
612
620
|
country: '${i}',
|
|
613
621
|
},
|
|
614
|
-
`;s=s.slice(0,c)+p+s.slice(c),await h(o,s)};import{mkdir as
|
|
622
|
+
`;s=s.slice(0,c)+p+s.slice(c),await h(o,s)};import{mkdir as _p,writeFile as Qr}from"node:fs/promises";import ft from"node:path";var Qn=e=>{let{componentName:t,routePath:r,hasI18n:i}=e;return i?`import { generateSEOMetadata } from '@/lib/config/seo';
|
|
615
623
|
import type { Metadata } from 'next';
|
|
616
624
|
import { getTranslations, setRequestLocale } from 'next-intl/server';
|
|
617
625
|
import type { SupportedLocale } from '@/types/i18n';
|
|
@@ -657,7 +665,7 @@ export default function ${t}Page() {
|
|
|
657
665
|
</div>
|
|
658
666
|
);
|
|
659
667
|
}
|
|
660
|
-
`},
|
|
668
|
+
`},eo=e=>{let{componentName:t,paramName:r,routePath:i,hasI18n:n}=e;return n?`import { generateSEOMetadata } from '@/lib/config/seo';
|
|
661
669
|
import type { Metadata } from 'next';
|
|
662
670
|
import { getTranslations, setRequestLocale } from 'next-intl/server';
|
|
663
671
|
import type { SupportedLocale } from '@/types/i18n';
|
|
@@ -711,14 +719,14 @@ export default async function ${t}Page(props: Props) {
|
|
|
711
719
|
</div>
|
|
712
720
|
);
|
|
713
721
|
}
|
|
714
|
-
`},
|
|
722
|
+
`},to=e=>`export default function ${e.componentName}Loading() {
|
|
715
723
|
return (
|
|
716
724
|
<div className="flex h-full items-center justify-center">
|
|
717
725
|
<p>Loading...</p>
|
|
718
726
|
</div>
|
|
719
727
|
);
|
|
720
728
|
}
|
|
721
|
-
`,
|
|
729
|
+
`,ro=e=>`'use client';
|
|
722
730
|
|
|
723
731
|
export default function ${e.componentName}Error({
|
|
724
732
|
error,
|
|
@@ -735,7 +743,7 @@ export default function ${e.componentName}Error({
|
|
|
735
743
|
</div>
|
|
736
744
|
);
|
|
737
745
|
}
|
|
738
|
-
`;var
|
|
746
|
+
`;var ei=async e=>{let{name:t,projectPath:r,hasI18n:i,dynamic:n,withLoading:o=!1,withError:s=!1}=e,c=N(t),p=`/${t}`,u=i?"src/app/[locale]":"src/app",d;n?d=ft.join(r,u,t,`[${n}]`):d=ft.join(r,u,t),await _p(d,{recursive:!0});let f=n?eo({componentName:c,routePath:n?`${p}/[${n}]`:p,paramName:n,hasI18n:i}):Qn({componentName:c,routePath:p,hasI18n:i});await Qr(ft.join(d,"page.tsx"),f),o&&await Qr(ft.join(d,"loading.tsx"),to({componentName:c})),s&&await Qr(ft.join(d,"error.tsx"),ro({componentName:c}))};P();import{mkdir as Fp}from"node:fs/promises";import ti from"node:path";w();var io=(e,t)=>e.endsWith(t)?e:`${e}${t}`,no=({baseName:e})=>{let t=io(e,"Provider"),r=t.replace(/Provider$/,""),i=`${r}ContextValue`,n=`${r}Context`,o=`use${r}`;return`'use client';
|
|
739
747
|
import { createContext, useContext, useMemo } from 'react';
|
|
740
748
|
|
|
741
749
|
type ${i} = {
|
|
@@ -756,7 +764,7 @@ export const ${t} = ({ children }: { children: React.ReactNode }) => {
|
|
|
756
764
|
const value = useMemo<${i}>(() => ({}), []);
|
|
757
765
|
return <${n}.Provider value={value}>{children}</${n}.Provider>;
|
|
758
766
|
};
|
|
759
|
-
`},
|
|
767
|
+
`},oo=e=>io(e,"Provider");var Op=/^[A-Za-z][A-Za-z0-9-]*$/,Dp=e=>e.includes("-")?N(e):e.charAt(0).toUpperCase()+e.slice(1),ri=async e=>{let{name:t,projectPath:r}=e;if(!Op.test(t))throw new Error(`Invalid provider name "${t}". Use kebab-case or PascalCase letters and digits only.`);let i=Dp(t).replace(/Provider$/,""),n=oo(i),o=n,s=ti.join(r,a.PROVIDERS),c=ti.join(s,`${o}.tsx`);if(l(c))throw new Error(`Provider already exists at ${ti.relative(r,c)}.`);return await Fp(s,{recursive:!0}),await h(c,no({baseName:i})),{componentName:n,fileBaseName:o,providerFile:c}};w();import gt from"node:path";var so=e=>{let{componentName:t,sourceImportPath:r,testUtilsImportPath:i,hasRedux:n,hasI18n:o}=e,s=[];o&&s.push("messages: {}"),n&&s.push("preloadedState: {}");let c=s.length?`, {
|
|
760
768
|
${s.join(`,
|
|
761
769
|
`)},
|
|
762
770
|
}`:"";return`import { describe, expect, it } from 'vitest';
|
|
@@ -770,7 +778,7 @@ describe('${t}', () => {
|
|
|
770
778
|
expect(screen).toBeDefined();
|
|
771
779
|
});
|
|
772
780
|
});
|
|
773
|
-
`},
|
|
781
|
+
`},ao=e=>{let{hookName:t,sourceImportPath:r,withStore:i,testUtilsImportPath:n}=e;return i?`import { renderHook } from '@testing-library/react';
|
|
774
782
|
import { describe, expect, it } from 'vitest';
|
|
775
783
|
import { TestProviders } from '${n}';
|
|
776
784
|
import { ${t} } from '${r}';
|
|
@@ -791,7 +799,7 @@ describe('${t}', () => {
|
|
|
791
799
|
expect(result.current).toBeDefined();
|
|
792
800
|
});
|
|
793
801
|
});
|
|
794
|
-
`},
|
|
802
|
+
`},co=e=>{let{camelName:t,sourceImportPath:r}=e,i=`${t}Slice`;return`import { describe, expect, it } from 'vitest';
|
|
795
803
|
import { ${i}, resetState, setError, setLoading } from '${r}';
|
|
796
804
|
|
|
797
805
|
describe('${i}', () => {
|
|
@@ -816,30 +824,30 @@ describe('${i}', () => {
|
|
|
816
824
|
expect(next).toEqual(initialState);
|
|
817
825
|
});
|
|
818
826
|
});
|
|
819
|
-
`};var
|
|
827
|
+
`};var ge=async e=>{let{projectPath:t,sourceFile:r,kind:i,symbolName:n}=e,o=gt.dirname(r),s=gt.basename(r).replace(/\.(tsx?|jsx?)$/i,""),c=i==="component"?".tsx":".ts",p=gt.join(o,`${s}.test${c}`),u=`./${s}`,d=jp(o,gt.join(t,"test","test-utils")),f;return i==="component"?f=so({componentName:n,sourceImportPath:u,testUtilsImportPath:d,hasRedux:!!e.hasRedux,hasI18n:!!e.hasI18n}):i==="hook"?f=ao({hookName:n,sourceImportPath:u,withStore:!!e.hookUsesStore,testUtilsImportPath:e.hookUsesStore?d:void 0}):f=co({camelName:n,sourceImportPath:u}),await h(p,f),p},jp=(e,t)=>{let r=gt.relative(e,t).replace(/\\/g,"/");return r.startsWith(".")?r:`./${r}`};import Lp from"enquirer";var{prompt:Mp}=Lp,po=async(e,t={})=>{let r=[];e||r.push({type:"input",name:"componentName",message:"Component name (kebab-case):",validate:n=>n?/^[a-z][a-z0-9-]*$/.test(n)?!0:"Use lowercase letters, numbers, and hyphens only":"Component name is required"}),t.client===void 0&&r.push({type:"confirm",name:"isClient",message:"Add 'use client' directive?",initial:!1});let i=r.length>0?await Mp(r):{};return{componentName:e??i.componentName,isClient:t.client??i.isClient??!1}};var lo=e=>{e.command("component [name]").description("Generate a shared component").option("--client","Add 'use client' directive").option("--i18n","Add useTranslations hook").option("--feature <path>","Generate in feature directory (e.g., src/features/auth)").option("--test","Also generate a sibling test file").option("--no-test","Skip test file generation").action(async(t,r)=>{try{let i=process.cwd();m(le.cyan(`
|
|
820
828
|
\u{1F9E9} Component Generator
|
|
821
|
-
`)),
|
|
829
|
+
`)),y.start("Detecting project setup...");let n=await M(i);y.succeed("Project setup detected");let o=await po(t,{client:r.client});W(o.componentName,"component name"),r.feature&&pe(r.feature,"feature path");let s=N(o.componentName),c=o.isClient,p=r.i18n??!1,u=Gp(r,n.hasTests);y.start("Generating component..."),await Jr({name:o.componentName,projectPath:i,isClient:c||p,hasI18n:p,featurePath:r.feature}),y.succeed("Component generated");let d=null;if(u){let x=r.feature?ii.join(i,r.feature,"components",`${s}.tsx`):ii.join(i,"src/components/common",s,`${s}.tsx`);y.start("Generating test..."),d=await ge({projectPath:i,sourceFile:x,kind:"component",symbolName:s,hasRedux:n.hasRedux,hasI18n:n.hasI18n}),y.succeed("Test generated")}let f=r.feature?`${r.feature}/components/${s}.tsx`:`src/components/common/${s}/${s}.tsx`;m(le.green(`
|
|
822
830
|
\u2728 Component '${s}' created successfully!
|
|
823
|
-
`)),m(
|
|
824
|
-
${e}`,r=t.match(
|
|
831
|
+
`)),m(le.dim(` \u{1F4C4} ${f}`)),r.feature||(m(le.dim(` \u{1F4C4} src/components/common/${s}/index.ts`)),m(le.dim(" \u{1F4DD} Updated src/components/common/index.ts")),m(le.dim(" \u{1F4DD} Updated src/components/index.ts"))),d&&m(le.dim(` \u{1F9EA} ${ii.relative(i,d)}`)),m(""),m(le.cyan("Usage:")),r.feature?m(le.dim(` import { ${s} } from '${r.feature.replace(/^src\//,"@/")}/components/${s}';`)):m(le.dim(` import { ${s} } from '@/components';`)),m("")}catch(i){y.fail("Component generation failed"),E(`${i}`),process.exit(1)}})},Gp=(e,t)=>e.test===!1?!1:e.test===!0?!0:t;import $ from"picocolors";P();w();import Jp from"node:path";P();import uo from"node:path";import Hp from"picocolors";w();var mo=/export default (.*?);/,ni="ANALYZE=true next build",Jt=e=>e.includes("@next/bundle-analyzer"),ht=e=>{if(Jt(e))return e;let t=`import withBundleAnalyzer from '@next/bundle-analyzer';
|
|
832
|
+
${e}`,r=t.match(mo);if(!r)throw new Error("Could not locate `export default` in next.config.ts.");let n=`const bundleAnalyzer = withBundleAnalyzer({
|
|
825
833
|
enabled: process.env.ANALYZE === 'true',
|
|
826
834
|
});
|
|
827
835
|
|
|
828
|
-
export default bundleAnalyzer(${r[1]});`;return t.replace(
|
|
836
|
+
export default bundleAnalyzer(${r[1]});`;return t.replace(mo,n)};var Wt=async e=>{let t=S("Adding @next/bundle-analyzer...");try{let r=uo.join(e,a.NEXT_CONFIG);if(!l(r))throw new Error(`${a.NEXT_CONFIG} not found.`);let i=await g(r);if(Jt(i)){t.fail("@next/bundle-analyzer is already configured.");return}await h(r,ht(i)),await _(uo.join(e,a.PACKAGE_JSON),n=>(n.scripts=n.scripts??{},n.scripts.analyze||(n.scripts.analyze=ni),n)),t.text="Installing @next/bundle-analyzer...",await At(e,"@next/bundle-analyzer"),t.succeed(Hp.green("@next/bundle-analyzer configured."))}catch(r){throw t.fail("Failed to add @next/bundle-analyzer."),r}};P();import zp from"node:path";import Vp from"picocolors";w();P();import Up from"node:path";w();var qt=(e,t)=>e.filter(r=>r.kind==="missingPackage"&&r.depKind===t).map(r=>r.name),Bp=e=>e.filter(t=>t.kind==="missingFile").map(t=>t.file),F=(e,t)=>Bp(e).some(r=>r===t||r.startsWith(`${t}/`));var U=(e,t)=>e.some(r=>r.kind==="missingInjection"&&(t===void 0||r.file===t)),B=async(e,t)=>{let r=qt(t,"dependency"),i=qt(t,"devDependency");if(r.length===0&&i.length===0)return[];let n=await A(e);return r.length>0&&await $r(e,n,r),i.length>0&&await fe(e,n,i),[...r,...i]},Ee=async(e,t)=>{let r=new Map;for(let n of t)(n.kind==="missingScript"&&n.expected||n.kind==="mismatchedScript")&&r.set(n.name,n.expected);if(r.size===0)return[];let i=Up.join(e,a.PACKAGE_JSON);return l(i)?(await _(i,n=>{let o={...n.scripts??{}};for(let[s,c]of r)o[s]=c;return{...n,scripts:o}}),[...r.keys()]):[]},te=async(e,t)=>{await J(e);try{return await t(e)}finally{await v(e)}};var fo=async(e,t)=>{let r=S("Repairing Bundle Analyzer...");try{if(U(t,a.NEXT_CONFIG)){let s=zp.join(e,a.NEXT_CONFIG);if(l(s)){let c=await g(s),p=ht(c);p!==c&&await h(s,p)}}let i=await B(e,t),n=await Ee(e,t),o=[i.length>0?`reinstalled ${i.join(", ")}`:null,n.length>0?`restored ${n.join(", ")}`:null].filter(Boolean);r.succeed(Vp.green(o.length>0?`Bundle Analyzer repaired (${o.join("; ")}).`:"Bundle Analyzer repaired."))}catch(i){throw r.fail("Failed to repair Bundle Analyzer."),i}};var O=(e,t)=>async(r,i)=>{if(i&&i.length>0){await t(r,i);return}await e(r)};var oi=(e,t)=>{let r=e.split(`
|
|
829
837
|
`),i=[],n=new RegExp(`^import\\s+${t}\\s+from\\s+['"][^'"]+['"];?\\s*$`),o=/^(import\s+)\{([^}]+)\}(\s+from\s+['"][^'"]+['"];?\s*)$/;for(let s of r){if(n.test(s))continue;let c=s.match(o);if(c){let p=c[2].split(",").map(d=>d.trim()).filter(Boolean),u=p.filter(d=>d.replace(/^type\s+/,"").split(/\s+as\s+/)[0].trim()!==t);if(u.length===0)continue;if(u.length<p.length){i.push(`${c[1]}{ ${u.join(", ")} }${c[3]}`);continue}}i.push(s)}return i.join(`
|
|
830
|
-
`)},
|
|
831
|
-
`),i=new RegExp(`^([ \\t]*)<${e}\\b`),n=-1,o="";for(let f=0;f<r.length;f++){let
|
|
832
|
-
`);return
|
|
838
|
+
`)},Ve=e=>t=>{let r=t.split(`
|
|
839
|
+
`),i=new RegExp(`^([ \\t]*)<${e}\\b`),n=-1,o="";for(let f=0;f<r.length;f++){let x=r[f].match(i);if(x){n=f,o=x[1];break}}if(n===-1||!/>\s*$/.test(r[n]))return null;let s=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`^${s}<\\/${e}>\\s*$`),p=-1;for(let f=n+1;f<r.length;f++)if(c.test(r[f])){p=f;break}if(p===-1)return null;let u=r.slice(n+1,p).map(f=>f.startsWith(" ")?f.slice(2):f),d=[...r.slice(0,n),...u,...r.slice(p+1)].join(`
|
|
840
|
+
`);return oi(d,e)};var go=e=>{let t=e.split(`
|
|
833
841
|
`).filter(i=>!/^import\s+createNextIntlPlugin\s+from\s+['"]next-intl\/plugin['"];?\s*$/.test(i)).join(`
|
|
834
|
-
`);t=t.replace(/^const\s+withNextIntl\s*=\s*createNextIntlPlugin\([^)]*\);\s*\n?/m,"");let r=/withNextIntl\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/;return r.test(t)?(t=t.replace(r,"$1"),t):null},
|
|
835
|
-
`;var
|
|
836
|
-
`,await h(t,r))},
|
|
842
|
+
`);t=t.replace(/^const\s+withNextIntl\s*=\s*createNextIntlPlugin\([^)]*\);\s*\n?/m,"");let r=/withNextIntl\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/;return r.test(t)?(t=t.replace(r,"$1"),t):null},ho=e=>{let t=oi(e,"withBundleAnalyzer"),r=/^const\s+bundleAnalyzer\s*=\s*withBundleAnalyzer\(\{[\s\S]*?\}\);\s*\n?/m;if(!r.test(t))return null;t=t.replace(r,"");let i=/bundleAnalyzer\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/;return i.test(t)?(t=t.replace(i,"$1"),t):null};var yo={id:"bundle-analyzer",name:"Bundle Analyzer",description:"@next/bundle-analyzer wrapped around the default export",detect:async e=>{let t=Jp.join(e,a.NEXT_CONFIG);return l(t)?/@next\/bundle-analyzer/.test(await g(t)):!1},files:[],packages:[{name:"@next/bundle-analyzer",kind:"devDependency"}],scripts:[{name:"analyze",expectedValue:"ANALYZE=true next build"}],injections:[{file:a.NEXT_CONFIG,description:"withBundleAnalyzer import + wrapping",presence:/@next\/bundle-analyzer/,removePattern:ho}],apply:O(Wt,fo)};P();w();import Yp from"node:path";P();import xo from"node:path";import Wp from"picocolors";w();var yt=`${JSON.stringify({path:"cz-conventional-changelog"},null,2)}
|
|
843
|
+
`;var si=e=>{let t={...e.scripts??{}},r={...e.devDependencies??{}};return t.commit||(t.commit="cz"),r[R.COMMITIZEN]||(r[R.COMMITIZEN]="*"),r[R.CZ_CONVENTIONAL_CHANGELOG]||(r[R.CZ_CONVENTIONAL_CHANGELOG]="*"),{...e,scripts:t,devDependencies:r}},ai=e=>{let t=e.devDependencies??{},r=[];return t[R.COMMITIZEN]||r.push(R.COMMITIZEN),t[R.CZ_CONVENTIONAL_CHANGELOG]||r.push(R.CZ_CONVENTIONAL_CHANGELOG),r};var Xt=async e=>{let t=S("Setting up Commitizen...");try{let r=xo.join(e,a.CZRC);l(r)||await h(r,yt);let i=xo.join(e,a.PACKAGE_JSON),n=JSON.parse(await g(i)),o=ai(n);if(await _(i,s=>si(s)),o.length>0){t.text=`Installing ${o.join(", ")}...`;let s=await A(e);await fe(e,s,o)}t.succeed(Wp.green("Commitizen configured. Use `commit` to start a guided commit."))}catch(r){throw t.fail("Failed to set up Commitizen."),r}};P();import qp from"node:path";import Xp from"picocolors";w();var wo=async(e,t)=>{let r=S("Repairing Commitizen...");try{let i=!1;if(F(t,a.CZRC)){let c=qp.join(e,a.CZRC);l(c)||(await h(c,yt),i=!0)}let n=await B(e,t),o=await Ee(e,t),s=[i?`rewrote ${a.CZRC}`:null,n.length>0?`reinstalled ${n.join(", ")}`:null,o.length>0?`restored ${o.join(", ")}`:null].filter(Boolean);r.succeed(Xp.green(s.length>0?`Commitizen repaired (${s.join("; ")}).`:"Commitizen repaired."))}catch(i){throw r.fail("Failed to repair Commitizen."),i}};var Po={id:"commitizen",name:"Commitizen",description:"Guided conventional-commit prompt via `commit` script",detect:async e=>l(Yp.join(e,a.CZRC)),files:[{path:a.CZRC,generated:!0}],packages:[{name:"commitizen",kind:"devDependency"},{name:"cz-conventional-changelog",kind:"devDependency"}],scripts:[{name:"commit",expectedValue:"cz"}],injections:[],apply:O(Xt,wo)};P();w();import tl from"node:path";import Kp from"node:path";import Zp from"picocolors";w();P();import vo from"node:path";w();var So=async(e,t)=>{t.text="Fetching assets from starter repo...",await J(e)},Eo=async(e,t)=>{let r=vo.join(e,a.THEME_PROVIDER),i=vo.join(t,"src/providers/CustomThemeProvider.tsx");await b(i,r)};P();w();import xt from"node:path";P();w();import To from"node:path";var Yt=async e=>{let t=[To.join(e,a.ROOT_LAYOUT),To.join(e,"src/app/[locale]/layout.tsx")];for(let r of t)if(l(r)&&(await g(r)).includes("<body"))return r;for(let r of t)if(l(r))return r;return""};var Co=async e=>{let t=xt.join(e,a.THEME_PROVIDER),r=xt.join(e,a.GLOBALS_CSS),i=xt.join(e,"package.json");if(l(t))return{isSetup:!0,reason:"CustomThemeProvider.tsx exists"};if(l(i)){let n=JSON.parse(await g(i)),o="@teispace/next-themes";if(n.dependencies?.[o]||n.devDependencies?.[o])return{isSetup:!0,reason:`${o} is installed`}}return l(r)&&(await g(r)).includes("@custom-variant dark")?{isSetup:!0,reason:"Dark theme CSS found in globals.css"}:{isSetup:!1,reason:""}},Ro=async e=>{let t=xt.join(e,a.GLOBALS_CSS),r=xt.join(e,a.PROVIDERS_INDEX),i=await Yt(e);if(!l(t)||!i||!l(r))throw new Error("Project structure mismatch. Ensure src/styles/globals.css, src/app/layout.tsx (or src/app/[locale]/layout.tsx), and src/providers/index.ts exist.");return i};P();w();import Kt from"node:path";var Zt=async e=>{let t=Kt.join(e,a.PROVIDERS_INDEX),r=await g(t);r.includes("CustomThemeProvider")||(r+=`export * from './CustomThemeProvider';
|
|
844
|
+
`,await h(t,r))},Qt=async e=>{let t=Kt.join(e,"src/providers/RootProvider.tsx");if(!l(t))return;let r=await g(t),i="'use client';",n=r.includes(i);if(n&&(r=r.replace(i,"").trim()),r.includes("CustomThemeProvider")||(/import\s*\{[^}]*\}\s*from\s*'@\/providers'/.test(r)?r=r.replace(/(import\s*\{)([^}]*)(\}\s*from\s*'@\/providers')/,(o,s,c,p)=>`${s}${c.trim()?`${c.trim()}, CustomThemeProvider `:" CustomThemeProvider "}${p}`):r=`import { CustomThemeProvider } from '@/providers';
|
|
837
845
|
${r}`),n&&(r=`${i}
|
|
838
846
|
${r}`),!r.includes("<CustomThemeProvider"))if(r.includes("{children}"))r=r.replace(/\{children\}/,"<CustomThemeProvider>{children}</CustomThemeProvider>");else{let o=r.match(/return\s*\(\s*([\s\S]*?)\s*\);/);o&&(r=r.replace(o[0],`return (
|
|
839
847
|
<CustomThemeProvider>
|
|
840
848
|
${o[1]}
|
|
841
849
|
</CustomThemeProvider>
|
|
842
|
-
);`))}await h(t,r)},
|
|
850
|
+
);`))}await h(t,r)},bo=async(e,t)=>{let r=Kt.join(e,a.GLOBALS_CSS),i=Kt.join(t,"src/styles/globals.css"),n="";if(l(i)){let s=await g(i),c=s.match(/@custom-variant dark \(.*?\);/),p=s.match(/@theme \{[\s\S]*?\}/);c&&(n+=`
|
|
843
851
|
${c[0]}
|
|
844
852
|
`),p&&(n+=`
|
|
845
853
|
${p[0]}
|
|
@@ -851,40 +859,40 @@ ${p[0]}
|
|
|
851
859
|
--color-light: #f5f5f5;
|
|
852
860
|
}
|
|
853
861
|
`);let o=await g(r);if(!o.includes("@custom-variant dark")){if(o.includes("@import")){let s=o.lastIndexOf("@import"),c=o.indexOf(`
|
|
854
|
-
`,s);o=o.slice(0,c+1)+n+o.slice(c+1)}else o=n+o;await h(r,o)}},
|
|
862
|
+
`,s);o=o.slice(0,c+1)+n+o.slice(c+1)}else o=n+o;await h(r,o)}},Io=async e=>{let t=await g(e);t.includes("dark:bg-dark")||(t=t.replace(/className="([^"]*)"/,'className="$1 bg-light dark:bg-dark"'),await h(e,t))};var er=async e=>{let t=S("Setting up Dark Theme..."),r=Kp.join(e,".next-maker-temp");try{let{isSetup:i,reason:n}=await Co(e);if(i){t.fail(`Dark Theme is already set up (${n}).`);return}let o=await Ro(e);await So(r,t),await Eo(e,r),await Zt(e),await Qt(e),await bo(e,r),await Io(o),t.text="Installing @teispace/next-themes...",await z(e,"@teispace/next-themes"),t.text="Formatting code...";let s=await A(e);await K(e,s,"lint:fix"),t.succeed(Zp.green("Dark Theme setup successfully!"))}catch(i){throw t.fail("Failed to setup Dark Theme."),i}finally{await v(r)}};P();import tr from"node:path";import Qp from"picocolors";w();var el="src/providers/RootProvider.tsx",$o=async(e,t)=>{let r=S("Repairing Dark Theme..."),i=tr.join(e,".next-maker-temp-dark-theme-repair");try{let n=tr.join(e,a.THEME_PROVIDER),o=[];F(t,a.THEME_PROVIDER)&&!l(n)&&(r.text="Fetching CustomThemeProvider from starter repo...",await te(i,async p=>{await b(tr.join(p,a.THEME_PROVIDER),n)}),o.push(a.THEME_PROVIDER)),U(t,el)&&(r.text="Restoring <CustomThemeProvider> wrap...",l(tr.join(e,a.PROVIDERS_INDEX))&&await Zt(e),await Qt(e),o.push("<CustomThemeProvider> wrap")),r.text="Restoring dependencies...";let s=await B(e,t),c=[o.length>0?`restored ${o.join(", ")}`:null,s.length>0?`reinstalled ${s.join(", ")}`:null].filter(Boolean);r.succeed(Qp.green(c.length>0?`Dark Theme repaired (${c.join("; ")}).`:"Dark Theme repaired."))}catch(n){throw r.fail("Failed to repair Dark Theme."),n}};var ko={id:"dark-theme",name:"Dark Theme",description:"@teispace/next-themes + CustomThemeProvider",detect:async e=>l(tl.join(e,a.THEME_PROVIDER)),files:[{path:a.THEME_PROVIDER,generated:!0}],packages:[{name:"@teispace/next-themes",kind:"dependency"}],scripts:[],injections:[{file:"src/providers/RootProvider.tsx",description:"<CustomThemeProvider> wrap",presence:/CustomThemeProvider/,removePattern:Ve("CustomThemeProvider")}],apply:O(er,$o)};import rl from"node:fs/promises";import ir from"node:path";import nr from"enquirer";import ci from"picocolors";w();P();import re from"node:fs/promises";import T from"node:path";w();var No=async(e,t)=>{t.text="Downloading assets from starter repository...",await J(e)},Ao=async(e,t,r,i)=>{let n=T.join(e,a.HTTP_UTILS),o=T.join(t,a.HTTP_UTILS);await re.cp(T.join(t,a.ERRORS_DIR),T.join(e,a.ERRORS_DIR),{recursive:!0});let s=T.join(e,a.APP_APIS);l(s)||await b(T.join(t,a.APP_APIS),s);let c=T.join(e,a.API_URL_FILE);l(c)||await b(T.join(t,a.API_URL_FILE),c);let p=T.join(e,a.CONSTANTS);if(!l(p))await b(T.join(t,a.CONSTANTS),p);else{let d=await g(p),f=!1;d.includes("API_RESPONSE_DATA_KEY")||(d+=`
|
|
855
863
|
export const API_RESPONSE_DATA_KEY = 'data';
|
|
856
864
|
`,f=!0),d.includes("SAVE_AUTH_TOKENS")||(d+=`
|
|
857
865
|
export const SAVE_AUTH_TOKENS = false;
|
|
858
|
-
`,f=!0),f&&await h(p,d)}let u=T.join(e,a.STORAGE_SERVICE);if(l(u)||await
|
|
866
|
+
`,f=!0),f&&await h(p,d)}let u=T.join(e,a.STORAGE_SERVICE);if(l(u)||await re.cp(T.join(t,a.STORAGE_SERVICE),u,{recursive:!0}),await re.cp(T.join(t,a.COMMON_TYPES_DIR),T.join(e,a.COMMON_TYPES_DIR),{recursive:!0}),await re.cp(T.join(t,a.UTILITY_TYPES_DIR),T.join(e,a.UTILITY_TYPES_DIR),{recursive:!0}),await b(T.join(o,"token-store.ts"),T.join(n,"token-store.ts")),await b(T.join(o,"client-utils.ts"),T.join(n,"client-utils.ts")),await re.cp(T.join(t,a.HTTP_SHARED),T.join(e,a.HTTP_SHARED),{recursive:!0,force:!0}),await b(T.join(o,"server.ts"),T.join(n,"server.ts")),await re.cp(T.join(t,a.HTTP_BUNDLE_SENTINEL_DIR),T.join(e,a.HTTP_BUNDLE_SENTINEL_DIR),{recursive:!0,force:!0}),i&&i.length>0)for(let d of i){let f=T.join(e,d==="fetch"?a.FETCH_CLIENT:a.AXIOS_CLIENT);await v(f)}for(let d of r)d==="fetch"?await re.cp(T.join(t,a.FETCH_CLIENT),T.join(e,a.FETCH_CLIENT),{recursive:!0}):await re.cp(T.join(t,a.AXIOS_CLIENT),T.join(e,a.AXIOS_CLIENT),{recursive:!0});await b(T.join(o,"index.ts"),T.join(n,"index.ts")),await b(T.join(t,a.HTTP_TYPES),T.join(e,a.HTTP_TYPES))},_o=async e=>{let{isFileUsed:t,isStringUsed:r,stripSaveAuthTokens:i}=await Promise.resolve().then(()=>(Be(),nn));await v(T.join(e,a.HTTP_UTILS));let n=T.join(e,a.STORAGE_SERVICE);l(n)&&(await r(e,"SecureStorageService",[n])||await v(n));let o=T.join(e,a.API_URL_FILE);l(o)&&(await r(e,"getApiBaseUrl",[o])||await re.unlink(o));let s=T.join(e,a.CONSTANTS);if(l(s)){let d=await g(s),f=!1;if(await r(e,"API_RESPONSE_DATA_KEY",[s])||(d=d.replace(/export const API_RESPONSE_DATA_KEY = .*;\n?/g,""),f=!0),!await r(e,"SAVE_AUTH_TOKENS",[s])){let H=i(d);H!==d&&(d=H,f=!0)}f&&(d=`${d.replace(/\n\s*\n/g,`
|
|
859
867
|
|
|
860
868
|
`).trim()}
|
|
861
|
-
`,await h(s,d))}let c=T.join(e,a.ERRORS_DIR);if(l(c)){let d=await
|
|
869
|
+
`,await h(s,d))}let c=T.join(e,a.ERRORS_DIR);if(l(c)){let d=await re.readdir(c),f=!1;for(let x of d){let I=T.parse(x).name;if(await t(e,I,[T.join(c,x)])){f=!0;break}}f||await v(c)}let p=T.join(e,a.COMMON_TYPES_DIR);l(p)&&(await re.readdir(p)).length===0&&await v(p);let u=T.join(e,a.UTILITY_TYPES_DIR);l(u)&&(await re.readdir(u)).length===0&&await v(u)};P();w();import wt from"node:path";var rr=async e=>{let t=wt.join(e,a.FETCH_CLIENT_FILE),r=wt.join(e,a.AXIOS_CLIENT_FILE),i=l(t),n=l(r);return i&&n?{status:"both",reason:"Both Fetch and Axios clients are detected"}:i?{status:"fetch",reason:"Fetch client is already setup"}:n?{status:"axios",reason:"Axios client is already setup"}:{status:"none"}},Fo=async e=>{let r=[wt.join(e,"src/lib"),wt.join(e,"src/types"),wt.join(e,"src/lib/config")].filter(i=>!l(i));if(r.length>0)throw new Error(`Invalid project structure. Missing directories:
|
|
862
870
|
${r.map(i=>`- ${i}`).join(`
|
|
863
|
-
`)}`)};
|
|
871
|
+
`)}`)};Be();var or=async e=>{let t=S("Checking HTTP Client setup..."),r=ir.join(e,".next-maker-temp-http");try{let{status:i,reason:n}=await rr(e);t.stop();let o=await il(i,n);if(o.type==="cancel"){console.log(ci.yellow("Setup cancelled."));return}if(t.start("Setting up HTTP client(s)..."),await Fo(e),await No(r,t),o.type==="replace"&&o.fromClient&&(t.text="Migrating client usages...",await jr(e,o.fromClient,o.clients[0])),o.type!=="remove-both"&&o.type!=="remove-one"){t.text="Copying client files...";let I=o.type==="replace"&&o.fromClient?[o.fromClient]:void 0;await Ao(e,r,o.clients,I)}if(o.type==="remove-one"||o.type==="remove-both"){t.text="Removing client files...";let{PROJECT_PATHS:I}=await Promise.resolve().then(()=>(P(),Xi));for(let k of o.clients){let Z=ir.join(e,k==="fetch"?I.FETCH_CLIENT:I.AXIOS_CLIENT);await v(Z)}Oo(i,o).length===0&&(t.text="Performing full cleanup...",await _o(e),await Mr(e))}let s=Oo(i,o);s.length>0?(t.text="Configuring client...",await Ar(e,s),await _r(e),await Fr(e),await Or(e),await tt(e),await we(e,s),await Pe(e,s)):await rt(e),await Ue(e,s),t.text="Managing dependencies...";let c=ir.join(e,"package.json"),p=JSON.parse(await rl.readFile(c,"utf-8")),u={...p.dependencies,...p.devDependencies};s.includes("axios")?u.axios||(t.text="Installing Axios...",await z(e,"axios")):u.axios&&(t.text="Uninstalling Axios...",await He(e,"axios")),s.length>0?u["server-only"]||(t.text="Installing server-only...",await z(e,"server-only")):u["server-only"]&&(t.text="Uninstalling server-only...",await He(e,"server-only"));let d=ir.join(e,"src/services/storage");s.length>0||l(d)?u["react-secure-storage"]||(t.text="Installing react-secure-storage...",await z(e,"react-secure-storage")):u["react-secure-storage"]&&(t.text="Uninstalling react-secure-storage...",await He(e,"react-secure-storage")),t.text="Formatting code...";let x=await A(e);await K(e,x,"lint:fix"),t.succeed(ci.green(nl(o)))}catch(i){throw t.fail("Failed to setup HTTP Client."),i}finally{await v(r)}};async function il(e,t){if(e==="none"){let{choice:i}=await nr.prompt({type:"select",name:"choice",message:"Which HTTP client(s) do you want to setup?",choices:[{name:"fetch",message:"Fetch (Native)"},{name:"axios",message:"Axios"},{name:"both",message:"Both (Fetch + Axios)"}]});return i==="both"?{type:"install",clients:["fetch","axios"]}:{type:"install",clients:[i]}}if(e==="fetch"){let{action:i}=await nr.prompt({type:"select",name:"action",message:`${t}. What would you like to do?`,choices:[{name:"cancel",message:"Keep Fetch only (cancel)"},{name:"add",message:"Add Axios (have both)"},{name:"replace",message:"Replace with Axios only"},{name:"remove",message:"Remove Fetch"}]});if(i==="cancel")return{type:"cancel",clients:[]};if(i==="add")return{type:"add",clients:["axios"]};if(i==="replace")return{type:"replace",clients:["axios"],fromClient:"fetch"};if(i==="remove")return{type:"remove-one",clients:["fetch"]}}if(e==="axios"){let{action:i}=await nr.prompt({type:"select",name:"action",message:`${t}. What would you like to do?`,choices:[{name:"cancel",message:"Keep Axios only (cancel)"},{name:"add",message:"Add Fetch (have both)"},{name:"replace",message:"Replace with Fetch only"},{name:"remove",message:"Remove Axios"}]});if(i==="cancel")return{type:"cancel",clients:[]};if(i==="add")return{type:"add",clients:["fetch"]};if(i==="replace")return{type:"replace",clients:["fetch"],fromClient:"axios"};if(i==="remove")return{type:"remove-one",clients:["axios"]}}console.log(ci.yellow(`\u2716 ${t}`));let{action:r}=await nr.prompt({type:"select",name:"action",message:"What would you like to do?",choices:[{name:"cancel",message:"Keep both (cancel)"},{name:"remove-fetch",message:"Remove Fetch (keep Axios)"},{name:"remove-axios",message:"Remove Axios (keep Fetch)"},{name:"remove-both",message:"Remove both"}]});return r==="cancel"?{type:"cancel",clients:[]}:r==="remove-fetch"?{type:"remove-one",clients:["fetch"]}:r==="remove-axios"?{type:"remove-one",clients:["axios"]}:r==="remove-both"?{type:"remove-both",clients:["fetch","axios"]}:{type:"cancel",clients:[]}}function Oo(e,t){return t.type==="install"?t.clients:t.type==="add"?[...e==="fetch"?["fetch"]:["axios"],...t.clients]:t.type==="replace"?t.clients:t.type==="remove-one"?e==="both"?t.clients[0]==="fetch"?["axios"]:["fetch"]:[]:[]}function nl(e){if(e.type==="install")return`HTTP Client (${e.clients.map(r=>r==="fetch"?"Fetch":"Axios").join(" + ")}) setup successfully!`;if(e.type==="add")return`${e.clients[0]==="fetch"?"Fetch":"Axios"} client added successfully! Both clients are now available.`;if(e.type==="replace"){let t=e.fromClient==="fetch"?"Fetch":"Axios",r=e.clients[0]==="fetch"?"Fetch":"Axios";return`Replaced ${t} with ${r} successfully! Imports automatically migrated.`}return e.type==="remove-one"?`${e.clients[0]==="fetch"?"Fetch":"Axios"} client removed successfully!`:e.type==="remove-both"?"Both HTTP clients removed successfully!":"HTTP Client setup completed!"}Be();P();import ol from"node:fs/promises";import Ae from"node:path";import sl from"picocolors";w();Be();var Do=async(e,t)=>{let r=S("Repairing HTTP Client..."),i=Ae.join(e,".next-maker-temp-http-repair");try{let{status:n}=await rr(e),o=n==="both"?["fetch","axios"]:n==="none"?[]:[n],s=[a.HTTP_SHARED,a.HTTP_BUNDLE_SENTINEL_DIR].filter(f=>F(t,f)&&!l(Ae.join(e,f))),c=[a.HTTP_SERVER_FILE,a.API_URL_FILE].filter(f=>F(t,f)&&!l(Ae.join(e,f))),p=[];(s.length>0||c.length>0)&&(r.text="Fetching assets from starter repo...",await te(i,async f=>{for(let x of s)await ol.cp(Ae.join(f,x),Ae.join(e,x),{recursive:!0,force:!0}),p.push(x);for(let x of c)await b(Ae.join(f,x),Ae.join(e,x)),p.push(x)}),o.length>0&&(await we(e,o),await Pe(e,o))),U(t)&&(r.text="Re-mounting the bundle sentinel...",await tt(e),p.push("<HttpClientBundleSentinel /> mount"));let u=await B(e,t),d=[p.length>0?`restored ${p.join(", ")}`:null,u.length>0?`reinstalled ${u.join(", ")}`:null].filter(Boolean);r.succeed(sl.green(d.length>0?`HTTP Client repaired (${d.join("; ")}).`:"HTTP Client repaired."))}catch(n){throw r.fail("Failed to repair HTTP Client."),n}};var al=/<HttpClientBundleSentinel\s*\/>/,jo={id:"http-client",name:"HTTP Client",description:"Axios and/or Fetch client utilities",detect:async e=>{let{detectProjectSetup:t}=await Promise.resolve().then(()=>(q(),ct));return(await t(e)).httpClient!=="none"},files:[{path:"src/lib/utils/http",generated:!0,isDir:!0,containsUserContent:!0,removeHint:"holds the http client + any service modules you wired through it \u2014 review before deleting"},{path:"src/lib/utils/http/shared",generated:!0,isDir:!0},{path:"src/lib/utils/http/server.ts",generated:!0},{path:"src/lib/utils/http/__bundle-sentinel__",generated:!0,isDir:!0},{path:"src/lib/config/api-url.ts",generated:!0}],packages:[],scripts:[],injections:[{file:"src/app/[locale]/layout.tsx",alternativeFiles:["src/app/layout.tsx"],description:"<HttpClientBundleSentinel /> mount in the app layout",presence:al,removePattern:_t}],apply:O(or,Do)};P();import pi from"node:path";import ll from"picocolors";w();P();import cl from"node:fs/promises";import Te from"node:path";w();var Lo=async(e,t)=>{t.text="Fetching assets from starter repo...",await J(e)},Mo=async(e,t)=>{let r=Te.join(t,"src/i18n"),i=Te.join(e,a.I18N_DIR);await cl.cp(r,i,{recursive:!0});let n=Te.join(t,"src/proxy.ts"),o=Te.join(e,a.PROXY);await b(n,o);let s=Te.join(t,"src/types/i18n.ts"),c=Te.join(e,a.I18N_TYPES);await b(s,c);let p=Te.join(t,"src/lib/config/app-locales.ts"),u=Te.join(e,a.APP_LOCALES);await b(p,u)};P();w();import sr from"node:path";var Go=async e=>{let t=sr.join(e,a.I18N_DIR),r=sr.join(e,"package.json");if(l(t))return{isSetup:!0,reason:"src/i18n directory exists"};if(l(r)){let i=JSON.parse(await g(r));if(i.dependencies?.["next-intl"]||i.devDependencies?.["next-intl"])return{isSetup:!0,reason:"next-intl is installed"}}return{isSetup:!1,reason:""}},Ho=async e=>{let t=sr.join(e,a.ROOT_LAYOUT),r=sr.join(e,"src/app/[locale]/layout.tsx");if(!l(t)&&!l(r))throw new Error("Project structure mismatch. Ensure src/app/layout.tsx exists.")};P();w();import pl from"node:fs/promises";import he from"node:path";var ar=async e=>{let t=he.join(e,a.NEXT_CONFIG);if(l(t)){let r=await g(t);if(!r.includes("createNextIntlPlugin")){r=`import createNextIntlPlugin from 'next-intl/plugin';
|
|
864
872
|
${r}`;let i=/export default (.*?);/;i.test(r)?r=r.replace(i,`
|
|
865
873
|
const withNextIntl = createNextIntlPlugin();
|
|
866
874
|
export default withNextIntl($1);`):(r+=`
|
|
867
875
|
const withNextIntl = createNextIntlPlugin();
|
|
868
876
|
`,r+=`export default withNextIntl(nextConfig);
|
|
869
|
-
`),await h(t,r)}}},
|
|
870
|
-
`,await h(t,r))}},
|
|
871
|
-
`,await h(t,r))}},
|
|
877
|
+
`),await h(t,r)}}},cr=async e=>{let t=he.join(e,a.TYPES_INDEX);if(l(t)){let r=await g(t);r.includes("./i18n")||(r+=`export * from './i18n';
|
|
878
|
+
`,await h(t,r))}},pr=async e=>{let t=he.join(e,a.CONFIG_INDEX);if(l(t)){let r=await g(t);r.includes("./app-locales")||(r+=`export * from './app-locales';
|
|
879
|
+
`,await h(t,r))}},lr=async e=>{let t=he.join(e,"src/providers/RootProvider.tsx");if(l(t)){let r=await g(t),i="'use client';",n=r.includes(i);if(n&&(r=r.replace(i,"").trim()),r.includes("next-intl")||(r=`import { type AbstractIntlMessages, NextIntlClientProvider } from 'next-intl';
|
|
872
880
|
import type { SupportedLocale } from '@/types/i18n';
|
|
873
881
|
`+r),n&&(r=`${i}
|
|
874
882
|
${r}`),!r.includes("locale: SupportedLocale")){let o=` locale: SupportedLocale;
|
|
875
883
|
messages: AbstractIntlMessages;
|
|
876
|
-
timeZone: string;`,s=/(type\s+RootProviderProps\s*=\s*\{)([\s\S]*?)(\};?)/,c=/export const RootProvider = \(\{([\s\S]*?)\}: \{([\s\S]*?)\}\) => \{/;if(s.test(r))r=r.replace(s,(p,u,d,f)=>{let
|
|
884
|
+
timeZone: string;`,s=/(type\s+RootProviderProps\s*=\s*\{)([\s\S]*?)(\};?)/,c=/export const RootProvider = \(\{([\s\S]*?)\}: \{([\s\S]*?)\}\) => \{/;if(s.test(r))r=r.replace(s,(p,u,d,f)=>{let x=d.replace(/\s+$/,"");return`${u}${x}
|
|
877
885
|
${o}
|
|
878
886
|
${f}`}),r=r.replace(/export const RootProvider = \(\{([\s\S]*?)\}:\s*RootProviderProps\)/,(p,u)=>{let d=u.trim().replace(/,$/,"");return`export const RootProvider = ({ ${d?`${d}, `:""}locale, messages, timeZone }: RootProviderProps)`});else{let p=r.match(c);if(p){let u=p[1].trim().replace(/,$/,""),d=p[2].trim().replace(/;$/,""),f=`
|
|
879
887
|
${u?`${u},
|
|
880
888
|
`:""}locale,
|
|
881
889
|
messages,
|
|
882
|
-
timeZone,`,
|
|
890
|
+
timeZone,`,x=`
|
|
883
891
|
${d?`${d};
|
|
884
892
|
`:""}locale: SupportedLocale;
|
|
885
893
|
messages: AbstractIntlMessages;
|
|
886
894
|
timeZone: string;`;r=r.replace(p[0],`export const RootProvider = ({${f}
|
|
887
|
-
}: {${
|
|
895
|
+
}: {${x}
|
|
888
896
|
}) => {`)}}}if(!r.includes("<NextIntlClientProvider")){let o=r.match(/return\s*(?:\(\s*)?([\s\S]*?)(?:\s*\))?;/);if(o){let s=o[1],c=`<NextIntlClientProvider locale={locale} messages={messages} timeZone={timeZone}>
|
|
889
897
|
{children}
|
|
890
898
|
</NextIntlClientProvider>`;if(s.includes("{children}")){let p=s.replace("{children}",c);r=r.replace(o[0],`return (
|
|
@@ -893,7 +901,7 @@ ${f}`}),r=r.replace(/export const RootProvider = \(\{([\s\S]*?)\}:\s*RootProvide
|
|
|
893
901
|
<NextIntlClientProvider locale={locale} messages={messages} timeZone={timeZone}>
|
|
894
902
|
${s}
|
|
895
903
|
</NextIntlClientProvider>
|
|
896
|
-
);`)}}await h(t,r)}},
|
|
904
|
+
);`)}}await h(t,r)}},Uo=async e=>{let t=he.join(e,a.ROOT_LAYOUT),r=he.join(e,a.ROOT_PAGE),i=he.join(e,"src/app/[locale]");if(await pl.mkdir(i,{recursive:!0}),l(t)){let n=he.join(i,"layout.tsx"),o=await g(t);if(o.includes("next-intl")||(o=`import { routing } from '@/i18n/routing';
|
|
897
905
|
import { hasLocale } from 'next-intl';
|
|
898
906
|
import { notFound } from 'next/navigation';
|
|
899
907
|
import { getMessages, getTimeZone, setRequestLocale } from 'next-intl/server';
|
|
@@ -915,7 +923,7 @@ export function generateStaticParams() {
|
|
|
915
923
|
setRequestLocale(locale);
|
|
916
924
|
|
|
917
925
|
const [messages, timeZone] = await Promise.all([getMessages(), getTimeZone()]);
|
|
918
|
-
`+o.slice(f+1)}o=o.replace(/<RootProvider>/,"<RootProvider locale={locale} messages={messages} timeZone={timeZone}>"),o=o.replace(/<html lang="en"/,"<html lang={locale} dir={getLocaleDirection(locale)}")}await h(n,o),await C(t)}if(l(r)){let n=
|
|
926
|
+
`+o.slice(f+1)}o=o.replace(/<RootProvider>/,"<RootProvider locale={locale} messages={messages} timeZone={timeZone}>"),o=o.replace(/<html lang="en"/,"<html lang={locale} dir={getLocaleDirection(locale)}")}await h(n,o),await C(t)}if(l(r)){let n=he.join(i,"page.tsx"),o=await g(r);o.includes("next-intl")||(o=`import { SupportedLocale } from '@/types/i18n';
|
|
919
927
|
import { setRequestLocale } from 'next-intl/server';
|
|
920
928
|
${o}`),o=o.replace(/export default function Home\(\)/,`type Props = {
|
|
921
929
|
params: Promise<{ locale: string }>;
|
|
@@ -924,8 +932,8 @@ ${o}`),o=o.replace(/export default function Home\(\)/,`type Props = {
|
|
|
924
932
|
export default async function Home(props: Props)`);let s=o.indexOf("export default async function Home(props: Props) {");if(s!==-1){let c=`
|
|
925
933
|
const locale = (await props.params).locale as SupportedLocale;
|
|
926
934
|
setRequestLocale(locale);
|
|
927
|
-
`,p=o.indexOf("{",s);o=o.slice(0,p+1)+c+o.slice(p+1)}await h(n,o),await C(r)}};var
|
|
928
|
-
reactCompiler: true,`)};var
|
|
935
|
+
`,p=o.indexOf("{",s);o=o.slice(0,p+1)+c+o.slice(p+1)}await h(n,o),await C(r)}};var mr=async e=>{let t=S("Setting up Internationalization (next-intl)..."),r=pi.join(e,".next-maker-temp-i18n");try{let{isSetup:i,reason:n}=await Go(e);if(i){t.fail(`i18n is already set up (${n}).`);return}await Ho(e),await Lo(r,t),t.text="Copying i18n files...",await Mo(e,r),t.text="Configuring project structure...",await ar(e),await cr(e),await pr(e),await lr(e),t.text="Migrating to [locale] structure...",await Uo(e),t.text="Installing dependencies...",await z(e,"next-intl");let o=pi.join(e,a.VITEST_CONFIG);if(l(o)){let c=JSON.parse(await g(pi.join(e,a.PACKAGE_JSON))),p={...c.dependencies,...c.devDependencies},u=!!(p["@reduxjs/toolkit"]&&p["react-redux"]);await ce(e,{redux:u,i18n:!0})}t.text="Formatting code...";let s=await A(e);await K(e,s,"lint:fix"),t.succeed(ll.green("Internationalization setup successfully!"))}catch(i){throw t.fail("Failed to setup Internationalization."),i}finally{await v(r)}};P();import ml from"node:fs/promises";import Pt from"node:path";import Bo from"picocolors";w();var dl="src/providers/RootProvider.tsx",zo=async(e,t)=>{let r=S("Repairing Internationalization..."),i=Pt.join(e,".next-maker-temp-i18n-repair");try{let n=Pt.join(e,a.I18N_DIR),o=Pt.join(e,a.PROXY),s=F(t,a.I18N_DIR)&&!l(n),c=F(t,a.PROXY)&&!l(o),p=[];(s||c)&&(r.text="Fetching assets from starter repo...",await te(i,async x=>{s&&(await ml.cp(Pt.join(x,a.I18N_DIR),n,{recursive:!0}),p.push(a.I18N_DIR)),c&&(await b(Pt.join(x,a.PROXY),o),p.push(a.PROXY))})),U(t,a.NEXT_CONFIG)&&(r.text="Restoring the next-intl plugin wrap...",await ar(e),p.push("createNextIntlPlugin wrap")),U(t,dl)&&(r.text="Restoring <NextIntlClientProvider>...",await lr(e),p.push("<NextIntlClientProvider> wrap")),p.length>0&&(await cr(e),await pr(e)),r.text="Restoring dependencies...";let u=await B(e,t),d=F(t,a.LOCALE_DIR),f=[p.length>0?`restored ${p.join(", ")}`:null,u.length>0?`reinstalled ${u.join(", ")}`:null].filter(Boolean);r.succeed(Bo.green(f.length>0?`Internationalization repaired (${f.join("; ")}).`:"Internationalization repaired.")),d&&console.log(Bo.yellow(` \u26A0\uFE0F ${a.LOCALE_DIR} is missing. Recreating it means moving your app-router pages, so it is left for you: run \`next-maker setup --i18n\` on a clean tree, or move your pages under ${a.LOCALE_DIR}/ by hand.`))}catch(n){throw r.fail("Failed to repair Internationalization."),n}};var Vo={id:"i18n",name:"Internationalization",description:"next-intl with [locale] routing, RootProvider, and proxy.ts",detect:async e=>{let{detectProjectSetup:t}=await Promise.resolve().then(()=>(q(),ct));return(await t(e)).hasI18n},files:[{path:"src/i18n",generated:!0,isDir:!0,containsUserContent:!0,removeHint:"holds your translation JSON files \u2014 copy any you want to keep, then delete by hand"},{path:"src/proxy.ts",generated:!0},{path:"src/app/[locale]",generated:!0,isDir:!0,containsUserContent:!0,removeHint:"holds every page you generated under the locale segment \u2014 move them to src/app/ before deleting"}],packages:[{name:"next-intl",kind:"dependency"}],scripts:[],injections:[{file:"next.config.ts",description:"createNextIntlPlugin wrap in next.config.ts",presence:/next-intl\/plugin/,removePattern:go},{file:"src/providers/RootProvider.tsx",description:"<NextIntlClientProvider> wrap",presence:/NextIntlClientProvider/,removePattern:Ve("NextIntlClientProvider")}],apply:O(mr,zo)};P();w();import yl from"node:path";P();import ul from"node:path";import fl from"picocolors";w();var Jo=/(const\s+nextConfig\s*:\s*NextConfig\s*=\s*\{)/,dr=e=>/reactCompiler\s*:/.test(e),vt=e=>{if(dr(e))return e;if(!Jo.test(e))throw new Error("Could not locate `const nextConfig: NextConfig = {` in next.config.ts.");return e.replace(Jo,`$1
|
|
936
|
+
reactCompiler: true,`)};var ur=async e=>{let t=S("Enabling React Compiler...");try{let r=ul.join(e,a.NEXT_CONFIG);if(!l(r))throw new Error(`${a.NEXT_CONFIG} not found.`);let i=await g(r);if(dr(i)){t.fail("React Compiler is already configured in next.config.ts.");return}await h(r,vt(i)),t.text="Installing babel-plugin-react-compiler...",await At(e,"babel-plugin-react-compiler"),t.succeed(fl.green("React Compiler enabled."))}catch(r){throw t.fail("Failed to enable React Compiler."),r}};P();import gl from"node:path";import hl from"picocolors";w();var Wo=async(e,t)=>{let r=S("Repairing React Compiler...");try{if(U(t,a.NEXT_CONFIG)){let n=gl.join(e,a.NEXT_CONFIG);if(l(n)){let o=await g(n),s=vt(o);s!==o&&await h(n,s)}}let i=await B(e,t);r.succeed(hl.green(i.length>0?`React Compiler repaired (reinstalled ${i.join(", ")}).`:"React Compiler repaired."))}catch(i){throw r.fail("Failed to repair React Compiler."),i}};var qo={id:"react-compiler",name:"React Compiler",description:"reactCompiler: true in next.config.ts + babel-plugin-react-compiler",detect:async e=>{let t=yl.join(e,a.NEXT_CONFIG);return l(t)?/reactCompiler\s*:\s*true/.test(await g(t)):!1},files:[],packages:[{name:"babel-plugin-react-compiler",kind:"devDependency"}],scripts:[],injections:[{file:a.NEXT_CONFIG,description:"`reactCompiler: true` flag",presence:/reactCompiler\s*:\s*true/,removePattern:/\n\s*reactCompiler:\s*true,?/}],apply:O(ur,Wo)};P();import di from"node:path";import xl from"picocolors";w();P();import Xo from"node:fs/promises";import _e from"node:path";w();var Yo=async(e,t)=>{t.text="Fetching assets from starter repo...",await J(e)},Ko=async(e,t)=>{let r=_e.join(t,"src/providers/StoreProvider.tsx"),i=_e.join(e,a.STORE_PROVIDER);await b(r,i);let n=_e.join(t,"src/store"),o=_e.join(e,a.STORE);await Xo.cp(n,o,{recursive:!0})},Zo=async(e,t)=>{let r=_e.join(t,"src/features/counter"),i=_e.join(e,a.COUNTER_FEATURE);await Xo.cp(r,i,{recursive:!0});let n=_e.join(i,"components/Counter.tsx");if(await l(n)){let o=await g(n);o=o.replace(/import \{ useTranslations \} from 'next-intl';\n?/,""),o=o.replace(/const t = useTranslations\('Count'\);\n?/,""),o=o.replace(/\{t\('currentCount', \{ count: value \}\)\}/g,"Current Count: {value}"),o=o.replace(/\{t\('increment'\)\}/g,"Increment"),o=o.replace(/\{t\('decrement'\)\}/g,"Decrement"),o=o.replace(/\{t\('reset'\)\}/g,"Reset"),await h(n,o)}};P();w();import li from"node:path";var Qo=async e=>{let t=li.join(e,a.STORE),r=li.join(e,"package.json");if(l(t))return{isSetup:!0,reason:"src/store directory exists"};if(l(r)){let i=JSON.parse(await g(r));if(i.dependencies?.["@reduxjs/toolkit"]||i.devDependencies?.["@reduxjs/toolkit"])return{isSetup:!0,reason:"@reduxjs/toolkit is installed"}}return{isSetup:!1,reason:""}},es=async e=>{let t=li.join(e,a.PROVIDERS_INDEX);if(!await Yt(e)||!l(t))throw new Error("Project structure mismatch. Ensure src/app/layout.tsx (or src/app/[locale]/layout.tsx) and src/providers/index.ts exist.")};P();w();import mi from"node:path";var ts=async e=>{},fr=async e=>{let t=mi.join(e,"src/providers/RootProvider.tsx");if(!l(t))return;let r=await g(t),i="'use client';",n=r.includes(i);if(n&&(r=r.replace(i,"").trim()),r.includes("from '@/store'")||(r=`import type { AppState } from '@/store';
|
|
929
937
|
${r}`),r.includes("from './StoreProvider'")||(r=`${r.includes("from '@/store'"),""}import { StoreProvider } from './StoreProvider';
|
|
930
938
|
${r}`),n&&(r=`${i}
|
|
931
939
|
${r}`),r.includes("preloadedState")||(r=r.replace(/children:\s*React\.ReactNode;/,`children: React.ReactNode;
|
|
@@ -933,13 +941,13 @@ ${r}`),r.includes("preloadedState")||(r=r.replace(/children:\s*React\.ReactNode;
|
|
|
933
941
|
<StoreProvider preloadedState={preloadedState}>
|
|
934
942
|
${s}
|
|
935
943
|
</StoreProvider>
|
|
936
|
-
);`)}}await h(t,r)},
|
|
944
|
+
);`)}}await h(t,r)},rs=async e=>{let t=[mi.join(e,a.ROOT_PAGE),mi.join(e,"src/app/[locale]/page.tsx")],r="";for(let n of t)if(l(n)){r=n;break}if(!r)return;let i=await g(r);if(i.includes("Counter")||(i=`import { Counter } from '@/features/counter';
|
|
937
945
|
${i}`),!i.includes("<Counter />")){let n=i.lastIndexOf("</div>"),o=i.lastIndexOf("</main>"),s=o!==-1?o:n;s!==-1&&(i=i.slice(0,s)+`
|
|
938
946
|
<div className="mt-8">
|
|
939
947
|
<h2 className="mb-4 text-2xl font-bold">Redux Counter</h2>
|
|
940
948
|
<Counter />
|
|
941
949
|
</div>
|
|
942
|
-
`+i.slice(s),await h(r,i))}};var
|
|
950
|
+
`+i.slice(s),await h(r,i))}};var gr=async e=>{let t=S("Setting up Redux Toolkit..."),r=di.join(e,".next-maker-temp-redux");try{let{isSetup:i,reason:n}=await Qo(e);if(i){t.fail(`Redux is already set up (${n}).`);return}await es(e),await Yo(r,t),t.text="Copying Redux files...",await Ko(e,r),t.text="Creating Counter feature...",await Zo(e,r),t.text="Updating providers and pages...",await ts(e),await fr(e),await rs(e),t.text="Installing dependencies...",await z(e,"@reduxjs/toolkit"),await z(e,"react-redux"),await z(e,"redux-persist"),await z(e,"react-secure-storage");let o=di.join(e,a.VITEST_CONFIG);if(l(o)){let c=JSON.parse(await g(di.join(e,a.PACKAGE_JSON))),p={...c.dependencies,...c.devDependencies};await ce(e,{redux:!0,i18n:!!p["next-intl"]})}t.text="Formatting code...";let s=await A(e);await K(e,s,"lint:fix"),t.succeed(xl.green("Redux Toolkit setup successfully!"))}catch(i){throw t.fail("Failed to setup Redux Toolkit."),i}finally{await v(r)}};P();import wl from"node:fs/promises";import St from"node:path";import Pl from"picocolors";w();var vl="src/providers/RootProvider.tsx",is=async(e,t)=>{let r=S("Repairing Redux Toolkit..."),i=St.join(e,".next-maker-temp-redux-repair");try{let n=St.join(e,a.STORE),o=St.join(e,a.STORE_PROVIDER),s=F(t,a.STORE)&&!l(n),c=F(t,a.STORE_PROVIDER)&&!l(o),p=[];(s||c)&&(r.text="Fetching assets from starter repo...",await te(i,async f=>{s&&(await wl.cp(St.join(f,a.STORE),n,{recursive:!0}),p.push(a.STORE)),c&&(await b(St.join(f,a.STORE_PROVIDER),o),p.push(a.STORE_PROVIDER))})),U(t,vl)&&(r.text="Restoring <StoreProvider> wrap...",await fr(e),p.push("<StoreProvider> wrap")),r.text="Restoring dependencies...";let u=await B(e,t),d=[p.length>0?`restored ${p.join(", ")}`:null,u.length>0?`reinstalled ${u.join(", ")}`:null].filter(Boolean);r.succeed(Pl.green(d.length>0?`Redux Toolkit repaired (${d.join("; ")}).`:"Redux Toolkit repaired."))}catch(n){throw r.fail("Failed to repair Redux Toolkit."),n}};var ns={id:"redux",name:"Redux Toolkit",description:"Redux Toolkit + react-redux + redux-persist + StoreProvider",detect:async e=>{let{detectProjectSetup:t}=await Promise.resolve().then(()=>(q(),ct));return(await t(e)).hasRedux},files:[{path:"src/store",generated:!0,isDir:!0,containsUserContent:!0,removeHint:"holds the rootReducer and any slices you registered \u2014 review before deleting"},{path:"src/providers/StoreProvider.tsx",generated:!0}],packages:[{name:"@reduxjs/toolkit",kind:"dependency"},{name:"react-redux",kind:"dependency"},{name:"redux-persist",kind:"dependency"}],scripts:[],injections:[{file:"src/providers/RootProvider.tsx",description:"<StoreProvider> wrap in RootProvider",presence:/<StoreProvider/,removePattern:Ve("StoreProvider")}],apply:O(gr,is)};P();w();import Il from"node:path";P();import Tl from"node:path";import Cl from"picocolors";w();var ss=[{key:"X-DNS-Prefetch-Control",value:"on"},{key:"Strict-Transport-Security",value:"max-age=63072000; includeSubDomains; preload"},{key:"X-XSS-Protection",value:"1; mode=block"},{key:"X-Frame-Options",value:"SAMEORIGIN"},{key:"X-Content-Type-Options",value:"nosniff"},{key:"Referrer-Policy",value:"origin-when-cross-origin"}],os=/(const\s+nextConfig\s*:\s*NextConfig\s*=\s*\{)/,Sl=/^\s+headers\s*:/m,El=e=>`
|
|
943
951
|
headers: async () => {
|
|
944
952
|
return [
|
|
945
953
|
{
|
|
@@ -950,7 +958,7 @@ ${e.map(({key:r,value:i})=>` { key: '${r}', value: '${i}' },`).join(`
|
|
|
950
958
|
],
|
|
951
959
|
},
|
|
952
960
|
];
|
|
953
|
-
},`,
|
|
961
|
+
},`,Je=e=>Sl.test(e),Et=(e,t=ss)=>{if(Je(e))return e;if(!os.test(e))throw new Error("Could not locate `const nextConfig: NextConfig = {` in next.config.ts.");return e.replace(os,`$1${El(t)}`)};var hr=async e=>{let t=S("Adding security headers to next.config.ts...");try{let r=Tl.join(e,a.NEXT_CONFIG);if(!l(r))throw new Error(`${a.NEXT_CONFIG} not found.`);let i=await g(r);if(Je(i)){t.succeed("Security headers already configured.");return}let n=Et(i);await h(r,n),t.succeed(Cl.green("Security headers added."))}catch(r){throw t.fail("Failed to add security headers."),r}};P();import Rl from"node:path";import bl from"picocolors";w();var as=async(e,t)=>{if(!U(t,a.NEXT_CONFIG))return;let r=S("Repairing security headers...");try{let i=Rl.join(e,a.NEXT_CONFIG);if(!l(i)){r.fail(`${a.NEXT_CONFIG} not found \u2014 cannot restore security headers.`);return}let n=await g(i),o=Et(n);o!==n&&await h(i,o),r.succeed(bl.green("Security headers restored."))}catch(i){throw r.fail("Failed to repair security headers."),i}};var cs={id:"security-headers",name:"Security Headers",description:"Hardened HTTP headers in next.config.ts",detect:async e=>{let t=Il.join(e,a.NEXT_CONFIG);return l(t)?Je(await g(t)):!1},files:[],packages:[],scripts:[],injections:[{file:a.NEXT_CONFIG,description:"headers() function in next.config.ts",presence:/^\s+headers\s*:/m,removePattern:/\s+headers:\s*async\s*\(\)\s*=>\s*\{[\s\S]*?\n\s{0,2}\},/m}],apply:O(hr,as)};P();w();import _l from"node:path";P();import $l from"node:fs/promises";import Ce from"node:path";import kl from"picocolors";w();var Nl=["vitest","jsdom","@vitejs/plugin-react","@testing-library/dom","@testing-library/jest-dom","@testing-library/react","@testing-library/user-event"],yr=async e=>{let t=S("Setting up testing (Vitest + RTL)..."),r=Ce.join(e,".next-maker-temp-tests");try{let i=Ce.join(e,a.VITEST_CONFIG);if(l(i)){t.fail("Testing is already set up (vitest.config.ts exists).");return}t.text="Fetching assets from starter repo...",await J(r),await b(Ce.join(r,a.VITEST_CONFIG),Ce.join(e,a.VITEST_CONFIG));let n=Ce.join(e,a.TEST_DIR);await $l.mkdir(n,{recursive:!0}),await b(Ce.join(r,a.TEST_DIR,"setup.ts"),Ce.join(n,"setup.ts"));let o=Ce.join(e,a.PACKAGE_JSON),s=JSON.parse(await g(o)),c={...s.dependencies,...s.devDependencies},p=!!(c["@reduxjs/toolkit"]&&c["react-redux"]),u=!!c["next-intl"];await ce(e,{redux:p,i18n:u}),await _(o,f=>(f.scripts=f.scripts??{},f.scripts.test=f.scripts.test??"vitest run",f.scripts["test:watch"]=f.scripts["test:watch"]??"vitest",f.scripts["test:coverage"]=f.scripts["test:coverage"]??"vitest run --coverage",typeof f.scripts.validate=="string"&&!/\byarn\s+test(?![:\w])/.test(f.scripts.validate)&&(f.scripts.validate=f.scripts.validate.replace(/(\byarn\s+check:deprecated\s*)(&&)/,"$1&& yarn test $2")),f)),t.text="Installing testing devDependencies...";let d=await A(e);await fe(e,d,Nl),t.text="Formatting code...",await K(e,d,"lint:fix"),t.succeed(kl.green("Testing setup complete."))}catch(i){throw t.fail("Failed to set up testing."),i}finally{await v(r)}};P();import Fe from"node:path";import Al from"picocolors";w();var ps=async(e,t)=>{let r=S("Repairing testing setup..."),i=Fe.join(e,".next-maker-temp-tests-repair");try{let n=F(t,a.VITEST_CONFIG)&&!l(Fe.join(e,a.VITEST_CONFIG)),o=Fe.join(e,a.TEST_SETUP_FILE),s=F(t,a.TEST_DIR)&&!l(o),c=[];if((n||s)&&(r.text="Fetching assets from starter repo...",await te(i,async f=>{n&&(await b(Fe.join(f,a.VITEST_CONFIG),Fe.join(e,a.VITEST_CONFIG)),c.push(a.VITEST_CONFIG)),s&&(await b(Fe.join(f,a.TEST_SETUP_FILE),o),c.push(a.TEST_SETUP_FILE))}),s)){let f=Fe.join(e,a.PACKAGE_JSON),x=l(f)?JSON.parse(await g(f)):{},I={...x.dependencies,...x.devDependencies};await ce(e,{redux:!!(I["@reduxjs/toolkit"]&&I["react-redux"]),i18n:!!I["next-intl"]}),c.push("test/test-utils.tsx")}r.text="Restoring testing dependencies...";let p=await B(e,t),u=await Ee(e,t),d=[c.length>0?`restored ${c.join(", ")}`:null,p.length>0?`reinstalled ${p.join(", ")}`:null,u.length>0?`reset ${u.join(", ")}`:null].filter(Boolean);r.succeed(Al.green(d.length>0?`Testing setup repaired (${d.join("; ")}).`:"Testing setup repaired."))}catch(n){throw r.fail("Failed to repair testing setup."),n}};var ls={id:"tests",name:"Tests",description:"Vitest + React Testing Library + jsdom",detect:async e=>l(_l.join(e,a.VITEST_CONFIG)),files:[{path:a.VITEST_CONFIG,generated:!0},{path:"test",generated:!0,isDir:!0,containsUserContent:!0,removeHint:"holds setup.ts / test-utils.tsx and any helpers you added \u2014 review before deleting"}],packages:[{name:"vitest",kind:"devDependency"},{name:"jsdom",kind:"devDependency"},{name:"@vitejs/plugin-react",kind:"devDependency"},{name:"@testing-library/dom",kind:"devDependency"},{name:"@testing-library/jest-dom",kind:"devDependency"},{name:"@testing-library/react",kind:"devDependency"},{name:"@testing-library/user-event",kind:"devDependency"}],scripts:[{name:"test",expectedValue:"vitest run"},{name:"test:watch",expectedValue:"vitest"}],injections:[],apply:O(yr,ps)};w();import Ll from"node:path";P();import us from"node:path";import Dl from"picocolors";w();var Fl={npm:"npm run",yarn:"yarn",pnpm:"pnpm",bun:"bun run"},Ol=e=>{let t=Fl[e];return["ci:check","type-check","check:deprecated","test","build"].map(r=>`${t} ${r}`).join(" && ")},Tt=(e,t)=>{let r={...e.scripts??{}},i={...e.devDependencies??{}};return r["env:sync"]||(r["env:sync"]="tsx scripts/sync-env.ts"),r["check:deprecated"]||(r["check:deprecated"]="tsx scripts/check-deprecated.ts"),r["type-check"]||(r["type-check"]="tsc --noEmit"),r.validate||(r.validate=Ol(t)),!i.tsx&&!Object.hasOwn(e.dependencies??{},"tsx")&&(i.tsx="*"),{...e,scripts:r,devDependencies:i}};var ms=`import * as fs from 'node:fs';
|
|
954
962
|
import * as path from 'node:path';
|
|
955
963
|
|
|
956
964
|
const checkOnly = process.argv.includes('--check');
|
|
@@ -1024,7 +1032,7 @@ if (checkOnly) {
|
|
|
1024
1032
|
|
|
1025
1033
|
fs.writeFileSync(examplePath, newExampleContent);
|
|
1026
1034
|
console.log('\u2705 Synchronized .env.example with .env');
|
|
1027
|
-
`,
|
|
1035
|
+
`,ds=`/**
|
|
1028
1036
|
* Walks every identifier in the project and flags any whose resolved TypeScript
|
|
1029
1037
|
* symbol carries a \`@deprecated\` JSDoc tag. Catches deprecated API usage that
|
|
1030
1038
|
* \`tsc --noEmit\` does not surface (deprecations are "suggestion"-level, not
|
|
@@ -1088,120 +1096,120 @@ if (hits === 0) {
|
|
|
1088
1096
|
|
|
1089
1097
|
console.log(\`\\n\${hits} deprecated symbol use(s) found.\`);
|
|
1090
1098
|
process.exit(1);
|
|
1091
|
-
`,
|
|
1099
|
+
`,Ct=[{relative:"scripts/sync-env.ts",content:ms},{relative:"scripts/check-deprecated.ts",content:ds}];var xr=async e=>{let t=S("Adding validation scripts...");try{let r=!1;for(let{relative:o,content:s}of Ct){let c=us.join(e,o);l(c)||(await h(c,s),r=!0)}let i=await A(e),n=!1;await _(us.join(e,a.PACKAGE_JSON),o=>{let s=o.devDependencies?.tsx,c=Tt(o,i);return n=!s&&!!c.devDependencies?.tsx,c}),n&&(t.text="Installing tsx...",await fe(e,i,["tsx"])),t.succeed(Dl.green(r?"Validation scripts added (env:sync, check:deprecated, validate).":"Validation scripts already present \u2014 refreshed package.json."))}catch(r){throw t.fail("Failed to add validation scripts."),r}};P();import fs from"node:path";import jl from"picocolors";w();var gs=async(e,t)=>{let r=S("Repairing validation scripts...");try{let i=[];for(let{relative:p,content:u}of Ct){if(!F(t,p))continue;let d=fs.join(e,p);l(d)||(await h(d,u),i.push(p))}let n=await B(e,t),o=fs.join(e,a.PACKAGE_JSON);if(l(o)){let p=await A(e);await _(o,u=>Tt(u,p))}let s=await Ee(e,t),c=[i.length>0?`rewrote ${i.join(", ")}`:null,n.length>0?`reinstalled ${n.join(", ")}`:null,s.length>0?`reset ${s.join(", ")}`:null].filter(Boolean);r.succeed(jl.green(c.length>0?`Validation scripts repaired (${c.join("; ")}).`:"Validation scripts repaired."))}catch(i){throw r.fail("Failed to repair validation scripts."),i}};var hs=["scripts/sync-env.ts","scripts/check-deprecated.ts"],ys={id:"validate-scripts",name:"Validation Scripts",description:"sync-env, check-deprecated, and the validate chain",detect:async e=>hs.every(t=>l(Ll.join(e,t))),files:hs.map(e=>({path:e,generated:!0})),packages:[{name:"tsx",kind:"devDependency"}],scripts:[{name:"env:sync",expectedValue:"tsx scripts/sync-env.ts"},{name:"check:deprecated",expectedValue:"tsx scripts/check-deprecated.ts"},{name:"type-check",expectedValue:"tsc --noEmit"},{name:"validate"}],injections:[],apply:O(xr,gs)};import{access as Bl,readFile as zl}from"node:fs/promises";import Ts from"node:path";P();import gi from"node:path";import Ml from"picocolors";w();P();import ui from"node:fs/promises";import Rt from"node:path";w();var xs=async(e,t)=>{t.text="Downloading assets from starter repository...",await J(e)},ws=async(e,t,r)=>{let i=Rt.join(e,a.WS_UTILS);await ui.cp(Rt.join(t,a.WS_UTILS),i,{recursive:!0,force:!0});let n=Rt.join(e,a.WS_SLICE_FILE);await b(Rt.join(t,a.WS_SLICE_FILE),n),r.keepTests||await fi(i)},fi=async e=>{let t=async r=>{let i=await ui.readdir(r,{withFileTypes:!0});for(let n of i){let o=Rt.join(r,n.name);if(n.isDirectory()){if(n.name==="__test-utils__"){await v(o);continue}await t(o)}else n.isFile()&&/\.test\.tsx?$/.test(n.name)&&await ui.unlink(o)}};await t(e)};P();w();import Ps from"node:path";var vs=async e=>{let t=Ps.join(e,a.WS_UTILS);return l(t)?{isSetup:!0,reason:"src/lib/utils/ws/ already exists"}:{isSetup:!1}},Ss=async e=>{let t=[],r=[{rel:"src/lib",label:"src/lib"},{rel:"src/store",label:"src/store (Redux Toolkit not installed?)"},{rel:a.ROOT_REDUCER,label:"src/store/rootReducer.ts (Redux not initialised?)"},{rel:a.STORE_PROVIDER,label:"src/providers/StoreProvider.tsx (Redux not initialised?)"}];for(let{rel:i,label:n}of r)l(Ps.join(e,i))||t.push(`- ${n}`);if(t.length>0)throw new Error(`WebSocket setup requires Redux Toolkit. Missing:
|
|
1092
1100
|
${t.join(`
|
|
1093
1101
|
`)}
|
|
1094
1102
|
|
|
1095
|
-
Run \`next-maker setup --redux\` first.`)};var
|
|
1096
|
-
`)},
|
|
1103
|
+
Run \`next-maker setup --redux\` first.`)};var wr=async e=>{let t=S("Setting up WebSocket layer..."),r=gi.join(e,".next-maker-temp-ws");try{let{isSetup:i,reason:n}=await vs(e);if(i){t.fail(`WebSocket layer is already set up (${n}).`);return}await Ss(e),await xs(r,t),t.text="Copying WebSocket files...";let o=l(gi.join(e,a.VITEST_CONFIG));await ws(e,r,{keepTests:o}),t.text="Registering wsReducer...",await Ft(e),t.text="Mounting WS bridge in StoreProvider...",await Dt(e),t.text="Ensuring test/setup.ts mocks...",await jt(e),t.text="Installing socket.io-client...";let s=gi.join(e,a.PACKAGE_JSON),c=JSON.parse(await g(s));({...c.dependencies,...c.devDependencies})["socket.io-client"]||await z(e,"socket.io-client@^4.8.3"),t.text="Formatting code...";let u=await A(e);await K(e,u,"lint:fix"),t.succeed(Ml.green("WebSocket layer setup successfully!"))}catch(i){throw t.fail("Failed to setup WebSocket layer."),i}finally{await v(r)}};P();import Gl from"node:fs/promises";import We from"node:path";import Hl from"picocolors";w();var Ul="socket.io-client@^4.8.3",Es=async(e,t)=>{let r=S("Repairing WebSocket layer..."),i=We.join(e,".next-maker-temp-ws-repair");try{let n=We.join(e,a.WS_UTILS),o=We.join(e,a.WS_SLICE_FILE),s=F(t,a.WS_UTILS)&&!l(n),c=F(t,a.WS_SLICE_FILE)&&!l(o),p=[];if(s||c){r.text="Fetching assets from starter repo...";let f=l(We.join(e,a.VITEST_CONFIG));await te(i,async x=>{s&&(await Gl.cp(We.join(x,a.WS_UTILS),n,{recursive:!0,force:!0}),f||await fi(n),p.push(a.WS_UTILS)),c&&(await b(We.join(x,a.WS_SLICE_FILE),o),p.push(a.WS_SLICE_FILE))})}U(t,a.ROOT_REDUCER)&&(r.text="Re-registering wsReducer...",await Ft(e),p.push("wsReducer registration")),U(t,a.STORE_PROVIDER)&&(r.text="Re-mounting the WS bridge...",await Dt(e),p.push("attachWsBridge mount")),await jt(e);let u=[];qt(t,"dependency").includes("socket.io-client")&&(r.text="Installing socket.io-client...",await z(e,Ul),u.push("socket.io-client"));let d=[p.length>0?`restored ${p.join(", ")}`:null,u.length>0?`reinstalled ${u.join(", ")}`:null].filter(Boolean);r.succeed(Hl.green(d.length>0?`WebSocket layer repaired (${d.join("; ")}).`:"WebSocket layer repaired."))}catch(n){throw r.fail("Failed to repair WebSocket layer."),n}};var Vl=async e=>{try{let t=JSON.parse(await zl(Ts.join(e,"package.json"),"utf-8"));return{...t.dependencies,...t.devDependencies}["socket.io-client"]?(await Bl(Ts.join(e,"src/lib/utils/ws")),!0):!1}catch{return!1}},Cs={id:"ws",name:"WebSocket Client",description:"socket.io-client + lazy WS singleton + Redux slice + hooks",detect:Vl,files:[{path:"src/lib/utils/ws",generated:!0,isDir:!0,containsUserContent:!0,removeHint:"holds the ws client + any feature event maps you added \u2014 review before deleting"},{path:"src/store/slices/ws.slice.ts",generated:!0}],packages:[{name:"socket.io-client",kind:"dependency"}],scripts:[],injections:[{file:"src/store/rootReducer.ts",description:"wsReducer registration in rootReducer",presence:/ws:\s*wsReducer\b/,removePattern:Lt},{file:"src/providers/StoreProvider.tsx",description:"attachWsBridge mount in StoreProvider",presence:/attachWsBridge\(wsClient,\s*store\.dispatch\)/,removePattern:Ot}],apply:O(wr,Es)};P();w();import Oe from"node:path";var Rs=async e=>{let t=Oe.join(e,a.PACKAGE_JSON);return l(t)?JSON.parse(await g(t)):null},Jl=async(e,t)=>{let r=Oe.join(e,a.PACKAGE_JSON);await h(r,`${JSON.stringify(t,null,2)}
|
|
1104
|
+
`)},bs=(e,t)=>(t==="dependency"?e.dependencies:e.devDependencies)??{},Is=e=>[e.file,...e.alternativeFiles??[]],qe=async(e,t)=>{let r=await e.detect(t),i=[];if(!r)return{manifest:e,installed:!1,drift:[]};for(let o of e.files)o.required!==!1&&(l(Oe.join(t,o.path))||i.push({kind:"missingFile",file:o.path}));let n=await Rs(t);if(n){for(let s of e.packages)bs(n,s.kind)[s.name]||i.push({kind:"missingPackage",name:s.name,depKind:s.kind});let o=n.scripts??{};for(let s of e.scripts){let c=o[s.name];c?s.expectedValue&&c!==s.expectedValue&&i.push({kind:"mismatchedScript",name:s.name,expected:s.expectedValue,actual:c}):i.push({kind:"missingScript",name:s.name,expected:s.expectedValue})}}for(let o of e.injections){let c=Is(o).filter(u=>l(Oe.join(t,u)));if(c.length===0){i.push({kind:"missingInjection",file:o.file,description:o.description});continue}let p=!1;for(let u of c){let d=await g(Oe.join(t,u));if(o.presence.test(d)){p=!0;break}}p||i.push({kind:"missingInjection",file:c[0],description:o.description})}return{manifest:e,installed:r,drift:i}},Pr=async(e,t,r={})=>{let i=r.dryRun??!1,n={filesRemoved:[],packagesUninstalled:[],scriptsRemoved:[],blocksStripped:[],manualCleanup:[]};for(let c of e.injections)for(let p of Is(c)){let u=Oe.join(t,p);if(!l(u))continue;if(!c.removePattern){n.manualCleanup.push({file:p,description:c.description});continue}let d=await g(u);if(!c.presence.test(d))continue;let f;if(typeof c.removePattern=="function"){let x=c.removePattern(d);if(x===null){n.manualCleanup.push({file:p,description:c.description});continue}f=x}else f=d.replace(c.removePattern,"");f!==d?(i||await h(u,f),n.blocksStripped.push({file:p,description:c.description})):n.manualCleanup.push({file:p,description:c.description})}let{rm:o}=await import("node:fs/promises");for(let c of e.files){if(!c.generated)continue;let p=Oe.join(t,c.path);if(l(p)){if(c.containsUserContent){let u=c.removeHint?`${c.path} \u2014 ${c.removeHint}`:`${c.path} (may contain user-authored files; review before deleting)`;n.manualCleanup.push({file:c.path,description:u});continue}i||await o(p,{recursive:!0,force:!0}),n.filesRemoved.push(c.path)}}let s=await Rs(t);if(s){let c=!1;if(s.scripts)for(let p of e.scripts)s.scripts[p.name]&&(i||delete s.scripts[p.name],n.scriptsRemoved.push(p.name),c=!0);for(let p of e.packages)bs(s,p.kind)[p.name]&&n.packagesUninstalled.push(p.name);c&&!i&&await Jl(t,s)}if(!i&&n.packagesUninstalled.length>0){let c=await A(t);await kr(t,c,n.packagesUninstalled)}return n};var De=[cs,ys,Po,qo,yo,ls,ko,jo,ns,Cs,Vo],$s=e=>De.find(t=>t.id===e);var ks=e=>{switch(e.kind){case"missingFile":return`missing file: ${e.file}`;case"missingPackage":return`missing ${e.depKind==="dependency"?"dep":"devDep"}: ${e.name}`;case"missingScript":return`missing script: ${e.name}`;case"mismatchedScript":return`script "${e.name}" expected ${$.dim(e.expected)} but got ${$.dim(e.actual)}`;case"missingInjection":return`missing block in ${e.file}: ${e.description}`}},Wl=e=>{let t=e.filter(i=>i.installed),r=t.filter(i=>i.drift.length>0);return{installedCount:t.length,driftedCount:r.length,cleanCount:t.length-r.length,driftedResults:r}},ql={fixed:$.green("\u2713"),stillDrifted:$.red("\u2717"),noApply:$.yellow("\u26A0\uFE0F")},Xl={fixed:$.green("FIXED"),stillDrifted:$.red("STILL DRIFTED"),noApply:$.yellow("NO AUTOMATIC FIX AVAILABLE")},Yl=async(e,t)=>{let r=[];for(let i of e){let{manifest:n,drift:o}=i;if(!n.apply){r.push({id:n.id,name:n.name,status:"noApply",remaining:o});continue}let s;try{await n.apply(t,o)}catch(p){s=p instanceof Error?p.message:String(p)}let c=await qe(n,t);r.push({id:n.id,name:n.name,status:c.drift.length===0&&!s?"fixed":"stillDrifted",remaining:c.drift,error:s})}return r},Ns=e=>{e.command("doctor").description("Diagnose drift between the project and known feature manifests").option("--fix","Re-apply manifests that report drift (idempotent)").option("--feature <id>","Only check this manifest id (e.g. redux, security-headers)").option("--json","Print machine-readable JSON instead of the human report").action(async t=>{try{let r=process.cwd(),i=t.feature?De.filter(u=>u.id===t.feature):De;if(t.feature&&i.length===0)throw new Error(`Unknown feature "${t.feature}". Valid: ${De.map(u=>u.id).join(", ")}.`);let n=[];for(let u of i)n.push(await qe(u,r));t.json&&(m(JSON.stringify(n.map(u=>({id:u.manifest.id,name:u.manifest.name,installed:u.installed,drift:u.drift})),null,2)),process.exit(n.some(u=>u.drift.length>0)?1:0)),m($.cyan(`
|
|
1097
1105
|
\u{1FA7A} Project Doctor
|
|
1098
|
-
`));for(let u of n){let{manifest:d,installed:f,drift:
|
|
1106
|
+
`));for(let u of n){let{manifest:d,installed:f,drift:x}=u;if(!f){m(` ${$.dim("\u2014")} ${$.dim(d.name)} ${$.dim("(not installed)")}`);continue}if(x.length===0){m(` ${$.green("\u2713")} ${d.name}`);continue}m(` ${$.yellow("!")} ${$.bold(d.name)} ${$.dim(`(${x.length} issue${x.length===1?"":"s"})`)}`);for(let I of x)m(` ${$.yellow("\u2022")} ${ks(I)}`)}let o=Wl(n);m(""),m($.dim(`${o.cleanCount} clean, ${o.driftedCount} drifted, ${n.length-o.installedCount} not installed`)),o.driftedCount===0&&(m($.green(`
|
|
1099
1107
|
\u2713 No drift detected.
|
|
1100
1108
|
`)),process.exit(0)),t.fix||(m($.dim(`
|
|
1101
1109
|
Run with --fix to re-apply drifted features.
|
|
1102
1110
|
`)),process.exit(1)),m($.cyan(`
|
|
1103
1111
|
\u{1F527} Applying fixes...
|
|
1104
|
-
`));let s=await Yl(o.driftedResults,r);m("");for(let u of s){m(` ${ql[u.status]} ${u.name} ${Xl[u.status]}`);for(let d of u.remaining)m(` ${$.yellow("\u2022")} ${
|
|
1112
|
+
`));let s=await Yl(o.driftedResults,r);m("");for(let u of s){m(` ${ql[u.status]} ${u.name} ${Xl[u.status]}`);for(let d of u.remaining)m(` ${$.yellow("\u2022")} ${ks(d)}`);u.error&&m(` ${$.red("\u2022")} ${u.error}`)}let c=s.filter(u=>u.status==="fixed").length,p=s.length-c;m(""),m($.dim(`${c} fixed, ${p} still drifted`)),p>0&&(m($.yellow(`
|
|
1105
1113
|
! Doctor could not fix everything.
|
|
1106
1114
|
`)),process.exit(1)),m($.green(`
|
|
1107
1115
|
\u2713 All drift fixed.
|
|
1108
|
-
`)),process.exit(0)}catch(r){E(`${r instanceof Error?r.message:r}`),process.exit(1)}})};import
|
|
1109
|
-
.describe('${o}')`}return` ${t}: ${r},`},
|
|
1116
|
+
`)),process.exit(0)}catch(r){E(`${r instanceof Error?r.message:r}`),process.exit(1)}})};import Xe from"picocolors";P();w();import hi from"node:path";var Kl=/^[A-Z][A-Z0-9_]*$/,Fs=e=>{if(!Kl.test(e))throw new Error(`Invalid env var name "${e}". Use UPPER_SNAKE_CASE (e.g. SENTRY_DSN, NEXT_PUBLIC_API_URL).`)},ye=(e,t)=>t?e.startsWith("NEXT_PUBLIC_")?e:`NEXT_PUBLIC_${e}`:e,yi=e=>e.public?"client":"server",Zl=e=>{if(e.default===void 0)return"";switch(e.type){case"number":return`.default(${Number(e.default)})`;case"boolean":return`.default(${e.default==="true"})`;default:return`.default('${e.default.replace(/'/g,"\\'")}')`}},Ql=e=>{switch(e.type){case"url":return"e.url()";case"number":return"e.number()";case"boolean":return"e.boolean()";case"enum":{let t=e.enumValues??[];if(t.length===0)throw new Error(`Enum env var "${e.name}" requires --enum values.`);return`e.enum([${t.map(i=>`'${i.replace(/'/g,"\\'")}'`).join(", ")}])`}default:return"e.string()"}},Os=e=>{let t=ye(e.name,e.public),r=Ql(e),i=e.default!==void 0,n=!e.required&&!i;if(i&&(r+=Zl(e)),n&&(r+=".optional()"),e.description){let o=e.description.replace(/'/g,"\\'");r+=`
|
|
1117
|
+
.describe('${o}')`}return` ${t}: ${r},`},Ds=e=>{let t=ye(e.name,e.public);return` ${t}: process.env.${t},`},em=e=>new RegExp(`(${e}:\\s*\\{)([\\s\\S]*?)(\\n\\s*\\})`),As=/(runtimeEnv:\s*\{)([\s\S]*?)(\n\s*\})/,_s=(e,t,r,i)=>{let n=t.replace(/\s+$/,""),o=n.length===0||/,\s*$/.test(n)?n:`${n},`;return`${e}${o}
|
|
1110
1118
|
${i}
|
|
1111
|
-
${r.replace(/^\n/,"")}`},
|
|
1119
|
+
${r.replace(/^\n/,"")}`},js=(e,t)=>{let r=ye(t.name,t.public),i=yi(t);if(new RegExp(`\\b${r}\\s*:`).test(e))return e;if(!/defineEnv\(\{/.test(e))throw new Error("Could not locate `defineEnv({ \u2026 })` in src/lib/env/index.ts. Is this a @teispace/env project?");let o=em(i),s=e.match(o);if(!s)throw new Error(`Could not locate the \`${i}: { \u2026 }\` group in src/lib/env/index.ts.`);let[,c,p,u]=s,d=Os(t),f=e.replace(o,_s(c,p,u,d)),x=f.match(As);if(!x)throw new Error("Could not locate the `runtimeEnv: { \u2026 }` map in src/lib/env/index.ts.");let[,I,H,k]=x;return f=f.replace(As,_s(I,H,k,Ds(t))),f},tm="# -public",rm=e=>{let t=ye(e.name,e.public),r=e.default??"",i=e.public?` ${tm}`:"";return`${t}=${r}${i}`},Ls=(e,t)=>{let r=ye(t.name,t.public);if(new RegExp(`^${r}=`,"m").test(e))return e;let n=e===""||e.endsWith(`
|
|
1112
1120
|
`)?"":`
|
|
1113
1121
|
`,o=e===""?"":`
|
|
1114
1122
|
`,s=t.description?`# ${t.description}
|
|
1115
1123
|
`:"";return`${e}${n}${o}${s}${rm(t)}
|
|
1116
|
-
`},
|
|
1124
|
+
`},Ms=(e,t)=>{let r=ye(t.name,t.public);if(new RegExp(`^${r}=`,"m").test(e))return e;let n=e===""||e.endsWith(`
|
|
1117
1125
|
`)?"":`
|
|
1118
1126
|
`,o=t.default??"";return`${e}${n}${r}=${o}
|
|
1119
|
-
`},
|
|
1127
|
+
`},xi=async(e,t)=>{Fs(t.name);let r=hi.join(e,"src/lib/env/index.ts");if(!l(r))throw new Error("src/lib/env/index.ts not found \u2014 run `next-maker init` first.");let i=await g(r),n=js(i,t),o=n!==i;o&&await h(r,n);let s=hi.join(e,a.ENV_EXAMPLE),c=!1;if(l(s)){let d=await g(s),f=Ls(d,t);c=f!==d,c&&await h(s,f)}let p=hi.join(e,".env"),u=!1;if(l(p)){let d=await g(p),f=Ms(d,t);u=f!==d,u&&await h(p,f)}return{schemaUpdated:o,envExampleUpdated:c,envUpdated:u,group:yi(t)}};var Gs=new Set(["string","url","number","boolean","enum"]),im=e=>{let t=(e??"string").toLowerCase();if(!Gs.has(t))throw new Error(`Invalid --type "${e}". Valid: ${Array.from(Gs).join(", ")}.`);return t},nm=e=>{if(!e)return;let t=e.split(",").map(r=>r.trim()).filter(Boolean);return t.length===0?void 0:t},Hs=e=>{e.command("env <NAME>").description("Declare a new environment variable across src/lib/env/index.ts, .env.example, and .env").option("--type <type>","Coercer type (string|url|number|boolean|enum)","string").option("--required","Make the variable required (no .optional() / .default())").option("--default <value>","Set a default value (mutually exclusive with --required)").option("--public","Mark as public: place in the client group, auto-prefix NEXT_PUBLIC_, tag .env.example").option("--describe <text>","Description (rendered as .describe() and .env.example comment)").option("--enum <list>",'Comma-separated values when --type=enum (e.g. "dev,prod")').action(async(t,r)=>{try{let i=process.cwd();if(m(Xe.cyan(`
|
|
1120
1128
|
\u{1F510} Env Var Generator
|
|
1121
|
-
`)),r.required&&r.default!==void 0)throw new Error("--required and --default are mutually exclusive.");let n=im(r.type),o=nm(r.enum);if(n==="enum"&&(!o||o.length===0))throw new Error("--type=enum requires at least one value via --enum a,b,c.");let s={name:t,type:n,required:!!r.required,default:r.default,description:r.describe,enumValues:o,public:!!r.public};
|
|
1129
|
+
`)),r.required&&r.default!==void 0)throw new Error("--required and --default are mutually exclusive.");let n=im(r.type),o=nm(r.enum);if(n==="enum"&&(!o||o.length===0))throw new Error("--type=enum requires at least one value via --enum a,b,c.");let s={name:t,type:n,required:!!r.required,default:r.default,description:r.describe,enumValues:o,public:!!r.public};y.start("Updating src/lib/env/index.ts, .env.example, and .env...");let c=await xi(i,s);y.succeed("Env var written");let p=ye(s.name,s.public);m(Xe.green(`
|
|
1122
1130
|
\u2728 ${p} declared in the ${c.group} group.
|
|
1123
|
-
`)),m(
|
|
1124
|
-
`};var
|
|
1131
|
+
`)),m(Xe.dim("Touched:")),m(Xe.dim(` ${c.schemaUpdated?"\u270F\uFE0F ":"\u23ED "} src/lib/env/index.ts`)),m(Xe.dim(` ${c.envExampleUpdated?"\u270F\uFE0F ":"\u23ED "} .env.example`)),m(Xe.dim(` ${c.envUpdated?"\u270F\uFE0F ":"\u23ED "} .env`)),m("")}catch(i){y.fail("Env var declaration failed"),E(`${i instanceof Error?i.message:i}`),process.exit(1)}})};import Er from"node:path";import Le from"picocolors";import om from"enquirer";var{prompt:sm}=om,Us=async(e={})=>e.source?{source:e.source}:{source:(await sm({type:"input",name:"source",message:"Path to source image (PNG/JPG/JPEG/SVG/WebP/AVIF):",validate:r=>r?!0:"Source path is required"})).source};import{access as am,readFile as cm,stat as pm}from"node:fs/promises";import je from"node:path";var Bs=async e=>{try{return await am(e),!0}catch{return!1}},lm=async e=>{try{return(await pm(e)).isDirectory()}catch{return!1}},vr=async e=>{let t=[je.join(e,"src","app"),je.join(e,"app")];for(let r of t)if(await lm(r))return r;return null},mm=["next-pwa","@ducanh2912/next-pwa","@serwist/next","serwist"],wi=async e=>{let t={isPwa:!1},r=[je.join(e,"public","manifest.json"),je.join(e,"public","manifest.webmanifest"),je.join(e,"public","site.webmanifest")];for(let n of r)if(await Bs(n)){t.publicManifestPath=n,t.isPwa=!0;break}let i=await vr(e);if(i)for(let n of["ts","tsx","js"]){let o=je.join(i,`manifest.${n}`);if(await Bs(o)){t.appManifestPath=o,t.isPwa=!0;break}}try{let n=JSON.parse(await cm(je.join(e,"package.json"),"utf-8")),o={...n.dependencies,...n.devDependencies};for(let s of mm)if(o[s]){t.framework=s,t.isPwa=!0;break}}catch{}return t};import{mkdir as hm,readFile as Qs,stat as ym,writeFile as xm}from"node:fs/promises";import me from"node:path";import wm from"sharp";import um from"png-to-ico";import bt from"sharp";var zs=e=>e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),Pi=(e,t,r)=>{switch(e){case"square":return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${t}"><rect width="${t}" height="${t}" fill="white"/></svg>`;case"circle":{let i=t/2;return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${t}"><circle cx="${i}" cy="${i}" r="${i}" fill="white"/></svg>`}case"rounded":{let i=Math.round(t*r/100);return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${t}"><rect width="${t}" height="${t}" rx="${i}" ry="${i}" fill="white"/></svg>`}case"squircle":return dm(t)}},dm=e=>{let t=e,r=t*.225,i=[`M 0 ${r}`,`C 0 0 0 0 ${r} 0`,`L ${t-r} 0`,`C ${t} 0 ${t} 0 ${t} ${r}`,`L ${t} ${t-r}`,`C ${t} ${t} ${t} ${t} ${t-r} ${t}`,`L ${r} ${t}`,`C 0 ${t} 0 ${t} 0 ${t-r}`,"Z"].join(" ");return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${t}"><path d="${zs(i)}" fill="white"/></svg>`},Vs=(e,t)=>`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${e}"><rect width="${e}" height="${e}" fill="${zs(t)}"/></svg>`;var Ye=async e=>{let{size:t,paddingPercent:r,bg:i,fit:n,shape:o,radiusPercent:s,quality:c,forceSquare:p,sourceBuffer:u}=e,d=Math.max(1,Math.round(t*(1-r*2/100))),f=n==="cover"?"cover":"contain",x=await bt(u,{density:384}).resize(d,d,{fit:f,background:{r:0,g:0,b:0,alpha:0}}).png().toBuffer(),I=Math.round((t-d)/2),H=i==="transparent"?{r:0,g:0,b:0,alpha:0}:await vi(i),k=await bt({create:{width:t,height:t,channels:4,background:H}}).composite([{input:x,left:I,top:I}]).png().toBuffer();if(!p&&(o!=="square"||n==="clip")){let kt=o==="square"?"rounded":o,ka=Buffer.from(Pi(kt,t,s));k=await bt(k).composite([{input:ka,blend:"dest-in"}]).png({compressionLevel:Js(c)}).toBuffer()}else k=await bt(k).png({compressionLevel:Js(c)}).toBuffer();return k},vi=async e=>{let t=await bt(Buffer.from(Vs(1,e))).raw().toBuffer({resolveWithObject:!0}),[r,i,n,o=255]=t.data;return{r,g:i,b:n,alpha:o/255}},Js=e=>{let t=Math.round((100-e)/100*9);return Math.max(0,Math.min(9,t))},Ws=async e=>{if(e.length===0)throw new Error("No frames provided to encodeIco");return um(e)};import{readFile as fm,writeFile as VT}from"node:fs/promises";var qs=e=>e.map(({src:t,size:r})=>({src:t,sizes:`${r}x${r}`,type:"image/png",purpose:"any maskable"})),Xs=async(e,t)=>{let r=await fm(e,"utf-8"),i=JSON.parse(r),n=Array.isArray(i.icons)?i.icons:[],o=new Map;for(let s of[...n,...t])s&&typeof s.src=="string"&&o.set(s.src,s);return i.icons=[...o.values()],`${JSON.stringify(i,null,2)}
|
|
1132
|
+
`};var Ys=e=>`icons: [
|
|
1125
1133
|
${e.map(r=>` { src: '${r.src}', sizes: '${r.sizes}', type: '${r.type}'${r.purpose?`, purpose: '${r.purpose}'`:""} }`).join(`,
|
|
1126
1134
|
`)},
|
|
1127
|
-
],`,
|
|
1128
|
-
`;import{stat as gm}from"node:fs/promises";import
|
|
1135
|
+
],`,Ks=(e,t,r)=>`${JSON.stringify({name:e,short_name:e,start_url:"/",display:"standalone",background_color:"#ffffff",theme_color:t,icons:r},null,2)}
|
|
1136
|
+
`;import{stat as gm}from"node:fs/promises";import Si from"node:path";var Zs=[".png",".jpg",".jpeg",".webp",".svg",".avif"],Sr=async e=>{if(!e)throw new Error("Source image path is required (use --path).");let t=Si.isAbsolute(e)?e:Si.resolve(process.cwd(),e),r;try{r=await gm(t)}catch{throw new Error(`Source image not found: ${t}`)}if(!r.isFile())throw new Error(`Source is not a file: ${t}`);let i=Si.extname(t).toLowerCase();if(!Zs.includes(i))throw new Error(`Unsupported source format '${i}'. Use one of: ${Zs.join(", ")}`);return{absolutePath:t,ext:i,bytes:r.size,isVector:i===".svg"}};var Ei=(e,t)=>{if(!e)return t;let r=e.split(",").map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0&&i<=1024);if(r.length===0)throw new Error(`Invalid --sizes value: '${e}'. Provide comma-separated positive integers.`);return r};var Pm=async e=>{try{return await ym(e),!0}catch{return!1}},vm=async(e,t,r)=>{let i=[];for(let n of e){if(await Pm(n.outPath)&&!t&&!n.alwaysWrite){i.push({path:n.outPath,bytes:n.bytes.length,skipped:!0});continue}r||(await hm(me.dirname(n.outPath),{recursive:!0}),await xm(n.outPath,n.bytes)),i.push({path:n.outPath,bytes:n.bytes.length})}return i},Ti=async(e,t)=>{let r=await Sr(t.source),i=await Qs(r.absolutePath),n=t.ogSource?await Qs((await Sr(t.ogSource)).absolutePath):i,o=[],s=[];for(let d of t.icoSizes)s.push(await Ye({sourceBuffer:i,size:d,shape:"square",radiusPercent:t.radius,bg:t.bg,paddingPercent:t.padding,fit:t.fit,quality:t.quality,forceSquare:!0}));let c=await Ws(s);if(o.push({outPath:me.join(t.outDir,"favicon.ico"),bytes:c}),t.emitIcon){let d=await Ye({sourceBuffer:i,size:512,shape:t.shape,radiusPercent:t.radius,bg:t.bg,paddingPercent:t.padding,fit:t.fit,quality:t.quality});o.push({outPath:me.join(t.outDir,"icon.png"),bytes:d})}if(t.emitApple){let d=t.bg==="transparent"?"#ffffff":t.bg,f=await Ye({sourceBuffer:i,size:180,shape:t.shape,radiusPercent:t.radius,bg:d,paddingPercent:t.padding,fit:t.fit,quality:t.quality});o.push({outPath:me.join(t.outDir,"apple-icon.png"),bytes:f})}if(t.emitOg){let d=await ea(n,t,!1);o.push({outPath:me.join(t.outDir,"opengraph-image.png"),bytes:d})}if(t.emitTwitter){let d=await ea(n,t,!0);o.push({outPath:me.join(t.outDir,"twitter-image.png"),bytes:d})}let p;if(t.pwa||t.pwaInit){let d=await wi(e);if(t.pwa&&!d.isPwa)throw new Error("No PWA setup detected. Use --pwa-init to bootstrap a manifest, or set up next-pwa/serwist first.");let f=me.join(e,"public"),x=[192,512],I=[];for(let k of x){let Z=await Ye({sourceBuffer:i,size:k,shape:t.shape,radiusPercent:t.radius,bg:t.bg,paddingPercent:t.padding,fit:t.fit,quality:t.quality}),kt=`icon-${k}.png`;o.push({outPath:me.join(f,kt),bytes:Z}),I.push({src:`/${kt}`,size:k})}let H=qs(I);if(d.publicManifestPath){let k=await Xs(d.publicManifestPath,H);o.push({outPath:d.publicManifestPath,bytes:Buffer.from(k,"utf-8"),alwaysWrite:!0})}else if(d.appManifestPath)p=Ys(H);else if(t.pwaInit){let k=me.join(f,"manifest.webmanifest"),Z=Ks(me.basename(e)||"App","#000000",H);o.push({outPath:k,bytes:Buffer.from(Z,"utf-8")})}}return{outputs:await vm(o,t.force,t.dryRun),pwaSnippet:p}},ea=async(e,t,r)=>{let n=r?600:630,o=Math.round(Math.min(1200,n)*(1-t.padding*2/100)),s=await Ye({sourceBuffer:e,size:o,shape:t.shape,radiusPercent:t.radius,bg:"transparent",paddingPercent:0,fit:t.fit,quality:t.quality}),c=t.bg==="transparent"?"#ffffff":t.bg,p=await vi(c),u=Math.round((1200-o)/2),d=Math.round((n-o)/2);return wm({create:{width:1200,height:n,channels:4,background:p}}).composite([{input:s,left:u,top:d}]).png().toBuffer()};var ta=new Set(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"]);var Sm=["square","rounded","circle","squircle"],Em=["contain","cover","clip"],ra=(e,t,r,i)=>{if(!e)return r;if(!t.includes(e))throw new Error(`Invalid value for --${i}: '${e}'. Allowed: ${t.join(", ")}`);return e},Ci=(e,t,r,i,n)=>{if(e===void 0)return t;let o=Number(e);if(!Number.isFinite(o)||o<i||o>n)throw new Error(`Invalid value for --${r}: '${e}'. Must be a number between ${i}\u2013${n}.`);return o},na=e=>{e.command("favicon").description("Generate favicon.ico (and optionally icons, OG image, PWA manifest icons)").option("--path <file>","Path to source image (PNG, JPG, JPEG, WebP, SVG, AVIF)").option("--out <dir>","Output dir (default: src/app or app)").option("--force","Overwrite existing files without prompt",!1).option("--dry-run","Show what would be written without writing",!1).option("--icon","Also emit icon.png (512\xD7512)",!1).option("--apple","Also emit apple-icon.png (180\xD7180)",!1).option("--og","Also emit opengraph-image.png (1200\xD7630)",!1).option("--og-source <file>","Use a separate image for the OG/Twitter card").option("--twitter","Also emit twitter-image.png (1200\xD7600)",!1).option("--all","Shorthand for --icon --apple --og",!1).option("--pwa","Detect PWA setup and emit manifest icons (192/512); errors if not detected",!1).option("--pwa-init","Bootstrap public/manifest.webmanifest with icons",!1).option("--shape <shape>","square | rounded | circle | squircle","square").option("--radius <percent>","Corner radius % when shape=rounded (0-50)","20").option("--bg <color>",'Background color (hex, css name, or "transparent")',"transparent").option("--padding <percent>","Padding around source content (0-30)","0").option("--fit <fit>","How source fits target: contain | cover | clip","contain").option("--sizes <list>","Comma-separated ICO sizes (default: 16,32,48)").option("--quality <n>","PNG compression 1-100 (higher = smaller file; PNG is lossless, default: 90)","90").action(async t=>{try{let r=process.cwd();m(Le.cyan(`
|
|
1129
1137
|
\u{1F3A8} Favicon Generator
|
|
1130
|
-
`));let i=await
|
|
1138
|
+
`));let i=await Us({source:t.path}),n=await Tm(r,t.out),o=ra(t.shape,Sm,"square","shape"),s=ra(t.fit,Em,"contain","fit"),c=Ci(t.radius,20,"radius",0,50),p=Ci(t.padding,0,"padding",0,30),u=Ci(t.quality,90,"quality",1,100),d=Ei(t.sizes,[16,32,48]),f=t.bg??"transparent";bm(f);let x=t.all===!0,I={source:i.source,outDir:n,force:!!t.force,dryRun:!!t.dryRun,emitIcon:!!t.icon||x,emitApple:!!t.apple||x,emitOg:!!t.og||x,emitTwitter:!!t.twitter,ogSource:t.ogSource,pwa:!!t.pwa,pwaInit:!!t.pwaInit,shape:o,radius:c,bg:f,padding:p,fit:s,icoSizes:d,quality:u};y.start("Generating favicon assets...");let H=await Ti(r,I);y.succeed(I.dryRun?"Favicon plan ready":"Favicon assets generated"),m("");for(let k of H.outputs){let Z=Er.relative(r,k.path);k.skipped?m(Le.yellow(` \u21B7 skipped ${Z} (exists; use --force to overwrite)`)):I.dryRun?m(Le.dim(` \u{1F4C4} would write ${Z} (${ia(k.bytes)})`)):m(Le.green(` \u2713 ${Z} `)+Le.dim(`(${ia(k.bytes)})`))}H.pwaSnippet&&(m(""),m(Le.cyan("Add this to your typed manifest (src/app/manifest.ts):")),m(Le.dim(H.pwaSnippet))),m("")}catch(r){y.fail("Favicon generation failed");let i=r instanceof Error?r.message:String(r);E(i),process.exit(1)}})},Tm=async(e,t)=>{if(t)return Er.isAbsolute(t)?t:Er.resolve(e,t);let r=await vr(e);return r||(Gi("Could not detect app/ or src/app/ \u2014 falling back to src/app"),Er.join(e,"src","app"))},Cm=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,Rm=/^(?:rgb|rgba|hsl|hsla)\(\s*[\d.,%\s/]+\)$/i,bm=e=>{if(e!=="transparent"&&!Cm.test(e)&&!Rm.test(e)&&!ta.has(e.toLowerCase()))throw new Error(`Invalid value for --bg: '${e}'. Use 'transparent', a hex code (e.g. #0f172a), a CSS color name, or rgb()/rgba()/hsl()/hsla().`)},ia=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(2)} MB`;import pa from"node:path";import V from"picocolors";q();q();import Hm from"node:path";import{readFile as Im,writeFile as $m}from"node:fs/promises";import km from"node:path";var It=async e=>{let{serviceName:t,projectPath:r}=e,i=G(t),n=km.join(r,"src","lib","config","app-apis.ts");try{let o=await Im(n,"utf-8");if(o.includes(`${i}:`))return;if(!o.match(/export const AppApis = \{[\s\S]*?\} as const;/))throw new Error("Could not find AppApis object in app-apis.ts");let s=` ${i}: {
|
|
1131
1139
|
base: '/${t}',
|
|
1132
1140
|
getAll: '/${t}',
|
|
1133
|
-
},`;o=
|
|
1134
|
-
`;n=n.slice(0,s)+c+n.slice(s),await Am(i,n)};P();w();import
|
|
1141
|
+
},`;o=ot(o,s),await $m(n,o)}catch(o){throw new Error(`Failed to register API endpoints: ${o}`,{cause:o})}};import{readFile as Nm,writeFile as Am}from"node:fs/promises";import _m from"node:path";w();var Ri=async(e,t,r)=>{let i=_m.join(e,"src","lib","config","app-paths.ts");if(!l(i))return;let n=await Nm(i,"utf-8"),o=G(t);if(n.includes(`${o}:`))return;let s=n.lastIndexOf("} as const;");if(s===-1)return;let c=` ${o}: '${r}',
|
|
1142
|
+
`;n=n.slice(0,s)+c+n.slice(s),await Am(i,n)};P();w();import Tr from"node:path";var Fm=e=>new RegExp(`<\\s*${e}\\b`),oa=(e,t)=>{if(Fm(t).test(e))return e;let r=/^(?<indent>[ \t]*)\{children\}\s*$/m,i=e.match(r);if(!i||i.index===void 0)throw new Error("Could not locate `{children}` line in RootProvider \u2014 expected a line containing only `{children}`.");let n=i.groups?.indent??"",o=`${n} `,s=`${n}<${t}>
|
|
1135
1143
|
${o}{children}
|
|
1136
|
-
${n}</${t}>`;return e.replace(r,s)},
|
|
1144
|
+
${n}</${t}>`;return e.replace(r,s)},sa=(e,t)=>{let r=`export * from './${t}';`;if(e.includes(r))return e;let i=e.split(`
|
|
1137
1145
|
`),n=[],o=[];for(let f of i)/^export \* from '\.\/.*';\s*$/.test(f)?n.push(f):o.push(f);let s=[...n,r].sort(),c=i.findIndex(f=>/^export \* from '\.\//.test(f));if(c===-1)return`${r}
|
|
1138
|
-
${e.replace(/^\n+/,"")}`;let p=i.slice(0,c),u=i.findIndex((f,
|
|
1139
|
-
`)},Om=a.PROVIDERS,
|
|
1140
|
-
`))};var
|
|
1146
|
+
${e.replace(/^\n+/,"")}`;let p=i.slice(0,c),u=i.findIndex((f,x)=>x>c&&!/^export \* from '\.\//.test(f)),d=u===-1?[]:i.slice(u);return[...p,...s,...d].join(`
|
|
1147
|
+
`)},Om=a.PROVIDERS,Dm=a.ROOT_PROVIDER,jm=a.PROVIDERS_INDEX,aa=async(e,t={fileExists:l,readFile:g})=>{let r=Tr.join(e,Dm);if(t.fileExists(r))return r;let i=Tr.join(e,Om);if(!t.fileExists(i))return null;let{readdir:n}=await import("node:fs/promises"),s=(await n(i).catch(()=>[])).filter(p=>p.endsWith(".tsx")),c=null;for(let p of s){let u=Tr.join(i,p),d=await t.readFile(u);if(!/\{children\}/.test(d))continue;let x=((d.split("{children}")[0]??"").match(/<[A-Z][A-Za-z0-9_]*\b/g)??[]).length;(!c||x>c.depth)&&(c={file:u,depth:x})}return c?.file??null},bi=async e=>{let{projectPath:t,componentName:r,fileBaseName:i}=e,n=await aa(t);if(n){let c=await g(n),p=c;(!/from '\.\//.test(c)||!c.includes(`{ ${r} }`))&&(p=nt(p,`import { ${r} } from './${i}';`)),p=oa(p,r),p!==c&&await h(n,p)}let o=Tr.join(t,jm),s=null;if(l(o)){let c=await g(o),p=sa(c,i);p!==c&&await h(o,p),s=o}return{rootProviderFile:n,barrelFile:s}};w();import{readFile as Lm,writeFile as Mm}from"node:fs/promises";import Gm from"node:path";var Ii=async(e,t)=>{let r=Gm.join(e,"src","i18n","translations","en.json");if(!l(r))return;let i=await Lm(r,"utf-8"),n=JSON.parse(i);n[t]||(n[t]={title:t,description:`${t} page description`},await Mm(r,`${JSON.stringify(n,null,2)}
|
|
1148
|
+
`))};var $i=()=>[{name:"Project setup detected",spinnerText:"Detecting project setup...",execute:async e=>{e.detection=await M(e.projectPath)}},{name:"Feature files generated",spinnerText:"Generating feature files...",execute:async e=>{await qr({name:e.featureName,outputPath:e.featurePath,createStore:e.createStore,persistStore:e.persistStore,createService:e.createService,httpClient:e.httpClient})}},{name:"API endpoints registered",spinnerText:"Registering API endpoints...",shouldSkip:e=>!e.createService,execute:async e=>{await It({serviceName:e.featureName,projectPath:e.projectPath})}},{name:"Feature registered in rootReducer",spinnerText:"Registering feature in rootReducer...",shouldSkip:e=>!e.createStore||!e.detection.hasRedux,execute:async e=>{await ke({projectPath:e.projectPath,name:e.featureName,persist:e.persistStore,importPath:Hm.join(e.basePath,e.featureName,"store")})}}];var Me=async(e,t)=>{for(let r of e)if(!r.shouldSkip?.(t)){t.spinner.start(r.spinnerText);try{await r.execute(t),t.spinner.succeed(r.name)}catch(i){throw t.spinner.fail(r.name),i}}};var ki=()=>[{name:"Service files generated",spinnerText:"Generating service files...",execute:async e=>{await pt({name:e.serviceName,outputPath:e.servicePath,httpClient:e.httpClient})}},{name:"API endpoints registered",spinnerText:"Registering API endpoints...",execute:async e=>{await It({serviceName:e.serviceName,projectPath:e.projectPath})}}];import Um from"node:path";var Ni=()=>[{name:"Slice files generated",spinnerText:"Generating slice files...",execute:async e=>{await dt({name:e.sliceName,outputPath:e.slicePath,persist:e.persistSlice})}},{name:"Slice registered in rootReducer",spinnerText:"Registering slice in rootReducer...",execute:async e=>{await ke({projectPath:e.projectPath,name:e.sliceName,persist:e.persistSlice,importPath:Um.join(e.basePath,e.sliceName)})}}];import Bm from"enquirer";var{prompt:zm}=Bm,ca=async(e,t,r,i,n,o,s)=>{let c=[];e||c.push({type:"input",name:"featureName",message:"What is the feature name?",initial:"my-feature",validate:u=>/^[a-z0-9-]+$/.test(u)?!0:"Feature name must be lowercase and contain only alphanumeric characters and hyphens."}),t&&i===void 0&&n===void 0&&(c.push({type:"confirm",name:"createStore",message:"Generate Redux store for this feature?",initial:!0}),c.push({type:"confirm",name:"persistStore",message:"Enable persistence for this store?",initial:!1,skip(){return!this.state.answers.createStore}})),r&&r!=="none"&&o===void 0&&s===void 0&&(c.push({type:"confirm",name:"createService",message:"Generate API service for this feature?",initial:!0}),r==="both"&&c.push({type:"select",name:"selectedHttpClient",message:"Which HTTP client to use for the service?",choices:["fetch","axios"],initial:0,skip(){return!this.state.answers.createService}}));let p=c.length>0?await zm(c):{};return{featureName:e||p.featureName,hasRedux:t||!1,createStore:i===!0?!1:n!==void 0?!0:p.createStore||!1,persistStore:n==="persist"?!0:n==="no-persist"?!1:p.persistStore||!1,httpClient:r||"none",createService:o===!0?!1:s!==void 0?!0:p.createService||!1,selectedHttpClient:s||p.selectedHttpClient||(r==="both"?"fetch":r!=="none"?r:void 0)}};var la=e=>{e.command("feature [name]").description("Generate a new feature module").option("--skip-store","Skip Redux store generation").option("--store <type>","Generate Redux store with persistence option (persist|no-persist)").option("--skip-service","Skip API service generation").option("--service <client>","Generate API service with specific HTTP client (axios|fetch)").option("--path <path>","Custom path for feature generation (default: src/features)").action(async(t,r)=>{try{let i=process.cwd();Vm(r),m(V.cyan(`
|
|
1141
1149
|
\u{1F3AF} Feature Generator
|
|
1142
|
-
`));let n
|
|
1143
|
-
`));let c=await
|
|
1150
|
+
`));let n=$i();y.start("Detecting project setup...");let{detectProjectSetup:o}=await Promise.resolve().then(()=>(q(),ct)),s=await o(i);y.succeed("Project setup detected"),m(V.dim(` Redux: ${s.hasRedux?"\u2713":"\u2717"}`)),m(V.dim(` HTTP Client: ${s.httpClient}`)),m(V.dim(` i18n: ${s.hasI18n?"\u2713":"\u2717"}
|
|
1151
|
+
`));let c=await ca(t,s.hasRedux,s.httpClient,r.skipStore,r.store,r.skipService,r.service);W(c.featureName,"feature name"),r.path&&pe(r.path,"path");let p=r.path||pa.join("src","features"),u=Gt(i,p,c.featureName);await Se(i,c.featureName,p)&&(E(`Feature '${c.featureName}' already exists at ${p}!`),process.exit(1)),await Me(n.slice(1),{projectPath:i,spinner:y,featureName:c.featureName,basePath:p,featurePath:u,createStore:c.createStore,persistStore:c.persistStore,createService:c.createService,httpClient:c.selectedHttpClient,detection:s}),Jm(c,p)}catch(i){y.fail("Feature generation failed"),E(`${i}`),process.exit(1)}})},Vm=e=>{e.store&&!["persist","no-persist"].includes(e.store)&&(E("Invalid --store option. Use: persist or no-persist"),process.exit(1)),e.service&&!["axios","fetch"].includes(e.service)&&(E("Invalid --service option. Use: axios or fetch"),process.exit(1)),e.skipStore&&e.store&&(E("Cannot use --skip-store and --store together"),process.exit(1)),e.skipService&&e.service&&(E("Cannot use --skip-service and --service together"),process.exit(1))},Jm=(e,t)=>{let r=pa.join(t,e.featureName);m(V.green(`
|
|
1144
1152
|
\u2728 Feature '${e.featureName}' created successfully!
|
|
1145
1153
|
`)),m(V.dim("Generated files:")),m(V.dim(` \u{1F4C2} ${r}/`)),m(V.dim(" \u251C\u2500\u2500 components/")),m(V.dim(" \u251C\u2500\u2500 hooks/")),m(V.dim(" \u251C\u2500\u2500 types/")),e.createStore&&m(V.dim(" \u251C\u2500\u2500 store/")),e.createService&&m(V.dim(" \u251C\u2500\u2500 services/")),m(V.dim(` \u2514\u2500\u2500 index.ts
|
|
1146
|
-
`)),m(V.cyan("Next steps:"));let i=t.replace(/^src\//,"@/");m(V.dim(` 1. Import and use the feature: import { ${e.featureName} } from '${i}/${e.featureName}'`)),e.createStore&&m(V.dim(` 2. Customize your Redux slice in: ${r}/store/`)),e.createService&&m(V.dim(` 3. Add API methods in: ${r}/services/${e.featureName}.service.ts`)),m("")};import
|
|
1154
|
+
`)),m(V.cyan("Next steps:"));let i=t.replace(/^src\//,"@/");m(V.dim(` 1. Import and use the feature: import { ${e.featureName} } from '${i}/${e.featureName}'`)),e.createStore&&m(V.dim(` 2. Customize your Redux slice in: ${r}/store/`)),e.createService&&m(V.dim(` 3. Add API methods in: ${r}/services/${e.featureName}.service.ts`)),m("")};import Ai from"node:path";import Ke from"picocolors";q();import Wm from"enquirer";var{prompt:qm}=Wm,ma=async e=>e?{hookName:e}:await qm({type:"input",name:"hookName",message:'Hook name (kebab-case, without "use" prefix):',validate:r=>r?/^[a-z][a-z0-9-]*$/.test(r)?!0:"Use lowercase letters, numbers, and hyphens only":"Hook name is required"});var da=e=>{e.command("hook [name]").description("Generate a custom React hook").option("--client","Add 'use client' directive (default: true)",!0).option("--feature <path>","Generate in feature directory (e.g., src/features/auth)").option("--test","Also generate a sibling test file").option("--no-test","Skip test file generation").action(async(t,r)=>{try{let i=process.cwd();m(Ke.cyan(`
|
|
1147
1155
|
\u{1FA9D} Hook Generator
|
|
1148
|
-
`));let n=await M(i),o=await
|
|
1156
|
+
`));let n=await M(i),o=await ma(t);W(o.hookName,"hook name"),r.feature&&pe(r.feature,"feature path");let c=`use${N(o.hookName)}`,p=Xm(r,n.hasTests);y.start("Generating hook..."),await Yr({name:o.hookName,projectPath:i,isClient:r.client??!0,featurePath:r.feature}),y.succeed("Hook generated");let u=r.feature?Ai.join(i,r.feature,"hooks",`${c}.ts`):Ai.join(i,"src/hooks",`${c}.ts`),d=null;p&&(y.start("Generating test..."),d=await ge({projectPath:i,sourceFile:u,kind:"hook",symbolName:c,hookUsesStore:n.hasRedux&&!!r.feature}),y.succeed("Test generated"));let f=r.feature?`${r.feature}/hooks/${c}.ts`:`src/hooks/${c}.ts`;m(Ke.green(`
|
|
1149
1157
|
\u2728 Hook '${c}' created successfully!
|
|
1150
|
-
`)),m(
|
|
1158
|
+
`)),m(Ke.dim(` \u{1F4C4} ${f}`)),d&&m(Ke.dim(` \u{1F9EA} ${Ai.relative(i,d)}`)),m(""),m(Ke.cyan("Usage:"));let x=r.feature?`${r.feature.replace(/^src\//,"@/")}/hooks/${c}`:`@/hooks/${c}`;m(Ke.dim(` import { ${c} } from '${x}';`)),m("")}catch(i){y.fail("Hook generation failed"),E(`${i}`),process.exit(1)}})},Xm=(e,t)=>e.test===!1?!1:e.test===!0?!0:t;import Cr from"picocolors";q();var ua=e=>{e.command("layout <segment>").description("Generate a nested layout.tsx (locale-aware when i18n is detected)").option("--group","Treat the segment as a route group (wraps it in parens)").option("--at <path>","Place the layout under this nested path (kebab-case, slash-separated)").option("--no-locale","Skip the locale wrapper even if i18n is detected").action(async(t,r)=>{try{let i=process.cwd();m(Cr.cyan(`
|
|
1151
1159
|
\u{1F4D0} Layout Generator
|
|
1152
|
-
`)),
|
|
1153
|
-
`)),
|
|
1160
|
+
`)),y.start("Detecting project setup...");let n=await M(i);y.succeed("Project setup detected");let o=n.hasI18n&&r.locale!==!1;m(Cr.dim(` i18n: ${o?"\u2713":"\u2717"}
|
|
1161
|
+
`)),y.start("Generating layout...");let s=await Kr({segment:t,at:r.at,projectPath:i,hasI18n:o,withGroup:!!r.group});y.succeed("Layout generated"),m(Cr.green(`
|
|
1154
1162
|
\u2728 ${s.componentName} created!
|
|
1155
|
-
`)),m(
|
|
1163
|
+
`)),m(Cr.dim(` \u{1F4C4} ${s.displayPath}`)),m("")}catch(i){y.fail("Layout generation failed"),E(`${i instanceof Error?i.message:i}`),process.exit(1)}})};import de from"picocolors";w();q();import Ym from"enquirer";var{prompt:Km}=Ym,fa=async(e,t={})=>{let r=[];e||r.push({type:"input",name:"code",message:"Locale code (e.g., es, fr, de):",validate:n=>n?/^[a-z]{2}(-[A-Z]{2})?$/.test(n)?!0:"Use format: xx or xx-XX (e.g., es, pt-BR)":"Locale code is required"}),r.push({type:"input",name:"name",message:"Language name (e.g., Spanish, French):",validate:n=>n?!0:"Language name is required"},{type:"input",name:"country",message:"Country (e.g., Spain, France):",validate:n=>n?!0:"Country is required"},{type:"input",name:"flag",message:"Flag emoji (e.g., \u{1F1EA}\u{1F1F8}, \u{1F1EB}\u{1F1F7}):",validate:n=>n?!0:"Flag emoji is required"}),t.copyTranslations===void 0&&r.push({type:"confirm",name:"copyTranslations",message:"Copy translations from English? (No = empty values)",initial:!1});let i=await Km(r);return{code:e??i.code,name:i.name,country:i.country,flag:i.flag,copyTranslations:t.copyTranslations??i.copyTranslations??!1}};var ga=e=>{e.command("locale [code]").description("Add a new locale/language").option("--copy-translations","Copy translations from English instead of empty values").action(async(t,r)=>{try{let i=process.cwd();m(de.cyan(`
|
|
1156
1164
|
\u{1F30D} Locale Generator
|
|
1157
|
-
`)),
|
|
1165
|
+
`)),y.start("Detecting project setup...");let n=await M(i);y.succeed("Project setup detected"),n.hasI18n||(y.fail("i18n is not set up in this project"),E("Please set up internationalization first"),m(de.dim(`
|
|
1158
1166
|
Run: npx @teispace/next-maker setup --i18n
|
|
1159
|
-
`)),process.exit(1));let o=await
|
|
1167
|
+
`)),process.exit(1));let o=await fa(t,{copyTranslations:r.copyTranslations});W(o.code,"locale code");let s=Gt(i,"src","i18n","translations",`${o.code}.json`);l(s)&&(E(`Locale '${o.code}' already exists!`),process.exit(1)),y.start("Adding locale..."),await Zr({...o,projectPath:i}),y.succeed("Locale added"),m(de.green(`
|
|
1160
1168
|
\u2728 Locale '${o.code}' (${o.name}) added successfully!
|
|
1161
|
-
`)),m(
|
|
1169
|
+
`)),m(de.dim("Updated files:")),m(de.dim(` \u{1F4C4} src/i18n/translations/${o.code}.json`)),m(de.dim(" \u{1F4DD} src/types/i18n.ts (SupportedLocale type)")),m(de.dim(" \u{1F4DD} src/lib/config/app-locales.ts")),m(""),m(de.cyan("Next steps:")),m(de.dim(` 1. Translate: src/i18n/translations/${o.code}.json`)),m(de.dim(` 2. Visit: http://localhost:3000/${o.code}`)),m("")}catch(i){y.fail("Locale generation failed"),E(`${i}`),process.exit(1)}})};import ya from"node:path";import ne from"picocolors";q();import Zm from"enquirer";var{prompt:Qm}=Zm,ha=async(e,t={})=>{let r=[];e||r.push({type:"input",name:"pageName",message:"Page name (kebab-case):",validate:n=>n?/^[a-z][a-z0-9-]*$/.test(n)?!0:"Use lowercase letters, numbers, and hyphens only":"Page name is required"}),t.loading===void 0&&r.push({type:"confirm",name:"withLoading",message:"Generate loading.tsx?",initial:!0}),t.error===void 0&&r.push({type:"confirm",name:"withError",message:"Generate error.tsx?",initial:!0});let i=r.length>0?await Qm(r):{};return{pageName:e??i.pageName,withLoading:t.loading??i.withLoading??!0,withError:t.error??i.withError??!0}};var xa=e=>{e.command("page [name]").description("Generate a new page/route").option("--dynamic <param>","Create dynamic route with parameter (e.g., id)").option("--loading","Generate loading.tsx").option("--error","Generate error.tsx").action(async(t,r)=>{try{let i=process.cwd();m(ne.cyan(`
|
|
1162
1170
|
\u{1F4C4} Page Generator
|
|
1163
|
-
`)),
|
|
1164
|
-
`));let o=await
|
|
1171
|
+
`)),y.start("Detecting project setup...");let n=await M(i);y.succeed("Project setup detected"),m(ne.dim(` i18n: ${n.hasI18n?"\u2713":"\u2717"}
|
|
1172
|
+
`));let o=await ha(t,{loading:r.loading,error:r.error}),s=o.pageName;W(s,"page name"),r.dynamic&&W(r.dynamic,"dynamic param");let c=N(s),p=n.hasI18n?"src/app/[locale]":"src/app";await Se(i,s,p)&&(E(`Page '${s}' already exists at ${p}/${s}!`),process.exit(1)),y.start("Generating page files..."),await ei({name:s,projectPath:i,hasI18n:n.hasI18n,dynamic:r.dynamic,withLoading:r.loading??o.withLoading,withError:r.error??o.withError}),y.succeed("Page files generated"),y.start("Registering route...");let d=r.dynamic?`/${s}/[${r.dynamic}]`:`/${s}`;await Ri(i,s,d),y.succeed("Route registered"),n.hasI18n&&(y.start("Adding translation namespace..."),await Ii(i,c),y.succeed("Translation namespace added"));let f=r.dynamic?ya.join(p,s,`[${r.dynamic}]`):ya.join(p,s);m(ne.green(`
|
|
1165
1173
|
\u2728 Page '${s}' created successfully!
|
|
1166
|
-
`)),m(
|
|
1174
|
+
`)),m(ne.dim("Generated files:")),m(ne.dim(` \u{1F4C2} ${f}/`)),m(ne.dim(" \u251C\u2500\u2500 page.tsx")),(r.loading??o.withLoading)&&m(ne.dim(" \u251C\u2500\u2500 loading.tsx")),(r.error??o.withError)&&m(ne.dim(" \u2514\u2500\u2500 error.tsx")),m(""),n.hasI18n&&(m(ne.cyan("Next steps:")),m(ne.dim(` 1. Add translations in: src/i18n/translations/en.json \u2192 "${c}"`)),m(ne.dim(` 2. Visit: http://localhost:3000/${s}`)),m(""))}catch(i){y.fail("Page generation failed"),E(`${i}`),process.exit(1)}})};import _i from"node:path";import Re from"picocolors";var wa=e=>{e.command("provider <name>").description("Generate a context provider in src/providers/ and wire it into RootProvider").action(async t=>{try{let r=process.cwd();m(Re.cyan(`
|
|
1167
1175
|
\u{1F50C} Provider Generator
|
|
1168
|
-
`)),
|
|
1176
|
+
`)),y.start("Generating provider...");let{componentName:i,fileBaseName:n,providerFile:o}=await ri({name:t,projectPath:r});y.succeed("Provider generated"),y.start("Registering provider in RootProvider and barrel...");let{rootProviderFile:s,barrelFile:c}=await bi({projectPath:r,componentName:i,fileBaseName:n});y.succeed("Provider registered"),m(Re.green(`
|
|
1169
1177
|
\u2728 ${i} created!
|
|
1170
|
-
`)),m(
|
|
1171
|
-
\u26A0\uFE0F Could not locate a RootProvider file. Wire the new provider manually:`)),m(
|
|
1178
|
+
`)),m(Re.dim("Generated files:")),m(Re.dim(` \u{1F4C4} ${_i.relative(r,o)}`)),s?m(Re.dim(` \u270F\uFE0F ${_i.relative(r,s)} \u2014 wrapped {children}`)):(m(Re.yellow(`
|
|
1179
|
+
\u26A0\uFE0F Could not locate a RootProvider file. Wire the new provider manually:`)),m(Re.dim(` <${i}>{children}</${i}>`))),c&&m(Re.dim(` \u270F\uFE0F ${_i.relative(r,c)} \u2014 added re-export`)),m("")}catch(r){y.fail("Provider generation failed"),E(`${r instanceof Error?r.message:r}`),process.exit(1)}})};import ed from"enquirer";import X from"picocolors";var{prompt:td}=ed,rd=e=>{let t=[];for(let r of e.filesRemoved)t.push(` ${X.red("-")} delete: ${r}`);for(let r of e.blocksStripped)t.push(` ${X.red("-")} strip block: ${r.description} ${X.dim(`(${r.file})`)}`);for(let r of e.scriptsRemoved)t.push(` ${X.red("-")} remove script: ${r}`);for(let r of e.packagesUninstalled)t.push(` ${X.red("-")} uninstall: ${r}`);for(let r of e.manualCleanup)t.push(` ${X.yellow("?")} manual cleanup: ${r.description} ${X.dim(`(${r.file})`)}`);return t},id=e=>e.filesRemoved.length===0&&e.blocksStripped.length===0&&e.scriptsRemoved.length===0&&e.packagesUninstalled.length===0&&e.manualCleanup.length===0,Pa=e=>{e.command("remove <feature>").alias("uninstall").description("Reverse a feature install (uses the feature manifest)").option("-y, --yes","Skip confirmation prompt").option("--dry-run","Show what would change without writing").action(async(t,r)=>{try{let i=process.cwd(),n=$s(t);if(!n)throw new Error(`Unknown feature "${t}". Valid: ${De.map(p=>p.id).join(", ")}.`);if(m(X.cyan(`
|
|
1172
1180
|
\u{1F5D1} Remove ${n.name}
|
|
1173
|
-
`)),!(await
|
|
1181
|
+
`)),!(await qe(n,i)).installed){m(X.dim(`${n.name} is not installed \u2014 nothing to remove.`));return}y.start("Computing changes...");let s=await Pr(n,i,{dryRun:!0});if(y.succeed("Computed plan"),id(s)){m(X.yellow(`
|
|
1174
1182
|
\u26A0\uFE0F Manifest had no removable artifacts. Nothing to do.
|
|
1175
|
-
`));return}m(
|
|
1183
|
+
`));return}m(X.bold(`
|
|
1176
1184
|
Planned changes:
|
|
1177
|
-
`));for(let p of rd(s))m(p);if(m(""),r.dryRun){m(
|
|
1178
|
-
`));return}if(!r.yes){let{confirm:p}=await td({type:"confirm",name:"confirm",message:`Apply the changes above to remove ${n.name}?`,initial:!1});if(!p){m(
|
|
1185
|
+
`));for(let p of rd(s))m(p);if(m(""),r.dryRun){m(X.dim(`--dry-run set \u2014 exiting without writing.
|
|
1186
|
+
`));return}if(!r.yes){let{confirm:p}=await td({type:"confirm",name:"confirm",message:`Apply the changes above to remove ${n.name}?`,initial:!1});if(!p){m(X.yellow(`
|
|
1179
1187
|
Aborted.
|
|
1180
|
-
`));return}}
|
|
1181
|
-
\u2713 ${n.name} removed.`)),c.manualCleanup.length>0){m(
|
|
1182
|
-
\u26A0\uFE0F Manual cleanup still required:`));for(let p of c.manualCleanup)m(` - ${p.description} (${p.file})`)}m("")}catch(i){
|
|
1188
|
+
`));return}}y.start(`Removing ${n.name}...`);let c;if(n.remove?(await n.remove(i),c=s):c=await Pr(n,i),y.succeed(`${n.name} removed`),m(X.green(`
|
|
1189
|
+
\u2713 ${n.name} removed.`)),c.manualCleanup.length>0){m(X.yellow(`
|
|
1190
|
+
\u26A0\uFE0F Manual cleanup still required:`));for(let p of c.manualCleanup)m(` - ${p.description} (${p.file})`)}m("")}catch(i){y.fail("Remove failed"),E(`${i instanceof Error?i.message:i}`),process.exit(1)}})};import{existsSync as ad}from"node:fs";import{mkdir as cd}from"node:fs/promises";import $t from"node:path";import oe from"picocolors";q();import{readFile as nd,writeFile as od}from"node:fs/promises";import sd from"node:path";var va=async(e,t)=>{let r=G(t),i=sd.join(e,"src","lib","config","app-apis.ts");try{let n=await nd(i,"utf-8");if(n.includes(`${r}:`))return;if(!n.match(/export const AppApis = \{[\s\S]*?\} as const;/))throw new Error("Could not find AppApis object in app-apis.ts");let o=Gn({camelName:r,kebabName:t});n=ot(n,o),await od(i,n)}catch(n){throw new Error(`Failed to register CRUD API endpoints: ${n}`,{cause:n})}};import Sa from"enquirer";var Ea=async(e,t,r,i)=>{let n=e||(await Sa.prompt({type:"input",name:"serviceName",message:"Service name (kebab-case):",validate:s=>s?/^[a-z0-9-]+$/.test(s)?!0:"Service name must be lowercase with hyphens only":"Service name is required"})).serviceName,o;return t!==void 0?o="axios":r!==void 0?o="fetch":i==="axios"?o="axios":i==="fetch"?o="fetch":i==="both"?o=(await Sa.prompt({type:"select",name:"httpClient",message:"Choose HTTP client:",choices:["axios","fetch"]})).httpClient:o="axios",{serviceName:n,httpClient:o}};var Ta=e=>{e.command("service [name]").description("Generate an API service").option("--path <path>","Custom path for service generation (default: create new feature)").option("--axios","Use Axios HTTP client").option("--fetch","Use Fetch HTTP client").option("--crud","Generate full CRUD service (getAll, getById, create, update, delete)").action(async(t,r)=>{try{let i=process.cwd();r.axios&&r.fetch&&(E("Cannot use --axios and --fetch together"),process.exit(1)),m(oe.cyan(`
|
|
1183
1191
|
\u{1F527} Service Generator
|
|
1184
|
-
`)),
|
|
1192
|
+
`)),y.start("Detecting project setup...");let n=await M(i);y.succeed("Project setup detected"),n.httpClient==="none"&&(y.fail("No HTTP client is setup in this project"),E("Please setup either AxiosClient or FetchClient first"),m(oe.dim(`
|
|
1185
1193
|
Check: lib/utils/http/axios-client or lib/utils/http/fetch-client
|
|
1186
|
-
`)),process.exit(1));let o=[];(n.httpClient==="axios"||n.httpClient==="both")&&o.push("Axios \u2713"),(n.httpClient==="fetch"||n.httpClient==="both")&&o.push("Fetch \u2713"),m(
|
|
1187
|
-
`));let s=await
|
|
1194
|
+
`)),process.exit(1));let o=[];(n.httpClient==="axios"||n.httpClient==="both")&&o.push("Axios \u2713"),(n.httpClient==="fetch"||n.httpClient==="both")&&o.push("Fetch \u2713"),m(oe.dim(` HTTP Clients: ${o.join(", ")}
|
|
1195
|
+
`));let s=await Ea(t,r.axios,r.fetch,n.httpClient);W(s.serviceName,"service name"),r.path&&pe(r.path,"path");let{basePath:c,servicePath:p}=pd(i,s.serviceName,r.path);ad(p)||await cd(p,{recursive:!0}),Ht(i,c,`${s.serviceName}.service.ts`)&&(E(`Service '${s.serviceName}' already exists at ${c}!`),process.exit(1)),r.crud?(y.start("Generating CRUD service files..."),await Wr({name:s.serviceName,outputPath:p,httpClient:s.httpClient}),y.succeed("CRUD service files generated"),y.start("Registering CRUD API endpoints..."),await va(i,s.serviceName),y.succeed("CRUD API endpoints registered")):await Me(ki(),{projectPath:i,spinner:y,serviceName:s.serviceName,servicePath:p,httpClient:s.httpClient}),ld(s,c,!!r.crud)}catch(i){y.fail("Service generation failed"),E(`${i}`),process.exit(1)}})},pd=(e,t,r)=>{let i;if(r){let n=r.replace(/^src\//,"");if(n.startsWith("features/")){let o=n.split("/")[1];i=$t.join("src","features",o,"services")}else i=$t.join("src",n)}else i=$t.join("src","features",t,"services");return{basePath:i,servicePath:$t.join(e,i)}},ld=(e,t,r=!1)=>{let i=$t.join(t,`${e.serviceName}.service.ts`);m(oe.green(`
|
|
1188
1196
|
\u2728 ${r?"CRUD ":""}Service '${e.serviceName}' created successfully!
|
|
1189
|
-
`)),m(
|
|
1190
|
-
`)),m(
|
|
1197
|
+
`)),m(oe.dim("Generated files:")),m(oe.dim(` \u{1F4C4} ${i}
|
|
1198
|
+
`)),m(oe.cyan("Next steps:"));let n=t.replace(/^src\//,"@/");m(oe.dim(` 1. Import service: import { ${e.serviceName}Service } from '${n}/${e.serviceName}.service'`)),r?(m(oe.dim(" 2. Available methods: getAll, getById, create, update, delete")),m(oe.dim(" 3. Update DTO types in the service file"))):m(oe.dim(` 2. Use in component: const data = await ${e.serviceName}Service.getAll()`)),m("")};import md from"enquirer";import Fi from"picocolors";var{prompt:dd}=md,Oi=[{key:"http-client",label:"HTTP Client (Axios/Fetch)",flag:"httpClient",handler:or},{key:"dark-theme",label:"Dark Theme",flag:"darkTheme",handler:er},{key:"redux",label:"Redux Toolkit",flag:"redux",handler:gr},{key:"ws",label:"WebSocket Client (requires Redux)",flag:"ws",handler:wr},{key:"i18n",label:"Internationalization (next-intl)",flag:"i18n",handler:mr},{key:"tests",label:"Testing (Vitest + RTL)",flag:"tests",handler:yr},{key:"react-compiler",label:"React Compiler",flag:"reactCompiler",handler:ur},{key:"bundle-analyzer",label:"Bundle Analyzer",flag:"bundleAnalyzer",handler:Wt},{key:"security-headers",label:"Security Headers",flag:"securityHeaders",handler:hr},{key:"validate-scripts",label:"Validation Scripts",flag:"validateScripts",handler:xr},{key:"commitizen",label:"Commitizen",flag:"commitizen",handler:Xt}],ud=async(e,t={})=>{let r=t.promptFn??dd,i=t.cwd??(()=>process.cwd());m(Fi.cyan(`
|
|
1191
1199
|
\u{1F527} Setup Wizard
|
|
1192
|
-
`));let n=
|
|
1193
|
-
\u26A0\uFE0F ${s} setup is not implemented yet.`)),null)},
|
|
1200
|
+
`));let n=Oi.filter(p=>!!e[p.flag]);if(n.length>0){for(let p of n)await p.handler(i());return n.length===1?n[0].key:"multiple"}let s=(await r([{type:"select",name:"feature",message:"What would you like to setup?",choices:[...Oi.map(p=>({name:p.key,message:p.label})),{name:"cancel",message:"Cancel"}]}])).feature;if(s==="cancel")return m(Fi.yellow("Setup cancelled.")),null;let c=Oi.find(p=>p.key===s);return c?(await c.handler(i()),c.key):(m(Fi.yellow(`
|
|
1201
|
+
\u26A0\uFE0F ${s} setup is not implemented yet.`)),null)},Ca=e=>{e.command("setup").description("Setup features in an existing Next.js project").option("--http-client","Setup HTTP client (axios|fetch)").option("--dark-theme","Setup Dark Theme (Tailwind + @teispace/next-themes)").option("--redux","Setup Redux Toolkit").option("--ws","Setup WebSocket client (socket.io-client + Redux bridge; requires --redux)").option("--i18n","Setup next-intl for internationalization").option("--tests","Setup testing (Vitest + React Testing Library)").option("--react-compiler","Enable the React Compiler").option("--bundle-analyzer","Add @next/bundle-analyzer").option("--security-headers","Add hardened HTTP headers to next.config.ts").option("--validate-scripts","Add scripts/sync-env.ts, scripts/check-deprecated.ts, and the validate chain").option("--commitizen","Add Commitizen with the conventional-changelog adapter").action(async t=>{try{await ud(t)}catch(r){y.fail("Setup failed"),E(`${r}`),process.exit(1)}})};import{existsSync as hd}from"node:fs";import{mkdir as yd}from"node:fs/promises";import be from"node:path";import Y from"picocolors";q();import fd from"enquirer";var{prompt:gd}=fd,Ra=async(e,t)=>{let r=[];e||r.push({type:"input",name:"sliceName",message:"What is the slice name?",initial:"my-slice",validate:n=>/^[a-z0-9-]+$/.test(n)?!0:"Slice name must be lowercase and contain only alphanumeric characters and hyphens."}),t===void 0&&r.push({type:"confirm",name:"persistSlice",message:"Enable persistence for this slice?",initial:!1});let i=r.length>0?await gd(r):{};return{sliceName:e||i.sliceName,persistSlice:t===void 0?i.persistSlice||!1:t}};var ba=e=>{e.command("slice [name]").description("Generate a Redux slice").option("--path <path>","Custom path for slice generation (default: create new feature)").option("--persist","Enable persistence for this slice").option("--no-persist","Disable persistence for this slice").option("--test","Also generate a sibling test file").option("--no-test","Skip test file generation").action(async(t,r)=>{try{let i=process.cwd();m(Y.cyan(`
|
|
1194
1202
|
\u{1F527} Slice Generator
|
|
1195
|
-
`)),
|
|
1203
|
+
`)),y.start("Detecting project setup...");let n=await M(i);y.succeed("Project setup detected"),n.hasRedux||(y.fail("Redux is not setup in this project"),E("Please install @reduxjs/toolkit and react-redux first"),m(Y.dim(`
|
|
1196
1204
|
Run: npm install @reduxjs/toolkit react-redux
|
|
1197
|
-
`)),process.exit(1)),m(
|
|
1198
|
-
`));let o=await
|
|
1205
|
+
`)),process.exit(1)),m(Y.dim(` Redux: \u2713
|
|
1206
|
+
`));let o=await Ra(t,r.persist);W(o.sliceName,"slice name"),r.path&&pe(r.path,"path");let{basePath:s,slicePath:c}=xd(i,o.sliceName,r.path),p=be.join(i,s);hd(p)||await yd(p,{recursive:!0}),await Se(i,o.sliceName,s)&&(E(`Slice '${o.sliceName}' already exists at ${s}!`),process.exit(1)),await Me(Ni(),{projectPath:i,spinner:y,sliceName:o.sliceName,basePath:s,slicePath:c,persistSlice:o.persistSlice});let d=null;if(wd(r,n.hasTests)){let x=be.join(c,`${o.sliceName}.slice.ts`);y.start("Generating test..."),d=await ge({projectPath:i,sourceFile:x,kind:"slice",symbolName:G(o.sliceName)}),y.succeed("Test generated")}Pd(o,s,d,i)}catch(i){y.fail("Slice generation failed"),E(`${i}`),process.exit(1)}})},xd=(e,t,r)=>{let i;if(r){let n=r.replace(/^src\//,"");if(n.startsWith("features/")){let o=n.split("/")[1];i=be.join("src","features",o,"store")}else i=be.join("src",n)}else i=be.join("src","features",t,"store");return{basePath:i,slicePath:be.join(e,i,t)}},wd=(e,t)=>e.test===!1?!1:e.test===!0?!0:t,Pd=(e,t,r,i)=>{let n=be.join(t,e.sliceName);m(Y.green(`
|
|
1199
1207
|
\u2728 Slice '${e.sliceName}' created successfully!
|
|
1200
|
-
`)),m(
|
|
1201
|
-
`)),r&&m(
|
|
1202
|
-
`)),m(
|
|
1203
|
-
Infers the kind from filename/content; pass --kind to override.`).option("--kind <kind>","Override inferred kind: component | hook | slice").option("--force","Overwrite an existing test file").action(async(t,r)=>{try{let i=process.cwd(),n=
|
|
1208
|
+
`)),m(Y.dim("Generated files:")),m(Y.dim(` \u{1F4C2} ${n}/`)),m(Y.dim(` \u251C\u2500\u2500 ${e.sliceName}.slice.ts`)),m(Y.dim(` \u251C\u2500\u2500 ${e.sliceName}.selectors.ts`)),e.persistSlice&&m(Y.dim(" \u251C\u2500\u2500 persist.ts")),m(Y.dim(` \u251C\u2500\u2500 ${e.sliceName}.types.ts`)),m(Y.dim(` \u2514\u2500\u2500 index.ts
|
|
1209
|
+
`)),r&&m(Y.dim(` \u{1F9EA} ${be.relative(i,r)}
|
|
1210
|
+
`)),m(Y.cyan("Next steps:"));let o=t.replace(/^src\//,"@/");m(Y.dim(` 1. Import actions: import { setLoading, setError } from '${o}/${e.sliceName}'`)),m(Y.dim(" 2. Use in component: dispatch(setLoading(true))")),m("")};import se from"node:path";import Di from"picocolors";w();q();var Ia=e=>{e.command("test <file>").description(`Generate a sibling test file for an existing component, hook, or slice.
|
|
1211
|
+
Infers the kind from filename/content; pass --kind to override.`).option("--kind <kind>","Override inferred kind: component | hook | slice").option("--force","Overwrite an existing test file").action(async(t,r)=>{try{let i=process.cwd(),n=se.isAbsolute(t)?t:se.join(i,t);m(Di.cyan(`
|
|
1204
1212
|
\u{1F9EA} Test Generator
|
|
1205
|
-
`)),l(n)||(E(`Source file not found: ${t}`),process.exit(1));let o=await M(i);o.hasTests||(E("Testing is not installed in this project. Run `next-maker setup --tests` first."),process.exit(1));let s=await g(n),c=vd(r.kind)??Sd(n,s);c||(E(`Could not infer test kind for ${
|
|
1206
|
-
\u2728 Test '${
|
|
1207
|
-
`)),m(
|
|
1213
|
+
`)),l(n)||(E(`Source file not found: ${t}`),process.exit(1));let o=await M(i);o.hasTests||(E("Testing is not installed in this project. Run `next-maker setup --tests` first."),process.exit(1));let s=await g(n),c=vd(r.kind)??Sd(n,s);c||(E(`Could not infer test kind for ${se.basename(n)}. Pass --kind component|hook|slice.`),process.exit(1));let p=Ed(n,c),u=Td(n,c);l(u)&&!r.force&&(E(`Test file already exists: ${se.relative(i,u)}. Use --force to overwrite.`),process.exit(1)),y.start(`Generating ${c} test...`);let d=await ge({projectPath:i,sourceFile:n,kind:c,symbolName:p,hasRedux:o.hasRedux,hasI18n:o.hasI18n,hookUsesStore:c==="hook"&&o.hasRedux&&s.includes("useAppSelector")});y.succeed("Test generated"),m(Di.green(`
|
|
1214
|
+
\u2728 Test '${se.basename(d)}' created.
|
|
1215
|
+
`)),m(Di.dim(` \u{1F9EA} ${se.relative(i,d)}`)),m("")}catch(i){y.fail("Test generation failed"),E(`${i}`),process.exit(1)}})},vd=e=>{if(!e)return null;if(e==="component"||e==="hook"||e==="slice")return e;throw new Error(`Invalid --kind: ${e}. Use component | hook | slice.`)},Sd=(e,t)=>{let r=se.basename(e);return/\.slice\.ts$/.test(r)?"slice":/^use[A-Z]/.test(r.replace(/\.tsx?$/,""))?"hook":r.endsWith(".tsx")?"component":/createSlice\s*\(/.test(t)?"slice":/^export\s+(const|function)\s+use[A-Z]/m.test(t)?"hook":null},Ed=(e,t)=>{let r=se.basename(e).replace(/\.(tsx?|jsx?)$/i,"");return t==="slice"?G(r.replace(/\.slice$/,"")):t==="hook"?/^use[A-Z]/.test(r)?r:`use${N(r.replace(/^use-?/,""))}`:N(r)},Td=(e,t)=>{let r=se.dirname(e),i=se.basename(e).replace(/\.(tsx?|jsx?)$/i,""),n=t==="component"?".tsx":".ts";return se.join(r,`${i}.test${n}`)};var $a=e=>{Nn(e),Ca(e),la(e),ba(e),Ta(e),xa(e),ua(e),lo(e),ga(e),da(e),wa(e),Hs(e),na(e),Ns(e),Pa(e),Ia(e)};var Rd=process.emitWarning;process.emitWarning=function(e,t,r,i){if(!(typeof e=="string"&&e.includes("--localstorage-file")&&e.includes("was provided without a valid path")))return Rd.apply(process,arguments)};async function bd(){Mi({logger:t=>Nt(t)});let e=new Cd;e.name("next-maker").description("Teispace Next.js Project Generator").version(ji.version),$a(e),e.parse()}bd().catch(e=>{let t=e&&typeof e=="object"&&"message"in e?e.message:String(e);Nt(`Unexpected error: ${t}`)});
|