@easy-cms/nuxt 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,43 @@
1
+ # @easy-cms/nuxt
2
+
3
+ Nuxt 4 module for [Easy CMS](https://github.com/maritonx/easy-crm).
4
+
5
+ ```bash
6
+ pnpm add @easy-cms/nuxt @easy-cms/core @easy-cms/db-sqlite
7
+ ```
8
+
9
+ ```ts
10
+ // nuxt.config.ts
11
+ export default defineNuxtConfig({
12
+ modules: ['@easy-cms/nuxt'],
13
+ easyCms: {
14
+ // configPath: 'easy-cms.config.ts',
15
+ // trustProxy: false, // use X-Forwarded-For for login rate limiting
16
+ },
17
+ })
18
+ ```
19
+
20
+ With `easy-cms.config.ts` in the project root you get:
21
+
22
+ - **REST API** at `/api/cms` (collections, globals, uploads, login/logout/me); change it with `routes.api` in the Easy CMS config.
23
+ - **Admin UI** at `/admin` (`admin.path` in the config).
24
+ - **Local API** in server routes, typed from your config:
25
+
26
+ ```ts
27
+ // server/api/posts.get.ts
28
+ export default defineEventHandler(async (event) => {
29
+ const cms = await useEasyCMS()
30
+ const user = await useEasyCMSUser(event) // logged-in Easy CMS user or null
31
+ return cms.find('posts', { where: { status: { equals: 'published' } } })
32
+ })
33
+ ```
34
+
35
+ ## Development and production
36
+
37
+ - `nuxi dev` pushes schema changes to the database automatically.
38
+ - In production the schema must match the latest migration. Create migrations with
39
+ `npx easy-cms migrate:create <name>`, deploy the `easy-cms/migrations` folder, run
40
+ `npx easy-cms migrate`, then start the server **from the project root** (relative database
41
+ paths and the migrations folder resolve from the working directory).
42
+ - The module tells Nitro to ship files the database adapter loads dynamically (libsql's native
43
+ binary), so `.output` runs on its own. Build on the same OS/architecture you deploy to.
@@ -0,0 +1,11 @@
1
+ import { NuxtModule } from '@nuxt/schema';
2
+
3
+ interface ModuleOptions {
4
+ /** Path to the Easy CMS config, relative to the project root. Default: `easy-cms.config.ts` (or .mts/.js/.mjs). */
5
+ configPath?: string;
6
+ /** Use `X-Forwarded-For` for the client IP (login rate limiting). Only enable behind a proxy you control. */
7
+ trustProxy?: boolean;
8
+ }
9
+ declare const module$1: NuxtModule<ModuleOptions>;
10
+
11
+ export { type ModuleOptions, module$1 as default };
package/dist/module.js ADDED
@@ -0,0 +1,136 @@
1
+ // src/module.ts
2
+ import { existsSync, readFileSync } from "fs";
3
+ import { createRequire } from "module";
4
+ import { dirname, isAbsolute, join, relative, resolve } from "path";
5
+ import { renderShell, SECURITY_HEADERS, SHELL_FILE } from "@easy-cms/admin";
6
+ import {
7
+ CONFIG_FILE_NAMES,
8
+ DEFAULT_ADMIN_PATH,
9
+ DEFAULT_API_PATH,
10
+ importConfig
11
+ } from "@easy-cms/core";
12
+ import {
13
+ addServerHandler,
14
+ addServerImports,
15
+ addServerPlugin,
16
+ addTypeTemplate,
17
+ createResolver,
18
+ defineNuxtModule,
19
+ useLogger
20
+ } from "@nuxt/kit";
21
+ var SERVER = "#easy-cms-local-api";
22
+ var HANDLER = "#easy-cms-rest-handler";
23
+ var ADMIN_SHELL = "#easy-cms-admin-shell";
24
+ var module = defineNuxtModule({
25
+ meta: {
26
+ name: "@easy-cms/nuxt",
27
+ configKey: "easyCms",
28
+ compatibility: { nuxt: ">=4.0.0" }
29
+ },
30
+ defaults: {
31
+ trustProxy: false
32
+ },
33
+ async setup(options, nuxt) {
34
+ const logger = useLogger("easy-cms");
35
+ const { resolve: resolveRuntime } = createResolver(import.meta.url);
36
+ const rootDir = nuxt.options.rootDir;
37
+ const configPath = options.configPath ? isAbsolute(options.configPath) ? options.configPath : resolve(rootDir, options.configPath) : CONFIG_FILE_NAMES.map((name) => join(rootDir, name)).find((path) => existsSync(path));
38
+ if (!configPath || !existsSync(configPath)) {
39
+ logger.warn(
40
+ `No Easy CMS config found in ${rootDir}. Create easy-cms.config.ts (or run \`npx create-easy-cms\`). The module is disabled.`
41
+ );
42
+ return;
43
+ }
44
+ let rawConfig;
45
+ try {
46
+ rawConfig = await importConfig(configPath);
47
+ } catch (error) {
48
+ logger.warn(`Could not read ${configPath} at build time: ${error.message}`);
49
+ }
50
+ const apiPath = `/${(rawConfig?.routes?.api ?? DEFAULT_API_PATH).replace(/^\/+|\/+$/g, "")}`;
51
+ const adminPath = `/${(rawConfig?.admin?.path ?? DEFAULT_ADMIN_PATH).replace(/^\/+|\/+$/g, "")}`;
52
+ const slash = (path) => path.replace(/\\/g, "/");
53
+ const runtime = (file) => JSON.stringify(slash(resolveRuntime(`./runtime/${file}`)));
54
+ const config = JSON.stringify(slash(configPath));
55
+ const nitro = nuxt.options.nitro;
56
+ nitro.virtual ??= {};
57
+ Object.assign(nitro.virtual, {
58
+ [SERVER]: `import config from ${config}
59
+ import { getEasyCMS, getEasyCMSUser } from ${runtime("cms.js")}
60
+ export function useEasyCMS() { return getEasyCMS(config) }
61
+ export function useEasyCMSUser(event) { return getEasyCMSUser(config, event) }
62
+ `,
63
+ [HANDLER]: `import config from ${config}
64
+ import { createHandler } from ${runtime("handler.js")}
65
+ export default createHandler(config, ${JSON.stringify({ basePath: apiPath, trustProxy: options.trustProxy ?? false })})
66
+ `
67
+ });
68
+ addTypeTemplate(
69
+ {
70
+ filename: "types/easy-cms.d.ts",
71
+ getContents: ({ nuxt: n }) => {
72
+ const from = relative(join(n.options.buildDir, "types"), configPath).replace(/\\/g, "/").replace(/\.(m?ts|m?js)$/, "");
73
+ return `// Generated by @easy-cms/nuxt
74
+ declare module '${SERVER}' {
75
+ import type { AuthUser, EasyCMS } from '@easy-cms/core'
76
+ import type { H3Event } from 'h3'
77
+ type Config = typeof import('${from.startsWith(".") ? from : `./${from}`}').default
78
+
79
+ /** The Easy CMS Local API for this server. */
80
+ export function useEasyCMS(): Promise<EasyCMS<Config>>
81
+ /** The logged-in Easy CMS user for this request (session cookie or Bearer token), or null. */
82
+ export function useEasyCMSUser(event: H3Event): Promise<AuthUser | null>
83
+ }
84
+ `;
85
+ }
86
+ },
87
+ { nitro: true, nuxt: false }
88
+ );
89
+ addServerImports([
90
+ { name: "useEasyCMS", from: SERVER },
91
+ { name: "useEasyCMSUser", from: SERVER }
92
+ ]);
93
+ addServerHandler({ route: apiPath, handler: HANDLER });
94
+ addServerHandler({ route: `${apiPath}/**`, handler: HANDLER });
95
+ addServerPlugin(resolveRuntime("./runtime/plugin.js"));
96
+ const runtimeDir = resolveRuntime("./runtime");
97
+ nitro.externals = {
98
+ ...nitro.externals,
99
+ inline: [...nitro.externals?.inline ?? [], runtimeDir]
100
+ };
101
+ const adminPackage = createRequire(import.meta.url).resolve("@easy-cms/admin/package.json");
102
+ const adminAppDir = join(dirname(adminPackage), "dist/app");
103
+ const shell = renderShell(readFileSync(join(adminAppDir, SHELL_FILE), "utf8"), {
104
+ basePath: adminPath,
105
+ apiPath,
106
+ locale: rawConfig?.admin?.locale ?? "en"
107
+ });
108
+ nitro.virtual[ADMIN_SHELL] = `export const basePath = ${JSON.stringify(adminPath)}
109
+ export const html = ${JSON.stringify(shell)}
110
+ export const headers = ${JSON.stringify(SECURITY_HEADERS)}
111
+ `;
112
+ nitro.publicAssets = [
113
+ ...nitro.publicAssets ?? [],
114
+ // fallthrough: app routes (not files) continue to the shell handler below.
115
+ { dir: adminAppDir, baseURL: adminPath, maxAge: 60 * 60 * 24 * 365, fallthrough: true }
116
+ ];
117
+ const adminHandler = resolveRuntime("./runtime/admin.js");
118
+ addServerHandler({ route: adminPath, handler: adminHandler });
119
+ addServerHandler({ route: `${adminPath}/**`, handler: adminHandler });
120
+ const traceInclude = rawConfig?.db?.bundle?.traceInclude ?? [];
121
+ if (traceInclude.length > 0) {
122
+ const externals = nitro.externals ?? {};
123
+ nitro.externals = {
124
+ ...externals,
125
+ traceInclude: [...externals.traceInclude ?? [], ...traceInclude]
126
+ };
127
+ }
128
+ nuxt.options.ignore.push("**/*.db", "**/*.db-*", "easy-cms/migrations/**");
129
+ nuxt.options.watch.push(configPath);
130
+ logger.info(`Easy CMS admin at ${adminPath}, API at ${apiPath}`);
131
+ }
132
+ });
133
+ var module_default = module;
134
+ export {
135
+ module_default as default
136
+ };
@@ -0,0 +1,10 @@
1
+ import * as h3 from 'h3';
2
+
3
+ /**
4
+ * Serves the admin SPA's HTML for every route under the admin path.
5
+ * Assets are served by Nitro as public assets; a request that reaches this
6
+ * handler for /assets/* means the file does not exist.
7
+ */
8
+ declare const _default: h3.EventHandler<h3.EventHandlerRequest, string>;
9
+
10
+ export { _default as default };
@@ -0,0 +1,28 @@
1
+ import { defineEventHandler, getRequestURL, setResponseHeaders, setResponseStatus } from "h3";
2
+ import { basePath, headers, html } from "#easy-cms-admin-shell";
3
+ var admin_default = defineEventHandler((event) => {
4
+ const url = getRequestURL(event);
5
+ setResponseHeaders(event, headers);
6
+ if (event.method !== "GET" && event.method !== "HEAD") {
7
+ setResponseStatus(event, 405);
8
+ setResponseHeaders(event, { allow: "GET, HEAD" });
9
+ return "Method not allowed";
10
+ }
11
+ if (url.pathname === basePath) {
12
+ setResponseStatus(event, 308);
13
+ setResponseHeaders(event, { location: `${basePath}/${url.search}` });
14
+ return "";
15
+ }
16
+ if (url.pathname.startsWith(`${basePath}/assets/`)) {
17
+ setResponseStatus(event, 404);
18
+ return "Not found";
19
+ }
20
+ setResponseHeaders(event, {
21
+ "content-type": "text/html; charset=utf-8",
22
+ "cache-control": "no-store"
23
+ });
24
+ return html;
25
+ });
26
+ export {
27
+ admin_default as default
28
+ };
@@ -0,0 +1,12 @@
1
+ import { Config, EasyCMS, AuthUser } from '@easy-cms/core';
2
+ import { H3Event } from 'h3';
3
+
4
+ /**
5
+ * Returns the Easy CMS instance for this server, creating it on first use.
6
+ * When the config module is reloaded (dev HMR) the old instance is closed.
7
+ */
8
+ declare function getEasyCMS(config: Config): Promise<EasyCMS>;
9
+ /** The logged-in Easy CMS user for a request (session cookie or Bearer token), or `null`. */
10
+ declare function getEasyCMSUser(config: Config, event: H3Event): Promise<AuthUser | null>;
11
+
12
+ export { getEasyCMS, getEasyCMSUser };
@@ -0,0 +1,32 @@
1
+ import {
2
+ createEasyCMS,
3
+ readCookie,
4
+ SESSION_COOKIE
5
+ } from "@easy-cms/core";
6
+ import { getRequestHeader } from "h3";
7
+ const KEY = /* @__PURE__ */ Symbol.for("easy-cms.nuxt");
8
+ const store = globalThis;
9
+ function getEasyCMS(config) {
10
+ const cached = store[KEY];
11
+ if (cached?.config === config) return cached.promise;
12
+ if (cached) void cached.promise.then((cms) => cms.destroy()).catch(() => {
13
+ });
14
+ const promise = createEasyCMS(config);
15
+ store[KEY] = { config, promise };
16
+ promise.catch(() => {
17
+ if (store[KEY]?.promise === promise) delete store[KEY];
18
+ });
19
+ return promise;
20
+ }
21
+ async function getEasyCMSUser(config, event) {
22
+ const cms = await getEasyCMS(config);
23
+ const authorization = getRequestHeader(event, "authorization");
24
+ if (authorization?.startsWith("Bearer ")) return cms.auth.verify(authorization.slice(7).trim());
25
+ const cookie = getRequestHeader(event, "cookie");
26
+ const token = cookie ? readCookie(new Request("http://x", { headers: { cookie } }), SESSION_COOKIE) : void 0;
27
+ return cms.auth.verify(token);
28
+ }
29
+ export {
30
+ getEasyCMS,
31
+ getEasyCMSUser
32
+ };
@@ -0,0 +1,12 @@
1
+ import * as h3 from 'h3';
2
+ import { Config } from '@easy-cms/core';
3
+
4
+ interface HandlerOptions {
5
+ readonly basePath: string;
6
+ /** Trust `X-Forwarded-For` for the client IP (only behind a proxy you control). */
7
+ readonly trustProxy: boolean;
8
+ }
9
+ /** Mounts the Easy CMS REST API as a Nitro event handler. */
10
+ declare function createHandler(config: Config, options: HandlerOptions): h3.EventHandler<h3.EventHandlerRequest, Promise<void>>;
11
+
12
+ export { type HandlerOptions, createHandler };
@@ -0,0 +1,24 @@
1
+ import { createRestHandler } from "@easy-cms/core";
2
+ import { defineEventHandler, getRequestIP, sendWebResponse, toWebRequest } from "h3";
3
+ import { getEasyCMS } from "./cms.js";
4
+ function createHandler(config, options) {
5
+ const handlers = /* @__PURE__ */ new WeakMap();
6
+ const clientIps = /* @__PURE__ */ new WeakMap();
7
+ return defineEventHandler(async (event) => {
8
+ const cms = await getEasyCMS(config);
9
+ let handler = handlers.get(cms);
10
+ if (!handler) {
11
+ handler = createRestHandler(cms, {
12
+ basePath: options.basePath,
13
+ getClientIp: (r) => clientIps.get(r)
14
+ });
15
+ handlers.set(cms, handler);
16
+ }
17
+ const request = toWebRequest(event);
18
+ clientIps.set(request, getRequestIP(event, { xForwardedFor: options.trustProxy }));
19
+ return sendWebResponse(event, await handler(request));
20
+ });
21
+ }
22
+ export {
23
+ createHandler
24
+ };
@@ -0,0 +1,4 @@
1
+ /** Nitro plugin: connect (and push or verify the schema) at startup so problems show up immediately. */
2
+ declare function easyCmsStartup(): void;
3
+
4
+ export { easyCmsStartup as default };
@@ -0,0 +1,9 @@
1
+ import { useEasyCMS } from "#easy-cms-local-api";
2
+ function easyCmsStartup() {
3
+ useEasyCMS().catch((error) => {
4
+ console.error(`[easy-cms] ${error instanceof Error ? error.message : String(error)}`);
5
+ });
6
+ }
7
+ export {
8
+ easyCmsStartup as default
9
+ };
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@easy-cms/nuxt",
3
+ "version": "0.1.0",
4
+ "description": "Nuxt module for Easy CMS",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/module.d.ts",
10
+ "default": "./dist/module.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22.19"
19
+ },
20
+ "dependencies": {
21
+ "@nuxt/kit": "^4.5.2",
22
+ "h3": "^1.15.11",
23
+ "@easy-cms/admin": "^0.1.0"
24
+ },
25
+ "peerDependencies": {
26
+ "nuxt": "^4.0.0",
27
+ "@easy-cms/core": "^0.1.0"
28
+ },
29
+ "devDependencies": {
30
+ "@nuxt/schema": "^4.5.2",
31
+ "@nuxt/test-utils": "^4.3.2",
32
+ "nuxt": "^4.5.2",
33
+ "@easy-cms/core": "^0.1.0",
34
+ "@easy-cms/db-sqlite": "^0.1.0"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/maritonx/easy-crm.git",
42
+ "directory": "packages/nuxt"
43
+ },
44
+ "keywords": [
45
+ "easy-cms",
46
+ "nuxt",
47
+ "nuxt-module",
48
+ "cms",
49
+ "headless-cms"
50
+ ],
51
+ "scripts": {
52
+ "build": "tsup",
53
+ "typecheck": "tsc --noEmit",
54
+ "test": "vitest run"
55
+ }
56
+ }