zappie 0.1.7 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +17 -2
- package/dist/cli.js +24 -1960
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,113 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import path16 from "path";
|
|
5
|
-
|
|
6
|
-
// src/args.ts
|
|
7
|
-
import { parseArgs } from "util";
|
|
8
|
-
|
|
9
|
-
// src/config.ts
|
|
10
|
-
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
11
|
-
import path from "path";
|
|
12
|
-
|
|
13
|
-
// src/errors.ts
|
|
14
|
-
var CliError = class extends Error {
|
|
15
|
-
constructor(message, exitCode = 1) {
|
|
16
|
-
super(message);
|
|
17
|
-
this.name = "CliError";
|
|
18
|
-
this.exitCode = exitCode;
|
|
19
|
-
}
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
// src/config.ts
|
|
23
|
-
var CONFIG_FILE = "zappie.json";
|
|
24
|
-
function normaliseApi(api) {
|
|
25
|
-
return api.replace(/\/+$/, "");
|
|
26
|
-
}
|
|
27
|
-
function readProjectConfig(dir) {
|
|
28
|
-
const file = path.join(dir, CONFIG_FILE);
|
|
29
|
-
if (!existsSync(file)) {
|
|
30
|
-
return void 0;
|
|
31
|
-
}
|
|
32
|
-
let source2;
|
|
33
|
-
try {
|
|
34
|
-
source2 = readFileSync(file, "utf8");
|
|
35
|
-
} catch {
|
|
36
|
-
throw new CliError(`We could not read ${file}.`);
|
|
37
|
-
}
|
|
38
|
-
let parsed;
|
|
39
|
-
try {
|
|
40
|
-
parsed = JSON.parse(source2);
|
|
41
|
-
} catch {
|
|
42
|
-
throw new CliError(`${file} is not valid JSON.`);
|
|
43
|
-
}
|
|
44
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
45
|
-
throw new CliError(`Put an object in ${file}.`);
|
|
46
|
-
}
|
|
47
|
-
const value = parsed;
|
|
48
|
-
if (value.api !== void 0 && typeof value.api !== "string") {
|
|
49
|
-
throw new CliError(`Use a string for "api" in ${file} when you set it.`);
|
|
50
|
-
}
|
|
51
|
-
return {
|
|
52
|
-
...value,
|
|
53
|
-
...value.api !== void 0 ? { api: normaliseApi(value.api) } : {}
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
function writeProjectConfig(dir, config) {
|
|
57
|
-
writeFileSync(
|
|
58
|
-
path.join(dir, CONFIG_FILE),
|
|
59
|
-
`${JSON.stringify(config, null, 2)}
|
|
60
|
-
`
|
|
61
|
-
);
|
|
62
|
-
}
|
|
63
|
-
var DEFAULT_REGISTRY = "https://registry.zappie.ai/v1";
|
|
64
|
-
function registrySource(flag, configured) {
|
|
65
|
-
return flag ?? configured ?? DEFAULT_REGISTRY;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// src/args.ts
|
|
69
|
-
var registryFlag = "--registry <url|dir>";
|
|
70
|
-
var verifyRunners = ["cli", "ci", "build-worker", "sandbox"];
|
|
71
|
-
var verifyCheckSets = {
|
|
72
|
-
quick: ["V01", "V02", "V03", "V04", "V05", "V06", "V07", "V09", "V10", "V13"]
|
|
73
|
-
};
|
|
74
|
-
function parseOnly(value) {
|
|
75
|
-
const entries = value.split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
76
|
-
if (entries.length === 0) {
|
|
77
|
-
throw new CliError("Name at least one check or check set for --only.");
|
|
78
|
-
}
|
|
79
|
-
const ids = /* @__PURE__ */ new Set();
|
|
80
|
-
for (const entry of entries) {
|
|
81
|
-
const set = verifyCheckSets[entry.toLowerCase()];
|
|
82
|
-
if (set) {
|
|
83
|
-
set.forEach((id) => ids.add(id));
|
|
84
|
-
} else if (/^[VE]\d{2}$/i.test(entry)) {
|
|
85
|
-
ids.add(entry.toUpperCase());
|
|
86
|
-
} else {
|
|
87
|
-
throw new CliError(
|
|
88
|
-
`"${entry}" is not a check ID or set for --only. Pass IDs such as V01,V02 or one of: ${Object.keys(verifyCheckSets).join(", ")}.`
|
|
89
|
-
);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return [...ids];
|
|
93
|
-
}
|
|
94
|
-
function parseStart(value) {
|
|
95
|
-
if (!/^\/(?!\/)[^\\]*$/.test(value)) {
|
|
96
|
-
throw new CliError("Pass a route such as /menu for --start.");
|
|
97
|
-
}
|
|
98
|
-
return value;
|
|
99
|
-
}
|
|
100
|
-
function parsePort(value) {
|
|
101
|
-
const port = Number(value);
|
|
102
|
-
if (!/^\d+$/.test(value) || port < 1 || port > 65535) {
|
|
103
|
-
throw new CliError("Pass a port between 1 and 65535 for --port.");
|
|
104
|
-
}
|
|
105
|
-
return port;
|
|
106
|
-
}
|
|
107
|
-
var usage = `Usage: zappie <command>
|
|
2
|
+
import path17 from"path";import{parseArgs}from"util";import{existsSync,readFileSync,writeFileSync}from"fs";import path from"path";var CliError=class extends Error{constructor(message,exitCode=1){super(message);this.name="CliError";this.exitCode=exitCode}};var CONFIG_FILE="zappie.json";function normaliseApi(api){return api.replace(/\/+$/,"")}function readProjectConfig(dir){const file=path.join(dir,CONFIG_FILE);if(!existsSync(file)){return void 0}let source2;try{source2=readFileSync(file,"utf8")}catch{throw new CliError(`We could not read ${file}.`)}let parsed;try{parsed=JSON.parse(source2)}catch{throw new CliError(`${file} is not valid JSON.`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){throw new CliError(`Put an object in ${file}.`)}const value=parsed;if(value.api!==void 0&&typeof value.api!=="string"){throw new CliError(`Use a string for "api" in ${file} when you set it.`)}return{...value,...value.api!==void 0?{api:normaliseApi(value.api)}:{}}}function writeProjectConfig(dir,config){writeFileSync(path.join(dir,CONFIG_FILE),`${JSON.stringify(config,null,2)}
|
|
3
|
+
`)}var DEFAULT_REGISTRY="https://registry.zappie.ai/v1";function registrySource(flag,configured){return flag??configured??DEFAULT_REGISTRY}var registryFlag="--registry <url|dir>";var verifyRunners=["cli","ci","build-worker","sandbox"];var verifyCheckSets={quick:["V01","V02","V03","V04","V05","V06","V07","V09","V10","V13"]};function parseOnly(value){const entries=value.split(",").map(entry=>entry.trim()).filter(Boolean);if(entries.length===0){throw new CliError("Name at least one check or check set for --only.")}const ids=new Set;for(const entry of entries){const set=verifyCheckSets[entry.toLowerCase()];if(set){set.forEach(id=>ids.add(id))}else if(/^[VE]\d{2}$/i.test(entry)){ids.add(entry.toUpperCase())}else{throw new CliError(`"${entry}" is not a check ID or set for --only. Pass IDs such as V01,V02 or one of: ${Object.keys(verifyCheckSets).join(", ")}.`)}}return[...ids]}function parseStart(value){if(!/^\/(?!\/)[^\\]*$/.test(value)){throw new CliError("Pass a route such as /menu for --start.")}return value}function parsePort(value){const port=Number(value);if(!/^\d+$/.test(value)||port<1||port>65535){throw new CliError("Pass a port between 1 and 65535 for --port.")}return port}var usage=`Usage: zappie <command>
|
|
108
4
|
|
|
109
5
|
Commands:
|
|
110
|
-
init [dir] Create a storefront
|
|
6
|
+
init [dir] Create a storefront, or add Zappie to a project
|
|
111
7
|
add <name...> Add components from a registry
|
|
112
8
|
list Show registry or installed components
|
|
113
9
|
diff [name] Compare your installed components with the registry
|
|
@@ -136,1866 +32,34 @@ Options:
|
|
|
136
32
|
--overwrite Replace files you changed locally during add
|
|
137
33
|
--dry-run Show an add or diff --apply plan without writing
|
|
138
34
|
--apply Apply registry updates with a 3-way merge
|
|
139
|
-
--no-install Skip installing missing npm dependencies
|
|
35
|
+
--no-install Skip installing missing npm dependencies in init or add
|
|
140
36
|
--installed Show your installed components
|
|
141
|
-
-h, --help Show this help`;
|
|
142
|
-
function noArguments(name2, rest) {
|
|
143
|
-
if (rest.length > 0) {
|
|
144
|
-
throw new CliError(`Run ${name2} without arguments.
|
|
145
|
-
|
|
146
|
-
${usage}`);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
function parseCommand(argv) {
|
|
150
|
-
let parsed;
|
|
151
|
-
try {
|
|
152
|
-
parsed = parseArgs({
|
|
153
|
-
args: argv,
|
|
154
|
-
options: {
|
|
155
|
-
registry: { type: "string" },
|
|
156
|
-
yes: { type: "boolean" },
|
|
157
|
-
template: { type: "string" },
|
|
158
|
-
json: { type: "boolean" },
|
|
159
|
-
overwrite: { type: "boolean" },
|
|
160
|
-
"dry-run": { type: "boolean" },
|
|
161
|
-
"no-install": { type: "boolean" },
|
|
162
|
-
installed: { type: "boolean" },
|
|
163
|
-
apply: { type: "boolean" },
|
|
164
|
-
all: { type: "boolean" },
|
|
165
|
-
audit: { type: "string" },
|
|
166
|
-
history: { type: "boolean" },
|
|
167
|
-
suite: { type: "string" },
|
|
168
|
-
report: { type: "string" },
|
|
169
|
-
key: { type: "string" },
|
|
170
|
-
store: { type: "string" },
|
|
171
|
-
only: { type: "string" },
|
|
172
|
-
start: { type: "string" },
|
|
173
|
-
"no-build": { type: "boolean" },
|
|
174
|
-
port: { type: "string" },
|
|
175
|
-
artifacts: { type: "string" },
|
|
176
|
-
runner: { type: "string" },
|
|
177
|
-
help: { type: "boolean", short: "h" }
|
|
178
|
-
},
|
|
179
|
-
allowPositionals: true,
|
|
180
|
-
strict: true
|
|
181
|
-
});
|
|
182
|
-
} catch (error) {
|
|
183
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
184
|
-
throw new CliError(`${reason}
|
|
185
|
-
|
|
186
|
-
${usage}`);
|
|
187
|
-
}
|
|
188
|
-
const { values, positionals } = parsed;
|
|
189
|
-
const registry = typeof values.registry === "string" ? values.registry : void 0;
|
|
190
|
-
const json4 = values.json === true;
|
|
191
|
-
const [name2, ...rest] = positionals;
|
|
192
|
-
if (values.help === true || name2 === void 0 || name2 === "help") {
|
|
193
|
-
return { name: "help" };
|
|
194
|
-
}
|
|
195
|
-
if (name2 === "init") {
|
|
196
|
-
if (rest.length > 1) {
|
|
197
|
-
throw new CliError("Pass init at most one directory.");
|
|
198
|
-
}
|
|
199
|
-
return {
|
|
200
|
-
name: name2,
|
|
201
|
-
directory: rest[0],
|
|
202
|
-
registry,
|
|
203
|
-
json: json4,
|
|
204
|
-
yes: values.yes === true,
|
|
205
|
-
store: typeof values.store === "string" ? values.store : void 0,
|
|
206
|
-
key: typeof values.key === "string" ? values.key : void 0,
|
|
207
|
-
template: typeof values.template === "string" ? values.template : "react-router"
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
if (name2 === "add") {
|
|
211
|
-
if (rest.length === 0) {
|
|
212
|
-
throw new CliError(`Name at least one component to add.
|
|
213
|
-
|
|
214
|
-
${usage}`);
|
|
215
|
-
}
|
|
216
|
-
return {
|
|
217
|
-
name: name2,
|
|
218
|
-
items: rest,
|
|
219
|
-
registry,
|
|
220
|
-
json: json4,
|
|
221
|
-
overwrite: values.overwrite === true,
|
|
222
|
-
dryRun: values["dry-run"] === true,
|
|
223
|
-
install: values["no-install"] !== true
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
if (name2 === "list") {
|
|
227
|
-
noArguments(name2, rest);
|
|
228
|
-
return { name: name2, registry, json: json4, installed: values.installed === true };
|
|
229
|
-
}
|
|
230
|
-
if (name2 === "diff") {
|
|
231
|
-
if (rest.length > 1) {
|
|
232
|
-
throw new CliError(`Name at most one component to diff.
|
|
233
|
-
|
|
234
|
-
${usage}`);
|
|
235
|
-
}
|
|
236
|
-
return {
|
|
237
|
-
name: name2,
|
|
238
|
-
item: rest[0],
|
|
239
|
-
registry,
|
|
240
|
-
json: json4,
|
|
241
|
-
apply: values.apply === true,
|
|
242
|
-
dryRun: values["dry-run"] === true
|
|
243
|
-
};
|
|
244
|
-
}
|
|
245
|
-
if (name2 === "doctor") {
|
|
246
|
-
noArguments(name2, rest);
|
|
247
|
-
return { name: name2, registry, json: json4 };
|
|
248
|
-
}
|
|
249
|
-
if (name2 === "check") {
|
|
250
|
-
if (rest.length > 1) {
|
|
251
|
-
throw new CliError(`Pass check at most one directory.
|
|
252
|
-
|
|
253
|
-
${usage}`);
|
|
254
|
-
}
|
|
255
|
-
const audit = values.audit ?? "report";
|
|
256
|
-
if (audit !== "off" && audit !== "report" && audit !== "enforce") {
|
|
257
|
-
throw new CliError("Choose off, report or enforce for --audit.");
|
|
258
|
-
}
|
|
259
|
-
return {
|
|
260
|
-
name: name2,
|
|
261
|
-
directory: rest[0],
|
|
262
|
-
all: values.all === true,
|
|
263
|
-
audit,
|
|
264
|
-
history: values.history === true,
|
|
265
|
-
json: json4
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
if (name2 === "verify") {
|
|
269
|
-
if (rest.length > 1) {
|
|
270
|
-
throw new CliError(`Pass verify at most one URL.
|
|
271
|
-
|
|
272
|
-
${usage}`);
|
|
273
|
-
}
|
|
274
|
-
const suite = values.suite ?? "standard";
|
|
275
|
-
if (suite !== "standard" && suite !== "extended") {
|
|
276
|
-
throw new CliError(
|
|
277
|
-
"Choose standard or extended for --suite. To run the quick checks, pass --only quick."
|
|
278
|
-
);
|
|
279
|
-
}
|
|
280
|
-
const runner = values.runner;
|
|
281
|
-
if (typeof runner === "string" && !verifyRunners.includes(runner)) {
|
|
282
|
-
throw new CliError(`Choose ${verifyRunners.join(", ")} for --runner.`);
|
|
283
|
-
}
|
|
284
|
-
const build = values["no-build"] !== true;
|
|
285
|
-
const port = typeof values.port === "string" ? parsePort(values.port) : void 0;
|
|
286
|
-
if (rest[0] && (!build || port !== void 0)) {
|
|
287
|
-
throw new CliError(
|
|
288
|
-
"--no-build and --port apply to the local preview. Drop them, or drop the URL."
|
|
289
|
-
);
|
|
290
|
-
}
|
|
291
|
-
return {
|
|
292
|
-
name: name2,
|
|
293
|
-
url: rest[0],
|
|
294
|
-
suite,
|
|
295
|
-
report: typeof values.report === "string" ? values.report : void 0,
|
|
296
|
-
key: typeof values.key === "string" ? values.key : void 0,
|
|
297
|
-
store: typeof values.store === "string" ? values.store : void 0,
|
|
298
|
-
only: typeof values.only === "string" ? parseOnly(values.only) : void 0,
|
|
299
|
-
startPath: typeof values.start === "string" ? parseStart(values.start) : void 0,
|
|
300
|
-
build,
|
|
301
|
-
port,
|
|
302
|
-
artifacts: typeof values.artifacts === "string" ? values.artifacts : void 0,
|
|
303
|
-
runner,
|
|
304
|
-
json: json4
|
|
305
|
-
};
|
|
306
|
-
}
|
|
307
|
-
throw new CliError(`Command "${name2}" is unknown.
|
|
308
|
-
|
|
309
|
-
${usage}`);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
// src/project-package.ts
|
|
313
|
-
import { createRequire } from "module";
|
|
314
|
-
import path2 from "path";
|
|
315
|
-
import { pathToFileURL } from "url";
|
|
316
|
-
async function loadProjectPackage(cwd, name2, manager) {
|
|
317
|
-
const require2 = createRequire(path2.join(cwd, "package.json"));
|
|
318
|
-
let entry;
|
|
319
|
-
try {
|
|
320
|
-
entry = require2.resolve(name2);
|
|
321
|
-
} catch {
|
|
322
|
-
throw new CliError(
|
|
323
|
-
`You have not installed ${name2}. Install it with: ${installCommand(manager, name2)}`
|
|
324
|
-
);
|
|
325
|
-
}
|
|
326
|
-
return await import(pathToFileURL(entry).href);
|
|
327
|
-
}
|
|
328
|
-
function installCommand(manager, name2) {
|
|
329
|
-
if (manager === "npm") {
|
|
330
|
-
return `npm install --save-dev ${name2}`;
|
|
331
|
-
}
|
|
332
|
-
if (manager === "yarn") {
|
|
333
|
-
return `yarn add --dev ${name2}`;
|
|
334
|
-
}
|
|
335
|
-
if (manager === "bun") {
|
|
336
|
-
return `bun add --dev ${name2}`;
|
|
337
|
-
}
|
|
338
|
-
return `pnpm add --save-dev ${name2}`;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
// src/check-command.ts
|
|
342
|
-
async function runProjectCheck(options) {
|
|
343
|
-
const loaded = await (options.load ?? loadProjectCheck)(
|
|
344
|
-
options.cwd,
|
|
345
|
-
options.packageManager
|
|
346
|
-
);
|
|
347
|
-
const result = await loaded.runCheck({
|
|
348
|
-
cwd: options.cwd,
|
|
349
|
-
all: options.all,
|
|
350
|
-
audit: options.audit ?? "report",
|
|
351
|
-
history: options.history ?? false,
|
|
352
|
-
packageManager: options.packageManager,
|
|
353
|
-
...options.signal ? { signal: options.signal } : {}
|
|
354
|
-
});
|
|
355
|
-
const print = options.print ?? console.log;
|
|
356
|
-
print(options.json ? JSON.stringify(result) : humanOutput(result));
|
|
357
|
-
return result;
|
|
358
|
-
}
|
|
359
|
-
async function loadProjectCheck(cwd, manager) {
|
|
360
|
-
const loaded = await loadProjectPackage(
|
|
361
|
-
cwd,
|
|
362
|
-
"@zappie/check",
|
|
363
|
-
manager
|
|
364
|
-
);
|
|
365
|
-
if (typeof loaded.runCheck !== "function") {
|
|
366
|
-
throw new CliError(
|
|
367
|
-
"Your installed @zappie/check does not export runCheck."
|
|
368
|
-
);
|
|
369
|
-
}
|
|
370
|
-
return loaded;
|
|
371
|
-
}
|
|
372
|
-
function humanOutput(result) {
|
|
373
|
-
const lines2 = [];
|
|
374
|
-
for (const checked of result.steps) {
|
|
375
|
-
lines2.push(`${checked.name}: ${checked.result}`);
|
|
376
|
-
for (const issue of checked.problems) {
|
|
377
|
-
const location = issue.file ? `${issue.file}${issue.line ? `:${issue.line}` : ""}` : "project";
|
|
378
|
-
lines2.push(
|
|
379
|
-
` ${location}${issue.rule ? ` [${issue.rule}]` : ""} ${issue.message}`
|
|
380
|
-
);
|
|
381
|
-
if (issue.fix) {
|
|
382
|
-
lines2.push(` Fix: ${issue.fix}`);
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
return lines2.join("\n");
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
// src/doctor.ts
|
|
390
|
-
import path7 from "path";
|
|
391
|
-
import { fileURLToPath } from "url";
|
|
392
|
-
|
|
393
|
-
// src/doctor-checks.ts
|
|
394
|
-
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
|
|
395
|
-
import path4 from "path";
|
|
396
|
-
import { satisfies } from "semver";
|
|
397
|
-
|
|
398
|
-
// src/hash.ts
|
|
399
|
-
import { createHash } from "crypto";
|
|
400
|
-
function sha256(content) {
|
|
401
|
-
return createHash("sha256").update(content).digest("hex");
|
|
402
|
-
}
|
|
37
|
+
-h, --help Show this help`;function noArguments(name2,rest){if(rest.length>0){throw new CliError(`Run ${name2} without arguments.
|
|
403
38
|
|
|
404
|
-
|
|
405
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
406
|
-
import path3 from "path";
|
|
407
|
-
function json(file) {
|
|
408
|
-
let source2;
|
|
409
|
-
try {
|
|
410
|
-
source2 = readFileSync2(file, "utf8");
|
|
411
|
-
} catch {
|
|
412
|
-
throw new CliError(`We could not read ${file}.`);
|
|
413
|
-
}
|
|
414
|
-
try {
|
|
415
|
-
return JSON.parse(source2);
|
|
416
|
-
} catch {
|
|
417
|
-
throw new CliError(`${file} is not valid JSON.`);
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
function packageJson(cwd) {
|
|
421
|
-
const file = path3.join(cwd, "package.json");
|
|
422
|
-
if (!existsSync2(file)) {
|
|
423
|
-
throw new CliError(`There is no package.json in ${cwd}.`);
|
|
424
|
-
}
|
|
425
|
-
return json(file);
|
|
426
|
-
}
|
|
427
|
-
function detectFramework(cwd) {
|
|
428
|
-
const value = packageJson(cwd);
|
|
429
|
-
const dependencies = {
|
|
430
|
-
...value.dependencies,
|
|
431
|
-
...value.devDependencies,
|
|
432
|
-
...value.peerDependencies
|
|
433
|
-
};
|
|
434
|
-
if (dependencies.next) {
|
|
435
|
-
return "next";
|
|
436
|
-
}
|
|
437
|
-
if (dependencies["react-router"] || dependencies["react-router-dom"]) {
|
|
438
|
-
return "react-router";
|
|
439
|
-
}
|
|
440
|
-
if (dependencies.vite) {
|
|
441
|
-
return "vite";
|
|
442
|
-
}
|
|
443
|
-
throw new CliError("We could not detect React Router, Next.js or Vite.");
|
|
444
|
-
}
|
|
445
|
-
function defaultDirectory(cwd, framework) {
|
|
446
|
-
if (framework === "react-router") {
|
|
447
|
-
return "app/components/zappie";
|
|
448
|
-
}
|
|
449
|
-
if (framework === "next" && !existsSync2(path3.join(cwd, "src"))) {
|
|
450
|
-
return "components/zappie";
|
|
451
|
-
}
|
|
452
|
-
return "src/components/zappie";
|
|
453
|
-
}
|
|
454
|
-
function parseTsconfig(cwd) {
|
|
455
|
-
const file = path3.join(cwd, "tsconfig.json");
|
|
456
|
-
if (!existsSync2(file)) {
|
|
457
|
-
return void 0;
|
|
458
|
-
}
|
|
459
|
-
const source2 = readFileSync2(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|\s)\/\/.*$/gm, "$1").replace(/,\s*([}\]])/g, "$1");
|
|
460
|
-
try {
|
|
461
|
-
return JSON.parse(source2);
|
|
462
|
-
} catch {
|
|
463
|
-
throw new CliError(`${file} is not valid JSON or JSONC.`);
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
function detectAlias(cwd, directory) {
|
|
467
|
-
const config = parseTsconfig(cwd);
|
|
468
|
-
const compiler = config?.compilerOptions;
|
|
469
|
-
if (typeof compiler !== "object" || compiler === null) {
|
|
470
|
-
return void 0;
|
|
471
|
-
}
|
|
472
|
-
const paths = compiler.paths;
|
|
473
|
-
if (typeof paths !== "object" || paths === null) {
|
|
474
|
-
return void 0;
|
|
475
|
-
}
|
|
476
|
-
const target = directory.replaceAll("\\", "/");
|
|
477
|
-
for (const [alias, entries] of Object.entries(paths)) {
|
|
478
|
-
if (!Array.isArray(entries)) {
|
|
479
|
-
continue;
|
|
480
|
-
}
|
|
481
|
-
for (const entry of entries) {
|
|
482
|
-
if (typeof entry !== "string") {
|
|
483
|
-
continue;
|
|
484
|
-
}
|
|
485
|
-
const normalized = entry.replace(/^\.\//, "").replaceAll("\\", "/");
|
|
486
|
-
const star = normalized.indexOf("*");
|
|
487
|
-
const prefix = star < 0 ? normalized : normalized.slice(0, star);
|
|
488
|
-
if (!target.startsWith(prefix)) {
|
|
489
|
-
continue;
|
|
490
|
-
}
|
|
491
|
-
const remainder = target.slice(prefix.length);
|
|
492
|
-
return star < 0 ? alias : alias.replace("*", remainder);
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
return void 0;
|
|
496
|
-
}
|
|
497
|
-
function kitProject(cwd) {
|
|
498
|
-
const current = readProjectConfig(cwd) ?? {};
|
|
499
|
-
const { alias: configuredAlias, ...rest } = current;
|
|
500
|
-
const framework = current.framework ?? detectFramework(cwd);
|
|
501
|
-
const componentsDir = current.componentsDir ?? defaultDirectory(cwd, framework);
|
|
502
|
-
const alias = configuredAlias ?? detectAlias(cwd, componentsDir);
|
|
503
|
-
return {
|
|
504
|
-
...rest,
|
|
505
|
-
framework,
|
|
506
|
-
componentsDir: componentsDir.replaceAll("\\", "/"),
|
|
507
|
-
...alias !== void 0 ? { alias } : {},
|
|
508
|
-
tsx: current.tsx ?? true,
|
|
509
|
-
installed: current.installed ?? {}
|
|
510
|
-
};
|
|
511
|
-
}
|
|
39
|
+
${usage}`)}}function parseCommand(argv){let parsed;try{parsed=parseArgs({args:argv,options:{registry:{type:"string"},yes:{type:"boolean"},template:{type:"string"},json:{type:"boolean"},overwrite:{type:"boolean"},"dry-run":{type:"boolean"},"no-install":{type:"boolean"},installed:{type:"boolean"},apply:{type:"boolean"},all:{type:"boolean"},audit:{type:"string"},history:{type:"boolean"},suite:{type:"string"},report:{type:"string"},key:{type:"string"},store:{type:"string"},only:{type:"string"},start:{type:"string"},"no-build":{type:"boolean"},port:{type:"string"},artifacts:{type:"string"},runner:{type:"string"},help:{type:"boolean",short:"h"}},allowPositionals:true,strict:true})}catch(error){const reason=error instanceof Error?error.message:String(error);throw new CliError(`${reason}
|
|
512
40
|
|
|
513
|
-
|
|
514
|
-
function check(name2, status, message, fix) {
|
|
515
|
-
return { name: name2, status, message, ...fix ? { fix } : {} };
|
|
516
|
-
}
|
|
517
|
-
function json2(file) {
|
|
518
|
-
try {
|
|
519
|
-
return JSON.parse(readFileSync3(file, "utf8"));
|
|
520
|
-
} catch {
|
|
521
|
-
return void 0;
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
function configCheck(file, raw, errors) {
|
|
525
|
-
if (errors.length === 0) {
|
|
526
|
-
return check("config", "ok", "zappie.json matches the kit project schema.");
|
|
527
|
-
}
|
|
528
|
-
if (!existsSync3(file)) {
|
|
529
|
-
return check(
|
|
530
|
-
"config",
|
|
531
|
-
"fail",
|
|
532
|
-
"There is no zappie.json in this project.",
|
|
533
|
-
"Run zappie add to create it."
|
|
534
|
-
);
|
|
535
|
-
}
|
|
536
|
-
if (raw === void 0) {
|
|
537
|
-
return check(
|
|
538
|
-
"config",
|
|
539
|
-
"fail",
|
|
540
|
-
"We could not read zappie.json as JSON.",
|
|
541
|
-
"Fix the JSON in zappie.json."
|
|
542
|
-
);
|
|
543
|
-
}
|
|
544
|
-
return check(
|
|
545
|
-
"config",
|
|
546
|
-
"fail",
|
|
547
|
-
errors.join(" "),
|
|
548
|
-
"Fix these fields in zappie.json."
|
|
549
|
-
);
|
|
550
|
-
}
|
|
551
|
-
function nodeCheck(version2, range) {
|
|
552
|
-
return satisfies(version2, range) ? check("node", "ok", `Your Node ${version2} meets ${range}.`) : check(
|
|
553
|
-
"node",
|
|
554
|
-
"fail",
|
|
555
|
-
`Your Node ${version2} does not meet ${range}.`,
|
|
556
|
-
`Install Node ${range}.`
|
|
557
|
-
);
|
|
558
|
-
}
|
|
559
|
-
function frameworkCheck(cwd, config) {
|
|
560
|
-
try {
|
|
561
|
-
const detected = detectFramework(cwd);
|
|
562
|
-
if (config?.framework && config.framework !== detected) {
|
|
563
|
-
return check(
|
|
564
|
-
"framework",
|
|
565
|
-
"fail",
|
|
566
|
-
`Found ${detected}, but zappie.json says ${config.framework}.`,
|
|
567
|
-
"Update zappie.json to match your project."
|
|
568
|
-
);
|
|
569
|
-
}
|
|
570
|
-
const directory = config?.componentsDir;
|
|
571
|
-
if (!directory || !existsSync3(path4.join(cwd, directory))) {
|
|
572
|
-
return check(
|
|
573
|
-
"framework",
|
|
574
|
-
"fail",
|
|
575
|
-
`Found ${detected}, but the components directory is missing.`,
|
|
576
|
-
"Create your configured componentsDir or run zappie add."
|
|
577
|
-
);
|
|
578
|
-
}
|
|
579
|
-
return check("framework", "ok", `Found ${detected}. ${directory} exists.`);
|
|
580
|
-
} catch (error) {
|
|
581
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
582
|
-
return check(
|
|
583
|
-
"framework",
|
|
584
|
-
"fail",
|
|
585
|
-
message,
|
|
586
|
-
"Add React Router, Next.js or Vite and configure componentsDir."
|
|
587
|
-
);
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
function filesCheck(cwd, config) {
|
|
591
|
-
const modified2 = Object.entries(config?.installed ?? {}).flatMap(
|
|
592
|
-
([name2, item2]) => Object.entries(item2.files).filter(([file, expected]) => {
|
|
593
|
-
const target = path4.join(cwd, file);
|
|
594
|
-
return !existsSync3(target) || sha256(readFileSync3(target, "utf8")) !== expected;
|
|
595
|
-
}).map(([file]) => `${name2}:${file}`)
|
|
596
|
-
);
|
|
597
|
-
return modified2.length === 0 ? check(
|
|
598
|
-
"files",
|
|
599
|
-
"ok",
|
|
600
|
-
"Your installed component files match their recorded hashes."
|
|
601
|
-
) : check(
|
|
602
|
-
"files",
|
|
603
|
-
"warn",
|
|
604
|
-
`Changed or missing files: ${modified2.join(", ")}.`,
|
|
605
|
-
"Run zappie diff before you apply an update."
|
|
606
|
-
);
|
|
607
|
-
}
|
|
608
|
-
function doctorText(checks) {
|
|
609
|
-
return checks.flatMap((entry) => [
|
|
610
|
-
`[${entry.status}] ${entry.name}: ${entry.message}`,
|
|
611
|
-
...entry.fix ? [` Fix: ${entry.fix}`] : []
|
|
612
|
-
]).join("\n");
|
|
613
|
-
}
|
|
41
|
+
${usage}`)}const{values,positionals}=parsed;const registry=typeof values.registry==="string"?values.registry:void 0;const json4=values.json===true;const[name2,...rest]=positionals;if(values.help===true||name2===void 0||name2==="help"){return{name:"help"}}if(name2==="init"){if(rest.length>1){throw new CliError("Pass init at most one directory.")}return{name:name2,directory:rest[0],registry,json:json4,yes:values.yes===true,store:typeof values.store==="string"?values.store:void 0,key:typeof values.key==="string"?values.key:void 0,template:typeof values.template==="string"?values.template:"react-router",install:values["no-install"]!==true}}if(name2==="add"){if(rest.length===0){throw new CliError(`Name at least one component to add.
|
|
614
42
|
|
|
615
|
-
|
|
616
|
-
import path6 from "path";
|
|
617
|
-
import { satisfies as satisfies2 } from "semver";
|
|
43
|
+
${usage}`)}return{name:name2,items:rest,registry,json:json4,overwrite:values.overwrite===true,dryRun:values["dry-run"]===true,install:values["no-install"]!==true}}if(name2==="list"){noArguments(name2,rest);return{name:name2,registry,json:json4,installed:values.installed===true}}if(name2==="diff"){if(rest.length>1){throw new CliError(`Name at most one component to diff.
|
|
618
44
|
|
|
619
|
-
|
|
620
|
-
import { access, readFile } from "fs/promises";
|
|
621
|
-
import path5 from "path";
|
|
622
|
-
function object(value, label) {
|
|
623
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
624
|
-
throw new CliError(`Registry ${label} is invalid.`);
|
|
625
|
-
}
|
|
626
|
-
return value;
|
|
627
|
-
}
|
|
628
|
-
function string(value, label) {
|
|
629
|
-
if (typeof value !== "string" || value.length === 0) {
|
|
630
|
-
throw new CliError(`Registry ${label} is invalid.`);
|
|
631
|
-
}
|
|
632
|
-
return value;
|
|
633
|
-
}
|
|
634
|
-
function record(value, label) {
|
|
635
|
-
const input = object(value, label);
|
|
636
|
-
return Object.fromEntries(
|
|
637
|
-
Object.entries(input).map(([key, entry]) => [key, string(entry, label)])
|
|
638
|
-
);
|
|
639
|
-
}
|
|
640
|
-
function item(value) {
|
|
641
|
-
const input = object(value, "item");
|
|
642
|
-
const type = string(input.type, "item type");
|
|
643
|
-
if (type !== "component" && type !== "block") {
|
|
644
|
-
throw new CliError("Registry item type is invalid.");
|
|
645
|
-
}
|
|
646
|
-
if (!Array.isArray(input.files) || !Array.isArray(input.registryDependencies)) {
|
|
647
|
-
throw new CliError("Registry item files or dependencies are invalid.");
|
|
648
|
-
}
|
|
649
|
-
return {
|
|
650
|
-
name: string(input.name, "item name"),
|
|
651
|
-
type,
|
|
652
|
-
version: string(input.version, "item version"),
|
|
653
|
-
title: string(input.title, "item title"),
|
|
654
|
-
description: string(input.description, "item description"),
|
|
655
|
-
requires: record(input.requires, "item requirements"),
|
|
656
|
-
dependencies: record(input.dependencies, "item dependencies"),
|
|
657
|
-
registryDependencies: input.registryDependencies.map(
|
|
658
|
-
(entry) => string(entry, "registry dependency")
|
|
659
|
-
),
|
|
660
|
-
files: input.files.map((entry) => {
|
|
661
|
-
const file = object(entry, "item file");
|
|
662
|
-
return {
|
|
663
|
-
path: string(file.path, "file path"),
|
|
664
|
-
target: string(file.target, "file target"),
|
|
665
|
-
sha256: string(file.sha256, "file hash"),
|
|
666
|
-
content: string(file.content, "file content")
|
|
667
|
-
};
|
|
668
|
-
})
|
|
669
|
-
};
|
|
670
|
-
}
|
|
671
|
-
function index(value) {
|
|
672
|
-
const input = object(value, "index");
|
|
673
|
-
if (!Array.isArray(input.items)) {
|
|
674
|
-
throw new CliError("Registry index items are invalid.");
|
|
675
|
-
}
|
|
676
|
-
return {
|
|
677
|
-
version: string(input.version, "index version"),
|
|
678
|
-
items: input.items.map((entry) => {
|
|
679
|
-
const value2 = item({
|
|
680
|
-
...object(entry, "index item"),
|
|
681
|
-
requires: {},
|
|
682
|
-
dependencies: {},
|
|
683
|
-
registryDependencies: [],
|
|
684
|
-
files: [
|
|
685
|
-
{ path: "index", target: "index", sha256: "index", content: "index" }
|
|
686
|
-
]
|
|
687
|
-
});
|
|
688
|
-
return {
|
|
689
|
-
name: value2.name,
|
|
690
|
-
type: value2.type,
|
|
691
|
-
version: value2.version,
|
|
692
|
-
title: value2.title,
|
|
693
|
-
description: value2.description
|
|
694
|
-
};
|
|
695
|
-
})
|
|
696
|
-
};
|
|
697
|
-
}
|
|
698
|
-
var Registry = class {
|
|
699
|
-
constructor(source2, cwd) {
|
|
700
|
-
this.source = source2;
|
|
701
|
-
this.cwd = cwd;
|
|
702
|
-
}
|
|
703
|
-
remote() {
|
|
704
|
-
return /^https?:\/\//.test(this.source);
|
|
705
|
-
}
|
|
706
|
-
async exists(file) {
|
|
707
|
-
return access(path5.join(path5.resolve(this.cwd, this.source), file)).then(
|
|
708
|
-
() => true,
|
|
709
|
-
() => false
|
|
710
|
-
);
|
|
711
|
-
}
|
|
712
|
-
async read(file) {
|
|
713
|
-
try {
|
|
714
|
-
if (this.remote()) {
|
|
715
|
-
const response = await fetch(
|
|
716
|
-
`${this.source.replace(/\/+$/, "")}/${file}`
|
|
717
|
-
);
|
|
718
|
-
if (!response.ok) {
|
|
719
|
-
throw new Error(`${response.status} ${response.statusText}`.trim());
|
|
720
|
-
}
|
|
721
|
-
return await response.json();
|
|
722
|
-
}
|
|
723
|
-
const root = path5.resolve(this.cwd, this.source);
|
|
724
|
-
return JSON.parse(await readFile(path5.join(root, file), "utf8"));
|
|
725
|
-
} catch (error) {
|
|
726
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
727
|
-
throw new CliError(`We could not read registry ${file}: ${message}`, 3);
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
async index() {
|
|
731
|
-
return index(await this.read("index.json"));
|
|
732
|
-
}
|
|
733
|
-
async item(name2, version2) {
|
|
734
|
-
if (version2 === void 0) {
|
|
735
|
-
return item(await this.read(`items/${name2}.json`));
|
|
736
|
-
}
|
|
737
|
-
const pinned = `items/${name2}@${version2}.json`;
|
|
738
|
-
if (this.remote() || await this.exists(pinned)) {
|
|
739
|
-
return item(await this.read(pinned));
|
|
740
|
-
}
|
|
741
|
-
const current = item(await this.read(`items/${name2}.json`));
|
|
742
|
-
if (current.version !== version2) {
|
|
743
|
-
throw new CliError(
|
|
744
|
-
`We could not read registry ${pinned}: this registry has ${name2} ${current.version} only.`,
|
|
745
|
-
3
|
|
746
|
-
);
|
|
747
|
-
}
|
|
748
|
-
return current;
|
|
749
|
-
}
|
|
750
|
-
};
|
|
45
|
+
${usage}`)}return{name:name2,item:rest[0],registry,json:json4,apply:values.apply===true,dryRun:values["dry-run"]===true}}if(name2==="doctor"){noArguments(name2,rest);return{name:name2,registry,json:json4}}if(name2==="check"){if(rest.length>1){throw new CliError(`Pass check at most one directory.
|
|
751
46
|
|
|
752
|
-
|
|
753
|
-
function packageVersion(cwd, name2) {
|
|
754
|
-
const file = path6.join(
|
|
755
|
-
cwd,
|
|
756
|
-
"node_modules",
|
|
757
|
-
...name2.split("/"),
|
|
758
|
-
"package.json"
|
|
759
|
-
);
|
|
760
|
-
const value = json2(file);
|
|
761
|
-
if (typeof value !== "object" || value === null) {
|
|
762
|
-
return void 0;
|
|
763
|
-
}
|
|
764
|
-
return typeof value.version === "string" ? value.version : void 0;
|
|
765
|
-
}
|
|
766
|
-
function dependencyChecks(cwd, manifests) {
|
|
767
|
-
const required = Object.assign(
|
|
768
|
-
{},
|
|
769
|
-
...manifests.map((item2) => item2.requires)
|
|
770
|
-
);
|
|
771
|
-
const dependencies = Object.assign(
|
|
772
|
-
{},
|
|
773
|
-
...manifests.map((item2) => item2.dependencies)
|
|
774
|
-
);
|
|
775
|
-
const bad = Object.entries(required).filter(([name2, range]) => {
|
|
776
|
-
const version2 = packageVersion(cwd, name2);
|
|
777
|
-
return version2 === void 0 || !satisfies2(version2, range);
|
|
778
|
-
});
|
|
779
|
-
const missing = Object.keys(dependencies).filter(
|
|
780
|
-
(name2) => packageVersion(cwd, name2) === void 0
|
|
781
|
-
);
|
|
782
|
-
return [
|
|
783
|
-
bad.length === 0 ? check(
|
|
784
|
-
"requires",
|
|
785
|
-
"ok",
|
|
786
|
-
"Your installed Zappie package versions meet every item requirement."
|
|
787
|
-
) : check(
|
|
788
|
-
"requires",
|
|
789
|
-
"fail",
|
|
790
|
-
`Unmet requirements: ${bad.map(([name2, range]) => `${name2} ${range}`).join(", ")}.`,
|
|
791
|
-
"Install versions that meet each registry item's requires field."
|
|
792
|
-
),
|
|
793
|
-
missing.length === 0 ? check(
|
|
794
|
-
"dependencies",
|
|
795
|
-
"ok",
|
|
796
|
-
"You have every registry npm dependency installed."
|
|
797
|
-
) : check(
|
|
798
|
-
"dependencies",
|
|
799
|
-
"fail",
|
|
800
|
-
`Missing dependencies: ${missing.join(", ")}.`,
|
|
801
|
-
"Install the missing npm dependencies."
|
|
802
|
-
)
|
|
803
|
-
];
|
|
804
|
-
}
|
|
805
|
-
function unavailable() {
|
|
806
|
-
const fix = "Restore registry access and run zappie doctor again.";
|
|
807
|
-
return [
|
|
808
|
-
check(
|
|
809
|
-
"requires",
|
|
810
|
-
"warn",
|
|
811
|
-
"Without the registry, we could not check package requirements.",
|
|
812
|
-
fix
|
|
813
|
-
),
|
|
814
|
-
check(
|
|
815
|
-
"dependencies",
|
|
816
|
-
"warn",
|
|
817
|
-
"Without the registry, we could not check registry dependencies.",
|
|
818
|
-
fix
|
|
819
|
-
)
|
|
820
|
-
];
|
|
821
|
-
}
|
|
822
|
-
async function registryChecks(cwd, source2, config) {
|
|
823
|
-
try {
|
|
824
|
-
const registry = new Registry(registrySource(source2), cwd);
|
|
825
|
-
await registry.index();
|
|
826
|
-
const manifests = await Promise.all(
|
|
827
|
-
Object.entries(config?.installed ?? {}).map(
|
|
828
|
-
([name2, item2]) => registry.item(name2, item2.version)
|
|
829
|
-
)
|
|
830
|
-
);
|
|
831
|
-
return [
|
|
832
|
-
check("registry", "ok", "We can reach your registry."),
|
|
833
|
-
...dependencyChecks(cwd, manifests)
|
|
834
|
-
];
|
|
835
|
-
} catch (error) {
|
|
836
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
837
|
-
return [
|
|
838
|
-
check(
|
|
839
|
-
"registry",
|
|
840
|
-
"warn",
|
|
841
|
-
message,
|
|
842
|
-
"Check the registry URL or try again when you are online."
|
|
843
|
-
),
|
|
844
|
-
...unavailable()
|
|
845
|
-
];
|
|
846
|
-
}
|
|
847
|
-
}
|
|
47
|
+
${usage}`)}const audit=values.audit??"report";if(audit!=="off"&&audit!=="report"&&audit!=="enforce"){throw new CliError("Choose off, report or enforce for --audit.")}return{name:name2,directory:rest[0],all:values.all===true,audit,history:values.history===true,json:json4}}if(name2==="verify"){if(rest.length>1){throw new CliError(`Pass verify at most one URL.
|
|
848
48
|
|
|
849
|
-
|
|
850
|
-
var frameworks = /* @__PURE__ */ new Set(["react-router", "next", "vite"]);
|
|
851
|
-
var allowed = /* @__PURE__ */ new Set([
|
|
852
|
-
"$schema",
|
|
853
|
-
"framework",
|
|
854
|
-
"componentsDir",
|
|
855
|
-
"alias",
|
|
856
|
-
"tsx",
|
|
857
|
-
"registry",
|
|
858
|
-
"installed"
|
|
859
|
-
]);
|
|
860
|
-
var name = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
861
|
-
var version = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
862
|
-
var hash = /^[a-f0-9]{64}$/;
|
|
863
|
-
function object2(value) {
|
|
864
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
865
|
-
}
|
|
866
|
-
function relative(value) {
|
|
867
|
-
if (typeof value !== "string" || value.length === 0) {
|
|
868
|
-
return false;
|
|
869
|
-
}
|
|
870
|
-
const normalized = value.replaceAll("\\", "/");
|
|
871
|
-
return !normalized.startsWith("/") && !/^[A-Za-z]:\//.test(normalized) && !normalized.split("/").includes("..");
|
|
872
|
-
}
|
|
873
|
-
function validateProject(value) {
|
|
874
|
-
const errors = [];
|
|
875
|
-
if (!object2(value)) {
|
|
876
|
-
return ["Put an object in zappie.json."];
|
|
877
|
-
}
|
|
878
|
-
for (const key of Object.keys(value)) {
|
|
879
|
-
if (!allowed.has(key)) {
|
|
880
|
-
errors.push(`Field "${key}" is unknown.`);
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
if (typeof value.$schema !== "string" || !URL.canParse(value.$schema)) {
|
|
884
|
-
errors.push("Use a URL for $schema.");
|
|
885
|
-
}
|
|
886
|
-
if (typeof value.framework !== "string" || !frameworks.has(value.framework)) {
|
|
887
|
-
errors.push("Set framework to react-router, next or vite.");
|
|
888
|
-
}
|
|
889
|
-
if (!relative(value.componentsDir)) {
|
|
890
|
-
errors.push("Keep componentsDir inside your project.");
|
|
891
|
-
}
|
|
892
|
-
if (value.alias !== void 0 && (typeof value.alias !== "string" || value.alias.length === 0)) {
|
|
893
|
-
errors.push("Use a non-empty string for alias.");
|
|
894
|
-
}
|
|
895
|
-
if (typeof value.tsx !== "boolean") {
|
|
896
|
-
errors.push("Use a boolean for tsx.");
|
|
897
|
-
}
|
|
898
|
-
if (typeof value.registry !== "string" || value.registry.length === 0) {
|
|
899
|
-
errors.push("Set registry to a URL or local directory.");
|
|
900
|
-
}
|
|
901
|
-
if (!object2(value.installed)) {
|
|
902
|
-
errors.push("Use an object for installed.");
|
|
903
|
-
return errors;
|
|
904
|
-
}
|
|
905
|
-
for (const [itemName, item2] of Object.entries(value.installed)) {
|
|
906
|
-
if (!name.test(itemName) || !object2(item2)) {
|
|
907
|
-
errors.push(`installed.${itemName} is invalid.`);
|
|
908
|
-
continue;
|
|
909
|
-
}
|
|
910
|
-
if (typeof item2.version !== "string" || !version.test(item2.version)) {
|
|
911
|
-
errors.push(`installed.${itemName}.version is invalid.`);
|
|
912
|
-
}
|
|
913
|
-
if (!object2(item2.files)) {
|
|
914
|
-
errors.push(`installed.${itemName}.files is invalid.`);
|
|
915
|
-
continue;
|
|
916
|
-
}
|
|
917
|
-
for (const [file, fileHash] of Object.entries(item2.files)) {
|
|
918
|
-
if (!relative(file) || typeof fileHash !== "string" || !hash.test(fileHash)) {
|
|
919
|
-
errors.push(`installed.${itemName}.files.${file} is invalid.`);
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
return errors;
|
|
924
|
-
}
|
|
49
|
+
${usage}`)}const suite=values.suite??"standard";if(suite!=="standard"&&suite!=="extended"){throw new CliError("Choose standard or extended for --suite. To run the quick checks, pass --only quick.")}const runner=values.runner;if(typeof runner==="string"&&!verifyRunners.includes(runner)){throw new CliError(`Choose ${verifyRunners.join(", ")} for --runner.`)}const build=values["no-build"]!==true;const port=typeof values.port==="string"?parsePort(values.port):void 0;if(rest[0]&&(!build||port!==void 0)){throw new CliError("--no-build and --port apply to the local preview. Drop them, or drop the URL.")}return{name:name2,url:rest[0],suite,report:typeof values.report==="string"?values.report:void 0,key:typeof values.key==="string"?values.key:void 0,store:typeof values.store==="string"?values.store:void 0,only:typeof values.only==="string"?parseOnly(values.only):void 0,startPath:typeof values.start==="string"?parseStart(values.start):void 0,build,port,artifacts:typeof values.artifacts==="string"?values.artifacts:void 0,runner,json:json4}}throw new CliError(`Command "${name2}" is unknown.
|
|
925
50
|
|
|
926
|
-
// src/doctor.ts
|
|
927
|
-
|
|
928
|
-
const print = options.print ?? console.log;
|
|
929
|
-
const file = path7.join(options.cwd, CONFIG_FILE);
|
|
930
|
-
const raw = json2(file);
|
|
931
|
-
const errors = validateProject(raw);
|
|
932
|
-
const config = errors.length === 0 ? raw : void 0;
|
|
933
|
-
const packageFile = json2(
|
|
934
|
-
fileURLToPath(new URL("../package.json", import.meta.url))
|
|
935
|
-
);
|
|
936
|
-
const range = options.engineRange ?? packageFile?.engines?.node ?? ">=20";
|
|
937
|
-
const checks = [
|
|
938
|
-
nodeCheck(options.nodeVersion ?? process.versions.node, range),
|
|
939
|
-
configCheck(file, raw, errors),
|
|
940
|
-
frameworkCheck(options.cwd, config),
|
|
941
|
-
filesCheck(options.cwd, config),
|
|
942
|
-
...await registryChecks(
|
|
943
|
-
options.cwd,
|
|
944
|
-
options.source ?? config?.registry,
|
|
945
|
-
config
|
|
946
|
-
)
|
|
947
|
-
];
|
|
948
|
-
const result = { command: "doctor", checks };
|
|
949
|
-
print(options.json ? JSON.stringify(result) : doctorText(checks));
|
|
950
|
-
return { ...result, failed: checks.some((entry) => entry.status === "fail") };
|
|
951
|
-
}
|
|
51
|
+
${usage}`)}import{createRequire}from"module";import path2 from"path";import{pathToFileURL}from"url";async function loadProjectPackage(cwd,name2,manager){const require2=createRequire(path2.join(cwd,"package.json"));let entry;try{entry=require2.resolve(name2)}catch{throw new CliError(`You have not installed ${name2}. Install it with: ${installCommand(manager,name2)}`)}return await import(pathToFileURL(entry).href)}function installCommand(manager,name2){if(manager==="npm"){return`npm install --save-dev ${name2}`}if(manager==="yarn"){return`yarn add --dev ${name2}`}if(manager==="bun"){return`bun add --dev ${name2}`}return`pnpm add --save-dev ${name2}`}async function runProjectCheck(options){const loaded=await(options.load??loadProjectCheck)(options.cwd,options.packageManager);const result=await loaded.runCheck({cwd:options.cwd,all:options.all,audit:options.audit??"report",history:options.history??false,packageManager:options.packageManager,...options.signal?{signal:options.signal}:{}});const print=options.print??console.log;print(options.json?JSON.stringify(result):humanOutput(result));return result}async function loadProjectCheck(cwd,manager){const loaded=await loadProjectPackage(cwd,"@zappie/check",manager);if(typeof loaded.runCheck!=="function"){throw new CliError("Your installed @zappie/check does not export runCheck.")}return loaded}function humanOutput(result){const lines2=[];for(const checked of result.steps){lines2.push(`${checked.name}: ${checked.result}`);for(const issue of checked.problems){const location=issue.file?`${issue.file}${issue.line?`:${issue.line}`:""}`:"project";lines2.push(` ${location}${issue.rule?` [${issue.rule}]`:""} ${issue.message}`);if(issue.fix){lines2.push(` Fix: ${issue.fix}`)}}}return lines2.join("\n")}import path7 from"path";import{fileURLToPath}from"url";import{existsSync as existsSync3,readFileSync as readFileSync3}from"fs";import path4 from"path";import{satisfies}from"semver";import{createHash}from"crypto";function sha256(content){return createHash("sha256").update(content).digest("hex")}import{existsSync as existsSync2,readFileSync as readFileSync2}from"fs";import path3 from"path";function json(file){let source2;try{source2=readFileSync2(file,"utf8")}catch{throw new CliError(`We could not read ${file}.`)}try{return JSON.parse(source2)}catch{throw new CliError(`${file} is not valid JSON.`)}}function packageJson(cwd){const file=path3.join(cwd,"package.json");if(!existsSync2(file)){throw new CliError(`There is no package.json in ${cwd}.`)}return json(file)}function detectFramework(cwd){const value=packageJson(cwd);const dependencies={...value.dependencies,...value.devDependencies,...value.peerDependencies};if(dependencies.next){return"next"}if(dependencies["react-router"]||dependencies["react-router-dom"]){return"react-router"}if(dependencies.vite){return"vite"}throw new CliError("We could not detect React Router, Next.js or Vite.")}function defaultDirectory(cwd,framework){if(framework==="react-router"){return"app/components/zappie"}if(framework==="next"&&!existsSync2(path3.join(cwd,"src"))){return"components/zappie"}return"src/components/zappie"}function parseTsconfig(cwd){const file=path3.join(cwd,"tsconfig.json");if(!existsSync2(file)){return void 0}const source2=readFileSync2(file,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|\s)\/\/.*$/gm,"$1").replace(/,\s*([}\]])/g,"$1");try{return JSON.parse(source2)}catch{throw new CliError(`${file} is not valid JSON or JSONC.`)}}function detectAlias(cwd,directory){const config=parseTsconfig(cwd);const compiler=config?.compilerOptions;if(typeof compiler!=="object"||compiler===null){return void 0}const paths=compiler.paths;if(typeof paths!=="object"||paths===null){return void 0}const target=directory.replaceAll("\\","/");for(const[alias,entries]of Object.entries(paths)){if(!Array.isArray(entries)){continue}for(const entry of entries){if(typeof entry!=="string"){continue}const normalized=entry.replace(/^\.\//,"").replaceAll("\\","/");const star=normalized.indexOf("*");const prefix=star<0?normalized:normalized.slice(0,star);if(!target.startsWith(prefix)){continue}const remainder=target.slice(prefix.length);return star<0?alias:alias.replace("*",remainder)}}return void 0}function kitProject(cwd){const current=readProjectConfig(cwd)??{};const{alias:configuredAlias,...rest}=current;const framework=current.framework??detectFramework(cwd);const componentsDir=current.componentsDir??defaultDirectory(cwd,framework);const alias=configuredAlias??detectAlias(cwd,componentsDir);return{...rest,framework,componentsDir:componentsDir.replaceAll("\\","/"),...alias!==void 0?{alias}:{},tsx:current.tsx??true,installed:current.installed??{}}}function check(name2,status,message,fix){return{name:name2,status,message,...fix?{fix}:{}}}function json2(file){try{return JSON.parse(readFileSync3(file,"utf8"))}catch{return void 0}}function configCheck(file,raw,errors){if(errors.length===0){return check("config","ok","zappie.json matches the kit project schema.")}if(!existsSync3(file)){return check("config","fail","There is no zappie.json in this project.","Run zappie add to create it.")}if(raw===void 0){return check("config","fail","We could not read zappie.json as JSON.","Fix the JSON in zappie.json.")}return check("config","fail",errors.join(" "),"Fix these fields in zappie.json.")}function nodeCheck(version2,range){return satisfies(version2,range)?check("node","ok",`Your Node ${version2} meets ${range}.`):check("node","fail",`Your Node ${version2} does not meet ${range}.`,`Install Node ${range}.`)}function frameworkCheck(cwd,config){try{const detected=detectFramework(cwd);if(config?.framework&&config.framework!==detected){return check("framework","fail",`Found ${detected}, but zappie.json says ${config.framework}.`,"Update zappie.json to match your project.")}const directory=config?.componentsDir;if(!directory||!existsSync3(path4.join(cwd,directory))){return check("framework","fail",`Found ${detected}, but the components directory is missing.`,"Create your configured componentsDir or run zappie add.")}return check("framework","ok",`Found ${detected}. ${directory} exists.`)}catch(error){const message=error instanceof Error?error.message:String(error);return check("framework","fail",message,"Add React Router, Next.js or Vite and configure componentsDir.")}}function filesCheck(cwd,config){const modified2=Object.entries(config?.installed??{}).flatMap(([name2,item2])=>Object.entries(item2.files).filter(([file,expected])=>{const target=path4.join(cwd,file);return!existsSync3(target)||sha256(readFileSync3(target,"utf8"))!==expected}).map(([file])=>`${name2}:${file}`));return modified2.length===0?check("files","ok","Your installed component files match their recorded hashes."):check("files","warn",`Changed or missing files: ${modified2.join(", ")}.`,"Run zappie diff before you apply an update.")}function doctorText(checks){return checks.flatMap(entry=>[`[${entry.status}] ${entry.name}: ${entry.message}`,...entry.fix?[` Fix: ${entry.fix}`]:[]]).join("\n")}import path6 from"path";import{satisfies as satisfies2}from"semver";import{access,readFile}from"fs/promises";import path5 from"path";function object(value,label){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new CliError(`Registry ${label} is invalid.`)}return value}function string(value,label){if(typeof value!=="string"||value.length===0){throw new CliError(`Registry ${label} is invalid.`)}return value}function record(value,label){const input=object(value,label);return Object.fromEntries(Object.entries(input).map(([key,entry])=>[key,string(entry,label)]))}function item(value){const input=object(value,"item");const type=string(input.type,"item type");if(type!=="component"&&type!=="block"){throw new CliError("Registry item type is invalid.")}if(!Array.isArray(input.files)||!Array.isArray(input.registryDependencies)){throw new CliError("Registry item files or dependencies are invalid.")}return{name:string(input.name,"item name"),type,version:string(input.version,"item version"),title:string(input.title,"item title"),description:string(input.description,"item description"),requires:record(input.requires,"item requirements"),dependencies:record(input.dependencies,"item dependencies"),registryDependencies:input.registryDependencies.map(entry=>string(entry,"registry dependency")),files:input.files.map(entry=>{const file=object(entry,"item file");return{path:string(file.path,"file path"),target:string(file.target,"file target"),sha256:string(file.sha256,"file hash"),content:string(file.content,"file content")}})}}function index(value){const input=object(value,"index");if(!Array.isArray(input.items)){throw new CliError("Registry index items are invalid.")}return{version:string(input.version,"index version"),items:input.items.map(entry=>{const value2=item({...object(entry,"index item"),requires:{},dependencies:{},registryDependencies:[],files:[{path:"index",target:"index",sha256:"index",content:"index"}]});return{name:value2.name,type:value2.type,version:value2.version,title:value2.title,description:value2.description}})}}var Registry=class{constructor(source2,cwd){this.source=source2;this.cwd=cwd}remote(){return/^https?:\/\//.test(this.source)}async exists(file){return access(path5.join(path5.resolve(this.cwd,this.source),file)).then(()=>true,()=>false)}async read(file){try{if(this.remote()){const response=await fetch(`${this.source.replace(/\/+$/,"")}/${file}`);if(!response.ok){throw new Error(`${response.status} ${response.statusText}`.trim())}return await response.json()}const root=path5.resolve(this.cwd,this.source);return JSON.parse(await readFile(path5.join(root,file),"utf8"))}catch(error){const message=error instanceof Error?error.message:String(error);throw new CliError(`We could not read registry ${file}: ${message}`,3)}}async index(){return index(await this.read("index.json"))}async item(name2,version2){if(version2===void 0){return item(await this.read(`items/${name2}.json`))}const pinned=`items/${name2}@${version2}.json`;if(this.remote()||await this.exists(pinned)){return item(await this.read(pinned))}const current=item(await this.read(`items/${name2}.json`));if(current.version!==version2){throw new CliError(`We could not read registry ${pinned}: this registry has ${name2} ${current.version} only.`,3)}return current}};function packageVersion(cwd,name2){const file=path6.join(cwd,"node_modules",...name2.split("/"),"package.json");const value=json2(file);if(typeof value!=="object"||value===null){return void 0}return typeof value.version==="string"?value.version:void 0}function dependencyChecks(cwd,manifests){const required=Object.assign({},...manifests.map(item2=>item2.requires));const dependencies=Object.assign({},...manifests.map(item2=>item2.dependencies));const bad=Object.entries(required).filter(([name2,range])=>{const version2=packageVersion(cwd,name2);return version2===void 0||!satisfies2(version2,range)});const missing=Object.keys(dependencies).filter(name2=>packageVersion(cwd,name2)===void 0);return[bad.length===0?check("requires","ok","Your installed Zappie package versions meet every item requirement."):check("requires","fail",`Unmet requirements: ${bad.map(([name2,range])=>`${name2} ${range}`).join(", ")}.`,"Install versions that meet each registry item's requires field."),missing.length===0?check("dependencies","ok","You have every registry npm dependency installed."):check("dependencies","fail",`Missing dependencies: ${missing.join(", ")}.`,"Install the missing npm dependencies.")]}function unavailable(){const fix="Restore registry access and run zappie doctor again.";return[check("requires","warn","Without the registry, we could not check package requirements.",fix),check("dependencies","warn","Without the registry, we could not check registry dependencies.",fix)]}async function registryChecks(cwd,source2,config){try{const registry=new Registry(registrySource(source2),cwd);await registry.index();const manifests=await Promise.all(Object.entries(config?.installed??{}).map(([name2,item2])=>registry.item(name2,item2.version)));return[check("registry","ok","We can reach your registry."),...dependencyChecks(cwd,manifests)]}catch(error){const message=error instanceof Error?error.message:String(error);return[check("registry","warn",message,"Check the registry URL or try again when you are online."),...unavailable()]}}var frameworks=new Set(["react-router","next","vite"]);var allowed=new Set(["$schema","framework","componentsDir","alias","tsx","registry","installed"]);var name=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;var version=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;var hash=/^[a-f0-9]{64}$/;function object2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function relative(value){if(typeof value!=="string"||value.length===0){return false}const normalized=value.replaceAll("\\","/");return!normalized.startsWith("/")&&!/^[A-Za-z]:\//.test(normalized)&&!normalized.split("/").includes("..")}function validateProject(value){const errors=[];if(!object2(value)){return["Put an object in zappie.json."]}for(const key of Object.keys(value)){if(!allowed.has(key)){errors.push(`Field "${key}" is unknown.`)}}if(typeof value.$schema!=="string"||!URL.canParse(value.$schema)){errors.push("Use a URL for $schema.")}if(typeof value.framework!=="string"||!frameworks.has(value.framework)){errors.push("Set framework to react-router, next or vite.")}if(!relative(value.componentsDir)){errors.push("Keep componentsDir inside your project.")}if(value.alias!==void 0&&(typeof value.alias!=="string"||value.alias.length===0)){errors.push("Use a non-empty string for alias.")}if(typeof value.tsx!=="boolean"){errors.push("Use a boolean for tsx.")}if(typeof value.registry!=="string"||value.registry.length===0){errors.push("Set registry to a URL or local directory.")}if(!object2(value.installed)){errors.push("Use an object for installed.");return errors}for(const[itemName,item2]of Object.entries(value.installed)){if(!name.test(itemName)||!object2(item2)){errors.push(`installed.${itemName} is invalid.`);continue}if(typeof item2.version!=="string"||!version.test(item2.version)){errors.push(`installed.${itemName}.version is invalid.`)}if(!object2(item2.files)){errors.push(`installed.${itemName}.files is invalid.`);continue}for(const[file,fileHash]of Object.entries(item2.files)){if(!relative(file)||typeof fileHash!=="string"||!hash.test(fileHash)){errors.push(`installed.${itemName}.files.${file} is invalid.`)}}}return errors}async function doctor(options){const print=options.print??console.log;const file=path7.join(options.cwd,CONFIG_FILE);const raw=json2(file);const errors=validateProject(raw);const config=errors.length===0?raw:void 0;const packageFile=json2(fileURLToPath(new URL("../package.json",import.meta.url)));const range=options.engineRange??packageFile?.engines?.node??">=20";const checks=[nodeCheck(options.nodeVersion??process.versions.node,range),configCheck(file,raw,errors),frameworkCheck(options.cwd,config),filesCheck(options.cwd,config),...await registryChecks(options.cwd,options.source??config?.registry,config)];const result={command:"doctor",checks};print(options.json?JSON.stringify(result):doctorText(checks));return{...result,failed:checks.some(entry=>entry.status==="fail")}}import{Buffer as Buffer2}from"buffer";import{createHash as createHash2}from"crypto";import{existsSync as existsSync7,lstatSync,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync7,writeFileSync as writeFileSync4}from"fs";import path13 from"path";import{createInterface}from"readline/promises";import{fileURLToPath as fileURLToPath2,pathToFileURL as pathToFileURL2,URL as URL2}from"url";import{existsSync as existsSync6,readFileSync as readFileSync6,writeFileSync as writeFileSync3}from"fs";import path12 from"path";import{existsSync as existsSync5,mkdirSync,readFileSync as readFileSync5,writeFileSync as writeFileSync2}from"fs";import path11 from"path";import path8 from"path";function safeTarget(cwd,target){const normalized=target.replaceAll("\\","/");if(normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized.split("/").includes("..")){throw new CliError(`Registry target points outside your project root: ${target}`)}const absolute=path8.resolve(cwd,normalized);if(absolute!==cwd&&!absolute.startsWith(`${cwd}${path8.sep}`)){throw new CliError(`Registry target points outside your project root: ${target}`)}return{normalized,absolute}}function verifySource(item2,file){if(sha256(file.content)!==file.sha256){throw new CliError(`The registry hash does not match ${item2}.`)}}import path9 from"path";var IMPORT=/(\bfrom\s+|\bimport\s*)(["'])(@\/components\/zappie\/([^"']+))\2/g;function posixRelative(from,to){const value=path9.posix.relative(path9.posix.dirname(from),to);return value.startsWith(".")?value:`./${value}`}function rewriteKitImports(content,target,componentsDir,alias){return content.replace(IMPORT,(match,keyword,quote,specifier,sibling)=>{const replacement=alias?`${alias.replace(/\/$/,"")}/${sibling}`:posixRelative(target,`${componentsDir}/${sibling}`);return`${keyword}${quote}${replacement}${quote}`})}function installTarget(target,componentsDir){const normalized=target.replaceAll("\\","/");return normalized.startsWith("components/zappie/")?`${componentsDir}/${normalized.slice("components/zappie/".length)}`:normalized}import{spawnSync}from"child_process";import{existsSync as existsSync4,readFileSync as readFileSync4}from"fs";import path10 from"path";function detectPackageManager(cwd){for(let directory=cwd;;directory=path10.dirname(directory)){if(existsSync4(path10.join(directory,"pnpm-lock.yaml"))){return"pnpm"}if(existsSync4(path10.join(directory,"package-lock.json"))){return"npm"}if(existsSync4(path10.join(directory,"yarn.lock"))){return"yarn"}if(existsSync4(path10.join(directory,"bun.lock"))||existsSync4(path10.join(directory,"bun.lockb"))){return"bun"}if(path10.dirname(directory)===directory){break}}return"npm"}function missingDependencies(cwd,requested){const manifest=JSON.parse(readFileSync4(path10.join(cwd,"package.json"),"utf8"));const present={...manifest.dependencies,...manifest.devDependencies,...manifest.peerDependencies};return Object.entries(requested).filter(([name2])=>!(name2 in present)).map(([name2,version2])=>`${name2}@${version2}`)}function installDependencies(cwd,dependencies,quiet=false){if(dependencies.length===0){return}const manager=detectPackageManager(cwd);const command=manager==="npm"?"install":"add";const result=spawnSync(manager,[command,...dependencies],{cwd,stdio:quiet?["ignore","ignore","inherit"]:"inherit"});if(result.status!==0){throw new CliError(`${manager} could not install your dependencies.`)}}async function batches(values,size,read){const output=[];for(let index2=0;index2<values.length;index2+=size){output.push(...await Promise.all(values.slice(index2,index2+size).map(read)))}return output}async function resolveRegistryItems(registry,requested){const index2=await registry.index();const known=new Set(index2.items.map(entry=>entry.name));for(const name2 of requested){if(!known.has(name2)){throw new CliError(`Registry item "${name2}" is unknown.`)}}const items=new Map;let pending=[...new Set(requested)];while(pending.length>0){const loaded=await batches(pending,6,name2=>registry.item(name2));for(const value of loaded){if(!known.has(value.name)){throw new CliError(`Registry item "${value.name}" is unknown.`)}items.set(value.name,value)}const dependencies=[];for(const value of loaded){for(const dependency of value.registryDependencies){if(!known.has(dependency)){throw new CliError(`${valueName(value)} needs unknown registry item "${dependency}".`)}if(!items.has(dependency)){dependencies.push(dependency)}}}pending=[...new Set(dependencies)]}const visiting=new Set;const visited=new Set;const ordered=[];const visit=(name2,trail)=>{if(visiting.has(name2)){throw new CliError(`Registry dependencies form a cycle: ${[...trail,name2].join(" -> ")}.`)}if(visited.has(name2)){return}const value=items.get(name2);if(!value){throw new CliError(`Registry item "${name2}" is unknown.`)}visiting.add(name2);for(const dependency of value.registryDependencies){visit(dependency,[...trail,name2])}visiting.delete(name2);visited.add(name2);ordered.push(value)};for(const name2 of requested){visit(name2,[])}return ordered}function valueName(value){return`Registry item "${value.name}"`}async function addItems(options){const print=options.print??console.log;const project2=kitProject(options.cwd);const registry=new Registry(options.source,options.cwd);const items=await resolveRegistryItems(registry,options.names);const planned=[];for(const item2 of items){for(const file of item2.files){verifySource(`${item2.name}/${file.path}`,file);const target=installTarget(file.target,project2.componentsDir);const safe=safeTarget(options.cwd,target);const content=rewriteKitImports(file.content,safe.normalized,project2.componentsDir,project2.alias);const installedHash=project2.installed[item2.name]?.files[safe.normalized];if(existsSync5(safe.absolute)){const currentHash=sha256(readFileSync5(safe.absolute,"utf8"));if(currentHash!==installedHash&&!options.overwrite){throw new CliError(`${safe.normalized} has local changes. Pass --overwrite to replace it.`)}}planned.push({item:item2.name,target:safe.normalized,content,hash:sha256(content)})}}const dependencies=missingDependencies(options.cwd,Object.assign({},...items.map(item2=>item2.dependencies)));const result={command:"add",dryRun:options.dryRun,items:items.map(item2=>item2.name),files:planned.map(file=>file.target),dependencies};if(options.dryRun){print(options.json?JSON.stringify(result):planText(result));return result}if(options.install){installDependencies(options.cwd,dependencies,options.json)}for(const file of planned){const absolute=path11.join(options.cwd,file.target);mkdirSync(path11.dirname(absolute),{recursive:true});writeFileSync2(absolute,file.content)}const installed={...project2.installed};for(const item2 of items){const files2=Object.fromEntries(planned.filter(file=>file.item===item2.name).map(file=>[file.target,file.hash]));installed[item2.name]={version:item2.version,files:files2}}writeProjectConfig(options.cwd,{...project2,$schema:"https://registry.zappie.ai/v1/schema/project.json",registry:options.source,installed});print(options.json?JSON.stringify(result):planText(result));return result}function planText(result){const heading=result.dryRun?"Plan to add":"Added";const lines2=[`${heading}: ${result.items.join(", ")}`,...result.files];if(result.dependencies.length>0){lines2.push(`Dependencies: ${result.dependencies.join(", ")}`)}return lines2.join("\n")}var PACKAGES=["@zappie/sdk","@zappie/foundations","@zappie/tokens"];async function initExistingProject(command,directory,store,key){const{framework,componentsDir,alias}=kitProject(directory);const missing=missingDependencies(directory,Object.fromEntries(PACKAGES.map(name2=>[name2,"latest"])));const add={cwd:directory,names:["provider"],source:registrySource(command.registry,readProjectConfig(directory)?.registry),overwrite:false,install:false,json:true,print:()=>{}};await addItems({...add,dryRun:true});if(command.install){installDependencies(directory,missing,command.json)}const{files:files2}=await addItems({...add,dryRun:false});const prefix=framework==="next"?"NEXT_PUBLIC_":"VITE_";const env=path12.join(directory,".env.local");const current=existsSync6(env)?readFileSync6(env,"utf8"):"";const loaded=[".env",".env.local",".env.development",".env.development.local"].map(name2=>path12.join(directory,name2)).filter(existsSync6).map(file=>readFileSync6(file,"utf8")).join("\n");const defined=name2=>new RegExp(`^\\s*(?:export\\s+)?${name2}\\s*=`,"m").test(loaded);const lines2=[[`${prefix}ZAPPIE_STORE`,store],[`${prefix}ZAPPIE_KEY`,key]].filter(([name2,value])=>value&&!defined(name2)).map(([name2,value])=>`${name2}=${value}
|
|
52
|
+
`);if(lines2.length){writeFileSync3(env,`${current}${current&&!current.endsWith("\n")?"\n":""}${lines2.join("")}`)}const written=[...files2,"zappie.json",...lines2.length?[".env.local"]:[]];const read=framework==="next"?"process.env.NEXT_PUBLIC_":"import.meta.env.VITE_";const root=framework==="react-router"?"app/root.tsx":framework==="next"?`${componentsDir.startsWith("src/")?"src/":""}app/layout.tsx`:"src/main.tsx";const relative2=path12.posix.relative(path12.posix.dirname(root),componentsDir);const from=`${alias??(relative2.startsWith(".")?relative2:`./${relative2}`)}/zappie-provider`;const wrap=`import { ZappieProvider } from "${from}";
|
|
952
53
|
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
lstatSync,
|
|
959
|
-
mkdirSync,
|
|
960
|
-
readdirSync,
|
|
961
|
-
readFileSync as readFileSync5,
|
|
962
|
-
writeFileSync as writeFileSync2
|
|
963
|
-
} from "fs";
|
|
964
|
-
import path9 from "path";
|
|
965
|
-
import { createInterface } from "readline/promises";
|
|
966
|
-
import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL2, URL as URL2 } from "url";
|
|
967
|
-
|
|
968
|
-
// src/package-manager.ts
|
|
969
|
-
import { spawnSync } from "child_process";
|
|
970
|
-
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
|
|
971
|
-
import path8 from "path";
|
|
972
|
-
function detectPackageManager(cwd) {
|
|
973
|
-
for (let directory = cwd; ; directory = path8.dirname(directory)) {
|
|
974
|
-
if (existsSync4(path8.join(directory, "pnpm-lock.yaml"))) {
|
|
975
|
-
return "pnpm";
|
|
976
|
-
}
|
|
977
|
-
if (existsSync4(path8.join(directory, "package-lock.json"))) {
|
|
978
|
-
return "npm";
|
|
979
|
-
}
|
|
980
|
-
if (existsSync4(path8.join(directory, "yarn.lock"))) {
|
|
981
|
-
return "yarn";
|
|
982
|
-
}
|
|
983
|
-
if (existsSync4(path8.join(directory, "bun.lock")) || existsSync4(path8.join(directory, "bun.lockb"))) {
|
|
984
|
-
return "bun";
|
|
985
|
-
}
|
|
986
|
-
if (path8.dirname(directory) === directory) {
|
|
987
|
-
break;
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
return "npm";
|
|
991
|
-
}
|
|
992
|
-
function missingDependencies(cwd, requested) {
|
|
993
|
-
const manifest = JSON.parse(
|
|
994
|
-
readFileSync4(path8.join(cwd, "package.json"), "utf8")
|
|
995
|
-
);
|
|
996
|
-
const present = {
|
|
997
|
-
...manifest.dependencies,
|
|
998
|
-
...manifest.devDependencies,
|
|
999
|
-
...manifest.peerDependencies
|
|
1000
|
-
};
|
|
1001
|
-
return Object.entries(requested).filter(([name2]) => !(name2 in present)).map(([name2, version2]) => `${name2}@${version2}`);
|
|
1002
|
-
}
|
|
1003
|
-
function installDependencies(cwd, dependencies, quiet = false) {
|
|
1004
|
-
if (dependencies.length === 0) {
|
|
1005
|
-
return;
|
|
1006
|
-
}
|
|
1007
|
-
const manager = detectPackageManager(cwd);
|
|
1008
|
-
const command = manager === "npm" ? "install" : "add";
|
|
1009
|
-
const result = spawnSync(manager, [command, ...dependencies], {
|
|
1010
|
-
cwd,
|
|
1011
|
-
stdio: quiet ? ["ignore", "ignore", "inherit"] : "inherit"
|
|
1012
|
-
});
|
|
1013
|
-
if (result.status !== 0) {
|
|
1014
|
-
throw new CliError(`${manager} could not install your dependencies.`);
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
// src/starter-archive.ts
|
|
1019
|
-
import "buffer";
|
|
1020
|
-
import { gunzipSync } from "zlib";
|
|
1021
|
-
function readStarterArchive(bytes) {
|
|
1022
|
-
const tar = gunzipSync(new Uint8Array(bytes), {
|
|
1023
|
-
maxOutputLength: 32 * 1024 * 1024
|
|
1024
|
-
});
|
|
1025
|
-
const files2 = /* @__PURE__ */ new Map();
|
|
1026
|
-
const invalid = () => new CliError("The starter archive is invalid or contains an unsafe path.");
|
|
1027
|
-
const text = (start, length) => tar.subarray(start, start + length).toString("utf8").split("\0")[0];
|
|
1028
|
-
let offset = 0;
|
|
1029
|
-
while (offset + 512 <= tar.length) {
|
|
1030
|
-
const header = tar.subarray(offset, offset + 512);
|
|
1031
|
-
if (header.every((byte) => byte === 0)) {
|
|
1032
|
-
if (tar.length < offset + 1024 || tar.length % 512 !== 0 || tar.subarray(offset).some((byte) => byte !== 0)) {
|
|
1033
|
-
throw invalid();
|
|
1034
|
-
}
|
|
1035
|
-
for (const name3 of files2.keys()) {
|
|
1036
|
-
const parts = name3.split("/");
|
|
1037
|
-
parts.pop();
|
|
1038
|
-
while (parts.length) {
|
|
1039
|
-
if (files2.has(parts.join("/"))) {
|
|
1040
|
-
throw invalid();
|
|
1041
|
-
}
|
|
1042
|
-
parts.pop();
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
return files2;
|
|
1046
|
-
}
|
|
1047
|
-
const checksum = header.reduce(
|
|
1048
|
-
(sum, byte, index2) => sum + (index2 >= 148 && index2 < 156 ? 32 : byte),
|
|
1049
|
-
0
|
|
1050
|
-
);
|
|
1051
|
-
const stored = text(offset + 148, 8).trim();
|
|
1052
|
-
const sizeText = text(offset + 124, 12).trim();
|
|
1053
|
-
const name2 = text(offset, 100);
|
|
1054
|
-
const kind = text(offset + 156, 1);
|
|
1055
|
-
if (!/^[0-7]+$/.test(stored) || parseInt(stored, 8) !== checksum || !/^[0-7]+$/.test(sizeText) || kind !== "0" || text(offset + 257, 6) !== "ustar" || text(offset + 345, 155) !== "" || /[\\:\x00-\x1f\x7f]/.test(name2) || name2.split("/").some((part) => !part || part === "." || part === "..") || files2.has(name2)) {
|
|
1056
|
-
throw invalid();
|
|
1057
|
-
}
|
|
1058
|
-
const size = parseInt(sizeText, 8);
|
|
1059
|
-
offset += 512;
|
|
1060
|
-
if (!Number.isSafeInteger(size) || offset + size > tar.length) {
|
|
1061
|
-
throw invalid();
|
|
1062
|
-
}
|
|
1063
|
-
files2.set(name2, tar.subarray(offset, offset + size));
|
|
1064
|
-
offset += Math.ceil(size / 512) * 512;
|
|
1065
|
-
}
|
|
1066
|
-
throw invalid();
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
// src/init.ts
|
|
1070
|
-
async function download(url) {
|
|
1071
|
-
if (url.protocol === "file:") {
|
|
1072
|
-
return readFileSync5(fileURLToPath2(url));
|
|
1073
|
-
}
|
|
1074
|
-
const response = await fetch(url.href, {
|
|
1075
|
-
signal: AbortSignal.timeout(3e4)
|
|
1076
|
-
});
|
|
1077
|
-
if (!response.ok) {
|
|
1078
|
-
throw new CliError(`Could not download the starter (${response.status}).`);
|
|
1079
|
-
}
|
|
1080
|
-
return Buffer2.from(await response.arrayBuffer());
|
|
1081
|
-
}
|
|
1082
|
-
async function initProject(command, cwd) {
|
|
1083
|
-
const directory = path9.resolve(cwd, command.directory ?? ".");
|
|
1084
|
-
if (existsSync5(directory) && (!lstatSync(directory).isDirectory() || readdirSync(directory).length > 0)) {
|
|
1085
|
-
throw new CliError(
|
|
1086
|
-
"Choose a new or empty folder. Existing-project init is not available yet."
|
|
1087
|
-
);
|
|
1088
|
-
}
|
|
1089
|
-
if (command.template !== "react-router") {
|
|
1090
|
-
throw new CliError("Choose react-router for --template.");
|
|
1091
|
-
}
|
|
1092
|
-
let { store, key } = command;
|
|
1093
|
-
if (!command.yes && !command.json && process.stdin.isTTY && (!store || !key)) {
|
|
1094
|
-
const prompt = createInterface({
|
|
1095
|
-
input: process.stdin,
|
|
1096
|
-
output: process.stdout
|
|
1097
|
-
});
|
|
1098
|
-
try {
|
|
1099
|
-
store ||= await prompt.question("Store slug: ");
|
|
1100
|
-
key ||= await prompt.question(
|
|
1101
|
-
"Test publishable key (leave blank to set it later): "
|
|
1102
|
-
);
|
|
1103
|
-
} finally {
|
|
1104
|
-
prompt.close();
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
if (!store || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(store)) {
|
|
1108
|
-
throw new CliError(
|
|
1109
|
-
"Pass --store with your store slug, using lowercase letters, numbers and hyphens."
|
|
1110
|
-
);
|
|
1111
|
-
}
|
|
1112
|
-
if (key && !/^pk_test_[A-Za-z0-9_-]+$/.test(key)) {
|
|
1113
|
-
throw new CliError(
|
|
1114
|
-
"Use a pk_test_ publishable key. Live and secret keys are not accepted by init."
|
|
1115
|
-
);
|
|
1116
|
-
}
|
|
1117
|
-
const name2 = path9.basename(directory).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 63) || "my-storefront";
|
|
1118
|
-
const source2 = command.registry ?? DEFAULT_REGISTRY;
|
|
1119
|
-
const base = /^[a-z]+:\/\//i.test(source2) ? new URL2(source2.endsWith("/") ? source2 : `${source2}/`) : pathToFileURL2(path9.resolve(cwd, source2) + path9.sep);
|
|
1120
|
-
const manifest = JSON.parse(
|
|
1121
|
-
(await download(new URL2("starters/index.json", base))).toString("utf8")
|
|
1122
|
-
);
|
|
1123
|
-
const template = manifest.templates?.[command.template];
|
|
1124
|
-
const entry = template?.versions?.[template.latest];
|
|
1125
|
-
if (!entry || !/^react-router@\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?\.tgz$/.test(
|
|
1126
|
-
entry.file
|
|
1127
|
-
) || !/^[a-f0-9]{64}$/.test(entry.sha256) || !Number.isSafeInteger(entry.size) || entry.size <= 0) {
|
|
1128
|
-
throw new CliError("The starter manifest is invalid.");
|
|
1129
|
-
}
|
|
1130
|
-
const bytes = await download(new URL2(`starters/${entry.file}`, base));
|
|
1131
|
-
if (bytes.length !== entry.size || createHash2("sha256").update(new Uint8Array(bytes)).digest("hex") !== entry.sha256) {
|
|
1132
|
-
throw new CliError(
|
|
1133
|
-
"The starter archive does not match its manifest. Nothing was written."
|
|
1134
|
-
);
|
|
1135
|
-
}
|
|
1136
|
-
const files2 = readStarterArchive(bytes);
|
|
1137
|
-
for (const filename of [
|
|
1138
|
-
"package.json",
|
|
1139
|
-
"wrangler.jsonc",
|
|
1140
|
-
"zappie.config.ts",
|
|
1141
|
-
".gitignore"
|
|
1142
|
-
]) {
|
|
1143
|
-
const file = files2.get(filename);
|
|
1144
|
-
if (!file) {
|
|
1145
|
-
throw new CliError(
|
|
1146
|
-
`The starter is missing ${filename}. Nothing was written.`
|
|
1147
|
-
);
|
|
1148
|
-
}
|
|
1149
|
-
files2.set(
|
|
1150
|
-
filename,
|
|
1151
|
-
Buffer2.from(
|
|
1152
|
-
file.toString("utf8").replaceAll("__ZAPPIE_NAME__", name2).replaceAll("__ZAPPIE_STORE__", store)
|
|
1153
|
-
)
|
|
1154
|
-
);
|
|
1155
|
-
}
|
|
1156
|
-
if ([...files2.keys()].some((name3) => name3.startsWith(".dev.vars/"))) {
|
|
1157
|
-
throw new CliError(
|
|
1158
|
-
"The starter archive contains an unsafe path. Nothing was written."
|
|
1159
|
-
);
|
|
1160
|
-
}
|
|
1161
|
-
files2.set(
|
|
1162
|
-
".dev.vars",
|
|
1163
|
-
Buffer2.from(
|
|
1164
|
-
`ZAPPIE_API=https://api.zappie.ai/storefront/v1
|
|
54
|
+
<ZappieProvider publishableKey={${read}ZAPPIE_KEY!} store={${read}ZAPPIE_STORE!}>
|
|
55
|
+
{children}
|
|
56
|
+
</ZappieProvider>`;const manager=detectPackageManager(directory);const install=!command.install&&missing.length?`${manager} ${manager==="npm"?"install":"add"} ${missing.join(" ")}`:void 0;const hint=key||defined(`${prefix}ZAPPIE_KEY`)?void 0:`Set ${prefix}ZAPPIE_KEY in .env.local to your test publishable key.`;if(command.json){console.log(JSON.stringify({command:"init",directory,framework,dependencies:missing,installed:command.install,files:written,wrap:{file:root,code:wrap},...install?{next:[install]}:{},...hint?{hint}:{}}));return}console.log([`Added Zappie to your ${framework} project in ${directory}.`,...install?[`Install the packages it needs:
|
|
57
|
+
${install}`]:[],...hint?[hint]:[],`Wrote ${written.join(", ")}.`,`Wrap your app in the provider in ${root}:
|
|
58
|
+
${wrap}`].join("\n\n"))}import"buffer";import{gunzipSync}from"zlib";function readStarterArchive(bytes){const tar=gunzipSync(new Uint8Array(bytes),{maxOutputLength:32*1024*1024});const files2=new Map;const invalid=()=>new CliError("The starter archive is invalid or contains an unsafe path.");const text=(start,length)=>tar.subarray(start,start+length).toString("utf8").split("\0")[0];let offset=0;while(offset+512<=tar.length){const header=tar.subarray(offset,offset+512);if(header.every(byte=>byte===0)){if(tar.length<offset+1024||tar.length%512!==0||tar.subarray(offset).some(byte=>byte!==0)){throw invalid()}for(const name3 of files2.keys()){const parts=name3.split("/");parts.pop();while(parts.length){if(files2.has(parts.join("/"))){throw invalid()}parts.pop()}}return files2}const checksum=header.reduce((sum,byte,index2)=>sum+(index2>=148&&index2<156?32:byte),0);const stored=text(offset+148,8).trim();const sizeText=text(offset+124,12).trim();const name2=text(offset,100);const kind=text(offset+156,1);if(!/^[0-7]+$/.test(stored)||parseInt(stored,8)!==checksum||!/^[0-7]+$/.test(sizeText)||kind!=="0"||text(offset+257,6)!=="ustar"||text(offset+345,155)!==""||/[\\:\x00-\x1f\x7f]/.test(name2)||name2.split("/").some(part=>!part||part==="."||part==="..")||files2.has(name2)){throw invalid()}const size=parseInt(sizeText,8);offset+=512;if(!Number.isSafeInteger(size)||offset+size>tar.length){throw invalid()}files2.set(name2,tar.subarray(offset,offset+size));offset+=Math.ceil(size/512)*512}throw invalid()}async function download(url){if(url.protocol==="file:"){return readFileSync7(fileURLToPath2(url))}const response=await fetch(url.href,{signal:AbortSignal.timeout(3e4)});if(!response.ok){throw new CliError(`Could not download the starter (${response.status}).`)}return Buffer2.from(await response.arrayBuffer())}async function initProject(command,cwd){const directory=path13.resolve(cwd,command.directory??".");const existing=existsSync7(directory)&&(!lstatSync(directory).isDirectory()||readdirSync(directory).length>0);if(existing&&!existsSync7(path13.join(directory,"package.json"))){throw new CliError("Choose a new or empty folder, or a project folder with a package.json.")}if(!existing&&command.template!=="react-router"){throw new CliError("Choose react-router for --template.")}let{store,key}=command;if(!command.yes&&!command.json&&process.stdin.isTTY&&(!store||!key)){const prompt=createInterface({input:process.stdin,output:process.stdout});try{store||=await prompt.question("Store slug: ");key||=await prompt.question("Test publishable key (leave blank to set it later): ")}finally{prompt.close()}}if(!store||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(store)){throw new CliError("Pass --store with your store slug, using lowercase letters, numbers and hyphens.")}if(key&&!/^pk_test_[A-Za-z0-9_-]+$/.test(key)){throw new CliError("Use a pk_test_ publishable key. Live and secret keys are not accepted by init.")}if(existing){await initExistingProject(command,directory,store,key);return}const name2=path13.basename(directory).toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63)||"my-storefront";const source2=command.registry??DEFAULT_REGISTRY;const base=/^[a-z]+:\/\//i.test(source2)?new URL2(source2.endsWith("/")?source2:`${source2}/`):pathToFileURL2(path13.resolve(cwd,source2)+path13.sep);const manifest=JSON.parse((await download(new URL2("starters/index.json",base))).toString("utf8"));const template=manifest.templates?.[command.template];const entry=template?.versions?.[template.latest];if(!entry||!/^react-router@\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?\.tgz$/.test(entry.file)||!/^[a-f0-9]{64}$/.test(entry.sha256)||!Number.isSafeInteger(entry.size)||entry.size<=0){throw new CliError("The starter manifest is invalid.")}const bytes=await download(new URL2(`starters/${entry.file}`,base));if(bytes.length!==entry.size||createHash2("sha256").update(new Uint8Array(bytes)).digest("hex")!==entry.sha256){throw new CliError("The starter archive does not match its manifest. Nothing was written.")}const files2=readStarterArchive(bytes);for(const filename of["package.json","wrangler.jsonc","zappie.config.ts",".gitignore"]){const file=files2.get(filename);if(!file){throw new CliError(`The starter is missing ${filename}. Nothing was written.`)}files2.set(filename,Buffer2.from(file.toString("utf8").replaceAll("__ZAPPIE_NAME__",name2).replaceAll("__ZAPPIE_STORE__",store)))}if([...files2.keys()].some(name3=>name3.startsWith(".dev.vars/"))){throw new CliError("The starter archive contains an unsafe path. Nothing was written.")}files2.set(".dev.vars",Buffer2.from(`ZAPPIE_API=https://api.zappie.ai/storefront/v1
|
|
1165
59
|
ZAPPIE_STORE=${store}
|
|
1166
|
-
ZAPPIE_KEY=${key
|
|
1167
|
-
`
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
mkdirSync(directory, { recursive: true });
|
|
1171
|
-
|
|
1172
|
-
const destination = path9.join(directory, filename);
|
|
1173
|
-
mkdirSync(path9.dirname(destination), { recursive: true });
|
|
1174
|
-
writeFileSync2(destination, new Uint8Array(contents), { flag: "wx" });
|
|
1175
|
-
}
|
|
1176
|
-
const manager = detectPackageManager(directory);
|
|
1177
|
-
const run = manager === "npm" ? "npm run" : manager;
|
|
1178
|
-
const next = [`${manager} install`, `${run} dev`, `${run} check`];
|
|
1179
|
-
const hint = key ? void 0 : "Set your test publishable key in .dev.vars before starting the storefront.";
|
|
1180
|
-
if (command.json) {
|
|
1181
|
-
console.log(
|
|
1182
|
-
JSON.stringify({
|
|
1183
|
-
command: "init",
|
|
1184
|
-
directory,
|
|
1185
|
-
template: command.template,
|
|
1186
|
-
version: template.latest,
|
|
1187
|
-
next,
|
|
1188
|
-
...hint ? { hint } : {}
|
|
1189
|
-
})
|
|
1190
|
-
);
|
|
1191
|
-
} else {
|
|
1192
|
-
console.log(
|
|
1193
|
-
`Created your storefront in ${directory}.
|
|
1194
|
-
${hint ? `${hint}
|
|
1195
|
-
` : ""}In that folder, run:
|
|
1196
|
-
${next.join("\n")}`
|
|
1197
|
-
);
|
|
1198
|
-
}
|
|
1199
|
-
}
|
|
1200
|
-
|
|
1201
|
-
// src/kit-add.ts
|
|
1202
|
-
import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
|
|
1203
|
-
import path12 from "path";
|
|
1204
|
-
|
|
1205
|
-
// src/kit-files.ts
|
|
1206
|
-
import path10 from "path";
|
|
1207
|
-
function safeTarget(cwd, target) {
|
|
1208
|
-
const normalized = target.replaceAll("\\", "/");
|
|
1209
|
-
if (normalized.startsWith("/") || /^[A-Za-z]:\//.test(normalized) || normalized.split("/").includes("..")) {
|
|
1210
|
-
throw new CliError(
|
|
1211
|
-
`Registry target points outside your project root: ${target}`
|
|
1212
|
-
);
|
|
1213
|
-
}
|
|
1214
|
-
const absolute = path10.resolve(cwd, normalized);
|
|
1215
|
-
if (absolute !== cwd && !absolute.startsWith(`${cwd}${path10.sep}`)) {
|
|
1216
|
-
throw new CliError(
|
|
1217
|
-
`Registry target points outside your project root: ${target}`
|
|
1218
|
-
);
|
|
1219
|
-
}
|
|
1220
|
-
return { normalized, absolute };
|
|
1221
|
-
}
|
|
1222
|
-
function verifySource(item2, file) {
|
|
1223
|
-
if (sha256(file.content) !== file.sha256) {
|
|
1224
|
-
throw new CliError(`The registry hash does not match ${item2}.`);
|
|
1225
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
|
|
1228
|
-
// src/kit-imports.ts
|
|
1229
|
-
import path11 from "path";
|
|
1230
|
-
var IMPORT = /(\bfrom\s+|\bimport\s*)(["'])(@\/components\/zappie\/([^"']+))\2/g;
|
|
1231
|
-
function posixRelative(from, to) {
|
|
1232
|
-
const value = path11.posix.relative(path11.posix.dirname(from), to);
|
|
1233
|
-
return value.startsWith(".") ? value : `./${value}`;
|
|
1234
|
-
}
|
|
1235
|
-
function rewriteKitImports(content, target, componentsDir, alias) {
|
|
1236
|
-
return content.replace(
|
|
1237
|
-
IMPORT,
|
|
1238
|
-
(match, keyword, quote, specifier, sibling) => {
|
|
1239
|
-
const replacement = alias ? `${alias.replace(/\/$/, "")}/${sibling}` : posixRelative(target, `${componentsDir}/${sibling}`);
|
|
1240
|
-
return `${keyword}${quote}${replacement}${quote}`;
|
|
1241
|
-
}
|
|
1242
|
-
);
|
|
1243
|
-
}
|
|
1244
|
-
function installTarget(target, componentsDir) {
|
|
1245
|
-
const normalized = target.replaceAll("\\", "/");
|
|
1246
|
-
return normalized.startsWith("components/zappie/") ? `${componentsDir}/${normalized.slice("components/zappie/".length)}` : normalized;
|
|
1247
|
-
}
|
|
1248
|
-
|
|
1249
|
-
// src/registry-graph.ts
|
|
1250
|
-
async function batches(values, size, read) {
|
|
1251
|
-
const output = [];
|
|
1252
|
-
for (let index2 = 0; index2 < values.length; index2 += size) {
|
|
1253
|
-
output.push(
|
|
1254
|
-
...await Promise.all(values.slice(index2, index2 + size).map(read))
|
|
1255
|
-
);
|
|
1256
|
-
}
|
|
1257
|
-
return output;
|
|
1258
|
-
}
|
|
1259
|
-
async function resolveRegistryItems(registry, requested) {
|
|
1260
|
-
const index2 = await registry.index();
|
|
1261
|
-
const known = new Set(index2.items.map((entry) => entry.name));
|
|
1262
|
-
for (const name2 of requested) {
|
|
1263
|
-
if (!known.has(name2)) {
|
|
1264
|
-
throw new CliError(`Registry item "${name2}" is unknown.`);
|
|
1265
|
-
}
|
|
1266
|
-
}
|
|
1267
|
-
const items = /* @__PURE__ */ new Map();
|
|
1268
|
-
let pending = [...new Set(requested)];
|
|
1269
|
-
while (pending.length > 0) {
|
|
1270
|
-
const loaded = await batches(pending, 6, (name2) => registry.item(name2));
|
|
1271
|
-
for (const value of loaded) {
|
|
1272
|
-
if (!known.has(value.name)) {
|
|
1273
|
-
throw new CliError(`Registry item "${value.name}" is unknown.`);
|
|
1274
|
-
}
|
|
1275
|
-
items.set(value.name, value);
|
|
1276
|
-
}
|
|
1277
|
-
const dependencies = [];
|
|
1278
|
-
for (const value of loaded) {
|
|
1279
|
-
for (const dependency of value.registryDependencies) {
|
|
1280
|
-
if (!known.has(dependency)) {
|
|
1281
|
-
throw new CliError(
|
|
1282
|
-
`${valueName(value)} needs unknown registry item "${dependency}".`
|
|
1283
|
-
);
|
|
1284
|
-
}
|
|
1285
|
-
if (!items.has(dependency)) {
|
|
1286
|
-
dependencies.push(dependency);
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
}
|
|
1290
|
-
pending = [...new Set(dependencies)];
|
|
1291
|
-
}
|
|
1292
|
-
const visiting = /* @__PURE__ */ new Set();
|
|
1293
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1294
|
-
const ordered = [];
|
|
1295
|
-
const visit = (name2, trail) => {
|
|
1296
|
-
if (visiting.has(name2)) {
|
|
1297
|
-
throw new CliError(
|
|
1298
|
-
`Registry dependencies form a cycle: ${[...trail, name2].join(" -> ")}.`
|
|
1299
|
-
);
|
|
1300
|
-
}
|
|
1301
|
-
if (visited.has(name2)) {
|
|
1302
|
-
return;
|
|
1303
|
-
}
|
|
1304
|
-
const value = items.get(name2);
|
|
1305
|
-
if (!value) {
|
|
1306
|
-
throw new CliError(`Registry item "${name2}" is unknown.`);
|
|
1307
|
-
}
|
|
1308
|
-
visiting.add(name2);
|
|
1309
|
-
for (const dependency of value.registryDependencies) {
|
|
1310
|
-
visit(dependency, [...trail, name2]);
|
|
1311
|
-
}
|
|
1312
|
-
visiting.delete(name2);
|
|
1313
|
-
visited.add(name2);
|
|
1314
|
-
ordered.push(value);
|
|
1315
|
-
};
|
|
1316
|
-
for (const name2 of requested) {
|
|
1317
|
-
visit(name2, []);
|
|
1318
|
-
}
|
|
1319
|
-
return ordered;
|
|
1320
|
-
}
|
|
1321
|
-
function valueName(value) {
|
|
1322
|
-
return `Registry item "${value.name}"`;
|
|
1323
|
-
}
|
|
1324
|
-
|
|
1325
|
-
// src/kit-add.ts
|
|
1326
|
-
async function addItems(options) {
|
|
1327
|
-
const print = options.print ?? console.log;
|
|
1328
|
-
const project2 = kitProject(options.cwd);
|
|
1329
|
-
const registry = new Registry(options.source, options.cwd);
|
|
1330
|
-
const items = await resolveRegistryItems(registry, options.names);
|
|
1331
|
-
const planned = [];
|
|
1332
|
-
for (const item2 of items) {
|
|
1333
|
-
for (const file of item2.files) {
|
|
1334
|
-
verifySource(`${item2.name}/${file.path}`, file);
|
|
1335
|
-
const target = installTarget(file.target, project2.componentsDir);
|
|
1336
|
-
const safe = safeTarget(options.cwd, target);
|
|
1337
|
-
const content = rewriteKitImports(
|
|
1338
|
-
file.content,
|
|
1339
|
-
safe.normalized,
|
|
1340
|
-
project2.componentsDir,
|
|
1341
|
-
project2.alias
|
|
1342
|
-
);
|
|
1343
|
-
const installedHash = project2.installed[item2.name]?.files[safe.normalized];
|
|
1344
|
-
if (existsSync6(safe.absolute)) {
|
|
1345
|
-
const currentHash = sha256(readFileSync6(safe.absolute, "utf8"));
|
|
1346
|
-
if (currentHash !== installedHash && !options.overwrite) {
|
|
1347
|
-
throw new CliError(
|
|
1348
|
-
`${safe.normalized} has local changes. Pass --overwrite to replace it.`
|
|
1349
|
-
);
|
|
1350
|
-
}
|
|
1351
|
-
}
|
|
1352
|
-
planned.push({
|
|
1353
|
-
item: item2.name,
|
|
1354
|
-
target: safe.normalized,
|
|
1355
|
-
content,
|
|
1356
|
-
hash: sha256(content)
|
|
1357
|
-
});
|
|
1358
|
-
}
|
|
1359
|
-
}
|
|
1360
|
-
const dependencies = missingDependencies(
|
|
1361
|
-
options.cwd,
|
|
1362
|
-
Object.assign({}, ...items.map((item2) => item2.dependencies))
|
|
1363
|
-
);
|
|
1364
|
-
const result = {
|
|
1365
|
-
command: "add",
|
|
1366
|
-
dryRun: options.dryRun,
|
|
1367
|
-
items: items.map((item2) => item2.name),
|
|
1368
|
-
files: planned.map((file) => file.target),
|
|
1369
|
-
dependencies
|
|
1370
|
-
};
|
|
1371
|
-
if (options.dryRun) {
|
|
1372
|
-
print(options.json ? JSON.stringify(result) : planText(result));
|
|
1373
|
-
return result;
|
|
1374
|
-
}
|
|
1375
|
-
if (options.install) {
|
|
1376
|
-
installDependencies(options.cwd, dependencies, options.json);
|
|
1377
|
-
}
|
|
1378
|
-
for (const file of planned) {
|
|
1379
|
-
const absolute = path12.join(options.cwd, file.target);
|
|
1380
|
-
mkdirSync2(path12.dirname(absolute), { recursive: true });
|
|
1381
|
-
writeFileSync3(absolute, file.content);
|
|
1382
|
-
}
|
|
1383
|
-
const installed = { ...project2.installed };
|
|
1384
|
-
for (const item2 of items) {
|
|
1385
|
-
const files2 = Object.fromEntries(
|
|
1386
|
-
planned.filter((file) => file.item === item2.name).map((file) => [file.target, file.hash])
|
|
1387
|
-
);
|
|
1388
|
-
installed[item2.name] = {
|
|
1389
|
-
version: item2.version,
|
|
1390
|
-
files: files2
|
|
1391
|
-
};
|
|
1392
|
-
}
|
|
1393
|
-
writeProjectConfig(options.cwd, {
|
|
1394
|
-
...project2,
|
|
1395
|
-
$schema: "https://registry.zappie.ai/v1/schema/project.json",
|
|
1396
|
-
registry: options.source,
|
|
1397
|
-
installed
|
|
1398
|
-
});
|
|
1399
|
-
print(options.json ? JSON.stringify(result) : planText(result));
|
|
1400
|
-
return result;
|
|
1401
|
-
}
|
|
1402
|
-
function planText(result) {
|
|
1403
|
-
const heading = result.dryRun ? "Plan to add" : "Added";
|
|
1404
|
-
const lines2 = [`${heading}: ${result.items.join(", ")}`, ...result.files];
|
|
1405
|
-
if (result.dependencies.length > 0) {
|
|
1406
|
-
lines2.push(`Dependencies: ${result.dependencies.join(", ")}`);
|
|
1407
|
-
}
|
|
1408
|
-
return lines2.join("\n");
|
|
1409
|
-
}
|
|
1410
|
-
|
|
1411
|
-
// src/kit-apply.ts
|
|
1412
|
-
import { mkdirSync as mkdirSync3, rmSync, writeFileSync as writeFileSync4 } from "fs";
|
|
1413
|
-
import path13 from "path";
|
|
1414
|
-
|
|
1415
|
-
// src/kit-apply-plan.ts
|
|
1416
|
-
import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
|
|
1417
|
-
|
|
1418
|
-
// src/three-way.ts
|
|
1419
|
-
import { diff3Merge } from "node-diff3";
|
|
1420
|
-
function lines(content) {
|
|
1421
|
-
return content.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
1422
|
-
}
|
|
1423
|
-
function mergeText(ours, base, theirs) {
|
|
1424
|
-
if (ours === base) {
|
|
1425
|
-
return { content: theirs, conflicts: [] };
|
|
1426
|
-
}
|
|
1427
|
-
if (theirs === base || ours === theirs) {
|
|
1428
|
-
return { content: ours, conflicts: [] };
|
|
1429
|
-
}
|
|
1430
|
-
const regions = diff3Merge(lines(ours), lines(base), lines(theirs), {
|
|
1431
|
-
excludeFalseConflicts: true
|
|
1432
|
-
});
|
|
1433
|
-
const conflicts = [];
|
|
1434
|
-
const merged = [];
|
|
1435
|
-
for (const region of regions) {
|
|
1436
|
-
if (region.ok) {
|
|
1437
|
-
merged.push(...region.ok);
|
|
1438
|
-
continue;
|
|
1439
|
-
}
|
|
1440
|
-
if (region.conflict) {
|
|
1441
|
-
conflicts.push({
|
|
1442
|
-
hunk: conflicts.length + 1,
|
|
1443
|
-
oursLine: region.conflict.aIndex + 1,
|
|
1444
|
-
baseLine: region.conflict.oIndex + 1,
|
|
1445
|
-
theirsLine: region.conflict.bIndex + 1,
|
|
1446
|
-
ours: region.conflict.a.join(""),
|
|
1447
|
-
base: region.conflict.o.join(""),
|
|
1448
|
-
theirs: region.conflict.b.join("")
|
|
1449
|
-
});
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
return {
|
|
1453
|
-
...conflicts.length === 0 ? { content: merged.join("") } : {},
|
|
1454
|
-
conflicts
|
|
1455
|
-
};
|
|
1456
|
-
}
|
|
1457
|
-
|
|
1458
|
-
// src/kit-apply-plan.ts
|
|
1459
|
-
function files(cwd, project2, item2) {
|
|
1460
|
-
return new Map(
|
|
1461
|
-
item2.files.map((file) => {
|
|
1462
|
-
verifySource(`${item2.name}/${file.path}`, file);
|
|
1463
|
-
const target = installTarget(file.target, project2.componentsDir);
|
|
1464
|
-
const safe = safeTarget(cwd, target);
|
|
1465
|
-
return [
|
|
1466
|
-
safe.normalized,
|
|
1467
|
-
rewriteKitImports(
|
|
1468
|
-
file.content,
|
|
1469
|
-
safe.normalized,
|
|
1470
|
-
project2.componentsDir,
|
|
1471
|
-
project2.alias
|
|
1472
|
-
)
|
|
1473
|
-
];
|
|
1474
|
-
})
|
|
1475
|
-
);
|
|
1476
|
-
}
|
|
1477
|
-
function conflict(file, reason, hunks = []) {
|
|
1478
|
-
return { file, reason, hunks };
|
|
1479
|
-
}
|
|
1480
|
-
function planFile(cwd, target, base, theirs, installedHash) {
|
|
1481
|
-
const absolute = safeTarget(cwd, target).absolute;
|
|
1482
|
-
const ours = existsSync7(absolute) ? readFileSync7(absolute, "utf8") : void 0;
|
|
1483
|
-
if (base === void 0 && theirs !== void 0) {
|
|
1484
|
-
if (ours !== void 0 && ours !== theirs) {
|
|
1485
|
-
return {
|
|
1486
|
-
conflict: conflict(target, "The file you are adding already exists.")
|
|
1487
|
-
};
|
|
1488
|
-
}
|
|
1489
|
-
return ours === theirs ? { content: theirs } : {
|
|
1490
|
-
action: { kind: "write", target, content: theirs },
|
|
1491
|
-
content: theirs
|
|
1492
|
-
};
|
|
1493
|
-
}
|
|
1494
|
-
if (base !== void 0 && theirs === void 0) {
|
|
1495
|
-
if (ours === void 0) {
|
|
1496
|
-
return {};
|
|
1497
|
-
}
|
|
1498
|
-
if (installedHash !== void 0 && sha256(ours) === installedHash) {
|
|
1499
|
-
return { action: { kind: "delete", target } };
|
|
1500
|
-
}
|
|
1501
|
-
return {
|
|
1502
|
-
conflict: conflict(
|
|
1503
|
-
target,
|
|
1504
|
-
"The upstream file was removed but you have local changes."
|
|
1505
|
-
)
|
|
1506
|
-
};
|
|
1507
|
-
}
|
|
1508
|
-
if (base === void 0 || theirs === void 0) {
|
|
1509
|
-
return {};
|
|
1510
|
-
}
|
|
1511
|
-
if (ours === void 0) {
|
|
1512
|
-
return { conflict: conflict(target, "Your local file is missing.") };
|
|
1513
|
-
}
|
|
1514
|
-
const merged = mergeText(ours, base, theirs);
|
|
1515
|
-
if (merged.conflicts.length > 0 || merged.content === void 0) {
|
|
1516
|
-
return { conflict: conflict(target, "Changes overlap.", merged.conflicts) };
|
|
1517
|
-
}
|
|
1518
|
-
return merged.content === ours ? { content: ours } : {
|
|
1519
|
-
action: { kind: "write", target, content: merged.content },
|
|
1520
|
-
content: merged.content
|
|
1521
|
-
};
|
|
1522
|
-
}
|
|
1523
|
-
async function planItem(cwd, project2, registry, name2, latestVersion) {
|
|
1524
|
-
const installed = project2.installed[name2];
|
|
1525
|
-
if (!installed) {
|
|
1526
|
-
throw new CliError(`You have not installed item "${name2}".`);
|
|
1527
|
-
}
|
|
1528
|
-
if (installed.version === latestVersion) {
|
|
1529
|
-
return {
|
|
1530
|
-
result: {
|
|
1531
|
-
name: name2,
|
|
1532
|
-
from: installed.version,
|
|
1533
|
-
to: latestVersion,
|
|
1534
|
-
status: "skipped",
|
|
1535
|
-
files: [],
|
|
1536
|
-
conflicts: []
|
|
1537
|
-
}
|
|
1538
|
-
};
|
|
1539
|
-
}
|
|
1540
|
-
const [baseItem, latestItem] = await Promise.all([
|
|
1541
|
-
registry.item(name2, installed.version),
|
|
1542
|
-
registry.item(name2, latestVersion)
|
|
1543
|
-
]);
|
|
1544
|
-
if (baseItem.name !== name2 || baseItem.version !== installed.version || latestItem.name !== name2 || latestItem.version !== latestVersion) {
|
|
1545
|
-
throw new CliError(
|
|
1546
|
-
`Registry entries for "${name2}" do not match the index.`
|
|
1547
|
-
);
|
|
1548
|
-
}
|
|
1549
|
-
const base = files(cwd, project2, baseItem);
|
|
1550
|
-
const latest = files(cwd, project2, latestItem);
|
|
1551
|
-
const actions = [];
|
|
1552
|
-
const conflicts = [];
|
|
1553
|
-
const contents = /* @__PURE__ */ new Map();
|
|
1554
|
-
for (const target of /* @__PURE__ */ new Set([...base.keys(), ...latest.keys()])) {
|
|
1555
|
-
const plan = planFile(
|
|
1556
|
-
cwd,
|
|
1557
|
-
target,
|
|
1558
|
-
base.get(target),
|
|
1559
|
-
latest.get(target),
|
|
1560
|
-
installed.files[target]
|
|
1561
|
-
);
|
|
1562
|
-
if (plan.action) {
|
|
1563
|
-
actions.push(plan.action);
|
|
1564
|
-
}
|
|
1565
|
-
if (plan.conflict) {
|
|
1566
|
-
conflicts.push(plan.conflict);
|
|
1567
|
-
}
|
|
1568
|
-
if (plan.content !== void 0) {
|
|
1569
|
-
contents.set(target, plan.content);
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
|
-
const result = {
|
|
1573
|
-
name: name2,
|
|
1574
|
-
from: installed.version,
|
|
1575
|
-
to: latestVersion,
|
|
1576
|
-
status: conflicts.length > 0 ? "conflict" : "applied",
|
|
1577
|
-
files: conflicts.length > 0 ? [] : actions,
|
|
1578
|
-
conflicts
|
|
1579
|
-
};
|
|
1580
|
-
const next = {
|
|
1581
|
-
version: latestVersion,
|
|
1582
|
-
files: Object.fromEntries(
|
|
1583
|
-
[...latest.keys()].map((target) => [
|
|
1584
|
-
target,
|
|
1585
|
-
sha256(contents.get(target) ?? latest.get(target) ?? "")
|
|
1586
|
-
])
|
|
1587
|
-
)
|
|
1588
|
-
};
|
|
1589
|
-
return { result, next };
|
|
1590
|
-
}
|
|
1591
|
-
|
|
1592
|
-
// src/kit-apply.ts
|
|
1593
|
-
async function applyDiff(options) {
|
|
1594
|
-
const print = options.print ?? console.log;
|
|
1595
|
-
if (!readProjectConfig(options.cwd)?.installed) {
|
|
1596
|
-
throw new CliError("No kit components are installed in zappie.json.");
|
|
1597
|
-
}
|
|
1598
|
-
const project2 = kitProject(options.cwd);
|
|
1599
|
-
const source2 = registrySource(options.source, project2.registry);
|
|
1600
|
-
const registry = new Registry(source2, options.cwd);
|
|
1601
|
-
const index2 = await registry.index();
|
|
1602
|
-
const names = options.name ? [options.name] : Object.keys(project2.installed);
|
|
1603
|
-
const installed = { ...project2.installed };
|
|
1604
|
-
const results = [];
|
|
1605
|
-
let changed = false;
|
|
1606
|
-
for (const name2 of names) {
|
|
1607
|
-
const latest = index2.items.find((item2) => item2.name === name2);
|
|
1608
|
-
if (!latest) {
|
|
1609
|
-
throw new CliError(
|
|
1610
|
-
`The registry is missing your installed item "${name2}".`
|
|
1611
|
-
);
|
|
1612
|
-
}
|
|
1613
|
-
const planned = await planItem(
|
|
1614
|
-
options.cwd,
|
|
1615
|
-
project2,
|
|
1616
|
-
registry,
|
|
1617
|
-
name2,
|
|
1618
|
-
latest.version
|
|
1619
|
-
);
|
|
1620
|
-
const result = options.dryRun && planned.result.status === "applied" ? { ...planned.result, status: "would-apply" } : planned.result;
|
|
1621
|
-
results.push(result);
|
|
1622
|
-
if (planned.next && planned.result.status === "applied" && !options.dryRun) {
|
|
1623
|
-
for (const action of planned.result.files) {
|
|
1624
|
-
const absolute = safeTarget(options.cwd, action.target).absolute;
|
|
1625
|
-
if (action.kind === "delete") {
|
|
1626
|
-
rmSync(absolute, { force: true });
|
|
1627
|
-
} else {
|
|
1628
|
-
mkdirSync3(path13.dirname(absolute), { recursive: true });
|
|
1629
|
-
writeFileSync4(absolute, action.content);
|
|
1630
|
-
}
|
|
1631
|
-
}
|
|
1632
|
-
installed[name2] = planned.next;
|
|
1633
|
-
changed = true;
|
|
1634
|
-
}
|
|
1635
|
-
}
|
|
1636
|
-
if (!options.dryRun && changed) {
|
|
1637
|
-
writeProjectConfig(options.cwd, {
|
|
1638
|
-
...project2,
|
|
1639
|
-
registry: source2,
|
|
1640
|
-
installed
|
|
1641
|
-
});
|
|
1642
|
-
}
|
|
1643
|
-
const output = {
|
|
1644
|
-
command: "diff",
|
|
1645
|
-
apply: true,
|
|
1646
|
-
dryRun: options.dryRun,
|
|
1647
|
-
items: results
|
|
1648
|
-
};
|
|
1649
|
-
print(options.json ? JSON.stringify(output) : applyText(results));
|
|
1650
|
-
return {
|
|
1651
|
-
...output,
|
|
1652
|
-
failed: results.some((item2) => item2.status === "conflict")
|
|
1653
|
-
};
|
|
1654
|
-
}
|
|
1655
|
-
function applyText(items) {
|
|
1656
|
-
return items.flatMap((item2) => [
|
|
1657
|
-
`${item2.name} ${item2.status} ${item2.from} -> ${item2.to}`,
|
|
1658
|
-
...item2.files.map((file) => `${file.kind} ${file.target}`),
|
|
1659
|
-
...item2.conflicts.flatMap((entry) => [
|
|
1660
|
-
`conflict ${entry.file} ${entry.reason}`,
|
|
1661
|
-
...entry.hunks.map(
|
|
1662
|
-
(hunk) => `hunk ${hunk.hunk} ours:${hunk.oursLine} base:${hunk.baseLine} theirs:${hunk.theirsLine}`
|
|
1663
|
-
)
|
|
1664
|
-
])
|
|
1665
|
-
]).join("\n");
|
|
1666
|
-
}
|
|
1667
|
-
|
|
1668
|
-
// src/kit-status.ts
|
|
1669
|
-
import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
|
|
1670
|
-
import path14 from "path";
|
|
1671
|
-
|
|
1672
|
-
// src/unified-diff.ts
|
|
1673
|
-
function unifiedDiff(file, before, after) {
|
|
1674
|
-
if (before === after) {
|
|
1675
|
-
return "";
|
|
1676
|
-
}
|
|
1677
|
-
const oldLines = before.replace(/\n$/, "").split("\n");
|
|
1678
|
-
const newLines = after.replace(/\n$/, "").split("\n");
|
|
1679
|
-
return [
|
|
1680
|
-
`--- ${file}`,
|
|
1681
|
-
`+++ ${file}`,
|
|
1682
|
-
`@@ -1,${oldLines.length} +1,${newLines.length} @@`,
|
|
1683
|
-
...oldLines.map((line) => `-${line}`),
|
|
1684
|
-
...newLines.map((line) => `+${line}`)
|
|
1685
|
-
].join("\n");
|
|
1686
|
-
}
|
|
1687
|
-
|
|
1688
|
-
// src/kit-status.ts
|
|
1689
|
-
function project(cwd) {
|
|
1690
|
-
const config = readProjectConfig(cwd);
|
|
1691
|
-
if (!config?.installed) {
|
|
1692
|
-
throw new CliError("No kit components are installed in zappie.json.");
|
|
1693
|
-
}
|
|
1694
|
-
return { ...config, installed: config.installed };
|
|
1695
|
-
}
|
|
1696
|
-
function modified(cwd, files2) {
|
|
1697
|
-
return Object.entries(files2).some(([file, installedHash]) => {
|
|
1698
|
-
const target = path14.join(cwd, file);
|
|
1699
|
-
return !existsSync8(target) || sha256(readFileSync8(target, "utf8")) !== installedHash;
|
|
1700
|
-
});
|
|
1701
|
-
}
|
|
1702
|
-
function state(local, update) {
|
|
1703
|
-
if (local && update) {
|
|
1704
|
-
return "modified-with-update";
|
|
1705
|
-
}
|
|
1706
|
-
if (local) {
|
|
1707
|
-
return "modified";
|
|
1708
|
-
}
|
|
1709
|
-
if (update) {
|
|
1710
|
-
return "update-available";
|
|
1711
|
-
}
|
|
1712
|
-
return "up-to-date";
|
|
1713
|
-
}
|
|
1714
|
-
function source(flag, configured, cwd) {
|
|
1715
|
-
const value = registrySource(flag, configured);
|
|
1716
|
-
return new Registry(value, cwd);
|
|
1717
|
-
}
|
|
1718
|
-
async function listItems(options) {
|
|
1719
|
-
const print = options.print ?? console.log;
|
|
1720
|
-
const config = readProjectConfig(options.cwd);
|
|
1721
|
-
const registry = source(options.source, config?.registry, options.cwd);
|
|
1722
|
-
const index2 = await registry.index();
|
|
1723
|
-
if (!options.installed) {
|
|
1724
|
-
print(
|
|
1725
|
-
options.json ? JSON.stringify({ command: "list", items: index2.items }) : index2.items.map((item2) => `${item2.name} ${item2.version} ${item2.title}`).join("\n")
|
|
1726
|
-
);
|
|
1727
|
-
return index2.items;
|
|
1728
|
-
}
|
|
1729
|
-
const current = project(options.cwd);
|
|
1730
|
-
const versions = new Map(
|
|
1731
|
-
index2.items.map((item2) => [item2.name, item2.version])
|
|
1732
|
-
);
|
|
1733
|
-
const items = Object.entries(current.installed).map(
|
|
1734
|
-
([name2, value]) => {
|
|
1735
|
-
const local = modified(options.cwd, value.files);
|
|
1736
|
-
const update = versions.get(name2) !== value.version;
|
|
1737
|
-
return {
|
|
1738
|
-
name: name2,
|
|
1739
|
-
version: value.version,
|
|
1740
|
-
status: local ? "modified" : update ? "update-available" : "up-to-date"
|
|
1741
|
-
};
|
|
1742
|
-
}
|
|
1743
|
-
);
|
|
1744
|
-
print(
|
|
1745
|
-
options.json ? JSON.stringify({ command: "list", items }) : items.map((item2) => `${item2.name} ${item2.version} ${item2.status}`).join("\n")
|
|
1746
|
-
);
|
|
1747
|
-
return items;
|
|
1748
|
-
}
|
|
1749
|
-
async function diffItems(options) {
|
|
1750
|
-
const print = options.print ?? console.log;
|
|
1751
|
-
const config = project(options.cwd);
|
|
1752
|
-
const registry = source(options.source, config.registry, options.cwd);
|
|
1753
|
-
const index2 = await registry.index();
|
|
1754
|
-
const selected = selectInstalled(config.installed, options.name);
|
|
1755
|
-
const results = [];
|
|
1756
|
-
for (const [name2, installed] of selected) {
|
|
1757
|
-
const latest = index2.items.find((item2) => item2.name === name2);
|
|
1758
|
-
if (!latest) {
|
|
1759
|
-
throw new CliError(
|
|
1760
|
-
`The registry is missing your installed item "${name2}".`
|
|
1761
|
-
);
|
|
1762
|
-
}
|
|
1763
|
-
const local = modified(options.cwd, installed.files);
|
|
1764
|
-
const update = latest.version !== installed.version;
|
|
1765
|
-
const diffs = update ? await upstreamDiffs(registry, name2, installed.version, latest.version) : [];
|
|
1766
|
-
results.push({ name: name2, status: state(local, update), diffs });
|
|
1767
|
-
}
|
|
1768
|
-
print(
|
|
1769
|
-
options.json ? JSON.stringify({ command: "diff", items: results }) : results.flatMap((item2) => [`${item2.name} ${item2.status}`, ...item2.diffs]).join("\n")
|
|
1770
|
-
);
|
|
1771
|
-
return results;
|
|
1772
|
-
}
|
|
1773
|
-
function selectInstalled(installed, name2) {
|
|
1774
|
-
if (name2 && !installed[name2]) {
|
|
1775
|
-
throw new CliError(`You have not installed item "${name2}".`);
|
|
1776
|
-
}
|
|
1777
|
-
const names = name2 ? [name2] : Object.keys(installed);
|
|
1778
|
-
return names.map((entry) => {
|
|
1779
|
-
const value = installed[entry];
|
|
1780
|
-
if (!value) {
|
|
1781
|
-
throw new CliError(`You have not installed item "${entry}".`);
|
|
1782
|
-
}
|
|
1783
|
-
return [entry, value];
|
|
1784
|
-
});
|
|
1785
|
-
}
|
|
1786
|
-
async function upstreamDiffs(registry, name2, installedVersion, latestVersion) {
|
|
1787
|
-
const [before, after] = await Promise.all([
|
|
1788
|
-
registry.item(name2, installedVersion),
|
|
1789
|
-
registry.item(name2, latestVersion)
|
|
1790
|
-
]);
|
|
1791
|
-
const oldFiles = new Map(
|
|
1792
|
-
before.files.map((file) => [file.target, file.content])
|
|
1793
|
-
);
|
|
1794
|
-
return after.files.map(
|
|
1795
|
-
(file) => unifiedDiff(file.target, oldFiles.get(file.target) ?? "", file.content)
|
|
1796
|
-
).filter(Boolean);
|
|
1797
|
-
}
|
|
1798
|
-
|
|
1799
|
-
// src/verify-command.ts
|
|
1800
|
-
import { mkdir, writeFile } from "fs/promises";
|
|
1801
|
-
import path15 from "path";
|
|
1802
|
-
async function runProjectVerify(options) {
|
|
1803
|
-
const key = options.key ?? process.env.ZAPPIE_KEY;
|
|
1804
|
-
if (key?.startsWith("pk_live_")) {
|
|
1805
|
-
throw new CliError(
|
|
1806
|
-
"live_key_refused: Use only pk_test_ keys with verify. Create a test publishable key and run verify again."
|
|
1807
|
-
);
|
|
1808
|
-
}
|
|
1809
|
-
if (!key?.startsWith("pk_test_")) {
|
|
1810
|
-
throw new CliError("Set your pk_test_ key with --key or ZAPPIE_KEY.");
|
|
1811
|
-
}
|
|
1812
|
-
const loaded = await (options.load ?? loadProjectVerify)(
|
|
1813
|
-
options.cwd,
|
|
1814
|
-
options.packageManager
|
|
1815
|
-
);
|
|
1816
|
-
try {
|
|
1817
|
-
const result = await loaded.verifyProject({
|
|
1818
|
-
cwd: options.cwd,
|
|
1819
|
-
key,
|
|
1820
|
-
suite: options.suite,
|
|
1821
|
-
packageManager: options.packageManager,
|
|
1822
|
-
...options.url ? { url: options.url } : {},
|
|
1823
|
-
...options.store ? { store: options.store } : {},
|
|
1824
|
-
...options.only ? { only: options.only } : {},
|
|
1825
|
-
...options.startPath ? { startPath: options.startPath } : {},
|
|
1826
|
-
...options.build === false ? { build: false } : {},
|
|
1827
|
-
...options.port ? { port: options.port } : {},
|
|
1828
|
-
...options.artifacts ? { artifactsDir: path15.resolve(options.cwd, options.artifacts) } : {},
|
|
1829
|
-
...options.runner ? { runner: options.runner } : {},
|
|
1830
|
-
...options.signal ? { signal: options.signal } : {}
|
|
1831
|
-
});
|
|
1832
|
-
const ran = result.environment?.startPath;
|
|
1833
|
-
if (options.startPath && ran !== options.startPath) {
|
|
1834
|
-
throw new CliError(
|
|
1835
|
-
"Your @zappie/verify ignored --start. Update it to 0.3.0 or later."
|
|
1836
|
-
);
|
|
1837
|
-
}
|
|
1838
|
-
if (options.report) {
|
|
1839
|
-
const file = path15.resolve(options.cwd, options.report);
|
|
1840
|
-
await mkdir(path15.dirname(file), { recursive: true });
|
|
1841
|
-
await writeFile(file, `${JSON.stringify(result, null, 2)}
|
|
1842
|
-
`);
|
|
1843
|
-
}
|
|
1844
|
-
(options.print ?? console.log)(
|
|
1845
|
-
options.json ? JSON.stringify(result) : loaded.printSummary(result)
|
|
1846
|
-
);
|
|
1847
|
-
return result;
|
|
1848
|
-
} catch (error) {
|
|
1849
|
-
if (isVerifyError(error)) {
|
|
1850
|
-
throw new CliError(`${error.code}: ${error.message}`);
|
|
1851
|
-
}
|
|
1852
|
-
throw error;
|
|
1853
|
-
}
|
|
1854
|
-
}
|
|
1855
|
-
async function loadProjectVerify(cwd, manager) {
|
|
1856
|
-
const loaded = await loadProjectPackage(
|
|
1857
|
-
cwd,
|
|
1858
|
-
"@zappie/verify",
|
|
1859
|
-
manager
|
|
1860
|
-
);
|
|
1861
|
-
if (typeof loaded.verifyProject !== "function" || typeof loaded.printSummary !== "function") {
|
|
1862
|
-
throw new CliError(
|
|
1863
|
-
"Your installed @zappie/verify does not export verifyProject and printSummary."
|
|
1864
|
-
);
|
|
1865
|
-
}
|
|
1866
|
-
return loaded;
|
|
1867
|
-
}
|
|
1868
|
-
function isVerifyError(error) {
|
|
1869
|
-
return Boolean(
|
|
1870
|
-
error && typeof error === "object" && "code" in error && typeof error.code === "string" && "message" in error && typeof error.message === "string"
|
|
1871
|
-
);
|
|
1872
|
-
}
|
|
1873
|
-
|
|
1874
|
-
// src/cli.ts
|
|
1875
|
-
async function main(argv) {
|
|
1876
|
-
const command = parseCommand(argv);
|
|
1877
|
-
const cwd = process.cwd();
|
|
1878
|
-
switch (command.name) {
|
|
1879
|
-
case "init": {
|
|
1880
|
-
await initProject(command, cwd);
|
|
1881
|
-
return 0;
|
|
1882
|
-
}
|
|
1883
|
-
case "help": {
|
|
1884
|
-
console.log(usage);
|
|
1885
|
-
return 0;
|
|
1886
|
-
}
|
|
1887
|
-
case "add": {
|
|
1888
|
-
const configured = readProjectConfig(cwd)?.registry;
|
|
1889
|
-
const source2 = registrySource(command.registry, configured);
|
|
1890
|
-
await addItems({
|
|
1891
|
-
cwd,
|
|
1892
|
-
names: command.items,
|
|
1893
|
-
source: source2,
|
|
1894
|
-
overwrite: command.overwrite,
|
|
1895
|
-
dryRun: command.dryRun,
|
|
1896
|
-
install: command.install,
|
|
1897
|
-
json: command.json
|
|
1898
|
-
});
|
|
1899
|
-
return 0;
|
|
1900
|
-
}
|
|
1901
|
-
case "list": {
|
|
1902
|
-
await listItems({
|
|
1903
|
-
cwd,
|
|
1904
|
-
...command.registry !== void 0 ? { source: command.registry } : {},
|
|
1905
|
-
installed: command.installed,
|
|
1906
|
-
json: command.json
|
|
1907
|
-
});
|
|
1908
|
-
return 0;
|
|
1909
|
-
}
|
|
1910
|
-
case "diff": {
|
|
1911
|
-
if (command.apply) {
|
|
1912
|
-
const result = await applyDiff({
|
|
1913
|
-
cwd,
|
|
1914
|
-
...command.registry !== void 0 ? { source: command.registry } : {},
|
|
1915
|
-
...command.item !== void 0 ? { name: command.item } : {},
|
|
1916
|
-
dryRun: command.dryRun,
|
|
1917
|
-
json: command.json
|
|
1918
|
-
});
|
|
1919
|
-
return result.failed ? 1 : 0;
|
|
1920
|
-
}
|
|
1921
|
-
await diffItems({
|
|
1922
|
-
cwd,
|
|
1923
|
-
...command.registry !== void 0 ? { source: command.registry } : {},
|
|
1924
|
-
...command.item !== void 0 ? { name: command.item } : {},
|
|
1925
|
-
json: command.json
|
|
1926
|
-
});
|
|
1927
|
-
return 0;
|
|
1928
|
-
}
|
|
1929
|
-
case "doctor": {
|
|
1930
|
-
const result = await doctor({
|
|
1931
|
-
cwd,
|
|
1932
|
-
...command.registry !== void 0 ? { source: command.registry } : {},
|
|
1933
|
-
json: command.json
|
|
1934
|
-
});
|
|
1935
|
-
return result.failed ? 1 : 0;
|
|
1936
|
-
}
|
|
1937
|
-
case "check": {
|
|
1938
|
-
const directory = path16.resolve(cwd, command.directory ?? ".");
|
|
1939
|
-
const controller = new AbortController();
|
|
1940
|
-
const abort = () => controller.abort(new Error("Check cancelled."));
|
|
1941
|
-
process.once("SIGINT", abort);
|
|
1942
|
-
try {
|
|
1943
|
-
const result = await runProjectCheck({
|
|
1944
|
-
cwd: directory,
|
|
1945
|
-
all: command.all,
|
|
1946
|
-
audit: command.audit,
|
|
1947
|
-
history: command.history,
|
|
1948
|
-
json: command.json,
|
|
1949
|
-
packageManager: detectPackageManager(directory),
|
|
1950
|
-
signal: controller.signal
|
|
1951
|
-
});
|
|
1952
|
-
return result.result === "passed" ? 0 : 1;
|
|
1953
|
-
} finally {
|
|
1954
|
-
process.removeListener("SIGINT", abort);
|
|
1955
|
-
}
|
|
1956
|
-
}
|
|
1957
|
-
case "verify": {
|
|
1958
|
-
const controller = new AbortController();
|
|
1959
|
-
const abort = () => controller.abort(new Error("Verify cancelled."));
|
|
1960
|
-
process.once("SIGINT", abort);
|
|
1961
|
-
try {
|
|
1962
|
-
const result = await runProjectVerify({
|
|
1963
|
-
cwd,
|
|
1964
|
-
suite: command.suite,
|
|
1965
|
-
json: command.json,
|
|
1966
|
-
...command.url ? { url: command.url } : {},
|
|
1967
|
-
...command.report ? { report: command.report } : {},
|
|
1968
|
-
...command.key ? { key: command.key } : {},
|
|
1969
|
-
...command.store ? { store: command.store } : {},
|
|
1970
|
-
...command.only ? { only: command.only } : {},
|
|
1971
|
-
...command.startPath ? { startPath: command.startPath } : {},
|
|
1972
|
-
...command.build ? {} : { build: false },
|
|
1973
|
-
...command.port ? { port: command.port } : {},
|
|
1974
|
-
...command.artifacts ? { artifacts: command.artifacts } : {},
|
|
1975
|
-
...command.runner ? { runner: command.runner } : {},
|
|
1976
|
-
packageManager: detectPackageManager(cwd),
|
|
1977
|
-
signal: controller.signal
|
|
1978
|
-
});
|
|
1979
|
-
return result.result === "passed" ? 0 : 2;
|
|
1980
|
-
} finally {
|
|
1981
|
-
process.removeListener("SIGINT", abort);
|
|
1982
|
-
}
|
|
1983
|
-
}
|
|
1984
|
-
}
|
|
1985
|
-
}
|
|
1986
|
-
var json3 = process.argv.slice(2).includes("--json");
|
|
1987
|
-
main(process.argv.slice(2)).then(
|
|
1988
|
-
(code) => {
|
|
1989
|
-
process.exitCode = code;
|
|
1990
|
-
},
|
|
1991
|
-
(error) => {
|
|
1992
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1993
|
-
const exitCode = error instanceof CliError ? error.exitCode : 1;
|
|
1994
|
-
if (json3) {
|
|
1995
|
-
console.log(JSON.stringify({ error: { message, exitCode } }));
|
|
1996
|
-
} else {
|
|
1997
|
-
console.error(message);
|
|
1998
|
-
}
|
|
1999
|
-
process.exitCode = exitCode;
|
|
2000
|
-
}
|
|
2001
|
-
);
|
|
60
|
+
ZAPPIE_KEY=${key||"pk_test_REPLACE_ME"}
|
|
61
|
+
`));mkdirSync2(directory,{recursive:true});for(const[filename,contents]of files2){const destination=path13.join(directory,filename);mkdirSync2(path13.dirname(destination),{recursive:true});writeFileSync4(destination,new Uint8Array(contents),{flag:"wx"})}const manager=detectPackageManager(directory);const run=manager==="npm"?"npm run":manager;const next=[`${manager} install`,`${run} dev`,`${run} check`];const hint=key?void 0:"Set your test publishable key in .dev.vars before starting the storefront.";if(command.json){console.log(JSON.stringify({command:"init",directory,template:command.template,version:template.latest,next,...hint?{hint}:{}}))}else{console.log(`Created your storefront in ${directory}.
|
|
62
|
+
${hint?`${hint}
|
|
63
|
+
`:""}In that folder, run:
|
|
64
|
+
${next.join("\n")}`)}}import{mkdirSync as mkdirSync3,rmSync,writeFileSync as writeFileSync5}from"fs";import path14 from"path";import{existsSync as existsSync8,readFileSync as readFileSync8}from"fs";import{diff3Merge}from"node-diff3";function lines(content){return content.match(/[^\n]*\n|[^\n]+$/g)??[]}function mergeText(ours,base,theirs){if(ours===base){return{content:theirs,conflicts:[]}}if(theirs===base||ours===theirs){return{content:ours,conflicts:[]}}const regions=diff3Merge(lines(ours),lines(base),lines(theirs),{excludeFalseConflicts:true});const conflicts=[];const merged=[];for(const region of regions){if(region.ok){merged.push(...region.ok);continue}if(region.conflict){conflicts.push({hunk:conflicts.length+1,oursLine:region.conflict.aIndex+1,baseLine:region.conflict.oIndex+1,theirsLine:region.conflict.bIndex+1,ours:region.conflict.a.join(""),base:region.conflict.o.join(""),theirs:region.conflict.b.join("")})}}return{...conflicts.length===0?{content:merged.join("")}:{},conflicts}}function files(cwd,project2,item2){return new Map(item2.files.map(file=>{verifySource(`${item2.name}/${file.path}`,file);const target=installTarget(file.target,project2.componentsDir);const safe=safeTarget(cwd,target);return[safe.normalized,rewriteKitImports(file.content,safe.normalized,project2.componentsDir,project2.alias)]}))}function conflict(file,reason,hunks=[]){return{file,reason,hunks}}function planFile(cwd,target,base,theirs,installedHash){const absolute=safeTarget(cwd,target).absolute;const ours=existsSync8(absolute)?readFileSync8(absolute,"utf8"):void 0;if(base===void 0&&theirs!==void 0){if(ours!==void 0&&ours!==theirs){return{conflict:conflict(target,"The file you are adding already exists.")}}return ours===theirs?{content:theirs}:{action:{kind:"write",target,content:theirs},content:theirs}}if(base!==void 0&&theirs===void 0){if(ours===void 0){return{}}if(installedHash!==void 0&&sha256(ours)===installedHash){return{action:{kind:"delete",target}}}return{conflict:conflict(target,"The upstream file was removed but you have local changes.")}}if(base===void 0||theirs===void 0){return{}}if(ours===void 0){return{conflict:conflict(target,"Your local file is missing.")}}const merged=mergeText(ours,base,theirs);if(merged.conflicts.length>0||merged.content===void 0){return{conflict:conflict(target,"Changes overlap.",merged.conflicts)}}return merged.content===ours?{content:ours}:{action:{kind:"write",target,content:merged.content},content:merged.content}}async function planItem(cwd,project2,registry,name2,latestVersion){const installed=project2.installed[name2];if(!installed){throw new CliError(`You have not installed item "${name2}".`)}if(installed.version===latestVersion){return{result:{name:name2,from:installed.version,to:latestVersion,status:"skipped",files:[],conflicts:[]}}}const[baseItem,latestItem]=await Promise.all([registry.item(name2,installed.version),registry.item(name2,latestVersion)]);if(baseItem.name!==name2||baseItem.version!==installed.version||latestItem.name!==name2||latestItem.version!==latestVersion){throw new CliError(`Registry entries for "${name2}" do not match the index.`)}const base=files(cwd,project2,baseItem);const latest=files(cwd,project2,latestItem);const actions=[];const conflicts=[];const contents=new Map;for(const target of new Set([...base.keys(),...latest.keys()])){const plan=planFile(cwd,target,base.get(target),latest.get(target),installed.files[target]);if(plan.action){actions.push(plan.action)}if(plan.conflict){conflicts.push(plan.conflict)}if(plan.content!==void 0){contents.set(target,plan.content)}}const result={name:name2,from:installed.version,to:latestVersion,status:conflicts.length>0?"conflict":"applied",files:conflicts.length>0?[]:actions,conflicts};const next={version:latestVersion,files:Object.fromEntries([...latest.keys()].map(target=>[target,sha256(contents.get(target)??latest.get(target)??"")]))};return{result,next}}async function applyDiff(options){const print=options.print??console.log;if(!readProjectConfig(options.cwd)?.installed){throw new CliError("No kit components are installed in zappie.json.")}const project2=kitProject(options.cwd);const source2=registrySource(options.source,project2.registry);const registry=new Registry(source2,options.cwd);const index2=await registry.index();const names=options.name?[options.name]:Object.keys(project2.installed);const installed={...project2.installed};const results=[];let changed=false;for(const name2 of names){const latest=index2.items.find(item2=>item2.name===name2);if(!latest){throw new CliError(`The registry is missing your installed item "${name2}".`)}const planned=await planItem(options.cwd,project2,registry,name2,latest.version);const result=options.dryRun&&planned.result.status==="applied"?{...planned.result,status:"would-apply"}:planned.result;results.push(result);if(planned.next&&planned.result.status==="applied"&&!options.dryRun){for(const action of planned.result.files){const absolute=safeTarget(options.cwd,action.target).absolute;if(action.kind==="delete"){rmSync(absolute,{force:true})}else{mkdirSync3(path14.dirname(absolute),{recursive:true});writeFileSync5(absolute,action.content)}}installed[name2]=planned.next;changed=true}}if(!options.dryRun&&changed){writeProjectConfig(options.cwd,{...project2,registry:source2,installed})}const output={command:"diff",apply:true,dryRun:options.dryRun,items:results};print(options.json?JSON.stringify(output):applyText(results));return{...output,failed:results.some(item2=>item2.status==="conflict")}}function applyText(items){return items.flatMap(item2=>[`${item2.name} ${item2.status} ${item2.from} -> ${item2.to}`,...item2.files.map(file=>`${file.kind} ${file.target}`),...item2.conflicts.flatMap(entry=>[`conflict ${entry.file} ${entry.reason}`,...entry.hunks.map(hunk=>`hunk ${hunk.hunk} ours:${hunk.oursLine} base:${hunk.baseLine} theirs:${hunk.theirsLine}`)])]).join("\n")}import{existsSync as existsSync9,readFileSync as readFileSync9}from"fs";import path15 from"path";function unifiedDiff(file,before,after){if(before===after){return""}const oldLines=before.replace(/\n$/,"").split("\n");const newLines=after.replace(/\n$/,"").split("\n");return[`--- ${file}`,`+++ ${file}`,`@@ -1,${oldLines.length} +1,${newLines.length} @@`,...oldLines.map(line=>`-${line}`),...newLines.map(line=>`+${line}`)].join("\n")}function project(cwd){const config=readProjectConfig(cwd);if(!config?.installed){throw new CliError("No kit components are installed in zappie.json.")}return{...config,installed:config.installed}}function modified(cwd,files2){return Object.entries(files2).some(([file,installedHash])=>{const target=path15.join(cwd,file);return!existsSync9(target)||sha256(readFileSync9(target,"utf8"))!==installedHash})}function state(local,update){if(local&&update){return"modified-with-update"}if(local){return"modified"}if(update){return"update-available"}return"up-to-date"}function source(flag,configured,cwd){const value=registrySource(flag,configured);return new Registry(value,cwd)}async function listItems(options){const print=options.print??console.log;const config=readProjectConfig(options.cwd);const registry=source(options.source,config?.registry,options.cwd);const index2=await registry.index();if(!options.installed){print(options.json?JSON.stringify({command:"list",items:index2.items}):index2.items.map(item2=>`${item2.name} ${item2.version} ${item2.title}`).join("\n"));return index2.items}const current=project(options.cwd);const versions=new Map(index2.items.map(item2=>[item2.name,item2.version]));const items=Object.entries(current.installed).map(([name2,value])=>{const local=modified(options.cwd,value.files);const update=versions.get(name2)!==value.version;return{name:name2,version:value.version,status:local?"modified":update?"update-available":"up-to-date"}});print(options.json?JSON.stringify({command:"list",items}):items.map(item2=>`${item2.name} ${item2.version} ${item2.status}`).join("\n"));return items}async function diffItems(options){const print=options.print??console.log;const config=project(options.cwd);const registry=source(options.source,config.registry,options.cwd);const index2=await registry.index();const selected=selectInstalled(config.installed,options.name);const results=[];for(const[name2,installed]of selected){const latest=index2.items.find(item2=>item2.name===name2);if(!latest){throw new CliError(`The registry is missing your installed item "${name2}".`)}const local=modified(options.cwd,installed.files);const update=latest.version!==installed.version;const diffs=update?await upstreamDiffs(registry,name2,installed.version,latest.version):[];results.push({name:name2,status:state(local,update),diffs})}print(options.json?JSON.stringify({command:"diff",items:results}):results.flatMap(item2=>[`${item2.name} ${item2.status}`,...item2.diffs]).join("\n"));return results}function selectInstalled(installed,name2){if(name2&&!installed[name2]){throw new CliError(`You have not installed item "${name2}".`)}const names=name2?[name2]:Object.keys(installed);return names.map(entry=>{const value=installed[entry];if(!value){throw new CliError(`You have not installed item "${entry}".`)}return[entry,value]})}async function upstreamDiffs(registry,name2,installedVersion,latestVersion){const[before,after]=await Promise.all([registry.item(name2,installedVersion),registry.item(name2,latestVersion)]);const oldFiles=new Map(before.files.map(file=>[file.target,file.content]));return after.files.map(file=>unifiedDiff(file.target,oldFiles.get(file.target)??"",file.content)).filter(Boolean)}import{mkdir,writeFile}from"fs/promises";import path16 from"path";async function runProjectVerify(options){const key=options.key??process.env.ZAPPIE_KEY;if(key?.startsWith("pk_live_")){throw new CliError("live_key_refused: Use only pk_test_ keys with verify. Create a test publishable key and run verify again.")}if(!key?.startsWith("pk_test_")){throw new CliError("Set your pk_test_ key with --key or ZAPPIE_KEY.")}const loaded=await(options.load??loadProjectVerify)(options.cwd,options.packageManager);try{const result=await loaded.verifyProject({cwd:options.cwd,key,suite:options.suite,packageManager:options.packageManager,...options.url?{url:options.url}:{},...options.store?{store:options.store}:{},...options.only?{only:options.only}:{},...options.startPath?{startPath:options.startPath}:{},...options.build===false?{build:false}:{},...options.port?{port:options.port}:{},...options.artifacts?{artifactsDir:path16.resolve(options.cwd,options.artifacts)}:{},...options.runner?{runner:options.runner}:{},...options.signal?{signal:options.signal}:{}});const ran=result.environment;const placeholders=/\{(?:menu|branch)\}/.test(options.startPath??"");if(options.startPath&&(placeholders?ran?.startPathTemplate!==options.startPath:ran?.startPath!==options.startPath)){throw new CliError(`Your @zappie/verify ignored --start. Update it to ${placeholders?"0.3.1":"0.3.0"} or later.`)}if(options.report){const file=path16.resolve(options.cwd,options.report);await mkdir(path16.dirname(file),{recursive:true});await writeFile(file,`${JSON.stringify(result,null,2)}
|
|
65
|
+
`)}(options.print??console.log)(options.json?JSON.stringify(result):loaded.printSummary(result));return result}catch(error){if(isVerifyError(error)){throw new CliError(`${error.code}: ${error.message}`)}throw error}}async function loadProjectVerify(cwd,manager){const loaded=await loadProjectPackage(cwd,"@zappie/verify",manager);if(typeof loaded.verifyProject!=="function"||typeof loaded.printSummary!=="function"){throw new CliError("Your installed @zappie/verify does not export verifyProject and printSummary.")}return loaded}function isVerifyError(error){return Boolean(error&&typeof error==="object"&&"code"in error&&typeof error.code==="string"&&"message"in error&&typeof error.message==="string")}async function main(argv){const command=parseCommand(argv);const cwd=process.cwd();switch(command.name){case"init":{await initProject(command,cwd);return 0}case"help":{console.log(usage);return 0}case"add":{const configured=readProjectConfig(cwd)?.registry;const source2=registrySource(command.registry,configured);await addItems({cwd,names:command.items,source:source2,overwrite:command.overwrite,dryRun:command.dryRun,install:command.install,json:command.json});return 0}case"list":{await listItems({cwd,...command.registry!==void 0?{source:command.registry}:{},installed:command.installed,json:command.json});return 0}case"diff":{if(command.apply){const result=await applyDiff({cwd,...command.registry!==void 0?{source:command.registry}:{},...command.item!==void 0?{name:command.item}:{},dryRun:command.dryRun,json:command.json});return result.failed?1:0}await diffItems({cwd,...command.registry!==void 0?{source:command.registry}:{},...command.item!==void 0?{name:command.item}:{},json:command.json});return 0}case"doctor":{const result=await doctor({cwd,...command.registry!==void 0?{source:command.registry}:{},json:command.json});return result.failed?1:0}case"check":{const directory=path17.resolve(cwd,command.directory??".");const controller=new AbortController;const abort=()=>controller.abort(new Error("Check cancelled."));process.once("SIGINT",abort);try{const result=await runProjectCheck({cwd:directory,all:command.all,audit:command.audit,history:command.history,json:command.json,packageManager:detectPackageManager(directory),signal:controller.signal});return result.result==="passed"?0:1}finally{process.removeListener("SIGINT",abort)}}case"verify":{const controller=new AbortController;const abort=()=>controller.abort(new Error("Verify cancelled."));process.once("SIGINT",abort);try{const result=await runProjectVerify({cwd,suite:command.suite,json:command.json,...command.url?{url:command.url}:{},...command.report?{report:command.report}:{},...command.key?{key:command.key}:{},...command.store?{store:command.store}:{},...command.only?{only:command.only}:{},...command.startPath?{startPath:command.startPath}:{},...command.build?{}:{build:false},...command.port?{port:command.port}:{},...command.artifacts?{artifacts:command.artifacts}:{},...command.runner?{runner:command.runner}:{},packageManager:detectPackageManager(cwd),signal:controller.signal});return result.result==="passed"?0:2}finally{process.removeListener("SIGINT",abort)}}}}var json3=process.argv.slice(2).includes("--json");main(process.argv.slice(2)).then(code=>{process.exitCode=code},error=>{const message=error instanceof Error?error.message:String(error);const exitCode=error instanceof CliError?error.exitCode:1;if(json3){console.log(JSON.stringify({error:{message,exitCode}}))}else{console.error(message)}process.exitCode=exitCode});
|