@easy-cms/admin-build 0.0.0-stage → 1.51.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 Kanawut 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 CHANGED
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # @easy-cms/admin-build
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Builds [Easy CMS](https://easycms.dev) admin components written in **Vue**, **React** or **Svelte**
4
+ into the module the admin loads: one ES module, without imports, that defines a custom element per
5
+ component. It is what `npx easy-cms build:admin` runs.
6
+
7
+ ```bash
8
+ npm install -D @easy-cms/admin-build @vitejs/plugin-vue # or @vitejs/plugin-react, or @sveltejs/vite-plugin-svelte svelte
9
+ npx easy-cms build:admin # admin/components/* → admin/dist/components.js
10
+ ```
11
+
12
+ ```ts
13
+ // easy-cms.config.ts
14
+ admin: { modules: ['./admin/dist/components.js'] }
15
+ ```
16
+
17
+ Each component is named after its file (`acme-word-count.vue` → `<acme-word-count>`) and gets the
18
+ admin's properties as props, with `change`, `setField` and `navigate` (`AdminComponentProps` from
19
+ `@easy-cms/core`). See [Vue, React or Svelte](https://easycms.dev/guide/plugins#frameworks).
@@ -0,0 +1,35 @@
1
+ type Framework = 'vue' | 'react' | 'svelte';
2
+ /** Where components are looked for, and the module they make, without entries. */
3
+ declare const DEFAULT_DIR: string;
4
+ declare const DEFAULT_OUT: string;
5
+ declare class AdminBuildError extends Error {
6
+ name: string;
7
+ }
8
+ interface BuildAdminOptions {
9
+ /** The project root: components, the frameworks and their Vite plugins are found from it. */
10
+ readonly cwd: string;
11
+ /**
12
+ * Component files, each built into a module of its own. Default: every component in
13
+ * `admin/components/`, together in one module.
14
+ */
15
+ readonly entries?: readonly string[];
16
+ /**
17
+ * Where the module goes (one module), or the folder for them (several entries). Default
18
+ * `admin/dist/components.js`, or `admin/dist/<tag>.js` per entry.
19
+ */
20
+ readonly out?: string;
21
+ /** Build again when a file changes, until the process ends. */
22
+ readonly watch?: boolean;
23
+ readonly log?: (line: string) => void;
24
+ }
25
+ interface BuiltModule {
26
+ /** The module's file, absolute. */
27
+ readonly file: string;
28
+ /** The custom elements it defines. */
29
+ readonly tags: readonly string[];
30
+ }
31
+ /** Builds the modules; with `watch`, keeps building them as files change. */
32
+ declare function buildAdmin(options: BuildAdminOptions): Promise<BuiltModule[]>;
33
+
34
+ export { AdminBuildError, DEFAULT_DIR, DEFAULT_OUT, buildAdmin };
35
+ export type { BuildAdminOptions, BuiltModule, Framework };
package/dist/index.js ADDED
@@ -0,0 +1,342 @@
1
+ // src/index.ts
2
+ import { existsSync, readdirSync, readFileSync } from "fs";
3
+ import { mkdir, writeFile } from "fs/promises";
4
+ import { createRequire } from "module";
5
+ import { basename, dirname, extname, join, relative, resolve } from "path";
6
+ import { pathToFileURL } from "url";
7
+
8
+ // src/runtime.ts
9
+ var PROPS = [
10
+ "apiVersion",
11
+ "value",
12
+ "path",
13
+ "field",
14
+ "label",
15
+ "doc",
16
+ "collection",
17
+ "global",
18
+ "id",
19
+ "locale",
20
+ "uiLocale",
21
+ "readOnly",
22
+ "options",
23
+ "user",
24
+ "route",
25
+ "api"
26
+ ];
27
+ function defineRuntime() {
28
+ return `const PROPS = ${JSON.stringify(PROPS)}
29
+ // The module's CSS, put in each element's shadow root (filled in when the module is built).
30
+ const CSS = "__EASY_CMS_ADMIN_CSS__"
31
+
32
+ function define(tag, adapter) {
33
+ if (customElements.get(tag)) return
34
+ class AdminComponent extends HTMLElement {
35
+ #props = {}
36
+ #view
37
+ #queued = false
38
+ #target
39
+ #events
40
+ static {
41
+ for (const name of PROPS)
42
+ Object.defineProperty(this.prototype, name, {
43
+ configurable: true,
44
+ get() {
45
+ return this.#props[name]
46
+ },
47
+ set(value) {
48
+ this.#props[name] = value
49
+ this.#render()
50
+ },
51
+ })
52
+ }
53
+ constructor() {
54
+ super()
55
+ const root = this.attachShadow({ mode: 'open' })
56
+ if (CSS) {
57
+ const style = document.createElement('style')
58
+ style.textContent = CSS
59
+ root.append(style)
60
+ }
61
+ this.#target = document.createElement('div')
62
+ root.append(this.#target)
63
+ const send = (type, detail) => this.dispatchEvent(new CustomEvent(type, { detail }))
64
+ this.#events = {
65
+ change: (value) => send('change', value),
66
+ setField: (path, value) => send('set-field', { path, value }),
67
+ navigate: (path) => send('navigate', path),
68
+ }
69
+ }
70
+ connectedCallback() {
71
+ // Properties set before the element was defined shadow the setters: set them again.
72
+ for (const name of PROPS)
73
+ if (Object.hasOwn(this, name)) {
74
+ const value = this[name]
75
+ delete this[name]
76
+ this[name] = value
77
+ }
78
+ this.#view ??= adapter.mount(this.#target, this.#all())
79
+ }
80
+ disconnectedCallback() {
81
+ // Moved, not removed, when it is back by the next microtask.
82
+ queueMicrotask(() => {
83
+ if (this.isConnected || !this.#view) return
84
+ this.#view.unmount()
85
+ this.#view = undefined
86
+ })
87
+ }
88
+ #all() {
89
+ return { ...this.#props, ...this.#events }
90
+ }
91
+ #render() {
92
+ if (!this.#view || this.#queued) return
93
+ this.#queued = true
94
+ queueMicrotask(() => {
95
+ this.#queued = false
96
+ this.#view?.update(this.#all())
97
+ })
98
+ }
99
+ }
100
+ customElements.define(tag, AdminComponent)
101
+ }
102
+ `;
103
+ }
104
+ var FRAMEWORK_CODE = {
105
+ vue: `import { createApp as __createApp, h as __h, shallowReactive as __shallowReactive } from 'vue'
106
+ // Only the props the component declares: Vue would put the others on its root element as attributes.
107
+ function __declared(component, props) {
108
+ const declared = component.props
109
+ const names = Array.isArray(declared) ? declared : Object.keys(declared ?? {})
110
+ return Object.fromEntries(names.filter((n) => n in props).map((n) => [n, props[n]]))
111
+ }
112
+ const vue = (component) => ({
113
+ mount(target, props) {
114
+ const state = __shallowReactive(__declared(component, props))
115
+ const app = __createApp({ render: () => __h(component, state) })
116
+ app.mount(target)
117
+ return {
118
+ update(next) {
119
+ Object.assign(state, __declared(component, next))
120
+ },
121
+ unmount() {
122
+ app.unmount()
123
+ },
124
+ }
125
+ },
126
+ })`,
127
+ react: `import { createElement as __createElement } from 'react'
128
+ import { createRoot as __createRoot } from 'react-dom/client'
129
+ const react = (component) => ({
130
+ mount(target, props) {
131
+ const root = __createRoot(target)
132
+ root.render(__createElement(component, props))
133
+ return {
134
+ update(next) {
135
+ root.render(__createElement(component, next))
136
+ },
137
+ unmount() {
138
+ root.unmount()
139
+ },
140
+ }
141
+ },
142
+ })`
143
+ };
144
+ var SVELTE_ADAPTER = `import { mount, unmount } from 'svelte'
145
+
146
+ export const svelte = (component) => ({
147
+ mount(target, initial) {
148
+ const props = $state({ ...initial })
149
+ const app = mount(component, { target, props })
150
+ return {
151
+ update(next) {
152
+ Object.assign(props, next)
153
+ },
154
+ unmount() {
155
+ unmount(app)
156
+ },
157
+ }
158
+ },
159
+ })
160
+ `;
161
+
162
+ // src/index.ts
163
+ var EXTENSIONS = {
164
+ ".vue": "vue",
165
+ ".tsx": "react",
166
+ ".jsx": "react",
167
+ ".svelte": "svelte"
168
+ };
169
+ var NEEDS = {
170
+ vue: { package: "vue", min: [3, 5], plugin: "@vitejs/plugin-vue" },
171
+ react: { package: "react", min: [18, 0], plugin: "@vitejs/plugin-react" },
172
+ svelte: { package: "svelte", min: [5, 0], plugin: "@sveltejs/vite-plugin-svelte" }
173
+ };
174
+ var DEFAULT_DIR = join("admin", "components");
175
+ var DEFAULT_OUT = join("admin", "dist", "components.js");
176
+ var AdminBuildError = class extends Error {
177
+ name = "AdminBuildError";
178
+ };
179
+ var TAG = /^[a-z][a-z0-9]*(-[a-z0-9]+)+$/;
180
+ async function buildAdmin(options) {
181
+ const cwd = resolve(options.cwd);
182
+ const log = options.log ?? (() => {
183
+ });
184
+ const groups = plan(cwd, options);
185
+ const require2 = createRequire(join(cwd, "package.json"));
186
+ const { build } = await import("vite");
187
+ const built = [];
188
+ for (const group of groups) {
189
+ const frameworks = [...new Set(group.components.map((c) => c.framework))];
190
+ for (const framework of frameworks) checkVersion(require2, framework);
191
+ const plugins = await Promise.all(frameworks.map((f) => frameworkPlugin(require2, f)));
192
+ const entry = await writeEntry(cwd, group.out, group.components);
193
+ await build({
194
+ root: cwd,
195
+ configFile: false,
196
+ logLevel: "warn",
197
+ plugins: [...plugins, inlineCss()],
198
+ // React reads it; nothing replaces it in a library build otherwise.
199
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
200
+ build: {
201
+ lib: { entry, formats: ["es"], fileName: () => basename(group.out) },
202
+ outDir: dirname(group.out),
203
+ emptyOutDir: false,
204
+ copyPublicDir: false,
205
+ cssCodeSplit: false,
206
+ rolldownOptions: { output: { codeSplitting: false } },
207
+ ...options.watch ? { watch: {} } : {}
208
+ }
209
+ });
210
+ built.push({ file: group.out, tags: group.components.map((c) => c.tag) });
211
+ log(
212
+ `${options.watch ? "Watching" : "Built"} ${relative(cwd, group.out)} (${group.components.map((c) => `<${c.tag}>`).join(", ")})`
213
+ );
214
+ }
215
+ return built;
216
+ }
217
+ function plan(cwd, options) {
218
+ if (!options.entries || options.entries.length === 0) {
219
+ const dir2 = join(cwd, DEFAULT_DIR);
220
+ const files = existsSync(dir2) ? readdirSync(dir2).filter((f) => extname(f) in EXTENSIONS).sort().map((f) => join(dir2, f)) : [];
221
+ if (files.length === 0)
222
+ throw new AdminBuildError(
223
+ `No components in ${DEFAULT_DIR}/: add one, e.g. ${join(DEFAULT_DIR, "acme-color-picker.vue")} (the file name is the tag), or name the files to build.`
224
+ );
225
+ return [{ out: resolve(cwd, options.out ?? DEFAULT_OUT), components: files.map(component) }];
226
+ }
227
+ const components = options.entries.map((e) => component(resolve(cwd, e)));
228
+ if (components.length === 1 && options.out)
229
+ return [{ out: resolve(cwd, options.out), components }];
230
+ const dir = resolve(cwd, options.out ?? dirname(DEFAULT_OUT));
231
+ return components.map((c) => ({ out: join(dir, `${c.tag}.js`), components: [c] }));
232
+ }
233
+ function component(file) {
234
+ if (!existsSync(file)) throw new AdminBuildError(`${file} not found.`);
235
+ const framework = EXTENSIONS[extname(file)];
236
+ if (!framework)
237
+ throw new AdminBuildError(
238
+ `${file}: a component is a .vue, .tsx, .jsx or .svelte file (got ${extname(file) || "no extension"}).`
239
+ );
240
+ const tag = basename(file, extname(file));
241
+ if (!TAG.test(tag))
242
+ throw new AdminBuildError(
243
+ `${basename(file)}: the file name is the element's tag, so it must be lowercase with a "-", e.g. acme-${tag.toLowerCase().replace(/[^a-z0-9]+/g, "-") || "component"}${extname(file)}.`
244
+ );
245
+ return { file, tag, framework };
246
+ }
247
+ function checkVersion(require2, framework) {
248
+ const need = NEEDS[framework];
249
+ let version;
250
+ try {
251
+ version = JSON.parse(readFileSync(require2.resolve(`${need.package}/package.json`), "utf8")).version;
252
+ } catch {
253
+ throw new AdminBuildError(
254
+ `${framework} components need ${need.package} ${need.min.join(".")} or later and ${need.plugin} in the project: npm install -D ${need.package} ${need.plugin}${framework === "react" ? " react-dom" : ""}`
255
+ );
256
+ }
257
+ const [major = 0, minor = 0] = version.split(".").map(Number);
258
+ if (major < need.min[0] || major === need.min[0] && minor < need.min[1])
259
+ throw new AdminBuildError(
260
+ `${need.package} ${version} is installed; ${framework} admin components need ${need.min.join(".")} or later.`
261
+ );
262
+ }
263
+ async function frameworkPlugin(require2, framework) {
264
+ const need = NEEDS[framework];
265
+ let file;
266
+ try {
267
+ file = require2.resolve(need.plugin);
268
+ } catch {
269
+ throw new AdminBuildError(
270
+ `${framework} components need ${need.plugin} in the project: npm install -D ${need.plugin}`
271
+ );
272
+ }
273
+ const mod = await import(pathToFileURL(file).href);
274
+ const create = framework === "svelte" ? mod.svelte : mod.default;
275
+ return create(framework === "vue" ? await vueOptions(require2, file) : void 0);
276
+ }
277
+ async function vueOptions(require2, pluginFile) {
278
+ let ts;
279
+ try {
280
+ ts = await import(pathToFileURL(require2.resolve("typescript")).href).then((m) => m.default ?? m);
281
+ } catch {
282
+ return void 0;
283
+ }
284
+ const compilerFile = createRequire(pluginFile).resolve("vue/compiler-sfc");
285
+ const compiler = await import(pathToFileURL(compilerFile).href);
286
+ compiler.registerTS(() => ts);
287
+ return { compiler };
288
+ }
289
+ async function writeEntry(cwd, out, components) {
290
+ const dir = join(
291
+ cwd,
292
+ "node_modules",
293
+ ".easy-cms",
294
+ "admin-build",
295
+ relative(cwd, out).replace(/[^a-zA-Z0-9]+/g, "_")
296
+ );
297
+ await mkdir(dir, { recursive: true });
298
+ const frameworks = [...new Set(components.map((c) => c.framework))];
299
+ const lines = [defineRuntime()];
300
+ for (const framework of frameworks) {
301
+ if (framework === "svelte") {
302
+ await writeFile(join(dir, "svelte-adapter.svelte.js"), SVELTE_ADAPTER);
303
+ lines.push(`import { svelte } from './svelte-adapter.svelte.js'`);
304
+ } else lines.push(FRAMEWORK_CODE[framework]);
305
+ }
306
+ components.forEach((c, i) => {
307
+ lines.push(`import C${i} from ${JSON.stringify(c.file)}`);
308
+ lines.push(`define(${JSON.stringify(c.tag)}, ${c.framework}(C${i}))`);
309
+ });
310
+ const entry = join(dir, "entry.js");
311
+ await writeFile(entry, `${lines.join("\n")}
312
+ `);
313
+ return entry;
314
+ }
315
+ var CSS_PLACEHOLDER = "__EASY_CMS_ADMIN_CSS__";
316
+ function inlineCss() {
317
+ return {
318
+ name: "easy-cms:inline-css",
319
+ enforce: "post",
320
+ generateBundle(_, bundle) {
321
+ let css = "";
322
+ for (const [name, item] of Object.entries(bundle)) {
323
+ if (item.type === "asset" && name.endsWith(".css")) {
324
+ css += typeof item.source === "string" ? item.source : new TextDecoder().decode(item.source);
325
+ delete bundle[name];
326
+ }
327
+ }
328
+ for (const item of Object.values(bundle)) {
329
+ if (item.type === "chunk" && item.code) {
330
+ const literal = JSON.stringify(css);
331
+ item.code = item.code.replaceAll(`"${CSS_PLACEHOLDER}"`, literal).replaceAll(`'${CSS_PLACEHOLDER}'`, literal).replaceAll(`\`${CSS_PLACEHOLDER}\``, literal);
332
+ }
333
+ }
334
+ }
335
+ };
336
+ }
337
+ export {
338
+ AdminBuildError,
339
+ DEFAULT_DIR,
340
+ DEFAULT_OUT,
341
+ buildAdmin
342
+ };
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "@easy-cms/admin-build",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.51.0",
4
+ "description": "Builds Easy CMS admin components written in Vue, React or Svelte into the admin's custom-element modules (easy-cms build:admin)",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "dependencies": {
19
+ "vite": "^8.3.1"
20
+ },
21
+ "peerDependencies": {
22
+ "@sveltejs/vite-plugin-svelte": "^7.0.0",
23
+ "@vitejs/plugin-react": "^6.0.0",
24
+ "@vitejs/plugin-vue": "^6.0.0",
25
+ "react": ">=18.0.0",
26
+ "react-dom": ">=18.0.0",
27
+ "svelte": "^5.0.0",
28
+ "vue": "^3.5.0"
29
+ },
30
+ "peerDependenciesMeta": {
31
+ "@sveltejs/vite-plugin-svelte": {
32
+ "optional": true
33
+ },
34
+ "@vitejs/plugin-react": {
35
+ "optional": true
36
+ },
37
+ "@vitejs/plugin-vue": {
38
+ "optional": true
39
+ },
40
+ "react": {
41
+ "optional": true
42
+ },
43
+ "react-dom": {
44
+ "optional": true
45
+ },
46
+ "svelte": {
47
+ "optional": true
48
+ },
49
+ "vue": {
50
+ "optional": true
51
+ }
52
+ },
53
+ "devDependencies": {
54
+ "@sveltejs/vite-plugin-svelte": "^7.3.1",
55
+ "@vitejs/plugin-react": "^6.3.0",
56
+ "@vitejs/plugin-vue": "^6.0.9",
57
+ "happy-dom": "^21.0.4",
58
+ "react": "^19.3.0",
59
+ "react-dom": "^19.3.0",
60
+ "svelte": "^5.57.3",
61
+ "typescript": "~6.0.3",
62
+ "vue": "^3.5.43",
63
+ "@easy-cms/core": "^1.51.0"
64
+ },
65
+ "engines": {
66
+ "node": ">=22.12"
67
+ },
68
+ "publishConfig": {
69
+ "access": "public"
70
+ },
71
+ "repository": {
72
+ "type": "git",
73
+ "url": "git+https://github.com/maritonx/easy-cms.git",
74
+ "directory": "packages/admin-build"
75
+ },
76
+ "keywords": [
77
+ "easy-cms",
78
+ "admin",
79
+ "web-components",
80
+ "vite",
81
+ "vue",
82
+ "react",
83
+ "svelte"
84
+ ],
85
+ "scripts": {
86
+ "build": "tsup",
87
+ "typecheck": "tsc --noEmit",
88
+ "test": "vitest run"
89
+ }
6
90
  }