create-easy-cms 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kanawoot K.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,10 @@
1
+ # create-easy-cms
2
+
3
+ Adds [Easy CMS](https://github.com/maritonx/easy-crm) to a Nuxt or Next.js project.
4
+
5
+ ```bash
6
+ npx create-easy-cms [dir] [--db sqlite|postgres] [--yes] [--skip-install]
7
+ ```
8
+
9
+ Creates `easy-cms.config.ts`, adds `EASY_CMS_SECRET` to `.env`, updates `.gitignore`, wires the
10
+ Nuxt module or the Next.js route handlers and config, and installs the packages. Safe to run again.
package/dist/bin.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ run
4
+ } from "./chunk-F7EP27M3.js";
5
+
6
+ // src/bin.ts
7
+ process.exitCode = await run(process.argv.slice(2));
@@ -0,0 +1,331 @@
1
+ // src/index.ts
2
+ import { spawn } from "child_process";
3
+ import { randomBytes } from "crypto";
4
+ import { existsSync, readFileSync } from "fs";
5
+ import { mkdir, readFile, writeFile } from "fs/promises";
6
+ import { dirname, join, relative, resolve } from "path";
7
+ import { createInterface } from "readline/promises";
8
+ import { fileURLToPath } from "url";
9
+ import { parseArgs } from "util";
10
+
11
+ // src/templates.ts
12
+ function configTemplate(db) {
13
+ const database = db === "sqlite" ? `import { sqlite } from '@easy-cms/db-sqlite'` : `import { postgres } from '@easy-cms/db-postgres'`;
14
+ const adapter = db === "sqlite" ? ` db: sqlite({ url: process.env.DATABASE_URL ?? 'file:./cms.db' }),` : ` // A Postgres server when DATABASE_URL is set; otherwise PGlite (Postgres in WebAssembly) in .pglite.
15
+ db: process.env.DATABASE_URL
16
+ ? postgres({ url: process.env.DATABASE_URL })
17
+ : postgres({ pglite: '.pglite' }),`;
18
+ return `import { defineConfig } from '@easy-cms/core'
19
+ ${database}
20
+
21
+ export default defineConfig({
22
+ secret: process.env.EASY_CMS_SECRET ?? '',
23
+ ${adapter}
24
+ admin: { locale: 'en' },
25
+ collections: [
26
+ {
27
+ slug: 'posts',
28
+ drafts: true,
29
+ useAsTitle: 'title',
30
+ // Visitors see published posts; logged-in editors see drafts too.
31
+ access: { read: ({ user }) => (user ? true : { status: { equals: 'published' } }) },
32
+ fields: [
33
+ { name: 'title', type: 'text', required: true },
34
+ { name: 'slug', type: 'slug', from: 'title' },
35
+ { name: 'cover', type: 'upload' },
36
+ { name: 'body', type: 'richText' },
37
+ ],
38
+ },
39
+ ],
40
+ globals: [
41
+ {
42
+ slug: 'site',
43
+ access: { read: () => true },
44
+ fields: [{ name: 'siteName', type: 'text', defaultValue: 'My site' }],
45
+ },
46
+ ],
47
+ })
48
+ `;
49
+ }
50
+ function nextApiRoute(configImport) {
51
+ return `import { createRouteHandlers } from '@easy-cms/next'
52
+ import config from '${configImport}'
53
+
54
+ // The Easy CMS REST API (routes.api in easy-cms.config.ts).
55
+ export const { GET, HEAD, POST, PATCH, PUT, DELETE, OPTIONS } = createRouteHandlers(config)
56
+ `;
57
+ }
58
+ function nextAdminRoute(configImport) {
59
+ return `import { createAdminRouteHandlers } from '@easy-cms/next'
60
+ import config from '${configImport}'
61
+
62
+ // The Easy CMS admin UI (admin.path in easy-cms.config.ts).
63
+ export const { GET, HEAD } = createAdminRouteHandlers(config)
64
+ `;
65
+ }
66
+
67
+ // src/index.ts
68
+ var defaultIO = {
69
+ out: (line) => console.log(line),
70
+ err: (line) => console.error(line),
71
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
72
+ prompt: async (question) => {
73
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
74
+ try {
75
+ return (await rl.question(question)).trim();
76
+ } finally {
77
+ rl.close();
78
+ }
79
+ },
80
+ exec: (command, args, cwd) => new Promise((done) => {
81
+ const child = spawn(command, args, {
82
+ cwd,
83
+ stdio: "inherit",
84
+ shell: process.platform === "win32"
85
+ });
86
+ child.on("close", (code) => done(code ?? 1));
87
+ child.on("error", () => done(1));
88
+ })
89
+ };
90
+ var HELP = `Usage: create-easy-cms [dir] [options]
91
+
92
+ Adds Easy CMS to the Nuxt or Next.js project in [dir] (default: current directory).
93
+
94
+ Options:
95
+ --db <sqlite|postgres> Database (default: ask, or sqlite with --yes)
96
+ --yes, -y Accept the defaults without asking
97
+ --skip-install Write files only; install the packages yourself
98
+ -h, --help Show help
99
+ `;
100
+ function detectFramework(pkg) {
101
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
102
+ if (deps.nuxt) return "nuxt";
103
+ if (deps.next) return "next";
104
+ return void 0;
105
+ }
106
+ function detectPackageManager(dir) {
107
+ if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm";
108
+ if (existsSync(join(dir, "yarn.lock"))) return "yarn";
109
+ if (existsSync(join(dir, "bun.lock")) || existsSync(join(dir, "bun.lockb"))) return "bun";
110
+ if (existsSync(join(dir, "package-lock.json"))) return "npm";
111
+ const agent = process.env.npm_config_user_agent ?? "";
112
+ for (const pm of ["pnpm", "yarn", "bun"]) if (agent.startsWith(pm)) return pm;
113
+ return "npm";
114
+ }
115
+ function ownVersion() {
116
+ try {
117
+ const pkg = JSON.parse(
118
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")
119
+ );
120
+ return pkg.version && pkg.version !== "0.0.0" ? `^${pkg.version}` : "latest";
121
+ } catch {
122
+ return "latest";
123
+ }
124
+ }
125
+ function packagesFor(framework, db) {
126
+ const v = ownVersion();
127
+ const deps = [`@easy-cms/core@${v}`, `@easy-cms/${framework}@${v}`];
128
+ if (db === "sqlite") deps.push(`@easy-cms/db-sqlite@${v}`);
129
+ else deps.push(`@easy-cms/db-postgres@${v}`, "@electric-sql/pglite");
130
+ return { deps, devDeps: [`easy-cms@${v}`] };
131
+ }
132
+ function installArgs(pm, packages, dev) {
133
+ const add = pm === "npm" ? "install" : "add";
134
+ const devFlag = pm === "npm" ? "--save-dev" : pm === "bun" ? "--dev" : "-D";
135
+ return [add, ...dev ? [devFlag] : [], ...packages];
136
+ }
137
+ async function run(argv, io = defaultIO) {
138
+ let values;
139
+ let positionals;
140
+ try {
141
+ ;
142
+ ({ values, positionals } = parseArgs({
143
+ args: [...argv],
144
+ allowPositionals: true,
145
+ options: {
146
+ db: { type: "string" },
147
+ yes: { type: "boolean", short: "y" },
148
+ "skip-install": { type: "boolean" },
149
+ help: { type: "boolean", short: "h" }
150
+ }
151
+ }));
152
+ } catch (error) {
153
+ io.err(error.message);
154
+ io.err(HELP);
155
+ return 1;
156
+ }
157
+ if (values.help) {
158
+ io.out(HELP);
159
+ return 0;
160
+ }
161
+ const dir = resolve(positionals[0] ?? process.cwd());
162
+ const pkgFile = join(dir, "package.json");
163
+ if (!existsSync(pkgFile)) {
164
+ io.err(`No package.json in ${dir}. Run this inside a Nuxt or Next.js project.`);
165
+ return 1;
166
+ }
167
+ const framework = detectFramework(JSON.parse(await readFile(pkgFile, "utf8")));
168
+ if (!framework) {
169
+ io.err('This does not look like a Nuxt or Next.js project (no "nuxt" or "next" dependency).');
170
+ io.err("Create one first, e.g. `npx nuxi init my-app` or `npx create-next-app my-app`.");
171
+ return 1;
172
+ }
173
+ let db = values.db;
174
+ if (db !== void 0 && db !== "sqlite" && db !== "postgres") {
175
+ io.err(`--db must be "sqlite" or "postgres" (got "${db}")`);
176
+ return 1;
177
+ }
178
+ if (!db) {
179
+ if (!values.yes && io.interactive && io.prompt) {
180
+ const answer = (await io.prompt("Database? [1] SQLite (default) [2] Postgres (PGlite locally): ")).toLowerCase();
181
+ db = answer === "2" || answer.startsWith("p") ? "postgres" : "sqlite";
182
+ } else {
183
+ db = "sqlite";
184
+ }
185
+ }
186
+ io.out(`Adding Easy CMS to this ${framework === "nuxt" ? "Nuxt" : "Next.js"} project (${db}).`);
187
+ const changes = [];
188
+ const notes = [];
189
+ const configFile = join(dir, "easy-cms.config.ts");
190
+ if (existsSync(configFile)) {
191
+ notes.push("easy-cms.config.ts already exists; left unchanged.");
192
+ } else {
193
+ await writeFile(configFile, configTemplate(db));
194
+ changes.push("created easy-cms.config.ts");
195
+ }
196
+ const envFile = join(dir, ".env");
197
+ const env = existsSync(envFile) ? await readFile(envFile, "utf8") : "";
198
+ if (!/^EASY_CMS_SECRET=\S+/m.test(env)) {
199
+ const secret = randomBytes(32).toString("hex");
200
+ await writeFile(
201
+ envFile,
202
+ `${env}${env && !env.endsWith("\n") ? "\n" : ""}EASY_CMS_SECRET=${secret}
203
+ `
204
+ );
205
+ changes.push("added EASY_CMS_SECRET to .env");
206
+ }
207
+ const ignoreFile = join(dir, ".gitignore");
208
+ const ignore = existsSync(ignoreFile) ? await readFile(ignoreFile, "utf8") : "";
209
+ const wanted = [".env", "cms.db*", "uploads/", ".pglite/"].filter(
210
+ (entry) => !ignore.split("\n").some((line) => line.trim() === entry)
211
+ );
212
+ if (wanted.length) {
213
+ const block = `
214
+ # Easy CMS
215
+ ${wanted.join("\n")}
216
+ `;
217
+ await writeFile(
218
+ ignoreFile,
219
+ `${ignore}${ignore && !ignore.endsWith("\n") ? "\n" : ""}${block.trimStart()}`
220
+ );
221
+ changes.push(`added ${wanted.join(", ")} to .gitignore`);
222
+ }
223
+ if (framework === "nuxt") await setupNuxt(dir, changes, notes);
224
+ else await setupNext(dir, changes, notes);
225
+ for (const change of changes) io.out(` \u2713 ${change}`);
226
+ for (const note of notes) io.out(` \u2022 ${note}`);
227
+ const pm = detectPackageManager(dir);
228
+ const { deps, devDeps } = packagesFor(framework, db);
229
+ if (values["skip-install"]) {
230
+ io.out("\nInstall the packages:");
231
+ io.out(` ${pm} ${installArgs(pm, deps, false).join(" ")}`);
232
+ io.out(` ${pm} ${installArgs(pm, devDeps, true).join(" ")}`);
233
+ } else if (io.exec) {
234
+ io.out(`
235
+ Installing with ${pm}\u2026`);
236
+ const code = await io.exec(pm, installArgs(pm, deps, false), dir) || await io.exec(pm, installArgs(pm, devDeps, true), dir);
237
+ if (code !== 0) {
238
+ io.err(
239
+ `
240
+ Installing failed. Run it yourself:
241
+ ${pm} ${installArgs(pm, deps, false).join(" ")}`
242
+ );
243
+ return 1;
244
+ }
245
+ }
246
+ const devCommand = pm === "npm" ? "npm run dev" : `${pm} dev`;
247
+ io.out(`
248
+ Done. Next:
249
+ 1. ${devCommand}
250
+ 2. Open /admin and create the first admin (or run: npx easy-cms create-admin)
251
+ 3. Before deploying: npx easy-cms migrate:create init, commit easy-cms/migrations,
252
+ and run npx easy-cms migrate where you deploy.`);
253
+ return 0;
254
+ }
255
+ async function setupNuxt(dir, changes, notes) {
256
+ const file = ["nuxt.config.ts", "nuxt.config.js", "nuxt.config.mjs"].map((f) => join(dir, f)).find(existsSync);
257
+ const manual = "add '@easy-cms/nuxt' to `modules` in nuxt.config";
258
+ if (!file) {
259
+ notes.push(`No nuxt.config found: ${manual}.`);
260
+ return;
261
+ }
262
+ const source = await readFile(file, "utf8");
263
+ if (source.includes("@easy-cms/nuxt")) return;
264
+ let next;
265
+ if (/modules\s*:\s*\[/.test(source)) {
266
+ next = source.replace(/modules\s*:\s*\[/, (match) => `${match}'@easy-cms/nuxt', `);
267
+ } else if (/defineNuxtConfig\(\s*\{/.test(source)) {
268
+ next = source.replace(
269
+ /defineNuxtConfig\(\s*\{/,
270
+ (match) => `${match}
271
+ modules: ['@easy-cms/nuxt'],`
272
+ );
273
+ }
274
+ if (next) {
275
+ await writeFile(file, next);
276
+ changes.push(`added @easy-cms/nuxt to modules in ${relative(dir, file)}`);
277
+ } else {
278
+ notes.push(`Could not edit ${relative(dir, file)}: ${manual}.`);
279
+ }
280
+ }
281
+ async function setupNext(dir, changes, notes) {
282
+ const appDir = existsSync(join(dir, "src", "app")) ? join(dir, "src", "app") : join(dir, "app");
283
+ const routes = [
284
+ { file: join(appDir, "api", "cms", "[[...path]]", "route.ts"), template: nextApiRoute },
285
+ { file: join(appDir, "admin", "[[...path]]", "route.ts"), template: nextAdminRoute }
286
+ ];
287
+ for (const { file, template } of routes) {
288
+ if (existsSync(file)) {
289
+ notes.push(`${relative(dir, file)} already exists; left unchanged.`);
290
+ continue;
291
+ }
292
+ const configImport = relative(dirname(file), join(dir, "easy-cms.config")).replace(/\\/g, "/");
293
+ await mkdir(dirname(file), { recursive: true });
294
+ await writeFile(file, template(configImport));
295
+ changes.push(`created ${relative(dir, file)}`);
296
+ }
297
+ const configFile = ["next.config.ts", "next.config.mjs", "next.config.js"].map((f) => join(dir, f)).find(existsSync);
298
+ const manual = "wrap your Next config: `export default withEasyCMS(config)` from '@easy-cms/next/config'";
299
+ if (!configFile) {
300
+ await writeFile(
301
+ join(dir, "next.config.ts"),
302
+ `import { withEasyCMS } from '@easy-cms/next/config'
303
+
304
+ export default withEasyCMS({})
305
+ `
306
+ );
307
+ changes.push("created next.config.ts");
308
+ return;
309
+ }
310
+ const source = await readFile(configFile, "utf8");
311
+ if (source.includes("withEasyCMS")) return;
312
+ const match = /export\s+default\s+([A-Za-z_$][\w$]*)\s*;?/.exec(source);
313
+ if (!match) {
314
+ notes.push(`Could not edit ${relative(dir, configFile)}: ${manual}.`);
315
+ return;
316
+ }
317
+ const updated = `import { withEasyCMS } from '@easy-cms/next/config'
318
+ ${source.replace(
319
+ match[0],
320
+ `export default withEasyCMS(${match[1].trim()})`
321
+ )}`;
322
+ await writeFile(configFile, updated);
323
+ changes.push(`wrapped the config in withEasyCMS() in ${relative(dir, configFile)}`);
324
+ }
325
+
326
+ export {
327
+ detectFramework,
328
+ detectPackageManager,
329
+ packagesFor,
330
+ run
331
+ };
@@ -0,0 +1,24 @@
1
+ type DatabaseChoice = 'sqlite' | 'postgres';
2
+
3
+ type Framework = 'nuxt' | 'next';
4
+ type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';
5
+ interface IO {
6
+ readonly out: (line: string) => void;
7
+ readonly err: (line: string) => void;
8
+ readonly interactive: boolean;
9
+ readonly prompt?: (question: string) => Promise<string>;
10
+ /** Runs a command (the package manager). Returns the exit code. */
11
+ readonly exec?: (command: string, args: string[], cwd: string) => Promise<number>;
12
+ }
13
+ /** Detects the framework from package.json dependencies. */
14
+ declare function detectFramework(pkg: Record<string, unknown>): Framework | undefined;
15
+ /** Detects the package manager from the lockfile, falling back to the one running us. */
16
+ declare function detectPackageManager(dir: string): PackageManager;
17
+ declare function packagesFor(framework: Framework, db: DatabaseChoice): {
18
+ deps: string[];
19
+ devDeps: string[];
20
+ };
21
+ /** Runs create-easy-cms and returns the exit code. */
22
+ declare function run(argv: readonly string[], io?: IO): Promise<number>;
23
+
24
+ export { type Framework, type IO, type PackageManager, detectFramework, detectPackageManager, packagesFor, run };
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ import {
2
+ detectFramework,
3
+ detectPackageManager,
4
+ packagesFor,
5
+ run
6
+ } from "./chunk-F7EP27M3.js";
7
+ export {
8
+ detectFramework,
9
+ detectPackageManager,
10
+ packagesFor,
11
+ run
12
+ };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "create-easy-cms",
3
+ "version": "0.1.0",
4
+ "description": "Add Easy CMS to a Nuxt or Next.js project",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "create-easy-cms": "./dist/bin.js"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "engines": {
20
+ "node": ">=22.12"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/maritonx/easy-crm.git",
28
+ "directory": "packages/create-easy-cms"
29
+ },
30
+ "keywords": [
31
+ "easy-cms",
32
+ "create",
33
+ "nuxt",
34
+ "nextjs",
35
+ "cms"
36
+ ],
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "typecheck": "tsc --noEmit",
40
+ "test": "vitest run"
41
+ }
42
+ }