znode-plugin 0.1.6 → 0.1.7

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.
@@ -1,1083 +1,1191 @@
1
- #!/usr/bin/env node
2
- // znode-plugin: build, pack and install Znode runtime packages (themes, plugins, widgets, content).
3
- //
4
- // znode build <packageDir|manifest.json> build into <packageDir>/dist
5
- // znode pack <packageDir|manifest.json> build, then zip it as
6
- // <packageDir>/releases/<name>-<version>.zpkg.zip
7
- // znode install <zip|packageDir> [storeDir] validate and install into the store's plugin
8
- // directory (default: RUNTIME_PLUGINS_DIR);
9
- // the registry entry keeps its settings and stores
10
- // znode create <theme|plugin|widget|content> <name> [dir]
11
- // a starter package that builds as it is
12
- // (default dir ./<name>)
13
- // znode check <packageDir> marketplace review: metadata, permissions against
14
- // the code, settings, size, server-render format
15
- // znode deploy <packageDir> [storeDir] pack, then install into the store's plugin directory
16
- // znode dev <packageDir> [storeDir] deploy, then again on every change under src/ or to the manifest
17
- // znode link-store <storeRepoDir> [dir] the store's real types: writes tsconfig.store.json (see README)
18
- // znode eject [<Name>] [--force] in a package folder: list the store components that can be ejected, or
19
- // copy one into src/components/ and register it in its slot
20
- // (<Name> is the component or its slot name)
21
- // znode add-slot <Component> <area.name> [--dry-run] [--file <f>] a slot around a store component, written into
22
- // the linked store's source (base developers; review and commit there)
23
- //
24
- // A package is a folder with znode-package.json (README.md shows a whole project, as create-znode-plugin makes it):
25
- // {
26
- // "name": "artifi", "version": "1.0.0", "kind": "plugin" | "theme" | "widget" | "content", "apiVersion": 1,
27
- // "label": "...", "publisher": "...", "description": "...", "parent": "<theme>", (parent: themes only)
28
- // "build": { "server": "src/server.ts", "browser": "src/browser.tsx" }, (TypeScript entry points)
29
- // "styles": ["src/styles/*.css"], "assets": ["src/assets/fonts/*.woff2"], "messages": "src/i18n/labels.json",
30
- // "pages": { "/": "src/pages/home.json" }, "widgets": ["HeroBanner"],
31
- // code imports Next.js as an app does: next/image, next/link, next/navigation, next/font/google, react
32
- // (next-imports.mjs: the store's own modules at runtime; Google fonts downloaded into the package when it builds)
33
- // "overrides": { "/api/place-order": "place-order" }, (store BFF routes it takes over, by one of its routes)
34
- // "serverPages": ["/my-page"], (whole pages at new URLs, rendered by its server part's serverPages)
35
- // "dedupeStyles": true, (styles: drop the rules the store already has; STORE_URL = a page of a running store)
36
- // "settingsSchema": { "websiteId": { "type": "string", "required": true, "browser": true, "label": "..." },
37
- // "banner": { "type": "string", "browser": true, "attribute": "StoreBannerText" } },
38
- // (attribute: the value comes from a Znode global attribute, "Code" for the store's, or
39
- // { "code": "...", "levels": ["store", "account", "user"] }; the most specific level wins)
40
- // marketplace: "license", "keywords", "homepage", "compatibility": { "webstore": ">=10.0.0" },
41
- // "permissions": ["routes", "cartHooks", "overrides", "znodeApi", "externalNetwork", "uploads"] (what it does beyond UI;
42
- // "uploads": its routes take files, multipart/form-data up to RUNTIME_PLUGIN_UPLOAD_BYTES)
43
- // "sandbox": true (its server part runs in a separate, permission-limited Node process: routes and overrides only)
44
- // }
45
- import fs from "node:fs";
46
- import path from "node:path";
47
- import { execFileSync, spawnSync } from "node:child_process";
48
- import { createRequire } from "node:module";
49
- import { fileURLToPath, pathToFileURL } from "node:url";
50
- import vm from "node:vm";
51
- import { TEMPLATES } from "./templates.mjs";
52
-
53
- const HERE = path.dirname(fileURLToPath(import.meta.url));
54
- const MANIFEST = "znode-package.json";
55
- // the build tools (TypeScript, rollup, adm-zip, postcss): this package's own dependencies, wherever npm put them
56
- // (ZNODE_TOOLS: a node_modules folder to use instead)
57
- const require = process.env.ZNODE_TOOLS ? createRequire(path.join(process.env.ZNODE_TOOLS, "noop.js")) : createRequire(import.meta.url);
58
- // a dependency's folder (its package.json's), found from what it resolves to
59
- function packageDir(name) {
60
- for (let dir = path.dirname(require.resolve(name)); dir !== path.dirname(dir); dir = path.dirname(dir)) {
61
- const file = path.join(dir, "package.json");
62
- if (fs.existsSync(file) && JSON.parse(fs.readFileSync(file, "utf8")).name === name) return dir;
63
- }
64
- throw new Error(`znode-plugin: ${name} is not installed`);
65
- }
66
- const TSC = () => path.join(packageDir("typescript"), "bin", "tsc");
67
- const ROLLUP = () => path.join(packageDir("rollup"), "dist", "bin", "rollup");
68
- const AdmZip = require("adm-zip");
69
-
70
- const API_VERSION = 1;
71
- const KINDS = ["theme", "plugin", "widget", "content"];
72
- const NAME = /^[a-z0-9][a-z0-9-]{1,48}$/;
73
- const VERSION = /^\d+\.\d+\.\d+(-[0-9a-z.-]+)?$/i;
74
- const SERVED = new Set([".mjs", ".map", ".css", ".woff2", ".woff", ".ttf", ".otf", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".json"]);
75
- const MAX_BYTES = 10 * 1024 * 1024;
76
- const SETTING_TYPES = ["string", "number", "boolean", "list", "json", "object", "array"];
77
- const ATTRIBUTE_LEVELS = ["store", "account", "user"];
78
- const ATTRIBUTE_CODE = /^[A-Za-z][A-Za-z0-9_]{1,99}$/;
79
- const PERMISSIONS = ["routes", "cartHooks", "overrides", "znodeApi", "externalNetwork", "uploads"];
80
-
81
- const fail = (message) => {
82
- console.error(`znode-package: ${message}`);
83
- process.exit(1);
84
- };
85
- const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
86
- const glob = (dir, pattern) => {
87
- const folder = path.join(dir, path.dirname(pattern));
88
- const re = new RegExp(
89
- `^${path
90
- .basename(pattern)
91
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
92
- .replace(/\*/g, ".*")}$`
93
- );
94
- return fs.existsSync(folder)
95
- ? fs
96
- .readdirSync(folder)
97
- .filter((name) => re.test(name))
98
- .map((name) => path.join(folder, name))
99
- : [];
100
- };
101
-
102
- function validateManifest(manifest, where) {
103
- if (!NAME.test(manifest.name || "")) fail(`${where}: name must be lowercase letters, digits and dashes`);
104
- if (!VERSION.test(manifest.version || "")) fail(`${where}: version must be semver (1.2.3)`);
105
- if (!KINDS.includes(manifest.kind)) fail(`${where}: kind must be one of ${KINDS.join(", ")}`);
106
- if (manifest.apiVersion !== API_VERSION) fail(`${where}: apiVersion ${manifest.apiVersion} isn't supported (this store runs ${API_VERSION})`);
107
- if (manifest.parent && manifest.kind !== "theme") fail(`${where}: only a theme has a parent`);
108
- // whole pages its server part renders (IRuntimePlugin.serverPages), at new lowercase URLs the store doesn't use
109
- if (manifest.serverPages !== undefined) {
110
- if (!Array.isArray(manifest.serverPages)) fail(`${where}: serverPages must be a list of paths ("/my-page")`);
111
- // the source manifest names the entry (build.server), the built one the file (files.server)
112
- if (manifest.serverPages.length && !manifest.build?.server && !manifest.files?.server) fail(`${where}: serverPages need a server part (build.server)`);
113
- for (const page of manifest.serverPages) {
114
- if (!/^\/[a-z0-9][a-z0-9-]*(\/[a-z0-9][a-z0-9-]*)*$/.test(String(page))) fail(`${where}: serverPages "${page}" must be a lowercase path like /my-page`);
115
- if (/^\/(api|runtime-page|_next|login|signup|account|cart|checkout|search|product|category|404|error|maintenance)(\/|$)/.test(page)) fail(`${where}: serverPages "${page}" is a store route`);
116
- }
117
- }
118
- // store BFF routes the package takes over: "/api/<path>" -> one of its own routes
119
- for (const [route, target] of Object.entries(manifest.overrides || {})) {
120
- if (!/^\/api\/[A-Za-z0-9/_-]+$/.test(route) || /^\/api\/extensions(\/|$)/.test(route)) fail(`${where}: override "${route}" must be a store route under /api/`);
121
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(String(target))) fail(`${where}: override "${route}" must name one of the package's routes`);
122
- }
123
- for (const [key, field] of Object.entries(manifest.settingsSchema || {})) {
124
- if (field?.type !== undefined && !SETTING_TYPES.includes(field.type)) fail(`${where}: setting "${key}" has type "${field.type}" (one of ${SETTING_TYPES.join(", ")})`);
125
- const attribute = field?.attribute;
126
- if (attribute === undefined) continue;
127
- const code = typeof attribute === "string" ? attribute : attribute?.code;
128
- if (!ATTRIBUTE_CODE.test(String(code || ""))) fail(`${where}: setting "${key}" names attribute "${code}" (letters, digits and _, as Znode attribute codes)`);
129
- const levels = typeof attribute === "string" ? ["store"] : attribute.levels || ["store"];
130
- if (!Array.isArray(levels) || !levels.length || levels.some((level) => !ATTRIBUTE_LEVELS.includes(level))) {
131
- fail(`${where}: setting "${key}" attribute levels must be some of ${ATTRIBUTE_LEVELS.join(", ")}`);
132
- }
133
- }
134
- if (manifest.sandbox !== undefined && typeof manifest.sandbox !== "boolean") fail(`${where}: sandbox must be true or false`);
135
- if (manifest.permissions !== undefined && (!Array.isArray(manifest.permissions) || manifest.permissions.some((item) => !PERMISSIONS.includes(item)))) {
136
- fail(`${where}: permissions must be some of ${PERMISSIONS.join(", ")}`);
137
- }
138
- }
139
-
140
- // ---- build: TypeScript entry points -> one ES module each (tsc + rollup), plus styles, assets, labels, pages ----
141
- // a package folder (its znode-package.json) or one of several manifests in a folder (<name>.znode-package.json)
142
- function resolvePackage(target) {
143
- const isFile = fs.statSync(target).isFile();
144
- const dir = isFile ? path.dirname(target) : target;
145
- const manifestFile = isFile ? target : path.join(dir, MANIFEST);
146
- return { dir, manifestFile, outName: path.basename(manifestFile) === MANIFEST ? "dist" : `dist-${path.basename(manifestFile, `.${MANIFEST}`)}` };
147
- }
148
-
149
- // The package's tsconfig check. tsc also checks the store files the package imports; their errors are the store's, not
150
- // the package's: listed as warnings. An error in the package's own files stops the build.
151
- function typeCheck(dir, tsconfigFile) {
152
- let output = "";
153
- try {
154
- execFileSync(process.execPath, [TSC(), "-p", tsconfigFile, "--noEmit", "--pretty", "false"], {
155
- cwd: dir,
156
- encoding: "utf8",
157
- stdio: ["ignore", "pipe", "pipe"],
158
- });
159
- return;
160
- } catch (error) {
161
- output = `${error.stdout || ""}${error.stderr || ""}`;
162
- }
163
- // one entry per error: "file(line,col): error TSnnnn: message" and its indented continuation lines
164
- const errors = output.split(/\r?\n(?=\S)/).filter((entry) => /^.+?\(\d+,\d+\): error TS\d+:/.test(entry));
165
- if (!errors.length) fail(`tsconfig check failed:\n${output}`);
166
- // inside the package folder: a relative path that does not climb out (on Windows a file on another drive comes back
167
- // absolute from path.relative, which is outside too)
168
- const inPackage = (entry) => {
169
- const relative = path.relative(dir, path.resolve(dir, entry.slice(0, entry.indexOf("("))));
170
- return !relative.startsWith("..") && !path.isAbsolute(relative);
171
- };
172
- const own = errors.filter(inPackage);
173
- const store = errors.filter((entry) => !inPackage(entry));
174
- if (store.length) console.log(`warning ${store.length} type error(s) in store files the package imports (the store's to fix):\n ${store.join("\n ")}`);
175
- if (own.length) fail(`type errors in the package:\n ${own.join("\n ")}`);
176
- }
177
-
178
- // every .ts / .tsx under srcRoot compiled to .js under outRoot, one file at a time and without resolving imports (the
179
- // tsconfig check has done the types): types removed, JSX as Next.js compiles it (react/jsx-runtime)
180
- function transpileSources(srcRoot, outRoot) {
181
- const ts = require("typescript");
182
- const walk = (folder) =>
183
- fs.readdirSync(folder, { withFileTypes: true }).flatMap((item) => {
184
- const file = path.join(folder, item.name);
185
- if (item.isDirectory()) return walk(file);
186
- return /\.tsx?$/.test(item.name) && !item.name.endsWith(".d.ts") ? [file] : [];
187
- });
188
- for (const file of walk(srcRoot)) {
189
- const { outputText } = ts.transpileModule(fs.readFileSync(file, "utf8"), {
190
- fileName: file,
191
- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ES2022, jsx: ts.JsxEmit.ReactJSX, jsxImportSource: "react" },
192
- });
193
- const target = path.join(outRoot, path.relative(srcRoot, file)).replace(/\.tsx?$/, ".js");
194
- fs.mkdirSync(path.dirname(target), { recursive: true });
195
- fs.writeFileSync(target, outputText);
196
- }
197
- }
198
-
199
- // The store the package is linked to (tsconfig.store.json, written by link-store): its root, its @znode paths and its
200
- // Generated Store Module Registry (packages/extensions/store-module-registry.json), for the package's store imports
201
- function linkedStore(dir) {
202
- const file = path.join(dir, "tsconfig.store.json");
203
- if (!fs.existsSync(file)) return null;
204
- const { compilerOptions = {} } = readJson(file);
205
- if (!compilerOptions.baseUrl) return null;
206
- const root = path.resolve(dir, compilerOptions.baseUrl);
207
- const registryFile = path.join(root, "packages/extensions/store-module-registry.json");
208
- const registry = fs.existsSync(registryFile) ? readJson(registryFile).modules : null;
209
- return { root, paths: compilerOptions.paths || {}, registry };
210
- }
211
-
212
- function build(target) {
213
- const { dir, manifestFile, outName } = resolvePackage(target);
214
- const manifest = readJson(manifestFile);
215
- validateManifest(manifest, path.basename(manifestFile));
216
- const out = path.join(dir, outName);
217
- fs.rmSync(out, { recursive: true, force: true });
218
- fs.mkdirSync(out, { recursive: true });
219
- const tmp = path.join(dir, ".build");
220
- const files = {};
221
- const prefix = `${manifest.name}-${manifest.version}`;
222
- // next/font/google fonts built into the package (next-imports.mjs): their files and @font-face CSS
223
- const fonts = [];
224
- // the store modules its browser part imports (Generated Store Module Registry keys), for the store to load first
225
- const storeImports = [];
226
- const store = linkedStore(dir);
227
- // A package with its own tsconfig.json (extending the store's tsconfig.base.json) is checked against the store's real
228
- // types (every @znode alias, no declarations to write), then compiled file by file without type information, JSX as
229
- // Next.js does (react/jsx-runtime: the store's). Without one, the package compiles as before (tsc, JSX factory h).
230
- const tsconfigFile = path.join(dir, "tsconfig.json");
231
- const projectMode = fs.existsSync(tsconfigFile);
232
- if (projectMode && Object.values(manifest.build || {}).length) typeCheck(dir, tsconfigFile);
233
-
234
- for (const part of ["server", "browser"]) {
235
- const entry = manifest.build?.[part];
236
- if (!entry) continue;
237
- fs.rmSync(tmp, { recursive: true, force: true });
238
- if (projectMode) transpileSources(path.dirname(path.join(dir, entry)), tmp);
239
- else execFileSync(
240
- process.execPath,
241
- [
242
- TSC(),
243
- "--target",
244
- "es2022",
245
- "--module",
246
- "es2022",
247
- "--moduleResolution",
248
- "bundler",
249
- "--lib",
250
- "es2022,dom",
251
- "--skipLibCheck",
252
- // import React from "react", as the store's own components do
253
- "--allowSyntheticDefaultImports",
254
- "--jsx",
255
- "react",
256
- "--jsxFactory",
257
- "h",
258
- "--jsxFragmentFactory",
259
- "Fragment",
260
- "--outDir",
261
- tmp,
262
- path.join(dir, entry),
263
- ],
264
- { stdio: "inherit" }
265
- );
266
- const compiled = path.join(tmp, path.basename(entry).replace(/\.tsx?$/, ".js"));
267
- const target = `${prefix}.${part}.mjs`;
268
- // rollup with the Next.js imports plugin (next-imports.mjs), from a config file: the plugin downloads fonts, which
269
- // is async, in rollup's own process; what it built comes back in fonts.json
270
- const config = path.join(tmp, "rollup.config.mjs");
271
- const fontsFile = path.join(tmp, "fonts.json");
272
- const storeImportsFile = path.join(tmp, "store-imports.json");
273
- fs.writeFileSync(
274
- config,
275
- [
276
- `import fs from "node:fs";`,
277
- `import { znodeNext } from ${JSON.stringify(pathToFileURL(path.join(HERE, "next-imports.mjs")).href)};`,
278
- `const fonts = [];`,
279
- `const storeImports = [];`,
280
- `const store = ${JSON.stringify(store)};`,
281
- `if (store?.registry) store.registry = new Set(store.registry);`,
282
- `export default {`,
283
- ` input: ${JSON.stringify(compiled)},`,
284
- ` output: { file: ${JSON.stringify(path.join(out, target))}, format: "es", sourcemap: true },`,
285
- ` plugins: [`,
286
- ` znodeNext({ part: ${JSON.stringify(part)}, prefix: ${JSON.stringify(prefix)}, outDir: ${JSON.stringify(out)}, fonts, store, storeImports }),`,
287
- ` { name: "fonts-out", writeBundle() { fs.writeFileSync(${JSON.stringify(fontsFile)}, JSON.stringify(fonts)); fs.writeFileSync(${JSON.stringify(storeImportsFile)}, JSON.stringify(storeImports)); } },`,
288
- ` ],`,
289
- `};`,
290
- ].join("\n")
291
- );
292
- execFileSync(process.execPath, [ROLLUP(), "--config", config, "--silent"], { stdio: "inherit" });
293
- if (fs.existsSync(fontsFile)) fonts.push(...JSON.parse(fs.readFileSync(fontsFile, "utf8")));
294
- if (fs.existsSync(storeImportsFile)) storeImports.push(...JSON.parse(fs.readFileSync(storeImportsFile, "utf8")));
295
- files[part] = target;
296
- }
297
- fs.rmSync(tmp, { recursive: true, force: true });
298
-
299
- // styles: concatenated into one stylesheet, after the fonts next/font/google built; assets (fonts, images) keep their
300
- // names, which the stylesheet refers to
301
- if (manifest.styles?.length || fonts.length) {
302
- const css = [
303
- ...fonts.map((font) => font.css),
304
- ...(manifest.styles || []).flatMap((pattern) => glob(dir, pattern)).map((file) => fs.readFileSync(file, "utf8")),
305
- ].join("\n");
306
- files.styles = [`${prefix}.css`];
307
- fs.writeFileSync(path.join(out, files.styles[0]), css);
308
- // rules the store's own stylesheets already have, loaded again later, would beat its responsive variants
309
- if (manifest.dedupeStyles) {
310
- const target = path.join(out, files.styles[0]);
311
- execFileSync(process.execPath, [path.join(HERE, "css-dedupe.mjs"), target, process.env.STORE_URL || "http://staplespromo.localhost:3000/", target], { stdio: "inherit" });
312
- }
313
- }
314
- files.assets = (manifest.assets || [])
315
- .flatMap((pattern) => glob(dir, pattern))
316
- .map((file) => {
317
- fs.copyFileSync(file, path.join(out, path.basename(file)));
318
- return path.basename(file);
319
- })
320
- // the font files next/font/google downloaded, already in dist
321
- .concat(fonts.flatMap((font) => font.files));
322
- if (manifest.messages) {
323
- files.messages = `${prefix}.labels.json`;
324
- fs.copyFileSync(path.join(dir, manifest.messages), path.join(out, files.messages));
325
- }
326
- if (manifest.pages) {
327
- files.pages = Object.fromEntries(
328
- Object.entries(manifest.pages).map(([route, file], index) => {
329
- const target = `${prefix}.page${index}.json`;
330
- fs.copyFileSync(path.join(dir, file), path.join(out, target));
331
- return [route, target];
332
- })
333
- );
334
- }
335
- const { build: _build, styles: _styles, assets: _assets, dedupeStyles: _dedupe, ...rest } = manifest;
336
- fs.writeFileSync(path.join(out, MANIFEST), JSON.stringify({ ...rest, files, ...(storeImports.length ? { storeImports: [...new Set(storeImports)].sort() } : {}) }, null, 2) + "\n");
337
- console.log(`built ${manifest.kind} ${manifest.name}@${manifest.version}: ${fs.readdirSync(out).length} files`);
338
- return { manifest, out };
339
- }
340
-
341
- function pack(target) {
342
- const { manifest, out } = build(target);
343
- const { dir } = resolvePackage(target);
344
- const zip = new AdmZip();
345
- for (const name of fs.readdirSync(out)) zip.addLocalFile(path.join(out, name));
346
- fs.mkdirSync(path.join(dir, "releases"), { recursive: true });
347
- const file = path.join(dir, "releases", `${manifest.name}-${manifest.version}.zpkg.zip`);
348
- zip.writeZip(file);
349
- console.log(`packed ${path.basename(file)} (${fs.statSync(file).size} bytes)`);
350
- }
351
-
352
- // ---- install: validate, copy into the plugin directory, upsert the registry entry -------------------------------
353
- // Installs into one folder can run at the same time (several pipelines, an admin upload): each takes the folder's lock
354
- // (an atomic mkdir) for the read-change-write of plugins.json, writes it atomically (a temp file renamed over it, so the
355
- // running webstore never reads half a file) and keeps the previous registry in .history/ (the last HISTORY_KEEP).
356
- const LOCK_WAIT_MS = 60000;
357
- const LOCK_STALE_MS = 120000;
358
- const HISTORY_KEEP = 50;
359
- const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
360
-
361
- function lockRegistry(storeDir) {
362
- fs.mkdirSync(storeDir, { recursive: true });
363
- const lock = path.join(storeDir, ".plugins.lock");
364
- const deadline = Date.now() + LOCK_WAIT_MS;
365
- for (;;) {
366
- try {
367
- fs.mkdirSync(lock);
368
- break;
369
- } catch (error) {
370
- if (error.code !== "EEXIST") throw error;
371
- // a lock left by a crashed install
372
- try {
373
- if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) fs.rmSync(lock, { recursive: true, force: true });
374
- } catch {
375
- // removed meanwhile
376
- }
377
- if (Date.now() > deadline) fail(`the registry in ${storeDir} is locked by another install (remove ${lock} if none is running)`);
378
- sleep(25 + Math.floor(Math.random() * 50));
379
- }
380
- }
381
- const release = () => fs.rmSync(lock, { recursive: true, force: true });
382
- process.on("exit", release);
383
- return () => {
384
- release();
385
- process.off("exit", release);
386
- };
387
- }
388
-
389
- function writeRegistry(registryFile, registry) {
390
- const dir = path.dirname(registryFile);
391
- if (fs.existsSync(registryFile)) {
392
- const history = path.join(dir, ".history");
393
- fs.mkdirSync(history, { recursive: true });
394
- fs.copyFileSync(registryFile, path.join(history, `plugins-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}.json`));
395
- const old = fs
396
- .readdirSync(history)
397
- .filter((name) => name.startsWith("plugins-"))
398
- .sort();
399
- for (const name of old.slice(0, Math.max(0, old.length - HISTORY_KEEP))) fs.rmSync(path.join(history, name), { force: true });
400
- }
401
- const temp = `${registryFile}.tmp-${process.pid}`;
402
- fs.writeFileSync(temp, JSON.stringify(registry, null, 2) + "\n");
403
- fs.renameSync(temp, registryFile);
404
- }
405
- const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
406
-
407
- // the store's settings over the package defaults; an object setting (labels, panels) keeps the store's values and
408
- // gains the keys a new version adds
409
- function mergeSettings(defaults, previous) {
410
- const merged = { ...defaults, ...previous };
411
- for (const [key, value] of Object.entries(defaults)) {
412
- if (isPlainObject(value) && isPlainObject(previous[key])) merged[key] = { ...value, ...previous[key] };
413
- }
414
- return merged;
415
- }
416
-
417
- function install(source, storeDir) {
418
- let entries;
419
- if (fs.statSync(source).isDirectory()) {
420
- // a package folder's build output (dist; package in packages built before the dist folder)
421
- const built = ["dist", "package"].map((name) => path.join(source, name)).find((dir) => fs.existsSync(path.join(dir, MANIFEST)));
422
- const dir = built || source;
423
- entries = fs.readdirSync(dir).map((name) => ({ name, data: fs.readFileSync(path.join(dir, name)) }));
424
- } else {
425
- entries = new AdmZip(source)
426
- .getEntries()
427
- .filter((entry) => !entry.isDirectory)
428
- .map((entry) => ({ name: entry.entryName, data: entry.getData() }));
429
- }
430
- const manifestEntry = entries.find((entry) => entry.name === "znode-package.json");
431
- if (!manifestEntry) fail("no znode-package.json in the package");
432
- const manifest = JSON.parse(manifestEntry.data.toString("utf8"));
433
- validateManifest(manifest, "package");
434
-
435
- const total = entries.reduce((sum, entry) => sum + entry.data.length, 0);
436
- if (total > MAX_BYTES) fail(`package is ${total} bytes; the limit is ${MAX_BYTES}`);
437
- const files = entries.filter((entry) => entry.name !== "znode-package.json");
438
- for (const entry of files) {
439
- if (entry.name !== path.basename(entry.name)) fail(`"${entry.name}": a package is flat, no folders`);
440
- if (!SERVED.has(path.extname(entry.name).toLowerCase())) fail(`"${entry.name}": file type not allowed`);
441
- }
442
- const has = (name) => files.some((entry) => entry.name === name);
443
- const referenced = [
444
- manifest.files?.server,
445
- manifest.files?.browser,
446
- manifest.files?.messages,
447
- ...(manifest.files?.styles || []),
448
- ...Object.values(manifest.files?.pages || {}),
449
- ].filter(Boolean);
450
- for (const name of referenced) if (!has(name)) fail(`znode-package.json names "${name}", which isn't in the package`);
451
-
452
- const registryFile = path.join(storeDir, "plugins.json");
453
- const unlock = lockRegistry(storeDir);
454
- const registry = fs.existsSync(registryFile) ? readJson(registryFile) : { plugins: [] };
455
- // a package never replaces a file another installed package uses
456
- const owners = new Map();
457
- for (const item of registry.plugins) {
458
- if (item.name === manifest.name) continue;
459
- for (const name of [item.file, item.browser, item.messages, ...(item.styles || []), ...Object.values(item.pages || {})]) if (name) owners.set(name, item.name);
460
- }
461
- for (const entry of files) if (owners.has(entry.name)) fail(`"${entry.name}" belongs to package ${owners.get(entry.name)}`);
462
-
463
- fs.mkdirSync(storeDir, { recursive: true });
464
- for (const entry of files) fs.writeFileSync(path.join(storeDir, entry.name), entry.data);
465
-
466
- const previous = registry.plugins.find((item) => item.name === manifest.name);
467
- const defaults = Object.fromEntries(
468
- Object.entries(manifest.settingsSchema || {})
469
- .filter(([, field]) => field.default !== undefined)
470
- .map(([key, field]) => [key, field.default])
471
- );
472
- const entry = {
473
- name: manifest.name,
474
- kind: manifest.kind === "widget" ? "plugin" : manifest.kind,
475
- version: manifest.version,
476
- label: manifest.label,
477
- publisher: manifest.publisher,
478
- ...(manifest.parent ? { parent: manifest.parent } : {}),
479
- ...(manifest.files?.server ? { file: manifest.files.server } : {}),
480
- ...(manifest.files?.browser ? { browser: manifest.files.browser } : {}),
481
- ...(manifest.files?.styles?.length ? { styles: manifest.files.styles } : {}),
482
- ...(manifest.files?.messages ? { messages: manifest.files.messages } : {}),
483
- ...(manifest.files?.pages ? { pages: manifest.files.pages } : {}),
484
- ...(manifest.widgets?.length ? { widgets: manifest.widgets } : {}),
485
- // the store modules its browser bundle imports: the store loads them first (Generated Store Module Registry)
486
- ...(Array.isArray(manifest.storeImports) && manifest.storeImports.length ? { storeImports: manifest.storeImports.map(String) } : {}),
487
- ...(manifest.overrides ? { overrides: manifest.overrides } : {}),
488
- ...(manifest.serverPages?.length ? { serverPages: manifest.serverPages } : {}),
489
- ...(manifest.sandbox === true ? { sandbox: true } : {}),
490
- // the webstore accepts files (multipart) only for a package that declares them
491
- ...((manifest.permissions || []).includes("uploads") ? { uploads: true } : {}),
492
- ...(manifest.settingsSchema ? { settingsSchema: manifest.settingsSchema } : {}),
493
- // where it runs and its settings are the store owner's: an upgrade keeps them; a new package starts switched off
494
- enabled: previous ? previous.enabled : false,
495
- stores: previous ? previous.stores : [],
496
- settings: mergeSettings(defaults, previous?.settings || {}),
497
- };
498
- if (previous) registry.plugins[registry.plugins.indexOf(previous)] = entry;
499
- else registry.plugins.push(entry);
500
- writeRegistry(registryFile, registry);
501
- // the replaced version's files (an upgrade's old bundles and stylesheets) leave the plugin directory
502
- const kept = new Set(files.map((file) => file.name));
503
- for (const name of [previous?.file, previous?.browser, previous?.messages, ...(previous?.styles || []), ...Object.values(previous?.pages || {})]) {
504
- if (name && !kept.has(name) && name === path.basename(name)) fs.rmSync(path.join(storeDir, name), { force: true });
505
- }
506
-
507
- unlock();
508
-
509
- const missing = Object.entries(manifest.settingsSchema || {}).filter(([key, field]) => field.required && (entry.settings[key] === undefined || entry.settings[key] === ""));
510
- console.log(
511
- `installed ${manifest.kind} ${manifest.name}@${manifest.version}${previous ? ` (was ${previous.version || "unversioned"})` : ""}: ${files.length} files, ${entry.enabled ? "enabled" : "disabled"} for ${JSON.stringify(entry.stores)}`
512
- );
513
- if (missing.length) console.log(` settings to fill in before enabling: ${missing.map(([key]) => key).join(", ")}`);
514
- }
515
-
516
- // ---- create: a starter package of a kind (templates.mjs), with the API typings next to its sources ---------------
517
- function create(kind, name, dir) {
518
- if (!TEMPLATES[kind]) fail(`kind must be one of ${Object.keys(TEMPLATES).join(", ")}`);
519
- if (!NAME.test(name || "")) fail("name must be lowercase letters, digits and dashes (2 to 49)");
520
- const target = path.resolve(dir || path.join(process.cwd(), name));
521
- if (fs.existsSync(target) && fs.readdirSync(target).length) fail(`${target} exists and is not empty`);
522
- for (const [file, content] of Object.entries(TEMPLATES[kind](name))) {
523
- const full = path.join(target, file);
524
- fs.mkdirSync(path.dirname(full), { recursive: true });
525
- fs.writeFileSync(full, typeof content === "string" ? content : JSON.stringify(content, null, 2) + "\n");
526
- }
527
- if (kind !== "content") fs.copyFileSync(path.join(HERE, "..", "types", "extension-api.d.ts"), path.join(target, "src", "extension-api.d.ts"));
528
- console.log(`created ${kind} ${name} in ${target}`);
529
- console.log(" next: fill in label, publisher and description in znode-package.json, then run its build-and-upload.sh");
530
- }
531
-
532
- // ---- check: what a marketplace review looks at, from the package's own files ------------------------------------
533
- const HOOK_NAMES = ["onCartChanged", "beforeAddToCart", "afterAddToCart", "mapCartItems"];
534
-
535
- // the code an entry pulls in: the entry and the files it imports by relative path, followed (a package's server and
536
- // browser parts share a folder, so a folder read would mix them); type-only imports are skipped
537
- function sourceOf(dir, entry) {
538
- if (!entry) return "";
539
- const seen = new Set();
540
- const sources = [];
541
- const visit = (file) => {
542
- if (seen.has(file) || !fs.existsSync(file)) return;
543
- seen.add(file);
544
- const code = fs.readFileSync(file, "utf8");
545
- sources.push(code);
546
- for (const [, typeOnly, spec] of code.matchAll(/\bimport\s+(type\s+)?[^;]*?from\s+["'](\.[^"']+)["']/g)) {
547
- if (typeOnly) continue;
548
- const base = path.resolve(path.dirname(file), spec).replace(/\.(m?js)$/, "");
549
- const found = [".ts", ".tsx", ".js", ".mjs", "/index.ts", "/index.tsx"].map((ext) => base + ext).find((candidate) => fs.existsSync(candidate));
550
- if (found) visit(found);
551
- }
552
- };
553
- visit(path.join(dir, entry));
554
- return sources.join("\n");
555
- }
556
-
557
- // the server renders a browser bundle in this format from one compiled copy for all stores
558
- // (packages/extensions/src/server-instances.ts); any other is imported once per store, and Node keeps every copy
559
- function serverRenderFormat(code) {
560
- const match = /\bexport\s*(?:\{\s*([A-Za-z_$][\w$]*)\s+as\s+default\s*,?\s*\}|default\s+([A-Za-z_$][\w$]*))\s*;?\s*(?:\/\/#\s*sourceMappingURL=\S*\s*)?$/.exec(code);
561
- if (!match || /(^|[^\w$.])import\s*\(/.test(code.slice(0, match.index))) return false;
562
- try {
563
- new vm.Script(`(function () {\n"use strict";\n${code.slice(0, match.index)}\nreturn ${match[1] || match[2]};\n})`);
564
- return true;
565
- } catch {
566
- return false;
567
- }
568
- }
569
-
570
- function check(target) {
571
- const { dir, manifestFile } = resolvePackage(target);
572
- const manifest = readJson(manifestFile);
573
- validateManifest(manifest, path.basename(manifestFile));
574
- const errors = [];
575
- const warnings = [];
576
-
577
- // the listing
578
- for (const key of ["label", "publisher", "description"]) if (!String(manifest[key] || "").trim()) errors.push(`"${key}" is missing (the marketplace shows it)`);
579
- if (/describe what it does/i.test(manifest.description || "") || manifest.publisher === "Your company") errors.push("the starter's publisher or description is still in place");
580
- else if (String(manifest.description || "").length < 30) warnings.push('"description" is short: say what it does for the store');
581
- for (const key of ["license", "compatibility"]) if (!manifest[key]) warnings.push(`"${key}" is missing`);
582
-
583
- // permissions against the code
584
- const server = sourceOf(dir, manifest.build?.server);
585
- const browser = sourceOf(dir, manifest.build?.browser);
586
- const used = new Set();
587
- if (/\broutes\s*[:=,}]/.test(server)) used.add("routes");
588
- if (HOOK_NAMES.some((hook) => new RegExp(`\\b${hook}\\b`).test(server))) used.add("cartHooks");
589
- if (Object.keys(manifest.overrides || {}).length) used.add("overrides");
590
- if (/\bznode\s*\(/.test(server)) used.add("znodeApi");
591
- if (/\bfetch\s*\(|\bhttps?\.request\s*\(/.test(server)) used.add("externalNetwork");
592
- if (/\.files\b/.test(server)) used.add("uploads");
593
- const declared = new Set(manifest.permissions || []);
594
- for (const item of used) if (!declared.has(item)) errors.push(`uses "${item}" without declaring it in "permissions"`);
595
- for (const item of declared) if (!used.has(item)) warnings.push(`declares "${item}" but no code uses it (the review asks why)`);
596
- if (/\beval\s*\(|new Function\s*\(/.test(server + browser)) errors.push("uses eval or new Function");
597
- if (/document\.cookie/.test(browser)) warnings.push("reads cookies in the browser: keep secrets on the server (routes)");
598
-
599
- // settings
600
- for (const [key, field] of Object.entries(manifest.settingsSchema || {})) {
601
- if (!field.label) warnings.push(`setting "${key}" has no label (the admin shows it)`);
602
- if (field.required && field.default !== undefined) warnings.push(`setting "${key}" is required but has a default`);
603
- if (field.browser && /secret|password|token|api_?key/i.test(key)) errors.push(`setting "${key}" looks secret but is sent to the browser ("browser": true)`);
604
- }
605
- if (manifest.kind === "theme" && !Object.values(manifest.settingsSchema || {}).some((field) => field.attribute)) {
606
- warnings.push("no setting is bound to a Znode attribute: per-store branding then needs a registry change per store");
607
- }
608
-
609
- // the built files (pack first)
610
- const out = path.join(dir, "dist");
611
- if (fs.existsSync(out)) {
612
- let total = 0;
613
- for (const name of fs.readdirSync(out)) {
614
- const size = fs.statSync(path.join(out, name)).size;
615
- total += size;
616
- if (name.endsWith(".browser.mjs")) {
617
- if (size > 512 * 1024) warnings.push(`${name} is ${Math.round(size / 1024)} KB: every page of the store loads it`);
618
- if (!serverRenderFormat(fs.readFileSync(path.join(out, name), "utf8")))
619
- warnings.push(`${name} is not in the server-render format (no imports, one default export): the server keeps a copy per store`);
620
- }
621
- if (name.endsWith(".css") && size > 200 * 1024) warnings.push(`${name} is ${Math.round(size / 1024)} KB`);
622
- }
623
- if (total > MAX_BYTES) errors.push(`dist is ${Math.round(total / 1048576)} MB (limit 10 MB)`);
624
- } else warnings.push("not built yet: pack it to check sizes and the server-render format");
625
-
626
- for (const item of errors) console.log(`error ${item}`);
627
- for (const item of warnings) console.log(`warning ${item}`);
628
- console.log(`check ${manifest.name}@${manifest.version}: ${errors.length} errors, ${warnings.length} warnings`);
629
- if (errors.length) process.exit(1);
630
- }
631
-
632
- // ---- project commands: deploy, dev, link-store ------------------------------------------------------------------
633
-
634
- const needStore = (storeDir) =>
635
- storeDir || fail("needs the store's plugin folder: pass it after the package, or set RUNTIME_PLUGINS_DIR");
636
-
637
- // pack, then install the zip it made into the store's plugin folder
638
- function deploy(target, storeDir) {
639
- pack(target);
640
- const { dir, manifestFile } = resolvePackage(target);
641
- const manifest = readJson(manifestFile);
642
- install(path.join(dir, "releases", `${manifest.name}-${manifest.version}.zpkg.zip`), storeDir);
643
- }
644
-
645
- // deploy now, then again whenever the package's sources or manifest change; the store picks a new file up on the next
646
- // request (it reloads a package when its files change), so a page refresh shows the change
647
- function dev(target, storeDir) {
648
- const { dir } = resolvePackage(target);
649
- const self = fileURLToPath(import.meta.url);
650
- const run = () => spawnSync(process.execPath, [self, "deploy", dir, storeDir], { stdio: "inherit" });
651
- run();
652
- let timer = null;
653
- const changed = (file) => {
654
- if (!file || /(^|[\\/])(dist|releases|\.build|node_modules)([\\/]|$)/.test(String(file))) return;
655
- clearTimeout(timer);
656
- timer = setTimeout(() => {
657
- console.log(`znode dev: ${file} changed, deploying`);
658
- run();
659
- }, 300);
660
- };
661
- fs.watch(path.join(dir, "src"), { recursive: true }, (_event, file) => changed(file && path.join("src", file)));
662
- fs.watch(dir, (_event, file) => file === MANIFEST && changed(file));
663
- console.log(`znode dev: watching ${dir} (Ctrl+C to stop)`);
664
- }
665
-
666
- // the store's real types for the editor and the build check: tsconfig.store.json (git-ignored, per machine) is this
667
- // package's preset plus the store repo's aliases (every @znode path of its tsconfig.base.json, from the store's folder).
668
- // Only the aliases are taken: the store's own options (its rootDir among them) would refuse a project kept elsewhere.
669
- function linkStore(storeRepo, project = ".") {
670
- const base = path.resolve(storeRepo, "tsconfig.base.json");
671
- if (!fs.existsSync(base)) fail(`${base} not found: pass the store repo's folder (the one with tsconfig.base.json)`);
672
- const ts = require("typescript");
673
- const { config, error } = ts.readConfigFile(base, ts.sys.readFile);
674
- if (error) fail(`${base}: ${ts.flattenDiagnosticMessageText(error.messageText, "\n")}`);
675
- const options = config.compilerOptions || {};
676
- const toSlash = (value) => value.split(path.sep).join("/");
677
- const file = path.resolve(project, "tsconfig.store.json");
678
- const linked = {
679
- extends: "znode-plugin/tsconfig.json",
680
- compilerOptions: { baseUrl: toSlash(path.resolve(path.dirname(base), options.baseUrl || ".")), paths: options.paths || {} },
681
- };
682
- fs.writeFileSync(file, JSON.stringify(linked, null, 2) + "\n");
683
- console.log(`linked ${file} to ${base} (${Object.keys(linked.compilerOptions.paths).length} store aliases)`);
684
- }
685
-
686
- // ---- eject: a store component copied into the package, in place of the store's, through its slot ----------------
687
- // A store component that has a runtime slot whose children are the component itself (withRuntimeWrapper(Wrapper, Base,
688
- // "Name") where it is defined) can be taken over by a package: `znode eject <Name>` copies its file from the linked store
689
- // into src/components/<Name>.tsx (relative imports turned into the store's @znode aliases, the runtime wrapper removed so
690
- // the copy is the plain component) and registers it in src/browser.tsx under the slot, so the store renders the copy
691
- // instead of its own. `znode eject` lists the components that can be ejected.
692
- const EJECT_SLOTS = {
693
- RuntimeProductBasicInfo: "product.basicInfo",
694
- RuntimeProductCard: "product.card",
695
- RuntimeProductImage: "product.image",
696
- RuntimeAddToCart: "product.addToCart",
697
- RuntimeProductVariants: "product.variants",
698
- RuntimeAddToCartNotification: "addToCart.notification",
699
- RuntimeCheckoutAddress: "checkout.address",
700
- RuntimeShippingOptions: "checkout.shippingOptions",
701
- };
702
-
703
- // the slot each store wrapper renders: every `export function Runtime<X>` in packages/extensions/src/slots with the first
704
- // <RuntimeSlot name="…"> in its body (so a slot added with `znode add-slot` is ejectable with no SDK release); the
705
- // hand-kept EJECT_SLOTS above fill in for a store that predates this
706
- function storeWrapperSlots(root) {
707
- const slots = { ...EJECT_SLOTS };
708
- const dir = path.join(root, "packages/extensions/src/slots");
709
- if (!fs.existsSync(dir)) return slots;
710
- for (const entry of fs.readdirSync(dir)) {
711
- if (!/\.tsx$/.test(entry)) continue;
712
- const text = fs.readFileSync(path.join(dir, entry), "utf8");
713
- const starts = [...text.matchAll(/export\s+function\s+(Runtime\w+)/g)];
714
- starts.forEach((m, i) => {
715
- const body = text.slice(m.index, i + 1 < starts.length ? starts[i + 1].index : undefined);
716
- // the first slot that is handed the component as children (<RuntimeSlot name="…">…{children}…</RuntimeSlot>); a
717
- // layout slot (self-closing, the base rendered hidden beside it) cannot take an ejected copy
718
- for (const open of body.matchAll(/<RuntimeSlot\s+name=["']([\w.]+)["']/g)) {
719
- const rest = body.slice(open.index + open[0].length);
720
- const close = rest.indexOf("</RuntimeSlot>");
721
- const next = rest.indexOf("<RuntimeSlot");
722
- if (close >= 0 && (next < 0 || close < next) && /\{\s*children\s*\}/.test(rest.slice(0, close))) {
723
- if (!slots[m[1]]) slots[m[1]] = open[1];
724
- break;
725
- }
726
- }
727
- });
728
- }
729
- return slots;
730
- }
731
-
732
- // every withRuntimeWrapper(<Wrapper>, <Base>, "<Name>") in the store's base components, with the slot it fills
733
- function ejectableComponents(root) {
734
- const EJECT_SLOTS = storeWrapperSlots(root);
735
- const found = [];
736
- const walk = (dir) => {
737
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
738
- const file = path.join(dir, entry.name);
739
- if (entry.isDirectory()) {
740
- if (entry.name !== "node_modules") walk(file);
741
- } else if (/\.tsx?$/.test(entry.name)) {
742
- const text = fs.readFileSync(file, "utf8");
743
- for (const m of text.matchAll(/withRuntimeWrapper\(\s*(\w+)\s*,\s*(\w+)\s*,\s*"(\w+)"\s*\)/g)) {
744
- if (EJECT_SLOTS[m[1]]) found.push({ name: m[3], wrapper: m[1], base: m[2], slot: EJECT_SLOTS[m[1]], file });
745
- }
746
- }
747
- }
748
- };
749
- for (const dir of ["packages/base-components/src", "packages/page-builder/src"]) if (fs.existsSync(path.join(root, dir))) walk(path.join(root, dir));
750
- return found.sort((a, b) => a.name.localeCompare(b.name));
751
- }
752
-
753
- // a store file's import path as the package can import it: the store alias that maps to that file, without extension
754
- function storeAlias(store, absolute) {
755
- const target = absolute.split(path.sep).join("/").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "");
756
- let best = null;
757
- const norm = (value) => path.resolve(store.root, value).split(path.sep).join("/").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "");
758
- // an exact alias for this very module ("@znode/base-components/stores": [".../stores/index.ts"]) wins
759
- for (const [alias, targets] of Object.entries(store.paths)) {
760
- if (!alias.endsWith("/*") && targets.some((pattern) => norm(pattern) === target)) return alias;
761
- }
762
- for (const [alias, targets] of Object.entries(store.paths)) {
763
- if (!alias.endsWith("/*")) continue;
764
- for (const pattern of targets) {
765
- const prefix = path.resolve(store.root, pattern.replace(/\*$/, "")).split(path.sep).join("/").replace(/\/$/, "") + "/";
766
- if (target.startsWith(prefix) && (!best || prefix.length > best.prefix.length)) best = { prefix, alias: alias.slice(0, -1) };
767
- }
768
- }
769
- return best ? best.alias + target.slice(best.prefix.length) : null;
770
- }
771
-
772
- function eject(name, force) {
773
- const project = path.resolve(".");
774
- if (!fs.existsSync(path.join(project, MANIFEST))) fail(`run znode eject in a package folder (the one with ${MANIFEST})`);
775
- const store = linkedStore(project);
776
- if (!store) fail("the package is not linked to a store: npm run link-store -- <store repo>");
777
- const components = ejectableComponents(store.root);
778
- if (!name || name === "--list") {
779
- console.log("Store components a package can eject (the slot that takes your copy):\n");
780
- for (const c of components) console.log(` ${c.name.padEnd(34)} ${c.slot.padEnd(26)} ${path.relative(store.root, c.file).split(path.sep).join("/")}`);
781
- console.log("\nznode eject <Name> copies one into src/components/ and registers it in src/browser.tsx");
782
- return;
783
- }
784
- const c = components.find((item) => item.name.toLowerCase() === name.toLowerCase() || item.slot.toLowerCase() === name.toLowerCase());
785
- if (!c)
786
- fail(
787
- `${name} cannot be ejected: no store component with that name or slot hands itself over to a slot.\n` +
788
- ` znode eject lists the ones that can (component name or slot name both work)\n` +
789
- ` znode add-slot ${/^[A-Z]/.test(name) ? name : "<Component>"} <area.name> adds a slot for a store component (edits the linked store's source)`
790
- );
791
-
792
- const out = path.join(project, "src", "components", `${c.name}.tsx`);
793
- if (fs.existsSync(out) && !force) fail(`${path.relative(project, out)} exists: delete it or run znode eject ${c.name} --force`);
794
- const warnings = [];
795
- let text = fs.readFileSync(c.file, "utf8");
796
- // relative imports become the store's aliases (the package lives elsewhere); a style file stays the store's
797
- text = text.replace(/((?:from|import)\s*\(?\s*["'])(\.{1,2}\/[^"']+)(["'])/g, (whole, before, spec, after) => {
798
- const absolute = path.resolve(path.dirname(c.file), spec);
799
- if (/\.(s?css)$/.test(spec)) {
800
- warnings.push(`style import ${spec}: kept out of the copy; the store's own stylesheet is loaded where the store renders it, add your CSS to src/styles/`);
801
- return `${before}${spec}${after}`;
802
- }
803
- const alias = storeAlias(store, fs.existsSync(absolute) || /\.\w+$/.test(spec) ? absolute : absolute);
804
- if (!alias) {
805
- warnings.push(`import ${spec}: no store alias for it; change it by hand`);
806
- return whole;
807
- }
808
- return `${before}${alias}${after}`;
809
- });
810
- // drop scss/css side-effect imports that point into the store (they cannot be bundled into a package)
811
- text = text.replace(/^import\s+["'][^"']+\.s?css["'];?\s*\n/gm, "");
812
- // the copy is the plain component: no runtime wrapper (the slot is what puts it in place)
813
- text = text.replace(new RegExp(`^.*import\\s*\\{[^}]*\\b(?:withRuntimeWrapper|${c.wrapper})\\b[^}]*\\}\\s*from\\s*["'][^"']+["'];?\\s*\\n`, "gm"), "");
814
- text = text.replace(new RegExp(`withRuntimeWrapper\\(\\s*${c.wrapper}\\s*,\\s*${c.base}\\s*,\\s*"${c.name}"\\s*\\)`), c.base);
815
- const storeFile = path.relative(store.root, c.file).split(path.sep).join("/");
816
- const header = `// Ejected from the store: ${storeFile} (${new Date().toISOString().slice(0, 10)}), with \`znode eject ${c.name}\`.\n// The store renders this copy instead of its own through the slot "${c.slot}" (src/browser.tsx). It is yours now: the\n// store's later changes to ${c.name} do not reach it, so compare it with the store's file after a store upgrade.\n`;
817
- text = text.startsWith('"use client"') || text.startsWith("'use client'") ? text.replace(/^(["']use client["'];?\s*\n)/, `$1${header}`) : header + text;
818
- fs.mkdirSync(path.dirname(out), { recursive: true });
819
- fs.writeFileSync(out, text);
820
- console.log(`ejected ${c.name} -> ${path.relative(project, out)}`);
821
-
822
- // npm packages the copy imports that this package does not have (react, next and the store's @znode modules come from
823
- // the store): install them at the store's version, so the types match and the build finds them
824
- const PROVIDED = /^(react|react-dom|next|next-intl|@znode)(\/|$)/;
825
- const storePackage = (() => {
826
- try {
827
- return readJson(path.join(store.root, "package.json"));
828
- } catch {
829
- return {};
830
- }
831
- })();
832
- const storeDeps = { ...(storePackage.devDependencies || {}), ...(storePackage.dependencies || {}) };
833
- const missing = new Map();
834
- for (const m of text.matchAll(/(?:from|import)\s*\(?\s*["']([^."'/][^"']*)["']/g)) {
835
- const spec = m[1];
836
- if (PROVIDED.test(spec)) continue;
837
- const pkg = spec.startsWith("@") ? spec.split("/").slice(0, 2).join("/") : spec.split("/")[0];
838
- try {
839
- createRequire(path.join(project, "package.json")).resolve(`${pkg}/package.json`);
840
- } catch {
841
- missing.set(pkg, storeDeps[pkg] ? `${pkg}@${storeDeps[pkg].replace(/^[\^~]/, "")}` : pkg);
842
- }
843
- }
844
- if (missing.size) {
845
- console.log(`\nThe copy imports npm packages this package does not have (bundled into the package when it builds):`);
846
- console.log(` npm install ${[...missing.values()].join(" ")}`);
847
- }
848
-
849
- // register the copy under the slot in src/browser.tsx
850
- const browser = path.join(project, "src", "browser.tsx");
851
- const exportsDefault = new RegExp(`export\\s+default\\s+${c.name}\\b`).test(text) || new RegExp(`export\\s+default\\s+${c.base}\\b`).test(text);
852
- const local = `Ejected${c.name}`;
853
- const importLine = exportsDefault
854
- ? `import ${local} from "./components/${c.name}.js";`
855
- : `import { ${c.name} as ${local} } from "./components/${c.name}.js";`;
856
- if (!fs.existsSync(browser)) {
857
- warnings.push(`src/browser.tsx not found: register it yourself: ${importLine} and slots: { "${c.slot}": ${local} }`);
858
- } else {
859
- let source = fs.readFileSync(browser, "utf8");
860
- if (new RegExp(`["']${c.slot.replace(".", "\\.")}["']\\s*:`).test(source)) {
861
- warnings.push(`src/browser.tsx already fills "${c.slot}": point it at ${local} (${importLine}) yourself`);
862
- } else if (/slots\s*:\s*\{/.test(source)) {
863
- if (!source.includes(importLine)) {
864
- const imports = [...source.matchAll(/^import .*;\s*$/gm)];
865
- const at = imports.length ? imports[imports.length - 1].index + imports[imports.length - 1][0].length : 0;
866
- source = source.slice(0, at) + `\n${importLine}` + source.slice(at);
867
- }
868
- source = source.replace(/slots\s*:\s*\{\s*\}/, `slots: {\n "${c.slot}": ${local},\n }`);
869
- if (!source.includes(`"${c.slot}": ${local}`)) source = source.replace(/slots\s*:\s*\{/, `slots: {\n // ejected (znode eject ${c.name}): the store renders this copy instead of its own\n "${c.slot}": ${local},`);
870
- fs.writeFileSync(browser, source);
871
- console.log(`registered "${c.slot}": ${local} in src/browser.tsx`);
872
- } else {
873
- warnings.push(`no "slots" in src/browser.tsx: add ${importLine} and slots: { "${c.slot}": ${local} }`);
874
- }
875
- }
876
- for (const warning of warnings) console.log(`warning ${warning}`);
877
- console.log(`\nNext: npm run build (it names any store import a package cannot use), then npm run dev and open a page that shows ${c.name}.`);
878
- }
879
-
880
- // ---- add-slot: a runtime slot around a store component, written into the linked store's source ------------------
881
- // `znode add-slot <Component> <area.name>` does in the store what a base developer did by hand for product.basicInfo:
882
- // a Runtime<Component> wrapper (packages/extensions/src/slots/RuntimeAddedSlots.tsx) that renders <RuntimeSlot name>
883
- // with the component's props and the component itself as children, and the component's export wrapped with
884
- // withRuntimeWrapper, so every place that renders it gets the slot. It edits source only (never .next, never git):
885
- // review the diff, commit it through the store's own flow, rebuild the webstore; then `znode eject <Component>` works.
886
- const ADDED_SLOTS_FILE = "packages/extensions/src/slots/RuntimeAddedSlots.tsx";
887
- const SLOT_NAME = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
888
-
889
- function storeSourceFiles(root) {
890
- const files = [];
891
- const walk = (dir) => {
892
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
893
- const file = path.join(dir, entry.name);
894
- if (entry.isDirectory()) {
895
- if (entry.name !== "node_modules" && !entry.name.startsWith("__")) walk(file);
896
- } else if (/\.tsx$/.test(entry.name) && !/\.(test|spec|stories)\.tsx$/.test(entry.name)) files.push(file);
897
- }
898
- };
899
- for (const dir of ["packages/base-components/src", "packages/page-builder/src"]) if (fs.existsSync(path.join(root, dir))) walk(path.join(root, dir));
900
- return files;
901
- }
902
-
903
- function addSlot(name, slot, { dryRun, file: chosen }) {
904
- const usage = "usage: znode add-slot <Component> <area.name> [--dry-run] [--file <store file>] e.g. znode add-slot ProductBasicInfo product.basicInfo";
905
- if (!name || !slot) fail(usage);
906
- if (!/^[A-Z]\w*$/.test(name)) fail(`"${name}" is not a component name (PascalCase, e.g. ProductDetails)\n${usage}`);
907
- if (!SLOT_NAME.test(slot)) fail(`"${slot}" is not a slot name: area.name in camelCase, e.g. product.details`);
908
- const store = linkedStore(path.resolve("."));
909
- if (!store) fail("not linked to a store: run it in a package linked with npm run link-store -- <store repo> (add-slot edits that store's source)");
910
- const root = store.root;
911
- const rel = (file) => path.relative(root, file).split(path.sep).join("/");
912
-
913
- // the slot must be new
914
- const slotsDir = path.join(root, "packages/extensions/src/slots");
915
- if (!fs.existsSync(slotsDir)) fail(`${rel(slotsDir)} not found: this store has no runtime slots (packages/extensions)`);
916
- const wrapperSlots = storeWrapperSlots(root);
917
- const taken = Object.entries(wrapperSlots).find(([, value]) => value === slot);
918
- if (taken) fail(`slot "${slot}" already exists (${taken[0]}); znode eject lists what it hands over`);
919
- const wrapper = `Runtime${name}`;
920
- if (wrapperSlots[wrapper] || fs.readdirSync(slotsDir).some((f) => new RegExp(`export\\s+function\\s+${wrapper}\\b`).test(fs.readFileSync(path.join(slotsDir, f), "utf8"))))
921
- fail(`${wrapper} already exists in ${rel(slotsDir)}: ${name} already has a slot (znode eject lists it)`);
922
-
923
- // the file that defines the component
924
- const DEFINES = new RegExp(`^(export\\s+(?:default\\s+)?)?(async\\s+)?function\\s+${name}\\s*[(<]|^(export\\s+)?const\\s+${name}\\s*(?::[^=]+)?=\\s*(async\\b)?`, "m");
925
- let candidates = chosen ? [path.resolve(root, chosen)] : storeSourceFiles(root).filter((f) => DEFINES.test(fs.readFileSync(f, "utf8")));
926
- if (chosen && !fs.existsSync(candidates[0])) fail(`${chosen} not found in ${root}`);
927
- if (candidates.length > 1) {
928
- const named = candidates.filter((f) => path.basename(f, ".tsx") === name);
929
- if (named.length === 1) candidates = named;
930
- else fail(`${name} is defined in more than one store file; pick one with --file:\n ${candidates.map(rel).join("\n ")}`);
931
- }
932
- if (!candidates.length) fail(`no ${name} component found in packages/base-components/src or packages/page-builder/src (only .tsx components can get a slot)`);
933
- const target = candidates[0];
934
- let source = fs.readFileSync(target, "utf8");
935
- const def = source.match(DEFINES);
936
- if (!def) fail(`${rel(target)} does not define ${name} as a function or const component`);
937
-
938
- // only a client-renderable component: a slot is filled in the browser
939
- if (new RegExp(`withRuntimeWrapper\\([^)]*["']${name}["']`).test(source)) fail(`${name} is already wrapped (${rel(target)}): it has a slot, znode eject lists it`);
940
- if (def[2] || def[4])
941
- fail(
942
- `${name} is an async server component (${rel(target)}): a runtime slot is filled in the browser, so it cannot wrap a server component.\n` +
943
- ` Add the slot to a client component it renders instead (e.g. its ProductBasicInfo), or split ${name} into a server part (data) and a client part (UI) and add the slot to the client part.`
944
- );
945
- const serverImport = source.match(/^\s*import\b[^;]*["'](server-only|next\/headers|fs|node:fs)["']/m);
946
- if (serverImport) fail(`${name} imports ${serverImport[1]} (${rel(target)}): it runs on the server only, so a browser slot cannot wrap it`);
947
-
948
- // wrap the export: <Name>Base is the component, <Name> is the wrapped one every caller already imports
949
- const baseName = `${name}Base`;
950
- if (new RegExp(`\\b${baseName}\\b`).test(source)) fail(`${rel(target)} already has a ${baseName}: wrap it by hand`);
951
- const wrapped = `withRuntimeWrapper(${wrapper}, ${baseName}, "${name}")`;
952
- const comment = `// runtime packages render around it through the slot "${slot}" (znode add-slot); with none, it renders as it is`;
953
- if (/^export\s+default\s+/.test(def[0])) {
954
- source = source.replace(def[0], def[0].replace(/^export\s+default\s+/, "").replace(name, baseName));
955
- source = source.trimEnd() + `\n\n${comment}\nconst ${name} = ${wrapped};\n\nexport default ${name};\n`;
956
- } else if (def[1] || def[3]) {
957
- source = source.replace(def[0], def[0].replace(/^export\s+/, "").replace(name, baseName));
958
- source = source.trimEnd() + `\n\n${comment}\nexport const ${name} = ${wrapped};\n`;
959
- } else {
960
- // defined, exported later (export default Name; / export { Name }): the wrapped const goes right before that export
961
- source = source.replace(def[0], def[0].replace(name, baseName));
962
- const exportAt = source.search(new RegExp(`^export\\s+(default\\s+${name}\\b|\\{[^}]*\\b${name}\\b)`, "m"));
963
- const line = `${comment}\nconst ${name} = ${wrapped};\n\n`;
964
- source = exportAt >= 0 ? source.slice(0, exportAt) + line + source.slice(exportAt) : source.trimEnd() + `\n\n${line}`;
965
- }
966
- // statics set on the component belong to the base (they run before the wrapped const exists)
967
- source = source.replace(new RegExp(`\\b${name}\\.(displayName|defaultProps|propTypes)\\b`, "g"), `${baseName}.$1`);
968
- const imports = [`import { withRuntimeWrapper } from "@znode/extensions/slots/with-runtime-wrapper";`, `import { ${wrapper} } from "@znode/extensions/slots/RuntimeAddedSlots";`].filter(
969
- (line) => !(line.includes("withRuntimeWrapper }") && /import\s*\{[^}]*\bwithRuntimeWrapper\b/.test(source))
970
- );
971
- const directive = source.match(/^\s*["']use (client|server)["'];?\s*\n/);
972
- const at = directive ? directive[0].length : 0;
973
- source = source.slice(0, at) + (directive ? "\n" : "") + imports.join("\n") + "\n" + (directive ? "" : "\n") + source.slice(at).replace(/^\n+/, directive ? "" : "");
974
-
975
- // the wrapper
976
- const addedFile = path.join(root, ADDED_SLOTS_FILE);
977
- const addedBefore = fs.existsSync(addedFile) ? fs.readFileSync(addedFile, "utf8") : null;
978
- let added =
979
- addedBefore ??
980
- `"use client";\n\n// Slots added with \`znode add-slot <Component> <area.name>\` (znode-plugin): each Runtime<Component> renders the slot\n// around the store component (withRuntimeWrapper where the component is defined), with the component's props and the\n// component itself as children. With no runtime package for the slot, the component renders as it is.\n\nimport { ReactNode } from "react";\nimport { RuntimeSlot } from "../client/RuntimeSlot";\n`;
981
- added =
982
- added.trimEnd() +
983
- `\n\n/** ${slot}: the store's ${name} (children), with every prop it gets. Added with \`znode add-slot ${name} ${slot}\` (${new Date().toISOString().slice(0, 10)}). */\n` +
984
- `export function ${wrapper}({ children, ...props }: Readonly<Record<string, unknown> & { children?: ReactNode }>) {\n` +
985
- ` return (\n <RuntimeSlot name="${slot}" props={props}>\n {children}\n </RuntimeSlot>\n );\n}\n`;
986
-
987
- const changes = [
988
- { file: target, before: fs.readFileSync(target, "utf8"), after: source },
989
- { file: addedFile, before: addedBefore, after: added },
990
- ];
991
- const warnings = [];
992
-
993
- // the slot list in the SDK types of the store (packages/extensions/src/types.ts), when it has one
994
- const typesFile = path.join(root, "packages/extensions/src/types.ts");
995
- if (fs.existsSync(typesFile)) {
996
- const before = fs.readFileSync(typesFile, "utf8");
997
- const lines = before.split("\n");
998
- const start = lines.findIndex((line) => /^\s*\/\/\s*Slots\s*\(/.test(line));
999
- if (start >= 0) {
1000
- let end = start + 1;
1001
- while (end < lines.length && /^\s*\/\/\s{3,}/.test(lines[end])) end++;
1002
- lines.splice(end, 0, `// ${slot.padEnd(20)} the store's ${name} itself (children) props: every prop ${name} gets (znode add-slot)`);
1003
- changes.push({ file: typesFile, before, after: lines.join("\n") });
1004
- } else warnings.push(`${rel(typesFile)}: no "// Slots (" comment found; add "${slot}" to the slot list yourself`);
1005
- }
1006
- // the slot table in docs/RUNTIME_EXTENSIONS_AGENTS.md, when it has one
1007
- const docsFile = path.join(root, "docs/RUNTIME_EXTENSIONS_AGENTS.md");
1008
- if (fs.existsSync(docsFile)) {
1009
- const before = fs.readFileSync(docsFile, "utf8");
1010
- const lines = before.split("\n");
1011
- let row = lines.findIndex((line) => line.startsWith("| `product.card`"));
1012
- if (row >= 0) {
1013
- while (row + 1 < lines.length && lines[row + 1].startsWith("|")) row++;
1014
- lines.splice(row + 1, 0, `| \`${slot}\` | \`${wrapper}\` (\`${ADDED_SLOTS_FILE.replace("packages/extensions/src/", "")}\`) | \`${rel(target).replace(/^packages\/[\w-]+\/src\//, "").replace(/\.tsx$/, "")}\` (its children: the component itself) | every ${name} prop; keep \`children\`, wrap it, or render a copy instead (\`znode eject ${name}\`) |`);
1015
- changes.push({ file: docsFile, before, after: lines.join("\n") });
1016
- } else warnings.push(`${rel(docsFile)}: slot table not found; add a "${slot}" row yourself`);
1017
- }
1018
-
1019
- console.log(`${dryRun ? "would add" : "adding"} slot "${slot}" around ${name} (${rel(target)}) in ${root}\n`);
1020
- for (const { file, before, after } of changes) {
1021
- const old = new Set((before || "").split("\n"));
1022
- const added = after.split("\n").filter((line) => !old.has(line));
1023
- console.log(`${before === null ? "new " : "edit"} ${rel(file)}`);
1024
- for (const line of added) console.log(` + ${line}`);
1025
- }
1026
- if (dryRun) {
1027
- console.log("\n--dry-run: nothing written. Run it again without --dry-run to write these changes.");
1028
- return;
1029
- }
1030
- for (const { file, after } of changes) fs.writeFileSync(file, after);
1031
-
1032
- // the store's module registry, when the store generates one (the ejected copy's imports are checked against it)
1033
- const registry = path.join(root, "scripts/gen-store-module-registry.mjs");
1034
- if (fs.existsSync(registry)) spawnSync(process.execPath, [registry], { cwd: root, stdio: "inherit" });
1035
- for (const warning of warnings) console.log(`warning ${warning}`);
1036
- console.log(
1037
- `\nDone (the store's source only: nothing committed, .next untouched). Next:\n` +
1038
- ` 1. review the diff in ${root} (git diff) and commit it through the store's own flow (hooks, review: it edits base components)\n` +
1039
- ` 2. rebuild / restart the webstore so it renders the slot\n` +
1040
- ` 3. here: npx znode eject ${name} (or fill "${slot}" in src/browser.tsx with a component of your own)`
1041
- );
1042
- }
1043
-
1044
- const args = process.argv.slice(2);
1045
- // the store's plugin folder: the argument, else RUNTIME_PLUGINS_DIR, else the project's git-ignored znode.local.json
1046
- // ({ "pluginsDir": "…" }, written by create-znode-plugin --plugins-dir) in the folder the command runs in
1047
- function localPluginsDir() {
1048
- try {
1049
- return JSON.parse(fs.readFileSync(path.resolve("znode.local.json"), "utf8")).pluginsDir || undefined;
1050
- } catch {
1051
- return undefined;
1052
- }
1053
- }
1054
- const [command, target, storeDir = process.env.RUNTIME_PLUGINS_DIR || localPluginsDir()] = args;
1055
- if (command === "create") {
1056
- create(args[1], args[2], args[3]);
1057
- process.exit(0);
1058
- }
1059
- if (command === "eject") {
1060
- eject(args.find((arg, index) => index > 0 && !arg.startsWith("--")), args.includes("--force"));
1061
- process.exit(0);
1062
- }
1063
- if (command === "add-slot" || (command === "add" && args[1] === "slot")) {
1064
- const rest = args.slice(command === "add" ? 2 : 1).filter((arg) => arg !== "--");
1065
- const fileAt = rest.indexOf("--file");
1066
- const file = fileAt >= 0 ? rest[fileAt + 1] : undefined;
1067
- const positional = rest.filter((arg, index) => !arg.startsWith("--") && !(fileAt >= 0 && index === fileAt + 1));
1068
- addSlot(positional[0], positional[1], { dryRun: rest.includes("--dry-run"), file });
1069
- process.exit(0);
1070
- }
1071
- if (command === "link-store") {
1072
- if (!target) fail("usage: znode link-store <storeRepoDir> [projectDir]");
1073
- linkStore(target, args[2]);
1074
- process.exit(0);
1075
- }
1076
- if (!target) fail("usage: znode <build|pack|check|install|deploy|dev> <dir|zip> [storeDir], znode create <kind> <name> [dir], znode link-store <storeRepoDir>");
1077
- if (command === "check") check(path.resolve(target));
1078
- else if (command === "build") build(path.resolve(target));
1079
- else if (command === "pack") pack(path.resolve(target));
1080
- else if (command === "install") install(path.resolve(target), path.resolve(needStore(storeDir)));
1081
- else if (command === "deploy") deploy(path.resolve(target), path.resolve(needStore(storeDir)));
1082
- else if (command === "dev") dev(path.resolve(target), path.resolve(needStore(storeDir)));
1083
- else fail(`unknown command "${command}"`);
1
+ #!/usr/bin/env node
2
+ // znode-plugin: build, pack and install Znode runtime packages (themes, plugins, widgets, content).
3
+ //
4
+ // znode build <packageDir|manifest.json> build into <packageDir>/dist
5
+ // znode pack <packageDir|manifest.json> build, then zip it as
6
+ // <packageDir>/releases/<name>-<version>.zpkg.zip
7
+ // znode install <zip|packageDir> [storeDir] validate and install into the store's plugin
8
+ // directory (default: RUNTIME_PLUGINS_DIR);
9
+ // the registry entry keeps its settings and stores
10
+ // znode create <theme|plugin|widget|content> <name> [dir]
11
+ // a starter package that builds as it is
12
+ // (default dir ./<name>)
13
+ // znode check <packageDir> marketplace review: metadata, permissions against
14
+ // the code, settings, size, server-render format
15
+ // znode deploy <packageDir> [storeDir] pack, then install into the store's plugin directory
16
+ // znode dev <packageDir> [storeDir] deploy, then again on every change under src/ or to the manifest
17
+ // znode link-store <storeRepoDir> [dir] the store's real types: writes tsconfig.store.json (see README)
18
+ // znode eject [<Name>] [--force] in a package folder: list the store components that can be ejected, or
19
+ // copy one into src/components/ and register it in its slot
20
+ // (<Name> is the component or its slot name)
21
+ // znode create-slot <Component> <area.name> [--dry-run] [--file <f>] a slot around a store component, written into
22
+ // the linked store's source (base developers; review and commit there)
23
+ // znode slot list [<filter>] [--json] every slot the linked store renders, what it hands over, what can be
24
+ // ejected into it and what this package fills (also: znode slots)
25
+ //
26
+ // A package is a folder with znode-package.json (README.md shows a whole project, as create-znode-plugin makes it):
27
+ // {
28
+ // "name": "artifi", "version": "1.0.0", "kind": "plugin" | "theme" | "widget" | "content", "apiVersion": 1,
29
+ // "label": "...", "publisher": "...", "description": "...", "parent": "<theme>", (parent: themes only)
30
+ // "build": { "server": "src/server.ts", "browser": "src/browser.tsx" }, (TypeScript entry points)
31
+ // "styles": ["src/styles/*.css"], "assets": ["src/assets/fonts/*.woff2"], "messages": "src/i18n/labels.json",
32
+ // "pages": { "/": "src/pages/home.json" }, "widgets": ["HeroBanner"],
33
+ // code imports Next.js as an app does: next/image, next/link, next/navigation, next/font/google, react
34
+ // (next-imports.mjs: the store's own modules at runtime; Google fonts downloaded into the package when it builds)
35
+ // "overrides": { "/api/place-order": "place-order" }, (store BFF routes it takes over, by one of its routes)
36
+ // "serverPages": ["/my-page"], (whole pages at new URLs, rendered by its server part's serverPages)
37
+ // "dedupeStyles": true, (styles: drop the rules the store already has; STORE_URL = a page of a running store)
38
+ // "settingsSchema": { "websiteId": { "type": "string", "required": true, "browser": true, "label": "..." },
39
+ // "banner": { "type": "string", "browser": true, "attribute": "StoreBannerText" } },
40
+ // (attribute: the value comes from a Znode global attribute, "Code" for the store's, or
41
+ // { "code": "...", "levels": ["store", "account", "user"] }; the most specific level wins)
42
+ // marketplace: "license", "keywords", "homepage", "compatibility": { "webstore": ">=10.0.0" },
43
+ // "permissions": ["routes", "cartHooks", "overrides", "znodeApi", "externalNetwork", "uploads"] (what it does beyond UI;
44
+ // "uploads": its routes take files, multipart/form-data up to RUNTIME_PLUGIN_UPLOAD_BYTES)
45
+ // "sandbox": true (its server part runs in a separate, permission-limited Node process: routes and overrides only)
46
+ // }
47
+ import fs from "node:fs";
48
+ import path from "node:path";
49
+ import { execFileSync, spawnSync } from "node:child_process";
50
+ import { createRequire } from "node:module";
51
+ import { fileURLToPath, pathToFileURL } from "node:url";
52
+ import vm from "node:vm";
53
+ import { TEMPLATES } from "./templates.mjs";
54
+
55
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
56
+ const MANIFEST = "znode-package.json";
57
+ // the build tools (TypeScript, rollup, adm-zip, postcss): this package's own dependencies, wherever npm put them
58
+ // (ZNODE_TOOLS: a node_modules folder to use instead)
59
+ const require = process.env.ZNODE_TOOLS ? createRequire(path.join(process.env.ZNODE_TOOLS, "noop.js")) : createRequire(import.meta.url);
60
+ // a dependency's folder (its package.json's), found from what it resolves to
61
+ function packageDir(name) {
62
+ for (let dir = path.dirname(require.resolve(name)); dir !== path.dirname(dir); dir = path.dirname(dir)) {
63
+ const file = path.join(dir, "package.json");
64
+ if (fs.existsSync(file) && JSON.parse(fs.readFileSync(file, "utf8")).name === name) return dir;
65
+ }
66
+ throw new Error(`znode-plugin: ${name} is not installed`);
67
+ }
68
+ const TSC = () => path.join(packageDir("typescript"), "bin", "tsc");
69
+ const ROLLUP = () => path.join(packageDir("rollup"), "dist", "bin", "rollup");
70
+ const AdmZip = require("adm-zip");
71
+
72
+ const API_VERSION = 1;
73
+ const KINDS = ["theme", "plugin", "widget", "content"];
74
+ const NAME = /^[a-z0-9][a-z0-9-]{1,48}$/;
75
+ const VERSION = /^\d+\.\d+\.\d+(-[0-9a-z.-]+)?$/i;
76
+ const SERVED = new Set([".mjs", ".map", ".css", ".woff2", ".woff", ".ttf", ".otf", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".json"]);
77
+ const MAX_BYTES = 10 * 1024 * 1024;
78
+ const SETTING_TYPES = ["string", "number", "boolean", "list", "json", "object", "array"];
79
+ const ATTRIBUTE_LEVELS = ["store", "account", "user"];
80
+ const ATTRIBUTE_CODE = /^[A-Za-z][A-Za-z0-9_]{1,99}$/;
81
+ const PERMISSIONS = ["routes", "cartHooks", "overrides", "znodeApi", "externalNetwork", "uploads"];
82
+
83
+ const fail = (message) => {
84
+ console.error(`znode-package: ${message}`);
85
+ process.exit(1);
86
+ };
87
+ const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
88
+ const glob = (dir, pattern) => {
89
+ const folder = path.join(dir, path.dirname(pattern));
90
+ const re = new RegExp(
91
+ `^${path
92
+ .basename(pattern)
93
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
94
+ .replace(/\*/g, ".*")}$`
95
+ );
96
+ return fs.existsSync(folder)
97
+ ? fs
98
+ .readdirSync(folder)
99
+ .filter((name) => re.test(name))
100
+ .map((name) => path.join(folder, name))
101
+ : [];
102
+ };
103
+
104
+ function validateManifest(manifest, where) {
105
+ if (!NAME.test(manifest.name || "")) fail(`${where}: name must be lowercase letters, digits and dashes`);
106
+ if (!VERSION.test(manifest.version || "")) fail(`${where}: version must be semver (1.2.3)`);
107
+ if (!KINDS.includes(manifest.kind)) fail(`${where}: kind must be one of ${KINDS.join(", ")}`);
108
+ if (manifest.apiVersion !== API_VERSION) fail(`${where}: apiVersion ${manifest.apiVersion} isn't supported (this store runs ${API_VERSION})`);
109
+ if (manifest.parent && manifest.kind !== "theme") fail(`${where}: only a theme has a parent`);
110
+ // whole pages its server part renders (IRuntimePlugin.serverPages), at new lowercase URLs the store doesn't use
111
+ if (manifest.serverPages !== undefined) {
112
+ if (!Array.isArray(manifest.serverPages)) fail(`${where}: serverPages must be a list of paths ("/my-page")`);
113
+ // the source manifest names the entry (build.server), the built one the file (files.server)
114
+ if (manifest.serverPages.length && !manifest.build?.server && !manifest.files?.server) fail(`${where}: serverPages need a server part (build.server)`);
115
+ for (const page of manifest.serverPages) {
116
+ if (!/^\/[a-z0-9][a-z0-9-]*(\/[a-z0-9][a-z0-9-]*)*$/.test(String(page))) fail(`${where}: serverPages "${page}" must be a lowercase path like /my-page`);
117
+ if (/^\/(api|runtime-page|_next|login|signup|account|cart|checkout|search|product|category|404|error|maintenance)(\/|$)/.test(page)) fail(`${where}: serverPages "${page}" is a store route`);
118
+ }
119
+ }
120
+ // store BFF routes the package takes over: "/api/<path>" -> one of its own routes
121
+ for (const [route, target] of Object.entries(manifest.overrides || {})) {
122
+ if (!/^\/api\/[A-Za-z0-9/_-]+$/.test(route) || /^\/api\/extensions(\/|$)/.test(route)) fail(`${where}: override "${route}" must be a store route under /api/`);
123
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(String(target))) fail(`${where}: override "${route}" must name one of the package's routes`);
124
+ }
125
+ for (const [key, field] of Object.entries(manifest.settingsSchema || {})) {
126
+ if (field?.type !== undefined && !SETTING_TYPES.includes(field.type)) fail(`${where}: setting "${key}" has type "${field.type}" (one of ${SETTING_TYPES.join(", ")})`);
127
+ const attribute = field?.attribute;
128
+ if (attribute === undefined) continue;
129
+ const code = typeof attribute === "string" ? attribute : attribute?.code;
130
+ if (!ATTRIBUTE_CODE.test(String(code || ""))) fail(`${where}: setting "${key}" names attribute "${code}" (letters, digits and _, as Znode attribute codes)`);
131
+ const levels = typeof attribute === "string" ? ["store"] : attribute.levels || ["store"];
132
+ if (!Array.isArray(levels) || !levels.length || levels.some((level) => !ATTRIBUTE_LEVELS.includes(level))) {
133
+ fail(`${where}: setting "${key}" attribute levels must be some of ${ATTRIBUTE_LEVELS.join(", ")}`);
134
+ }
135
+ }
136
+ if (manifest.sandbox !== undefined && typeof manifest.sandbox !== "boolean") fail(`${where}: sandbox must be true or false`);
137
+ if (manifest.permissions !== undefined && (!Array.isArray(manifest.permissions) || manifest.permissions.some((item) => !PERMISSIONS.includes(item)))) {
138
+ fail(`${where}: permissions must be some of ${PERMISSIONS.join(", ")}`);
139
+ }
140
+ }
141
+
142
+ // ---- build: TypeScript entry points -> one ES module each (tsc + rollup), plus styles, assets, labels, pages ----
143
+ // a package folder (its znode-package.json) or one of several manifests in a folder (<name>.znode-package.json)
144
+ function resolvePackage(target) {
145
+ const isFile = fs.statSync(target).isFile();
146
+ const dir = isFile ? path.dirname(target) : target;
147
+ const manifestFile = isFile ? target : path.join(dir, MANIFEST);
148
+ return { dir, manifestFile, outName: path.basename(manifestFile) === MANIFEST ? "dist" : `dist-${path.basename(manifestFile, `.${MANIFEST}`)}` };
149
+ }
150
+
151
+ // The package's tsconfig check. tsc also checks the store files the package imports; their errors are the store's, not
152
+ // the package's: listed as warnings. An error in the package's own files stops the build.
153
+ function typeCheck(dir, tsconfigFile) {
154
+ let output = "";
155
+ try {
156
+ execFileSync(process.execPath, [TSC(), "-p", tsconfigFile, "--noEmit", "--pretty", "false"], {
157
+ cwd: dir,
158
+ encoding: "utf8",
159
+ stdio: ["ignore", "pipe", "pipe"],
160
+ });
161
+ return;
162
+ } catch (error) {
163
+ output = `${error.stdout || ""}${error.stderr || ""}`;
164
+ }
165
+ // one entry per error: "file(line,col): error TSnnnn: message" and its indented continuation lines
166
+ const errors = output.split(/\r?\n(?=\S)/).filter((entry) => /^.+?\(\d+,\d+\): error TS\d+:/.test(entry));
167
+ if (!errors.length) fail(`tsconfig check failed:\n${output}`);
168
+ // inside the package folder: a relative path that does not climb out (on Windows a file on another drive comes back
169
+ // absolute from path.relative, which is outside too)
170
+ const inPackage = (entry) => {
171
+ const relative = path.relative(dir, path.resolve(dir, entry.slice(0, entry.indexOf("("))));
172
+ return !relative.startsWith("..") && !path.isAbsolute(relative);
173
+ };
174
+ const own = errors.filter(inPackage);
175
+ const store = errors.filter((entry) => !inPackage(entry));
176
+ if (store.length) console.log(`warning ${store.length} type error(s) in store files the package imports (the store's to fix):\n ${store.join("\n ")}`);
177
+ if (own.length) fail(`type errors in the package:\n ${own.join("\n ")}`);
178
+ }
179
+
180
+ // every .ts / .tsx under srcRoot compiled to .js under outRoot, one file at a time and without resolving imports (the
181
+ // tsconfig check has done the types): types removed, JSX as Next.js compiles it (react/jsx-runtime)
182
+ function transpileSources(srcRoot, outRoot) {
183
+ const ts = require("typescript");
184
+ const walk = (folder) =>
185
+ fs.readdirSync(folder, { withFileTypes: true }).flatMap((item) => {
186
+ const file = path.join(folder, item.name);
187
+ if (item.isDirectory()) return walk(file);
188
+ return /\.tsx?$/.test(item.name) && !item.name.endsWith(".d.ts") ? [file] : [];
189
+ });
190
+ for (const file of walk(srcRoot)) {
191
+ const { outputText } = ts.transpileModule(fs.readFileSync(file, "utf8"), {
192
+ fileName: file,
193
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ES2022, jsx: ts.JsxEmit.ReactJSX, jsxImportSource: "react" },
194
+ });
195
+ const target = path.join(outRoot, path.relative(srcRoot, file)).replace(/\.tsx?$/, ".js");
196
+ fs.mkdirSync(path.dirname(target), { recursive: true });
197
+ fs.writeFileSync(target, outputText);
198
+ }
199
+ }
200
+
201
+ // The store the package is linked to (tsconfig.store.json, written by link-store): its root, its @znode paths and its
202
+ // Generated Store Module Registry (packages/extensions/store-module-registry.json), for the package's store imports
203
+ function linkedStore(dir) {
204
+ const file = path.join(dir, "tsconfig.store.json");
205
+ if (!fs.existsSync(file)) return null;
206
+ const { compilerOptions = {} } = readJson(file);
207
+ if (!compilerOptions.baseUrl) return null;
208
+ const root = path.resolve(dir, compilerOptions.baseUrl);
209
+ const registryFile = path.join(root, "packages/extensions/store-module-registry.json");
210
+ const registry = fs.existsSync(registryFile) ? readJson(registryFile).modules : null;
211
+ return { root, paths: compilerOptions.paths || {}, registry };
212
+ }
213
+
214
+ function build(target) {
215
+ const { dir, manifestFile, outName } = resolvePackage(target);
216
+ const manifest = readJson(manifestFile);
217
+ validateManifest(manifest, path.basename(manifestFile));
218
+ const out = path.join(dir, outName);
219
+ fs.rmSync(out, { recursive: true, force: true });
220
+ fs.mkdirSync(out, { recursive: true });
221
+ const tmp = path.join(dir, ".build");
222
+ const files = {};
223
+ const prefix = `${manifest.name}-${manifest.version}`;
224
+ // next/font/google fonts built into the package (next-imports.mjs): their files and @font-face CSS
225
+ const fonts = [];
226
+ // the store modules its browser part imports (Generated Store Module Registry keys), for the store to load first
227
+ const storeImports = [];
228
+ const store = linkedStore(dir);
229
+ // A package with its own tsconfig.json (extending the store's tsconfig.base.json) is checked against the store's real
230
+ // types (every @znode alias, no declarations to write), then compiled file by file without type information, JSX as
231
+ // Next.js does (react/jsx-runtime: the store's). Without one, the package compiles as before (tsc, JSX factory h).
232
+ const tsconfigFile = path.join(dir, "tsconfig.json");
233
+ const projectMode = fs.existsSync(tsconfigFile);
234
+ if (projectMode && Object.values(manifest.build || {}).length) typeCheck(dir, tsconfigFile);
235
+
236
+ for (const part of ["server", "browser"]) {
237
+ const entry = manifest.build?.[part];
238
+ if (!entry) continue;
239
+ fs.rmSync(tmp, { recursive: true, force: true });
240
+ if (projectMode) transpileSources(path.dirname(path.join(dir, entry)), tmp);
241
+ else execFileSync(
242
+ process.execPath,
243
+ [
244
+ TSC(),
245
+ "--target",
246
+ "es2022",
247
+ "--module",
248
+ "es2022",
249
+ "--moduleResolution",
250
+ "bundler",
251
+ "--lib",
252
+ "es2022,dom",
253
+ "--skipLibCheck",
254
+ // import React from "react", as the store's own components do
255
+ "--allowSyntheticDefaultImports",
256
+ "--jsx",
257
+ "react",
258
+ "--jsxFactory",
259
+ "h",
260
+ "--jsxFragmentFactory",
261
+ "Fragment",
262
+ "--outDir",
263
+ tmp,
264
+ path.join(dir, entry),
265
+ ],
266
+ { stdio: "inherit" }
267
+ );
268
+ const compiled = path.join(tmp, path.basename(entry).replace(/\.tsx?$/, ".js"));
269
+ const target = `${prefix}.${part}.mjs`;
270
+ // rollup with the Next.js imports plugin (next-imports.mjs), from a config file: the plugin downloads fonts, which
271
+ // is async, in rollup's own process; what it built comes back in fonts.json
272
+ const config = path.join(tmp, "rollup.config.mjs");
273
+ const fontsFile = path.join(tmp, "fonts.json");
274
+ const storeImportsFile = path.join(tmp, "store-imports.json");
275
+ fs.writeFileSync(
276
+ config,
277
+ [
278
+ `import fs from "node:fs";`,
279
+ `import { znodeNext } from ${JSON.stringify(pathToFileURL(path.join(HERE, "next-imports.mjs")).href)};`,
280
+ `const fonts = [];`,
281
+ `const storeImports = [];`,
282
+ `const store = ${JSON.stringify(store)};`,
283
+ `if (store?.registry) store.registry = new Set(store.registry);`,
284
+ `export default {`,
285
+ ` input: ${JSON.stringify(compiled)},`,
286
+ ` output: { file: ${JSON.stringify(path.join(out, target))}, format: "es", sourcemap: true },`,
287
+ ` plugins: [`,
288
+ ` znodeNext({ part: ${JSON.stringify(part)}, prefix: ${JSON.stringify(prefix)}, outDir: ${JSON.stringify(out)}, fonts, store, storeImports }),`,
289
+ ` { name: "fonts-out", writeBundle() { fs.writeFileSync(${JSON.stringify(fontsFile)}, JSON.stringify(fonts)); fs.writeFileSync(${JSON.stringify(storeImportsFile)}, JSON.stringify(storeImports)); } },`,
290
+ ` ],`,
291
+ `};`,
292
+ ].join("\n")
293
+ );
294
+ execFileSync(process.execPath, [ROLLUP(), "--config", config, "--silent"], { stdio: "inherit" });
295
+ if (fs.existsSync(fontsFile)) fonts.push(...JSON.parse(fs.readFileSync(fontsFile, "utf8")));
296
+ if (fs.existsSync(storeImportsFile)) storeImports.push(...JSON.parse(fs.readFileSync(storeImportsFile, "utf8")));
297
+ files[part] = target;
298
+ }
299
+ fs.rmSync(tmp, { recursive: true, force: true });
300
+
301
+ // styles: concatenated into one stylesheet, after the fonts next/font/google built; assets (fonts, images) keep their
302
+ // names, which the stylesheet refers to
303
+ if (manifest.styles?.length || fonts.length) {
304
+ const css = [
305
+ ...fonts.map((font) => font.css),
306
+ ...(manifest.styles || []).flatMap((pattern) => glob(dir, pattern)).map((file) => fs.readFileSync(file, "utf8")),
307
+ ].join("\n");
308
+ files.styles = [`${prefix}.css`];
309
+ fs.writeFileSync(path.join(out, files.styles[0]), css);
310
+ // rules the store's own stylesheets already have, loaded again later, would beat its responsive variants
311
+ if (manifest.dedupeStyles) {
312
+ const target = path.join(out, files.styles[0]);
313
+ execFileSync(process.execPath, [path.join(HERE, "css-dedupe.mjs"), target, process.env.STORE_URL || "http://staplespromo.localhost:3000/", target], { stdio: "inherit" });
314
+ }
315
+ }
316
+ files.assets = (manifest.assets || [])
317
+ .flatMap((pattern) => glob(dir, pattern))
318
+ .map((file) => {
319
+ fs.copyFileSync(file, path.join(out, path.basename(file)));
320
+ return path.basename(file);
321
+ })
322
+ // the font files next/font/google downloaded, already in dist
323
+ .concat(fonts.flatMap((font) => font.files));
324
+ if (manifest.messages) {
325
+ files.messages = `${prefix}.labels.json`;
326
+ fs.copyFileSync(path.join(dir, manifest.messages), path.join(out, files.messages));
327
+ }
328
+ if (manifest.pages) {
329
+ files.pages = Object.fromEntries(
330
+ Object.entries(manifest.pages).map(([route, file], index) => {
331
+ const target = `${prefix}.page${index}.json`;
332
+ fs.copyFileSync(path.join(dir, file), path.join(out, target));
333
+ return [route, target];
334
+ })
335
+ );
336
+ }
337
+ const { build: _build, styles: _styles, assets: _assets, dedupeStyles: _dedupe, ...rest } = manifest;
338
+ fs.writeFileSync(path.join(out, MANIFEST), JSON.stringify({ ...rest, files, ...(storeImports.length ? { storeImports: [...new Set(storeImports)].sort() } : {}) }, null, 2) + "\n");
339
+ console.log(`built ${manifest.kind} ${manifest.name}@${manifest.version}: ${fs.readdirSync(out).length} files`);
340
+ return { manifest, out };
341
+ }
342
+
343
+ function pack(target) {
344
+ const { manifest, out } = build(target);
345
+ const { dir } = resolvePackage(target);
346
+ const zip = new AdmZip();
347
+ for (const name of fs.readdirSync(out)) zip.addLocalFile(path.join(out, name));
348
+ fs.mkdirSync(path.join(dir, "releases"), { recursive: true });
349
+ const file = path.join(dir, "releases", `${manifest.name}-${manifest.version}.zpkg.zip`);
350
+ zip.writeZip(file);
351
+ console.log(`packed ${path.basename(file)} (${fs.statSync(file).size} bytes)`);
352
+ }
353
+
354
+ // ---- install: validate, copy into the plugin directory, upsert the registry entry -------------------------------
355
+ // Installs into one folder can run at the same time (several pipelines, an admin upload): each takes the folder's lock
356
+ // (an atomic mkdir) for the read-change-write of plugins.json, writes it atomically (a temp file renamed over it, so the
357
+ // running webstore never reads half a file) and keeps the previous registry in .history/ (the last HISTORY_KEEP).
358
+ const LOCK_WAIT_MS = 60000;
359
+ const LOCK_STALE_MS = 120000;
360
+ const HISTORY_KEEP = 50;
361
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
362
+
363
+ function lockRegistry(storeDir) {
364
+ fs.mkdirSync(storeDir, { recursive: true });
365
+ const lock = path.join(storeDir, ".plugins.lock");
366
+ const deadline = Date.now() + LOCK_WAIT_MS;
367
+ for (;;) {
368
+ try {
369
+ fs.mkdirSync(lock);
370
+ break;
371
+ } catch (error) {
372
+ if (error.code !== "EEXIST") throw error;
373
+ // a lock left by a crashed install
374
+ try {
375
+ if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) fs.rmSync(lock, { recursive: true, force: true });
376
+ } catch {
377
+ // removed meanwhile
378
+ }
379
+ if (Date.now() > deadline) fail(`the registry in ${storeDir} is locked by another install (remove ${lock} if none is running)`);
380
+ sleep(25 + Math.floor(Math.random() * 50));
381
+ }
382
+ }
383
+ const release = () => fs.rmSync(lock, { recursive: true, force: true });
384
+ process.on("exit", release);
385
+ return () => {
386
+ release();
387
+ process.off("exit", release);
388
+ };
389
+ }
390
+
391
+ function writeRegistry(registryFile, registry) {
392
+ const dir = path.dirname(registryFile);
393
+ if (fs.existsSync(registryFile)) {
394
+ const history = path.join(dir, ".history");
395
+ fs.mkdirSync(history, { recursive: true });
396
+ fs.copyFileSync(registryFile, path.join(history, `plugins-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}.json`));
397
+ const old = fs
398
+ .readdirSync(history)
399
+ .filter((name) => name.startsWith("plugins-"))
400
+ .sort();
401
+ for (const name of old.slice(0, Math.max(0, old.length - HISTORY_KEEP))) fs.rmSync(path.join(history, name), { force: true });
402
+ }
403
+ const temp = `${registryFile}.tmp-${process.pid}`;
404
+ fs.writeFileSync(temp, JSON.stringify(registry, null, 2) + "\n");
405
+ fs.renameSync(temp, registryFile);
406
+ }
407
+ const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
408
+
409
+ // the store's settings over the package defaults; an object setting (labels, panels) keeps the store's values and
410
+ // gains the keys a new version adds
411
+ function mergeSettings(defaults, previous) {
412
+ const merged = { ...defaults, ...previous };
413
+ for (const [key, value] of Object.entries(defaults)) {
414
+ if (isPlainObject(value) && isPlainObject(previous[key])) merged[key] = { ...value, ...previous[key] };
415
+ }
416
+ return merged;
417
+ }
418
+
419
+ function install(source, storeDir) {
420
+ let entries;
421
+ if (fs.statSync(source).isDirectory()) {
422
+ // a package folder's build output (dist; package in packages built before the dist folder)
423
+ const built = ["dist", "package"].map((name) => path.join(source, name)).find((dir) => fs.existsSync(path.join(dir, MANIFEST)));
424
+ const dir = built || source;
425
+ entries = fs.readdirSync(dir).map((name) => ({ name, data: fs.readFileSync(path.join(dir, name)) }));
426
+ } else {
427
+ entries = new AdmZip(source)
428
+ .getEntries()
429
+ .filter((entry) => !entry.isDirectory)
430
+ .map((entry) => ({ name: entry.entryName, data: entry.getData() }));
431
+ }
432
+ const manifestEntry = entries.find((entry) => entry.name === "znode-package.json");
433
+ if (!manifestEntry) fail("no znode-package.json in the package");
434
+ const manifest = JSON.parse(manifestEntry.data.toString("utf8"));
435
+ validateManifest(manifest, "package");
436
+
437
+ const total = entries.reduce((sum, entry) => sum + entry.data.length, 0);
438
+ if (total > MAX_BYTES) fail(`package is ${total} bytes; the limit is ${MAX_BYTES}`);
439
+ const files = entries.filter((entry) => entry.name !== "znode-package.json");
440
+ for (const entry of files) {
441
+ if (entry.name !== path.basename(entry.name)) fail(`"${entry.name}": a package is flat, no folders`);
442
+ if (!SERVED.has(path.extname(entry.name).toLowerCase())) fail(`"${entry.name}": file type not allowed`);
443
+ }
444
+ const has = (name) => files.some((entry) => entry.name === name);
445
+ const referenced = [
446
+ manifest.files?.server,
447
+ manifest.files?.browser,
448
+ manifest.files?.messages,
449
+ ...(manifest.files?.styles || []),
450
+ ...Object.values(manifest.files?.pages || {}),
451
+ ].filter(Boolean);
452
+ for (const name of referenced) if (!has(name)) fail(`znode-package.json names "${name}", which isn't in the package`);
453
+
454
+ const registryFile = path.join(storeDir, "plugins.json");
455
+ const unlock = lockRegistry(storeDir);
456
+ const registry = fs.existsSync(registryFile) ? readJson(registryFile) : { plugins: [] };
457
+ // a package never replaces a file another installed package uses
458
+ const owners = new Map();
459
+ for (const item of registry.plugins) {
460
+ if (item.name === manifest.name) continue;
461
+ for (const name of [item.file, item.browser, item.messages, ...(item.styles || []), ...Object.values(item.pages || {})]) if (name) owners.set(name, item.name);
462
+ }
463
+ for (const entry of files) if (owners.has(entry.name)) fail(`"${entry.name}" belongs to package ${owners.get(entry.name)}`);
464
+
465
+ fs.mkdirSync(storeDir, { recursive: true });
466
+ for (const entry of files) fs.writeFileSync(path.join(storeDir, entry.name), entry.data);
467
+
468
+ const previous = registry.plugins.find((item) => item.name === manifest.name);
469
+ const defaults = Object.fromEntries(
470
+ Object.entries(manifest.settingsSchema || {})
471
+ .filter(([, field]) => field.default !== undefined)
472
+ .map(([key, field]) => [key, field.default])
473
+ );
474
+ const entry = {
475
+ name: manifest.name,
476
+ kind: manifest.kind === "widget" ? "plugin" : manifest.kind,
477
+ version: manifest.version,
478
+ label: manifest.label,
479
+ publisher: manifest.publisher,
480
+ ...(manifest.parent ? { parent: manifest.parent } : {}),
481
+ ...(manifest.files?.server ? { file: manifest.files.server } : {}),
482
+ ...(manifest.files?.browser ? { browser: manifest.files.browser } : {}),
483
+ ...(manifest.files?.styles?.length ? { styles: manifest.files.styles } : {}),
484
+ ...(manifest.files?.messages ? { messages: manifest.files.messages } : {}),
485
+ ...(manifest.files?.pages ? { pages: manifest.files.pages } : {}),
486
+ ...(manifest.widgets?.length ? { widgets: manifest.widgets } : {}),
487
+ // the store modules its browser bundle imports: the store loads them first (Generated Store Module Registry)
488
+ ...(Array.isArray(manifest.storeImports) && manifest.storeImports.length ? { storeImports: manifest.storeImports.map(String) } : {}),
489
+ ...(manifest.overrides ? { overrides: manifest.overrides } : {}),
490
+ ...(manifest.serverPages?.length ? { serverPages: manifest.serverPages } : {}),
491
+ ...(manifest.sandbox === true ? { sandbox: true } : {}),
492
+ // the webstore accepts files (multipart) only for a package that declares them
493
+ ...((manifest.permissions || []).includes("uploads") ? { uploads: true } : {}),
494
+ ...(manifest.settingsSchema ? { settingsSchema: manifest.settingsSchema } : {}),
495
+ // where it runs and its settings are the store owner's: an upgrade keeps them; a new package starts switched off
496
+ enabled: previous ? previous.enabled : false,
497
+ stores: previous ? previous.stores : [],
498
+ settings: mergeSettings(defaults, previous?.settings || {}),
499
+ };
500
+ if (previous) registry.plugins[registry.plugins.indexOf(previous)] = entry;
501
+ else registry.plugins.push(entry);
502
+ writeRegistry(registryFile, registry);
503
+ // the replaced version's files (an upgrade's old bundles and stylesheets) leave the plugin directory
504
+ const kept = new Set(files.map((file) => file.name));
505
+ for (const name of [previous?.file, previous?.browser, previous?.messages, ...(previous?.styles || []), ...Object.values(previous?.pages || {})]) {
506
+ if (name && !kept.has(name) && name === path.basename(name)) fs.rmSync(path.join(storeDir, name), { force: true });
507
+ }
508
+
509
+ unlock();
510
+
511
+ const missing = Object.entries(manifest.settingsSchema || {}).filter(([key, field]) => field.required && (entry.settings[key] === undefined || entry.settings[key] === ""));
512
+ console.log(
513
+ `installed ${manifest.kind} ${manifest.name}@${manifest.version}${previous ? ` (was ${previous.version || "unversioned"})` : ""}: ${files.length} files, ${entry.enabled ? "enabled" : "disabled"} for ${JSON.stringify(entry.stores)}`
514
+ );
515
+ if (missing.length) console.log(` settings to fill in before enabling: ${missing.map(([key]) => key).join(", ")}`);
516
+ }
517
+
518
+ // ---- create: a starter package of a kind (templates.mjs), with the API typings next to its sources ---------------
519
+ function create(kind, name, dir) {
520
+ if (!TEMPLATES[kind]) fail(`kind must be one of ${Object.keys(TEMPLATES).join(", ")}`);
521
+ if (!NAME.test(name || "")) fail("name must be lowercase letters, digits and dashes (2 to 49)");
522
+ const target = path.resolve(dir || path.join(process.cwd(), name));
523
+ if (fs.existsSync(target) && fs.readdirSync(target).length) fail(`${target} exists and is not empty`);
524
+ for (const [file, content] of Object.entries(TEMPLATES[kind](name))) {
525
+ const full = path.join(target, file);
526
+ fs.mkdirSync(path.dirname(full), { recursive: true });
527
+ fs.writeFileSync(full, typeof content === "string" ? content : JSON.stringify(content, null, 2) + "\n");
528
+ }
529
+ if (kind !== "content") fs.copyFileSync(path.join(HERE, "..", "types", "extension-api.d.ts"), path.join(target, "src", "extension-api.d.ts"));
530
+ console.log(`created ${kind} ${name} in ${target}`);
531
+ console.log(" next: fill in label, publisher and description in znode-package.json, then run its build-and-upload.sh");
532
+ }
533
+
534
+ // ---- check: what a marketplace review looks at, from the package's own files ------------------------------------
535
+ const HOOK_NAMES = ["onCartChanged", "beforeAddToCart", "afterAddToCart", "mapCartItems"];
536
+
537
+ // the code an entry pulls in: the entry and the files it imports by relative path, followed (a package's server and
538
+ // browser parts share a folder, so a folder read would mix them); type-only imports are skipped
539
+ function sourceOf(dir, entry) {
540
+ if (!entry) return "";
541
+ const seen = new Set();
542
+ const sources = [];
543
+ const visit = (file) => {
544
+ if (seen.has(file) || !fs.existsSync(file)) return;
545
+ seen.add(file);
546
+ const code = fs.readFileSync(file, "utf8");
547
+ sources.push(code);
548
+ for (const [, typeOnly, spec] of code.matchAll(/\bimport\s+(type\s+)?[^;]*?from\s+["'](\.[^"']+)["']/g)) {
549
+ if (typeOnly) continue;
550
+ const base = path.resolve(path.dirname(file), spec).replace(/\.(m?js)$/, "");
551
+ const found = [".ts", ".tsx", ".js", ".mjs", "/index.ts", "/index.tsx"].map((ext) => base + ext).find((candidate) => fs.existsSync(candidate));
552
+ if (found) visit(found);
553
+ }
554
+ };
555
+ visit(path.join(dir, entry));
556
+ return sources.join("\n");
557
+ }
558
+
559
+ // the server renders a browser bundle in this format from one compiled copy for all stores
560
+ // (packages/extensions/src/server-instances.ts); any other is imported once per store, and Node keeps every copy
561
+ function serverRenderFormat(code) {
562
+ const match = /\bexport\s*(?:\{\s*([A-Za-z_$][\w$]*)\s+as\s+default\s*,?\s*\}|default\s+([A-Za-z_$][\w$]*))\s*;?\s*(?:\/\/#\s*sourceMappingURL=\S*\s*)?$/.exec(code);
563
+ if (!match || /(^|[^\w$.])import\s*\(/.test(code.slice(0, match.index))) return false;
564
+ try {
565
+ new vm.Script(`(function () {\n"use strict";\n${code.slice(0, match.index)}\nreturn ${match[1] || match[2]};\n})`);
566
+ return true;
567
+ } catch {
568
+ return false;
569
+ }
570
+ }
571
+
572
+ function check(target) {
573
+ const { dir, manifestFile } = resolvePackage(target);
574
+ const manifest = readJson(manifestFile);
575
+ validateManifest(manifest, path.basename(manifestFile));
576
+ const errors = [];
577
+ const warnings = [];
578
+
579
+ // the listing
580
+ for (const key of ["label", "publisher", "description"]) if (!String(manifest[key] || "").trim()) errors.push(`"${key}" is missing (the marketplace shows it)`);
581
+ if (/describe what it does/i.test(manifest.description || "") || manifest.publisher === "Your company") errors.push("the starter's publisher or description is still in place");
582
+ else if (String(manifest.description || "").length < 30) warnings.push('"description" is short: say what it does for the store');
583
+ for (const key of ["license", "compatibility"]) if (!manifest[key]) warnings.push(`"${key}" is missing`);
584
+
585
+ // permissions against the code
586
+ const server = sourceOf(dir, manifest.build?.server);
587
+ const browser = sourceOf(dir, manifest.build?.browser);
588
+ const used = new Set();
589
+ if (/\broutes\s*[:=,}]/.test(server)) used.add("routes");
590
+ if (HOOK_NAMES.some((hook) => new RegExp(`\\b${hook}\\b`).test(server))) used.add("cartHooks");
591
+ if (Object.keys(manifest.overrides || {}).length) used.add("overrides");
592
+ if (/\bznode\s*\(/.test(server)) used.add("znodeApi");
593
+ if (/\bfetch\s*\(|\bhttps?\.request\s*\(/.test(server)) used.add("externalNetwork");
594
+ if (/\.files\b/.test(server)) used.add("uploads");
595
+ const declared = new Set(manifest.permissions || []);
596
+ for (const item of used) if (!declared.has(item)) errors.push(`uses "${item}" without declaring it in "permissions"`);
597
+ for (const item of declared) if (!used.has(item)) warnings.push(`declares "${item}" but no code uses it (the review asks why)`);
598
+ if (/\beval\s*\(|new Function\s*\(/.test(server + browser)) errors.push("uses eval or new Function");
599
+ if (/document\.cookie/.test(browser)) warnings.push("reads cookies in the browser: keep secrets on the server (routes)");
600
+
601
+ // settings
602
+ for (const [key, field] of Object.entries(manifest.settingsSchema || {})) {
603
+ if (!field.label) warnings.push(`setting "${key}" has no label (the admin shows it)`);
604
+ if (field.required && field.default !== undefined) warnings.push(`setting "${key}" is required but has a default`);
605
+ if (field.browser && /secret|password|token|api_?key/i.test(key)) errors.push(`setting "${key}" looks secret but is sent to the browser ("browser": true)`);
606
+ }
607
+ if (manifest.kind === "theme" && !Object.values(manifest.settingsSchema || {}).some((field) => field.attribute)) {
608
+ warnings.push("no setting is bound to a Znode attribute: per-store branding then needs a registry change per store");
609
+ }
610
+
611
+ // the built files (pack first)
612
+ const out = path.join(dir, "dist");
613
+ if (fs.existsSync(out)) {
614
+ let total = 0;
615
+ for (const name of fs.readdirSync(out)) {
616
+ const size = fs.statSync(path.join(out, name)).size;
617
+ total += size;
618
+ if (name.endsWith(".browser.mjs")) {
619
+ if (size > 512 * 1024) warnings.push(`${name} is ${Math.round(size / 1024)} KB: every page of the store loads it`);
620
+ if (!serverRenderFormat(fs.readFileSync(path.join(out, name), "utf8")))
621
+ warnings.push(`${name} is not in the server-render format (no imports, one default export): the server keeps a copy per store`);
622
+ }
623
+ if (name.endsWith(".css") && size > 200 * 1024) warnings.push(`${name} is ${Math.round(size / 1024)} KB`);
624
+ }
625
+ if (total > MAX_BYTES) errors.push(`dist is ${Math.round(total / 1048576)} MB (limit 10 MB)`);
626
+ } else warnings.push("not built yet: pack it to check sizes and the server-render format");
627
+
628
+ for (const item of errors) console.log(`error ${item}`);
629
+ for (const item of warnings) console.log(`warning ${item}`);
630
+ console.log(`check ${manifest.name}@${manifest.version}: ${errors.length} errors, ${warnings.length} warnings`);
631
+ if (errors.length) process.exit(1);
632
+ }
633
+
634
+ // ---- project commands: deploy, dev, link-store ------------------------------------------------------------------
635
+
636
+ const needStore = (storeDir) =>
637
+ storeDir || fail("needs the store's plugin folder: pass it after the package, or set RUNTIME_PLUGINS_DIR");
638
+
639
+ // pack, then install the zip it made into the store's plugin folder
640
+ function deploy(target, storeDir) {
641
+ pack(target);
642
+ const { dir, manifestFile } = resolvePackage(target);
643
+ const manifest = readJson(manifestFile);
644
+ install(path.join(dir, "releases", `${manifest.name}-${manifest.version}.zpkg.zip`), storeDir);
645
+ }
646
+
647
+ // deploy now, then again whenever the package's sources or manifest change; the store picks a new file up on the next
648
+ // request (it reloads a package when its files change), so a page refresh shows the change
649
+ function dev(target, storeDir) {
650
+ const { dir } = resolvePackage(target);
651
+ const self = fileURLToPath(import.meta.url);
652
+ const run = () => spawnSync(process.execPath, [self, "deploy", dir, storeDir], { stdio: "inherit" });
653
+ run();
654
+ let timer = null;
655
+ const changed = (file) => {
656
+ if (!file || /(^|[\\/])(dist|releases|\.build|node_modules)([\\/]|$)/.test(String(file))) return;
657
+ clearTimeout(timer);
658
+ timer = setTimeout(() => {
659
+ console.log(`znode dev: ${file} changed, deploying`);
660
+ run();
661
+ }, 300);
662
+ };
663
+ fs.watch(path.join(dir, "src"), { recursive: true }, (_event, file) => changed(file && path.join("src", file)));
664
+ fs.watch(dir, (_event, file) => file === MANIFEST && changed(file));
665
+ console.log(`znode dev: watching ${dir} (Ctrl+C to stop)`);
666
+ }
667
+
668
+ // the store's real types for the editor and the build check: tsconfig.store.json (git-ignored, per machine) is this
669
+ // package's preset plus the store repo's aliases (every @znode path of its tsconfig.base.json, from the store's folder).
670
+ // Only the aliases are taken: the store's own options (its rootDir among them) would refuse a project kept elsewhere.
671
+ function linkStore(storeRepo, project = ".") {
672
+ const base = path.resolve(storeRepo, "tsconfig.base.json");
673
+ if (!fs.existsSync(base)) fail(`${base} not found: pass the store repo's folder (the one with tsconfig.base.json)`);
674
+ const ts = require("typescript");
675
+ const { config, error } = ts.readConfigFile(base, ts.sys.readFile);
676
+ if (error) fail(`${base}: ${ts.flattenDiagnosticMessageText(error.messageText, "\n")}`);
677
+ const options = config.compilerOptions || {};
678
+ const toSlash = (value) => value.split(path.sep).join("/");
679
+ const file = path.resolve(project, "tsconfig.store.json");
680
+ const linked = {
681
+ extends: "znode-plugin/tsconfig.json",
682
+ compilerOptions: { baseUrl: toSlash(path.resolve(path.dirname(base), options.baseUrl || ".")), paths: options.paths || {} },
683
+ };
684
+ fs.writeFileSync(file, JSON.stringify(linked, null, 2) + "\n");
685
+ console.log(`linked ${file} to ${base} (${Object.keys(linked.compilerOptions.paths).length} store aliases)`);
686
+ }
687
+
688
+ // ---- eject: a store component copied into the package, in place of the store's, through its slot ----------------
689
+ // A store component that has a runtime slot whose children are the component itself (withRuntimeWrapper(Wrapper, Base,
690
+ // "Name") where it is defined) can be taken over by a package: `znode eject <Name>` copies its file from the linked store
691
+ // into src/components/<Name>.tsx (relative imports turned into the store's @znode aliases, the runtime wrapper removed so
692
+ // the copy is the plain component) and registers it in src/browser.tsx under the slot, so the store renders the copy
693
+ // instead of its own. `znode eject` lists the components that can be ejected.
694
+ const EJECT_SLOTS = {
695
+ RuntimeProductBasicInfo: "product.basicInfo",
696
+ RuntimeProductCard: "product.card",
697
+ RuntimeProductImage: "product.image",
698
+ RuntimeAddToCart: "product.addToCart",
699
+ RuntimeProductVariants: "product.variants",
700
+ RuntimeAddToCartNotification: "addToCart.notification",
701
+ RuntimeCheckoutAddress: "checkout.address",
702
+ RuntimeShippingOptions: "checkout.shippingOptions",
703
+ };
704
+
705
+ // the slot each store wrapper renders: every `export function Runtime<X>` in packages/extensions/src/slots with the first
706
+ // <RuntimeSlot name="…"> in its body (so a slot added with `znode create-slot` is ejectable with no SDK release); the
707
+ // hand-kept EJECT_SLOTS above fill in for a store that predates this
708
+ function storeWrapperSlots(root) {
709
+ const slots = { ...EJECT_SLOTS };
710
+ const dir = path.join(root, "packages/extensions/src/slots");
711
+ if (!fs.existsSync(dir)) return slots;
712
+ for (const entry of fs.readdirSync(dir)) {
713
+ if (!/\.tsx$/.test(entry)) continue;
714
+ const text = fs.readFileSync(path.join(dir, entry), "utf8");
715
+ const starts = [...text.matchAll(/export\s+function\s+(Runtime\w+)/g)];
716
+ starts.forEach((m, i) => {
717
+ const body = text.slice(m.index, i + 1 < starts.length ? starts[i + 1].index : undefined);
718
+ // the first slot that is handed the component as children (<RuntimeSlot name="…">…{children}…</RuntimeSlot>); a
719
+ // layout slot (self-closing, the base rendered hidden beside it) cannot take an ejected copy
720
+ for (const open of body.matchAll(/<RuntimeSlot\s+name=["']([\w.]+)["']/g)) {
721
+ const rest = body.slice(open.index + open[0].length);
722
+ const close = rest.indexOf("</RuntimeSlot>");
723
+ const next = rest.indexOf("<RuntimeSlot");
724
+ if (close >= 0 && (next < 0 || close < next) && /\{\s*children\s*\}/.test(rest.slice(0, close))) {
725
+ if (!slots[m[1]]) slots[m[1]] = open[1];
726
+ break;
727
+ }
728
+ }
729
+ });
730
+ }
731
+ return slots;
732
+ }
733
+
734
+ // every withRuntimeWrapper(<Wrapper>, <Base>, "<Name>") in the store's base components, with the slot it fills
735
+ function ejectableComponents(root) {
736
+ const EJECT_SLOTS = storeWrapperSlots(root);
737
+ const found = [];
738
+ const walk = (dir) => {
739
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
740
+ const file = path.join(dir, entry.name);
741
+ if (entry.isDirectory()) {
742
+ if (entry.name !== "node_modules") walk(file);
743
+ } else if (/\.tsx?$/.test(entry.name)) {
744
+ const text = fs.readFileSync(file, "utf8");
745
+ for (const m of text.matchAll(/withRuntimeWrapper\(\s*(\w+)\s*,\s*(\w+)\s*,\s*"(\w+)"\s*\)/g)) {
746
+ if (EJECT_SLOTS[m[1]]) found.push({ name: m[3], wrapper: m[1], base: m[2], slot: EJECT_SLOTS[m[1]], file });
747
+ }
748
+ }
749
+ }
750
+ };
751
+ for (const dir of ["packages/base-components/src", "packages/page-builder/src"]) if (fs.existsSync(path.join(root, dir))) walk(path.join(root, dir));
752
+ return found.sort((a, b) => a.name.localeCompare(b.name));
753
+ }
754
+
755
+ // a store file's import path as the package can import it: the store alias that maps to that file, without extension
756
+ function storeAlias(store, absolute) {
757
+ const target = absolute.split(path.sep).join("/").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "");
758
+ let best = null;
759
+ const norm = (value) => path.resolve(store.root, value).split(path.sep).join("/").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "");
760
+ // an exact alias for this very module ("@znode/base-components/stores": [".../stores/index.ts"]) wins
761
+ for (const [alias, targets] of Object.entries(store.paths)) {
762
+ if (!alias.endsWith("/*") && targets.some((pattern) => norm(pattern) === target)) return alias;
763
+ }
764
+ for (const [alias, targets] of Object.entries(store.paths)) {
765
+ if (!alias.endsWith("/*")) continue;
766
+ for (const pattern of targets) {
767
+ const prefix = path.resolve(store.root, pattern.replace(/\*$/, "")).split(path.sep).join("/").replace(/\/$/, "") + "/";
768
+ if (target.startsWith(prefix) && (!best || prefix.length > best.prefix.length)) best = { prefix, alias: alias.slice(0, -1) };
769
+ }
770
+ }
771
+ return best ? best.alias + target.slice(best.prefix.length) : null;
772
+ }
773
+
774
+ function eject(name, force) {
775
+ const project = path.resolve(".");
776
+ if (!fs.existsSync(path.join(project, MANIFEST))) fail(`run znode eject in a package folder (the one with ${MANIFEST})`);
777
+ const store = linkedStore(project);
778
+ if (!store) fail("the package is not linked to a store: npm run link-store -- <store repo>");
779
+ const components = ejectableComponents(store.root);
780
+ if (!name || name === "--list") {
781
+ console.log("Store components a package can eject (the slot that takes your copy):\n");
782
+ for (const c of components) console.log(` ${c.name.padEnd(34)} ${c.slot.padEnd(26)} ${path.relative(store.root, c.file).split(path.sep).join("/")}`);
783
+ console.log("\nznode eject <Name> copies one into src/components/ and registers it in src/browser.tsx");
784
+ return;
785
+ }
786
+ const c = components.find((item) => item.name.toLowerCase() === name.toLowerCase() || item.slot.toLowerCase() === name.toLowerCase());
787
+ if (!c)
788
+ fail(
789
+ `${name} cannot be ejected: no store component with that name or slot hands itself over to a slot.\n` +
790
+ ` znode eject lists the ones that can (component name or slot name both work)\n` +
791
+ ` znode create-slot ${/^[A-Z]/.test(name) ? name : "<Component>"} <area.name> creates a slot around a store component in the base (edits the linked store's source)`
792
+ );
793
+
794
+ const out = path.join(project, "src", "components", `${c.name}.tsx`);
795
+ if (fs.existsSync(out) && !force) fail(`${path.relative(project, out)} exists: delete it or run znode eject ${c.name} --force`);
796
+ const warnings = [];
797
+ let text = fs.readFileSync(c.file, "utf8");
798
+ // relative imports become the store's aliases (the package lives elsewhere); a style file stays the store's
799
+ text = text.replace(/((?:from|import)\s*\(?\s*["'])(\.{1,2}\/[^"']+)(["'])/g, (whole, before, spec, after) => {
800
+ const absolute = path.resolve(path.dirname(c.file), spec);
801
+ if (/\.(s?css)$/.test(spec)) {
802
+ warnings.push(`style import ${spec}: kept out of the copy; the store's own stylesheet is loaded where the store renders it, add your CSS to src/styles/`);
803
+ return `${before}${spec}${after}`;
804
+ }
805
+ const alias = storeAlias(store, fs.existsSync(absolute) || /\.\w+$/.test(spec) ? absolute : absolute);
806
+ if (!alias) {
807
+ warnings.push(`import ${spec}: no store alias for it; change it by hand`);
808
+ return whole;
809
+ }
810
+ return `${before}${alias}${after}`;
811
+ });
812
+ // drop scss/css side-effect imports that point into the store (they cannot be bundled into a package)
813
+ text = text.replace(/^import\s+["'][^"']+\.s?css["'];?\s*\n/gm, "");
814
+ // the copy is the plain component: no runtime wrapper (the slot is what puts it in place)
815
+ text = text.replace(new RegExp(`^.*import\\s*\\{[^}]*\\b(?:withRuntimeWrapper|${c.wrapper})\\b[^}]*\\}\\s*from\\s*["'][^"']+["'];?\\s*\\n`, "gm"), "");
816
+ text = text.replace(new RegExp(`withRuntimeWrapper\\(\\s*${c.wrapper}\\s*,\\s*${c.base}\\s*,\\s*"${c.name}"\\s*\\)`), c.base);
817
+ const storeFile = path.relative(store.root, c.file).split(path.sep).join("/");
818
+ const header = `// Ejected from the store: ${storeFile} (${new Date().toISOString().slice(0, 10)}), with \`znode eject ${c.name}\`.\n// The store renders this copy instead of its own through the slot "${c.slot}" (src/browser.tsx). It is yours now: the\n// store's later changes to ${c.name} do not reach it, so compare it with the store's file after a store upgrade.\n`;
819
+ text = text.startsWith('"use client"') || text.startsWith("'use client'") ? text.replace(/^(["']use client["'];?\s*\n)/, `$1${header}`) : header + text;
820
+ fs.mkdirSync(path.dirname(out), { recursive: true });
821
+ fs.writeFileSync(out, text);
822
+ console.log(`ejected ${c.name} -> ${path.relative(project, out)}`);
823
+
824
+ // npm packages the copy imports that this package does not have (react, next and the store's @znode modules come from
825
+ // the store): install them at the store's version, so the types match and the build finds them
826
+ const PROVIDED = /^(react|react-dom|next|next-intl|@znode)(\/|$)/;
827
+ const storePackage = (() => {
828
+ try {
829
+ return readJson(path.join(store.root, "package.json"));
830
+ } catch {
831
+ return {};
832
+ }
833
+ })();
834
+ const storeDeps = { ...(storePackage.devDependencies || {}), ...(storePackage.dependencies || {}) };
835
+ const missing = new Map();
836
+ for (const m of text.matchAll(/(?:from|import)\s*\(?\s*["']([^."'/][^"']*)["']/g)) {
837
+ const spec = m[1];
838
+ if (PROVIDED.test(spec)) continue;
839
+ const pkg = spec.startsWith("@") ? spec.split("/").slice(0, 2).join("/") : spec.split("/")[0];
840
+ try {
841
+ createRequire(path.join(project, "package.json")).resolve(`${pkg}/package.json`);
842
+ } catch {
843
+ missing.set(pkg, storeDeps[pkg] ? `${pkg}@${storeDeps[pkg].replace(/^[\^~]/, "")}` : pkg);
844
+ }
845
+ }
846
+ if (missing.size) {
847
+ console.log(`\nThe copy imports npm packages this package does not have (bundled into the package when it builds):`);
848
+ console.log(` npm install ${[...missing.values()].join(" ")}`);
849
+ }
850
+
851
+ // register the copy under the slot in src/browser.tsx
852
+ const browser = path.join(project, "src", "browser.tsx");
853
+ const exportsDefault = new RegExp(`export\\s+default\\s+${c.name}\\b`).test(text) || new RegExp(`export\\s+default\\s+${c.base}\\b`).test(text);
854
+ const local = `Ejected${c.name}`;
855
+ const importLine = exportsDefault
856
+ ? `import ${local} from "./components/${c.name}.js";`
857
+ : `import { ${c.name} as ${local} } from "./components/${c.name}.js";`;
858
+ if (!fs.existsSync(browser)) {
859
+ warnings.push(`src/browser.tsx not found: register it yourself: ${importLine} and slots: { "${c.slot}": ${local} }`);
860
+ } else {
861
+ let source = fs.readFileSync(browser, "utf8");
862
+ if (new RegExp(`["']${c.slot.replace(".", "\\.")}["']\\s*:`).test(source)) {
863
+ warnings.push(`src/browser.tsx already fills "${c.slot}": point it at ${local} (${importLine}) yourself`);
864
+ } else if (/slots\s*:\s*\{/.test(source)) {
865
+ if (!source.includes(importLine)) {
866
+ const imports = [...source.matchAll(/^import .*;\s*$/gm)];
867
+ const at = imports.length ? imports[imports.length - 1].index + imports[imports.length - 1][0].length : 0;
868
+ source = source.slice(0, at) + `\n${importLine}` + source.slice(at);
869
+ }
870
+ source = source.replace(/slots\s*:\s*\{\s*\}/, `slots: {\n "${c.slot}": ${local},\n }`);
871
+ if (!source.includes(`"${c.slot}": ${local}`)) source = source.replace(/slots\s*:\s*\{/, `slots: {\n // ejected (znode eject ${c.name}): the store renders this copy instead of its own\n "${c.slot}": ${local},`);
872
+ fs.writeFileSync(browser, source);
873
+ console.log(`registered "${c.slot}": ${local} in src/browser.tsx`);
874
+ } else {
875
+ warnings.push(`no "slots" in src/browser.tsx: add ${importLine} and slots: { "${c.slot}": ${local} }`);
876
+ }
877
+ }
878
+ for (const warning of warnings) console.log(`warning ${warning}`);
879
+ console.log(`\nNext: npm run build (it names any store import a package cannot use), then npm run dev and open a page that shows ${c.name}.`);
880
+ }
881
+
882
+ // ---- create-slot: a runtime slot around a store component, written into the linked store's source ------------------
883
+ // `znode create-slot <Component> <area.name>` does in the store what a base developer did by hand for product.basicInfo:
884
+ // a Runtime<Component> wrapper (packages/extensions/src/slots/RuntimeCreatedSlots.tsx) that renders <RuntimeSlot name>
885
+ // with the component's props and the component itself as children, and the component's export wrapped with
886
+ // withRuntimeWrapper, so every place that renders it gets the slot. It edits source only (never .next, never git):
887
+ // review the diff, commit it through the store's own flow, rebuild the webstore; then `znode eject <Component>` works.
888
+ const CREATED_SLOTS_FILE = "packages/extensions/src/slots/RuntimeCreatedSlots.tsx";
889
+ const SLOT_NAME = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
890
+
891
+ function storeSourceFiles(root) {
892
+ const files = [];
893
+ const walk = (dir) => {
894
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
895
+ const file = path.join(dir, entry.name);
896
+ if (entry.isDirectory()) {
897
+ if (entry.name !== "node_modules" && !entry.name.startsWith("__")) walk(file);
898
+ } else if (/\.tsx$/.test(entry.name) && !/\.(test|spec|stories)\.tsx$/.test(entry.name)) files.push(file);
899
+ }
900
+ };
901
+ for (const dir of ["packages/base-components/src", "packages/page-builder/src"]) if (fs.existsSync(path.join(root, dir))) walk(path.join(root, dir));
902
+ return files;
903
+ }
904
+
905
+ function createSlot(name, slot, { dryRun, file: chosen }) {
906
+ const usage = "usage: znode create-slot <Component> <area.name> [--dry-run] [--file <store file>] e.g. znode create-slot ProductBasicInfo product.basicInfo";
907
+ if (!name || !slot) fail(usage);
908
+ if (!/^[A-Z]\w*$/.test(name)) fail(`"${name}" is not a component name (PascalCase, e.g. ProductDetails)\n${usage}`);
909
+ if (!SLOT_NAME.test(slot)) fail(`"${slot}" is not a slot name: area.name in camelCase, e.g. product.details`);
910
+ const store = linkedStore(path.resolve("."));
911
+ if (!store) fail("not linked to a store: run it in a package linked with npm run link-store -- <store repo> (create-slot edits that store's source)");
912
+ const root = store.root;
913
+ const rel = (file) => path.relative(root, file).split(path.sep).join("/");
914
+
915
+ // the slot must be new
916
+ const slotsDir = path.join(root, "packages/extensions/src/slots");
917
+ if (!fs.existsSync(slotsDir)) fail(`${rel(slotsDir)} not found: this store has no runtime slots (packages/extensions)`);
918
+ const wrapperSlots = storeWrapperSlots(root);
919
+ const taken = Object.entries(wrapperSlots).find(([, value]) => value === slot);
920
+ if (taken) fail(`slot "${slot}" already exists (${taken[0]}); znode eject lists what it hands over`);
921
+ const wrapper = `Runtime${name}`;
922
+ if (wrapperSlots[wrapper] || fs.readdirSync(slotsDir).some((f) => new RegExp(`export\\s+function\\s+${wrapper}\\b`).test(fs.readFileSync(path.join(slotsDir, f), "utf8"))))
923
+ fail(`${wrapper} already exists in ${rel(slotsDir)}: ${name} already has a slot (znode eject lists it)`);
924
+
925
+ // the file that defines the component
926
+ const DEFINES = new RegExp(`^(export\\s+(?:default\\s+)?)?(async\\s+)?function\\s+${name}\\s*[(<]|^(export\\s+)?const\\s+${name}\\s*(?::[^=]+)?=\\s*(async\\b)?`, "m");
927
+ let candidates = chosen ? [path.resolve(root, chosen)] : storeSourceFiles(root).filter((f) => DEFINES.test(fs.readFileSync(f, "utf8")));
928
+ if (chosen && !fs.existsSync(candidates[0])) fail(`${chosen} not found in ${root}`);
929
+ if (candidates.length > 1) {
930
+ const named = candidates.filter((f) => path.basename(f, ".tsx") === name);
931
+ if (named.length === 1) candidates = named;
932
+ else fail(`${name} is defined in more than one store file; pick one with --file:\n ${candidates.map(rel).join("\n ")}`);
933
+ }
934
+ if (!candidates.length) fail(`no ${name} component found in packages/base-components/src or packages/page-builder/src (only .tsx components can get a slot)`);
935
+ const target = candidates[0];
936
+ let source = fs.readFileSync(target, "utf8");
937
+ const def = source.match(DEFINES);
938
+ if (!def) fail(`${rel(target)} does not define ${name} as a function or const component`);
939
+
940
+ // only a client-renderable component: a slot is filled in the browser
941
+ if (new RegExp(`withRuntimeWrapper\\([^)]*["']${name}["']`).test(source)) fail(`${name} is already wrapped (${rel(target)}): it has a slot, znode eject lists it`);
942
+ if (def[2] || def[4])
943
+ fail(
944
+ `${name} is an async server component (${rel(target)}): a runtime slot is filled in the browser, so it cannot wrap a server component.\n` +
945
+ ` Add the slot to a client component it renders instead (e.g. its ProductBasicInfo), or split ${name} into a server part (data) and a client part (UI) and add the slot to the client part.`
946
+ );
947
+ const serverImport = source.match(/^\s*import\b[^;]*["'](server-only|next\/headers|fs|node:fs)["']/m);
948
+ if (serverImport) fail(`${name} imports ${serverImport[1]} (${rel(target)}): it runs on the server only, so a browser slot cannot wrap it`);
949
+
950
+ // wrap the export: <Name>Base is the component, <Name> is the wrapped one every caller already imports
951
+ const baseName = `${name}Base`;
952
+ if (new RegExp(`\\b${baseName}\\b`).test(source)) fail(`${rel(target)} already has a ${baseName}: wrap it by hand`);
953
+ const wrapped = `withRuntimeWrapper(${wrapper}, ${baseName}, "${name}")`;
954
+ const comment = `// runtime packages render around it through the slot "${slot}" (znode create-slot); with none, it renders as it is`;
955
+ if (/^export\s+default\s+/.test(def[0])) {
956
+ source = source.replace(def[0], def[0].replace(/^export\s+default\s+/, "").replace(name, baseName));
957
+ source = source.trimEnd() + `\n\n${comment}\nconst ${name} = ${wrapped};\n\nexport default ${name};\n`;
958
+ } else if (def[1] || def[3]) {
959
+ source = source.replace(def[0], def[0].replace(/^export\s+/, "").replace(name, baseName));
960
+ source = source.trimEnd() + `\n\n${comment}\nexport const ${name} = ${wrapped};\n`;
961
+ } else {
962
+ // defined, exported later (export default Name; / export { Name }): the wrapped const goes right before that export
963
+ source = source.replace(def[0], def[0].replace(name, baseName));
964
+ const exportAt = source.search(new RegExp(`^export\\s+(default\\s+${name}\\b|\\{[^}]*\\b${name}\\b)`, "m"));
965
+ const line = `${comment}\nconst ${name} = ${wrapped};\n\n`;
966
+ source = exportAt >= 0 ? source.slice(0, exportAt) + line + source.slice(exportAt) : source.trimEnd() + `\n\n${line}`;
967
+ }
968
+ // statics set on the component belong to the base (they run before the wrapped const exists)
969
+ source = source.replace(new RegExp(`\\b${name}\\.(displayName|defaultProps|propTypes)\\b`, "g"), `${baseName}.$1`);
970
+ const imports = [`import { withRuntimeWrapper } from "@znode/extensions/slots/with-runtime-wrapper";`, `import { ${wrapper} } from "@znode/extensions/slots/RuntimeCreatedSlots";`].filter(
971
+ (line) => !(line.includes("withRuntimeWrapper }") && /import\s*\{[^}]*\bwithRuntimeWrapper\b/.test(source))
972
+ );
973
+ const directive = source.match(/^\s*["']use (client|server)["'];?\s*\n/);
974
+ const at = directive ? directive[0].length : 0;
975
+ source = source.slice(0, at) + (directive ? "\n" : "") + imports.join("\n") + "\n" + (directive ? "" : "\n") + source.slice(at).replace(/^\n+/, directive ? "" : "");
976
+
977
+ // the wrapper
978
+ const addedFile = path.join(root, CREATED_SLOTS_FILE);
979
+ const addedBefore = fs.existsSync(addedFile) ? fs.readFileSync(addedFile, "utf8") : null;
980
+ let added =
981
+ addedBefore ??
982
+ `"use client";\n\n// Slots created with \`znode create-slot <Component> <area.name>\` (znode-plugin): each Runtime<Component> renders the slot\n// around the store component (withRuntimeWrapper where the component is defined), with the component's props and the\n// component itself as children. With no runtime package for the slot, the component renders as it is.\n\nimport { ReactNode } from "react";\nimport { RuntimeSlot } from "../client/RuntimeSlot";\n`;
983
+ added =
984
+ added.trimEnd() +
985
+ `\n\n/** ${slot}: the store's ${name} (children), with every prop it gets. Created with \`znode create-slot ${name} ${slot}\` (${new Date().toISOString().slice(0, 10)}). */\n` +
986
+ `export function ${wrapper}({ children, ...props }: Readonly<Record<string, unknown> & { children?: ReactNode }>) {\n` +
987
+ ` return (\n <RuntimeSlot name="${slot}" props={props}>\n {children}\n </RuntimeSlot>\n );\n}\n`;
988
+
989
+ const changes = [
990
+ { file: target, before: fs.readFileSync(target, "utf8"), after: source },
991
+ { file: addedFile, before: addedBefore, after: added },
992
+ ];
993
+ const warnings = [];
994
+
995
+ // the slot list in the SDK types of the store (packages/extensions/src/types.ts), when it has one
996
+ const typesFile = path.join(root, "packages/extensions/src/types.ts");
997
+ if (fs.existsSync(typesFile)) {
998
+ const before = fs.readFileSync(typesFile, "utf8");
999
+ const lines = before.split("\n");
1000
+ const start = lines.findIndex((line) => /^\s*\/\/\s*Slots\s*\(/.test(line));
1001
+ if (start >= 0) {
1002
+ let end = start + 1;
1003
+ while (end < lines.length && /^\s*\/\/\s{3,}/.test(lines[end])) end++;
1004
+ lines.splice(end, 0, `// ${slot.padEnd(20)} the store's ${name} itself (children) props: every prop ${name} gets (znode create-slot)`);
1005
+ changes.push({ file: typesFile, before, after: lines.join("\n") });
1006
+ } else warnings.push(`${rel(typesFile)}: no "// Slots (" comment found; add "${slot}" to the slot list yourself`);
1007
+ }
1008
+ // the slot table in docs/RUNTIME_EXTENSIONS_AGENTS.md, when it has one
1009
+ const docsFile = path.join(root, "docs/RUNTIME_EXTENSIONS_AGENTS.md");
1010
+ if (fs.existsSync(docsFile)) {
1011
+ const before = fs.readFileSync(docsFile, "utf8");
1012
+ const lines = before.split("\n");
1013
+ let row = lines.findIndex((line) => line.startsWith("| `product.card`"));
1014
+ if (row >= 0) {
1015
+ while (row + 1 < lines.length && lines[row + 1].startsWith("|")) row++;
1016
+ lines.splice(row + 1, 0, `| \`${slot}\` | \`${wrapper}\` (\`${CREATED_SLOTS_FILE.replace("packages/extensions/src/", "")}\`) | \`${rel(target).replace(/^packages\/[\w-]+\/src\//, "").replace(/\.tsx$/, "")}\` (its children: the component itself) | every ${name} prop; keep \`children\`, wrap it, or render a copy instead (\`znode eject ${name}\`) |`);
1017
+ changes.push({ file: docsFile, before, after: lines.join("\n") });
1018
+ } else warnings.push(`${rel(docsFile)}: slot table not found; add a "${slot}" row yourself`);
1019
+ }
1020
+
1021
+ console.log(`${dryRun ? "would create" : "creating"} slot "${slot}" around ${name} (${rel(target)}) in ${root}\n`);
1022
+ for (const { file, before, after } of changes) {
1023
+ const old = new Set((before || "").split("\n"));
1024
+ const added = after.split("\n").filter((line) => !old.has(line));
1025
+ console.log(`${before === null ? "new " : "edit"} ${rel(file)}`);
1026
+ for (const line of added) console.log(` + ${line}`);
1027
+ }
1028
+ if (dryRun) {
1029
+ console.log("\n--dry-run: nothing written. Run it again without --dry-run to write these changes.");
1030
+ return;
1031
+ }
1032
+ for (const { file, after } of changes) fs.writeFileSync(file, after);
1033
+
1034
+ // the store's module registry, when the store generates one (the ejected copy's imports are checked against it)
1035
+ const registry = path.join(root, "scripts/gen-store-module-registry.mjs");
1036
+ if (fs.existsSync(registry)) spawnSync(process.execPath, [registry], { cwd: root, stdio: "inherit" });
1037
+ for (const warning of warnings) console.log(`warning ${warning}`);
1038
+ console.log(
1039
+ `\nDone (the store's source only: nothing committed, .next untouched). Next:\n` +
1040
+ ` 1. review the diff in ${root} (git diff) and commit it through the store's own flow (hooks, review: it edits base components)\n` +
1041
+ ` 2. rebuild / restart the webstore so it renders the slot\n` +
1042
+ ` 3. here: npx znode eject ${name} (or fill "${slot}" in src/browser.tsx with a component of your own)`
1043
+ );
1044
+ }
1045
+
1046
+ // ---- slot list: every slot the linked store renders, read from its source --------------------------------------
1047
+ // Each <RuntimeSlot name> (browser) and <RuntimeServerSlot name> (server) in the store's packages and apps, with the
1048
+ // store component it is around (the withRuntimeWrapper that renders the wrapper, else the file it is written in),
1049
+ // whether the slot is handed what the store renders there (children: keep, wrap or replace it) or only adds/lays out,
1050
+ // whether `znode eject` can copy the component into it, and whether this package already fills it.
1051
+ function storeSlots(root) {
1052
+ const slots = new Map();
1053
+ const files = [];
1054
+ const walk = (dir) => {
1055
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1056
+ const file = path.join(dir, entry.name);
1057
+ if (entry.isDirectory()) {
1058
+ if (!["node_modules", ".next", "dist", "out"].includes(entry.name) && !entry.name.startsWith("__")) walk(file);
1059
+ } else if (/\.tsx$/.test(entry.name) && !/\.(test|spec|stories)\.tsx$/.test(entry.name)) files.push(file);
1060
+ }
1061
+ };
1062
+ for (const dir of ["packages", "apps"]) if (fs.existsSync(path.join(root, dir))) walk(path.join(root, dir));
1063
+
1064
+ // wrapper -> the store components it is put around
1065
+ const components = {};
1066
+ for (const file of files) {
1067
+ for (const m of fs.readFileSync(file, "utf8").matchAll(/withRuntimeWrapper\(\s*(\w+)\s*,\s*\w+\s*,\s*["'](\w+)["']\s*\)/g)) (components[m[1]] ||= []).push(m[2]);
1068
+ }
1069
+ const handover = storeWrapperSlots(root);
1070
+ const slotsDir = path.join(root, "packages/extensions/src/slots");
1071
+ for (const file of files) {
1072
+ const text = fs.readFileSync(file, "utf8");
1073
+ const wrappers = file.startsWith(slotsDir) ? [...text.matchAll(/export\s+function\s+(Runtime\w+)/g)] : [];
1074
+ for (const m of text.matchAll(/<Runtime(Server)?Slot\s+name=["']([\w.]+)["']/g)) {
1075
+ const name = m[2];
1076
+ const tag = m[1] ? "RuntimeServerSlot" : "RuntimeSlot";
1077
+ const rest = text.slice(m.index + m[0].length, m.index + 2000);
1078
+ const close = rest.indexOf(`</${tag}>`);
1079
+ const next = rest.search(/<Runtime(Server)?Slot\s/);
1080
+ const wraps = close >= 0 && (next < 0 || close < next);
1081
+ const wrapper = wrappers.filter((w) => w.index < m.index).pop()?.[1];
1082
+ const relFile = path.relative(root, file).split(path.sep).join("/");
1083
+ const existing = slots.get(name);
1084
+ if (existing) {
1085
+ existing.files.push(relFile);
1086
+ continue;
1087
+ }
1088
+ // a slot written in a route file: the route (app/login/page), else the component file it is written in
1089
+ const where = /^apps\/[^/]+\/src\/app\//.test(relFile)
1090
+ ? "app/" + relFile.replace(/^apps\/[^/]+\/src\/app\/(\[locale\]\/)?/, "").replace(/\.tsx$/, "")
1091
+ : path.basename(file, ".tsx");
1092
+ const around = wrapper ? [...new Set(components[wrapper] || [])] : [where];
1093
+ slots.set(name, {
1094
+ name,
1095
+ side: m[1] ? "server" : "browser",
1096
+ handsOver: wraps,
1097
+ wrapper: wrapper || null,
1098
+ components: around,
1099
+ eject: wrapper && handover[wrapper] === name ? around[0] || null : null,
1100
+ files: [relFile],
1101
+ });
1102
+ }
1103
+ }
1104
+ return [...slots.values()].sort((a, b) => a.name.localeCompare(b.name));
1105
+ }
1106
+
1107
+ function slotList(filter, json) {
1108
+ const project = path.resolve(".");
1109
+ const store = linkedStore(project);
1110
+ if (!store) fail("not linked to a store: npm run link-store -- <store repo> (the slot list is read from the store's source)");
1111
+ let slots = storeSlots(store.root);
1112
+ // what this package fills (src/browser.tsx slots, src/server.tsx serverSlots)
1113
+ const filled = (file) => (fs.existsSync(path.join(project, "src", file)) ? fs.readFileSync(path.join(project, "src", file), "utf8") : "");
1114
+ const browser = filled("browser.tsx");
1115
+ const server = filled("server.tsx");
1116
+ for (const slot of slots) {
1117
+ const pattern = new RegExp(`["']${slot.name.replace(/\./g, "\\.")}["']\\s*:`);
1118
+ slot.filledByPackage = pattern.test(slot.side === "server" ? server : browser);
1119
+ }
1120
+ if (filter) slots = slots.filter((s) => [s.name, ...s.components].some((value) => value.toLowerCase().includes(filter.toLowerCase())));
1121
+ if (json) {
1122
+ console.log(JSON.stringify({ store: store.root, slots }, null, 2));
1123
+ return;
1124
+ }
1125
+ if (!slots.length) {
1126
+ console.log(filter ? `no slot matches "${filter}"` : "the linked store has no runtime slots");
1127
+ return;
1128
+ }
1129
+ const rows = [["Slot", "Side", "Hands over", "Store component", "Eject", "In this package"]];
1130
+ for (const s of slots) rows.push([s.name, s.side, s.handsOver ? "yes" : "no", s.components.join(", ") || "-", s.eject || "-", s.filledByPackage ? "yes" : ""]);
1131
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((row) => row[i].length)));
1132
+ console.log(`Slots in the linked store (${store.root}):\n`);
1133
+ rows.forEach((row, i) => {
1134
+ console.log(" " + row.map((cell, j) => cell.padEnd(widths[j])).join(" ").trimEnd());
1135
+ if (i === 0) console.log(" " + widths.map((w) => "-".repeat(w)).join(" "));
1136
+ });
1137
+ console.log(
1138
+ `\n Hands over: yes = the slot gets what the store renders there (children): keep it, wrap it or replace it; no = it adds or lays out.\n` +
1139
+ ` Fill one in src/browser.tsx (slots) or src/server.tsx (serverSlots). Eject: npx znode eject <component or slot>.\n` +
1140
+ ` No slot where you need one: npx znode create-slot <Component> <area.name> (in the base store). --json for the full list.`
1141
+ );
1142
+ }
1143
+
1144
+ const args = process.argv.slice(2);
1145
+ // the store's plugin folder: the argument, else RUNTIME_PLUGINS_DIR, else the project's git-ignored znode.local.json
1146
+ // ({ "pluginsDir": "…" }, written by create-znode-plugin --plugins-dir) in the folder the command runs in
1147
+ function localPluginsDir() {
1148
+ try {
1149
+ return JSON.parse(fs.readFileSync(path.resolve("znode.local.json"), "utf8")).pluginsDir || undefined;
1150
+ } catch {
1151
+ return undefined;
1152
+ }
1153
+ }
1154
+ const [command, target, storeDir = process.env.RUNTIME_PLUGINS_DIR || localPluginsDir()] = args;
1155
+ // create-slot <Component> <area.name> (also "create slot …"; add-slot is the 0.1.6 name, kept so it still works)
1156
+ const slotCommand = ["create-slot", "add-slot"].includes(command) ? 1 : (command === "create" || command === "add") && args[1] === "slot" ? 2 : 0;
1157
+ if (slotCommand) {
1158
+ const rest = args.slice(slotCommand).filter((arg) => arg !== "--");
1159
+ const fileAt = rest.indexOf("--file");
1160
+ const file = fileAt >= 0 ? rest[fileAt + 1] : undefined;
1161
+ const positional = rest.filter((arg, index) => !arg.startsWith("--") && !(fileAt >= 0 && index === fileAt + 1));
1162
+ createSlot(positional[0], positional[1], { dryRun: rest.includes("--dry-run"), file });
1163
+ process.exit(0);
1164
+ }
1165
+ // slot list [filter] [--json] (also "slots", "slot", "slot lists")
1166
+ if (command === "slots" || (command === "slot" && (!args[1] || /^lists?$/.test(args[1]) || args[1].startsWith("--")))) {
1167
+ const rest = args.slice(command === "slot" && /^lists?$/.test(args[1] || "") ? 2 : 1);
1168
+ slotList(rest.find((arg) => !arg.startsWith("--")), rest.includes("--json"));
1169
+ process.exit(0);
1170
+ }
1171
+ if (command === "create") {
1172
+ create(args[1], args[2], args[3]);
1173
+ process.exit(0);
1174
+ }
1175
+ if (command === "eject") {
1176
+ eject(args.find((arg, index) => index > 0 && !arg.startsWith("--")), args.includes("--force"));
1177
+ process.exit(0);
1178
+ }
1179
+ if (command === "link-store") {
1180
+ if (!target) fail("usage: znode link-store <storeRepoDir> [projectDir]");
1181
+ linkStore(target, args[2]);
1182
+ process.exit(0);
1183
+ }
1184
+ if (!target) fail("usage: znode <build|pack|check|install|deploy|dev> <dir|zip> [storeDir], znode create <kind> <name> [dir], znode link-store <storeRepoDir>");
1185
+ if (command === "check") check(path.resolve(target));
1186
+ else if (command === "build") build(path.resolve(target));
1187
+ else if (command === "pack") pack(path.resolve(target));
1188
+ else if (command === "install") install(path.resolve(target), path.resolve(needStore(storeDir)));
1189
+ else if (command === "deploy") deploy(path.resolve(target), path.resolve(needStore(storeDir)));
1190
+ else if (command === "dev") dev(path.resolve(target), path.resolve(needStore(storeDir)));
1191
+ else fail(`unknown command "${command}"`);