@mostra/runtime 0.14.0 → 0.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- package/dist/child-protocol-CPXR6pMu.js +13 -0
- package/dist/child-protocol-CPXR6pMu.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{instance-CFTw3g-c.js → instance-Bw1BxctF.js} +2581 -189
- package/dist/instance-Bw1BxctF.js.map +1 -0
- package/dist/plugins/child/host.d.ts +1 -0
- package/dist/plugins/child/host.js +165 -0
- package/dist/plugins/child/host.js.map +1 -0
- package/dist/reference/cli.md +147 -5
- package/dist/reference/diagnostics.json +234 -0
- package/dist/reference/errors/MOSTRA_LICENSE_ACCEPT_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_LICENSE_MISMATCH.md +23 -0
- package/dist/reference/errors/MOSTRA_LICENSE_UNACCEPTED.md +23 -0
- package/dist/reference/errors/MOSTRA_LICENSE_UNDECLARED.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_ADDRESS_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_CSS_UNIMPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_FETCH_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_FILE_EXISTS.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_ITEM_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_ITEM_NOT_FOUND.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_NOT_APPLIED.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_OFFLINE.md +23 -0
- package/dist/reference/errors/MOSTRA_PACK_TARGET_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_CONFLICT.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_ENTRY_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_EXPORTER_UNKNOWN.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_WARNING.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_NOT_A_PLUGIN.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_NOT_INSTALLED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_OPTIONS_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_PLATFORM_UNSUPPORTED.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_SCOPE_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_PLUGIN_SHADOWED.md +23 -0
- package/dist/skill/SKILL.md +4 -2
- package/dist/skill/references/mcp.md +2 -2
- package/dist/skill/references/plugins.md +51 -0
- package/package.json +10 -7
- package/src/deps/index.ts +407 -90
- package/src/deps/installer.ts +53 -10
- package/src/deps/lock.ts +74 -2
- package/src/home/settings.ts +3 -0
- package/src/instance/index.ts +57 -0
- package/src/packs/index.ts +7 -0
- package/src/packs/methods.ts +49 -0
- package/src/packs/packs.ts +706 -0
- package/src/packs/read.ts +759 -0
- package/src/platform/index.ts +1 -0
- package/src/platform/shell.ts +14 -0
- package/src/plugins/child/host.ts +231 -0
- package/src/plugins/child-protocol.ts +68 -0
- package/src/plugins/index.ts +7 -0
- package/src/plugins/location.ts +109 -0
- package/src/plugins/methods.ts +269 -0
- package/src/plugins/plugins.ts +1396 -0
- package/src/publish/publisher.ts +71 -3
- package/dist/instance-CFTw3g-c.js.map +0 -1
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Source packs (D30, ROUND-3 §6.3, EX-03): `pack/add`, which `mostra add` calls. It copies shadcn
|
|
3
|
+
* registry items (with or without a `mostra` block) into an artifact's source, as shadcn's own
|
|
4
|
+
* `add` would into a project, so any shadcn item installs unchanged:
|
|
5
|
+
*
|
|
6
|
+
* 1. every item is read with its registry dependencies (`read.ts`), before anything is written;
|
|
7
|
+
* 2. each file's place is found as shadcn finds it (`target`, `~/`, the `@components/`, `@ui/`,
|
|
8
|
+
* `@lib/` and `@hooks/` aliases, else the directory of its type), checked against the artifact
|
|
9
|
+
* (`checkArtifactPath`, no link out of it, no name differing from another only in case), and
|
|
10
|
+
* `@/registry/<style>/…` imports point at the aliases;
|
|
11
|
+
* 3. CSS (`cssVars`, `css`) joins one stylesheet in a block per item, replaced when the item is
|
|
12
|
+
* added again: `components.json`'s `tailwind.css`, else a stylesheet the entry imports, else a
|
|
13
|
+
* new `styles.css`;
|
|
14
|
+
* 4. npm packages (the items' `dependencies` and any plain specs) are added as `deps/add` adds
|
|
15
|
+
* them in one change of the working lockfile, which passes the plugin gate: the artifact's
|
|
16
|
+
* plugins as they stand, and the licenses the items' packages and the items themselves
|
|
17
|
+
* (`mostra.license`) bring, disclosed and acknowledged as a plugin's are (D31), before any
|
|
18
|
+
* of the packages' scripts run;
|
|
19
|
+
* 5. only once the layout is complete are the files written, each through a temporary file
|
|
20
|
+
* renamed into place, checked again for clashes just before; every one is restored when any
|
|
21
|
+
* fails or the lockfile can't be recorded.
|
|
22
|
+
*
|
|
23
|
+
* What an artifact has no place for (`envVars`, Tailwind 3's `tailwind.config`, `next/font`, a
|
|
24
|
+
* design system's `registry:base`) is listed as notes, never applied half-way.
|
|
25
|
+
*/
|
|
26
|
+
import { randomBytes } from "node:crypto";
|
|
27
|
+
import { existsSync } from "node:fs";
|
|
28
|
+
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
29
|
+
import { basename, dirname, join, posix } from "node:path";
|
|
30
|
+
import {
|
|
31
|
+
checkArtifactPath,
|
|
32
|
+
createDiagnostic,
|
|
33
|
+
type Diagnostic,
|
|
34
|
+
type PackAddResult,
|
|
35
|
+
type PackFileChange,
|
|
36
|
+
type PackItemSummary,
|
|
37
|
+
RpcError,
|
|
38
|
+
} from "@mostra/protocol";
|
|
39
|
+
import {
|
|
40
|
+
parsePackAddress,
|
|
41
|
+
type RegistryCssValue,
|
|
42
|
+
type RegistryItem,
|
|
43
|
+
} from "@mostra/protocol/plugin";
|
|
44
|
+
import type { Dependencies, DependencyTarget, StagedWrite } from "../deps/index.ts";
|
|
45
|
+
import { isOffline } from "../deps/index.ts";
|
|
46
|
+
import type { RequestKey } from "../ledger/index.ts";
|
|
47
|
+
import type { Environment, Log } from "../log.ts";
|
|
48
|
+
import { shellWord } from "../platform/index.ts";
|
|
49
|
+
import type { ItemLicense, Plugins } from "../plugins/index.ts";
|
|
50
|
+
import { type ReadItem, readComponentsJson, readItems, withoutTrailingSlashes } from "./read.ts";
|
|
51
|
+
|
|
52
|
+
/** Options for {@link createPacks}. */
|
|
53
|
+
export interface PacksOptions {
|
|
54
|
+
readonly dependencies: Dependencies;
|
|
55
|
+
readonly plugins: Plugins;
|
|
56
|
+
readonly log: Log;
|
|
57
|
+
readonly env: Environment;
|
|
58
|
+
/** GitHub's API and raw-file origins, for tests' local fakes (`MOSTRA_TEST_GITHUB_*`). */
|
|
59
|
+
readonly github?: { readonly api: string; readonly raw: string };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The packs of one instance. */
|
|
63
|
+
export interface Packs {
|
|
64
|
+
/** `pack/add`, for an artifact the publisher resolved and holds the queue of. */
|
|
65
|
+
add(input: {
|
|
66
|
+
readonly target: DependencyTarget;
|
|
67
|
+
/** The artifact's directory, and whether it is a directory artifact (a single file takes none). */
|
|
68
|
+
readonly root: string;
|
|
69
|
+
readonly kind: "file" | "dir";
|
|
70
|
+
/** The entry, relative to `root`. */
|
|
71
|
+
readonly entry: string;
|
|
72
|
+
readonly specs: readonly string[];
|
|
73
|
+
readonly overwrite: boolean;
|
|
74
|
+
readonly accept: readonly string[];
|
|
75
|
+
readonly request?: RequestKey | undefined;
|
|
76
|
+
/** Where relative item files are read from (the caller's working directory). */
|
|
77
|
+
readonly cwd: string;
|
|
78
|
+
/** The caller's variables for reading the items, over the instance's (`packVariables`). */
|
|
79
|
+
readonly environment?: Readonly<Record<string, string>>;
|
|
80
|
+
}): Promise<PackAddResult>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The default aliases, as `npx shadcn init` writes them, with `@/` the artifact's root. */
|
|
84
|
+
const DEFAULT_ALIASES = {
|
|
85
|
+
components: "components",
|
|
86
|
+
ui: "components/ui",
|
|
87
|
+
lib: "lib",
|
|
88
|
+
hooks: "hooks",
|
|
89
|
+
utils: "lib/utils",
|
|
90
|
+
} as const;
|
|
91
|
+
|
|
92
|
+
/** Names a pack never writes: the artifact's packages and Mostra's own state. */
|
|
93
|
+
const RESERVED = new Set(["node_modules", ".mostra", ".git"]);
|
|
94
|
+
|
|
95
|
+
const fail = (code: Parameters<typeof createDiagnostic>[0], message: string): RpcError =>
|
|
96
|
+
new RpcError(createDiagnostic(code, { message }));
|
|
97
|
+
|
|
98
|
+
/** One file a pack writes. */
|
|
99
|
+
interface PlannedFile {
|
|
100
|
+
/** `/`-separated, inside the artifact. */
|
|
101
|
+
readonly path: string;
|
|
102
|
+
readonly content: string;
|
|
103
|
+
readonly item: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** An alias of `components.json` as a path inside the artifact (`@/components/ui` → `components/ui`). */
|
|
107
|
+
function aliasPath(value: string | undefined, fallback: string): string {
|
|
108
|
+
if (value === undefined) return fallback;
|
|
109
|
+
return withoutTrailingSlashes(value.replace(/^@\//, "").replace(/^~\//, "")) || fallback;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Where a file of an item goes, as shadcn's `resolveFilePath` places it (shadcn 4.23.0). */
|
|
113
|
+
export function placeFile(
|
|
114
|
+
file: { readonly path: string; readonly type: string; readonly target?: string },
|
|
115
|
+
aliases: {
|
|
116
|
+
readonly components: string;
|
|
117
|
+
readonly ui: string;
|
|
118
|
+
readonly lib: string;
|
|
119
|
+
readonly hooks: string;
|
|
120
|
+
},
|
|
121
|
+
/** The artifact has `pages/` (D57): a page goes there; without it a page has no place. */
|
|
122
|
+
pages = true,
|
|
123
|
+
): string | undefined {
|
|
124
|
+
const target = file.target;
|
|
125
|
+
if (target !== undefined) {
|
|
126
|
+
if (target.startsWith("~/")) return target.slice(2);
|
|
127
|
+
const alias = /^@(components|ui|lib|hooks)\/(.+)$/.exec(target);
|
|
128
|
+
if (alias) {
|
|
129
|
+
const root = aliases[alias[1] as keyof typeof aliases];
|
|
130
|
+
const placed = posix.normalize(posix.join(root, alias[2] as string));
|
|
131
|
+
if (placed !== root && !placed.startsWith(`${root}/`)) {
|
|
132
|
+
throw fail(
|
|
133
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
134
|
+
`The target ${target} leaves the ${alias[1]} alias's directory.`,
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
return placed;
|
|
138
|
+
}
|
|
139
|
+
// Any other `@name/…` is a plain path, as shadcn reads it.
|
|
140
|
+
const plain = target.replace(/^@([^/]+)\//, "$1/").replace(/^src\//, "");
|
|
141
|
+
if (file.type === "registry:page") {
|
|
142
|
+
// Next.js's `app/<route>/page.tsx` is Mostra's `pages/<route>.tsx` (D57), as shadcn maps it
|
|
143
|
+
// for the pages router; an artifact without `pages/` has no routes, so, as shadcn does for
|
|
144
|
+
// a framework without them, the page isn't written.
|
|
145
|
+
if (!pages) return undefined;
|
|
146
|
+
return plain.replace(/^app\//, "pages/").replace(/\/page(\.[jt]sx?)$/, "$1");
|
|
147
|
+
}
|
|
148
|
+
return plain;
|
|
149
|
+
}
|
|
150
|
+
const dir =
|
|
151
|
+
file.type === "registry:ui"
|
|
152
|
+
? aliases.ui
|
|
153
|
+
: file.type === "registry:lib"
|
|
154
|
+
? aliases.lib
|
|
155
|
+
: file.type === "registry:hook"
|
|
156
|
+
? aliases.hooks
|
|
157
|
+
: aliases.components;
|
|
158
|
+
// The part of the item's path after the segment that names the directory (`ui` of
|
|
159
|
+
// `registry/new-york/ui/button.tsx`), else its file name.
|
|
160
|
+
const segments = file.path.replace(/^\/|\/$/g, "").split("/");
|
|
161
|
+
const last = dir.split("/").at(-1);
|
|
162
|
+
const at = segments.indexOf(last ?? "");
|
|
163
|
+
const rest = at === -1 ? (segments.at(-1) as string) : segments.slice(at + 1).join("/");
|
|
164
|
+
return posix.join(dir, rest);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Points `@/registry/<style>/<kind>/…` imports at the artifact's aliases, as shadcn rewrites them. */
|
|
168
|
+
export function rewriteImports(
|
|
169
|
+
content: string,
|
|
170
|
+
aliases: {
|
|
171
|
+
readonly components: string;
|
|
172
|
+
readonly ui: string;
|
|
173
|
+
readonly lib: string;
|
|
174
|
+
readonly hooks: string;
|
|
175
|
+
},
|
|
176
|
+
placed: ReadonlyMap<string, string> = new Map(),
|
|
177
|
+
): string {
|
|
178
|
+
const exact = content.replace(
|
|
179
|
+
/(["'])@\/(registry\/[^"']+)(["'])/g,
|
|
180
|
+
(whole, open: string, path: string, close: string) => {
|
|
181
|
+
const target = placed.get(path.replace(/\.[jt]sx?$/, ""));
|
|
182
|
+
return target === undefined ? whole : `${open}@/${target.replace(/\.[jt]sx?$/, "")}${close}`;
|
|
183
|
+
},
|
|
184
|
+
);
|
|
185
|
+
return exact.replace(
|
|
186
|
+
/(["'])@\/registry\/[^/"']+\/(ui|lib|hooks|components|blocks|examples)\//g,
|
|
187
|
+
(_, quote: string, kind: string) => {
|
|
188
|
+
const root =
|
|
189
|
+
kind === "ui"
|
|
190
|
+
? aliases.ui
|
|
191
|
+
: kind === "lib"
|
|
192
|
+
? aliases.lib
|
|
193
|
+
: kind === "hooks"
|
|
194
|
+
? aliases.hooks
|
|
195
|
+
: aliases.components;
|
|
196
|
+
return `${quote}@/${root}/`;
|
|
197
|
+
},
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Serializes an item's `css` the way shadcn writes it into a stylesheet. */
|
|
202
|
+
export function cssText(css: { readonly [key: string]: RegistryCssValue }, indent = ""): string {
|
|
203
|
+
const lines: string[] = [];
|
|
204
|
+
for (const [key, value] of Object.entries(css)) {
|
|
205
|
+
if (typeof value === "string") {
|
|
206
|
+
lines.push(`${indent}${key}: ${value};`);
|
|
207
|
+
} else if (Array.isArray(value)) {
|
|
208
|
+
for (const entry of value) {
|
|
209
|
+
if (typeof entry === "string") lines.push(`${indent}${key}: ${entry};`);
|
|
210
|
+
else {
|
|
211
|
+
lines.push(`${indent}${key} {`);
|
|
212
|
+
lines.push(cssText(entry as Record<string, RegistryCssValue>, `${indent} `));
|
|
213
|
+
lines.push(`${indent}}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
} else if (Object.keys(value as object).length === 0 && key.startsWith("@")) {
|
|
217
|
+
// An at-rule without a block: `@plugin "x"`, `@import "y"`.
|
|
218
|
+
lines.push(`${indent}${key};`);
|
|
219
|
+
} else {
|
|
220
|
+
lines.push(`${indent}${key} {`);
|
|
221
|
+
lines.push(cssText(value as Record<string, RegistryCssValue>, `${indent} `));
|
|
222
|
+
lines.push(`${indent}}`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return lines.filter((line) => line !== "").join("\n");
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The CSS an item adds: its variables and its rules. */
|
|
229
|
+
export function itemCss(item: RegistryItem): string | undefined {
|
|
230
|
+
const parts: string[] = [];
|
|
231
|
+
const declarations = (record: Readonly<Record<string, string>>): string[] =>
|
|
232
|
+
Object.entries(record).map(([name, value]) => ` --${name.replace(/^--/, "")}: ${value};`);
|
|
233
|
+
const light = item.cssVars?.light ?? {};
|
|
234
|
+
const dark = item.cssVars?.dark ?? {};
|
|
235
|
+
// As shadcn 4.23.0 writes them: a light or dark variable that holds a colour is a Tailwind
|
|
236
|
+
// colour (`--color-<name>: var(--<name>)`, so `bg-<name>` works), and `radius` gives the radius
|
|
237
|
+
// scale; the theme's own variables go in as they are.
|
|
238
|
+
const theme: Record<string, string> = { ...(item.cssVars?.theme ?? {}) };
|
|
239
|
+
for (const name of new Set([...Object.keys(light), ...Object.keys(dark)])) {
|
|
240
|
+
const bare = name.replace(/^--/, "");
|
|
241
|
+
const value = light[name] ?? dark[name] ?? "";
|
|
242
|
+
if (bare === "radius") {
|
|
243
|
+
Object.assign(theme, RADIUS_SCALE);
|
|
244
|
+
} else if (isColour(value)) {
|
|
245
|
+
const key = bare === "sidebar-background" ? "color-sidebar" : `color-${bare}`;
|
|
246
|
+
theme[key] ??= bare === "sidebar-background" ? "var(--sidebar)" : `var(--${bare})`;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (Object.keys(dark).length > 0) parts.push("@custom-variant dark (&:is(.dark *));");
|
|
250
|
+
if (Object.keys(theme).length > 0)
|
|
251
|
+
parts.push(`@theme inline {\n${declarations(theme).join("\n")}\n}`);
|
|
252
|
+
if (Object.keys(light).length > 0) parts.push(`:root {\n${declarations(light).join("\n")}\n}`);
|
|
253
|
+
if (Object.keys(dark).length > 0) parts.push(`.dark {\n${declarations(dark).join("\n")}\n}`);
|
|
254
|
+
if (item.css !== undefined && Object.keys(item.css).length > 0) parts.push(cssText(item.css));
|
|
255
|
+
return parts.length > 0 ? parts.join("\n\n") : undefined;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** The radius scale shadcn derives from `radius`. */
|
|
259
|
+
const RADIUS_SCALE: Readonly<Record<string, string>> = {
|
|
260
|
+
"radius-sm": "calc(var(--radius) * 0.6)",
|
|
261
|
+
"radius-md": "calc(var(--radius) * 0.8)",
|
|
262
|
+
"radius-lg": "var(--radius)",
|
|
263
|
+
"radius-xl": "calc(var(--radius) * 1.4)",
|
|
264
|
+
"radius-2xl": "calc(var(--radius) * 1.8)",
|
|
265
|
+
"radius-3xl": "calc(var(--radius) * 2.2)",
|
|
266
|
+
"radius-4xl": "calc(var(--radius) * 2.6)",
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
/** Whether a variable's value is a colour, as shadcn judges it. */
|
|
270
|
+
function isColour(value: string): boolean {
|
|
271
|
+
if (/^(?:hsl|rgb|#|oklch)/.test(value) || value.includes("--color-")) return true;
|
|
272
|
+
const parts = value.split(" ");
|
|
273
|
+
return parts.length === 3 && parts.slice(1).every((part) => part.includes("%"));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** `css` with the block of `item` set to `block` (added at the end the first time). */
|
|
277
|
+
export function withCssBlock(css: string, item: string, block: string): string {
|
|
278
|
+
const begin = `/* mostra add ${item}: begin */`;
|
|
279
|
+
const end = `/* mostra add ${item}: end */`;
|
|
280
|
+
const text = `${begin}\n${block}\n${end}`;
|
|
281
|
+
const start = css.indexOf(begin);
|
|
282
|
+
const stop = css.indexOf(end);
|
|
283
|
+
if (start !== -1 && stop > start)
|
|
284
|
+
return `${css.slice(0, start)}${text}${css.slice(stop + end.length)}`;
|
|
285
|
+
return `${css.trimEnd()}${css.trim() === "" ? "" : "\n\n"}${text}\n`;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** The stylesheets an entry imports, relative to the root (`import "./styles.css"`). */
|
|
289
|
+
function importedStylesheets(entryText: string, entry: string): string[] {
|
|
290
|
+
const found: string[] = [];
|
|
291
|
+
for (const match of entryText.matchAll(/import\s+(?:[^"';]+\s+from\s+)?["']([^"']+\.css)["']/g)) {
|
|
292
|
+
const specifier = match[1] as string;
|
|
293
|
+
if (specifier.startsWith("./") || specifier.startsWith("../")) {
|
|
294
|
+
found.push(posix.normalize(posix.join(posix.dirname(entry), specifier)));
|
|
295
|
+
} else if (specifier.startsWith("@/")) found.push(specifier.slice(2));
|
|
296
|
+
}
|
|
297
|
+
return found;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Creates the packs of one instance. */
|
|
301
|
+
export function createPacks(options: PacksOptions): Packs {
|
|
302
|
+
const { dependencies, plugins, log } = options;
|
|
303
|
+
return {
|
|
304
|
+
async add(input) {
|
|
305
|
+
const components = input.kind === "dir" ? await readComponentsJson(input.root) : undefined;
|
|
306
|
+
// `@scope/name` is an item only where the artifact's components.json registers `@scope`, as
|
|
307
|
+
// shadcn reads it; anywhere else it is the scoped npm package it looks like.
|
|
308
|
+
const isItem = (spec: string): boolean => {
|
|
309
|
+
const address = parsePackAddress(spec);
|
|
310
|
+
if (address === undefined) return false;
|
|
311
|
+
if (address.kind !== "namespace") return true;
|
|
312
|
+
return components?.registries?.[address.namespace] !== undefined;
|
|
313
|
+
};
|
|
314
|
+
const itemSpecs = input.specs.filter(isItem);
|
|
315
|
+
const plainSpecs = input.specs.filter((spec) => !isItem(spec));
|
|
316
|
+
// A single file holds no other files: items need a directory artifact; npm packages don't.
|
|
317
|
+
if (input.kind === "file" && itemSpecs.length > 0) {
|
|
318
|
+
throw fail(
|
|
319
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
320
|
+
`${input.target.artifactPath} is a single-file artifact, which holds no other files: move it into a directory (as index.tsx) to add ${itemSpecs.join(", ")} to it.`,
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
const env: Environment = { ...options.env, ...(input.environment ?? {}) };
|
|
324
|
+
const items: ReadItem[] =
|
|
325
|
+
itemSpecs.length === 0
|
|
326
|
+
? []
|
|
327
|
+
: await readItems(
|
|
328
|
+
itemSpecs,
|
|
329
|
+
{
|
|
330
|
+
...(components !== undefined ? { components } : {}),
|
|
331
|
+
env,
|
|
332
|
+
offline: isOffline(options.env),
|
|
333
|
+
pluginItem: (pkg, name) => plugins.packItem(input.target, pkg, name),
|
|
334
|
+
...(options.github !== undefined ? { github: options.github } : {}),
|
|
335
|
+
},
|
|
336
|
+
input.cwd,
|
|
337
|
+
);
|
|
338
|
+
const aliases = {
|
|
339
|
+
components: aliasPath(components?.aliases?.["components"], DEFAULT_ALIASES.components),
|
|
340
|
+
ui: aliasPath(components?.aliases?.["ui"], DEFAULT_ALIASES.ui),
|
|
341
|
+
lib: aliasPath(components?.aliases?.["lib"], DEFAULT_ALIASES.lib),
|
|
342
|
+
hooks: aliasPath(components?.aliases?.["hooks"], DEFAULT_ALIASES.hooks),
|
|
343
|
+
};
|
|
344
|
+
const notes: Diagnostic[] = [];
|
|
345
|
+
const note = (message: string) =>
|
|
346
|
+
notes.push(createDiagnostic("MOSTRA_PACK_NOT_APPLIED", { message }));
|
|
347
|
+
|
|
348
|
+
// 2. Every file's place, checked, and what it would do.
|
|
349
|
+
const planned = new Map<string, PlannedFile>();
|
|
350
|
+
const hasPages = existsSync(join(input.root, "pages"));
|
|
351
|
+
const places: { read: ReadItem; index: number; path: string }[] = [];
|
|
352
|
+
const placedByRegistryPath = new Map<string, string>();
|
|
353
|
+
for (const read of items) {
|
|
354
|
+
(read.item.files ?? []).forEach((file, index) => {
|
|
355
|
+
const placed = placeFile(file, aliases, hasPages);
|
|
356
|
+
if (placed === undefined) {
|
|
357
|
+
note(
|
|
358
|
+
`${read.item.name}'s page ${file.target ?? file.path} wasn't written: the artifact has no pages/ (D57). Add pages/ to make it multi-page, then add the item again.`,
|
|
359
|
+
);
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
const check = checkArtifactPath(placed);
|
|
363
|
+
if (!check.ok) {
|
|
364
|
+
throw fail(
|
|
365
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
366
|
+
check.reason === "outside"
|
|
367
|
+
? `${read.item.name}'s file ${file.path} would land at ${placed}, outside the artifact.`
|
|
368
|
+
: `${read.item.name}'s file ${file.path} would land at ${placed}, whose name "${check.segment}" not every system can hold.`,
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
const top = check.path.split("/")[0] as string;
|
|
372
|
+
if (RESERVED.has(top)) {
|
|
373
|
+
throw fail(
|
|
374
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
375
|
+
`${read.item.name}'s file ${file.path} would land in ${top}/, which an artifact's source never holds.`,
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
places.push({ read, index, path: check.path });
|
|
379
|
+
placedByRegistryPath.set(
|
|
380
|
+
file.path.replace(/^\//, "").replace(/\.[jt]sx?$/, ""),
|
|
381
|
+
check.path,
|
|
382
|
+
);
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
for (const { read, index, path } of places) {
|
|
386
|
+
const file = (read.item.files ?? [])[index] as { type: string };
|
|
387
|
+
const content =
|
|
388
|
+
file.type === "registry:file" || file.type === "registry:item"
|
|
389
|
+
? (read.contents[index] as string)
|
|
390
|
+
: rewriteImports(read.contents[index] as string, aliases, placedByRegistryPath);
|
|
391
|
+
const key = path.toLowerCase();
|
|
392
|
+
const earlier = planned.get(key);
|
|
393
|
+
if (earlier !== undefined && earlier.path !== path) {
|
|
394
|
+
throw fail(
|
|
395
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
396
|
+
`${earlier.path} and ${path} differ only in case, which not every system can hold apart.`,
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
// A later item's file wins over an earlier one's, as shadcn writes them in order.
|
|
400
|
+
planned.set(key, { path, content, item: read.item.name });
|
|
401
|
+
}
|
|
402
|
+
for (const read of items) {
|
|
403
|
+
if (read.item.envVars !== undefined && Object.keys(read.item.envVars).length > 0) {
|
|
404
|
+
note(
|
|
405
|
+
`${read.item.name} asks for environment variables (${Object.keys(read.item.envVars).join(", ")}); an artifact's server code reads secrets instead: mostra secret set NAME --artifact <path>.`,
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
if (read.item.tailwind !== undefined && Object.keys(read.item.tailwind).length > 0) {
|
|
409
|
+
note(
|
|
410
|
+
`${read.item.name} carries a Tailwind 3 configuration (tailwind.config), which Tailwind 4 doesn't read; move its theme into your stylesheet's @theme.`,
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
if (read.item.font !== undefined) {
|
|
414
|
+
note(
|
|
415
|
+
`${read.item.name} installs the font ${read.item.font.family} through ${read.item.font.provider}; load it yourself (${read.item.font.dependency ?? "a @fontsource package"}) and set ${read.item.font.variable}.`,
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
if (read.item.type === "registry:base" || read.item.type === "registry:style") {
|
|
419
|
+
note(
|
|
420
|
+
`${read.item.name} is a ${read.item.type}, a project configuration an artifact doesn't take; its CSS and files were added.`,
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// 3. CSS: into one stylesheet.
|
|
426
|
+
const cssBlocks = items
|
|
427
|
+
.map((read) => ({ name: read.item.name, css: itemCss(read.item) }))
|
|
428
|
+
.filter((entry): entry is { name: string; css: string } => entry.css !== undefined);
|
|
429
|
+
let stylesheet: { path: string; before: string | undefined; after: string } | undefined;
|
|
430
|
+
if (cssBlocks.length > 0) {
|
|
431
|
+
const entryText = await readFile(join(input.root, input.entry), "utf8").catch(() => "");
|
|
432
|
+
const imported = importedStylesheets(entryText, input.entry);
|
|
433
|
+
const configured = components?.tailwind?.css;
|
|
434
|
+
const path = configured
|
|
435
|
+
? aliasPath(configured, configured).replace(/^\.\//, "")
|
|
436
|
+
: (imported[0] ?? "styles.css");
|
|
437
|
+
const check = checkArtifactPath(path);
|
|
438
|
+
if (!check.ok) {
|
|
439
|
+
throw fail(
|
|
440
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
441
|
+
`The stylesheet ${path} isn't a path inside the artifact.`,
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
const before = await readFile(join(input.root, check.path), "utf8").catch(() => undefined);
|
|
445
|
+
let after = before ?? '@import "tailwindcss";\n';
|
|
446
|
+
for (const block of cssBlocks) after = withCssBlock(after, block.name, block.css);
|
|
447
|
+
stylesheet = { path: check.path, before, after };
|
|
448
|
+
if (!imported.includes(check.path)) {
|
|
449
|
+
notes.push(
|
|
450
|
+
createDiagnostic("MOSTRA_PACK_CSS_UNIMPORTED", {
|
|
451
|
+
message: `The items' CSS is in ${check.path}, which ${input.entry} doesn't import yet: add import "./${check.path}"; to it.`,
|
|
452
|
+
}),
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
for (const file of planned.values()) {
|
|
458
|
+
if (stylesheet !== undefined && file.path === stylesheet.path) {
|
|
459
|
+
throw fail(
|
|
460
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
461
|
+
`${file.item} writes ${file.path}, the stylesheet the items' CSS joins.`,
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
const command = `mostra add ${input.specs.map(shellWord).join(" ")} --artifact ${shellWord(input.target.artifactPath)}`;
|
|
466
|
+
// What each file does, judged against the artifact as it is now; it is judged again just
|
|
467
|
+
// before anything is written, inside the artifact's queue.
|
|
468
|
+
const judge = async (): Promise<(PackFileChange & { content: string })[]> => {
|
|
469
|
+
const changes: (PackFileChange & { content: string })[] = [];
|
|
470
|
+
const clashes: string[] = [];
|
|
471
|
+
for (const file of planned.values()) {
|
|
472
|
+
await checkPlace(input.root, file.path);
|
|
473
|
+
const existing = await readFile(join(input.root, file.path), "utf8").catch(
|
|
474
|
+
() => undefined,
|
|
475
|
+
);
|
|
476
|
+
if (existing === undefined)
|
|
477
|
+
changes.push({ path: file.path, action: "created", content: file.content });
|
|
478
|
+
else if (existing === file.content)
|
|
479
|
+
changes.push({ path: file.path, action: "unchanged", content: file.content });
|
|
480
|
+
else if (input.overwrite)
|
|
481
|
+
changes.push({ path: file.path, action: "overwritten", content: file.content });
|
|
482
|
+
else clashes.push(file.path);
|
|
483
|
+
}
|
|
484
|
+
if (clashes.length > 0) {
|
|
485
|
+
throw new RpcError(
|
|
486
|
+
createDiagnostic("MOSTRA_PACK_FILE_EXISTS", {
|
|
487
|
+
message: `The artifact already has ${clashes.join(", ")}, with other content. Nothing was written.`,
|
|
488
|
+
fix: { kind: "command", command: `${command} --overwrite` },
|
|
489
|
+
}),
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
if (stylesheet !== undefined) {
|
|
493
|
+
await checkPlace(input.root, stylesheet.path);
|
|
494
|
+
const now = await readFile(join(input.root, stylesheet.path), "utf8").catch(
|
|
495
|
+
() => undefined,
|
|
496
|
+
);
|
|
497
|
+
let after = now ?? '@import "tailwindcss";\n';
|
|
498
|
+
for (const block of cssBlocks) after = withCssBlock(after, block.name, block.css);
|
|
499
|
+
if (now !== after) {
|
|
500
|
+
changes.push({
|
|
501
|
+
path: stylesheet.path,
|
|
502
|
+
action: now === undefined ? "created" : "updated",
|
|
503
|
+
content: after,
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return changes;
|
|
508
|
+
};
|
|
509
|
+
const firstLook = await judge();
|
|
510
|
+
|
|
511
|
+
// 4. npm packages and licenses, then 5. the files, all or nothing.
|
|
512
|
+
const itemPackages = [
|
|
513
|
+
...new Set(items.flatMap((read) => [...(read.item.dependencies ?? [])])),
|
|
514
|
+
];
|
|
515
|
+
const packages = [...new Set([...itemPackages, ...plainSpecs])];
|
|
516
|
+
const summaries: PackItemSummary[] = items.map((read) => ({
|
|
517
|
+
name: read.item.name,
|
|
518
|
+
type: read.item.type,
|
|
519
|
+
address: read.address,
|
|
520
|
+
source: read.source,
|
|
521
|
+
...(read.requiredBy !== undefined ? { requiredBy: read.requiredBy } : {}),
|
|
522
|
+
...(read.item.mostra?.fields !== undefined ? { fields: [...read.item.mostra.fields] } : {}),
|
|
523
|
+
}));
|
|
524
|
+
const devDependencies = [
|
|
525
|
+
...new Set(items.flatMap((read) => [...(read.item.devDependencies ?? [])])),
|
|
526
|
+
];
|
|
527
|
+
if (devDependencies.length > 0) {
|
|
528
|
+
note(
|
|
529
|
+
`The items name development packages (${devDependencies.join(", ")}), which an artifact's build doesn't use; add any the page imports with mostra add.`,
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
const names = itemPackages.map(packageName);
|
|
533
|
+
// The items' own licenses (`mostra.license`): copied source is disclosed and acknowledged
|
|
534
|
+
// as a package is (D31).
|
|
535
|
+
const itemLicenses: ItemLicense[] = items.flatMap((read) =>
|
|
536
|
+
read.item.mostra?.license !== undefined
|
|
537
|
+
? [
|
|
538
|
+
{
|
|
539
|
+
name: read.item.name,
|
|
540
|
+
license: read.item.mostra.license,
|
|
541
|
+
...(read.item.mostra.licenseClass !== undefined
|
|
542
|
+
? { class: read.item.mostra.licenseClass }
|
|
543
|
+
: {}),
|
|
544
|
+
},
|
|
545
|
+
]
|
|
546
|
+
: [],
|
|
547
|
+
);
|
|
548
|
+
// Every install is one change of the working lockfile, in the artifact's queue, through
|
|
549
|
+
// the plugin gate; the files are written last, once the layout is complete (WP-16 review).
|
|
550
|
+
let changes = firstLook;
|
|
551
|
+
return dependencies.change<PackAddResult>(
|
|
552
|
+
{ ...input.target, add: packages, request: input.request },
|
|
553
|
+
async (staged) => {
|
|
554
|
+
const admitted = await plugins.admitChange(
|
|
555
|
+
{ kind: "artifact", target: input.target },
|
|
556
|
+
{
|
|
557
|
+
staged,
|
|
558
|
+
packages: names,
|
|
559
|
+
items: itemLicenses,
|
|
560
|
+
accept: input.accept,
|
|
561
|
+
command,
|
|
562
|
+
},
|
|
563
|
+
);
|
|
564
|
+
return {
|
|
565
|
+
plugins: admitted.plugins,
|
|
566
|
+
licenses: admitted.licenses,
|
|
567
|
+
write: async () => {
|
|
568
|
+
changes = await judge();
|
|
569
|
+
const written = await writeAll(input.root, changes);
|
|
570
|
+
log.info("packs.added", {
|
|
571
|
+
items: summaries.map((item) => item.name),
|
|
572
|
+
files: changes.length,
|
|
573
|
+
packages: staged.added.map((pkg) => pkg.name),
|
|
574
|
+
});
|
|
575
|
+
return written;
|
|
576
|
+
},
|
|
577
|
+
result: (lockDigest) => ({
|
|
578
|
+
items: summaries,
|
|
579
|
+
files: changes.map(({ path, action }) => ({ path, action })),
|
|
580
|
+
packages: [...staged.added],
|
|
581
|
+
licenses: [...admitted.disclosures],
|
|
582
|
+
lockDigest,
|
|
583
|
+
notes,
|
|
584
|
+
}),
|
|
585
|
+
};
|
|
586
|
+
},
|
|
587
|
+
);
|
|
588
|
+
},
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** An npm spec's package name (`@scope/name@1` → `@scope/name`). */
|
|
593
|
+
function packageName(spec: string): string {
|
|
594
|
+
const at = spec.indexOf("@", spec.startsWith("@") ? 1 : 0);
|
|
595
|
+
return at === -1 ? spec : spec.slice(0, at);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Refuses a place that leads out of the artifact or onto something that isn't a file: a link or
|
|
600
|
+
* a file where a directory is needed, a link or a directory where the file goes, or a name that
|
|
601
|
+
* differs from one already there only in case.
|
|
602
|
+
*/
|
|
603
|
+
async function checkPlace(root: string, path: string): Promise<void> {
|
|
604
|
+
const segments = path.split("/");
|
|
605
|
+
let at = root;
|
|
606
|
+
for (const [index, segment] of segments.entries()) {
|
|
607
|
+
let entries: string[];
|
|
608
|
+
try {
|
|
609
|
+
entries = await readdir(at);
|
|
610
|
+
} catch {
|
|
611
|
+
return; // The rest is created.
|
|
612
|
+
}
|
|
613
|
+
const exact = entries.includes(segment);
|
|
614
|
+
const folded = entries.find(
|
|
615
|
+
(entry) => entry !== segment && entry.toLowerCase() === segment.toLowerCase(),
|
|
616
|
+
);
|
|
617
|
+
if (!exact && folded !== undefined) {
|
|
618
|
+
throw fail(
|
|
619
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
620
|
+
`${path} differs only in case from ${[...segments.slice(0, index), folded].join("/")}, which the artifact already has.`,
|
|
621
|
+
);
|
|
622
|
+
}
|
|
623
|
+
at = join(at, segment);
|
|
624
|
+
if (!exact) return;
|
|
625
|
+
const info = await lstat(at);
|
|
626
|
+
const last = index === segments.length - 1;
|
|
627
|
+
if (info.isSymbolicLink()) {
|
|
628
|
+
throw fail(
|
|
629
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
630
|
+
`${segments.slice(0, index + 1).join("/")} is a link; a pack writes only inside the artifact.`,
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
if (last ? !info.isFile() : !info.isDirectory()) {
|
|
634
|
+
throw fail(
|
|
635
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
636
|
+
`${segments.slice(0, index + 1).join("/")} is ${last ? "not a file" : "a file, not a folder"}.`,
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* Writes every change, each through a temporary file; restores everything when one fails. The
|
|
644
|
+
* replaced files stay aside until `commit` (the lockfile was recorded) or `rollback` (it wasn't).
|
|
645
|
+
*/
|
|
646
|
+
async function writeAll(
|
|
647
|
+
root: string,
|
|
648
|
+
changes: readonly (PackFileChange & { readonly content: string })[],
|
|
649
|
+
): Promise<StagedWrite> {
|
|
650
|
+
const token = randomBytes(6).toString("hex");
|
|
651
|
+
const done: { path: string; backup?: string }[] = [];
|
|
652
|
+
const createdDirs: string[] = [];
|
|
653
|
+
try {
|
|
654
|
+
for (const change of changes) {
|
|
655
|
+
if (change.action === "unchanged") continue;
|
|
656
|
+
const file = join(root, ...change.path.split("/"));
|
|
657
|
+
let dir = dirname(file);
|
|
658
|
+
const missing: string[] = [];
|
|
659
|
+
while (!existsSync(dir) && dir.length > root.length) {
|
|
660
|
+
missing.unshift(dir);
|
|
661
|
+
dir = dirname(dir);
|
|
662
|
+
}
|
|
663
|
+
for (const created of missing) {
|
|
664
|
+
await mkdir(created);
|
|
665
|
+
createdDirs.push(created);
|
|
666
|
+
}
|
|
667
|
+
const temporary = join(dirname(file), `.${basename(file)}.mostra-${token}.tmp`);
|
|
668
|
+
await writeFile(temporary, change.content);
|
|
669
|
+
let backup: string | undefined;
|
|
670
|
+
if (existsSync(file)) {
|
|
671
|
+
backup = join(dirname(file), `.${basename(file)}.mostra-${token}.old`);
|
|
672
|
+
await rename(file, backup);
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
await rename(temporary, file);
|
|
676
|
+
} catch (error) {
|
|
677
|
+
if (backup !== undefined) await rename(backup, file);
|
|
678
|
+
await rm(temporary, { force: true });
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
681
|
+
done.push({ path: file, ...(backup !== undefined ? { backup } : {}) });
|
|
682
|
+
}
|
|
683
|
+
} catch (error) {
|
|
684
|
+
await restore();
|
|
685
|
+
throw fail(
|
|
686
|
+
"MOSTRA_PACK_TARGET_INVALID",
|
|
687
|
+
`Writing the items' files failed (${error instanceof Error ? error.message : String(error)}); nothing was changed.`,
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
async function restore(): Promise<void> {
|
|
691
|
+
for (const entry of [...done].reverse()) {
|
|
692
|
+
await rm(entry.path, { force: true });
|
|
693
|
+
if (entry.backup !== undefined) await rename(entry.backup, entry.path);
|
|
694
|
+
}
|
|
695
|
+
for (const created of [...createdDirs].reverse())
|
|
696
|
+
await rm(created, { recursive: true, force: true });
|
|
697
|
+
}
|
|
698
|
+
return {
|
|
699
|
+
commit: async () => {
|
|
700
|
+
for (const entry of done) {
|
|
701
|
+
if (entry.backup !== undefined) await rm(entry.backup, { force: true });
|
|
702
|
+
}
|
|
703
|
+
},
|
|
704
|
+
rollback: restore,
|
|
705
|
+
};
|
|
706
|
+
}
|